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
|
---|---|---|---|---|---|---|
7c348d0c9ce327a36a746fcb772bd3632c2e4204 | delaneycarleton/uoregon-cis313 | /proj2_data/carleton/problem2.py | 812 | 3.5 | 4 | import sys
def main():
with open(sys.argv[1]) as f:
num = int( f.readline().strip())
for _ in range(num):
line = f.readline().strip()
opens = []
isValid = True
open_char = "([{<"
close_char = ")]}>"
for i in range(len(line)):
if not isValid:
break
o_index = open_char.find(line[i])
c_index = close_char.find(line[i])
if o_index > -1:
opens.append(o_index)
elif c_index > -1:
if c_index != opens.pop():
isValid = False
if isValid:
print("YES")
else:
print("NO")
if __name__ == "__main__":
main()
|
5c103c0f6f6fbc423a8b51374039af7132269a20 | M0R1u5/Part2_Task6 | /Task6.py | 77 | 3.8125 | 4 | number = input('Enter an integer: ')
numb = str(number + ' ')
print(10*numb) |
1ef85de140e409b3d49f9516a496921248d7f955 | musarratChowdhury/ProblemSolvingWithJavascript | /breakingTheRecords.py | 606 | 3.578125 | 4 | #
scores = [3 ,4 ,21 ,36 ,10 ,28 ,35, 5 ,24 ,42]
def breakingRecords(scores):
# Write your code here
temporary_max = scores[0]
temporary_min = scores[0]
maximum_score = []
minimum_score = []
result_arr = []
for score in scores:
if score<temporary_min:
minimum_score.append(score)
temporary_min = score
if score>temporary_max:
maximum_score.append(score)
temporary_max =score
result_arr.append(len(maximum_score))
result_arr.append(len(minimum_score))
return result_arr
breakingRecords(scores) |
71bceef4381b351bffd5f1a9dd52c6161d667464 | Stormlight-Coding/regex-practice | /regex.py | 5,781 | 3.90625 | 4 | import re
# FOR displaying the groups it can only be used if there is a known output. DOES NOT WORK WITH A "NONE TYPE"!!!!
# if you are going to have a possible None Type, you need to put logic in to catch it
# phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
#
# data = input()
#
# mo = phoneNumRegex.search(data)
#
# print('phone number found: ' + mo.group())
#
phoneNumGroup = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo2 = phoneNumGroup.search('my phone number is 415-555-5555')
print(mo2.group(1))
print(mo2.group(2))
print(mo2.group(0))
print(mo2.group())
# Pipe ( '|') will search for either criteria but will only return the first one if they are both in the search area. It needs to be CASE SENSITIVE
heroRegex = re.compile(r'Batman | Tina Fey')
mo3 = heroRegex.search('Batman & tina fey')
print(mo3.group())
# the below example is how to search for multiple types of words such as Batmobile, Batman, Batcar, etc.... CASE SENSITIVE
batRegex = re.compile(r'Bat(man|mobile|car|woman)')
mo4 = batRegex.search('the Batcar is on its way')
print(mo4.group())
# OPTIONAL MATCHING
optionalRegex = re.compile(r'Bat(wo)?man')
mo5 = optionalRegex.search('im Batwoman')
print(mo5.group())
# the aterik = the group that precedes the asterik can occur any number of times
# If you use a '+' then it will search for ONE or more. There must be at least one present or it will throw an error
starRegex = re.compile(r'Bat(wo)*man')
mo6 = starRegex.search('Im Batwowowowowowoman and I am Batman Batman')
print(mo6.group())
# The (#){#,#} STRUCTURE searches for a match of whatever is inside the parenthese and how many times in the curly brackets. -> if there are two numbers in the curly brackets then is will search for a minimum of the first number and a maximum of the second number. EXAMPLE -> (Ha){3,5} will look for a re-occurence of 'Ha' at a minimum of 3 times to a maximum fo five times.
# NOTE! If given a min and a max it will always search for the longest max -> "GREEDY MATCHING"
# "NON-GREEDY MATCHING" is the format of (#){#,#}? ---> Adding the question mark makes it search for the first shortest possibility.
haRegex = re.compile(r'(Ha){3}')
mo7 = haRegex.search('HaHaHa')
print(mo7.group())
mo8 = haRegex.search("Ha")
if mo8 == None:
print(True)
else:
print(False)
# THE findall() Method
# This will return all matches of the regex instead of groups
findRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo9 = findRegex.findall('Cell: 209-900-9988 and Work: 230-432-4434')
print(mo9)
# if there are parenthesises around the area code or there are groups (\d\d\d)-(\d\d\d)-(\d\d\d\d) --> then it will return a list of tuples
# EXAMPLE --> [('415','555', '4534'), ('234','345','6758')]
xmasRegex = re.compile(r'\d+\s\w+') #This will match ONLY a number(s) followed by a space and then by a match of letters, numeric character or a underline. in other words, a WORD
print(xmasRegex.findall('12 drummers, 11 pipers, 10 milk maids, 9 lords, etc...')) #Will not print the commas, the second word of "maids" or 'etc...'
vowelRegex = re.compile(r'[aeiouAEIOU]')
print(vowelRegex.findall('Robocop eats babyfood'))
consanentRegex = re.compile(r'[^aeiouAEIOU]')
print(consanentRegex.findall('Robocop eats baby food.'))
beginsWithHello = re.compile(r'^Hello') # The '^' makes sure it STARTS with "Hello" --> Case sensitive
print(beginsWithHello.search('Hello Hello')) # RETURNS -> <re.Match object; span=(0, 5), match='Hello'>
endsWithNumber = re.compile(r'\d$') # this will look for and return the last digit ONLY IF the search field ends in a digit and it will only return ONE value.
#To search for a larger number, add the plus sign
print(endsWithNumber.search('the number is 48589392')) #<re.Match object; span=(21, 22), match='2'>
searchWholeNum = re.compile(r'\d+$')
print(searchWholeNum.search('number is 1239812983123')) #<re.Match object; span=(10, 23), match='1239812983123'>
# THE DOT will match everything ex dpt a new line. in the below example it matches everything that ends with 'at'
atRegex = re.compile(r'.at')
print(atRegex.findall('cat, mat, sat, flat, bat, rat, 9at, .at')) #['cat', 'mat', 'sat', 'lat', 'bat', 'rat', '9at', '.at'] //notice it only returned LAT not FLAT
nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)') #This will match anything entered after first and last name field
name = nameRegex.search('First Name: Tim Last Name: Allen')
print(name.group(1)) #Tim
print(name.group(2)) #Allen
# THE DOT and DOT ASTERIK are greedy matching options, to use non-greedy options,use the '?' to match the first one.
###EXAMPLE###
nongreedyRegex = re.compile(r'<.*?>')
nongreedy = nongreedyRegex.search('<to serve man> for dinner.>')
print(nongreedy.group())
greedyRegex = re.compile(r'<.*>')
greedy = greedyRegex.search('<to serve man> for dinner.>')
print(greedy.group())
### HOW TO SEARCH MULTIPLE LINES: ###
newLineRegex = re.compile('.*', re.DOTALL)
print(newLineRegex.search('Serve the public. \nProsad \nanother line').group())
### HOW TO IGNORE upper or lower CASE ###
ignoreRegex = re.compile(r'robocop', re.I) # --> re.I or re.IGNORECASE ignores case sensitive
print(ignoreRegex.search('rObOcOp was here').group())
namesRegex = re.compile(r'Agent \w+')
x = namesRegex.sub('CENSORED', 'Agent Alice is complicit in the murder of Agent Bond.')
print(x)
agentNamesRegex = re.compile(r'Agent (\w)\w*')
z = agentNamesRegex.sub(r'\1******', 'Agent Alice told Agent Bob that Agent Eve was with Agent Bond.')
print(z)
phoneRegex = re.compile(r'''(
(\d{3}|\(d{3}\))?
(\s|-|\.)?
\d{3}
(\s|-|\.)
\d{4}
(\s*(ext|x|ext.)\s*d{2,5})?
)''',re.VERBOSE)
j = phoneRegex.search('408-344-3532, ext 4935')
print(j.group())
|
5ebb8cf419dd497c64b1d7ac3b22980f0c33b790 | sberk97/PythonCourse | /Week 2 - Mini Project Guess number game.py | 2,289 | 4.21875 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import random
import simplegui
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
global secret_number
global times
times = 7
print "You have 7 guesses"
secret_number=random.randrange(0,99)
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global secret_number
global times
times = 7
print "You have 7 guesses"
secret_number=random.randrange(0,99)
print "Restarting the game, range now is[0,100)"
def range1000():
# button that changes the range to [0,1000) and starts a new game
global secret_number
global times
times = 10
print "You have 10 guesses"
secret_number=random.randrange(0,999)
print "Restarting the game, range now is[0,1000)"
def input_guess(guess):
# main game logic goes here
guess=int(guess)
print "Guess was %s" % (guess)
if guess==secret_number:
print "Correct"
new_game()
elif guess > secret_number:
print "Lower"
global times
if times > 0:
times -= 1
print "You have %s guesses left" % (times)
else:
print "You are out of guesses, the secret number was %s, new game begins" % (secret_number)
new_game()
elif guess < secret_number:
print "Higher"
if times > 0:
times -= 1
print "You have %s guesses left" % (times)
else:
print "You are out of guesses, the secret number was %s, new game begins" % (secret_number)
new_game()
else:
print "Error"
# create frame
frame=simplegui.create_frame("Guess game", 300, 300)
input=frame.add_input("Input", input_guess, 50)
# register event handlers for control elements and start frame
button1=frame.add_button("Range is [0,100)", range100, 100)
button2=frame.add_button("Range is [0,1000)", range1000, 100)
frame.start()
# call new_game
new_game()
# always remember to check your completed program against the grading rubric
|
3878d38ef86301060b4f9e9fd8624afc0379021d | leegj93/PythonProject | /Code03-01 SQLite 데이터 입력.py | 453 | 3.953125 | 4 | import sqlite3
conn = sqlite3.connect("samsongDB")# 1. DB connecting
cur = conn.cursor() # 2. create cursor(connected rope)
sql = "CREATE TABLE IF NOT EXISTS userTable(userID INT, userName char(5))"
cur.execute(sql)
sql= "INSERT INTO userTable VALUES(1, '홍길동')";
cur.execute(sql)
sql= "INSERT INTO userTable VALUES(2, '이순신')";
cur.execute(sql)
cur.close()
conn.commit()
conn.close() # 6. DB disconnect
print('OK')
|
563b3341cab49a64ba69d6f1ebf14ad8815e65b3 | Carlosiiv/Algos | /Python_Algo_Solutions/hello_world.py | 606 | 3.921875 | 4 | # Task 1: print hello world
print("Hello World!")
msg = "Hello World!"
# Task 2: hello name
name = "Carlos"
print("Hello", name,"!")
print("Hello " + name + "!")
# Task 3: favorite number
number = 42
print("Hello" , name, "!", "My favorite number is", number,".")
print(f'{"Hello " + name + "!" + " My favorite number is" } {number}{"."}')
print("Hello " + name + "!" + " My favorite number is " + str(number) + ".")
# Task 4: favorite food
favFood1 = 'pizza'
favFood2 = 'tacos'
print("My favorite foods are {} and {}".format(favFood1, favFood2))
print(f"My favorite foods are {favFood1} and {favFood2}!") |
37d73ba59b4279905f3b0bd3575c87a5e664144a | Carlosiiv/Algos | /Python_Algo_Solutions/Functions_Basics1.py | 1,665 | 3.921875 | 4 | #1 prints out 5
def a():
return 5
print(a()) #5
#2 5+5=10 Prints 10
def a():
return 5
print(a()+a()) #10
#3 Returns 5 function ends
def a():
return 5
return 10
print(a()) #5
#4 returns 5 funtion ends
def a():
return 5
print(10)
print(a()) #5
#5 Prints 5 but doesnt return anything so x = null
def a():
print(5)
x = a()
print(x) #5
#6 Prints 3 & 5 but since nothing is returned you cant add the two elements together
def a(b,c):
print(b+c)
# print(a(1,2) + a(2,3))
#7 string plus string returns 25
def a(b,c):
return str(b)+str(c)
print(a(2,5)) #25
#8 prints 100 returns 10
def a():
b = 100
print(b)
if b < 10:
return 5
else:
return 10
return 7
print(a()) #100 10
#9 Prints 7 Prints 14 Prints 7 & 14 then adds the two elements that were returned
def a(b,c):
if b<c:
return 7
else:
return 14
return 3
print(a(2,3)) #7
print(a(5,3)) #14
print(a(2,3) + a(5,3)) #7+14= 21
#10 ads 3+5 retunrs 8 and prints
def a(b,c):
return b+c
return 10
print(a(3,5)) #8
#11 #500,500,300,500
b = 500
print(b) #500
def a():
b = 300
print(b) #300
print(b)#500
a()
print(b) #300
#12 500 500 300 300
b = 500
print(b) #500
def a():
b = 300
print(b) #300
return b
print(b) #500
a()
print(b) #300
b = 500
print(b) #500
def a():
b = 300
print(b) #300
return b
print(b) #500
b=a()
print(b) #300
#14 1 , 3 , 2
def a():
print(1)#1
b()#3
print(2)#2
def b():
print(3)
a()# <---- call
#15 1 , 3 , 5 , 10
def a():
print(1)#1
x = b()#3
print(x) #5
return 10
def b():
print(3)
return 5
y = a()
print(y)#10 |
2eb0fc12153dd9c11fe1b3ed4391c811aa8ca559 | mike-shevchuk/CodeWars | /Multiples of 3 or 5.py | 113 | 3.84375 | 4 | def solution(number):
return sum([i for i in range(number) if (i % 5 == 0 or i % 3 == 0)])
print(solution(10)) |
1b71cf284540511a24d5d45136738c32f7323846 | PRASASTIRAI/project-150 | /Random_country_and_city.py | 2,057 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 3 18:24:55 2021
@author: hp
"""
from tkinter import*
import random
root=Tk()
root.title("RANDOM LIST ANS LUCKY FRIEND GENERATER")
root.geometry("700x400")
enter_country=Entry(root)
enter_country.place(relx=0.5,rely=0.2,anchor=CENTER)
enter_city=Entry(root)
enter_city.place(relx=0.5,rely=0.4,anchor=CENTER)
label_country_list=Label(root)
label_random_country=Label(root)
label_random_country_name=Label(root)
label_city_list=Label(root)
label_random_city=Label(root)
label_random_city_name=Label(root)
list1=[]
list2=[]
def add_country_and_city():
country_name=enter_country.get()
list1.append(country_name)
label_country_list["text"]="Your country list is : " + str(list1)
city_name=enter_country.get()
list2.append(city_name)
label_city_list["text"]="Your city list is : " + str(list2)
def random_country_city():
length=len(list1)
random_no=random.randint(0,lenght-1)
label_random_country["text"]= str(list1)
genarated_random_country=list1[list1]
label_random_country_name["text"]="YOUR RANDOM COUNTRY IS : " + str(genarated_random_country)
length=len(list2)
random_no2=random.randint(0,lenght-1)
label_random_city["text"]= str(list2)
genarated_random_city=list1[list2]
label_random_city_name["text"]="YOUR RANDOM CITY IS : " + str(genarated_random_city)
button1=Button(root,text="ADDD TO YOUR COUNTRY AND CITY LIST!!" , command=add_country_and_city)
button1.place(relx=0.5,rely=0.3,anchor=CENTER)
label_country_list.place(relx=0.5,rely=0.4,anchor=CENTER)
button2=Button(root,text="DISPLAY RANDOM COUNTRY AND CITY!!!!" , command=random_country_city)
button2.place(relx=0.5,rely=0.5,anchor=CENTER)
label_random_country.place(relx=0.5,rely=0.7,anchor=CENTER)
label_random_country_name.place(relx=0.5,rely=0.8,anchor=CENTER)
label_random_city.place(relx=0.5,rely=0.9,anchor=CENTER)
label_random_city_name.place(relx=0.5,rely=1,anchor=CENTER)
root.mainloop()
|
e909d198f246c9c8e10931e57a8d14c3c8961d7d | shantanuHubb/facuilty_Time_Table_System- | /subject1.py | 506 | 3.53125 | 4 | from Tkinter import *
top=Tk()
top.config(background="brown4")
top.title("WELCOME")
top.geometry("1600x900")
Label(top,text="SUBJECT NAME=",fg="black",bg="brown4",bd=14,font=("times",27)).place(x=300,y=215)
el=Entry(top,font=("arial",21))
el.place(x=690,y=230)
Button(top,text="submit ",fg="white",bg="cyan4",bd=10,padx=5,pady=5).place(x=690,y=390)
Button(top,text="cancel",fg="white",bg="cyan4",command=top.destroy,bd=10,padx=5,pady=5).place(x=830,y=390)
top.mainloop()
|
633fa2812a8a223fdff3ec482404295c678874e3 | jihansalma/QUIZ-4 | /Quiz42_Jihan Salma R.W._1201180431.py | 179 | 3.640625 | 4 | fruits = ['Nanas', 'Apel', 'Pepaya', 'Kentang']
for i in range (4) :
print(fruits[i])
length = len(fruits)
i = 0
while i < length:
print(fruits[i])
i += 1 |
8130b1edf4df29a9ab76784289a22d5fb90863e7 | ridhishguhan/faceattractivenesslearner | /Classify.py | 1,158 | 3.6875 | 4 | import numpy as np
import Utils
class Classifier:
training = None
train_arr = None
classes = None
def __init__(self, training, train_arr, CLASSES = 3):
self.training = training
self.train_arr = train_arr
self.classes = CLASSES
#KNN Classification method
def OneNNClassify(self, test_set, K):
# KNN Method
# for each test sample t
# for each training sample tr
# compute norm |t - tr|
# choose top norm
# class which it belongs to is classification
[tr,tc] = test_set.shape
[trr,trc] = self.train_arr.shape
result = np.array(np.zeros([tc]))
i = 0
#print "KNN : with K = ",K
while i < tc:
x = test_set[:,i]
xmat = np.tile(x,(1,trc))
xmat = xmat - self.train_arr
norms = Utils.ComputeNorm(xmat)
closest_train = np.argmin(norms)
which_train = self.training[closest_train]
attr = which_train.attractiveness
result[i] = attr
#print "Class : ",result[i]
i += 1
return result |
8f4f102f4568c38e549ef17db710cc380141bb14 | Williamsjanthony15/ceaser_cipher | /ceaser_cipher/ceaser_cipher/ceaser_cipher.py | 1,235 | 3.78125 | 4 | import nltk
from nltk.corpus import words
nltk.download('words', quiet=True)
# nltk.download('names', quiet=True)
word_list = words.words()
# print(word_list)
# string = 'computer'
# word_count
# if string in word_list:
# word_count +=1
# # print(' I am here')
# else:
# print('I am not here')\
#cesar cipher
# The quick brown fox jumped over the lazy sleeping dog
# Shift of 15
# IWT FJXRZ QGDLC UDM YJBETS DKTG IWT APOXAN HATTEXCV SDV
def encrypt(plain_text, key):
encrypted_word = ''
print(f'The plain text word is{plain_text}.')
for i in range(len(plain_text)):
char = plain_text[i]
if (char.isupper()):
encrypted_word += chr((ord(char) + key-65) % 26 + 65)
else:
encrypted_word += chr((ord(char) + key -97) % 26 + 97)
return encrypted_word
def decrypt(encoded, key):
return encrypt(encoded, -key)
## This is for Encrypt method
if __name__ == "__main__":
plain_text = 'IM gonna getCHA'
key = 12
print('Text is: ' + plain_text)
print('Key is: ' + str(key))
print('Result is: ' + encrypt(plain_text, key))
## This is for decrypt method
# if __name__ == "__main__":
# print(decrypt('89', 6)) |
1a3df69863e18ff518fe81d2d649cbdaeda9adbe | ginajoerger/Artificial-Intelligence | /15 Puzzle/15 Puzzle.py | 5,940 | 4.03125 | 4 | from queue import PriorityQueue
import sys
numNodes = 0
class Node:
def __init__(self, state, parent, operator, depth, pathCost):
self.state = state
self.parent = parent
self.children = list()
self.operator = operator
self.depth= depth
self.pathCost = pathCost
def same(self, state):
"""
Compares two states, sees if they are equal and/or the goal state.
"""
if self.state == state:
return True
else:
return False
def __lt__(self, other):
"""
Compares the path cost of two states.
"""
return self.pathCost < other.pathCost
def move(self):
"""
Creates the children af†er checking if the moves are possible.
"""
global numNodes
zeroIndex = self.state.index(0)
new = self.state[:]
if zeroIndex not in [0, 1, 2, 3]: # Makes children after going up
temp = new[zeroIndex - 4]
new[zeroIndex - 4] = new[zeroIndex]
new[zeroIndex] = temp
child = Node(new, self, "U", self.depth + 1, self.pathCost)
self.children.append(child)
numNodes += 1
new = self.state[:]
if zeroIndex not in [3, 7, 11, 15]: # Makes children after going right
temp = new[zeroIndex + 1]
new[zeroIndex + 1] = new[zeroIndex]
new[zeroIndex] = temp
child = Node(new, self, "R", self.depth + 1, self.pathCost)
self.children.append(child)
numNodes += 1
new = self.state[:]
if zeroIndex not in [12, 13, 14, 15]: # Makes children after going down
temp = new[zeroIndex + 4]
new[zeroIndex + 4] = new[zeroIndex]
new[zeroIndex] = temp
child = Node(new, self, "D", self.depth + 1, self.pathCost)
self.children.append(child)
numNodes += 1
new = self.state[:]
if zeroIndex not in [0, 4, 8, 12]: # Makes children after going left
temp = new[zeroIndex - 1]
new[zeroIndex - 1] = new[zeroIndex]
new[zeroIndex] = temp
child = Node(new, self, "L", self.depth + 1, self.pathCost)
self.children.append(child)
numNodes += 1
def aStar(initial, final):
"""
A* Algorithm.
"""
p = PriorityQueue()
p.put(Node(initial, None, "", 0, 0))
GoalFound = False
while p and not GoalFound: #Until goal is found, the move function is recursed.
node = p.get()
node.move()
for child in node.children: #For every child, the pathCost is updated with the proper path cost
if child.same(final):
GoalFound = True
x = child.depth + manhattanH(child.state, final)
path(child, x)
cost = child.depth + manhattanH(child.state, final)
child.pathCost = cost
p.put(child, cost)
def manhattanH(state, final):
"""
Sums the distances of each state to its place in the final state.
"""
x = 0
for i in range(0, 16):
x += manhattanA(state.index(i), final.index(i))
return x
def manhattanA(x, y):
"""
Auxiliary function for the manhattan distance heuristic.
"""
#Matrix coordinates from the state list.
m = {0: (1, 1), 0.25: (1, 2), 0.50: (1, 3), 0.75: (1, 4),
1: (2, 1), 1.25: (2, 2), 1.50: (2, 3), 1.75: (2, 4),
2: (3, 1), 2.25: (3, 2), 2.50: (3, 3), 2.75: (3, 4),
3: (4, 1), 3.25: (4, 2), 3.50: (4, 3), 3.75: (4, 4)}
x1, y1 = m[x/4]
x2, y2 = m[y/4]
return abs(x1-x2) + abs(y1-y2)
def path(Node, x):
"""
Prints depth of node, then goes to each parent node to obtain the
operator needed to create the path to solution.
"""
node = Node
path = list()
f = list()
path.append(node.operator) #Gets the operator of last node
f.append(node.pathCost) #Gets the path cost of last node
depth = node.depth
while node.parent is not None: #Recurses up the A* graph until the root node is found
node = node.parent
path.insert(0, node.operator)
f.insert(0, node.pathCost)
del path[0]
del f[-1]
f.insert(len(f), x)
print("\n%d" % depth) #Prints depth
print(numNodes) #Prints number of nodes
for item in range(len(path)): #Prints the directions
if item == (len(path)-1):
print(path[item], end="\n")
else:
print(path[item], end=" ")
for item in f: #prints the f(n) value
print(item, end=" ")
def main():
"""
Reads given file, takes the input and output.
Puts them into the A* funtion, then outputs results into a text file.
"""
insert = []
finalinsert = []
initial = []
final = []
sys.stdout = open('Output5.txt','wt') #Makes output txt file for writing
file = open('Input1.txt', 'r') #Opens the Input File to read
for i in range(0, 4): #Reads each line and puts it in a list
x = file.readline()
print(x, end='') #Prints onto output text file
insert.append(x)
for i in insert: #Makes the items in list consistent for A*
x = list(map(int, i.split()))
for i in x:
initial.append(i)
for i in range(7, 12): #Reads each line and puts it in a list
x = file.readline()
print(x, end='') #Prints onto output text file
finalinsert.append(x)
for i in finalinsert: #Makes the items in list consistent for A*
x = list(map(int, i.split()))
for i in x:
final.append(i)
file.close()
aStar(initial, final)
if __name__ == '__main__':
main() |
289a90323ade1b352c59eda2657e6ae0237fc600 | nupur0502/Udemy | /FizzBuzz/solution.py | 368 | 3.9375 | 4 | def fizzBuzz(self, s):
string = []
for n in range(1, s + 1):
if n % 3 == 0 and n % 5 == 0:
string.append("FizzBuzz")
elif n % 3 == 0:
string.append("Fizz")
elif n % 5 == 0:
string.append("Buzz")
else:
string.append(n)
return string |
8ef3c6bb06b8ed4c9181e78f9b4ef30059334374 | dtroupe18/BasicPerceptron | /perceptron.py | 1,124 | 3.609375 | 4 | # a single perceptron
import numpy as np
class Perceptron(object):
def __init__(self, rate = 0.01, niter = 10):
self.rate = rate
self.niter = niter
def fit(self, X, y):
"""
Fit training data
:param X: Training vectors, X.shape: [samples, features]
:param y: Target value, y.shape : [samples]
:return:
"""
# weights
self.weight = np.zeros(1 + X.shape[1])
# Number of misclassifications
self.errors = []
for i in range(self.niter):
err = 0
for xi, target in zip(X, y):
delta_w = self.rate * (target - self.predict(xi))
self.weight[1:] += delta_w * xi
self.weight[0] += delta_w
err += int(delta_w != 0)
self.errors.append(err)
return self
def net_input(self, X):
""" Calculate net input """
return np.dot(X, self.weight[1:]) + self.weight[0]
def predict(self, X):
""" Return class label after unit step """
return np.where(self.net_input(X) >= 0.0, 1, -1)
|
8d82910e342182c0c6856ffe129bb94ad3391c39 | Evgeniy-code/python | /prob/calculator.py | 521 | 4.3125 | 4 | #!/usr/bin/env python3
a = float(input("введите первое число:"))
what = input("что делаем (+:-:*:/):")
b = float(input("введите второе число:"))
if what == "+":
d = a + b
print("равно:" + str(d))
elif what == "-":
d = a - b
print("равно:" + str(d))
elif what == "*":
d = a * b
print("равно:" + str(d))
elif what == "/":
d = a / b
print("равно:" + str(d))
else:
print("введено неверное значение")
|
84fc914a6678914e0e8898d4c4451d76c9810135 | fjollabeqiri/knapsack_problem | /Knapsack.py | 4,576 | 3.96875 | 4 | import random
from typing import List
class Item:
def __init__(self, item_id, weight, value):
self.id = item_id
self.weight = weight
self.value = value
self.ratio = value/weight
class Knapsack:
def __init__(self, items_in, items_out, capacity):
self.items_in = items_in
self.items_out = items_out
self.capacity = capacity
def check_feasibility(self, items):
w = 0
for item in items:
w = w + item.weight
if w > self.capacity:
return False
if w > self.capacity:
return False
else:
return True
def print_items(self):
items_in_knapsack_before = ""
for item in self.items_in:
items_in_knapsack_before = items_in_knapsack_before + str(item.id) + ", "
items_in_knapsack_before = items_in_knapsack_before[:-2]
items_in_knapsack_before = items_in_knapsack_before + " | "
for item in self.items_out:
items_in_knapsack_before = items_in_knapsack_before + str(item.id) + ", "
items_in_knapsack_before = items_in_knapsack_before[:-2]
items_in_knapsack_before = items_in_knapsack_before + "\tFitness: " + str(self.fitness())
print(items_in_knapsack_before)
def remove_items(self, items_in, items_removed):
no_of_items_in = len(self.items_in)
rand_no_of_items_out = random.randint(1, no_of_items_in - 1) #-1
rand_items_out = random.sample(list(range(0, no_of_items_in)), rand_no_of_items_out)
rand_items_out.sort(reverse=True)
for rand in rand_items_out:
items_removed.append(items_in[rand])
items_in.pop(rand)
def add_items(self, items_out_copy, items_in_updated, items_out_updated):
no_of_items_out = len(self.items_out)
rand_no_of_items_in = random.randint(1, no_of_items_out)
rand_items_in = random.sample(list(range(0, no_of_items_out)), rand_no_of_items_in)
rand_items_in.sort(reverse=True)
for rand in rand_items_in:
items_in_updated.append(items_out_copy[rand])
items_out_updated.remove(items_out_copy[rand])
def perturb1(self):
feasible = False
items_removed: List[Item] = []
items_in_updated: List[Item] = []
items_out_updated: List[Item] = []
while not feasible:
# remove n random elements
items_in_copy = self.items_in.copy()
items_out_copy = self.items_out.copy()
items_removed = []
self.remove_items(items_in_copy, items_removed)
counter = 0
while not feasible:
if counter <= 10:
# add m random elements
items_out_updated = items_out_copy.copy()
self.add_items(items_out_copy, items_in_copy, items_out_updated)
feasible = self.check_feasibility(items_in_copy)
counter = counter + 1
else:
break
for item in items_removed:
items_out_updated.append(item)
self.items_in = items_in_copy
self.items_out = items_out_updated
def perturb2(self):
# remove one or more items
items_in = self.items_in.copy()
items_out = self.items_out.copy()
items_removed = []
self.remove_items(items_in, items_removed)
for item in items_removed:
items_out.append(item)
# greedy algorithm
items_out_copy = items_out.copy()
i = 0
while i < 5:
if len(items_out) != 0:
next_item = self.select_next(items_out)
items_in.append(next_item)
items_out.remove(next_item)
items_out_copy.remove(next_item)
feasible = self.check_feasibility(items_in)
if not feasible:
items_in.remove(next_item)
items_out_copy.append(next_item)
i = i + 1
else:
break
self.items_in = items_in
self.items_out = items_out_copy
def select_next(self, items_out):
best_item = items_out[0]
for item in items_out:
if item.value >= best_item.value:
best_item = item
return best_item
def fitness(self):
fitness_score = 0
for item in self.items_in:
fitness_score = fitness_score + item.value
return fitness_score
|
210cdca8180547ed320f5c534cd0013985477424 | zpak96/ClassWork | /IntroToPython/class.py | 121 | 3.546875 | 4 | #!/usr/bin/python3
# Zane Paksi
def gc(a, b):
r = a % b
a = a - r
return a
print(gc(a=int(input('a: ')), b=3))
|
7677c3c2db21b429b009bbd88ee8b888e4522e7b | BarbecuePizza/py1000 | /005字符串赋值.py | 503 | 3.859375 | 4 | """
ans = input("您是否喜欢喝咖啡yes/no:")
if ans == "yes":
print("制作咖啡")
elif ans == "no":
print("随时恭候")
"""
# 字符串变量中所包含的索引值
astr = "python"
print(astr[0:2]) #变量[角标的起始位置 :角标的结束位置]
print(astr[0:8])
print(astr[0:8:2]) #变量[角标的起始位置 :角标的结束位置 : 步长值]
print(astr[-2])
print(astr[-1:-7:-1]) #反向取值
print(astr[:])
print(astr[::-1])
# if "p" in astr :
# print("yes")
|
c721631032d3d148c07a7235b0476f2033794e4b | ilankham/advent_of_code_2020 | /day10_adapter_array.py | 3,599 | 3.546875 | 4 | """ Solutions for https://adventofcode.com/2020/day/10 """
# import modules used below.
from collections import Counter, UserList
from itertools import chain, combinations
from math import prod
# Part 1: What is the number of 1-jolt differences multiplied by the number of
# 3-jolt differences in the provided data file?
# Create data model for output "joltages" in data file.
class OutputJoltages(UserList):
""" Data Model for output joltages from data file """
@classmethod
def from_file(cls, file_path):
""" Read output joltages from specified file and add min/max """
with open(file_path) as fp:
values_in_file = [int(line.rstrip()) for line in fp]
return cls(chain([0], values_in_file, [max(values_in_file)+3]))
def sorted_pairwise_differences(self, joltages=None):
""" Find sorted pairwise differences for Part 1 """
if joltages is None:
joltages = self
sorted_data_values = sorted(joltages)
pairwise_differences = [
sorted_data_values[i] - sorted_data_values[i-1]
for i in range(1, len(joltages))
]
return pairwise_differences
def partition_into_valid_joltage_subsequences(self):
""" Find all possible joltage subsequences for Part 2 """
sorted_data_values = sorted(self)
joltage_diffs = self.sorted_pairwise_differences()
data_partitions = {}
partition_lower_bound_index = 0
for i in range(len(self)-1):
if joltage_diffs[i] == 3:
data_partitions[
frozenset(
sorted_data_values[partition_lower_bound_index:i+1]
)
] = []
partition_lower_bound_index = i + 1
for partition in data_partitions:
if len(partition) == 1:
continue
partition_interior = partition - {min(partition), max(partition)}
partition_interior_powerset = list(chain.from_iterable(
combinations(partition_interior, n)
for n in range(len(partition_interior)+1)
))
for subset in partition_interior_powerset:
partition_subset = (
set(subset) |
{min(partition), max(partition)}
)
if max(self.sorted_pairwise_differences(partition_subset)) < 4:
data_partitions[partition].append(partition_subset)
return data_partitions
# Read "joltage" values from data file.
output_joltages = OutputJoltages.from_file('data/day10_adapter_array-data.txt')
# Find "joltages" differences for Part 1.
diffs = output_joltages.sorted_pairwise_differences()
counts = Counter(diffs)
print(f'Number of joltages values in data file: {len(output_joltages)}')
print(f'Number of differences of 1 for Part 1: {counts[1]}')
print(f'Number of differences of 3 for Part 1: {counts[3]}')
print(f'Product for Part 1: {counts[1]}*{counts[3]}={counts[1]*counts[3]}')
# Part 2: What is the total number of valid "joltage" sequences?
# Find total number of valid "joltage" sequences for Part 2.
partitions = output_joltages.partition_into_valid_joltage_subsequences()
number_of_sequences = prod(
len(v) for v in partitions.values() if len(v) != 0
)
print(f'\nLength of partitions for Part 2: {len(partitions)}')
print(f'Minimum partition length for Part 2: {min(partitions)}')
print(f'Maximum partition length for Part 2: {max(partitions)}')
print(f'Number of sequences for Part 2: {number_of_sequences}')
|
8e7f9c407cf091a1b4b7eede31be320598d9875b | ilankham/advent_of_code_2020 | /day01_report_repair.py | 1,777 | 4.0625 | 4 | """ Solutions for https://adventofcode.com/2020/day/1 """
# Part 1: Find the two entries that sum to 2020 in the provided data file
# and then multiply those two numbers together.
# Read positive integer values from data file.
with open('data/day01_report_repair-data.txt') as fp:
data_values = [int(line.rstrip()) for line in fp]
# In order to minimize the number of comparisons needed, calculate 2020 - v
# for each value v in the data file. If 2020 - v is also in the data file,
# then (2020 - v) + v = 2020. Consequently, the desired solution will be
# (2020-v)*v.
differences_from_2020 = {
2020 - v
for v in data_values
}
# Search the collection of difference for value in the data file, and stop
# once a solution has been found for Part 1.
for v in data_values:
if v in differences_from_2020:
print(f'Values from data file for Part 1: {(2020-v, v)}')
print(f'Solution for Part 1: {2020-v}*{v} = {(2020-v)*v}')
break
# Part 2: What is the product of the three entries that sum to 2020?
# Generalizing, calculate 2020 - (v1 + v2) for each pair of values (v1, v2)
# in the data file. If v = 2020 - (v1 + v2) is also in the data file, then
# v + v1 + v2 = 2020. Consequently, the desired solution will be v*v1*v2.
pairwise_differences_from_2020 = {
2020 - (v1 + v2): (v1, v2)
for v1 in data_values
for v2 in data_values
}
# Search the collection of difference for value in the data file, and stop
# once a solution has been found for Part 2.
for v in data_values:
if v in pairwise_differences_from_2020.keys():
v1, v2 = pairwise_differences_from_2020[v]
print(f'Values from data file for Part 2: {(v, v1, v2)}')
print(f'Solution for Part 2: {v}*{v1}*{v2} = {v*v1*v2}')
break
|
2cd084fa011c52f379ff5237fd6115cd7dce7dea | ilankham/advent_of_code_2020 | /day06_custom_customs.py | 1,868 | 3.984375 | 4 | """ Solutions for https://adventofcode.com/2020/day/6 """
# import modules used below.
from collections import UserDict
# Part 1: In the provided data file, how many group-wise "yeses" occur?
# Create data model for "group responses" in data file.
class GroupResponses(UserDict):
""" Data Model for "question group_responses" from data file """
def __init__(self):
super().__init__()
self.group_size = 0
def add_responses(self, responses):
""" Add questions responses for group, and increment group size """
for response in responses:
self[response] = self.get(response, 0) + 1
self.group_size += 1
@property
def unanimous_yeses(self):
""" Return questions for which the group unanimously responded """
return [q for q in self if self[q] == self.group_size]
# Read "question group_responses" from data file.
group_responses = []
current_group = GroupResponses()
with open('data/day06_custom_customs-data.txt') as fp:
for line in fp:
if line == '\n':
group_responses.append(current_group)
current_group = GroupResponses()
continue
current_group.add_responses(line.rstrip())
group_responses.append(current_group)
# Count number of group-wise "yeses" for Part 1.
number_of_gw_yeses = sum([len(r) for r in group_responses])
print(f'Number of response groups in data file: {len(group_responses)}')
print(f'Number of group-wise "yeses" for Part 1: {number_of_gw_yeses}')
# Part 2: In the provided data file, how many group-wise unanimous "yeses"
# occur?
# Count number of unanimous group-wise "yeses" for Part 2.
number_of_unanimous_gw_yeses = sum(
[len(r.unanimous_yeses) for r in group_responses]
)
print(
f'Number of unanimous group-wise "yeses" for Part 2: '
f'{number_of_unanimous_gw_yeses}'
)
|
1cdb26997f2e34b12970ba968ff4f0c1e279c03d | DaneSlattery/oops-hashcode-2019 | /simple.py | 1,125 | 3.515625 | 4 | rowlist = list()
# a_example
# b_small
# c_medium
# d_big
with open('d_big.in' , 'r') as f:
line_one = f.readline().split()
R = line_one[0]
C = line_one[1]
L = line_one[2]
H = line_one[3]
if (int(H) > int(C)):
H = C
print('Rows: ' + R)
print('Columns: ' + C)
print('Min Ingredient: ' + L)
print('Max Cells: ' + H)
print(' ' )
for i in range(int(R)):
line = f.readline()
chararray = list(line.strip('\n'))
j = 0
tcount = 0
mcount = 0
for char in chararray:
if char == 'T':
tcount += 1
#print('Tomatos Found on this row: ' +str( tcount) )
if char == 'M':
mcount += 1
#print('Mushroom found on this row: ' + str( mcount))
j += 1
if j >= int(H):
break
if ((mcount >= int(L)) and (tcount >= int(L))):
print('Row ' + str(i) + ' has a valid slice')
rowlist.append(i)
#print(chararray)
f.closed
with open('d_big.out', 'w') as out:
out.write(str(len(rowlist)) + '\n')
for x in range(len(rowlist)):
out.write(str(rowlist[x]) + ' 0 ' + str(rowlist[x]) + ' ' + str(int(H) - 1) + '\n')
out.closed |
8a000b72ad1df43bd275d8fa235dee249ecda2bd | Ali-Parandeh/dominos | /dominos/utils.py | 1,007 | 3.609375 | 4 | '''
Dominos Pizza API utility functions.
'''
import re
def enum(**enums):
'''
Utility function to create a simple enum-like data type. Behind the scenes
it is just a list.
:param list enums: A list of key value pairs.
:return: A simple list.
:rtype: list
'''
return type('Enum', (), enums)
def strip_unicode_characters(text):
'''
Remove the unicode symbols from the given string.
:param string text: The text containing the trademark symbol.
:return: Text with the unicode symbols removed.
:rtype: string
'''
return re.sub(r'[^\x00-\x7F]+', '', text)
def update_session_headers(session):
'''
Add content type header to the session.
:param: requests.sessions.Session session: A session.
:return: A session with modified headers.
:rtype: requests.sessions.Session
'''
session.headers.update({
'Content-Type': 'application/json; charset=utf-8',
'Host': 'www.dominos.co.uk'
})
return session
|
5c4362ae8eea49bd105ae1f0ffced5d62aba12ed | ArnoldKevinDesouza/258327_Daily_Commits | /Dict_Unsolved02.py | 209 | 4.5 | 4 | # Write a Python program to convert a list into a nested dictionary of keys
list = [1, 2, 3, 4]
dictionary = current = {}
for name in list:
current[name] = {}
current = current[name]
print(dictionary) |
3963dccc95056b06715cf81c7a8eab7091c682a5 | ArnoldKevinDesouza/258327_Daily_Commits | /If_Else_Unsolved04.py | 314 | 4.15625 | 4 | # Write a program to get next day of a given date
from datetime import date, timedelta
import calendar
year=int(input("Year:"))
month=int(input("\nMonth:"))
day=int(input("\nDay:"))
try:
date = date(year, month, day)
except:
print("\nPlease Enter a Valid Date\n")
date += timedelta(days=1)
print(date) |
52effe011dc2dce66488280fad756db564e61d9f | romanvoyt/ds_algs | /algorithms/quick_sort.py | 862 | 3.96875 | 4 | from typing import List
import random
class QuickSort:
def __int__(self, array: List[list]):
self.array = array
def swap(self, a, b):
temp = a
a = b
b = temp
# To do: fix bug (during the sorting the repeatable elements of the list are deleted)
def sort(self, array):
if len(array) < 2:
return array
base = array[0]
lower_subarray = [num for num in array[1:] if num < base]
higher_subarray = [num for num in array[1:] if num > base]
return self.sort(lower_subarray) + [base] + self.sort(higher_subarray)
if __name__ == '__main__':
numbers = [random.randint(1, 20) for _ in range(10)]
print(f'unsorted array : {numbers}')
quickie = QuickSort()
quickie.array = numbers
array = quickie.sort(quickie.array)
print(f'sorted array {array}')
|
7f9b8978b90454baec03b833d291fc1bf49959ba | KelstonClub/20191130 | /testing.py | 2,291 | 3.6875 | 4 | #!python
import unittest
import tommy as challenges
class TestChallenges(unittest.TestCase):
def test_fizz(self):
actual = list(challenges.fizz(10))
expected = [1, 2, 3, 4, 5, 6, 'Fizz', 8, 9, 10]
self.assertEqual(actual, expected)
def test_numbers(self):
actual = list(challenges.numbers(6))
expected = [1, 2, 3, 4, 5, 6]
self.assertEqual(actual, expected)
def test_odd_numbers(self):
actual = list(challenges.odd_numbers(8))
expected = [1, 3, 5, 7, 9, 11, 13, 15]
self.assertEqual(actual, expected)
def test_factorial(self):
actual = challenges.factorial(6)
expected = 720
self.assertEqual(actual, expected)
def test_triangular_numbers(self):
actual = list(challenges.triangular_numbers(5))
expected = [1, 3, 6, 10, 15]
self.assertEqual(actual, expected)
def test_backwards(self):
actual = challenges.backwards("Pomegranate")
expected = "Pomegranate"[::-1]
self.assertEqual(actual, expected)
def test_secret_santa(self):
candidates = ["Person %d" % (i + 1) for i in range(6)]
people = set(candidates)
actual = list(challenges.secret_santa(candidates))
givers = set(g for g, r in actual)
recipients = set(r for g, r in actual)
self.assertEqual(people, givers, "Someone isn't giving")
self.assertEqual(people, recipients, "Someone isn't receiving")
for giver, recipient in actual:
if giver == recipient:
raise RuntimeError("%s is giving to themself" % giver)
def test_anagrams(self):
import itertools
candidate = "wander"
actual = set(challenges.anagrams(candidate))
expected = set(["warned", "redawn", "andrew", "warden"])
self.assertEqual(actual, expected)
def test_palindromes(self):
length = 6
actual = set(challenges.palindromes(length))
words = set(w for w in open("words.txt").read().split() if len(w) == length)
expected = set(w for w in words if w == w[::-1])
self.assertEqual(actual, expected)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
dd652b879fd1162d85c7e3454f8b724e577f5e7e | Einsamax/Dice-Roller-V2 | /main.py | 2,447 | 4.375 | 4 | from time import sleep
import random
#Introduce user to the program
if __name__ == "__main__": #This does a good thing
print ("*" * 32)
print("Welcome to the Dice Roller!".center(32))
print ("*" * 32)
print()
sleep(1)
def roll_dice(diceamnt, diceint): #Defines function roll_dice
dicetotal = 0 #Reset dicetotal
for i in range(diceamnt): #Repeat for desired amount of dice rolled
diceroll = random.randint(1, diceint) #Roll based on type of dice selected
print(diceroll) #Print each roll as they are rolled
sleep(1)
dicetotal = dicetotal + diceroll #Add each dice roll to the total
return dicetotal
rolling=True
while rolling: #Repeats the loop upon each roll unless exited by user
choosing = True
while choosing:
#Prompt user to chose their dice type
print("*" * 32)
print("Which type of dice would you like to roll?")
sleep(1)
print("You may select from D2, D3, D4, D6, D8, D10, D12, D20, and D100!")
sleep(1)
print("You may also type 'exit' to leave the program.")
dicetype = str(input()) # User enters the type of dice they wish to roll
if dicetype == "exit": #User wishes to exit the program
sleep(1)
print("Thank you for rolling your luck!")
sleep(2)
rolling = False # exits the while loop
elif dicetype == "D2" or dicetype == "D3" or dicetype == "D4" or dicetype == "D6" or dicetype == "D8" or dicetype == "D10" or dicetype == "D12" or dicetype == "D20" or dicetype == "D100":
diceint = int(dicetype[1:]) #Extracts the dicetype as an integer
choosing = False
else:
print("Uh oh! It looks like you entered an invalid dice type!")
sleep(1)
#exit() #Exits the program because exiting the loop wasn't working lmao
sleep(1)
print("How many", dicetype, "would you like to roll?")
diceamnt = int(input()) # User enters number of dice to roll
sleep(1)
dicetotal = roll_dice(diceamnt, diceint) #Set the returned value to dicetotal
print("You rolled a total of", dicetotal, "!") #Print the total in a clear statement
sleep(2)
|
cad82c7d702e53a3cb6816d2668a10b2aa70ea65 | mariotalavera/ai_jetson_nano | /primer/pythonArrays.py | 159 | 3.515625 | 4 | gradeArray=[]
gradeArray.append(5.5)
gradeArray.append(3.2)
gradeArray.append(-2.7)
print(gradeArray)
gradeArray[1]=9.9
print(gradeArray[0])
print(gradeArray)
|
6c89d0c81a614532b532e70da283af3f7b3aa077 | mariotalavera/ai_jetson_nano | /primer/userInput.py | 120 | 3.953125 | 4 | x=float(input("Please enter First Number: "))
y=float(input("Please enter Second Number: "))
z=x+y
print("x + y = ", z)
|
f7bbc59863e4bb7060063b54a317e46b3f610ddf | abdullahshk17/Python-Programs | /31. Check prime number within a given range.py | 303 | 3.828125 | 4 | import math
low=int(input())
high=int(input())
prime=[]
for num in range(low,high+1):
factor=0
for i in range(2,int(math.sqrt(num))+1):
if num%i==0 :
factor+=1
break
if factor==0:
prime.append(num)
print("List of prime numbers is",prime)
|
456f4728d184207209eb09c73a9596509bb38988 | abdullahshk17/Python-Programs | /9.Program to reverse internal content of each word.py | 244 | 3.65625 | 4 | s=input() #Learning Python is easy
l=s.split()
new=[]
for i in range(len(l)):
new.append(l[i][::-1])
print(new) #['gninraeL', 'nohtyP', 'si', 'ysae']
for i in range(len(new)):
print(new[i],end=" ") #gninraeL nohtyP si ysae
|
b0002056658bc77575318dcdec59d11d5e4756c7 | abdullahshk17/Python-Programs | /11.Program to merge characters of 2 strings into a single string.py | 122 | 3.734375 | 4 | s1=input("Enter First String:") #ravi
s2=input("Enter Second String:") #mehta
output=s1+s2
print(output) #ravimehta
|
9b866ee496bae566841b445e8263337cb793c6b6 | abdullahshk17/Python-Programs | /17.Write a program to find the number of occurrences of each character present in the given String- Input ABCABCABBCDE & Output A-3,B-4,C-3,D-1,E-1.py | 211 | 3.546875 | 4 | def count(s):
l=sorted(list(set(s)))
for i in range(len(l)):
new=s.count(l[i])
print("{}-{}".format(l[i],new),end=" ") #A-3 B-4 C-3 D-1 E-1
s=input() #ABCABCABBCDE
count(s)
|
e5ba92e030f8f9c51964e21b7cfdef437ccde0c1 | rdagnoletto/AlgorithmsOOP-PracticePython | /HRcountSwapNodes.py | 2,311 | 3.703125 | 4 | #!/bin/python3
import os
import sys
#
# Complete the swapNodes function below.
#
class Node:
def __init__(self,key,depth):
self.left = None
self.right = None
self.val = key
self.depth = depth
def addChildren(self,c):
children = []
if c[0] != -1:
self.left = Node(c[0],self.depth+1)
children.append(self.left)
if c[1] != -1:
self.right = Node(c[1],self.depth+1)
children.append(self.right)
return children
def swap(self,d):
if d == 1:
if self.left is not None or self.right is not None:
temp = self.left
self.left = self.right
self.right = temp
del temp
else:
if self.left is not None:
self.left.swap(d-1)
if self.right is not None:
self.right.swap(d-1)
def inOrder(self,order=None):
if order is None:
order = []
if self.left is not None:
order = self.left.inOrder(order)
order.append(self.val)
if self.right is not None:
order = self.right.inOrder(order)
return order
def swapNodes(indexes, queries):
maxDepth = 1
root = Node(1,1)
children = root.addChildren(indexes[0])
while len(children) != 0:
temp = []
for c in children:
if c.depth > maxDepth:
maxDepth = c.depth
temp += c.addChildren(indexes[c.val-1])
children = temp
orders = []
for q in queries:
depth = q
while depth < maxDepth:
root.swap(depth)
depth += q
order = root.inOrder()
orders.append(order)
return orders
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
indexes = []
for _ in range(n):
indexes.append(list(map(int, input().rstrip().split())))
queries_count = int(input())
queries = []
for _ in range(queries_count):
queries_item = int(input())
queries.append(queries_item)
result = swapNodes(indexes, queries)
fptr.write('\n'.join([' '.join(map(str, x)) for x in result]))
fptr.write('\n')
fptr.close()
|
c6aadc50833356e4ce23f7f2a898634ff3efd4a7 | dsimonjones/MIT6.00.1x---Introduction-to-Computer-Science-and-Programming-using-Python | /Week2- Simple Programs/Lecture4- Functions/Function isIn (Chap 4.1.1).py | 611 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
@author: ali_shehzad
"""
"""
Finger exercise 11: Write a function isIn that accepts two strings as
arguments and returns True if either string occurs anywhere in the other,
and False otherwise. Hint: you might want to use the built-in str
operation in.
"""
def isIn(str1, str2):
if len(str1) > len(str2): #We're comparing which string is longer and then checking to see
if str2 in str1: #if the shorter string is present in the longer string
return True
else:
if str1 in str2:
return True
return False
|
55b9e5a113b11527ab82051a40b007fd8748d1eb | PPL-IIITA/ppl-assignment-AyushAgnihotri | /Question-8/source (copy)/girl.py | 1,034 | 3.625 | 4 | class girl:
'Class for girl'
name = ''
attractiveness = 0
maintenance_budget = 0
intelligence = 0
relationship_status = ''
boyfriend = ''
happiness=0
type_= ''
def __init__(self,name,attractiveness,maintenance_budget,intelligence,type_):
'Constructor fot initialising girl'
self.name = name
self.attractiveness = attractiveness
self.maintenance_budget = maintenance_budget
self.intelligence = intelligence
self.relationship_status = 'single'
self.boyfriend = ''
self.happiness=0
self.type_=type_
def set_happiness(self,happiness) :
'Method for setting happiness'
self.happiness=happiness
def set_boyfriend(self,boyfriend):
'Fucntion for setting boyfriend'
self.boyfriend=boyfriend
def modify_maintenance_budget(self,budget):
'Function for modifying maintainence budget'
self.maintenance_budget=budget
def is_eligible(self, boys_girlfriend_budget):
'Method for checking the eligibility'
if (self.maintenance_budget <= boys_girlfriend_budget):
return True
else:
return False
|
57f362801ece788c525d1d5d0c195d474d58182f | dravya08/workshop-python | /L11/P5.py | 460 | 4 | 4 | # wappp to ask user for dob and find the birthday
import datetime
try:
year = int(input("Enter year "))
month = int(input("Enter Month "))
day = int(input("Enter day "))
dob = datetime.date(year,month,day)
print(dob)
days_in_year = 365.2425
dt = datetime.datetime.now().date()
age = (dt - dob) / datetime.timedelta(days=365)
print("approx age= ", age)
diff = dt - dob
print("days=", diff)
except ValueError as e:
print("Input issue", e)
|
20c118532b54e4d820bcdc98d62e8cf0e68af89b | dravya08/workshop-python | /L12/P5.py | 1,811 | 3.546875 | 4 | from tkinter import *
from tkinter import messagebox
win = Tk()
win.title("Kamal Classes")
win.geometry("300x500+200+100")
win.configure(background='powder blue')
def f1():
fb,mat ="",""
if s1.get() == 1:
fb = "Fantastic"
if s1.get() == 2:
fb = "Excellent"
else:
fb = "Superb"
if n.get()==1:
mat += "Notes"
if s.get()==1:
mat += "Software"
if c.get()==1:
mat += "Certificate"
msg ="FeedBack" + fb + "\n" + "Materials" + mat
messagebox.showinfo("Result", msg)
to = "noron1999@gmail.com"
subject="Feedback+Materials by Dravya Gohil"
text = msg
import smtplib
sender = 'dravyagohil@gmail.com'
password = '8108214452'
message = 'Subject:{}\n\n{}'.format(subject,text)
server = smtplib.SMTP_SSL('smtp.gmail.com',465)
server.ehlo()
server.login(sender,password)
print("logged in")
try:
server.sendmail(sender,to,message)
print("enter email")
except:
print("Error sending email")
server.quit
s1 = IntVar()
s1.set(1)
fb= Label(win,text="FeedBack",font=('arial',20,'bold')).grid(stick='w')
rbFantastic = Radiobutton(win,text="Fantastic",font=('arial',15,'bold'),variable=s1, value=1).grid(stick='w')
rbExcellent = Radiobutton(win,text="Excellent",font=('arial',15,'bold'),variable=s1, value=2).grid(stick='w')
rbSuperb = Radiobutton(win,text="Superb",font=('arial',15,'bold'),variable=s1, value=3).grid(stick='w')
n,s,c = IntVar(),IntVar(),IntVar()
lblMaterials = Label(win,text="Materials",font=('arial',20,'bold')).grid(sticky='w')
cbNotes = Checkbutton(win,text="Notes",font=('arial',15,'bold')).grid(sticky ='w')
cbSoftware = Checkbutton(win,text="Software",font=('arial',15,'bold')).grid(sticky ='w')
cbCertificate = Checkbutton(win,text="Certificate",font=('arial',15,'bold')).grid(sticky ='w')
BEmail = Button(win,text="Email",font=('arial',18,'bold'),command =f1).grid()
win.mainloop() |
3bc103df43f3b4e607efa104b1e3a5a62caa1469 | LaurenShepheard/VsCode | /Learningpython.py | 1,227 | 4.375 | 4 | for i in range(2):
print("hello world")
# I just learnt how to comment by putting the hash key at the start of a line. Also if I put a backslash after a command you can put the command on the next line.
print\
("""This is a long code,
it spreads over multiple lines,
because of the triple quotaions and brackets""")
# A string is a sequence of one or more characters surrounded by quotes ' "", like above. It's data type is str.
print('This is a String but if you are using numbers the data type is int and called integer')
b = 100
print(b)
print(2+2)
# Numbers with a decimal are called a float and act like ints. True and false are bool data type called booleans.
print(2/2)
print("The number above is a constant as its value does not change whereas the b is a variable as I assigned it a value using the assignment operator =, doing this you can do math")
a = 50
y = a + b
print(y)
a = a + 1
# The above is an example of incrementing a variable, you can decrement it by using - as well. You can also skip putting the a like below.
a += 1
y = a + b
print(y)
print("Now the number changes because I incremented the variable.")
Nick = "A really cool guy who is probably a jedi but who really knows"
print(Nick)
|
2e58e78005d5cc25a79008d912c0691db06d92f8 | surajrnair007/Big-Data-Problems-and-Assignments | /A1Prob3aMapperV1.0.py | 1,569 | 4.03125 | 4 | """
This is a mapper program. It reads an input file which is in the format
Username<space>DNAseq.
The program considers the DNA seq as Key and Username as the Value. It sorts the
records on the DNA seq and then stores each record in the output file in the
format DNAseq<tab>Username
"""
# Open and read input file
inputFile = open("input_same_DNAseq.txt", "r")
inputRead = inputFile.read()
# Store each line in input line as an element of a list
tempList = inputRead.split("\n")
sortedList = list(tempList)
reverseList = list(tempList)
tempLen = len(tempList)
j = 0
# Store each group of User and DNA seq as an element of the 2D array
for i in range(0, tempLen):
sortedList[j] = tempList[i].split(" ")
j+=1
# In each element of the 2D array everse elements to store as 'DNA seq, User'
for i in range(0, tempLen):
sortedList[i][0], sortedList[i][1] = sortedList[i][1], sortedList[i][0]
# The below line of code sorts the elements in the list alphabetically
sortedList = sorted(sortedList)
# Open output file in write mode
outputFile = open("output_same_DNAseq.txt", "w")
for i in range(0, len(sortedList)):
# Store the string read from the list as the Value
keyStr = sortedList[i][0]
valueStr = sortedList[i][1]
# Write to output in Key<tab>Value format. Avoid \n on last entry
if i == (len(sortedList) - 1):
outRecord = keyStr + "\t" + valueStr
else:
outRecord = keyStr + "\t" + valueStr + "\n"
outputFile.write(outRecord)
outputFile.close()
|
cfa5d433e0390c4e199e9f2ad7fcdad9ad2c6191 | Matheus-Soares/AnalisadorSintatico | /symbol_table.py | 1,274 | 3.5 | 4 |
class SymbolTable:
def __init__(self):
self.table = {}
def add(self, name, cat, type, level, params=None):
self.table[str(name)] = {}
self.table[str(name)]["cat"] = cat
self.table[str(name)]["type"] = type
self.table[str(name)]["level"] = level
self.table[str(name)]["params"] = params
def search(self, name):
if name in self.table:
return True
else:
return False
def remove(self, name):
try:
del self.table[name]
except:
print("Erro deletando {}".format(name))
def remove_level(self, level):
to_delete = []
for name, attr in self.table.items():
if attr["level"] == level:
to_delete.append(name)
for name in to_delete:
del self.table[name]
def print(self):
return print(self.table)
def print_names(self):
l = ''
for name, attr in self.table.items():
l += str(print(name))
return l
if __name__ == "__main__":
a = SymbolTable()
a.add("var1", "v", 1)
a.add("var2", "f", 2)
a.add("var3", "f", 2)
a.add("var4", "f", 3)
a.add("var5", "f", 2)
a.remove_level(2)
a.print()
|
ffd58f656b6ba58dcde081c1545e4278c29a5ce6 | blankjul/dtree-python | /src/table.py | 5,387 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import csv
from tabulate import tabulate
from join import join_index
def gen(oReader):
for row in oReader:
yield row
def create_from_csv(p_strPath, p_strDelimiter=';', p_strQuotechar="|"):
with open(p_strPath, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=p_strDelimiter, quotechar=p_strQuotechar)
oTable = Table(reader.next(), gen(reader))
return oTable
"""
This is an Implementation of a column based Database
for processing Data with Python.
"""
class Table:
def __init__(self, p_lColumns, p_genData):
self.lColumns = p_lColumns
self.dData = {}
self.iCounter = 0
for strColumn in p_lColumns:
self.dData[strColumn] = []
for lRow in p_genData:
if len(lRow) != len(self.lColumns): continue
self.iCounter += 1
for i, entry in enumerate(lRow):
self.dData[self.lColumns[i]].append(entry)
self.dIndex = {}
def __getitem__(self, iIndex):
return self.get_row(iIndex)
def __iter__(self):
for i in range(0, self.count()):
yield self.get_row(i)
def get_columns(self):
return self.lColumns
def get_row(self, iIndex, lColumns=None):
row = []
for strColumn in self.lColumns:
if lColumns is not None and strColumn not in lColumns: continue
row.append(self.dData[strColumn][iIndex])
return tuple(row)
def count(self):
return self.iCounter
def add_column(self, p_strName, p_lData):
if self.iCounter == len(p_lData):
self.dData[p_strName] = p_lData
self.lColumns.append(p_strName)
return True
else:
return False
def get_column_index(self, p_strColumnName):
return self.lColumns.index(p_strColumnName)
def pretty_print(self):
print tabulate(self.dData, headers="keys", tablefmt="simple")
def get_index(self, p_lColumns, p_bCreateIfDoesNotExist=False):
if isinstance(p_lColumns, (list)): p_lColumns = tuple(p_lColumns)
elif not isinstance(p_lColumns, (tuple)): p_lColumns = (p_lColumns,)
if p_bCreateIfDoesNotExist and p_lColumns not in self.dIndex:
self.create_index(p_lColumns)
if p_lColumns in self.dIndex: return self.dIndex[p_lColumns]
else: return None
def create_index(self, p_lColumns):
if isinstance(p_lColumns, (list)): p_lColumns = tuple(p_lColumns)
elif not isinstance(p_lColumns, (tuple)): p_lColumns = (p_lColumns,)
h = {}
for i in range(0, self.count()):
entry = self.get_row(i, lColumns=p_lColumns)
if entry not in h: h[entry] = set()
h[entry].add(i)
self.dIndex[p_lColumns] = h
return h
def select(self, p_lConditions=[]):
# create a list of rows that are interesting
if p_lConditions is None or len(p_lConditions) == 0:
lDictRows = range(0, self.count())
elif len(p_lConditions) == 1:
key, value = p_lConditions[0]
dIndex = self.get_index(key, p_bCreateIfDoesNotExist=True)
lDictRows = dIndex[(value,)]
else:
lDictRows = []
for key, value in p_lConditions:
dIndex = self.get_index(key, p_bCreateIfDoesNotExist=True)
lDictRows.append(dIndex[(value,)])
lDictRows = join_index(lDictRows)
return lDictRows
def get_unique(self, p_strColumn, p_lConditions=[]):
if len(p_lConditions) == 0: lRows = range(0, self.count())
else: lRows = self.select(p_lConditions)
sResult = set()
for iRow in lRows:
entry = self.get_row(iRow, lColumns=p_strColumn)
sResult.add(entry[0])
return sResult
def get_freq_table(self, p_strColumn, p_lConditions=[]):
result = {}
# get all rows that are fitting to all the conditions
dIndex = self.get_index(p_strColumn, p_bCreateIfDoesNotExist=True)
# if there are no conditions we are faster
if p_lConditions is None or len(p_lConditions) == 0:
for entry in dIndex: result[entry] = len(dIndex[entry])
# create a selection and look for the conditions while counting
else:
lHashes = self.select(p_lConditions)
for entry in dIndex:
joined_hashes = join_index([dIndex[entry], lHashes])
if len(joined_hashes) > 0: result[entry] = len(joined_hashes)
return result
def get_cross_table(self, p_strFirstColumn, p_strSecondColumn, p_lConditions=[], p_bReturnRowIndex=False):
if len(p_lConditions) == 0: lRows = range(0, self.count())
else: lRows = self.select(p_lConditions)
dResult = {}
for iRow in lRows:
lEntry = self.get_row(iRow, [p_strFirstColumn,p_strSecondColumn])
if lEntry[0] not in dResult: dResult[lEntry[0]] = {}
if lEntry[1] not in dResult[lEntry[0]]:
dResult[lEntry[0]][lEntry[1]] = 1
else:
dResult[lEntry[0]][lEntry[1]] += 1
if p_bReturnRowIndex: return dResult, lRows
return dResult
|
1b55bfe95d0ee6f87aa7325851c6fa954b18e41b | sebschneid/adventofcode2019 | /day04/solution2.py | 901 | 3.609375 | 4 | import time
import collections
import numpy as np
puzzle_input_string = "356261-846303"
puzzle_input = (356261, 846303)
time1 = time.time()
count_passwords = 0
for number in range(*puzzle_input):
number_string = str(number)
digits = [digit for digit in number_string]
ascending_order = sorted(digits) == digits
# numpy variant: 16s
# unique, counts = np.unique(digits, return_counts=True)
# adjacent_match_outside_larger_group = any(counts == 2)
# colletions.Counter variant: 3s
counts = collections.Counter(digits)
adjacent_match_outside_larger_group = (
len([count for count in counts.values() if count == 2]) > 0
)
if ascending_order and adjacent_match_outside_larger_group:
count_passwords += 1
time2 = time.time()
print(f"Took {time2-time1} seconds")
print(f"There are {count_passwords} possible passwords in the input range!")
|
db52c61919c832c7e0afe321049fa77a7e4b2fe6 | R-Stefano/AI-assignment2 | /AStar.py | 2,249 | 3.953125 | 4 | import queue as q
from collections import namedtuple
max_iterations=1000000
def search(start):
"""
Performs A* search starting with the initialized puzzle board.
Returns a namedtuple 'Success' which contains namedtuple 'position'
(includes: node, cost, depth, prev), 'max_depth' and 'nodes_expanded'
if a node that passes the goal test has been found.
"""
'''
Create a class named nodeClass which contains 4 elements:
state: The puzzle object containing the puzzle board at the node
misplaced: num of misplaced tiles
depth: depth of the node in the tree
prev: parent node
'''
nodeClass = namedtuple('nodeClass', 'state, misplaced, depth, prev')
#instantiate object from class creating the root node
node = nodeClass(start, 0, 0, None)
#stores the nodes that are going to be explored.
#the node with lower f-score is explored first
frontier = q.PriorityQueue()
frontier.put((0,node))
# frontier_set keep track of the nodes in the frontier queue
frontier_set = {node}
#contains the board states already explored
explored_states = set()
for ite in range(1,max_iterations+2):#while True:
#Retrieve the node in the frontier with lowest value
node = frontier.get()[1]
#get the puzzle board obj from the node object
state = node.state
#Check if the game has ben solved
if state.solved or ite==max_iterations:
Result = namedtuple('Result', 'board, depth, nodesExpanded, max_depth, isSolved')
return Result(state, node.depth, ite, max(no.depth for no in frontier_set), state.solved)
# expanded nodes are added to explored set
explored_states.add(state)
#EXPANDING
for mov in state.possible_moves:
new_state=state.move(mov)
new_node = nodeClass(new_state, new_state.score,
node.depth + 1, node)
#compute f-score of the node
f_score=new_state.score + new_node.depth
if new_state not in explored_states and new_node not in frontier_set:
frontier.put((f_score,new_node))
frontier_set.add(new_node) |
35fa5c44e533394b62100fa936bc063b3b7e863e | mberrett/Hadoop | /Weather_Forecast/mapWD.py | 669 | 3.671875 | 4 | #!/usr/bin/env python
import sys
# input comes from STDIN (standard input)
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# split the line into words
words = line.split()
# increase counters
for word in words:
# write the results to STDOUT (standard output);
# what we output here will be the input for the
# Reduce step, i.e. the input for reducer.py
# each words is a row of a tab delimited table
day = words[1] # 2nd column value
tmax = words[5] # 6th column value
tmin = words[6] # 7th column value
print('%s\t%s\t%s' % (day, tmin, tmax))
|
20b609e21199215965d79601920124905c16ef2d | katesem/data-structures | /hash_table.py | 884 | 4.25 | 4 | '''
In Python, the Dictionary data types represent the implementation of hash tables. The Keys in the dictionary satisfy the following requirements.
The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique result for each unique value supplied to the hash function.
The order of data elements in a dictionary is not fixed.
So we see the implementation of hash table by using the dictionary data types
'''
# accessing data with keys in hash table :
hash_table = {1 :'one', 2 : 'two', 3 : 'three', 4 : 'four'}
hash_table[1] # -> one
hash_table[4] # -> four
#adding items:
hash_table[5] = 'five'
# updating dictionary:
hash_table[4] = 'FOUR'
print(hash_table)
#deleting items:
del hash_table[1] # remove entry with key 'Name'
hash_table.clear(); # remove all entries in dict
del hash_table ; # delete entire dictionary
|
763602e75ebb5e21a69239e2f9c095b1d752ed45 | avgn/6.00.2x | /noReplacement.py | 804 | 3.921875 | 4 | import random
def drawBalls():
bucket = [0, 0, 0, 1, 1, 1]
d1 = random.choice(bucket)
bucket.pop(d1)
d2 = random.choice(bucket)
bucket.pop(d1)
d3 = random.choice(bucket)
bucket.pop(d3)
if d1 + d2 + d3 == 0 or d1 + d2 + d3 == 3:
return True
else:
return False
def noReplacementSimulation(numTrials):
'''
Runs numTrials trials of a Monte Carlo simulation
of drawing 3 balls out of a bucket containing
3 red and 3 green balls. Balls are not replaced once
drawn. Returns the a decimal - the fraction of times 3
balls of the same color were drawn.
'''
sameColor = 0
for n in range(numTrials):
if drawBalls():
sameColor += 1
return sameColor/float(numTrials)
print noReplacementSimulation(5000) |
d3f5eee43bc21a6cf6517675db139478eb563386 | bbisher/Card-Game | /Deck.py | 1,226 | 3.6875 | 4 | from Card import Card
import random
class Deck(object):
def __init__(self):
cards_in_deck = 52
self.deck_of_cards = []
index = 0
while index < cards_in_deck:
card_number = index % 13
suit_number = int(index / 13)
new_card = Card()
new_card.number = card_number
new_card.suit = suit_number
new_card.name = self.setPlayingCardName(card_number, suit_number)
self.deck_of_cards.append(new_card)
index += 1
def get_deck(self):
return self.deck_of_cards
def shuffle(self):
return random.shuffle(self.deck_of_cards)
def burnCard(self):
self.deck_of_cards.pop(0)
return self.deck_of_cards
def deal(self):
card = self.deck_of_cards[0]
self.deck_of_cards.pop(0)
return card
def setPlayingCardName(self, card_number, suit_number):
name = None
if(card_number == 0):
name = "Ace of "
elif(card_number == 10):
name = "Jack of "
elif(card_number == 11):
name = "Queen of "
elif(card_number == 12):
name = "King of "
else:
name = str(card_number + 1) +" of "
if(suit_number == 0):
name += "Clubs"
elif(suit_number == 1):
name += "Diamonds"
elif(suit_number == 2):
name += "Hearts"
elif(suit_number == 3):
name += "Spades"
return name
|
17ca710d855a20c14af708f45da79d42017ff129 | renandantas/DeepLearning | /Cancer de mama/Cancer_Mama_simples.py | 4,304 | 3.625 | 4 | import pandas as pd
# Classe utilizada para a criação da rede neural
import keras
from keras.models import Sequential
# Classe para se utilizar camadas densas na rede neural
# ou seja, cada um dos neuronios é ligado com todos os neuronios da camada subsequente
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score
previsores = pd.read_csv('entradas-breast.csv')
classe = pd.read_csv('saidas-breast.csv')
previsores_treinamento, previsores_teste, classe_treinamento, classe_teste = train_test_split(previsores, classe,
test_size=0.25)
# Senquential() é o metodo que cria a rede neural
classificador = Sequential()
# contrução da primeira camada oculta e da camada de entrada
# units -> 16 neuronios na primeira camada oculta
# activation -> função de ativação
# kernel_initializer ->
# input_dim -> camada de entrada -> usado somente na primeira camada oculta
classificador.add(Dense(units=16, activation='relu',
kernel_initializer='random_uniform', input_dim=30))
#criando a segunda camada oculta
classificador.add(Dense(units=16, activation='relu',
kernel_initializer='random_uniform'))
# contrução da camada de saida
classificador.add(Dense(units=1, activation='sigmoid'))
# metodo compile faz a configuração do modelo para o treinamento
# Optimizer ->coloca qual a função vai ser utilizada para fazer o ajuste dos pesos (decida do gradiente)
# Loss -> é a função de perda, onde se faz o tratamento ou o calculo do erro
# metrics -> é a metrica que vai ser usada para a fazer a avaliação do erro
#classificador.compile(optimizer='adam', loss='binary_crossentropy',
# metrics=['binary_accuracy'])
# Configurações dos parametros de otimização
# learn rate (lr) -> quanto menor melhor, mas gasta mais tempo para realizar os calculos
# decay -> indica quanto o learn rate vai ser decrementado a cada atuaização de pesos
# começa com um learn rate alto e vai diminuindo o valor do learn rate aos poucos
# clipvalue -> vai prender o valor, os pesos ficam em uma determinada faixa de valor -> ex: 0.5 e -0.5
otimizador = keras.optimizers.Adam(lr = 0.001, decay=0.0001, clipvalue = 0.5)
classificador.compile(optimizer=otimizador, loss='binary_crossentropy',
metrics=['binary_accuracy'])
# Realiza o treinamento - encontra a relação dos previsores com a classe
# batch_size -> calcula o erro para x registro e dps faz o reajuste dos pesos
# epochs -> quantas vezes que vão ser feitas os ajuste dos pesos
classificador.fit(previsores_treinamento, classe_treinamento,
batch_size=10, epochs=100)
# Mostra os pesos que a rede neural encontrou para as ligações da camada de entrada para a primeira camada oculta
pesos0 = classificador.layers[0].get_weights()
# Mostra os pesos que a rede neural encontrou para as ligações da primeira camada oculta para a segunda camada oculta
pesos1 = classificador.layers[1].get_weights()
# Mostra os pesos que a rede neural encontrou para as ligações da segunda camada oculta para a camada de saída
pesos2 = classificador.layers[2].get_weights()
# Passa o registro do previsores_teste para o rna e a rna vai fazer o calculo dos pesos e aplicação da função de ativivação
# e vai retornar um valor de probabilidade
previsoes = classificador.predict(previsores_teste)
# Transforma a variavel previsoes em valores verdadeiro ou falso (sem cancer ou com cancer)
previsoes = (previsoes > 0.5)
# Compara o acerto entre a classe_teste (base de dados com resultados certos) e previsoes (base que foi gerada automaticamente pelo codigo)
# Retorna uma porcentagem de acerto -----> Utilizando sklearn
precisao = accuracy_score(classe_teste, previsoes)
# Cria uma matriz onde é possivel ter uma boa visualização em qual classe temos mais erro -----> Utilizando sklearn
# Original na horizontal e classificados automaticamente na vertical
matriz = confusion_matrix(classe_teste, previsoes)
# Retorna o valor de erro e o valor da precisao ---> utilizando o Keras
resultado = classificador.evaluate(previsores_teste, classe_teste)
|
5af68810c604e1eb30e057ec69a6b338c1e053fe | renandantas/DeepLearning | /Redes_Neurais_Convolucionais/Digitos/Classificação_digitos.py | 4,448 | 3.546875 | 4 | # Usada para visualizar as imagens que esto na base de dados
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.models import Sequential
# Flatten -> Transforma uma matriz em um vetor
# Conv2D -> Camada de convoluo
# MaxPooling2d -> Serve para infatizar as caracteristicas ou dos obejetos para a classificao
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout
# Utilizado para fazer o mapeamento das variaveis dummy -> necessario fazer uma transformao nesses dados pois temos 10 classes
from keras.utils import np_utils
# realiza a normalizao na camada de convolues
from keras.layers.normalization import BatchNormalization
# X - para atributos previsores
# y - para as classes
# Baixa as imagens para e separa o treinamento e o teste
(X_treinamento, y_treinamento), (X_teste, y_teste) = mnist.load_data()
# Visualiza as imagens e coloca escala de cinza - tira a cor da imagem
plt.imshow(X_treinamento[1], cmap = "gray")
plt.title("Classe " + str(y_treinamento[1]))
# Transforma os dados para o TensorFlow fazer a leitura - muda o formato da imagem
previsores_treinamento = X_treinamento.reshape(X_treinamento.shape[0], 28, 28, 1)
previsores_teste = X_teste.reshape(X_teste.shape[0], 28, 28, 1)
# Variaveis precisam ser float32
previsores_treinamento = previsores_treinamento.astype("float32")
previsores_teste = previsores_teste.astype("float32")
# Mudando a escala de valores, melhora o processamento, colocando os valores em uma escala de 0 at 1
# min_max_normalization -> transforma os valores em uma escala menor que favilita o processamento
# realiza uma normalizao dos dados
previsores_treinamento /= 255
previsores_teste /= 255
# Cria as variaveis dummy - necessrio pois a classificao so de mais de duas classes
classe_treinamento = np_utils.to_categorical(y_treinamento, 10)
classe_teste = np_utils.to_categorical(y_teste, 10)
# Cria o classificador
classificador = Sequential()
# Camada 1 - Define o operador de convoluo - gera uma mapa de caracteristicas
# 32 -> numero de kernels -> realiza alguns testes na imagem com "filtros"
# 3,3 -> tamanho do kernel, significa o tamanho do detector de caracteristicas - vai de acordo com o tamanho da imagem
# input_shape -> tamanho da imagem e quantidade de canais
# activation -> funo de ativao
classificador.add(Conv2D(32, (3,3), input_shape = (28, 28, 1), activation = "relu"))
# Realiza a normalizao na camada de convoluo
classificador.add(BatchNormalization())
# Camada 2 - Pooling
# pool_size -> tamanho da matriz ou da janela que vai selecionar as partes com maior valor no mapa de caracteristicas
classificador.add(MaxPooling2D(pool_size = (2,2)))
# Camada 3 - Flattening - transforma a matriz em formato de vetor para passarmos os valores para a rede neural densa
# Quando usamos o BacthNormalization o Flattening s vai ser usado na ultima camada de convoluo
#classificador.add(Flatten())
# Camada 4 - mais uma camda de concoluo
classificador.add(Conv2D(32, (3,3), activation = "relu"))
# Realiza a normalizao na camada de convoluo
classificador.add(BatchNormalization())
# Camada 5 - Pooling
# pool_size -> tamanho da matriz ou da janela que vai selecionar as partes com maior valor no mapa de caracteristicas
classificador.add(MaxPooling2D(pool_size = (2,2)))
# Camada 6 - Flattening - transforma a matriz em formato de vetor para passarmos os valores para a rede neural densa
classificador.add(Flatten())
# comea a criar a rede neural densa normalmente
# Camada 7 - Primeira camada oculta
classificador.add(Dense(units = 128, activation = "relu"))
# Dropout -> Zera 20% das entradas - pois existem muitos neuronios na camada
classificador.add(Dropout(0.2))
# Camada 8 - Segunda camada oculta
classificador.add(Dense(units = 128, activation = "relu"))
# Dropout -> Zera 20% das entradas - pois existem muitos neuronios na camada
classificador.add(Dropout(0.2))
# Camada 5 - Camada de saída
classificador.add(Dense(units = 10, activation = "softmax"))
# Realiza a compilao da rede neural
classificador.compile(loss = "categorical_crossentropy", optimizer = "adam", metrics = ["accuracy"])
# Realiza o treinamento
classificador.fit(previsores_treinamento, classe_treinamento, batch_size = 128, epochs = 5, validation_data = (previsores_teste, classe_teste))
resultado = classificador.evaluate(previsores_teste, classe_teste) |
411d1767e1b719d938b7ded2689e34f03d478bcc | wukunzan/algorithm004-05 | /Week 1/id_040/LeetCode_206_040.py | 1,005 | 4 | 4 | # 反转一个单链表。
#
# 示例:
#
# 输入: 1->2->3->4->5->NULL
# 输出: 5->4->3->2->1->NULL
#
# 进阶:
# 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
# Related Topics 链表
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
n = head
prev = None
while n:
n.next, prev, n = prev, n, n.next
return prev
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
n1 = ListNode(x=1)
n2 = ListNode(x=2)
n3 = ListNode(x=3)
n4 = ListNode(x=4)
n5 = ListNode(x=5)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
s = Solution()
r = s.reverseList(head=n1)
n = r
while n:
print(n.val)
n = n.next
|
848c6739f82cec9613049717dc5a143486752f71 | gminafuzz/barry | /dict_people.py | 1,099 | 4.03125 | 4 | people = {}
print ('Welcome to base of person!')
log = input('You want to add new person or watch base? (a/w):')
if log == 'a':
while True:
lastname = input('Input lastname of new person:')
firstname = input('Input firstname of new person:')
gender = input('Input gender of new person:')
occupation = input('Input occupation of new person:')
home = input('Input name of home planet this person ')
name = ('{} {}'.format(firstname, lastname))
people[lastname] = {'Name': name, 'Gender': gender, 'Occupation': occupation, 'Home planet': home}
rec = input('Add another person? (y/n):')
if rec == 'n':
rec2 = input('You want waches base of person? (y/n):')
if rec2 == 'y':
for key, data in people.items():
print ('-------------------------')
for key, detail in data.items():
print (key, '______', detail)
break
else:
break
else: continue
else:
print ('Goodbey')
|
fb20e9c8addc53b946081f1fceabcd719e85fa4b | jacarvalho/SimuRLacra | /Pyrado/pyrado/plotting/categorial.py | 6,379 | 3.625 | 4 | import numpy as np
from matplotlib import pyplot as plt
from typing import Sequence
def render_boxplot(
ax: plt.Axes,
data: [Sequence[list], Sequence[np.ndarray]],
x_labels: Sequence[str],
y_label: str,
vline_level: float = None,
vline_label: str = 'approx. solved',
alpha: float = 1.,
colorize: bool = False,
show_fliers: bool = False,
show_legend: bool = True,
legend_loc: str = 'best',
title: str = None,
) -> plt.Figure:
"""
Create a box plot for a list of data arrays. Every entry results in one column of the box plot.
The plot is neither shown nor saved.
.. note::
If you want to have a tight layout, it is best to pass axes of a figure with `tight_layout=True` or
`constrained_layout=True`.
:param ax: axis of the figure to plot on
:param data: list of data sets to plot as separate boxes
:param x_labels: labels for the categories on the x-axis
:param y_label: label for the y-axis
:param vline_level: if not `None` (default) add a vertical line at the given level
:param vline_label: label for the vertical line
:param alpha: transparency (alpha-value) for boxes (including the border lines)
:param colorize: colorize the core of the boxes
:param show_fliers: show outliers (more the 1.5 of the inter quartial range) as circles
:param show_legend: flag if the legend entry should be printed, set to True when using multiple subplots
:param legend_loc: location of the legend, ignored if `show_legend = False`
:param title: title displayed above the figure, set to None to suppress the title
:return: handle to the resulting figure
"""
medianprops = dict(linewidth=1., color='firebrick')
meanprops = dict(marker='D', markeredgecolor='black', markerfacecolor='purple')
boxprops = dict(linewidth=1.)
whiskerprops = dict(linewidth=1.)
capprops = dict(linewidth=1.)
# Plot the data
box = ax.boxplot(
data,
boxprops=boxprops, whiskerprops=whiskerprops, capprops=capprops,
meanprops=meanprops, meanline=False, showmeans=False,
medianprops=medianprops,
showfliers=show_fliers,
notch=False,
patch_artist=colorize, # necessary to colorize the boxes
labels=x_labels, widths=0.7
)
if colorize:
for i, patch in enumerate(box['boxes']):
patch.set_facecolorf(f'C{i%10}')
patch.set_alpha(alpha)
# Add dashed line to mark the approx solved threshold
if vline_level is not None:
ax.axhline(vline_level, c='k', ls='--', lw=1., label=vline_label)
ax.set_ylabel(y_label)
if show_legend:
ax.legend(loc=legend_loc)
if title is not None:
ax.set_title(title)
return plt.gcf()
def render_violinplot(
ax: plt.Axes,
data: [Sequence[list], Sequence[np.ndarray]],
x_labels: Sequence[str],
y_label: str,
vline_level: float = None,
vline_label: str = 'approx. solved',
alpha: float = 0.7,
show_inner_quartiles: bool = False,
show_legend: bool = True,
legend_loc: str = 'best',
title: str = None,
use_seaborn: bool = False,
) -> plt.Figure:
"""
Create a violin plot for a list of data arrays. Every entry results in one column of the violin plot.
The plot is neither shown nor saved.
.. note::
If you want to have a tight layout, it is best to pass axes of a figure with `tight_layout=True` or
`constrained_layout=True`.
:param ax: axis of the figure to plot on
:param data: list of data sets to plot as separate violins
:param x_labels: labels for the categories on the x-axis
:param y_label: label for the y-axis
:param vline_level: if not `None` (default) add a vertical line at the given level
:param vline_label: label for the vertical line
:param alpha: transparency (alpha-value) for violin body (including the border lines)
:param show_inner_quartiles: display the 1st and 3rd quartile with a thick line
:param show_legend: flag if the legend entry should be printed, set to `True` when using multiple subplots
:param legend_loc: location of the legend, ignored if `show_legend = False`
:param title: title displayed above the figure, set to None to suppress the title
:return: handle to the resulting figure
"""
if use_seaborn:
# Plot the data
import seaborn as sns
import pandas as pd
df = pd.DataFrame(data, x_labels).T
ax = sns.violinplot(data=df, scale='count', inner='stick', bw=0.3, cut=0) # cut controls the max7min values
medians = np.zeros(len(data))
for i in range(len(data)):
medians[i] = np.median(data[i])
x_grid = np.arange(0, len(medians))
ax.scatter(x_grid, medians, marker='o', s=50, zorder=3, color='white', edgecolors='black')
else:
# Plot the data
violin = ax.violinplot(data, showmeans=False, showmedians=False, showextrema=False)
# Set custom color scheme
for pc in violin['bodies']:
pc.set_facecolor('#b11226')
pc.set_edgecolor('black')
pc.set_alpha(alpha)
# Set axis style
ax.set_xticks(np.arange(1, len(x_labels) + 1))
ax.set_xticklabels(x_labels)
quartiles_up, medians, quartiles_lo = np.zeros(len(data)), np.zeros(len(data)), np.zeros(len(data))
data_mins, data_maxs = np.zeros(len(data)), np.zeros(len(data))
for i in range(len(data)):
quartiles_up[i], medians[i], quartiles_lo[i] = np.percentile(data[i], [25, 50, 75])
data_mins[i], data_maxs[i] = min(data[i]), max(data[i])
x_grid = np.arange(1, len(medians) + 1)
ax.scatter(x_grid, medians, marker='o', s=50, zorder=3, color='white', edgecolors='black')
ax.vlines(x_grid, data_mins, data_maxs, color='k', linestyle='-', lw=1, alpha=alpha)
if show_inner_quartiles:
ax.vlines(x_grid, quartiles_up, quartiles_lo, color='k', linestyle='-', lw=5)
# Add dashed line to mark the approx solved threshold
if vline_level is not None:
ax.axhline(vline_level, c='k', ls='--', lw=1.0, label=vline_label)
ax.set_ylabel(y_label)
if show_legend:
ax.legend(loc=legend_loc)
if title is not None:
ax.set_title(title)
return plt.gcf()
|
94f1995d73d9e2a22d3a966619e2b51ed0228e5f | jacarvalho/SimuRLacra | /Pyrado/pyrado/utils/__init__.py | 589 | 3.796875 | 4 | def get_class_name(obj) -> str:
"""
Get an arbitrary objects name.
:param obj: any object
:return: name of the class of the given object
"""
return obj.__class__.__name__
def issequence(obj) -> bool:
"""
Check if an object is a sequence / an iterable.
.. note::
Using against `isinstance(obj, collections.Sequence)` yields `False` for some types like `set` and `dict`.
:param obj: any object
:return: flag if the object is a sequence / an iterable
"""
return hasattr(type(obj), '__iter__') and hasattr(type(obj), '__len__')
|
b4c610c520aa24f910cc16165dac7efa82b9cde1 | dongul11/lpthw | /ex13.py | 380 | 3.875 | 4 | from sys import argv
# read the WYSS section for how to run this
script, first, second, third = argv
print ("The script is called:", script)
print ("Your first variable is:", first)
print ("Your second variable is:", second)
print ("Your third variable is:", third)
a = input("Input a #:")
b = input("Input another one:")
result = a + b
print(f"And {a} + {b} equals {result}")
|
77f8af91c65850e861023b9209a3b610464a9dec | h-parker/commencement-speech-generator | /front-end/user_interface.py | 2,131 | 3.578125 | 4 | import streamlit as st
import pandas as pd
import numpy as np
import project_functions
def main():
# Render the readme as markdown using st.markdown.
with open('opening.md', 'r') as f:
opening = f.read()
readme_text = st.markdown(opening)
# add a selector for the app mode on the sidebar.
st.sidebar.title("What would you like to do?")
app_mode = st.sidebar.selectbox("Choose what you'd like to do:",
['Read about this project', "Generate text - Markov Model",
"Classify the type of speaker", "Evaluate text"])
if app_mode == "Read about this project":
st.sidebar.success("""To explore this project, select any
option in the dropdown menu.""")
elif app_mode == "Generate text - Markov Model":
readme_text.empty()
with st.spinner('Getting a new speech ready...'):
markov_text_label = """How many sentences would you like to generate?"""
text = st.text_input(markov_text_label, value=int('3'))
generated = project_functions.run_markov(int(text))
st.success('Got it!')
st.write(generated)
elif app_mode == "Classify the type of speaker":
with st.spinner('Getting your prediction...'):
readme_text.empty()
classify_text_label = """Enter the speech you'd like to classify the speaker-type of."""
text = st.text_area(classify_text_label, value="""I am the president of the United States.""")
prediction = project_functions.run_predict(text)[0]
# 'business person' reads better, event thought "business" was the label.
if prediction == 'business':
prediction = 'business person'
print(prediction)
st.success('Got the prediction!')
st.write('The speaker seems like a(n)', prediction, '.')
elif app_mode == "Evaluate text":
readme_text.empty()
with st.spinner('Evaluating the text...'):
eval_text_label = "Enter the text you want to evaluate."
text = st.text_area(eval_text_label, value="""These sentences are correct. They have a score of 1.""")
# generated = project_functions.run_markov()
score = project_functions.grammar_score(text)
st.success('Got it!')
st.write('The score is:', score)
if __name__ == "__main__":
main() |
a5210445c8d2dd014113e44862152a0215244112 | jokeewu/python-crash-course | /chapter_04/list_slice.py | 168 | 4.03125 | 4 | # coding=utf-8
# 列表切片
chars = ['a', 'b', 'c', 'd']
print(chars[1:3])
print(chars[-1:])
print(chars[:2])
# 列表复制
new_chars = chars[:]
print(new_chars) |
2337b4d4ebe4eefe8c3fd6b59ed42d67aeccc457 | jokeewu/python-crash-course | /chapter_11/test_name_function.py | 424 | 3.578125 | 4 | import unittest
from name_function import get_formatted_name
class NameTestCase(unittest.TestCase):
def test_first_last_name(self):
formatted_name = get_formatted_name('Jacky', 'Wu')
self.assertEqual(formatted_name, 'Jacky Wu')
def test_first_last_middle_name(self):
formatted_name = get_formatted_name('Jacky', 'Wu', 'X')
self.assertEqual(formatted_name, 'Jacky X Wu')
unittest.main() |
de0a468c4cddc565aaa8bf8c9e166f60d65a6b51 | jokeewu/python-crash-course | /chapter_03/list_reverse.py | 129 | 3.65625 | 4 | # coding=utf-8
# 列表反转
chars = ["a", "b", "c"]
chars.reverse() # 影响原列表
print(chars)
chars.reverse()
print(chars) |
40f0446fc1edc6915ce6081cdd00285c4d930c6c | mshalvagal/cmc_epfl2018 | /Lab7/Webots/controllers/mouse/musculoskeletal/MuscleJoint.py | 2,664 | 3.734375 | 4 | """ MuscleJoint class """
import numpy as np
class MuscleJoint(object):
"""This class provides the interface between Muscles and Joints."""
def __init__(self, muscle, joint, parameters):
""" Class initialization."""
self.muscle = muscle
self.joint = joint
self.theta_max = np.deg2rad(parameters.theta_max)
self.theta_ref = np.deg2rad(parameters.theta_ref)
self.r_0 = parameters.r_0
if parameters.direction == 'cclockwise':
self.direction = 1.
elif parameters.direction == 'clockwise':
self.direction = -1.
def getDelta_Length(self):
"""Function returns the change in length of the muscle"""
return self.direction * self.r_0 * self.angleTF(self.joint.joint_type,
self.joint.getAngle())
def computeTorque(self):
"""Function computes the torque generated by
the muscle on the joint."""
moment_arm = self.angleTFPrime(
self.joint.joint_type, self.joint.getAngle())
torque = self.r_0 * self.muscle.tendonForce * moment_arm \
* self.direction
return torque
def addTorqueToJoint(self):
"""Function adds torque to the respective joint."""
self.joint.AddForce(self.computeTorque())
def angleTFPrime(self, joint_type, angle):
"""Function computes the moment_arm.
Parameters
----------
self: type
description
joint_type: GEYER/CONSTANT
Type of joint moment arm and muscle length computation
angle: float
Joint angle
"""
if (joint_type == 'CONSTANT'):
return 1.0
elif(joint_type == 'GEYER'):
return np.cos(angle - self.theta_max)
def angleTF(self, joint_type, angle):
"""Function computes the delta length.
Parameters
----------
self: type
description
joint_type: GEYER/CONSTANT
Type of joint moment arm and muscle length computation
angle: float
Joint angle
"""
if (joint_type == 'CONSTANT'):
return self.theta_ref - angle
elif (joint_type == 'GEYER'):
return np.sin(self.theta_max - angle) - np.sin(
self.theta_ref - self.theta_max)
else:
alpha = np.cos(self.theta_max)
return (
np.sqrt(-2.0 * alpha * np.cos(angle) + alpha**2 + 1)
- np.sqrt(
-2.0 * alpha * np.cos(
self.theta_ref) + alpha**2 + 1)) / alpha
|
02aa151e60891f3c43b27a1091a35e4d75fe5f7d | mshalvagal/cmc_epfl2018 | /Lab0/Python/1_Import.py | 1,610 | 4.375 | 4 | """This script introduces you to the useage of Imports in Python.
One of the most powerful tool of any programming langauge is to be able to resuse code.
Python allows this by setting up modules. One can import existing libraries using the import function."""
### IMPORTS ###
from __future__ import print_function # Only necessary in Python 2
import biolog
biolog.info(3*'\t' + 20*'#' + 'IMPORTS' + 20*'#' + 3*'\n')
# A generic import of a default module named math
import math
# Now you have access to all the functionality availble
# in the math module to be used in this function
print('Square root of 25 computed from math module : {}'.format(math.sqrt(25)))
# To import a specific function from a module
from math import sqrt
# Now you can avoid referencing that the sqrt function is from
# math module and directly use it.
print('Square root of 25 computed from math module by importing only sqrt function: ', sqrt(25))
# Import a user defined module
# Here we import biolog : Module developed to display log messages for the exercise
biolog.info('Module developed to display log messages for the exercies')
biolog.warning("When you explicitly import functions from modules, it can lead to naming errors!!!""")
# Importing multiple functions from the same module
from math import sqrt, cos
# Defining an alias :
# Often having to reuse the actual name of module can be a pain.
# We can assign aliases to module names to avoid this problem
import datetime as dt
biolog.info("Here we import the module datetime as dt.")
# Getting to know the methods availble in a module
biolog.info(dir(math))
|
03e488f5f0e683bb9f73e56dcf2f53e014f9409e | kibitzing/FluentPython | /archive/To01-25/01-22/keunhoi_01-22.py | 1,355 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# p605-609
# Example 19-17~21
"""
예제 위주로 작성
객체 속성과 클래스 속성
property의 고전적인 구문
"""
# Example 19-17
class LineItem1:
""" property를 사용한 예제
"""
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
@property
def weight(self):
return self.__weight
@weight.setter
def weight(self, value):
if value > 0:
self.__weight = value
else:
raise ValueError('weight value must be > 0')
# Example 19-18
class LineItem2:
""" 고전적인 구문
"""
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
def get_weight(self):
return self.__weight
def set_weight(self, value):
if value > 0:
self.__weight = value
else:
raise ValueError('weight value must be > 0')
weight = property(get_weight, set_weight)
# Example 19-19~21
# 객체 속성과 클래스 속성 차이
# if __name__ == "__main__": |
1f4c6caff70e9824ab454861d22e5aef971a51d1 | kibitzing/FluentPython | /archive/To11-12/11-14/seongbin_11_14.py | 706 | 3.75 | 4 | class Foo:
def __getitem__(self,pos):
return range(0, 30, 10)[pos]
f = Foo()
for i in f: print(i)
print(20 in f)
print(15 in f)
import collections
Card = collections.namedtuple('Card',['rank','suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2,11)]+list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank,suit) for suit in self.suits
for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]
temp = FrenchDeck()
print(len(temp))
for i in range(len(temp)): print(temp[i])
|
e1c6a2d3ef66d6a96b2533c27df808d42c82e95f | kibitzing/FluentPython | /archive/To01-25/01-22/jiyun_01-22.py | 2,939 | 3.765625 | 4 | class LineItem1:
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
# >>> raisins = LineItem('Golden raisins', 10, 6.95)
# >>> raisins.subtotal()
# 69.5
# >>> raisins.weight = -12
# >>> raisins.subtotal()
# -83.4
class LineItem2:
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
@property
def weight(self):
return self.__weight # 비공개 속성인 __weight에 저장
@weight.setter
def weight(self, value):
if value > 0:
self.__weight = value
else:
raise ValueError('음수는 안돼요') # 보호 장치
# >>> raisins.weight = -20
# Traceback (most recent call last):
# File "<input>", line 1, in <module>
# File "<input>", line 20, in weight
# ValueError: 음수는 안돼요
class LineItem3:
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
def get_weight(self): # 게터
return self.__weight
def set_weight(self, value): # 세터
if value > 0:
self.__weight = value
else:
raise ValueError('음수는 안돼요')
weight = property(get_weight, set_weight)
# property 객체 생성 후 클래스의 공개 속성에 할당
class Class:
data = 'the class data attr'
@property
def prop(self):
return 'the prop value'
# >>> obj = Class()
# >>> vars(obj)
# {}
# >>> obj.data
# 'the class data attr'
# >>> obj.data = 'bar' # 객체 속성 생성됨
# >>> vars(obj) # 객체 속성 생성 확인
# {'data': 'bar'}
# >>> obj.data
# 'bar' # 객체 속성의 값을 가져옴
# >>> Class.data
# 'the class data attr' # Class.data 속성은 그대로
# >>> Class.prop
# <property object at 0x000001F49540CD18> # 프로퍼티 객체 자체를 가져옴
# >>> obj.prop
# 'the prop value'
# >>> obj.prop = 'foo'
# Traceback (most recent call last): # 객체의 prop 속성에 값 할당할 수 없음
# File "<input>", line 1, in <module>
# AttributeError: can't set attribute
# >>> obj.__dict__['prop'] = 'foo' # __dict__에 직접 할당은 가능
# >>> vars(obj)
# {'prop': 'foo', 'data': 'bar'}
# >>> obj.prop
# 'the prop value'
# >>> Class.prop = 'baz' # 덮어쓰면 프로퍼티 객체 사라짐
# >>> obj.prop
# 'foo'
|
cac76b7094108398b256e29e9022ccfca3b062a4 | kibitzing/FluentPython | /archive/To01-25/01-23/jingu_01-23.py | 1,172 | 3.703125 | 4 | # Created by Jingu Kang on 01-23
# reference: Fluent Python by Luciano Ramalho
# learned how to add docs to property, use vars, set getter and setter in a different way.
class Foo:
@property
def bar(self):
'''The bar attribute'''
return self.__dict__['bar']
@bar.setter
def bar(self, value):
self.__dict__['bar'] = value
def quantity(storage_name):
def qty_getter(instance):
return instance.__dict__[storage_name]
def qty_setter(instance, value):
if value > 0 :
instance.__dict__[storage_name] = value
else:
raise ValueError('value must be > 0')
return property(qty_getter, qty_setter)
class LineItem:
weight = quantity('weight')
price = quantity('price')
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
nutmeg = LineItem('Moluccan nutmag', 8 , 13.4)
print(nutmeg.weight)
print(nutmeg.subtotal())
print(sorted(vars(nutmeg).items())) # [('description', 'Moluccan nutmag'), ('price', 13.4), ('weight', 8)]
|
8ca1935a02eb7c5af940ef55651429f801d10e61 | kibitzing/FluentPython | /archive/To10-29/10-30/sanghong_10-30.py | 2,208 | 3.546875 | 4 | #!/usr/bin/envs python3
# -*- coding: utf-8 -*-
#################################
#
# Inha University
# DSP Lab Sanghong Kim
#
#
#################################
"""
2018_10-30_Fluent_Python
@Author Sanghong.Kim
오늘은 예제만 돌려 보았다.
"""
# Import Modules
import time
import os
import sys
import argparse
import functools
import copy
def clock(func):
@functools.wraps(func)
def clocked(*args, **kwargs):
t0 = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - t0
name = func.__name__
arg_lst = []
if args:
arg_lst.append(', '.join(repr(arg) for arg in args))
if kwargs:
pairs = ['%s=%r' % (k, w) for k, w in sorted(kwargs.items())]
arg_lst.append(', '.join(pairs))
arg_str = ', '.join(arg_lst)
print('[%0.8fs] %s(%s) -> %r' % (elapsed, name, arg_str, result))
return result
return clocked
class Bus:
def __init__(self, passengers=None):
if passengers is None:
self.passengers = []
else:
self.passengers = list(passengers)
def pick(self, name):
self.passengers.append(name)
def drop(self, name):
self.passengers.remove(name)
l1 = [3, [66, 55, 44], (7, 8, 9)]
a = [10, 20]
b = [a ,30]
@clock
def main(args):
print("Add Your Code Below")
l2 = list(l1)
print(l2 == l1)
print(l2 is l1)
print('l1 : ', l1)
print('l2 : ', l2)
l2 = list(l1)
l1.append(100)
l1[1].remove(55)
print('l1 : ', l1)
print('l2 : ', l2)
l2[1] += [33,22]
l2[2] += (10,11)
print('l1 : ', l1)
print('l2 : ', l2)
bus1 = Bus(['Alice', 'Bill', 'Claire', 'David'])
bus2 = copy.copy(bus1)
bus3 = copy.deepcopy(bus1)
print(id(bus1), id(bus2), id(bus3))
bus1.drop('Bill')
print(bus2.passengers)
print(bus3.passengers)
print(id(bus1.passengers), id(bus2.passengers), id(bus3.passengers))
print(bus3.passengers)
a.append(b)
print(a)
c = copy.deepcopy(a)
print(c)
# Arguments Setting
if __name__ == '__main__':
parser = argparse.ArgumentParser()
args = parser.parse_args()
main(args)
|
5d891f17b02a931d3782e3ff51bb3201e400db12 | kibitzing/FluentPython | /archive/To11-19/11-22/keunhoi_11-22.py | 1,540 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# p347-351 (actually 352)
# Example 12-1 ~ 5
'''
__setitem__과 collections.UserDict에 대한 내용. + 클래스 상속
'''
import collections
class DoppelDict(dict):
def __setitem__(self, key, value):
super().__setitem__(key, [value] * 2)
class AnswerDict(dict):
def __getitem__(self, key):
return 42
class DoppelDict2(collections.UserDict):
def __setitem__(self, key, value):
super().__setitem__(key, [value] * 2)
class whatdidyouchoose(collections.UserDict):
def __getitem__(self, key):
if key in self:
if type(key) == int:
print('You choose a number.')
if type(key) == str:
print('You choose a character.')
else:
print('Please choose a key in your dict.')
class A:
def ping(self):
print('ping:', self)
class B(A):
def pong(self):
print('pong:', self)
class C(A):
def pong(self):
print('PONG:', self)
class D(B, C):
def ping(self):
super().ping()
print('post-ping:', self)
def pingpong(self):
self.ping()
super().ping()
self.pong()
super().pong()
C.pong(self)
def main():
dd = DoppelDict(one=1)
print(dd)
dd['two'] = 2
print(dd)
dd.update(three=3)
print(dd)
ad = AnswerDict(a='foo')
print(ad['a'])
d = {}
d.update(ad)
print(d['a'])
print(d)
dd = DoppelDict2(one=1)
print(dd)
dd['two'] = 2
print(dd)
dd.update(three=3)
print(dd)
d = D()
d.pong()
C.pong(d)
print(D.__mro__)
d = {'a':1, 'b':2, 2:4, 4:6,}
wdy = whatdidyouchoose(d)
wdy['a']
wdy[2]
wdy[99]
if __name__ == '__main__':
main()
|
f5ae4c3dc4c6a7cd34f3e446b56fe67cdd97ce40 | kibitzing/FluentPython | /archive/To11-19/11-23/seongbin_11_23.py | 767 | 3.859375 | 4 | class DoppelDict(dict):
def __setitem__(self, key, value):
super().__setitem__(key,[value]*2)
dd = DoppelDict(one=1)
print(dd)
dd['two'] = 2
print(dd)
dd.update(three =3)
print(dd)
class AnswerDict(dict):
def __getitem__(self, item):
return 42
ad = AnswerDict(a='foo')
print(ad['a'])
d = {}
d.update(ad)
print(d['a'])
print(d)
import collections
class DoppelDict2(collections.UserDict):
def __setitem__(self, key, value):
super().__setitem__(key,[value]*2)
dd2 = DoppelDict2(one=1)
print(dd2)
dd2['two'] = 2
dd2.update(three=3)
print(dd2)
class AnswerDict2(collections.UserDict):
def __getitem__(self, item):
return 42
ad2 = AnswerDict2(a='foo')
print(ad2['a'])
d2 = {}
d2.update(ad2)
print(d2['a'])
print(d)
|
bb263b105e528123a3002adbf29a1c7b6f078c72 | kibitzing/FluentPython | /archive/To10-12/10-12/keunhoi_10-12.py | 1,658 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
print([callable(obj) for obj in (abs, str, int, float, 13, 'str', math)])
import random
class Lotto:
def __init__(self, items):
self._items = list(items)
random.shuffle(self._items)
def pick(self):
self.numbers = []
for i in range(6):
self.numbers.append(self._items.pop())
return self.numbers
def __call__(self):
return self.pick()
print("="*100)
lotto = Lotto(range(1,46))
print('The lotto numbers of this week:', lotto.pick())
print("="*100)
class Fail: pass
obj = Fail()
def Failfunc(): pass
print(sorted(set(dir(Failfunc))))
print(sorted(set(dir(obj))))
print(sorted(set(dir(Failfunc)) - set(dir(obj))))
print("="*100)
# example 5-10
def tag(name, *content, cls=None, **attrs):
"""Generate one or more HTML tags"""
if cls is not None:
attrs['class'] = cls
if attrs:
attr_str = ''.join(' %s="%s"' % (attr, value)
for attr, value
in sorted(attrs.items()))
else:
attr_str = ''
if content:
return '\n'.join('<%s%s>%s</%s>' %
(name, attr_str, c, name) for c in content)
else:
return '<%s%s />' % (name, attr_str)
# example 5-11
t = ('hello', 'world')
l = list(t)
print(tag('br'))
print(tag('p', 'hello'))
print(tag('p', 'hello', 'world'))
print(tag('p', ('hello', 'world')))
print(tag('p', *('hello', 'world')))
print(tag('p', t))
print(tag('p', *t))
print(tag('p', l))
print(tag('p', *l))
print(tag('p', 'hello', id=33))
print(tag('p', 'hello', 'world', cls='sidebar'))
print(tag(content='testing', name="img"))
my_tag = {'name': 'img', 'title': 'Sunset Boulevard', 'src': 'sunset.jpg', 'cls': 'framed'}
print(tag(**my_tag))
|
53c926599d106529172857e53c8f2d4aaa347e54 | kibitzing/FluentPython | /archive/To12-14/12-11/jingu_12-11.py | 1,320 | 3.796875 | 4 | #!/anaconda3/envs/tensorflow/bin/python
# -*- coding: utf-8 -*-
"""
Created by Jingu Kang on 11/12/2018.
Copyright © 2018 Jingu Kang. All rights reserved.
DESCRIPTION:
When to use Generate function?
How to use more effieciently with itertools?
"""
class ArithmeticProgression:
def __init__(self, begin, step, end=None):
self.begin = begin
self.step = step
self.end = end
def __iter__(self):
result = type(self.begin + self.step)(self.begin)
forever = self.end is None
index = 0
while forever or result < self.end:
yield result
index += 1
result = self.begin + self.step * index
def aritprog_gen(begin, step, end=None):
result = type(begin + step)(begin)
forever = end is None
index = 0
while forever or result < end:
yield result
index += 1
result = begin + step * index
ap = ArithmeticProgression(0, 1, 4)
print(list(ap))
ap2 = aritprog_gen(0, 1, 4)
print(list(ap2))
import itertools
gen = itertools.count(0, 1)
gen_list = []
i = 0
while i < 4:
gen_list.append(next(gen))
i += 1
print(gen_list)
gen2 = itertools.takewhile(lambda n: n < 4, itertools.count(0, 1))
print(list(gen2))
|
d2277970789fc7a457e98c843a740a3c30d3a459 | kibitzing/FluentPython | /archive/To10-29/10-29/seunghyun_10-29.py | 726 | 4.09375 | 4 | class Bus:
def __init__(self, passengers=None):
if passengers is None:
self.passengers = []
else:
self.passengers = list(passengers)
def pick(self, name):
self.passengers.append(name)
def drop(self, name):
self.passengers.remove(name)
import copy
bus1 = Bus(['Alice', 'Bill', 'Claire', 'David'])
bus2 = copy.copy(bus1)
bus3 = copy.deepcopy(bus1)
print (id(bus1), id(bus2), id(bus3))
bus1.drop('Bill')
print (bus2.passengers)
print (id(bus1.passengers), id(bus2.passengers), id(bus3.passengers))
print (bus3.passengers)
a = [10, 20]
b = [a, 30]
a.append(b)
print (a)
from copy import deepcopy
c = deepcopy(a)
print (c)
|
ed8daafff478fd97ca91fdcf47fef624e02bc598 | kibitzing/FluentPython | /archive/To12-21/12-17/jingu_12-17.py | 1,736 | 3.53125 | 4 | #!/anaconda3/envs/tensorflow/bin/python
#-*- coding: utf-8 -*-
"""
Created by Jingu Kang on 17/12/2018.
Copyright © 2018 Jingu Kang. All rights reserved.
DESCRIPTION:
simple variation of example source
using with and stdout.write
"""
import sys
class LookingMinus:
def __enter__(self):
self.original_write = sys.stdout.write
sys.stdout.write = self.minus_write
return '12345'
def minus_write(self, numbers):
for number in numbers:
if number == '[' or number == ']' or number == ',' or number == ' ' or number == '\n':
continue
self.original_write('-'+ str(number))
self.original_write('\n')
def __exit__(self, exc_type, exc_value, traceback):
sys.stdout.write = self.original_write
if exc_type is ZeroDivisionError:
print('Please DO NOT divide by zero!')
return True
with LookingMinus() as what:
print([1,2,3,4,5])
print('what?', what)
print('Back to normal.')
print('what?', what)
print('================')
class LookingGlass:
def __enter__(self):
self.original_write = sys.stdout.write
sys.stdout.write = self.reverse_write
return 'abcdef'
def reverse_write(self, text):
self.original_write(text[::-1])
def __exit__(self, exc_type, exc_value, traceback):
sys.stdout.write = self.original_write
if exc_type is ZeroDivisionError:
print('Please DO NOT divide by zero!')
return True
with LookingGlass() as what:
print('Alice, Kitty and Snowdrop')
print('what?',what)
print('Back to normal.')
print('what?',what)
|
203e8b01e97d053c33ce1e37ea499b16dfed2960 | kibitzing/FluentPython | /archive/To11-05/11-05/keunhoi_11-05.py | 1,930 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# p252-256
'''
예제에 @property를 사용하여서 visualize 매소드를 추가함.
'''
import datetime
import math
import numpy as np
from matplotlib import pyplot as plt
# 9-4
class Demo:
@classmethod
def klassmeth(*args):
return args
@staticmethod
def statmeth(*args):
return args
print(Demo.klassmeth())
print(Demo.klassmeth('spam'))
print(Demo.statmeth())
print(Demo.statmeth('spam'))
print("="*50)
br1 =1/2.43
print(format(br1, '0.4f'))
print('1 BRL = {rate:0.2f} USD'.format(rate=br1))
print("="*50)
now = datetime.datetime.now()
format(now, '%H%M%S')
print("It's now {:%I:%M %p}".format(now))
# 9-6 custom
class Vector2d:
typecode = 'd'
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __iter__(self):
return (i for i in (self.x, self.y))
def __repr__(self):
class_name = type(self).__name__
return '{}({!r}, {!r})'.format(class_name, *self)
def __str__(self):
return str(tuple(self))
def __bytes__(self):
return (bytes([ord(self.typecode)]) + bytes(array(self.typecode, self)))
def __eq__(self, other):
return tuple(self) == tuple(other)
def __abs__(self):
return math.hypot(self.x, self.y)
def angle(self):
return math.atan2(self.y, self.x)
def __bool__(self):
return bool(abs(self))
def __format__(self, fmt_spec=''):
if fmt_spec.endswith('p'):
fmt_spec = fmt_spec[:-1]
coords = (abs(self), self.angle())
outer_fmt = '<{}, {}>'
else:
coords = self
outer_fmt = '({}, {})'
components = (format(c, fmt_spec) for c in coords)
return outer_fmt.format(*components)
@property
def visualize(self):
plt.figure()
plt.title('Visualized Vector')
plt.xlim(-(self.x+3), self.x+3)
plt.ylim(-(self.y+3), self.y + 3)
ax = plt.axes()
ax.arrow(0,0,*(self.x,self.y),head_width=0.1)
plt.show()
Vector2d(3,4).visualize # MatplotlibDeprecationWarning이 뜨긴 함. |
42a52e8994dd790ea8b5ffb45d1a2a66c4ddbea7 | danielrbk/Projects | /Generalized Euler Problems/problem16.py | 146 | 3.59375 | 4 | """
trivial in python
"""
t = int(input())
for a0 in range(t):
n = int(input())
n = str(2**n)
print(sum([int(x) for x in n])) |
ca7a4e7e278b23bdaef2eea41c0b859e98ae00ab | danielrbk/Projects | /Generalized Euler Problems/problem17.py | 3,025 | 3.96875 | 4 | """
Challenge link: https://www.hackerrank.com/contests/projecteuler/challenges/euler017
------------
Description:
For T test cases, print out N in worded numbers, i.e: 13 is thirteen
------------
Constraints:
1 <= T <= 10
1 <= N <= 10**12
------------
Algorithm:
A bit of a pain to implement the algorithm, however it is trivial and implemented in such a way that this is algorithm
is easily expendable to far greater orders of magnitude for N
------------
"""
def countDigits(n):
c = 0
while (n != 0):
c += 1
n //= 10
return c
def unit(d,original):
if original<10 and d == 0:
return ["Zero"]
elif d == 1:
return ["One"]
elif d == 2:
return ["Two"]
elif d == 3:
return ["Three"]
elif d == 4:
return ["Four"]
elif d == 5:
return ["Five"]
elif d == 6:
return ["Six"]
elif d == 7:
return ["Seven"]
elif d == 8:
return ["Eight"]
elif d == 9:
return ["Nine"]
else:
return [""]
def tens(d,original):
if d == 10:
return ["Ten"]
elif d == 11:
return ["Eleven"]
elif d == 12:
return ["Twelve"]
elif d == 13:
return ["Thirteen"]
elif d == 14:
return ["Fourteen"]
elif d == 15:
return ["Fifteen"]
elif d == 16:
return ["Sixteen"]
elif d == 17:
return ["Seventeen"]
elif d == 18:
return ["Eighteen"]
elif d == 19:
return ["Nineteen"]
ten = d // 10
if ten == 0:
return unit(d % 10,original)
elif ten == 2:
return ["Twenty"] + unit(d % 10,original)
elif ten == 3:
return ["Thirty"] + unit(d % 10,original)
elif ten == 4:
return ["Forty"] + unit(d % 10,original)
elif ten == 5:
return ["Fifty"] + unit(d % 10,original)
elif ten == 6:
return ["Sixty"] + unit(d % 10,original)
elif ten == 7:
return ["Seventy"] + unit(d % 10,original)
elif ten == 8:
return ["Eighty"] + unit(d % 10,original)
elif ten == 9:
return ["Ninety"] + unit(d % 10,original)
def hundred(n,original):
if n < 100:
return tens(n,original)
return unit(n // 100,original) + ["Hundred"] + tens(n % 100,original)
def numberToString(n):
prefix = [["Thousand"], ["Million"], ["Billion"], ["Trillion"]]
s = []
l = countDigits(n)
original = n
while l >= 4:
temp = n
c = 0
while temp >= 1000:
c += 1
temp //= 1000
hund = n//(10 ** (3 * c))
if hund!=0:
s += hundred(hund,original) + prefix[(l - 1) // 3 - 1]
n = n % (10 ** (3 * c))
l = countDigits(n)
s += hundred(n,original)
s = [x for x in s if x!=""]
return " ".join(s)
t = int(input())
for a0 in range(t):
n = int(input())
print(numberToString(n))
|
ede1885178d2d73ebb9e09aa7e690a722a0a0636 | MojoJolo/code_snippets | /Python/count_unique_words.py | 428 | 3.921875 | 4 | # Count unique words in a list
def countUniqueWords(words):
wordList = []
for word in words:
# Get all the word in the dictionary list
wl = [w['word'] for w in wordList]
if word not in wl:
wordList.append({'word': word, 'count': 1})
else:
# get the current word in the dictionary list
wordMap = [w for w in wordList if w['word'] == word][0]
wordMap['count'] += 1
return wordList |
6767fbaf980420e69a36decdf303682deade4109 | Visheshkant/My_codes | /gui_calcy.py | 3,428 | 3.796875 | 4 | from tkinter import *
gui = Tk()
gui.title("Simple Calculator")
gui.resizable(0, 0)
gui.geometry("300x200")
expression = ""
# ******************************** Backend *************************************
# ****** For press function ******
def press(num):
global expression
expression+=str(num)
equation.set(expression)
# ****** For equalpress function ******
def equalpress():
global expression
total = str(eval(expression))
equation.set(total)
expression=""
# ****** For clearpress function ******
def clearpress():
global expression
expression=""
equation.set("")
# ******************************** Display *************************************
menubar = Menu(gui)
gui.configure(menu = menubar)
filemenu = Menu(menubar)
menubar.add_cascade(label="View", menu = filemenu)
menubar.add_cascade(label="Edit", menu = filemenu)
menubar.add_cascade(label="Help", menu = filemenu)
equation = StringVar()
expression_field = Entry(gui, textvariable = equation, width=75)
expression_field.configure(background="white", font=("Verdana", 12))
expression_field.grid(columnspan = 91, ipady=10)
equation.set("Enter the value")
button1 = Button(gui, text="1", height=2, width=9, command=lambda:press(1), activebackground="silver")
button1.grid(row = 2, column=0)
button2 = Button(gui, text="2", height=2, width=9, command=lambda:press(2), activebackground="silver")
button2.grid(row = 2, column=1)
button3 = Button(gui, text="3", height=2, width=9, command=lambda:press(3), activebackground="silver")
button3.grid(row = 2, column=2)
plus = Button(gui, text="+", height=2, width=9, command=lambda:press("+"), activebackground="silver")
plus.grid(row = 2, column=3)
button4 = Button(gui, text="4", height=2, width=9, command=lambda:press(4), activebackground="silver")
button4.grid(row = 3, column=0)
button5 = Button(gui, text="5", height=2, width=9, command=lambda:press(5), activebackground="silver")
button5.grid(row = 3, column=1)
button6 = Button(gui, text="6", height=2, width=9, command=lambda:press(6), activebackground="silver")
button6.grid(row = 3, column=2)
minus = Button(gui, text="-", height=2, width=9, command=lambda:press("-"), activebackground="silver")
minus.grid(row = 3, column=3)
button7 = Button(gui, text="7", height=2, width=9, command=lambda:press(7), activebackground="silver")
button7.grid(row = 4, column=0)
button8 = Button(gui, text="8", height=2, width=9, command=lambda:press(8), activebackground="silver")
button8.grid(row = 4, column=1)
button9 = Button(gui, text="9", height=2, width=9, command=lambda:press(9), activebackground="silver")
button9.grid(row = 4, column=2)
multiply = Button(gui, text="*", height=2, width=9, command=lambda:press("*"), activebackground="silver")
multiply.grid(row = 4, column=3)
button0 = Button(gui, text="0", height=2, width=9, command=lambda:press(0), activebackground="silver")
button0.grid(row = 5, column=0)
clear = Button(gui, text="CLEAR", height=2, width=9, command=clearpress, activebackground="silver", activeforeground='red')
clear.grid(row = 5, column=1)
equal = Button(gui, text="=", height=2, width=9, command=equalpress, activebackground="silver")
equal.grid(row = 5, column=2)
divide = Button(gui, text="/", height=2, width=9, command=lambda:press("/"), activebackground="silver")
divide.grid(row = 5, column=3)
gui.mainloop()
|
87d98c47c12298664e090be70942a405a3b7055a | CHyuye/Python | /lecture04/Algorithm_research.py | 1,346 | 3.640625 | 4 | """
广度优先搜索 -- 一种对图进行搜索的算法
广度优先搜索会优先从离起点近的顶点开始搜索
"""
from collections import deque # 模块提供一些有用的集合类
graph = {}
graph['you'] = ['alice', 'bob', 'claire']
graph['bob'] = ['anuj', 'peggy']
graph['alice'] = ['peggy']
graph['claire'] = ['thom', 'jonny']
graph['anuj'] = []
graph['peggy'] = []
graph['thom'] = []
graph['jonny'] = []
def research(name):
research_queue = deque() # 建立一个双端队列
research_queue += graph[name] # 将你的邻居都加入到这个搜索队列中
searched = [] # 这个数组用来记录已检查过的人
while research_queue: # 队列不为空时循环执行
person = research_queue.popleft() # 对队列中的第一项进行判断,出队
if person not in searched: # 仅当这个人没检查时才检查
if person_is_seller(person): # 如果是person就打印
print(person + " is a mango seller.")
else: # 如果person不是商人,就将person的朋友都加入搜索队列
research_queue += graph[person]
searched.append(person) # 讲这个人标记为检查过
def person_is_seller(name): # 名字最后一个为‘m’就是商人
return name[-1] == 'm'
research('you')
|
f99c73ad9d430e13e868d69f429e28109712a5df | CHyuye/Python | /lecture06/whlie_day_03.py | 1,736 | 4.09375 | 4 | """
作者:陈志安
功能:计算出时间,是几年几天
"""
from datetime import datetime
def is_leap_year(year):
"""
判断是否是闰年
"""
is_leap = False
if (year % 400 == 0) or (year % 4 == 0) and (year != 0):
is_leap = True
return is_leap
def main():
"""
主函数
"""
# input_date_str = input('请输入日期(yyyy/mm/dd):')
# input_date = datetime.strptime(input_date_str, '%Y/%m/%d')
# print(input_date)
#
# year = input_date.year
# month = input_date.month
# day = input_date.day
#
# # 计算每月天数的总和以及当前月份天数
# days_in_month_tup = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
# # print(days_in_month_tup[:month - 1])
# days = sum(days_in_month_tup[:month - 1]) + day
#
# # 判断闰年
# if (year % 400 == 0) or (year % 4 == 0) and (year != 0):
# if month > 2:
# days += 1
# print('这是第{}天。'.format(days))
input_date_str = input('请输入日期(yyyy/mm/dd):')
input_date = datetime.strptime(input_date_str, '%Y/%m/%d')
print(input_date)
year = input_date.year
month = input_date.month
day = input_date.day
# 集合方式
day_30_month_set = {4, 6, 9, 11}
day_31_month_set = {1, 3, 5, 7, 8, 10, 12}
# 初始值
days = 0
days += day
for i in range(1, month):
if i in day_30_month_set:
days += 30
elif i in day_31_month_set:
days += 31
else:
days += 28
if is_leap_year(year) and month > 2:
days += 29
print('这是{}年的第{}天'.format(year, days))
if __name__ == '__main__':
main() |
284bc204ed2f1e0a77165a97ba635d904b7e7773 | CHyuye/Python | /lecture09/AQI_v3.0.py | 735 | 3.59375 | 4 | """
作者:陈志安
日期:19/3/21
功能:AQI计算
版本:v.1
"""
import csv
import json
def process_json_file(filepath):
"""
解码json文件
"""
f = open(filepath, mode='r', encoding='utf-8')
city_list = json.load(f)
return city_list
def main():
"""
主函数
"""
filepath = input('请输入json文件名')
city_list = process_json_file(filepath)
city_list.sort(key=lambda city: city['aqi'])
lines = []
# 列名
lines.append(list(city_list[0].keys()))
for city in city_list:
lines.append(list(city.values()))
f = open('aqi.csv', 'w', encoding='utf-8', newline='')
writer = csv.writer(f)
for line in lines:
writer.writerow(line)
f.close()
if __name__ == '__main__':
main()
|
9be2af7ed65654c93ea19f5b4388126b4b627fdb | CHyuye/Python | /Card_program/python_variable.py | 3,301 | 4.28125 | 4 | """
变量 :
1、变量的引用
2、可变和不可变类型
3、全局变量和局部变量
"""
"""
1、变量的引用 —— 变量和数据都是保存在内存中
在python中函数的参数传递以及返回值都是靠引用传递
变量和数据是分开存储的
数据保存在内存中的一个位置
变量保存着数据在内存的地址
变量中记录数据的地址就叫引用
id() 方法可以查看变量中保存数据所在的内存地址
"""
# 注意:当给一个变量赋值的时候,本质上是修改了数据的引用
# · 变量不再对之前的数据引用
# · 变量改为对新赋值的数据引用
# def test(num):
#
# print("在函数内部{} 对应的内存地址是 {}".format(num, id(num)))
#
# # 1> 定义一个字符串变量
# result = "Hello"
#
# # 2> 将字符串变量返回,返回的是数据的引用,而不是数据本身
# return result
#
# # 定义一个数字变量
# a = 10
#
# # 数据的地址本质上就是一个数字
# print("a的变量保存的数据内存地址是 {}".format(id(a)))
#
# # 调用test函数,本质上传递的是实参保存的数据引用,而不是实参保存的数字
# # 注意:如果函数有返回值,但没有调用函数,程序不报错,但无返回结果
# r = test(a)
#
# print("{}的内存地址是 {}".format(r, id(r)))
# 注意:字典的key只能使用不可变类型的数据
# 字典的value可以是任意的类型数据
"""
可变类型和不可变类型
· 不可变类型 —— 内存的数据不允许被修改
·数字类型 int, bool, float, complex, long(2,x)
·字符串 str
·元组 tuple
· 可变类型 ——内存数据允许修改
·列表 list
·字典 dictionary
"""
# 可变类型的数据变化是通过方法来实现的
# 如果给一个可变类型的变量,赋值了一个新的数据,引用会修改,变量改为对新赋值的·引用
# 注意:字典的key只能使用不可变类型的数据
# 全局变量 and 局部变量
"""
局部变量特点
1、局部变量是在函数内部定义的变量,只能在函数内部使用
2、函数执行结束后,函数内部的局部变量,会被系统回收
3、不同的函数,可以定义相同的名字的局部变量,但是各自不会产生影响
"""
# def demo1():
#
# num = 10
# print("demo1 ==> {}".format(num))
#
#
# def demo2():
#
# num = 99
# print("demo2 ==> {}".format(num))
#
#
# demo1()
# demo2()
# 全局变量
"""
特点1、函数不能直接修改全局变量的引用
特点2、global方法,修改全局变量
特点3、全局变量的定位应该字所有函数上方,保证函数可以访问到每个全局变量
"""
# 全局变量的命名
gl_num = 99
gl_name = "Allen"
def demo1():
# 函数不能直接修改全局变量的引用
# 如果使用赋值语句,会在函数内部定义一个局部变量
# 修改全局变量使用global声明一下后面的是全局变量,再使用赋值语句就不会创建局部变量
# global num
num = 10
print("demo1 ==> {}".format(num))
def demo2():
print("demo2 ==> {}".format(gl_num))
print("{}" .format(gl_name))
demo1()
demo2() |
29d3f18d1a9f52d1d4a5b7340b40f49e28250fa7 | CHyuye/Python | /lecture03/python-basic3.py | 629 | 3.921875 | 4 | """
综合应用——石头剪刀布
"""
import random
while True:
player = int(input("请输入您要出的拳 石头(1)/剪刀(2)/布(3):"))
computer = random.randint(1, 3)
print("玩家出的拳是 %d -- 电脑出的拳是 %d" % (player, computer))
if ((player == 1 and computer == 2)
or (player == 2 and computer == 3)
or (player == 3 and computer == 1)):
print("电脑弱爆了!")
break
# 平局
elif player == computer:
print("真是心有灵犀,再来一盘")
# 电脑获胜
else:
print("不服气,决战到天亮!") |
189c2824801ff6acbec856b0b6c44c5b35cd98cd | CHyuye/Python | /lecture04/Algorithm_QuickSort.py | 1,191 | 3.953125 | 4 | import random
"""
快速排序——首先会在序列中选择一个基准值(pivot),然后将除了基准值以外的数分为
"比基准值大的数"和"比基准值小的数",再将其排列
"""
data = [45,3,9,15,67,51,42]
def quickSort(data, start, end):
i = start
j = end
# i和j重合时,依次排序结束
if i >= j:
return
# 设置最左边的数为基准值
flag = data[start]
while i < j:
while i < j and data[j] >= flag:
j -= 1
# 找到右边的第一个小于基准值的数,赋值给左边的i,此时左边的i被记录在flag中
data[i] = data[j]
while i < j and data[i] < flag:
i += 1
# 找到左边第一个大于基准值的数,赋值给右边的j,右边的j与左边的i相同
data[i] = data[j]
# 由于循环以i结尾,循环完毕后把flag值放在i所在的位置
data[i] = flag
# 除去i之外的两端递归
quickSort(data, start, i-1)
quickSort(data, i+1, end)
# if __name__ == "__main__":
# data = [each for each in range(15)]
# random.shuffle(data)
quickSort(data, 0, len(data) - 1)
print(data)
|
185ced33a8ef0de6e8800e633be17ce7ee5e83a6 | manishwvn/arrays_basics | /all_subarrays.py | 331 | 4.0625 | 4 | # given an array, print all subarrays
def all_subarrays(arr):
n = len(arr)
for i in range(0,n):
for j in range(i,n):
for k in range(i,j+1):
print (arr[k], end = " ")
print ("\n", end = "")
n = int(input())
arr = [int(input()) for x in range(n)]
all_subarrays(arr)
|
5d4f73278e7471be409d88fdcfc7ab6bbbec95f2 | mjrice04/data_engineering_utilities | /google_maps/address_to_lat_long.py | 2,619 | 3.703125 | 4 | import requests
import pandas as pd
import numpy as np
import json
import os
def address_reader(path='data/address_data_example.csv'):
"""
This function reads the address data and returns a dataframe of the addresses
:param path: path to the data
:return:
"""
address_csv = pd.read_csv(path, dtype={'Address': 'str', 'City': 'str', 'State': 'str',
'Zip': 'str', 'Comment': 'str'})
return address_csv
def get_lat_long(address_csv):
"""
makes a call to the google maps API service and returns a list of lat, long with an ID
:param address_csv: input address csv
:return:
"""
lat_long_list = []
for index, row in address_csv.iterrows():
print(row)
street = row['Address']
city = row['City']
state = row['State']
zipcode = row['Zip']
comment = row['Comment']
clean = lambda x: '+'.join(x.split(' '))
clean_street = clean(street)
clean_city = clean(city)
URL = f"https://maps.googleapis.com/maps/api/geocode/json?address={clean_street},+{clean_city},+{state}+{zipcode}&key={os.environ['MAPS_API_KEY']}"
response = requests.get(URL)
json_response = json.loads(response.text)
try:
lat = json_response['results'][0]['geometry']['location']['lat']
except:
lat = 0
try:
lng = json_response['results'][0]['geometry']['location']['lng']
except:
lng = 0
lat_long_list.append(f"{index},{lat},{lng},{comment}")
return lat_long_list
def lat_long_to_frame(lat_long_list):
"""
creates pandas dataframe out of list of latitudes and longitudes
:param lat_long_list: list of lat and long
:return:
"""
lat_list = []
lng_list = []
index_list = []
comment_list = []
for i in lat_long_list:
split = i.split(',')
index_list.append(split[0])
lat_list.append(split[1])
lng_list.append(split[2])
comment_list.append(split[3])
dict = {'ID': index_list, 'LAT': lat_list, 'LNG': lng_list, 'Comment': comment_list}
df_lng_lat = pd.DataFrame(dict)
return df_lng_lat
def lat_long_data_handler():
"""
runs logic for parsing and returning long and lat frame based on input data csv
:return:
"""
address_csv = address_reader()
lat_long = get_lat_long(address_csv=address_csv)
lat_long_frame = lat_long_to_frame(lat_long_list=lat_long)
print(lat_long_frame)
return lat_long_frame
if __name__ == "__main__":
lat_long_data_handler()
|
e6fda354bf07e04d16e648697c09400a404af8d0 | fherbine/computorV1 | /controllers/ft_math.py | 2,825 | 3.59375 | 4 | """Own math module.
Contained functions are:
- ft_abs(n): return the absolute value of n.
- ft_power(n, p): return n raised to power p
- ft_sqrt(n): return the square root of n. Should be improved !
Contained objects are:
- Complex(r, i): Represents a coplex number.
"""
def ft_abs(n):
return -n if n < 0 else n
def ft_power(n, p):
total = 1
for _ in range(p):
total *= n
return total
def ft_sqrt(n):
if n < 0:
raise ValueError('Square root function is not defined for negatives.')
i = 0
# Ugly way to calculate sqrt :/
while (i+1) * (i+1) <= n:
i += 1
while (i+.1) * (i+.1) <= n:
i+= .1
while (i+.01) * (i+.01) <= n:
i += .01
while (i+.001) * (i+.001) <= n:
i += .001
while (i+.0001) * (i+.0001) <= n:
i += .0001
return i
class Complex:
def __init__(self, r, i):
self._r = r
self._i = i
@property
def r(self):
if not isinstance(self._r, int):
return int(self._r) if self._r.is_integer() else self._r
return self._r
@r.setter
def r(self, value):
self._r = value
@property
def i(self):
if not isinstance(self._i, int):
return int(self._i) if self._i.is_integer() else self._i
return self._i
@i.setter
def i(self, value):
self._i = value
def __repr__(self):
return "'%s'" % self.__str__()
def __str__(self):
r, i = self.r, self.i
separator = '+' if i >= 0 else '-'
i = ft_abs(i)
if not i:
return f'{r}'
if not r:
if separator == '+':
separator = ''
return f'{separator}{i}i'
return f'({r} {separator} {i}i)'
def __add__(self, number):
r = self.r
i = self.i
if isinstance(number, Complex):
r = self.r + number.r
i = self.i + number.i
return Complex(r, i)
return Complex(r + number, i)
def __sub__(self, number):
r = self.r
i = self.i
if isinstance(number, Complex):
r = self.r - number.r
i = self.i - number.i
return Complex(r, i)
return Complex(r - number, i)
def __mul__(self, number):
if isinstance(number, Complex):
# Not implemented yet
raise TypeError(
'Cannot multiplie complex numbers between them.'
)
return Complex(self.r * number, self.i * number)
def __truediv__(self, number):
if isinstance(number, Complex):
# Not implemented yet
raise TypeError(
'Cannot divide complex numbers between them.'
)
return Complex(self.r / number, self.i / number)
|
46967699118df771c18826d0a4624f3a731f1b78 | andersongfs/Programming | /URI/URI-1091.py | 488 | 3.734375 | 4 | # -*- coding: utf-8 -*-
while True:
qtd_casa = int(raw_input())
if(qtd_casa == 0):
break
x_ponto, y_ponto = map(int, raw_input().split())
for i in range(qtd_casa):
x_casa, y_casa = map(int, raw_input().split())
if(x_casa > x_ponto and y_casa > y_ponto):
print "NE"
elif(x_casa > x_ponto and y_casa < y_ponto):
print "SE"
elif(x_casa < x_ponto and y_casa > y_ponto):
print "NO"
elif(x_casa < x_ponto and y_casa < y_ponto):
print "SO"
else:
print "divisa"
|
192954d0c5a47b4c92128468a1fee0553ce03b18 | andersongfs/Programming | /URI/URI-1068.py | 308 | 3.890625 | 4 | # -*- coding: utf-8 -*-
while True:
try:
entrada = raw_input()
num = 0
for i in entrada:
if(i == "("):
num = num + 1
elif(i == ")"):
if(num == 0):
num = num - 1
break
num = num - 1
if (num == 0):
print "correct"
else:
print "incorrect"
except EOFError:
break |
cff73288b24f82dcc147d565c92a56fcee7cd947 | yifyirf/GSEA-Genialis | /gsea.py | 6,047 | 3.546875 | 4 | import csv
import numpy as np
import random
from scipy import stats
import gsea_functions as gf
'''Program to calculate the normalized enrichment scores and pvalues according to the publication:
http://software.broadinstitute.org/gsea/doc/subramanian_tamayo_gsea_pnas.pdf
The program accepts 2 files, which user can specify in the respective input step after the program
is launched. First file should contain the gene expression data in the format of the example file
"leukemia.txt". The second file should contain the gene sets data, in the format of the example
file "pathways.txt". Further input includes 2 phenotype lables (case sensitive, should be the same
as in the gene expression data). The advantage is, if the data contains multiple phenotypes, they
can be examined by pairs. Number of permutations defines how many permutations will be run to
calculate the pvalues and the normalized enrichment scores. The file "gsea_functions.py" should be
in the same folder as this file. It contains functions required in the calculattion.
Returns 2 files with results, each for one of the phenotypes. The results files contain gene sets
names, normalized enrichment scores and pvalues based on the user inputs. The results are sorted
by the normalized enrichment score. '''
#asking for user input
print('Thank you for starting the GSEA program.')
gene_list = input('Enter the path to the file containing gene expression data\n>')
pathways = input('Enter the path to the file containing gene sets\n>')
phenotype_1 = input('Enter the name of the first phenotype to be examined\n>')
phenotype_2 = input('Enter the name of the second phenotype to be examined\n>')
number_permutations = input('Enter the number of permutations for the calculation\n>')
number_permutations = int(number_permutations)
phenotype_1_columns = []
phenotype_2_columns = []
unranked_data = []
gene_sets = []
#reading in the list of genes and their expression profiles
with open(gene_list, newline='') as f:
reader = csv.reader(f, delimiter='\t')
#reading the file header and columns for different phenotypes
#the columns indicating the data for specific phenotypes will be needed for the ranking function
header = next(reader)
for index, column_header in enumerate(header):
if column_header == phenotype_1:
phenotype_1_columns.append(index)
elif column_header == phenotype_2:
phenotype_2_columns.append(index)
#transforming the values from str to float
for line in reader:
new_line = []
new_line.append(line[0])
for element in line[1:]:
new_line.append(float(element))
unranked_data.append(new_line)
#reading in the list of gene sets
with open(pathways, newline='') as f:
reader = csv.reader(f, delimiter='\t')
for line in reader:
gene_sets.append(line)
#ranking the gene expression profiles by the signal to noise metric
ranked_list = gf.build_ranked_list(unranked_data, phenotype_1_columns, phenotype_2_columns)
#following lists will contain the calculation results for both phenotypes in question
results_1 = []
results_2 = []
#this loop contains the calculation of the original enrichment scores, enrichment scores for each
#permutation as well as the respective p values and the normalized enrichment scores
for gene_set in gene_sets:
print('Analyzing the gene set: ' + gene_set[0])
#calculating the original enrichment score for a given gene set
enrichment_score = gf.calculate_es(ranked_list, gene_set)
#preparing a list to store the results of the permutations
null_hypotheses_scores = [[],[]]
for permutation in range(number_permutations):
#randomly permuting the phenotype labels, however the number of the samples for each phenotype is
#preserved
new_columns_1 = []
new_columns_2 = []
new_columns_1 = random.sample(range(1,len(header)), len(phenotype_1_columns))
for index in range(1,len(header)):
if index not in new_columns_1:
new_columns_2.append(index)
#ranking the gene expression profiles according to the new metric
permuted_ranked_list = gf.build_ranked_list(unranked_data, new_columns_1, new_columns_2)
#calculating the enrichment score for a given permutation
permuted_enrichment_score = gf.calculate_es(permuted_ranked_list, gene_set)
null_hypotheses_scores[0].append(max(permuted_enrichment_score[0]))
null_hypotheses_scores[1].append(max(permuted_enrichment_score[1]))
#calculating the pvalues for each phenotype based on the results of the permutations
pvalue_1 = stats.ttest_1samp(null_hypotheses_scores[0], max(enrichment_score[0]))
pvalue_2 = stats.ttest_1samp(null_hypotheses_scores[1], max(enrichment_score[1]))
#calculating the normalized enrichment scores based on the results of the permutations
normalized_es_1 = max(enrichment_score[0])/np.mean(null_hypotheses_scores[0])
normalized_es_2 = max(enrichment_score[1])/np.mean(null_hypotheses_scores[1])
#storing the data for later output
results_1.append([gene_set[0], normalized_es_1, pvalue_1[1]])
results_2.append([gene_set[0], normalized_es_2, pvalue_2[1]])
#sorting the data by the normalized enrichment score
sorted_results_1 = sorted(results_1, key=lambda x: x[1], reverse=True)
sorted_results_2 = sorted(results_2, key=lambda x: x[1], reverse=True)
#creating the output in form of 2 files, one for each phenotype
with open(phenotype_1 + '_output.txt', 'w') as output:
output.write('name of the gene set\tnormalized ES\tP-Value\n')
for row in sorted_results_1:
output.write(str(row[0]) + '\t' + str(row[1]) + '\t' + str(row[2]) + '\n')
with open(phenotype_2 + '_output.txt', 'w') as output:
output.write('name of the gene set\tnormalized ES\tP-Value\n')
for row in sorted_results_2:
output.write(str(row[0]) + '\t' + str(row[1]) + '\t' + str(row[2]) + '\n')
print('The calculation is completed.\nThank you for using the GSEA program!')
|
411b4158477752c54ec28d42df0f4e80bfb902eb | glourenco/DetectFraudAndPredictStockMarket | /HelloWorld/Lecture5/MultivalueVariables.py | 942 | 4.09375 | 4 | #Tupples
tuple1 = (1,2,3,4,5)
stringTuple = ("one","two","tree")
mixedTuple = ("one", tuple1, 3)
itemTuple = ("apple", 2, 3.5)
print(itemTuple)
print("lenght",len(itemTuple))
print("min",min(tuple1))
print("max",max(tuple1))
print("index 2 ",itemTuple.index("apple"))
#Arrays
grocList = ["eggs","milk","flour","butter"]
print(grocList)
print(grocList[1])
print(grocList[2:3])
grocList[1] = "baking soda"
print(grocList)
grocList.append("milk")
print(grocList)
grocList.insert(2,"sugar")
print(grocList)
grocList.remove("butter")
print(grocList)
del grocList[1]
print(grocList)
clothesList = ["tshirt","shorts","sunglasses"]
shoppingList = [grocList,clothesList]
print(shoppingList)
print(shoppingList[1][0])
#Dictionaries
listOfStudents = {0:"Lourenco",1:"Jill",2:"Harry",3:"lucy"}
print(listOfStudents)
print(listOfStudents[0])
listOfStudents[3] = "Tanya"
print(listOfStudents)
print(listOfStudents.keys())
print(listOfStudents.values())
|
b73441fed6deebc5913598aa784f3efd610dd5ce | C-Baird/PythonCustomer | /src/DataSource/editmenu.py | 769 | 4.09375 | 4 | def addmenu(name_item, price_pound = 0, price_pence = 0):
try:
price_pound = int(price_pound)
except ValueError:
print("a number is required here")
return
try:
price_pence = int(price_pence)
except ValueError:
print("a number is required here")
return
if len(str(price_pence)) == 1:
price_pence = "0" + str(price_pence)
newitem = name_item + "^" + str(price_pound) + "." + str(price_pence)
menu_file = open("resource\Entities\menu.txt", "a")
menu_file.write("\n"+ newitem)
menu_file.close
def addhelp():
print('To add an item to the menu type addmenu("name of item", pounds, pence) \n'
'an example of this would be additem(donut,1,50) to ad a donut at £1.50')
|
5387925674f561110379c6e5b98b34ce194fc28b | Natthapolmnc/Algorithm_Exercise | /quickSort/sort.py | 448 | 3.6875 | 4 | lst=[1,4,5,2]
def quickSort(lst,start,stop):
if(start<stop):
q=partition(lst,start,stop)
quickSort(lst,start,q-1)
quickSort(lst,q+1,stop)
def partition(lst,start,stop):
x=lst[stop]
i=start-1
for j in range(start,stop-1):
if lst[j]<=x:
i+=1
lst[j],lst[i]=lst[i],lst[j]
lst[i+1],lst[stop]=lst[stop],lst[i+1]
return i+1
quickSort(lst,0,len(lst)-1)
print (lst)
|
f1e67dd9fca8f9084416098d03f1b0fa0ec3f0ec | dimoka777/Time-in-Words | /time_words.py | 2,190 | 3.984375 | 4 | """ Hackerrank The Time in words Medium 25 Max Score
Input Format
The first line contains , the hours portion The second line contains , the minutes portion
Constraints
Output Format
Print the time in words as described.
Sample Input 0
5
47
Sample Output 0
thirteen minutes to six
"""
# Complete the timeInWords function below.
def timeInWords(h, m):
dictionary_time = {
'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight',
'9': 'nine', '10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'quarter',
'16': 'sixteen', '17': 'seventeen', '18': 'eighteen', '19': 'nineteen', '20': 'twenty', '21': 'twenty one',
'22': 'twenty two', '23': 'twenty three', '24': 'twenty four', '25': 'twenty five', '26': 'twenty six',
'27': 'twenty seven', '28': 'twenty eight', '29': 'twenty nine', '30': 'half', '0': 'zero'
}
minute_temp = m
if m > 30:
minute_temp = m - 30
hours = dictionary_time[str(h)]
minutes = dictionary_time[str(minute_temp)]
if m == 0:
addition = " o' clock"
res = hours + addition
return res
elif 1 <= m <= 30:
addition = "past"
if m != 30 and m != 1 and m != 15:
res = minutes + ' minutes ' + addition + ' ' + hours
return res
elif m == 1:
res = minutes + ' minute ' + addition + ' ' + hours
return res
else:
res = minutes + ' ' + addition + ' ' + hours
return res
elif m > 30:
m = abs(m - 60)
addition = "to"
minutes = dictionary_time[str(m)]
hours = dictionary_time[str(h + 1)]
if m != 15:
res = minutes + ' minutes ' + addition + ' ' + hours
return res
else:
res = minutes + ' ' + addition + ' ' + hours
return res
if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
h = int(input())
m = int(input())
result = timeInWords(h, m)
# fptr.write(result + '\n')
# fptr.close()
print(result) |
cf2e4033c9db5be4c93eded5ac9e35b9bc1909d4 | arushi-j/Hangman | /final_hangman_arushi.py | 5,191 | 3.90625 | 4 | import random
#List to store the Words and dictionary for hints as values
movie_list = ["the martian", "gravity", "interstellar", "trainwreck", "steve jobs", "inside out", "minions"]
movie_hint = {"the martian" : "Stuck on Mars", "gravity" : "Stars Sandra Bullock", "interstellar" : "Nolan Space Throry", "trainwreck" : "Amy Schumer", "steve jobs" : "mac", "inside out" : "what happens in our head?", "minions" : "cute yellow creatures"}
animal_list = ["tiger", "monkey", "zebra", "unicorn", "donkey"]
animal_hint = {"tiger" : "yellow", "monkey" : "imitators", "zebra" : "crossing", "unicorn" : "magic", "donkey" : "stupid"}
tv_list = ["breaking bad", "sherlock", "criminal minds", "narcos", "daredevil"]
tv_hint = {"breaking bad" : "meth", "sherlock" : "mystery", "criminal minds" : "serial killers", "narcos" : "new drug show", "daredevil" : "blind"}
geek_list = ["darth vader", "coding", "gadgets", "gandalf", "heisenberg"]
geek_hint = {"darth vader" : "star trek" , "coding" : "we love it", "gadgets" : "tech stuff" , "gandalf" : "Sauron's enemy", "heisenberg" : "quantum mechanics"}
#Asks User to enter a category choice
user_input = raw_input("Enter your choice 1 - Movies, 2 - Animals, 3 - TV series, 4 - Geek Stuff : ")
if (user_input == "1"):
hangman_words = random.choice(movie_list) #Randomly selecting the movie
hangman_index = movie_list.index(hangman_words) #Finding the index of the movie selected
hint = movie_hint[hangman_words]
elif (user_input == "2"):
hangman_words = random.choice(animal_list)
hangman_index = animal_list.index(hangman_words)
hint = animal_hint[hangman_words]
elif (user_input == "3"):
hangman_words = random.choice(tv_list)
hangman_index = tv_list.index(hangman_words)
hint = tv_hint[hangman_words]
elif (user_input == "4"):
hangman_words = random.choice(geek_list)
hangman_index = geek_list.index(hangman_words)
hint = geek_hint[hangman_words]
else:
print "Invalid Input"
#Stages of hangman in ASCII art
hangman_stage = ['''
+---+
|
|
|
|
|
=========''','''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
hangman_list= list(hangman_words) #Converting the string into a list
blank_list = list(hangman_words) #for blanks
gameIsDone = False
print "H A N G M A N"
print "Hint : " , hint
incorrect_guessed_letters = []
incorrect_guess = 0
correct_guessed_letters = []
correct_guess=0
blanks_check = len(hangman_words) #for number of characters
c=0 #counter
#Assigns '/' to spaces and '_' to strings and stores in blank_list
for i in range (len(blank_list)):
if (blank_list[i] == ' '):
c +=1 #counts the number of spaces
blank_list[i] = ' / '
else:
blank_list[i] = '_'
print ' '.join(blank_list) #Prints the hangman word in secret
blanks_check = blanks_check - c #Number of character in word excluding the space
print "Number of Characters ", blanks_check
while (gameIsDone != True): #runs till the game is complete
letter = raw_input("Enter a letter : ") #Makes the user input a letter
letter = letter.lower() #converts the letter to lower case
if (len(letter) != 1): #checks the user enters a single letter
print ("Enter a single letter ")
elif (letter in correct_guessed_letters): #ensures that the user doesnt enter the same letter twice
print ("You have already guessed that. Choose again. ")
elif (letter not in 'abcdefghijklmnopqrstuvwxyz'): #ensures that the user enters only a letter
print ("Please enter a letter. ")
if (letter not in hangman_words):
incorrect_guessed_letters.append(letter) #adds incorrect guesses to list
incorrect_guess += 1
print hangman_stage[incorrect_guess] #displays hangman ASCII art according to stage
print "Oh no!, Wrong guess! "
print "Incorrect Guesses : ", ','.join(incorrect_guessed_letters)
if (len(incorrect_guessed_letters) == len(hangman_stage)-1): #checks wrong guesses
print "You have run out of guesses! You lose."
print "The secret word was : ", hangman_words
gameIsDone = True #breaks out of while loop. Ends the game
else:
gameIsDone = False #goes down the while loop
elif (letter in hangman_words):
correct_guessed_letters.append(letter) #adds correct guesses to list
#Checks for user input in the word
for i in range (len(hangman_list)):
if (letter == hangman_list[i]):
blank_list[i] = letter #replaces the blank with the correct guessed letter
print ' '.join(blank_list) #prints progress
if blank_list.count('_') == 0: #checks whether the user has guessed all the letters
print ("You win!")
print "The secret word is ", hangman_words
gameIsDone = True
quit() #leaves the loop. finishs game
else:
gameIsDone = False
else:
gameIsDone = False
|
08776ad73d47bce8f11afafa0c13cce17ab24267 | hj24/Fluent-Python-example-code | /chapter 7/7_1_2.py | 621 | 3.59375 | 4 | """
一个简单的例子
"""
def deco(func):
def inner():
print('running inner()')
return inner
@deco
def target():
print('running target()')
target()
"""
装饰器在被装饰的函数定义之后就立即执行
"""
registry = []
def register(func):
print(f'running register({func})')
registry.append(func)
return func
@register
def f1():
print('running f1()')
@register
def f2():
print('running f2()')
def f3():
print('running f3()')
def f4():
print('running f4()')
def main():
print('running main()')
print(f'registry -> {registry}')
f1()
f2()
f3()
f4()
if __name__ == '__main__':
main() |
05172f7f712177a2f1be98bd0af8d8e285b9ac6b | nat-chan/TDD_RedGreenRefactor | /fizzbuzz/test_fizzbuzz.py | 1,263 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import *
from fizzbuzz import FizzBuzz
import unittest
class TestFizzBuzz(unittest.TestCase):
def test_出力はstrである(self):
self.assertEqual(str, type(FizzBuzz.single_line_answer(1)))
def test_数値の1を渡したら文字列の1を返す(self):
self.assertEqual("1", FizzBuzz.single_line_answer(1))
def test_数値の2を渡したら文字列の2を返す(self):
self.assertEqual("2", FizzBuzz.single_line_answer(2))
def test_intの3を渡したら文字列Fizzを返す(self):
self.assertEqual("Fizz", FizzBuzz.single_line_answer(3))
def test_intの6を渡したら文字列Fizzを返す(self):
self.assertEqual("Fizz", FizzBuzz.single_line_answer(6))
def test_intの5を渡したら文字列Buzzを返す(self):
self.assertEqual("Buzz", FizzBuzz.single_line_answer(5))
def test_intの10を渡したら文字列Buzzを返す(self):
self.assertEqual("Buzz", FizzBuzz.single_line_answer(10))
def test_intの15を渡したら文字列FizzBuzzを返す(self):
self.assertEqual("FizzBuzz", FizzBuzz.single_line_answer(15))
if __name__ == '__main__':
unittest.main() # pragma: no cover
|
Subsets and Splits