blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0622a8a418e06b920759274259881fb2a4781b8d | MrRickSan/python3bootcamp | /section22 - modules/exercise74 - iskeyword.py | 229 | 3.8125 | 4 | from keyword import iskeyword
def contains_keyword(*args):
for x in args:
if iskeyword(x) == True: return True
return False
print(contains_keyword('rick', 'test'))
print(contains_keyword('rick', 'test', 'def')) |
2432f1c5e46507b0468abe8d9d53d48332e40273 | yfeng2018/IntroPython2016a | /students/JohnRudolph/session3/rot13.py | 1,528 | 4.40625 | 4 |
def getnumref(let):
'''
This function accepts any ASCII character
Function to create ASCII reference for ROT13 encryption
First if checks if letter is Upcase A-Z and performs ROT13
Second if checks if letter is Lowcase a-z and performs ROT13
If not Upcase or Lowcase A-Z or a-z then retain ordinal of character
'''
if ord("A") <= ord(let) <= ord('Z'): # nice use of ord!
if ord(let) + 13 <= ord('Z'):
return ord(let) + 13
else:
return ord(let) - ord('Z') + ord('A') +12
elif ord('a') <= ord(let) <= ord('z'):
if ord(let) + 13 <= ord('z'):
return ord(let) + 13
else:
return ord(let) - ord('z') + ord('a') + 12
else:
return ord(let)
def rot13(string):
'''
This function accepts a string arguement and loops through each character in string
Each character string is passed to getnumref function for ROT13 encryption
Each ROT13 encrypted character is appended to list and joined to create string
'''
str_container = []
for let in string:
str_container.append(chr(getnumref(let)))
s = ''.join(str_container)
return s
if __name__ == '__main__':
print('Zntargvp sebz bhgfvqr arne pbeare', 'ROT13: ',
rot13('Zntargvp sebz bhgfvqr arne pbeare'))
print('Blajhkajhds!!! *&^*&^*^POP', 'ROT13: ',
rot13('Blajhkajhds!!! *&^*&^*^POP'))
print('1111 22222 AAAA ZZZZ aaa zzzzz', 'ROT13: ',
rot13('1111 22222 AAAA ZZZZ aaa zzzzz'))
print('abcdefghijklmnopqrstuvwxyz', 'ROT13: ',
rot13('abcdefghijklmnopqrstuvwxyz'))
print('lmnop LMNOP', 'ROT13: ',
rot13('lmnop LMNOP'))
|
ebb8c38815ff77757aadc8887155c04b6fa5ef8c | orbardugo/English_Exams_System | /src/Student.py | 5,516 | 3.78125 | 4 | import json
import os
import random
import time
class Student(object):
def __init__(self, name, ident):
self.name = name
self.ident = ident
self.correct_ans_counter = 0
def train(self):
""" train function will gives you all types of questions, when you answer you will receive if your answer correct or not """
print("Welcome to train mode, here you'll get feedback after each question..\nLets begin!(type exit in any time to stop training)\n")
train_file = open_file("train_data", "train")
suffle_q = train_file['questions']
random.shuffle(suffle_q)
for question in suffle_q:
q_type = question['type']
if q_type == 1: #Completion of sentence
print("Write the following word in english:")
ans = input(question['q'] + "\nIn english: ")
if ans == "exit":
return
self.check_train_ans(ans, question['a'])
else: # dictation
ans_option_list = []
for option in question['a']:
ans_option_list.append(option)
random.shuffle(ans_option_list)
print("Chose the missing word to complete the sentence (1-4):\n" + question['q'])
for index, a in enumerate(ans_option_list):
print("{}. {}".format(index + 1, a))
ans = None
while ans is None:
try:
ans = input("your choice is: ")
if ans == "exit":
return
ans = int(ans)
except ValueError:
print("please enter number from the range 1-4")
ans = None
if ans != None and ans not in range(1, 5):
ans = None
self.check_train_ans(ans_option_list[ans - 1], question['a'][0])
def exam(self):
""" exam function, you need to choose exam, when you finish the exam you will get report with your grade"""
print("Choose exam from the list and enter his name:")
for root, dirs, files in os.walk("./Exams"):
for i, filename in enumerate(files):
print("{}.\t{}".format(i+1, filename[:-5]))
choose = input()
exam = None
while exam is None:
try:
exam = open_file(choose, "exam")
except FileNotFoundError:
choose = input("Wrong file name, please enter again the file name\n")
res_file = open("./checked_exams/"+choose+"-"+self.name+".txt", "w+", encoding='utf-8')
res_file.write("{}\nStudent name: {}\nStudent ID: {}\n".format(time.strftime("%d/%m/%Y %H:%M:%S"), self.name, self.ident))
for question in exam['questions']:
q_type = question['type']
if q_type == 1:
print("Write the following word in english:")
ans = input(question['q']+"\nIn english: ")
self.check_and_write_ans(question['q'], ans, question['a'], res_file)
else: # dictation
ans_option_list = []
for option in question['a']:
ans_option_list.append(option)
random.shuffle(ans_option_list)
print("Chose the missing word to complete the sentence (1-4):\n"+question['q'])
for index, a in enumerate(ans_option_list):
print("{}. {}".format(index+1, a))
ans = None
while ans is None:
try:
ans = input("your choice is: ")
ans = int(ans)
except ValueError:
print("please enter number from the range 1-4")
ans = None
if ans != None and ans not in range(1,5):
ans = None
self.check_and_write_ans(question['q'], ans_option_list[ans-1], question['a'][0], res_file)
res_file.write("Your final grade: "+ str(int((100/len(exam['questions']))*self.correct_ans_counter)))
res_file.close()
file = "cd ./checked_exams & notepad.exe "+choose+"-"+self.name+".txt"
os.system(file)
def check_and_write_ans(self, question, student_ans, correct_ans, res_file):
""" The function checking the answer and build the outpot file """
if student_ans != correct_ans:
res_file.write(
"question: '{}', Your answer: {}, Correct answer: {} X\n".format(question, student_ans, correct_ans))
else:
res_file.write(
"question: '{}', Your answer: {}, Correct answer: {} √\n".format(question, student_ans, correct_ans))
self.correct_ans_counter += 1
def check_train_ans(self, student_ans, correct_ans):
if student_ans != correct_ans:
print("WRONG!(X) - The correct answer is: "+ correct_ans + "\n")
else:
print("CORRECT!(√)\n")
def open_file(file_name, flag):
if(flag == "exam"):
with open("./Exams/"+file_name+".json", 'r', encoding="utf-8") as json_file:
data = json.load(json_file, encoding='utf-8')
else:
with open("./"+file_name+".json", 'r', encoding="utf-8") as json_file:
data = json.load(json_file, encoding='utf-8')
return data |
0157fc50a376f4c79e3d37b041b85499a8d1db8f | ball4410/python-challenge | /PyPoll/main.py | 2,193 | 3.703125 | 4 | #Modules
import os
import csv
import pandas as pd
# Get data file needed for analysis
election_data_path = "./Resources/election_data.csv"
#Store data into a pandas data frame
election_file_df = pd.read_csv(election_data_path)
#Create variables to store values needed for summary
total_votes = 0
khan_votes = 0
correy_votes = 0
li_votes = 0
tooley_votes = 0
#Get unique candidate names
candidates = [election_file_df["Candidate"].unique()]
# Open the file above and store contents
with open(election_data_path) as pollfile:
csvreader = csv.reader(pollfile, delimiter=",")
#The file has a header row so store this seperately from the data
csv_header = next(csvreader)
for row in csvreader:
total_votes = total_votes + 1
if row[2] == 'Khan':
khan_votes = khan_votes + 1
elif(row[2] == 'Correy'):
correy_votes = correy_votes + 1
elif(row[2] == 'Li'):
li_votes = li_votes + 1
elif(row[2] == "O'Tooley"):
tooley_votes = tooley_votes + 1
#Store unique candidates and total votes in a new data frame
summary_df = pd.DataFrame({"Candidates": ["Khan", "Correy", "Li", "O'Tooley"],
"Total_Votes": [khan_votes, correy_votes, li_votes, tooley_votes]})
#Format percentages
khan_percentage = "{:.3%}".format(khan_votes/total_votes)
correy_percentage = "{:.3%}".format(correy_votes/total_votes)
li_percentage = "{:.3%}".format(li_votes/total_votes)
tooley_percentage = "{:.3%}".format(tooley_votes/total_votes)
#Find the max number of votes
most_votes = summary_df["Total_Votes"].max()
#Find the name of the candidate with the max votes
get_winner = summary_df.loc[summary_df["Total_Votes"] == most_votes, [
"Candidates"]]
winner = get_winner["Candidates"]
#Print summary
print("Election Results")
print("-----------------")
print(f"Total Votes: {total_votes}")
print("-----------------")
print(f"Khan {khan_percentage} ({khan_votes})")
print(f"Correy {correy_percentage} ({correy_votes})")
print(f"Li {li_percentage} ({li_votes})")
print(f"O'Tooley {tooley_percentage} ({tooley_votes})")
print("-----------------")
print(f"Winner {winner}") |
1dc5bc5308f74ca53aaf21d890db45fe21650a15 | RapetiBhargav/datascience | /2019-may/1.python/11.functional-style.py | 1,130 | 4.34375 | 4 | #functions are first class objects i.e., they can be used like other data objects
funcs = [sum, len, type]
for func in funcs:
print(func(range(1,5)))
#anonymous functions: functions without name
funcs = [lambda x: x, lambda x: x**2, lambda x: x**3]
for func in funcs:
print(func(10))
#higher order functions: functions that accepts function as argument
def f(a, b, g):
return g(a, b)
f(1, 2, lambda x, y: x + y)
f(1, 2, lambda x, y: x * y)
#functions returning other functions
def f(a):
def g(x):
return a + x
return g
g = f(3)
g(5)
#some built-in higher order functions in python
x = map(lambda x: x**2, range(4))
print(type(x))
print(list(x))
def square(x):
return x*x
y = list( map(square, range(1, 10)) )
print(y)
z = filter(lambda x: x % 2 == 0, range(4))
print(list(z))
from functools import reduce
import numpy as np
reduce(lambda x, y: x + y, range(1, 5) )
reduce(lambda x, y: x + y, range(1, 10) )
reduce(lambda xs, ys: xs + ys, [[1,2], [3,4], [5,6]])
reduce(lambda xs, ys: xs + ys, [np.array([1,2]), np.array([3,4]), np.array([5,6])])
|
5575451c70757bc7b7f7178b11044a61ae9a45d7 | jaxmandev/Python_JSON_Task | /exchange.py | 1,038 | 3.96875 | 4 | # the json module is imported
# to handle a .json file
import json
# class created and methods initiated
class Currency:
def __init__(self):
self.xchange_rates = self.load_dic()
self.display_basic_info()
self.display_rates()
# store .json file data in a python object
def load_dic(self):
with open("exchange_rate.json", "r") as x:
loaded_dic = json.load(x)
return loaded_dic
# iterate and displ the date and base currency
def display_basic_info(self):
for key, value in self.xchange_rates.items():
if key == "date":
print(f"{key}: {value}")
elif key == "base":
print(f"{key}: {value}")
else:
pass
# iterate and display through the nested dictionary
# containing country code and rates
def display_rates(self):
for key, value in self.xchange_rates["rates"].items():
print(f"{key}: {value}")
# instabtiate the class
Currency() |
37c1a27d7f088d992759f80df681c6cbcea2b067 | subahan983/Basic-programs-in-python | /Multiply.py | 171 | 4.375 | 4 | # In this program, the product of two numbers is found.
num1 = int(input('Enter any number : '))
num2 = int(input('Enter any number : '))
print('Product = ',num1*num2)
|
059b7d3225a615c54bb30459130fa7ad17f66d17 | czhhhhhhh/pythonchenzehua | /day1.py | 3,242 | 3.90625 | 4 | # email = '666@qq.com'
# for e in email:
# o = ord(e)-10
# print(chr(o),end='')
# year = int(input('请输入一个年份:'))
## if (year % 4 == 0 and year % 100 !=0) or (year % 400 == 0):
# print ('%d 是闰年' %year)
# else:
# print ('%d 不是闰年' %year)
#作业1
# C = float(input('请输入一个摄氏温度:'))
# F = 1.8*C +32
# print('华氏温度:%f'%F)
#2
# import math
# π = math.pi
# r = float(input('输入圆柱体的半径'))
# h = float(input('输入圆柱体的高'))
# area = r * r * π
# volume= area * h
# print('the area is %.4f'%area)
# print('the volume is %.1f '%volume)
#3
# feet = float(input('输入一个英尺:'))
# meters=feet/0.305
# print('%.1f feet is %.4f meters'%(feet,meters))
#4
# kg = float(input('输入水的重量(kg):'))
# IT = float(input('输入水的初始温度:'))
# FT = float(input('输入水的最终温度:'))
# Q = kg * (FT - IT)*4184
# print('能量为%.1f'%Q)
#5
# c=float(input('输入差额'))
# n=float(input('输入年利率'))
# l=c*(n/1200)
# print('输出利息为%.6f'%l)
#6
# v0=float(input('输入v0'))
# v1=float(input('输入v1'))
# t=float(input('输入时间t'))
# a=(v1-v0)/t
# print('输出平均加速度a%.4f'%a)
#7
# money = float(input('请输入每个月存款数'))
# a = money * ( 1 + 0.00417)
# b = ( a + money) * ( 1 + 0.00417)
# c = ( b + money) * ( 1 + 0.00417)
# d = ( c + money) * ( 1 + 0.00417)
# e = ( d + money) * ( 1 + 0.00417)
# f = ( e + money) * ( 1 + 0.00417)
# print('六个月后账户余额为',f)
# n=float(input('请输入每月存款数:'))
# m=1
# a=n*1.00417
# print(a)
# while m<=5:
# a=(a+100)*1.00417
# m+=1
# print('六个月后的账户总额:', a)
#8
# number = int (input('请输入0到1000的数字:'))
# bai = number//100
# shi = number//10%10
# ge = number%10
# sum_ = bai + shi + ge
# print('the sum of the digits is:%d'%sum_)
#9
# import math
# π = math.pi
# tan = math.tan
# sin = math.sin
# r = float(input('输入五边形定点到中心的距离:'))
# s = 2 * r *sin (π /5)
# area = 5 * s * s /(4*tan(π/5))
# print('五边形的面积:%.2f'%area)
#10
# import math
# π = math.pi
# tan = math.tan
# s = float(input('输入五角形的边'))
# area = 5 * s * s/(4 * tan(π/5))
# print('五角形的面积为:%f'%area)
#11
# import math
# π = math.pi
# tan = math.tan
# s = float(input('输入边长:'))
# n = int(input('输入边数:'))
# area = n * s * s/(4 * tan(π/n))
# print('正多边形的面积为:%f'%area)
#12
# a = int(input('请输入一个数:'))
# b = chr(a)
# print ('输出的字符:%s'%b)
#13
# name = str(input('请输入姓名:'))
# hours = float(input('一周工作时间:'))
# pay = float (input('每小时报酬:'))
# tax = float (input('联邦预扣税率'))
# a_tax = (input('州预扣税率'))
# print ('雇员名字:%s'%name)
# print('工作小时:%f'%hours)
# print('每小时报酬:%f'%tax)
#14
# number = str(input('请输入一个数:'))
# print(number [::-1])
|
75254e830a3eb1443aef2491b3ac494401d1d008 | nr96/WebSearch | /WebSearch.py | 2,082 | 3.625 | 4 | import requests
def main():
splitTxt = [] # list to hold parsed txt from webpage
keyHist = [] # list to hold keyword history
page = '' # var to hold webpage url
page = getWebpage(page) # get webpage url and store in page
txt = parseWebpage(page) # parse webpage content into txt
splitTxt = splitPage(txt, splitTxt) # split webpage txt from str to list
keywordSearch(txt, page, keyHist) # search txt for keyword
while True: # continuosly ask until user wants to quit
getChoice(txt, page, keyHist) # ask user what they wish to do next
def splitPage(txt, splitTxt):
splitTxt = txt.split('<') # split txt using '<' as delimeter
return splitTxt # return list to main function
def getChoice(txt, page, keyHist):
print("\nDo you wish to 1) enter a new webpage 2) enter a new keyword 3) exit")
choice = input("Please enter '1','2', or '3': ") # get choice from user
if choice == '1':
getWebpage() # user wishes to search new webpage
keywordSearch(txt, page, keyHist) # get new keyword from user
if choice == '2':
keywordSearch(txt, page, keyHist) # user wishes to enter new keyword on same webpage
if choice == '3':
print("exiting program...") # user wishes to exit program
exit()
def getKeywordCount(txt,key):
txt = txt.upper() # eliminate str casing variability for ease of counting
count = txt.count(key.upper()) # search txt for keyword
return count
def keywordSearch(txt, page, keyHist):
key = input("Please enter a keyword to search for: ") # get keyword from user
keyHist.append(key)
count = getKeywordCount(txt,key) # get count from txt
print("Keyword '" + key + "' appears " + str(count) + " times in " + str(page))
def getWebpage(page):
page = input("Please enter a webpage url: ") # get url from user
while "https://" not in page: # make sure a complete url is entered
page = input("Please enter complete url i.e 'https://...' : ")
return page
def parseWebpage(page):
#page = getWebpage(page)
response = requests.get(page) # get info from webpage
txt = response.text # turn webpage content into text
return txt
main()
|
af9d0977a048859c9698f1c3cbffbe9de37f5121 | gustavw10/pythonaflevering | /utils.py | 1,005 | 3.75 | 4 |
import os
import csv
def get_file_names(folderpath, out="output.txt"):
""" takes a path to a folder and writes all filenames in the folder to a specified output file"""
files = os.listdir(folderpath)
with open(out, 'w') as output_file:
for file in files:
output_file.write(file + '\n')
def print_line_one(file_names):
"""takes a list of filenames and print the first line of each"""
for file_name in file_names:
with open(file_name, "r") as f:
for line in f:
print(line)
break
def print_emails(file_names):
"""takes a list of filenames and print each line that contains an email (just look for @)"""
for file_name in file_names:
with open(file_name, "r") as f:
for line in f:
print(line)
break
# def write_headlines(md_files, out=output.txt):
# """takes a list of md files and writes all headlines (lines starting with #) to a file""" |
da8ddd51f04168591d75f04eb95b3e9c52666237 | jarelio/FUP | /Lista 1/1a.py | 201 | 4 | 4 | nota1 = float(input("Digite o primeiro número: "))
nota2 = float(input("Digite o segundo número: "))
media = (nota1*2 + nota2*3)/5
print("A média ponderada desses dois números é %.3f" %media)
|
5df8c7162f9f8344c1887f95dc6aa5db932eeed9 | ogoshi2000/smile | /crazysmiley2/crazysmiley2.pyde | 2,016 | 3.578125 | 4 | def setup():
size(400,400)
frameRate(10)
fullScreen()
number=100
radius=300
circle_size=50
max_circle=80
def draw():
global number,radius,circle_size,max_circle
g=(frameCount%max_circle)
if g < max_circle/2:
circle_size=g
else:
circle_size=max_circle-g
k=frameCount%number
if k < number/2:
j=k
else:
j=number-k
#background(random(125),random(125),random(125))
background(0)
f=frameCount%100
x3=sin(2*PI/100-f)
y3=cos(2*PI/100-f)*50
x4=-sin(-2*PI/100-f)*50
y4=-cos(2*PI/100-f)*50
x5=sin(2*PI/100-f)
y5=cos(2*PI/100-f)
fill(random(255),random(255),random(255),random(200,255))
circle(radius*2+random(-5,5),radius*1.5+random(-5,5),radius/2*PI)
fill(random(255),random(255),random(255),random(200,255))
eyesize=random((radius/2*PI)*0.125,(radius/2*PI)*0.25)
circle(radius*2-radius*0.4,radius*1.5,eyesize)
circle(radius*2+radius*0.4,radius*1.5,eyesize)
fill(0)
pupille=random((radius/2*PI)*0.125)
circle(radius*2+radius*0.4,radius*1.5,pupille)
circle(radius*2-radius*0.4,radius*1.5,pupille)
strokeWeight(random(50))
stroke(0)
line(radius*2-radius*0.4,radius*1.5+radius*0.4,radius*2+radius*0.4,radius*1.5+radius*0.4)
noStroke()
for i in range(0,j):
x=(2*PI/j*i)
x2=(2*PI/j*i)
radius2=radius*1.25
radius3=radius*1.5
noStroke()
fill(random(255),random(255),random(255),random(200,255))
circle(sin(x)*radius+radius*2,cos(x)*radius+radius*1.5,random(circle_size/2,circle_size))
fill(random(255),random(255),random(255),random(200,255))
circle(cos(x2)*radius2+radius*2,sin(x2)*radius2+radius*1.5,random(circle_size/2,circle_size*1.25))
fill(random(255),random(255),random(255),random(200,255))
circle(sin(x2)*radius3+radius*2,cos(x2)*radius3+radius*1.5,random(circle_size/2,circle_size*1.5))
|
1a77b99766e725e3b40c5c4c2ea13f31aa98413a | alexparunov/leetcode_solutions | /src/1-100/_96_unique-binary-search-trees.py | 370 | 3.546875 | 4 | """
https://leetcode.com/problems/unique-binary-search-trees/
"""
class Solution:
def numTrees(self, n: int) -> int:
# Calculate N-th Catalan Number
cat = [0] * (n + 1)
cat[0] = 1
cat[1] = 1
for i in range(2, n + 1):
for j in range(i):
cat[i] += cat[j] * cat[i - j - 1]
return cat[n]
|
05ddbd71a0244f9a2b1af78697f19221712ad097 | poohcid/class | /PSIT/170.py | 965 | 3.671875 | 4 | """ OTP """
def main():
""" OTP """
otp = input()
while otp != "0":
check = list(map(lambda x: otp.count(x), set(otp)))
if len(otp) == 4:
print("Valid" if verified(2, 1, list(check)) else "Invalid")
elif len(otp) == 6:
if verified(2, 2, list(check)):
print("Valid")
elif verified(3, 1, list(check)):
print("Valid")
else:
print("Invalid")
elif len(otp) == 8:
if verified(3, 2, list(check)):
print("Valid")
elif verified(2, 3, list(check)):
print("Valid")
else:
print("Invalid")
otp = input()
def verified(count, many, lst):
"""return verified"""
check = 0
for _ in range(many):
if count in lst:
lst.remove(count)
check += 1
return 1 if set(lst) == {1} and check == many else 0
main()
|
fad2243b7117d7956d43af65aa01b6b1f5b95637 | HOZH/leetCode | /leetCodePython2020/2265.count-nodes-equal-to-average-of-subtree.py | 856 | 3.515625 | 4 | #
# @lc app=leetcode id=2265 lang=python3
#
# [2265] Count Nodes Equal to Average of Subtree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
self.ans = 0
def helper(node):
if not node:
return 0, 0
left, right = helper(node.left), helper(node.right)
sub_tree_sum = (node.val+left[0]+right[0])
sub_tree_count = (1+left[1]+right[1])
if node.val == sub_tree_sum//sub_tree_count:
self.ans += 1
return sub_tree_sum, sub_tree_count
helper(root)
return self.ans
# @lc code=end
|
a527be8f0092e5e5cbed876c2264b750373dc737 | Eloquade/Python_zip_function | /main.py | 779 | 3.953125 | 4 | list1 = [1, 2, 3, 4, 5, 6]
list2 = ['one', 'two', 'three', 'four', 'five', 'six']
zipped = list(zip(list1, list2))
print(zipped)
unzipped = list(zip(*zipped))
print(unzipped)
for l1, l2 in zip(list1, list2):
print(l1)
print(l2)
items = ['apple', 'banana', 'grapes']
quantity = ['1', '2', '3']
prices = ['123', '312', '354']
sentences = []
for (items, quantity, prices) in zip(items, quantity, prices):
items, quantity, prices = str(items), str(quantity), str(prices)
sentence = 'i bought ' + quantity + ' ' + items + 's at ' + prices + '.'
sentences.append(sentence)
print(sentences)
# for i1, q1, p1 in zip(items, quantity, prices):
# # print(i1, q1, p1)
# # print(items, quantity, prices)
# print(i1)
# print(q1)
# print(p1)
|
32a2f8c08363a9ce97f48e0c3741d54bec0c9150 | liyi-1989/neu_ml | /code/data/data_collector.py | 9,874 | 3.8125 | 4 | import pdb
import numpy as np
class DataCollector:
"""Data collection class used to record data during algorithm execution for
subsequent analysis.
There are three concepts used by this class: 'trial', 'run', and
'iteration'. A 'trial' exists at the level of a particular algorithm
execution and corresponds to a given set of algorithm parameter settings,
e.g. A 'run' is a particular execution of a 'trial'. It's assumed that
generally you will get different data for a given trial, even for the same
input data (consider random initializations, for example). Finally, an
'iteration' corresponds to the data at a particular iteration of algorithm
execution.
As an example, K-means run with K=2 and K=3 represent two different trials.
K-means run five times with K=2 represents five runs of the K=2 trial. The
cluster assignments at iteration 3, for run two, and trial K=2 represent
data at a specific iteration for a given run and trial.
You may be interested in running an algorithm several times for different
parameter settings. An instance of this class will facilitate data
recording.
Before you collect any data, you must first call 'add_new_trial' to begin a
new data collection trial.
"""
def __init__(self):
self._cluster_assignments = []
self._trial_descriptions = []
def set_cluster_assignments(self, assignments, trial=0, run=0,
iteration=0):
"""Set cluster assigments for a given trial, run, and iteration.
Parameters
----------
assignments : array, shape ( n_instances )
An array of integer values indicating cluster assignments.
trial : integer, optional
Indicates which trial 'assignments' corresponds to. The first trial
is indexed at 0, the second at 1, etc.
run : integer, optional
Indicates which run 'assignments' corresponds to. The first run
is indexed at 0, the second at 1, etc.
iteration : integer, optional
Indicates which iteration 'assignments' corresponds to. The first
iteration is indexed at 0, the second at 1, etc.
"""
if trial >= self.get_num_trials():
raise ValueError("Trial does not exist")
if run >= self.get_num_runs(trial):
raise ValueError("Run does not exist")
if iteration >= self.get_num_iterations(trial, run):
raise ValueError("Iteration does not exist")
self._cluster_assignments[trial][run][iteration] = assignments
def add_new_trial(self):
"""Add a new trial to the data collector
"""
self._cluster_assignments.append([])
# Also append a blank description of this trial to the list of
# descriptions
self._trial_descriptions.append({})
def add_new_run(self, trial=0):
"""Add a new run for the specified trial.
Parameters
----------
trial : integer, optional
The trial for which to add the new run
"""
if trial >= self.get_num_trials:
raise ValueError("Requested trial does not exist")
self._cluster_assignments[trial].append([])
def add_new_iteration(self, trial=0, run=0):
"""Add a new iteration for the specified trial and run.
Parameters
----------
trial : integer, optional
The trial for which to add a new iteration
run : integer, optional
The run for which to add a new iteration
"""
if trial >= self.get_num_trials:
raise ValueError("Requested trial does not exist")
if run >= self.get_num_runs(trial):
raise ValueError("Requested run does not exist")
self._cluster_assignments[trial][run].append([])
def get_cluster_assignments(self, trial=0, run=0, iteration=0):
"""Get the cluster assignments for the specified trial, run, and,
iteration.
Parameters
----------
trial : integer, optional
An index indicating the trial number
run : integer, optional
An index indicating the run number
iteration : integer, optional
An index indicating the iteration number
Returns
-------
assignment : array, shape ( n_instances )
An array of indices indicatint cluster assignments for the
corresponding data instances.
"""
return self._cluster_assignments[trial][run][iteration]
def get_num_trials(self):
"""Get the number of stored trials.
Returns
-------
num_trials : integer
The number of stored trials.
"""
return len(self._cluster_assignments)
def get_num_runs(self, trial=0):
"""Get the number of stored runs for the specified trial.
Parameters
----------
trial : integer
An index indicating which trial to return the number of runs for
Returns
-------
num_runs : integer
The number of stored runs for the specified trial.
"""
if trial >= self.get_num_trials():
raise ValueError("Requested trial does not exist")
return len(self._cluster_assignments[trial])
def get_num_iterations(self, trial=0, run=0):
"""Get the number of stored iterations for the specified trial and run
Parameters
----------
trial : integer
An index indicating which trial to return the number of iterations
for
run : integer
An index indicating which run to return the number of iterations
for
Returns
-------
num_iterations : integer
The number of stored iterations for the specified trial and run
"""
if trial >= self.get_num_trials():
raise ValueError("Requested trial does not exist")
if run >= self.get_num_runs(trial):
raise ValueError("Requested run does not exist")
return len(self._cluster_assignments[trial][run])
def set_trial_description(self, trial, description):
"""Set a description of the a specified trial.
This is useful for documenting the settings used to produce the data
for a given trial.
Parameters
----------
trial : integer
An index indicating the trial number
description : dictionary
A dictionary-based descripiton of a given trial. The dictionary
entries can change from trial to trial. The onus is on the user to
keep track of dictionary entries.
"""
num_trials = self.get_num_trials()
if trial >= num_trials:
raise ValueError("Trial does not exist")
self._trial_descriptions[trial] = description
def get_trial_description(self, trial):
"""Get the description for the specified trial.
This is useful for documenting the settings used to produce the data
for a given trial.
Parameters
----------
trial, integer
An index indicating the trial number
Returns
-------
description, dictionary
A dictionary-based descripiton of a given trial. The dictionary
entries can change from trial to trial. The onus is on the user to
keep track of dictionary entries.
"""
num_descriptions = len(self._trial_descriptions)
if trial > num_descriptions:
raise ValueError("Requested trial does not exist")
return self._trial_descriptions[trial]
def get_latest_cluster_assignment_trial(self):
"""Get the trial index corresponding the 'latest' cluster assignment
trial (the one assumed to be added most recently).
Returns
-------
trial, integer
Index of the latest cluster assignment trial
"""
trial = len(self._cluster_assignments)-1
return trial
def get_latest_cluster_assignment_run(self, trial):
"""Get the run index corresponding the 'latest' cluster assignment
run (the one assumed to be added most recently) for the specified trial.
Parameters
----------
trial, integer
Index indicating which trial to get the latest run for.
Returns
-------
run, integer
Index of the latest cluster assignment run for the specified trial
"""
num_trials = len(self._cluster_assignments)
if trial == num_trials:
raise ValueError("Specified trial does not exist")
run = len(self._cluster_assignments[trial])-1
return run
def get_latest_cluster_assignment_iteration(self, trial, run):
"""Get the run index corresponding the 'latest' cluster assignment
iteration (the one assumed to be added most recently) for the
specified trial and run.
Parameters
----------
trial, integer
Index indicating which trial to get the latest iteration for.
run, integer
Index indicating which run to get the latest iteration for.
Returns
-------
iteration, integer
Index of the latest cluster assignment iteration for the specified
trial and run
"""
if trial >= self.get_num_trials():
raise ValueError("Specified trial does not exist")
if run >= self.get_num_runs(trial):
raise ValueError("Specified run does not exist")
iteration = self.get_num_iterations(trial, run) - 1
return iteration
|
b579040e68768d3c6ecd65eeda9f53d886ed3f52 | thatnerd2/Algorithms-Data-Structures | /misc-practice/costly-chess/costlychess.py | 412 | 3.890625 | 4 | def costFcn (start, end):
return start[0]*end[0] + start[1]*end[1];
# Define P_px->py to be the minimum cost to get from start to end
# Define positions to be p1, p2, p3, p4, end
# P_p1->p2 is the minimum cost of P_p1->p2 + Pp3->end
# base case: P_p?->end is min(all eight possibilities)
def compute(p, end, cost):
if p[0] == end[0] and p[1] == end[1]:
return cost + costFcn(p, end);
elif
|
453912539d8c95d07b221613b0581249d3f98473 | melanieren/MoMA-analysis | /MoMA-data-analysis.py | 4,526 | 3.734375 | 4 | # Import libraries and data
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df_artworks = pd.read_csv('data/artworks.csv')
print(df_artworks.shape)
print(df_artworks.head())
df_artists = pd.read_csv('data/artists.csv')
print(df_artists.shape)
print(df_artists.head())
# 1. Artists with most pieces on display
# Count the number of pieces each artist has on display and show the top 20 artists
print(df_artworks['Name'].value_counts().head(20))
# Use matplotlib to create a bar graph to display the 20 artists with the most pieces on display
top_10_artists = df_artworks['Name'].value_counts()[:20]
top_10_artists.plot(kind='barh').invert_yaxis()
plt.ylabel('Artist')
plt.xlabel('Number of Pieces on Display')
plt.suptitle('Artists With the Most Pieces on Display at the MoMA', fontsize=14, fontweight='bold')
plt.show()
# 2. Proportion of male to female artists with pieces on display
# Find the proportion of male to female artists who have works on display at the MoMA
print(df_artists['Gender'].value_counts())
# Clean up missing values and capitalization inconsistencies in the artist data
df_artists['Gender'].replace('male', 'Male', inplace=True)
df_artists['Gender'].replace(np.nan, 'Unknown', inplace=True)
# Check that all artists have been accounted for
print(sum(df_artists['Gender'].value_counts()) == df_artists.shape[0])
# Graph the proportion of male to female artists
labels = df_artists['Gender'].value_counts().index
sizes = df_artists['Gender'].value_counts().values
colors = ['gold', 'lightcoral', 'lightskyblue']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False, startangle=140)
plt.axis('equal')
plt.suptitle('Artists with Pieces on Display at the MoMA', fontsize=14, fontweight='bold')
plt.show()
# 3. Artists by nationality
# Find the proportion of artists of each nationality
most_common_nationalities = df_artists['Nationality'].value_counts()[:20]
most_common_nationalities.plot(kind='barh').invert_yaxis()
plt.ylabel('Nationality')
plt.xlabel('Number of Artists')
plt.suptitle('Most Common Nationalities of the Artists on Display at the MoMA', fontsize=14, fontweight='bold')
plt.show()
# Classify the 20 most common nationalities of the artists by continent
df_artists['Continent'] = np.nan
north_america = ['American', 'Canadian', 'Mexican']
south_america = ['Brazilian', 'Argentine']
europe = ['German', 'French', 'British', 'Italian', 'Swiss', 'Dutch', 'Austrian',
'Russian', 'Spanish', 'Polish', 'Danish', 'Belgian']
asia = ['Japanese']
def classify_nationality(row_index) :
if df_artists.loc[row_index,'Nationality'] in north_america:
df_artists.loc[row_index, 'Continent'] = 'North America'
elif df_artists.loc[row_index,'Nationality'] in south_america:
df_artists.loc[row_index, 'Continent'] = 'South America'
elif df_artists.loc[row_index,'Nationality'] in europe:
df_artists.loc[row_index, 'Continent'] = 'Europe'
elif df_artists.loc[row_index,'Nationality'] in asia:
df_artists.loc[row_index, 'Continent'] = 'Asia'
elif (df_artists.loc[row_index,'Nationality'] == 'Nationality unknown') :
df_artists.loc[row_index, 'Continent'] = 'Unknown'
for index, row in df_artists.iterrows() :
classify_nationality(index)
# Graph the proportion of continents represented by the 20 most common nationalities of the artists at the MoMA
labels = df_artists['Continent'].value_counts().index
sizes = df_artists['Continent'].value_counts().values
colors = ['gold', 'lightcoral', 'lightskyblue', 'mediumslateblue', 'firebrick']
plt.pie(sizes, colors=colors, autopct='%1.1f%%', pctdistance=1.2, shadow=False, startangle=140)
plt.axis('equal')
plt.suptitle('Top 20 Most Common Artist Nationalities by Continent', fontsize=14, fontweight='bold')
plt.legend(labels,loc=4)
plt.show()
# 4. When were the pieces on display added to the collection at MoMA?
# Sort the artworks data by 'Acquisition Date'
df_artworks['Acquisition Date'] = pd.to_datetime(df_artworks['Acquisition Date'], errors='coerce')
acquisitions = df_artworks['Acquisition Date'].value_counts()
acquisitions_sorted = acquisitions.sort_index()
# Show the data as a time series
acquisitions_sorted_cumsum = acquisitions_sorted.cumsum()
ts = acquisitions_sorted_cumsum.plot()
ts.set_title('Total Number of Artworks Acquired by the MoMA Over Time', fontsize=14, fontweight='bold')
ts.set_xlabel("Year")
ts.set_ylabel("Total Number of Artworks Acquired")
|
ac50a6bc11e3457aa288c818563df86fce381b1c | z727354123/pyCharmTest | /2018-01/01_Jan/15/02-methodUse.py | 376 | 3.5 | 4 | class Person:
name = "lisi"
def func1(self):
print('这是一个 实例方法', self.age, self.name)
return self
@classmethod
def func2(cls):
print(cls.__bases__[0].name)
p1 = Person()
p1.age = 111
funcX = p1.func1
# funcX()
class Person2(Person):
name = "XXXXX"
pass
p2 = Person2()
p2.age = 222
p2.func1()
Person2.func2()
|
419840d793c856513954dbb8a1b10e6a49d0e06e | NachbarStrom/public-python-nachbarstrom-commons | /nachbarstrom/commons/world/roof.py | 1,943 | 3.53125 | 4 | from enum import Enum
import math
class RoofType(Enum):
flat = 0
gabled = 1
halfHipped = 2
hipped = 3
mansard = 4
pyramid = 5
round = 6
class RoofOrientation(Enum):
East = 0
SouthEast = 1
South = 2
SouthWest = 3
West = 4
class Roof:
def __init__(self, roof_type: RoofType, orientation: RoofOrientation,
area: float) -> None:
self._validate_input(roof_type, orientation, area)
self.type = roof_type
self.orientation = orientation
self.area = float(area)
@staticmethod
def _validate_input(roof_type, orientation, area):
assert roof_type is not None
assert orientation is not None
assert area is not None
assert isinstance(roof_type, RoofType)
assert isinstance(orientation, RoofOrientation)
area = float(area)
assert area >= 0
def serialize(self):
return {
"roofType": self.type.name,
"orientation": self.orientation.name,
"area": str(self.area)
}
@staticmethod
def from_dict(roof_details: dict):
"""
Deserialize a Roof from a dict of the form:
{
"area: "100.00"
"roofType": "hipped",
"orientation": "SouthEast",
}
:param roof_details: the dict with the details
:return: A Roof instance
"""
assert "area" in roof_details
assert "roofType" in roof_details
assert "orientation" in roof_details
return Roof(
roof_type=RoofType[roof_details["roofType"]],
orientation=RoofOrientation[roof_details["orientation"]],
area=roof_details["area"],
)
def __eq__(self, other):
return (self.type == other.type and
self.orientation == other.orientation and
math.isclose(self.area, other.area, rel_tol=1e-10))
|
af3945be1d356c3952c1566e5129ae41c780056e | longlee218/Python-Algorithm | /017_week2/17+2_too_long_words.py | 885 | 4.25 | 4 | """
Let's consider a word too long, if it length is strictly more than 10 characters. All too long worlds
should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them
we write a number of letters between the first and the last letters. That number is in decimal system and
doesn't contain any leading zeroes.
Thus, "localization" will spelt as "l10n" and "internationalization" as "i18n".
"""
def code():
n = 0
while n < 1 or n > 100:
n = int(input("Enter n: "))
string = []
for i in range(n):
string.append(input(""))
for i in range(n):
if len(string[i]) >= 10:
string[i] = string[i][0] + str(len(string[i])-2) + string[i][-1]
return "\n".join(string)
if __name__ == '__main__':
print(code())
|
bdc30567bd67fce78bc7dd3c6bb5e8a92ad0578b | Nandik-Aminur-Peer-Programming/CodechefProblems | /SpecialString.py | 1,932 | 3.75 | 4 | """You are given a string S and you want to make it (n,k) special.
String A is (n,k) special if after concatenating n copies of string
A we get at least k substring of A in the resulting string (Overlapping substrings also count).
Your task is to find the minimum number of characters you need to alter to make string S, (n,k) special.
Note : Inputs are given such that it is always possible to get at least k substrings"""
import math,sys,bisect,heapq,os
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
pr = lambda x: x
def input(): return sys.stdin.readline().rstrip('\r\n')
#input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
aj = lambda: list(map(int, input().split()))
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
def printDivisors(n) :
A=[]
i = 1
while i <= math.sqrt(n):
if (n % i == 0) :
if (n / i == i) :
A.append(i)
else :
A.append(i)
A.append(n//i)
i = i + 1
return A
def solve():
for _ in range(int(input())):
n,k = aj()
s = input()
if n >= k or k == 1 or len(set(s)) == 1:
print(0)
else:
def fun(l):
G = defaultdict(Counter)
for i in range(len(s)):
G[i%l][s[i]] += 1
count = 0
tot = len(s)//l
# pr(G)
# print(l)
for i in G.keys():
c = G[i].most_common(1)[0][1]
count += tot - c
return count
ans = 1e9
loop = (len(s)*(n-1))//(k-1)
d= printDivisors(len(s))
d.sort()
for l in d:
if l > loop:
break
temp = fun(l)
ans = min(ans,temp)
print(ans)
solve() |
076d7e8a94a314c3b999633d94a72683de7c61be | pravinmaske/TorontoPython | /a2.py | 2,599 | 4.28125 | 4 | def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
dna2.
>>> is_longer('ATCG', 'AT')
True
>>> is_longer('ATCG', 'ATCGGA')
False
"""
return len(dna1)>len(dna2)
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
return dna.count(nucleotide)
def contains_sequence(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False
"""
return dna2 in dna1
def is_valid_sequence(dna):
"""
(str) -> bool
Return True if and only if the DNA sequence is valid(i.e. it contains no characters other than 'A','C','T' and 'G')
>>>is_valid_sequence('AGCTA')
True
>>>is_valid_sequence('AFHDTC')
False
>>>is_valid_sequence('dasdACT')
False
"""
#return dna in 'AGTC'
sequence='AGTC'
var=True
for char in dna:
if char not in sequence:
var= False
return var
#if not sequence.find(char)
# var= False
def insert_sequence(dna1,dna2,index):
"""
(str,str,int) -> str
Returns the DNA sequence obtained by inserting the second into the
first DNA sequence at the given index
>>>insert_sequence(CCGG,AT,2)
'CCATGG'
>>>insert_sequence(CTAGG,TT,3)
'CTATTGG'
''
"""
return dna1[:index]+dna2+dna1[index:]
def get_complement(str1):
"""
(str)->str
Returns the nucleotide's complement.
>>>get_complement('ACGTACG')
'TGCATGC'
>>>get_complement('AAATTTGGGCCC')
'TTTAAACCCGGG'
"""
''' if not is_valid_sequence(str1):
return False
if not get_length(str1) == 1:
return False
'''
str2=''
for char in str1:
if char =='T':
str2=str2+'A'
elif char =='A':
str2=str2+'T'
elif char =='C':
str2=str2+'G'
elif char =='G':
str2=str2+'C'
return str2
def get_complementary_sequence(dna):
if not is_valid_sequence(dna):
return False
out=''
for char in dna:
out= out+ get_complement(char)
return out
|
9473922c20a57bc5868f4c2bae76bbf3f134ee7f | szabgab/slides | /python/examples/format/formatted_float.py | 575 | 3.71875 | 4 | x = 412.345678901
print("{:e}".format(x)) # exponent: 4.123457e+02
print("{:E}".format(x)) # Exponent: 4.123457E+02
print("{:f}".format(x)) # fixed point: 412.345679 (default precision is 6)
print("{:.2f}".format(x)) # fixed point: 412.35 (set precision to 2)
print("{:F}".format(x)) # same as f. 412.345679
print("{:g}".format(x)) # generic: 412.346 (default precision is 6)
print("{:G}".format(x)) # generic: 412.346
print("{:n}".format(x)) # number: 412.346
print("{}".format(x)) # defaults to g 412.345678901
|
599301e824c68e3463785063859046dc49b9edc0 | 2jigoo/study_algorithm | /3-3.py | 1,134 | 3.828125 | 4 | # n * m 개의 카드
# 뽑고자 하는 행 선택
# 그 행중에서 가장 작은 수의 카드
# 최종적으로 가장 높은 숫자의 카드를 뽑을 수 있도록!
def using_double_for(data, result):
min_value = 20000
# 해당 행에서 min값과 아이템 비교해서 최소값 저장
for a in data:
min_value = min(min_value, a)
# 저장한 최소값이 현재까지 찾은 값과 비교해 더 큰 값을 저장
print("이번 행의 최소값: ", min_value, "현재까지 최대값: ", result)
return max(result, min_value)
def using_min(data, result):
print(data)
min_value = min(data)
print("이번 행의 최소값: ", min_value, "현재까지 최대값: ", result)
return max(result, min_value)
## 시작
print("n * m 행렬 사이즈 입력")
n, m = map(int, input().split())
result = 0
print("행렬 데이터 입력")
for i in range(n):
data = list(map(int, input().split()))
print("data: ", data)
# result = using_min(data, result)
result = using_double_for(data, result)
print(i, "번째 결과: ", result)
print("답: ", result) |
aa6586351e351ae8c8d191639acaaf7e4ad1f920 | ISMAILFAISAL/program | /multiple of 5/multiple of five.py | 55 | 3.609375 | 4 | num=int(input())
for i in range(1,6):
z=i*num
print(z)
|
b7bee446e46797634e8be10cb66d845bb14db141 | NallamilliRageswari/Python | /Exor_ex.py | 271 | 3.78125 | 4 | #n=4
#start=3
#output:8
#explaination:array nums is equal to [0,2,4,6,8] where [0^2^4^6^8] exor operation .
n=int(input("Enter a number :"))
start=int(input("Start number:"))
x=0
for i in range(n):
x^=start+(2*i)
print("after applying exor operation:"+str(x))
|
4f2bef7403690d885a3cae6df7403f722e213273 | AK-1121/code_extraction | /python/python_23552.py | 96 | 3.65625 | 4 | # Python list to list of lists
l = [1.0, 2.0, 3.0]
print [[x] for x in l]
[[1.0], [2.0], [3.0]]
|
606612bfd3f79b84648fc28d629e9d773be3a65b | jcwu411/Advective_equation | /plot_data.py | 1,305 | 3.625 | 4 | #!/usr/bin/env python3.8
"""
Created on 15/11/2020
@author: Jiacheng Wu, jcwu@pku.edu.cn
"""
import numpy as np
import matplotlib.pyplot as plt
def plot_2d(n, x, y, color, lw, lb,
ti="Plot", xl="X", yl="Y", legendloc=4,
xlim=(0, 1), ylim=(0, 1), ylog=False,
fn="plot2d.pdf", sa=False):
"""
Plot n lines on x-y coordinate system
:param n: The number of the plot line
:param x:
:param y:
:param color: The color of each line
:param lw: The width of each line
:param lb: The label of each line
:param ti: The title of plot
:param xl: The label of x axis
:param yl: The label of y axis
:param legendloc: The location of legend
:param xlim: The range of x axis
:param ylim: The range of y axis
:param ylog: Using logarithmic y axis or not
:param fn: The saved file name
:param sa: Saving the file or not
:return: None
"""
plt.figure()
for i in range(n):
plt.plot(x, y[i], color=color[i], linewidth=lw[i], label=lb[i])
plt.title(ti)
plt.xlabel(xl)
plt.ylabel(yl)
plt.xlim(xlim[0], xlim[1])
plt.ylim(ylim[0], ylim[1])
if ylog:
plt.yscale('log')
plt.legend(shadow=True, loc=legendloc)
if sa:
plt.savefig(fn)
plt.show()
plt.close()
|
60f3c46e1307438c3c95c75c98806675a416e77f | pitz-qa/python | /REST API with Fask And Python/pythonBasics/in StatWithIfStat.py | 233 | 4.1875 | 4 | movies_watched = {"3idiots","Tere Naam","Chakh De India"}
user_movie = input("Enter movie name: ").lower()
if user_movie in movies_watched:
print(f"I have watched {user_movie} too!")
else:
print(f"I didnt watched {user_movie}") |
77a37cef97957b1226c3b2313ec12a2f211f6c3c | cnrgrl/PYTHON-1 | /mp01/rpsls.py | 1,177 | 3.90625 | 4 | import random
def rpsls(player_choice,computer_choice):
d=(computer_choice-player_choice)%5
if d==1 or d==2:
print("computer wins")
elif d==0:
print("Spiel zieht")
else:
print("player wins")
def name_to_number(name):
if name == "rock":
number=0
elif name=="paper":
number=2
elif name=="scissor":
number=4
elif name=="lizard":
number=3
elif name=="spock":
number=1
else :
number=""
print("Sie haben einen falsche Auswahl eingegeben!")
return number
def number_to_name(num):
nam=""
if num==0:
nam="rock"
elif num==1:
nam="spock"
elif num==2:
nam="paper"
elif num==3:
nam="lizard"
elif num==4:
nam="scissor"
else :
nam=""
print("Error!")
return nam
name=input("Player Choice :").lower()
#comp_number=name_to_number(name)
print(name.upper())
p_choice=name_to_number(name)
#num=int(input("Computer's Guess"))
comp_number=random.randrange(0,4)
computer_choice=number_to_name(comp_number).upper()
print(computer_choice)
rpsls(p_choice,comp_number) |
1b166af4033338f867d38fd69e0819e77ca9f8e6 | amjadtaleb/Computational_Physics_in_Python | /fourier_transform.py | 4,013 | 3.609375 | 4 | import numpy as np
from scipy.fft import fft, ifft
def nextpow2(n):
"""
returns next power of 2 as fft algorithms work fastest when the input data
length is a power of 2
Inputs
------
n: int
next power of 2 to calculate for
Returns
-------
np.int(2 ** m_i): int
next power of 2
"""
m_f = np.log2(n)
m_i = np.ceil(m_f)
return np.int(2 ** m_i)
def dft(X):
"""
Discrete Fourier Transform.
Inputs
------
X: np.array
np.array of X values to be Fourier transformed. len(X) should be a power of 2
Returns
-------
x: np.array
DFT of X
"""
N = len(X)
x = np.zeros(N, 'complex')
K = np.arange(0, N, 1)
for n in range(0, N, 1):
x[n] = np.dot(X, np.exp(1j * 2 * np.pi * K * n / N))
return x
def idft(X):
"""
Inverse Discrete Fourier Transform. This is the inverse function of dft().
Inputs
------
X: np.array
np.array of X values to be inverse Fourier transformed. len(X) should be a power of 2
Returns
-------
x: np.array
DFT of X
"""
N = len(X)
x = np.zeros(N, 'complex')
K = np.arange(0, N, 1)
for n in range(0, N, 1):
x[n] = np.dot(X, np.exp(-1j * 2 * np.pi * K * n / N))
return x / N
def FFT(y, t):
"""
FFT function returns the frequency range up to Nyquist frequency and absolute spectral magnitude.
Inputs
------
y: np.array
np.array of values to perform FFT
t: np.array
np.array of corresponding time values
Returns
-------
freq: np.array
np.array of frequency values
amp: np.array
np.array of Fourier amplitudes
"""
dt = t[2] - t[1]
Fs = 1.0 / dt
L = len(y)
Y = fft(y, L) * dt # dt should mathematically be included in the result!
#amp=abs(Y)/(L/2) #FFT single sided spectrum
amp = abs(Y) #or simply take the amplitude only?
T = L * dt #1/T=Fs/L
freq = np.arange(0, Fs / 2, 1 / T) # list frequencies up to Nyquist frequency
# resize result vectors to match their lengths
if len(freq) < len(amp):
amp = amp[0:len(freq)] # make both vectors the same size
elif len(amp) < len(freq):
freq = freq[0:len(amp)]
return freq, amp
def CEPSTRUM(y, t):
"""
CEPSTRUM calculates the ceptram of a time series. The cepstrum is basically
a fourier transform of a fourier transform and has units of time
Inputs
------
y: np.array
np.array of values to perform FFT
t: np.array
np.array of corresponding time values
Returns
-------
q: np.array
np.array of quefrency values
C: np.array
np.array of Cepstral amplitudes
"""
dt = t[2] - t[1]
#Fs = 1.0 / dt
L = len(y)
#Y = fft(y, L)
#amp = np.abs(Y)/(L/2) # FFT single sided spectrum
#T = L * dt #1/T=Fs/L
#freq = np.arange(0, Fs / 2, 1 / T) # list frequencies up to Nyquist frequency
#C=real(ifft(log(abs(fft(y)))))
C = np.abs(ifft(np.log(np.abs(fft(y))**2)))**2
NumUniquePts = int(np.ceil((L + 1) / 2))
C = C[0:NumUniquePts]
q = np.arange(0, NumUniquePts, 1) * dt
return q, C
def SIDFT(X,D):
"""
this function demonstrates explicitly the shifted inverse DFT algorithm, but should not
be used because of the extremely slow speed. Faster algorithms use the fact
that FFT is symmetric.
"""
N=len(X)
x=np.zeros(N,'complex')
for n in range(0,N,1):
for k in range(0,N,1):
x[n]=x[n]+np.exp(-1j*2*np.pi*k*D/N)*X[k]*np.exp(1j*2*np.pi*k*n/N)
return x/N
def SHIFTFT(X,D):
"""
this function demonstrates explicitly the shifted DFT algorithm, but should not
be used because of the extremely slow speed. Faster algorithms use the fact
that FFT is symmetric.
"""
N=len(X)
for k in range(N):
X[k]=np.exp(-1j*2*np.pi*k*D/N)*X[k]
return X
|
a03c5da62c8b866e07a873378439addb6896353b | kugmax/show-me-the-data-structures | /problem_4.py | 3,377 | 3.828125 | 4 | class Group(object):
def __init__(self, _name):
self.name = _name
self.groups = set()
self.users = set()
def add_group(self, group):
self.groups.add(group)
def add_user(self, user):
self.users.add(user)
def get_groups(self):
return self.groups
def get_users(self):
return self.users
def get_name(self):
return self.name
def is_contain_user(self, user):
return user in self.users
def is_user_in_group(user, group):
"""
Return True if user is in the group, False otherwise.
Args:
user(str): user name/id
group(class:Group): group to check user membership against
"""
def loop(group, visited_groups):
if group.name in visited_groups:
return False
else:
visited_groups.add(group.name)
if group.is_contain_user(user):
return True
for g in group.groups:
is_in_group = loop(g, visited_groups)
if is_in_group:
return True
return False
return loop(group, set())
def assert_equals(expected, actual):
assert (expected == actual), "expected {0}, actual {1}".format(expected, actual)
def assert_true(actual):
assert_equals(True, actual)
def when_group_is_empty():
parent = Group("parent")
assert_true(not is_user_in_group("user_1", parent))
assert_true(not is_user_in_group("user_2", parent))
assert_true(not is_user_in_group("user_3", parent))
def when_there_is_one_group():
parent = Group("parent")
parent.add_user("user_1")
parent.add_user("user_2")
assert_true(is_user_in_group("user_1", parent))
assert_true(is_user_in_group("user_2", parent))
assert_true(not is_user_in_group("user_3", parent))
def when_there_are_many_sub_groups():
group_1 = Group("group_1")
group_1.add_user("user_1_A")
group_1.add_user("user_1_B")
group_1_1 = Group("group_1_1")
group_1_1.add_user("user_1_1_A")
group_1_2 = Group("group_1_2")
group_1_2.add_user("user_1_2_A")
group_1_2.add_user("user_1_2_B")
group_1_1_3 = Group("group_1_1_3")
group_1_1_3.add_user("user_1_1_3_A")
group_1_1_3.add_user("user_1_1_3_B")
group_1_1.add_group(group_1_1_3)
group_1.add_group(group_1_1)
group_1.add_group(group_1_2)
assert_true(is_user_in_group("user_1_A", group_1))
assert_true(is_user_in_group("user_1_1_A", group_1))
assert_true(is_user_in_group("user_1_2_B", group_1))
assert_true(is_user_in_group("user_1_1_3_B", group_1))
assert_true(not is_user_in_group("user_1_1_3_C", group_1))
assert_true(not is_user_in_group("user_1_1_3_C", group_1_1_3))
assert_true(is_user_in_group("user_1_2_B", group_1_2))
def when_sub_group_in_several_groups():
group_1 = Group("group_1")
group_1_1 = Group("group_1_1")
group_1_2 = Group("group_1_2")
group_1_n_1 = Group("group_1_n_1")
group_1_2.add_group(group_1_n_1)
group_1_1.add_group(group_1_n_1)
group_1.add_group(group_1_1)
group_1.add_group(group_1_2)
assert_true(not is_user_in_group("user", group_1))
assert_true(not is_user_in_group("not user", group_1))
if __name__ == "__main__":
when_group_is_empty()
when_there_is_one_group()
when_there_are_many_sub_groups()
when_sub_group_in_several_groups()
|
d2f7d6576fb46ce72ae73967d933582023e3ddc1 | TsymbaliukOleksandr1981/Python-for-beginners | /lesson_2/task_3.py | 121 | 3.921875 | 4 | import math
radius = float(input("Input circle radius: "))
perimetr = math.pi * 2 * radius
print("Perimetr = ",perimetr)
|
004d87d51091915a44b00a3ba024700056837167 | amit081thakur/assignment3 | /question5.py | 381 | 3.625 | 4 | Python 3.7.0b5 (v3.7.0b5:abb8802389, May 31 2018, 01:54:01) [MSC v.1913 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> A=[1,2,3,4]
>>> B=[5,6,7,8,9]
>>> A.sort()
>>> B.sort()
>>> A
[1, 2, 3, 4]
>>> B
[5, 6, 7, 8, 9]
>>> C=A+B
>>> C
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print("new ARRAY C:",C)
new ARRAY C: [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
|
3894c7ec8358539696700c1d996e665dd6a9ec9c | sheelabhadra/LeetCode-Python | /287_Find_the_Duplicate_Number.py | 775 | 3.921875 | 4 | """PROBLEM:
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least
one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
"""
"""SOLUTION:
Similar to cycle detection in linked list.
"""
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
slow = nums[0]
fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
ptr1 = nums[0]
ptr2 = slow
while ptr1 != ptr2:
ptr1 = nums[ptr1]
ptr2 = nums[ptr2]
return ptr1
|
dbdc3583bc8b8aa12652c2a76626011e271b43de | Bellroute/algorithm | /python/book_python_algorithm_interview/ch10/design_circular_deque.py | 1,700 | 3.6875 | 4 | # 리트코드 641. Design Circular Deque
class ListNode:
def __init__(self, val=None, prev=None, next=None):
self.val = val
self.prev = prev
self.next = next
class MyCircularDeque:
def __init__(self, k: int):
self.max = k
self.len = 0
self.head = ListNode(None)
self.tail = ListNode(None)
self.head.next, self.tail.prev = self.tail, self.head
def insertFront(self, value: int) -> bool:
if self.len == self.max:
return False
self.len += 1
self._add(self.head, ListNode(value))
return True
def insertLast(self, value: int) -> bool:
if self.len == self.max:
return False
self.len += 1
self._add(self.tail.prev, ListNode(value))
return True
def deleteFront(self) -> bool:
if self.len == 0:
return False
self.len -= 1
self._del(self.head)
return True
def deleteLast(self) -> bool:
if self.len == 0:
return False
self.len -= 1
self._del(self.tail.prev.prev)
return True
def getFront(self) -> int:
return self.head.next.val if self.len else -1
def getRear(self) -> int:
return self.tail.prev.val if self.len else -1
def isEmpty(self) -> bool:
return self.len == 0
def isFull(self) -> bool:
return self.len == self.max
def _add(self, node: ListNode, new: ListNode):
n = node.next
node.next = new
new.prev, new.next = node, n
n.prev = new
def _del(self, node: ListNode):
n = node.next.next
node.next = n
n.prev = node
|
7f5d0e930ea20f24e36551febf605a4331379eed | talk2sunil83/UpgradLearning | /06Deep Learning/02Convolutional Neural Networks/02Building CNNs with Python and Keras/02Building CNNs in Keras - MNIST/Building a Basic CNN The MNIST Dataset.py | 9,593 | 4.40625 | 4 | # %% [markdown]
# # Building a Basic CNN: The MNIST Dataset
#
# In this notebook, we will build a simple CNN-based architecture to classify the 10 digits (0-9) of the MNIST dataset. The objective of this notebook is to become familiar with the process of building CNNs in Keras.
#
# We will go through the following steps:
# 1. Importing libraries and the dataset
# 2. Data preparation: Train-test split, specifying the shape of the input data etc.
# 3. Building and understanding the CNN architecture
# 4. Fitting and evaluating the model
#
# Let's dive in.
# %% [markdown]
# ## 1. Importing Libraries and the Dataset
#
# Let's load the required libraries. From Keras, we need to import two main components:
# 1. `Sequential` from `keras.models`: `Sequential` is the keras abstraction for creating models with a stack of layers (MLP has multiple hidden layers, CNNs have convolutional layers, etc.).
# 2. Various types of layers from `keras.layers`: These layers are added (one after the other) to the `Sequential` model
#
# The keras `backend` is needed for keras to know that you are using tensorflow (not Theano) at the backend (the backend is <a href="https://keras.io/backend/">specified in a JSON file</a>).
#
# %%
import numpy as np
import random
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
# %% [markdown]
# Let's load the MNIST dataset from `keras.datasets`. The download may take a few minutes.
# %%
# load the dataset into train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# %%
print("train data")
print(x_train.shape)
print(y_train.shape)
print("\n test data")
print(x_test.shape)
print(y_test.shape)
# %% [markdown]
# So we have 60,000 training and 10,000 test images each of size 28 x 28. Note that the images are grayscale and thus are stored as 2D arrays.<br>
#
# Also, let's sample only 20k images for training (just to speed up the training a bit).
# %%
# sample only 20k images for training
idx = np.random.randint(x_train.shape[0], size=20000) # sample 20k indices from 0-60,000
x_train = x_train[idx, :]
y_train = y_train[idx]
print(x_train.shape)
print(y_train.shape)
# %% [markdown]
# ## 2. Data Preparation
#
# Let's prepare the dataset for feeding to the network. We will do the following three main steps:<br>
#
# #### 2.1 Reshape the Data
# First, let's understand the shape in which the network expects the training data.
# Since we have 20,000 training samples each of size (28, 28, 1), the training data (`x_train`) needs to be of the shape `(20000, 28, 28, 1)`. If the images were coloured, the shape would have been `(20000, 28, 28, 3)`.
#
# Further, each of the 20,000 images have a 0-9 label, so `y_train` needs to be of the shape `(20000, 10)` where each image's label is represented as a 10-d **one-hot encoded vector**.
#
# The shapes of `x_test` and `y_test` will be the same as that of `x_train` and `y_train` respectively.
#
# #### 2.2 Rescaling (Normalisation)
# The value of each pixel is between 0-255, so we will **rescale each pixel** by dividing by 255 so that the range becomes 0-1. Recollect <a href="https://stats.stackexchange.com/questions/185853/why-do-we-need-to-normalize-the-images-before-we-put-them-into-cnn">why normalisation is important for training NNs</a>.
#
# #### 2.3 Converting Input Data Type: Int to Float
# The pixels are originally stored as type `int`, but it is advisable to feed the data as `float`. This is not really compulsory, but advisable. You can read <a href="https://datascience.stackexchange.com/questions/13636/neural-network-data-type-conversion-float-from-int">why conversion from int to float is helpful here</a>.
#
# %%
# specify input dimensions of each image
img_rows, img_cols = 28, 28
input_shape = (img_rows, img_cols, 1)
# batch size, number of classes, epochs
batch_size = 128
num_classes = 10
epochs = 12
# %% [markdown]
# Let's now reshape the array `x_train` from shape `(20000, 28, 28)`to `(20000, 28, 28, 1)`. Analogously for `x_test`.
# %%
# reshape x_train and x_test
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
print(x_train.shape)
print(x_test.shape)
# %% [markdown]
# Now let's reshape `y_train` from `(20000,)` to `(20000, 10)`. This can be conveniently done using the keras' `utils` module.
# %%
# convert class labels (from digits) to one-hot encoded vectors
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.keras.utils.to_categorical(y_test, num_classes)
print(y_train.shape)
# %% [markdown]
# Finally, let's convert the data type of `x_train` and `x_test` from int to float and normalise the images.
# %%
# originally, the pixels are stored as ints
x_train.dtype
# %%
# convert int to float
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
# normalise
x_train /= 255
x_test /= 255
# %% [markdown]
# ## 3. Building the Model
# %% [markdown]
# Let's now build the CNN architecture. For the MNIST dataset, we do not need to build a very sophisticated CNN - a simple shallow-ish CNN would suffice.
#
# We will build a network with:
# - two convolutional layers having 32 and 64 filters respectively,
# - followed by a max pooling layer,
# - and then `Flatten` the output of the pooling layer to give us a long vector,
# - then add a fully connected `Dense` layer with 128 neurons, and finally
# - add a `softmax` layer with 10 neurons
#
# The generic way to build a model in Keras is to instantiate a `Sequential` model and keep adding `keras.layers` to it. We will also use some dropouts.
# %%
# model
model = Sequential()
# a keras convolutional layer is called Conv2D
# help(Conv2D)
# note that the first layer needs to be told the input shape explicitly
# first conv layer
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape)) # input shape = (img_rows, img_cols, 1)
# second conv layer
model.add(Conv2D(64, kernel_size=(3, 3),
activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
# flatten and put a fully connected layer
model.add(Flatten())
model.add(Dense(128, activation='relu')) # fully connected
model.add(Dropout(0.5))
# softmax layer
model.add(Dense(num_classes, activation='softmax'))
# model summary
model.summary()
# %% [markdown]
# #### Understanding Model Summary
#
# It is a good practice to spend some time staring at the model summary above and verify the number of parameteres, output sizes etc. Let's do some calculations to verify that we understand the model deeply enough.
#
# - Layer-1 (Conv2D): We have used 32 kernels of size (3, 3), and each kernel has a single bias, so we have 32 x 3 x 3 (weights) + 32 (biases) = 320 parameters (all trainable). Note that the kernels have only one channel since the input images are 2D (grayscale). By default, a convolutional layer uses stride of 1 and no padding, so the output from this layer is of shape 26 x 26 x 32, as shown in the summary above (the first element `None` is for the batch size).
#
# - Layer-2 (Conv2D): We have used 64 kernels of size (3, 3), but this time, each kernel has to convolve a tensor of size (26, 26, 32) from the previous layer. Thus, the kernels will also have 32 channels, and so the shape of each kernel is (3, 3, 32) (and we have 64 of them). So we have 64 x 3 x 3 x 32 (weights) + 64 (biases) = 18496 parameters (all trainable). The output shape is (24, 24, 64) since each kernel produces a (24, 24) feature map.
#
# - Max pooling: The pooling layer gets the (24, 24, 64) input from the previous conv layer and produces a (12, 12, 64) output (the default pooling uses stride of 2). There are no trainable parameters in the pooling layer.
#
# - The `Dropout` layer does not alter the output shape and has no trainable parameters.
#
# - The `Flatten` layer simply takes in the (12, 12, 64) output from the previous layer and 'flattens' it into a vector of length 12 x 12 x 64 = 9216.
#
# - The `Dense` layer is a plain fully connected layer with 128 neurons. It takes the 9216-dimensional output vector from the previous layer (layer l-1) as the input and has 128 x 9216 (weights) + 128 (biases) = 1179776 trainable parameters. The output of this layer is a 128-dimensional vector.
#
# - The `Dropout` layer simply drops a few neurons.
#
# - Finally, we have a `Dense` softmax layer with 10 neurons which takes the 128-dimensional vector from the previous layer as input. It has 128 x 10 (weights) + 10 (biases) = 1290 trainable parameters.
#
# Thus, the total number of parameters are 1,199,882 all of which are trainable.
# %% [markdown]
# ## 4. Fitting and Evaluating the Model
#
# Let's now compile and train the model.
# %%
# usual cross entropy loss
# choose any optimiser such as adam, rmsprop etc
# metric is accuracy
model.compile(loss=tf.keras.losses.categorical_crossentropy,
optimizer=tf.keras.optimizers.Adadelta(),
metrics=['accuracy'])
# %%
# fit the model
# this should take around 10-15 minutes when run locally on a windows/mac PC
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
# %%
# evaluate the model on test data
model.evaluate(x_test, y_test)
# %%
print(model.metrics_names)
# %% [markdown]
# The final loss (on test data) is about 0.04 and the accuracy is 98.59%.
|
695870486e96d4dcb50a5f812fb647d1d48ef3f5 | advorecky/python-basics | /lesson4/exercise01.py | 1,032 | 3.828125 | 4 | # 1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.
# В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия.
# Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
from sys import argv
productivity_in_hours, rate_per_hour, bonus = argv[1:]
def payroll(f_productivity_in_hours, f_rate_per_hour, f_bonus):
return (f_productivity_in_hours * f_rate_per_hour) + f_bonus
try:
print("Заработная плата сотрудника состаяляет: {} попугаев.".format(
payroll(float(productivity_in_hours), float(rate_per_hour),
float(bonus))))
except ValueError:
print("Введены нечисловые данные")
|
5966f7a0f57fa534445c0bbee25b92c55f9255e0 | AaravGang/KidNeuralNetwork | /SimplePerceptron/Perceptron.py | 1,254 | 3.890625 | 4 | from random import uniform
class Perceptron:
def __init__(self,n,lr):
self.weights = [uniform(-1,1) for _ in range(n)] # initialise the weights, number of weights is same as number of inputs
self.c = lr # learning rate is constant
def train(self,inputs,desired):
guess = self.feed_forward(inputs) # get the current guess of the neuron
# Compute the factor for changing the weight based on the error
# Error = desired output - guessed output
# Multiply by learning constant
error = desired - guess
# adjust the weights based on the error and the learning rate
for i in range(len(self.weights)):
self.weights[i] += inputs[i]*error*self.c
def feed_forward(self,inputs):
# calculate the cumulative sum
# s = w0*i0 + w1*i1 + w2*i2 ...
s = sum(map(lambda x,w:x*w,inputs,self.weights))
output = activate(s) # calculate the output using the activation function
return output
def get_weights(self):
return self.weights
def activate(a):
return 1 if a>=0 else -1
|
223d42f927bf50c98e0c95ab84a58ff6d6ae30be | All3yp/Daily-Coding-Problem-Solutions | /Solutions/115.py | 1,732 | 4.03125 | 4 | """
Problem:
Given two non-empty binary trees s and t, check whether tree t has exactly the same
structure and node values with a subtree of s. A subtree of s is a tree consists of a
node in s and all of this node's descendants. The tree s could also be considered as a
subtree of itself.
"""
from DataStructures.Tree import BinaryTree, Node
def is_equal(node1: Node, node2: Node) -> bool:
if (not node1) and (not node2):
return True
if (not node1) or (not node2):
return False
if node1.val != node2.val:
return False
return is_equal(node1.left, node2.left) and is_equal(node1.right, node2.right)
def find_helper(sub_tree1: Node, sub_tree2: Node) -> bool:
if is_equal(sub_tree1, sub_tree2):
return True
# if the subtree is not same, the children are checked
if sub_tree1.left and find_helper(sub_tree1.left, sub_tree2):
return True
if sub_tree1.right and find_helper(sub_tree1.right, sub_tree2):
return True
return False
def get_match(s: BinaryTree, t: BinaryTree) -> bool:
if s.root and t.root:
return find_helper(s.root, t.root)
return False
if __name__ == "__main__":
tree1 = BinaryTree()
tree1.root = Node(0)
tree1.root.left = Node(1)
tree1.root.right = Node(2)
tree1.root.right.left = Node(3)
tree1.root.right.right = Node(4)
tree2 = BinaryTree()
tree2.root = Node(2)
tree2.root.left = Node(3)
tree2.root.right = Node(4)
tree3 = BinaryTree()
tree3.root = Node(2)
tree3.root.left = Node(3)
tree3.root.right = Node(5)
print(get_match(tree1, tree2))
print(get_match(tree1, tree3))
"""
SPECS:
TIME COMPLEXITY: O(2 ^ n)
SPACE COMPLEXITY: O(log(n))
"""
|
b4c0ffd41dabfc4a7bbcfbc0c61f1f625c7a5266 | jdukosse/LOI_Python_course-SourceCode | /Chap15/recursivecount.py | 763 | 3.96875 | 4 | def count(lst, item):
""" Counts the number of occurrences of item within the list lst """
if len(lst) == 0: # Is the list empty?
return 0 # Nothing can appear in an empty list
else:
# Count the occurrences in the rest of the list
# (all but the first element)
count_rest = count(lst[1:], item)
if lst[0] == item:
return 1 + count_rest
else:
return count_rest
def main():
lst1 = [21, 19, 31, 22, 14, 31, 22, 6, 31]
print(count(lst1, 31))
lst2 = ['FRED', [2, 3], 44, 'WILMA', 'FRED', 8, 'BARNEY']
print(count(lst2, 'FRED'))
print(count(lst2, 'BETTY'))
print(count([], 16))
if __name__ == '__main__':
main()
|
bb8af46f1242bd5934a3f355cdb46f1b3ea5cb19 | lcookiel/ukr_tax_id | /main.py | 1,516 | 3.546875 | 4 | from datetime import date
import math
def birthcode(birth_date):
birth_date = birth_date.split("-")
birth_date = date(int(birth_date[0]), int(birth_date[1]), int(birth_date[2]))
delta = birth_date - date(1899, 12, 31)
return delta.days
def control_digit(taxid):
control_sum = int(taxid[0])*(-1) + int(taxid[1])*5 + int(taxid[2])*7 + int(taxid[3])*9 + int(taxid[4])*4 + int(taxid[5])*6 + int(taxid[6])*10 + int(taxid[7])*5 + int(taxid[8])*7
control_digit = (control_sum%11)%10
return str(control_digit)
def possible_taxid(birthcode, sex):
m = [1, 3, 5, 7, 9]
f = [0, 2, 4, 6, 8]
possible_taxid = []
if sex == "m":
for i in range(0, 1000):
for n in m:
taxid = str(birthcode) + (3 - len(str(i))) * "0" + str(i) + str(n)
taxid = str(taxid) + control_digit(taxid)
possible_taxid.append(taxid)
elif sex == "f":
for i in range(0, 1000):
for n in f:
taxid = str(birthcode) + (3 - len(str(i))) * "0" + str(i) + str(n)
taxid = str(taxid) + control_digit(taxid)
possible_taxid.append(taxid)
else:
pass
return possible_taxid
if __name__ == '__main__':
birth_date = input("Date of birth (e.g. 1999-12-31): ")
sex = input("Sex (m/f): ").lower()
# first 5 digits of tax id
birthcode = birthcode(birth_date)
possible_taxid = possible_taxid(birthcode, sex)
for id in possible_taxid:
print(id)
|
5ecfeefa0476b35b33c5884ca25728166b05d780 | Navajyoth/Anand-Python | /Anand python/unit2/u2prob17.py | 105 | 3.5625 | 4 | def reverse(s):
for i in reversed(open(s).readlines()):
print i.strip()
reverse('cat.txt')
|
3d58cfc2cca41f2fc7c9e05c5412bc7cb6f3e67f | PurpleMyst/aoc-2018 | /03/easy.py | 870 | 3.578125 | 4 | import collections
SQUARE_SIDE = 1000 # inches
Claim = collections.namedtuple("Claim", "x y w h")
def points(claim):
for dy in range(claim.h):
y = claim.y + dy
for dx in range(claim.w):
x = claim.x + dx
yield (x, y)
def parse_claims():
lines = open("03/input.txt")
for line in lines:
_, line = line.split(" @ ")
x, line = line.split(",")
y, line = line.split(": ")
w, h = line.split("x")
yield Claim(int(x), int(y), int(w), int(h))
def main():
claims = parse_claims()
taken = set()
overlapping = set()
for claim in claims:
for point in points(claim):
if point in taken:
overlapping.add(point)
else:
taken.add(point)
print(len(overlapping))
if __name__ == "__main__":
main()
|
1d742cda2a7123e39385003ac4d00f664efd6b3b | GB071957/Advent-of-Christmas | /Advent of Code problem 1 part 2 - expenses add to 2020.py | 772 | 3.609375 | 4 | # Advent of Code problem 1 part 2 Program by Greg Brinks
# Find three numbers in the list of 200 that add to 2020 and multiply them together
from timeit import default_timer as timeit
start= timeit()
import csv
expenses = []
with open("Advent of Code problem 1.txt") as expense_file:
file_contents = csv.reader(expense_file, delimiter='\n')
for line in file_contents:
expenses.append(int(line[0]))
for i in range(len(expenses)):
for j in range(i+1,len(expenses)):
for k in range(j+1,len(expenses)):
if expenses[i] + expenses[j] + expenses[k] == 2020:
print(f'Expenses {expenses[i]}, {expenses[j]}, and {expenses[k]} sum to 2020 and multiplied equal {expenses[i]*expenses[j]*expenses[k]}')
break
|
7828840d7e9827a56c42d6d84360a1f65ea002c6 | peltierchip/the_python_workbook_exercises | /chapter_8/exercise_183.py | 2,787 | 3.65625 | 4 | ##
# Find the longest sequence of elements starting with the chemical element entered from the user, so that each
# element follows an element whose last letter coincides with its first letter; the sequence cannot contain duplicates
# The following list contains the name of the chemical elements
c_e_l = ["Actinium", "Aluminium", "Americium", "Antimony", "Argon", \
"Arsenic", "Astatine", "Barium", "Berkelium", "Beryllium", "Bismuth", "Bohrium", "Boron", \
"Bromine", "Cadmium", "Caesium", "Calcium", "Californium", "Carbon", "Cerium", "Chlorine" , \
"Chromium", "Cobalt", "Copernicium", "Copper", "Curium", "Darmstadtium", "Dubnium", \
"Dysprosium", "Einsteinium", "Erbium", "Europium", "Fermium", "Flerovium", "Fluorine", \
"Francium", "Gadolinium", "Gallium", "Germanium", "Gold", "Hafnium", "Hassium", "Helium", "Holmium", \
"Hydrogen", "Indium", "Iodine", "Iridium", "Iron", "Krypton", "Lanthanum", "Lawrencium", \
"Lead", "Lithium", "Livermorium", "Lutetium", "Magnesium", "Manganese", "Meitnerium", \
"Mendelevium", "Mercury", "Molybdenum", "Moscovium", "Neodymium", "Neon", "Neptunium", \
"Nickel", "Nihonium", "Niobium" , "Nitrogen", "Nobelium", "Oganesson", "Osmium", "Oxygen", \
"Palladium", "Phosphorus", "Platinum", "Plutonium", "Polonium", "Potassium", "Praseodymium", \
"Promethium", "Protactinium", "Radium", "Radon", "Rhenium", "Rhodium", "Roentgenium", \
"Rubidium", "Ruthenium", "Rutherfordium", "Samarium", "Scandium", "Seaborgium", "Selenium", \
"Silicon", "Silver", "Sodium", "Strontium", "Sulfur", "Tantalum", "Technetium", "Tellurium", \
"Tennessine", "Terbium", "Thallium", "Thorium", "Thulium", "Tin", "Titanium", "Tungsten", \
"Uranium", "Vanadium", "Xenon", "Ytterbium", "Yttrium", "Zinc", "Zirconium"]
## Find the longest sequence of elements
# @param c_e the chemical element
# @param c_es the list of the chemical elements
# @return the longest sequence
def theLongestSequence(c_e, c_es):
if not(c_e):
return []
t_l_s = []
for i in range(0, len(c_es)):
if c_e[-1] == c_es[i][0].lower():
p_t_l_s = theLongestSequence(c_es[i], c_es[0:i] + c_es[i + 1 : len(c_es)])
if len(p_t_l_s) > len(t_l_s):
t_l_s = p_t_l_s
return [c_e] + t_l_s
# Demonstrate the theLongestSequence function
def main():
delimeter = " "
name_chemical_element = input("Enter the name of a chemical element:\n")
if name_chemical_element in c_e_l:
c_e_l.remove(name_chemical_element)
sequence = theLongestSequence(name_chemical_element, c_e_l)
print("The longest sequence for",name_chemical_element,"is:",delimeter.join(sequence))
else:
print("The name entered isn't valid.")
# Call the main function
main()
|
88c4348d3afbd1d175f0f40504317470f5df9808 | dillonp23/CSPT19_Sprint_1 | /sprint_challenge.py | 8,423 | 4.40625 | 4 |
"""
Exercise 1
Given a string (the input will be in the form of an array of characters), write a function that returns the reverse of the given string.
* Examples:
csReverseString(["l", "a", "m", "b", "d", "a"]) -> ["a", "d", "b", "m", "a", "l"]
csReverseString(["I", "'", "m", " ", "a", "w", "e", "s", "o", "m", "e"]) -> ["e", "m", "o", "s", "e", "w", "a", " ", "m", "'", "I"]
* Notes:
- Your solution should be "in-place" with O(1) space complexity. Although many in-place functions do not return the modified
input, in this case you should.
- You should try using a "two-pointers approach".
- Avoid using any built-in reverse methods in the language you are using (the goal of this challenge is for you to
implement your own method).
"""
def csReverseString(chars):
last_index = len(chars) - 1
for i in range(int(len(chars)/2)):
temp = chars[i]
chars[i] = chars[last_index]
chars[last_index] = temp
last_index -= 1
return chars
print(csReverseString([]))
print(csReverseString(["a"]))
print(csReverseString(["a", "b"]))
print(csReverseString(["a", "b", "c"]))
print(csReverseString(["a", "b", "c", "d", "e"]))
"""
Summary & Explanation for Exercise 1:
I immediately knew how to go about this by using list slicing, but realized that wouldn't do as a solution since we were
instructed not to use built in functionality. Obviously the easiest solution would simply be "return chars[::-1]" however
this is not acceptable in this circumstance.
I planned to use the two pointers technique in order to iterate the list and at each index, swap the characters at opposite
ends of the list. To do this I used a temporary pointer to store the value for the first index, updated the value at the
first index to the last index, and updated the last index with the temp variable.
At first I was iterating the entire list and returning the list but this was giving the list back in the original order.
I realized that I was swapping the indexes all the way through, so after getting past the first half of the array, doing
the same swap method would return the list to its original state. I realized that I needed to only iterate up to the length
of the list divided by 2, as stopping at the halfway mark is necessary to prevent reverting the list to the same order as the input.
Time & Space Complexity for Exercise 1:
The time complexity of this solution would be O(n) - linear. The exact time complexity would be O(n/2), which would simplify to O(n).
This is because we are only iterating through half of the input list each time the function is called. Although we're not iterating
the entire list, it wouldn't be O(log n) - logarithmic time, because the time is not getting halved with each iteration. We are simply
halving the number of iterations needed for a given input size each time method is called, rather than halving the number of iterations
with each iteration of the loop.
The space complexity is O(1) - constant. This is because we are changing the list in-place, meaning we are not creating a new instance
of a list in order to store the values as we reverse each element of the list. For this reason, the space complexity remains constant
with regards to an increase in input size.
"""
"""
Exercise 2
A palindrome is a word, phrase, number, or another sequence of characters that reads the same backward or forward. This includes
capital letters, punctuation, and other special characters.
Given a string, write a function that checks if the input is a valid palindrome.
Examples:
csCheckPalindrome("racecar") -> true
csCheckPalindrome("anna") -> true
csCheckPalindrome("12345") -> false
csCheckPalindrome("12321") -> true
* Notes:
- Try to solve this challenge without using the reverse of the input string; use a for loop to iterate through the string and
make the necessary comparisons.
- Something like the code below might be your first intuition, but can you figure out a way to use a for loop instead?
def csCheckPalindrome(input_str):
return input_str == "".join(reversed(input_str))
"""
def csCheckPalindrome(input_str):
length = len(input_str)
last_index = length - 1
for i in range(int(length/2)):
if input_str[i] != input_str[last_index]:
return False
last_index -= 1
return True
print(csCheckPalindrome("racecar"))
print(csCheckPalindrome("anna"))
print(csCheckPalindrome("12345"))
print(csCheckPalindrome("12321"))
print(csCheckPalindrome("teststring"))
"""
Summary & Explanation for Exercise 2:
This problem was pretty much exactly the same as the first exercise, except in this instance, rather than swapping the two
elements, we are simply comparing the two. If the elements are not equal, we know that the input is not a palindrome, so we
immediately return false. If the two elements are equal at opposing ends of the string, then we continue through the loop.
If we complete the loop, we know that the input is a palindrome, so we return true.
Time & Space Complexity for Exercise 2:
The time complexity is O(n). As the size of the input string grows, the time will increase at a rate of n/2, as we are
iterating half of the input string each time we call the function.
The space complexity is O(1) because we are not initializing any instances of a new object. The space complexity will always
be constant to the input size.
"""
"""
Exercise 3
Given a string, write a function that removes all duplicate words from the input. The string that you return should
only contain the first occurrence of each word in the string.
* Examples:
csRemoveDuplicateWords("alpha bravo bravo golf golf golf delta alpha bravo bravo golf golf golf delta") -> "alpha bravo golf delta"
csRemoveDuplicateWords("my dog is my dog is super smart") -> "my dog is super smart"
"""
def csRemoveDuplicateWords(input_str):
word_list = []
word = ""
length = len(input_str) - 1
for i in range(len(input_str)):
char = input_str[i]
if char.isalpha():
word += char
if i == length or char == " ":
if word not in word_list:
word_list.append(word)
word = ""
return " ".join(word_list)
print(csRemoveDuplicateWords("alpha bravo bravo golf golf golf delta alpha bravo bravo golf golf golf delta"))
print(csRemoveDuplicateWords("my dog is my dog is super smart"))
print(csRemoveDuplicateWords("this is only a test string test"))
"""
Summary & Explanation for Exercise 3:
I ran into a few issues while solving this problem. I started out by trying to build a result string to return,
but realized it was better to use a list and return that using the join method, using a single space as the separator.
Doing so eliminated the need to add an additional space between words and kept things more straight forward for the algorithm.
One issue I ran into was not having the last word be added to the resulting string. To remediate this issue, I changed my
for loop to iterate using the index rather than the character itself. By doing so, I was able to check if the character
was located at the last index of the string, and if so, would continue to check whether that word is in the resulting word
list. By rewriting the algorithm in this way, I eliminated the need for a separate conditional statement after the for loop.
This made the algorithm easier to understand and less verbose.
Time & Space Complexity for Exercise 3:
The time complexity for this solution is O(n) since we have to iterate through each character of the string. Off the top
of my head, I can't think of a way to improve this.
The space complexity would be O(n) as well. We are creating a new list instance in order to store the words that appear
in the input string. If the word is already in the list, then we continue to the next word. The space needed for the list
to store the unique words will increase linearly as the input size increases. I suppose in some cases the space complexity
could be between O(n) and O(1) depending on how many times the word appears in the input string, but generally speaking
the space complexity will have to grow as the input size increases assuming that the input is not a string of many
repetitive words.
""" |
4f24b7f36fbedb24c3effefdfec084e578ae4513 | Dastan-dev/part2.task7 | /task7.py | 121 | 4.09375 | 4 | number = int(input("vvedite chislo: "))
if number > 0:
print (1)
elif number < 0:
print (-1)
else:
print (0)
|
6ec2bff8324bfd8ee96f0d954229b1b4dc36ce2f | BillGrieser-GW/Final-Project-Group-7 | /code/svhnpickletypes.py | 2,854 | 3.71875 | 4 | """
Classes and command-line operations to convert the SVHN data into pickled
formats for tidier use.
bgrieser
"""
# =============================================================================
# Class definition for what gets pickled
# =============================================================================
class SvhnDigitPickle():
"""
This class represents one entry in the a of data where each entry is
the image and metadata for one digit.
"""
def __init__(self, digit_image, data):
"""
digit_image: a PIL image of the digit
data: metadata for the digit, type SvhnDigit
"""
self.digit_image = digit_image
self.data = data
class SvhnParentPickle():
"""
This class represents one entry in a list of data where each entry is
the parent image and metedata for all the digits that it contains.
"""
def __init__(self, file_name, parent_image, digit_data):
"""
file_name: The original file name of the parent image
parent_image: a PIL image of the parent image containing one or more digits
digit_data: a list of SvhnDigit classes, one per digit in the image
"""
self.parent_image = parent_image
self.digit_data = digit_data
self.file_name = file_name
class SvhnDigit():
"""
This class defines the metadata for one digit. It provides convenience
functions to generate the crop box to crop the digit image out of its
parent image, and to calculate the padding required to center the digit
image in a given image size.
"""
def __init__(self, file_name, seq_in_file, label, left, top, width, height):
self.file_name = file_name
self.seq_in_file = seq_in_file
self.label = label if label != 10 else 0
self.left = left
self.top = top
self.width = width
self.height = height
def get_crop_box(self, crop_adjust=0):
"""
Get the box used by Image.crop to crop this digit out of the parent.
"""
return (self.left + crop_adjust,
self.top + crop_adjust,
self.left + self.width + crop_adjust,
self.top + self.height + crop_adjust)
def get_padding(self, to_width, to_height):
"""
Returns a tuple with the padding required by ImageOps.expand to center
the digit image in an input block with the given shape. Note that this
is for the ImageOps.extend() method and returns the pads in this order:
left, top, right, bottom. Other padders use a different
convention.
"""
delta_w = to_width - self.width
delta_h = to_height - self.height
return(delta_w//2, delta_h//2, delta_w - (delta_w//2), delta_h - (delta_h//2))
|
dc02c4dd55566b1c11e9e1cf50b8677b68af889d | loggar/py | /py-core/List/list.sort.multiple-keys.py | 365 | 3.609375 | 4 | import operator
people = [
{'name': 'John', "age": 64},
{'name': 'Janet', "age": 34},
{'name': 'Ed', "age": 24},
{'name': 'Sara', "age": 64},
{'name': 'John', "age": 32},
{'name': 'Jane', "age": 34},
{'name': 'John', "age": 99},
]
people.sort(key=operator.itemgetter('age'))
people.sort(key=operator.itemgetter('name'))
print(people)
|
b9a7e97826c1f746c7ce528958f7320e671a9ab7 | yooni1903/DDIT | /workspace_python/HELLOPYTHON/day09/mynumpy03.py | 154 | 3.625 | 4 | import numpy as np
a = np.zeros((10, 10), dtype=int) # int형으로 넣어주는 명령어
print(a)
print(a.shape)
b = np.reshape(a,(20,5))
print(b)
|
b67b3c5c9fcf924ae6314681afeb8b05380a0f6d | freebz/Learning-Python | /ch32/spam_class.py | 952 | 3.8125 | 4 | # class Spam:
# numInstances = 0 # 정적 메서드 대신에 클래스 메서드 사용
# def __init__(self):
# Spam.numInstances += 1
# def printNumInstances(cls):
# print("Number of instances: %s" % cls.numInstances)
# printNumInstances = classmethod(printNumInstances)
class Spam:
numInstances = 0 # 전달된 클래스 추적
def __init__(self):
Spam.numInstances += 1
def printNumInstances(cls):
print("Number of instances: %s %s" % (cls.numInstances, cls))
printNumInstances = classmethod(printNumInstances)
class Sub(Spam):
def printNumInstances(cls): # 클래스 메서드 재정의
print("Extra stuff...", cls) # 하지만 원래 버전을 재호출
Spam.printNumInstances()
printNumInstances = classmethod(printNumInstances)
class Other(Spam): pass # 말 그대로 클래스 메서드 상속
|
668b0a0d32f742e53eca223b9ad76c52e6d251f1 | Vsevolod-dev/forTensor | /modules/quadratic_equation_module.py | 772 | 3.671875 | 4 | from math import sqrt
def quadr_equ(disc, a, b):
if disc == 0:
x = -b / (2 * a)
print("Корень уравнения = ", x)
elif disc > 0:
x1 = (-b + pow(disc, 0.5)) / (2*a) #без использования библеотек
x2 = (-b - sqrt(disc)) / (2*a) #с использованием библеотекb math
print(f"""
Первый корень = {x1}
Второй корень = {x2}
""")
else:
realPart = -b / (2*a) #действительная часть
imagPart = sqrt(-disc) #мнимая часть
x1 = complex(realPart, imagPart)
x2 = x1.conjugate
print(f"""
Первый корень = {x1}
Второй корень = {x2}
""") |
0184d9c6514e5dfd5efac1d43704a770e6134aa5 | wdempsey96/playground | /bubble_sort.py | 591 | 4.15625 | 4 | """Bubble sort implementation."""
UNSORTED_ARRAY = [5, 2, 4, 3, 1, 8, 10, 103, 69, 420, 17, 6, 88, 16, 191]
print("Unsorted array: ", UNSORTED_ARRAY)
print("Sorting...")
is_sorted = False
swapped = False
while not is_sorted:
i = 0
is_sorted = True
while i < len(UNSORTED_ARRAY) - 1:
if UNSORTED_ARRAY[i+1] < UNSORTED_ARRAY[i]:
# swap values
temp = UNSORTED_ARRAY[i+1]
UNSORTED_ARRAY[i+1] = UNSORTED_ARRAY[i]
UNSORTED_ARRAY[i] = temp
is_sorted = False
i += 1
print("Sorted array: ", UNSORTED_ARRAY)
|
1033179fb4d947f5468eb7bfbffe43cdfb5e086c | soowon-kang/tensorflow-practice | /03-Cost/02-gradientDescent.py | 1,071 | 3.703125 | 4 | import tensorflow as tf
# tf Graph input
x_data = [1., 2., 3.]
y_data = [1., 2., 3.]
# Try to find values for W and b that compute y_data = W * x_data + b
# (We know that W should be 1 and b 0, but TensorFlow will
# figure that out for us.)
W = tf.Variable(tf.random_uniform([1], -10.0, 10.0))
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# Our hypothesis
hypothesis = W * X
# Simplified cost function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Minimize
rate = tf.constant(0.1) # Learning rate, alpha
descent = W - rate * tf.reduce_mean((W * X - Y) * X)
update = W.assign(descent)
# Before starting, initialize the variables.
# We will 'run' this first
init = tf.global_variables_initializer()
# Launch the graph.
sess = tf.Session()
sess.run(init)
# Fit the line.
for step in range(20):
sess.run(update, feed_dict={X: x_data, Y: y_data})
print(("%2d | " % step) +
("cost: %.16f, " % (sess.run(cost,
feed_dict={X: x_data, Y: y_data}))) +
("W: %s" % (sess.run(W))))
|
a22c6b0650cd3272059ef3fcad25c693591508e9 | kevincharp/EjercicioPython-IFTS18 | /Ejercicio_9.py | 403 | 4 | 4 | #Pedir una nota en numero y decir si es Insuficiente, Suficiente, Bien, Muy Bien, Exelente
num = int(input('Ingrese nota del 1 al 10: '))
if num <= 3:
print('NOTA INSUFICIENTE')
if num <= 5:
print('NOTA SUFICIENTE')
if num <= 7:
print('NOTA BIEN')
if num <= 9:
print('NOTA MUY BIEN')
if num == 10:
print('NOTA EXELENTE')
if num > 10:
print('Calificacion invalida')
|
64a3f1b63d944622abceac3f887ce3a281324211 | xookerchang/age | /age.py | 460 | 3.890625 | 4 | driving = input('請問你有開過車嗎:')
if driving != '有' and driving != '沒有':
print('請輸入有或者沒有')
raise SystemExit
age = input('請輸入你的年齡:')
age = int(age) # casting
if driving == '有':
if age >= 18:
print('You pass the exam')
else:
print("it's werid, how?" )
elif driving == '沒有':
if age >= 18:
print('趕快去考試!!!')
else:
print('加油!快可以考了') |
7fe5c0acb0e85548ac285c8feea7f1942f2a2fb7 | tippenein/NonsenseGenerator | /nonsenseGenerator.py | 1,416 | 3.921875 | 4 | #!/usr/bin/env python
'''
USE THIS TO CREATE YOUR OWN RAMBLING PARANOID NEWS FEED!
'''
import random
def makeNonsense(part1, part2, part3, n=10):
"""return n random sentences"""
#convert to lists
p1 = part1.split('\n')
p2 = part2.split('\n')
p3 = part3.split('\n')
#shuffle the lists
[ random.shuffle( p ) for p in [p1,p2,p3] ]
#concatinate the sentences
sentence = []
for k in range(n):
try:
s = p1[k] + ' ' + p2[k] + ' ' + p3[k]
# THE LOUDER YOU YELL, THE RIGHTER YOU ARE!!
s += '!!!'
sentence.append(s)
except IndexError:
break
return sentence
# ------------------------------------------------------------------- #
# ------------------------------------------------------------------- #
# break a typical sentence into 3 parts
# first part of a sentence (subject)
#-----------------------------------------------
part1 = """\
The pope
The Military Industrial Complex
FEMA
HAARP
Flouride
Chemtrails
9/11"""
#-----------------------------------------------
# (action)
part2 = """\
is taking away
will take away
banned
censored
exposed"""
#-----------------------------------------------
# (object)
part3 = """\
Weaponized Babboons
your Freedom
your guns
your future"""
if __name__ == '__main__':
for nonsense in makeNonsense(part1, part2, part3):
print nonsense.upper()
|
8b1c92bb18b68596c1379522882291c193025c9f | hatopoppoK3/AtCoder-Practice | /CADDi/A.py | 105 | 3.5 | 4 | N = str(input())
ans = 0
for i in range(0, len(N)):
if N[i] == "2":
ans = ans + 1
print(ans)
|
8c52ee4d1a6dd9efb9dd97fa7f1b0e70eebca689 | Tvisha-D/COGS-18-Final-Project | /my_module/test_functions.py | 5,070 | 3.5625 | 4 | from functions import mood_finder, music_recommender, playlist_interest
##
##
# This tests the callability of the playlist_interest() function, ensures that the paramenter for the function is a list,
# and checks if the number of questions asked is 2. As the aim of the function is to collect user input (using the input function),
# the returns would be variable and user dependent, which is why the output aspect can't be specifically tested.
# However, if the input parameter is a list of length 2 as established here, the output would be a list of
# the preferred options presented (and length 2).
def test_mood_finder():
mood_insight = ['Hi! Welcome to Vibe - the mood based K-Pop music recommender :) \n\n Note: Please input your preferences just as they are presented in the options.\n\n Firstly, how are you primarily feeling? \nHappy\nCalm\nSad\nFrustrated\nRomantic\nExploratory\n\n',
'\nWhat kind of music are you open to now? \nChill\nIntense\nGroovy\nUplifting\nSurprise Me!\n\n']
assert callable(mood_finder)
assert isinstance(mood_insight, list)
assert len(mood_insight) == 2
# This tests a) its callability, b) the output type being a string,
# c) the functionality when both the mood and music type are particularly specified
# (for ex: ['Happy','Groovy']), and d) the functionality when the mood is given and the
# 'Surprise Me!' option is chosen under the music type (for ex: ['Calm','Surprise Me!']).
def test_music_recommender():
dummy_music_sampler = {'Happy_Chill':[' https://www.youtube.com/watch?v=WyiIGEHQP8o ',
' https://www.youtube.com/watch?v=IdssuxDdqKk '],
'Happy_Intense':[' https://www.youtube.com/watch?v=qfVuRQX0ydQ ',
' https://www.youtube.com/watch?v=CyzEtbG-sxY '],
'Happy_Groovy':[' https://www.youtube.com/watch?v=MAWM7Y9Wnd0 ',
' https://www.youtube.com/watch?v=AtNBhPxVwh0 '],
'Happy_Uplifting':[' https://www.youtube.com/watch?v=lNvBbh5jDcA ',
' https://www.youtube.com/watch?v=p9LLoijPQfg '],
'Calm_Chill':[' https://www.youtube.com/watch?v=R9VDPMk5ls0 ',
' https://www.youtube.com/watch?v=dz_W3yD0Ip0 '],
'Calm_Intense':[' https://www.youtube.com/watch?v=nt4f4pPCEFs ',
' https://www.youtube.com/watch?v=Z7yNvMzz2zg '],
'Calm_Groovy':[' https://www.youtube.com/watch?v=9VyUD_tBYq4 ',
' https://www.youtube.com/watch?v=gvdACvfuGFA '],
'Calm_Uplifting':[' https://www.youtube.com/watch?v=CKZvWhCqx1s ',
' https://www.youtube.com/watch?v=pa86DMlUpHg ']}
check = music_recommender(['Happy','Surprise Me!'], dummy_music_sampler)
assert callable(music_recommender)
assert isinstance(check, str)
assert music_recommender(['Happy','Groovy'], dummy_music_sampler) in [' https://www.youtube.com/watch?v=MAWM7Y9Wnd0 ',
' https://www.youtube.com/watch?v=AtNBhPxVwh0 ']
assert music_recommender(['Calm','Surprise Me!'], dummy_music_sampler) in [' https://www.youtube.com/watch?v=R9VDPMk5ls0 ',
' https://www.youtube.com/watch?v=dz_W3yD0Ip0 ',
' https://www.youtube.com/watch?v=nt4f4pPCEFs ',
' https://www.youtube.com/watch?v=Z7yNvMzz2zg ',
' https://www.youtube.com/watch?v=9VyUD_tBYq4 ',
' https://www.youtube.com/watch?v=gvdACvfuGFA ',
' https://www.youtube.com/watch?v=CKZvWhCqx1s ',
' https://www.youtube.com/watch?v=pa86DMlUpHg ']
# This tests the callability of the playlist_interest() function and ensures that the
# paramenters for the function are strings. The variables that are used for the
# playlist_interest() function have been copy-pasted here for this purpose.
def test_playlist_interest():
playlist_insight = 'Now that you have a feel, would you like a link to a frequently updated K-Pop playlist? \n\nYes\nNo\n\n'
playlist_choice = 'What is your platform of choice? \n\nYouTube\nSpotify\n\n'
assert callable(playlist_interest)
assert isinstance(playlist_insight, str)
assert isinstance(playlist_choice, str)
|
85f4d4063b5053c62e14ecfb1c18c53f4230efa8 | Jitender214/Python_basic_examples | /07-Errors and Exception Handling/CustomException.py | 725 | 3.78125 | 4 | class UserdefindExp(Exception):
pass
class NameEception(UserdefindExp):
pass
def testexp():
try:
mystring = 'Jithu'
enterstr = input("enter name ")
if mystring == enterstr:
print('name matches')
else:
raise NameEception
except NameEception:
print("Please enter correct name")
finally:
print("in finally block")
class AgeException(Exception):
pass
def myexp():
try:
age = 12
if(age<18):
raise AgeException
else:
print("Correct age")
except AgeException:
print("Age should be greater than or equal to 18")
finally:
print("End of the program")
|
67f22a74eedc6c07c1841e2848930856b3acccfc | jnwki/blackjack | /game.py | 2,246 | 3.6875 | 4 | from deck import Deck
from hand import Hand
def game():
# Instantiate game deck, player and dealer
deck = Deck()
player = Hand()
dealer = Hand()
# Initial Deal
player.hand = [deck.hit() for _ in range(2)]
dealer.hand = [deck.hit() for _ in range(2)]
print("\n\nWelcome to Blackjack.\n")
playing = True
player_stays = False
while playing is True:
player.get_value()
dealer.get_value()
print("Your Hand: {}".format(list(player.hand[0:])))
print("Your Hand's Value: {}".format(player.value))
print("\nDealer's Hand: [xxx Hidden Card xxx], {}".format(dealer.hand[1:]))
print("Dealer's Hand Value Showing: {}".format(dealer.shown_value))
print("_" * 60)
if player_stays is False:
if player.value < 21:
player_hit = input("\nWould you like to hit? Y/n").lower()
if player_hit != 'n':
player.hand.append(deck.hit())
else:
print("You Have Decided To Stay.")
player_stays = True
else:
player_stays = True
else:
if player.value > 21:
print("You Lose! Bust!")
playing = False
else:
if dealer.value < 17:
dealer.hand.append(deck.hit())
print("Dealer Hits.")
else:
if dealer.value > 21:
print("You Win! Dealer Busts.")
playing = False
elif dealer.value > player.value:
print("Dealer's Hand Beats Yours. You lost.")
playing = False
elif dealer.value == player.value:
print("Push. Nobody won.")
playing = False
else:
print("Your Hand Beats Dealer's Hand! You Win!")
playing = False
print("\n\nDealer's Hand Was: {} Total Value {}".format(dealer.hand, dealer.value))
if input("\nGame over. Play again? Y/n").lower() != 'n':
game()
else:
print("Goodbye!")
game()
|
62bc09870aef45a2fe74ab91ca15dcd774824c5f | ionutdrg45/BottlesOfBeer | /main.py | 401 | 3.90625 | 4 |
def bottles_of_beer(beer_num):
if beer_num < 1:
print("""No more bottles of beer on the wall. No more bottles of beer.""")
return
tmp = beer_num
beer_num -= 1
print("""{} bottles of beer on the wall. {} bottles of beer. Take one down, pass it
around, {} bottles of beer on the wall""".format(tmp, tmp, beer_num))
bottles_of_beer(beer_num)
bottles_of_beer(10) |
1d9bb9f6b50bc3c5f1d09130276f4000f23f385d | yangyuxiang1996/leetcode | /98.验证二叉搜索树.py | 1,780 | 3.71875 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-06 18:14:40
LastEditors: yangyuxiang
LastEditTime: 2021-05-06 18:49:21
FilePath: /leetcode/98.验证二叉搜索树.py
'''
#
# @lc app=leetcode.cn id=98 lang=python
#
# [98] 验证二叉搜索树
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def __init__(self):
self.min_val = float("-inf")
def isValidBST(self, root):
if root is None:
return True
if not self.isValidBST(root.left):
return False
if root.val <= self.min_val:
return False
self.min_val = root.val
if not self.isValidBST(root.right):
return False
return True
def isValidBST1(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
if not root.left and not root.right:
return True
if not root.left and root.val >= root.right.val:
return False
if not root.right and root.val <= root.left.val:
return False
output = self.inOrder(root, [])
for i in range(1, len(output)):
if output[i-1] >= output[i]:
return False
return True
def inOrder(self, root, output):
if not root:
return
self.inOrder(root.left, output)
output.append(root.val)
self.inOrder(root.right, output)
return output
# @lc code=end
|
5ce1f734f8785fd51730ec0f34e62e59c4a45a2c | shaziya21/PYTHON | /pali.py | 907 | 3.96875 | 4 | def count(lst):
even = 0
odd = 0
for i in lst:
if i%2==0:
even+=1
else:
odd+=1
return even,odd
lst=[20,25,14,19,16,24,28,47,26]
even,odd = count(lst)
print(even)
print(odd)
print(type(even))
######################################
def count(lst):
even = 0
odd = 0
for i in lst:
if i%2==0:
even+=1
else:
odd+=1
return even,odd
lst=[20,25,14,19,16,24,28,47,26]
even,odd = count(lst)
print('even : {} and odd : {}' .format(even,odd))
# format() method formats the specified
#value(s) and insert them inside the string's placeholder.
# QUES : Take 10 names from the user and then count and display the no of users who has len more thn 5 letters
names= int(input('enter the names of users'))
count+=1
for i in names:
if length>=5
print(names)
else:
print('not found')
|
9b1f993d127f6d22c9204327893885ebee304206 | huseyin1701/goruntu_isleme | /1. hafta - python giris/3_degiskenler.py | 231 | 3.65625 | 4 | a=5
b=5.5
c = "metin"
d = True
e = 'e'
print(a)
print(b)
print(c)
print(d)
print(e)
print("a nın değeri :", a)
print("b nın değeri :", b)
print("c nın değeri :", c)
print("d nın değeri :", d)
print("e nın değeri :", e)
|
754e12ed25948cf40c0312647c55647216355c2c | NaychukAnastasiya/goiteens-python3-naychuk | /lesson_5_work/Ex5.py | 285 | 3.859375 | 4 | donuts = ["ягідні","вишневі","шоколадні","карамельні"]
is_present= False
for i in donuts:
if i=="вишневі":
is_present= True
break
if is_present== True:
print("Є")
else:
print("Немає")
|
825d346ce56fdd28914dd483066b24483bd34ed8 | vthakur-1/sub1 | /prob12.py | 299 | 3.5625 | 4 | inpr=input()
liss=inpr.split(",")
num1=int(liss[0])
num2=int(liss[1])
if num1>=1000 and num2<=3000:
for inter in range(num1,num2):
f=0
for inter2 in str(inter):
if int(inter2) % 2 != 0:
f=1
break
if(f==0):
print(inter,end=",")
else:
print("entre number between given range")
|
4901dec5cb8e60c1d380169f4abdcc77da8188f8 | Hallyson34/uPython2 | /dentroparafora.py | 546 | 3.578125 | 4 | def decifrarE(v):
meio = len(v) // 2
j = meio - 1
for i in range(meio // 2):
aux = v[j]
v[j] = v[i]
v[i] = aux
j -= 1
def decifrarD(v):
meio = len(v) // 2
j = len(v) - 1
for i in range(meio, meio + meio // 2):
aux = v[j]
v[j] = v[i]
v[i] = aux
j -= 1
return "".join(v)
#-------------------------------
def main():
n = int(input())
for i in range(n):
text = list(input())
decifrarE(text)
print(decifrarD(text))
main() |
95088069ad85adc8652025bc006ae3325ebe4548 | leilalu/algorithm | /剑指offer/第一遍/linkedlist/07-2.求链表的中间结点.py | 1,426 | 3.953125 | 4 | """
题目描述
求链表的中间结点。
如果链表中的结点总数为奇数,则返回中间结点;如果结点总数是偶数,则返回中间两个结点的任意一个。
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindMidNode(self, head):
"""
可以使用【两个指针】,两个指针同时出发,第一个一次走两步,第二个一次走一步。当第一个指针走到链表末尾时,第二个指针刚好在链表中间
考虑几种特殊情况:
1、链表为空
2、链表只有1个结点 (属于奇数)
"""
if not head:
return None
first = second = head
# 第一个指针到尾,或到倒数第二个时结束
while first.next:
next = first.next
if next.next:
second = second.next
first = next.next
else:
break
return second
if __name__ == '__main__':
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node6 = ListNode(6)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = node6
s = Solution()
res = s.FindMidNode(node1)
print(res.val) |
38a0043338a353e10301d1bd9b26787dc84d1d54 | geometryolife/Python_Learning | /PythonCC/Chapter07/e5_counting.py | 285 | 4.09375 | 4 | print("----------使用while循环----------")
# for循环用于针对集合中的每个元素的一个代码块,而while循环不断地
# 运行,直到指定的条件不满足为止
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
|
8db85b9d702229b511a33f36b8052b4582de3a25 | denizcetiner/rosalindpractice | /HEA.py | 1,173 | 3.84375 | 4 | offset = 1
def parent(pos:int):
if pos == 1 or pos == 2:
return 0
else:
return int((pos - 1) / 2)
def swap(array:[], pos0:int, pos1):
temp = array[pos0]
array[pos0] = array[pos1]
array[pos1] = temp
def max_heapify(max_heap_array:[], check_pos:int):
largest = check_pos
left = (2 * check_pos) + 1
right = (2 * check_pos) + 2
if left < len(max_heap_array) and max_heap_array[check_pos] < max_heap_array[left]:
largest = left
if right < len(max_heap_array) and max_heap_array[largest] < max_heap_array[right]:
largest = right
if largest != check_pos:
swap(max_heap_array, largest, check_pos)
max_heapify(max_heap_array, largest)
def build_max_heap(array:[]):
max_heap_array = []
for element in array:
max_heap_array.append(element)
max_heapify(max_heap_array, len(max_heap_array))
def run(user_input="""5
1 3 5 7 2"""):
params = user_input.splitlines()
array = [int(i) for i in params[1].split()]
for i in range(len(array)-1, -1, -1):
max_heapify(array, i)
print(array)
return " ".join([str(i) for i in array])
run() |
573b03724fdc1cb3fb2da71fd1047cfd56a601e5 | queensland1990/HuyenNguyen-Fundamental-C4E17 | /SS02/Homeworkss2/turtle2.py | 156 | 3.96875 | 4 | from turtle import*
shape("turtle")
begin_fill()
color("red")
end_fill()
dot_distance=10
width=10
height=10
for i in range(10):
forward(10)
mainloop()
|
b3858dee8cfb7b3b783368ef4cdc7b8d46d05b7c | brunoparodi/IME-USP-Coursera | /Parte02/Exercícios extras/11.6a-matriz-Recebe duas matriz a_mat e b_mat e cria e retorna a matriz produto de a_mat por b_mat.py | 1,013 | 3.578125 | 4 | # A = (aij)m x p e B = (bij)p x n é a matriz C = (cij) m x n
def mat_mul(A,B):
num_linhas_A, num_colunas_A = len(A), len(A[0])
num_linhas_B, num_colunas_B = len(B), len(B[0])
assert num_colunas_A == num_linhas_B
C = []
for linha in range(num_linhas_A):
C.append([]) # Começando uma nova linha em C
for coluna in range(num_colunas_B):
# Adicionando uma nova coluna na linha
C[linha].append(0)
for k in range(num_colunas_A):
C[linha][coluna] += A[linha][k] * B[k][coluna]
return C
if __name__ == '__main__':
A = [ [1, 2, -1], [0, 3, 2] ]
B = [ [1, -1], [2, 0], [3, 2] ]
c = mat_mul(A,B)
print(c)
resultado = [ [2, -3], [12, 4] ]
if c == resultado:
print("Passou no primeiro teste! :-)")
else:
print("Nao passou no primeiro teste! :-(")
#multiplica_matriz([[2,3],[0,1], [-1,4] ],[ [1,2,3], [-2,0,4] ])
#multiplica_matriz([[1,2], [3,4] ],[ [-1,3], [4,2] ])
|
513f5901b898f4da35aa87a31a7896c6339ab999 | Pravin2796/python-practice- | /chapter 3/2.slicing.py | 106 | 3.625 | 4 | #greeting = "good morning,"
name = "pravin"
#c= greeting + name #concatinating two strngs
print(name[:-1]) |
e06ddc4767c5e66476d280e20173cfded49b9a6b | tafiela/Learn_Python_the_hardway | /lambda_fun.py | 413 | 4.21875 | 4 | #lambda is a way of writting functions in one line
#its the quick and dirty way of doing functions
#This is one way for writting a function
def square(x):
return x*x
print square(99)
#This is another way for writting a function
def square(x): return x*x
print square(10)
#Here is the lambda way
square = lambda x: x*x #lambda ALWAYS returns a values this is why we didnt explicitly say return
print square(3)
|
c020fb004676b8365fc4a56a49420819f70ee40f | xu-robert/Leetcode | /Diagonal Traverse.py | 3,447 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 25 21:14:12 2020
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal
order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Since the picture does not copy, please draw out the matrix and see how you would reach the output going diagonally from
top left corner to bottom right corner.
Solution:
BEcause of all the grid like questions I have come across, I know that each diagonal in a matrix is associated with
a number: see below
THESE ARE the coordinates
[
[(0,0),(0,1),(0,2)]
[(1,0),(1,1),(1,2)]
[(2,0),(2,1),(2,2)]
[(3,0),(3,1),(3,2)]
[(4,0),(4,1),(4,2)]
]
And note that if we add i and j for every coordinate, we get this:
[
[0,1,2]
[1,2,3]
[2,3,4]
[3,4,5]
[4,5,6]
]
Each diagonal is associated with a particular i+j sum: We can refer to the nth diagonal as all elements in the matrix
such that i+j=n. In total there are len(matrix) + len(matrix[0]) - 1 diagonals: here we have 3+5-1 = 7 diagonals
with an associated i+j ranging from 0 to 6.
So here is the idea: We iterate through these diagonals from 0 to 6, starting from the top right
corner of the diagonal and moving to the bottom left. As we iterate, we add these elements to a buffer. Once we reach
the bottom left of the diagonal, our buffer should contain all the elements of the nth diagonal. At this point, we need
to add the elements of the buffer to our answer. If n is even, we add them in reverse order. Otherwise, we add them in
normal order.
So the only thing we really need to figure out is where the top right corner of the nth diagonal is. The top right corner
is given by coordinate (i,j) where i+j=n. So we know what n is, meaning we only need to know one of i or j as
j = n-i and i = n-j. Lets pick i. Notice that in our example, for the first 3 diagonals, i starts at 0. Afterwards,
i ranges from 1 to 4. Also note that the the 3 diagonals where i starts at 0 corresponds to the number of columns we have
len(matrix[0]). So we can make the following observation: while n <= len(matrix[0]-1), the top right corner of the nth
diagonal is given by (0,n-i). Once n >= len(matrix[0]), the top right corner of the nth diagonal is given by
(n-len(matrix[0]+1), len(matrix[0])). More generally, we can say that for any n, the top right corner has i coordinate
max(0, n-len(matrix[0])-1), and j=n-i. Once we have i and j, we proceed to move down and left: i += 1, j -= 1, until
we reach other the left edge (j=0) or the bottom edge (i=len(matrix)-1). Once we hit either, the buffer contains all
elements of the nth diagonal.
@author: Robert Xu
"""
class Solution(object):
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
ans = []
for n in range(len(matrix) + len(matrix[0]) - 1):
buffer = []
i = max(0, n-len(matrix[0])+1)
j = n-i
while i<len(matrix) and j>=0:
buffer.append(matrix[i][j])
i += 1
j -= 1
if n%2==0:
ans.extend(buffer[::-1])
else:
ans.extend(buffer)
return ans
a = Solution()
b = a.findDiagonalOrder([[1],[2]]) |
7e3b376ead8d26563d80f2c754d94137db7e714c | Taoge123/OptimizedLeetcode | /LeetcodeNew/python/LC_140.py | 3,344 | 3.9375 | 4 | """
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]
Example 2:
Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]
"""
class SolutionTony:
def wordBreak(self, s: str, wordDict):
memo = {}
res = self.dfs(s, set(wordDict), 0, memo)
return [" ".join(words) for words in res]
def dfs(self, s, wordDict, i, memo):
if i in memo:
return memo[i]
n = len(s)
if i == n:
return [[]]
res = []
for j in range(i + 1, n + 1):
if s[i:j] in wordDict:
for sub in self.dfs(s, wordDict, j, memo):
res.append([s[i:j]] + sub)
memo[i] = res
return res
class Solution:
def wordBreak(self, s: str, wordDict):
return self.helper(s, wordDict, {})
def helper(self, s, wordDict, memo):
if not s:
return []
if s in memo:
return memo[s]
res = []
for word in wordDict:
if not s.startswith(word):
continue
if len(word) == len(s):
print(word)
res.append(word)
else:
rest = self.helper(s[len(word):], wordDict, memo)
for item in rest:
item = word + ' ' + item
print(item, '---')
res.append(item)
memo[s] = res
return res
class Solution2:
def wordBreak(self, s: str, wordDict):
memo = dict()
return self.dfs(s, wordDict, memo)
def dfs(self, s, wordDict, memo):
if s in memo:
return memo[s]
if not s:
return [""]
res = []
for word in wordDict:
if s[:len(word)] != word:
continue
for item in self.dfs(s[len(word):], wordDict, memo):
res.append(word + ("" if not item else " " + item))
memo[s] = res
return res
class SolutionTest:
def wordBreak(self, s: str, wordDict):
memo = {}
def dfs(st):
if st in memo:
return memo[st]
if not st:
return ['']
res = []
for word in wordDict:
if word == st[:len(word)]:
for r in dfs(st[len(word):]):
res.append(word + ('' if not r else ' '+r))
memo[st] = res
return res
return dfs(s)
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
a = Solution()
print(a.wordBreak(s, wordDict))
|
2e43d4911bbeb9f1629d6d50dbf4e2f83a5db327 | michaelcyng/python_tutorial | /tutorial5/boolean_examples/boolean.py | 270 | 4.125 | 4 | # Two possible values of boolean variables
a = True
b = False
print("a = {0}".format(a))
print("b = {0}".format(b))
# Examples of boolean examples
c = (10 > 9)
d = (10 == 9)
e = (10 < 9)
print("c = {0}".format(c))
print("d = {0}".format(d))
print("e = {0}".format(e))
|
c35ddfdb76ab90a772c5738cb4bfdb137081f72e | GuillaumeFavelier/persistence-atlas | /ttk/core/base/spectralEmbedding/spectralEmbedding.py | 20,284 | 3.609375 | 4 | def _graph_connected_component(graph, node_id):
"""Find the largest graph connected components that contains one
given node
Parameters
----------
graph : array-like, shape: (n_samples, n_samples)
adjacency matrix of the graph, non-zero weight means an edge
between the nodes
node_id : int
The index of the query node of the graph
Returns
-------
connected_components_matrix : array-like, shape: (n_samples,)
An array of bool value indicating the indexes of the nodes
belonging to the largest connected components of the given query
node
"""
import numpy as np
from scipy import sparse
n_node = graph.shape[0]
if sparse.issparse(graph):
# speed up row-wise access to boolean connection mask
graph = graph.tocsr()
connected_nodes = np.zeros(n_node, dtype=np.bool)
nodes_to_explore = np.zeros(n_node, dtype=np.bool)
nodes_to_explore[node_id] = True
for _ in range(n_node):
last_num_component = connected_nodes.sum()
np.logical_or(connected_nodes, nodes_to_explore, out=connected_nodes)
if last_num_component >= connected_nodes.sum():
break
indices = np.where(nodes_to_explore)[0]
nodes_to_explore.fill(False)
for i in indices:
if sparse.issparse(graph):
neighbors = graph[i].toarray().ravel()
else:
neighbors = graph[i]
np.logical_or(nodes_to_explore, neighbors, out=nodes_to_explore)
return connected_nodes
def _graph_is_connected(graph):
""" Return whether the graph is connected (True) or Not (False)
Parameters
----------
graph : array-like or sparse matrix, shape: (n_samples, n_samples)
adjacency matrix of the graph, non-zero weight means an edge
between the nodes
Returns
-------
is_connected : bool
True means the graph is fully connected and False means not
"""
from scipy import sparse
from scipy.sparse.csgraph import connected_components
if sparse.isspmatrix(graph):
# sparse graph, find all the connected components
n_connected_components, _ = connected_components(graph)
return n_connected_components == 1
else:
# dense graph, find all connected components start from node 0
return _graph_connected_component(graph, 0).sum() == graph.shape[0]
def _set_diag(laplacian, value, norm_laplacian):
"""Set the diagonal of the laplacian matrix and convert it to a
sparse format well suited for eigenvalue decomposition
Parameters
----------
laplacian : array or sparse matrix
The graph laplacian
value : float
The value of the diagonal
norm_laplacian : bool
Whether the value of the diagonal should be changed or not
Returns
-------
laplacian : array or sparse matrix
An array of matrix in a form that is well suited to fast
eigenvalue decomposition, depending on the band width of the
matrix.
"""
import numpy as np
from scipy import sparse
n_nodes = laplacian.shape[0]
# We need all entries in the diagonal to values
if not sparse.isspmatrix(laplacian):
if norm_laplacian:
laplacian.flat[::n_nodes + 1] = value
else:
laplacian = laplacian.tocoo()
if norm_laplacian:
diag_idx = (laplacian.row == laplacian.col)
laplacian.data[diag_idx] = value
# If the matrix has a small number of diagonals (as in the
# case of structured matrices coming from images), the
# dia format might be best suited for matvec products:
n_diags = np.unique(laplacian.row - laplacian.col).size
if n_diags <= 7:
# 3 or less outer diagonals on each side
laplacian = laplacian.todia()
else:
# csr has the fastest matvec and is thus best suited to
# arpack
laplacian = laplacian.tocsr()
return laplacian
def my_spectral_embedding(adjacency, n_components=8, eigen_solver=None,
random_state=None, eigen_tol=0.0,
norm_laplacian=False, drop_first=True):
"""Project the sample on the first eigenvectors of the graph Laplacian.
The adjacency matrix is used to compute a normalized graph Laplacian
whose spectrum (especially the eigenvectors associated to the
smallest eigenvalues) has an interpretation in terms of minimal
number of cuts necessary to split the graph into comparably sized
components.
This embedding can also 'work' even if the ``adjacency`` variable is
not strictly the adjacency matrix of a graph but more generally
an affinity or similarity matrix between samples (for instance the
heat kernel of a euclidean distance matrix or a k-NN matrix).
However care must taken to always make the affinity matrix symmetric
so that the eigenvector decomposition works as expected.
Note : Laplacian Eigenmaps is the actual algorithm implemented here.
Read more in the :ref:`User Guide <spectral_embedding>`.
Parameters
----------
adjacency : array-like or sparse matrix, shape: (n_samples, n_samples)
The adjacency matrix of the graph to embed.
n_components : integer, optional, default 8
The dimension of the projection subspace.
eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'}, default None
The eigenvalue decomposition strategy to use. AMG requires pyamg
to be installed. It can be faster on very large, sparse problems,
but may also lead to instabilities.
random_state : int, RandomState instance or None, optional, default: None
A pseudo random number generator used for the initialization of the
lobpcg eigenvectors decomposition. If int, random_state is the seed
used by the random number generator; If RandomState instance,
random_state is the random number generator; If None, the random number
generator is the RandomState instance used by `np.random`. Used when
``solver`` == 'amg'.
eigen_tol : float, optional, default=0.0
Stopping criterion for eigendecomposition of the Laplacian matrix
when using arpack eigen_solver.
norm_laplacian : bool, optional, default=True
If True, then compute normalized Laplacian.
drop_first : bool, optional, default=True
Whether to drop the first eigenvector. For spectral embedding, this
should be True as the first eigenvector should be constant vector for
connected graph, but for spectral clustering, this should be kept as
False to retain the first eigenvector.
Returns
-------
embedding : array, shape=(n_samples, n_components)
The reduced samples.
Notes
-----
Spectral Embedding (Laplacian Eigenmaps) is most useful when the graph
has one connected component. If there graph has many components, the first
few eigenvectors will simply uncover the connected components of the graph.
References
----------
* https://en.wikipedia.org/wiki/LOBPCG
* Toward the Optimal Preconditioned Eigensolver: Locally Optimal
Block Preconditioned Conjugate Gradient Method
Andrew V. Knyazev
http://dx.doi.org/10.1137%2FS1064827500366124
"""
import warnings
import numpy as np
from scipy import sparse
from scipy.linalg import eigh
from scipy.sparse.linalg import eigsh, lobpcg
from sklearn.base import BaseEstimator
from sklearn.externals import six
from sklearn.utils import check_random_state, check_array, check_symmetric
from sklearn.utils.extmath import _deterministic_vector_sign_flip
from sklearn.metrics.pairwise import rbf_kernel
from sklearn.neighbors import kneighbors_graph
adjacency = check_symmetric(adjacency)
try:
from pyamg import smoothed_aggregation_solver
except ImportError:
if eigen_solver == "amg":
raise ValueError("The eigen_solver was set to 'amg', but pyamg is "
"not available.")
if eigen_solver is None:
eigen_solver = 'arpack'
elif eigen_solver not in ('arpack', 'lobpcg', 'amg'):
raise ValueError("Unknown value for eigen_solver: '%s'."
"Should be 'amg', 'arpack', or 'lobpcg'"
% eigen_solver)
random_state = check_random_state(random_state)
n_nodes = adjacency.shape[0]
# Whether to drop the first eigenvector
if drop_first:
n_components = n_components + 1
if not _graph_is_connected(adjacency):
warnings.warn("Graph is not fully connected, spectral embedding"
" may not work as expected.")
laplacian, dd = sparse.csgraph.laplacian(adjacency, normed=norm_laplacian,
return_diag=True)
if (eigen_solver == 'arpack' or eigen_solver != 'lobpcg' and
(not sparse.isspmatrix(laplacian) or n_nodes < 5 * n_components)):
# lobpcg used with eigen_solver='amg' has bugs for low number of nodes
# for details see the source code in scipy:
# https://github.com/scipy/scipy/blob/v0.11.0/scipy/sparse/linalg/eigen
# /lobpcg/lobpcg.py#L237
# or matlab:
# http://www.mathworks.com/matlabcentral/fileexchange/48-lobpcg-m
laplacian = _set_diag(laplacian, 1, norm_laplacian)
# Here we'll use shift-invert mode for fast eigenvalues
# (see http://docs.scipy.org/doc/scipy/reference/tutorial/arpack.html
# for a short explanation of what this means)
# Because the normalized Laplacian has eigenvalues between 0 and 2,
# I - L has eigenvalues between -1 and 1. ARPACK is most efficient
# when finding eigenvalues of largest magnitude (keyword which='LM')
# and when these eigenvalues are very large compared to the rest.
# For very large, very sparse graphs, I - L can have many, many
# eigenvalues very near 1.0. This leads to slow convergence. So
# instead, we'll use ARPACK's shift-invert mode, asking for the
# eigenvalues near 1.0. This effectively spreads-out the spectrum
# near 1.0 and leads to much faster convergence: potentially an
# orders-of-magnitude speedup over simply using keyword which='LA'
# in standard mode.
try:
# We are computing the opposite of the laplacian inplace so as
# to spare a memory allocation of a possibly very large array
laplacian *= -1
v0 = random_state.uniform(-1, 1, laplacian.shape[0])
lambdas, diffusion_map = eigsh(laplacian, k=n_components,
sigma=1.0, which='LM',
tol=eigen_tol, v0=v0)
embedding = diffusion_map.T[n_components::-1] * dd
except RuntimeError:
# When submatrices are exactly singular, an LU decomposition
# in arpack fails. We fallback to lobpcg
eigen_solver = "lobpcg"
# Revert the laplacian to its opposite to have lobpcg work
laplacian *= -1
if eigen_solver == 'amg':
# Use AMG to get a preconditioner and speed up the eigenvalue
# problem.
if not sparse.issparse(laplacian):
warnings.warn("AMG works better for sparse matrices")
# lobpcg needs double precision floats
laplacian = check_array(laplacian, dtype=np.float64,
accept_sparse=True)
laplacian = _set_diag(laplacian, 1, norm_laplacian)
ml = smoothed_aggregation_solver(check_array(laplacian, 'csr'))
M = ml.aspreconditioner()
X = random_state.rand(laplacian.shape[0], n_components + 1)
X[:, 0] = dd.ravel()
lambdas, diffusion_map = lobpcg(laplacian, X, M=M, tol=1.e-12,
largest=False)
embedding = diffusion_map.T * dd
if embedding.shape[0] == 1:
raise ValueError
elif eigen_solver == "lobpcg":
# lobpcg needs double precision floats
laplacian = check_array(laplacian, dtype=np.float64,
accept_sparse=True)
if n_nodes < 5 * n_components + 1:
# see note above under arpack why lobpcg has problems with small
# number of nodes
# lobpcg will fallback to eigh, so we short circuit it
if sparse.isspmatrix(laplacian):
laplacian = laplacian.toarray()
lambdas, diffusion_map = eigh(laplacian)
embedding = diffusion_map.T[:n_components] * dd
else:
laplacian = _set_diag(laplacian, 1, norm_laplacian)
# We increase the number of eigenvectors requested, as lobpcg
# doesn't behave well in low dimension
X = random_state.rand(laplacian.shape[0], n_components + 1)
X[:, 0] = dd.ravel()
lambdas, diffusion_map = lobpcg(laplacian, X, tol=1e-15,
largest=False, maxiter=2000)
embedding = diffusion_map.T[:n_components] * dd
if embedding.shape[0] == 1:
raise ValueError
embedding = _deterministic_vector_sign_flip(embedding)
if drop_first:
vectors = embedding[1:n_components].T
else:
vectors = embedding[:n_components].T
return (lambdas, vectors)
def computeStress(k, D, M, C):
import numpy as np
from scipy.spatial import distance
# normalize D
# d = distance.squareform(D)
d = np.array(D, copy=True)
dmin = np.min(d)
d = np.add(d, -dmin)
dmax = np.max(d)
d = np.divide(d, dmax)
# normalize M
f = distance.pdist(M)
f = distance.squareform(f)
fmin = np.min(f)
f = np.add(f, -fmin)
fmax = np.max(f)
f = np.divide(f, fmax)
# prepare final normalization
n = np.sum(np.power(d, 2))
# follow connectivity rules
n = d.shape[0]
for i in range(n):
for j in range(n):
if C[i, j] == 0:
d[i, j] = 1.0
f[i, j] = 1.0
e = np.sum(np.power(f - d, 2)) / n
s = np.sqrt(e)
return (k, s)
def parallelStress(r, D, M, C, q):
result = list()
for k in r:
m = M[:, 0:k]
ret = computeStress(k, D, m, C)
result.append(ret)
q.put(result)
def parallelEmbedding(kmin, kmax, B, D, C, njobs):
import numpy as np
# import matplotlib.pyplot as plt
from multiprocessing import Process, Queue
l, M = my_spectral_embedding(B, n_components=kmax, random_state=0)
# create processes container and shared structure
P = list()
q = Queue()
R = np.array_split(range(kmin, kmax + 1), njobs)
for r in R:
p = Process(target=parallelStress, args=(r, D, M, C, q))
p.start()
P.append(p)
result = []
for p in P:
while p.is_alive():
p.join(timeout=1)
while not q.empty():
ret = q.get(block=False)
result += ret
dimensionality, stress = zip(*result)
x = stress.index(min(stress))
x = dimensionality[x]
dimensionality, stress = zip(*sorted(zip(dimensionality, stress)))
# export to CSV
# import csv
# csvfile = open('/tmp/spectralEmbedding.csv', 'w')
# csvwriter = csv.writer(csvfile, delimiter=';')
# csvwriter.writerow(['dimensionality', 'stress'])
# for i in range(1, len(dimensionality)):
# csvwriter.writerow([dimensionality[i], stress[i]])
# plt.plot(dimensionality, stress)
# plt.show()
return (l, M[:, 0:x], M)
def sequentialEmbedding(kmin, kmax, B, D, C):
# import matplotlib.pyplot as plt
l, M = my_spectral_embedding(B, n_components=kmax, random_state=0)
x = 1
minStress = -1
stress = list()
dimensionality = list()
for k in range(kmin, kmax + 1):
m = M[:, 0:k]
ret = computeStress(k, D, m, C)
# get stress minimizer
if minStress == -1:
minStress = ret[1]
x = ret[0]
elif ret[1] < minStress:
minStress = ret[1]
x = ret[0]
# append for plot
dimensionality.append(ret[0])
stress.append(ret[1])
# export to CSV
# import csv
# csvfile = open('/tmp/spectralEmbedding.csv', 'w')
# csvwriter = csv.writer(csvfile, delimiter=';')
# csvwriter.writerow(['dimensionality', 'stress'])
# for i in range(1, len(dimensionality)):
# csvwriter.writerow([dimensionality[i], stress[i]])
# plt.plot(dimensionality, stress)
# plt.show()
# compute spectral clustering
return (l, M[:, 0:x], M)
def getValueKey(item):
return item[1]
def getIdKey(item):
return item[0]
def sequentialGapEmbedding(kmin, kmax, B, D, C):
import importlib
import math
l, M = my_spectral_embedding(B, n_components=kmax, random_state=0)
dimension = kmax
gapsPairs=[]
eigenvalues = sorted(l, reverse=True)
averageGap = 0.
for i in range(2, len(eigenvalues)):
gap = math.fabs(eigenvalues[i]-eigenvalues[i-1])
gapsPairs.append([i, gap])
averageGap = averageGap + gap
averageGap = averageGap/len(eigenvalues)
sortedGapsPairs=sorted(gapsPairs, key=getValueKey, reverse=True)
maxgap=sortedGapsPairs[0][1]
significantGapNb = 1
for i in range(1, len(sortedGapsPairs)):
currentGap=sortedGapsPairs[i][1]
if maxgap > 0.00001 and (currentGap/maxgap > 0.1):
significantGap = i
significantGapsPairs = sortedGapsPairs[0:significantGap+1]
significantGapsPairs = sorted(significantGapsPairs, key=getIdKey)
dimension=significantGapsPairs[0][0] - 1
print("[SpectralEmbedding] Python: Found dimension from gap: ", dimension)
return (l, M[:, 0:dimension], M)
def doIt(D, mincomponents, maxcomponents, nneighbors, sigma, njobs):
# for debug purpose:
print("[SpectralEmbedding] Python: Input distance matrix:")
print(D)
import importlib
# check if Numpy is installed
loader = importlib.find_loader('numpy')
found = loader is not None
if found:
print("[SpectralEmbedding] Python: numpy module found.")
else:
print("[SpectralEmbedding] Python error: numpy module not found.")
return 0
# check if scipy is installed
loader = importlib.find_loader('scipy')
found = loader is not None
if found:
print("[SpectralEmbedding] Python: scipy module found.")
else:
print("[SpectralEmbedding] Python error: scipy module not found.")
return 0
# check if Scikit-learn is installed
loader = importlib.find_loader('sklearn')
found = loader is not None
if found:
print("[SpectralEmbedding] Python: sklearn module found.")
else:
print("[SpectralEmbedding] Python error: sklearn module not found.")
return 0
from sklearn.neighbors import kneighbors_graph
forcedDimension = sigma
print("[SpectralEmbedding] Python: maxcomponents: ", maxcomponents)
connectivity = kneighbors_graph(D, nneighbors, include_self=True)
B = 0.5 * (connectivity + connectivity.T)
print("Weight matrix:")
print(B.toarray())
maxcomponents = max(maxcomponents, 3)
if forcedDimension > 0:
values, M = my_spectral_embedding(B, n_components=maxcomponents, random_state=0)
vectors = M[:, 0:forcedDimension]
else:
values, vectors, M = sequentialGapEmbedding(mincomponents, maxcomponents, B, D, connectivity)
coords = M[:, 0:3]
# for debug purpose:
print("[SpectralEmbedding] Python: Output eigenvectors:")
print(vectors)
print("[SpectralEmbedding] Python: Output eigenvalues:")
print(values)
print("[SpectralEmbedding] Python: Output coords:")
print(coords)
# padLength = len(D) - len(values)
# Z = np.pad(values, (0, padLength), mode='constant')
# Z = np.expand_dims(Z, axis=0)
# result = np.concatenate((vectors, Z.T), axis=1)
L = list()
L.append(values)
L.append(vectors)
L.append(coords)
return L
|
da0df8008b8f89f6aee683f204faefe8957e13ea | DaphneKeys/Python-Projects- | /amazon.py | 678 | 3.609375 | 4 | #This program retrieve the price of a product from amazon
import bs4
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
}
def getAmazonPrice(productUrl):
res = requests.get(productUrl)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
elems = soup.select('#newOfferAccordionRow .header-price')
return elems[0].text.strip()
price = getAmazonPrice('http://www.amazon.com/Automate-Boring-Stuff-Python-Programming/dp/1593275994/ref=tmm_pap_swatch_0?_encoding=UTF8&qid=&sr=')
print('The price is ' + price)
|
1352d9da2da74363a4bf2613fbbd4a7be5a45018 | Vadum-cmd/lab4_345 | /point.py | 435 | 4.1875 | 4 | class Point:
"""
Makes class to work with coordinates of the point.
"""
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to_origin(self):
"""
Gives us the distance from origin to point.
"""
return (self.x ** 2 + self.y ** 2) ** 0.5
if __name__ == "__main__":
print("I'm main!")
# I really don't know what I can test here...
|
f4505262682fe32839e00c9f44d26974970ca7b2 | swetabhmukherjee/moneytor-assessment | /answer-2.py | 605 | 4.0625 | 4 | # Python code to remove duplicate elements
def duplicate_removal(arr):
if((len(arr)>=1) and (len(arr)<=1000000)):
final_list = []
for num in arr:
if num not in final_list:
final_list.append(num)
return final_list
else:
return "out of bounds"
# Driver Code
arr = [1,2,3,4,4,2,1,5,1,4,5]
print(duplicate_removal(arr))
# simple solution could have been to just convert it to a set.
# for locating the duplicates of the array, we need to visit all the elements atleast once. As such, O(nlogn) time complexity is not possible at all.
|
43ff4526380d96a3ff0ee2b68ace13fce8664cac | gracexin2003/ssp19 | /Coding/Python HW 1/GhostGame.py | 2,039 | 4.125 | 4 | # Purpose: Write a word game
# Project: Ghost Game
# Due: 6/21/19
# Name: Grace Xin
def ghost():
player = 1 # starting player is player 1, will switch in between turns
# read words.txt into a list of valid words
valid_words = []
for line in open("words.txt", "r"):
valid_words.append(line[:-1]) # to delete the /n at the end of the line
game_over = False # determines when to break from the game loop
winner = 0 # the winner of the game: will eventually be 1 or 2
current_str = ""
while not game_over: # loop until one player loses
print("Current word: " + current_str.lower())
next_letter = input("Player " + str(player) + ", enter a letter: ")
# check for invalid inputs
if next_letter.isalpha():
current_str += next_letter
else:
print("Please enter a letter.")
continue
# check if the input creates a word longer than 3 letters (losing move)
losing_move = False
for word in valid_words:
if word.lower() == current_str.lower() and len(word) > 3:
losing_move = True
winner = 3-player # winner is the other player (3-1=2, 3-2=1)
print("You created a word longer than 3 letters!")
game_over = True
break
if game_over:
break
# check if there are no words that can be made by the input (losing move)
losing_move = True
for word in valid_words:
if word[:len(current_str)].lower() == current_str.lower():
losing_move = False
if losing_move:
print("You can't make any words with that sequence!")
winner = 3-player
game_over = True
else: # if no one lost, switch players
player = 3-player
print("Game over! The winner is Player " + str(winner) + "!") #print winner
ghost() # initiate the game
|
ad9a85141199235b64b78eda73095a35c3ed4089 | doubledherin/Markov-Chains | /markov_variable_prefix_length.py | 2,700 | 3.828125 | 4 | #!/usr/bin/env python
from sys import argv
import random, string
def make_chains(corpus, num):
"""Takes an input text as a string and returns a dictionary of
markov chains."""
new_corpus = ""
for char in corpus:
# leave out certain kinds of punctuation
if char in "_[]*": # NOT WORKING DELETE THIS or char == "--":
continue
# put everything else in the new_corpus string
else:
new_corpus += char
list_of_words = new_corpus.split()
d = {}
for i in range( (len(list_of_words) - num) ):
prefix = []
for j in range(num):
prefix.append(list_of_words[i + j])
prefix = tuple(prefix)
# prefix = (list_of_words[i], list_of_words[i+1], list_of_words[i+2])
suffix = list_of_words[i+num]
if prefix not in d:
d[prefix] = [suffix] # initializes the suffix as a list
else:
d[prefix].append(suffix)
return d
def make_text(chains, num):
"""Takes a dictionary of markov chains and returns random text
based off an original text."""
# create a list of chain's keys, then return one of the keys at random
random_prefix = random.choice(chains.keys())
# from the list of values for the chosen key, return one value at random
random_suffix = random.choice(chains[random_prefix])
# initialize an empty string for our random text string
markov_text = ""
# iterate over prefix's tuple and add each word to the random text string
for word in random_prefix:
markov_text += word + " "
# then add the suffix
markov_text += random_suffix + " "
# rename random_prefix and random_suffix so that we can call them
# in a the following for loop
prefix = random_prefix
suffix = random_suffix
for i in range(1000):
# create a new prefix from the last items in the most recent prefix and
# the most recent suffix
newprefix = []
for j in range(1, num):
newprefix.append(prefix[j])
newprefix.append(suffix)
prefix = tuple(newprefix)
# choose a random suffix from the new prefix's values
suffix = random.choice(chains[prefix])
# add it all to the random text string
markov_text += "%s " % (suffix)
return markov_text
def main():
script, filename, num = argv
num = int(num)
fin = open(filename)
input_text = fin.read()
fin.close()
chain_dict = make_chains(input_text, num)
random_text = make_text(chain_dict, num)
print random_text
if __name__ == "__main__":
main() |
f3f282b2dfffe2205ae0ba484860e7fa8c524d25 | marciojmo/ai-examples | /linear-regression/linear_regression.py | 4,797 | 4.28125 | 4 | #!/usr/bin/env python
"""
A multi variate linear regression model.
"""
import numpy as np
from matplotlib import pyplot as plt
def normal_equation(x, y):
"""
Computes the closed-form solution to linear regression
:param X: The input values
:param y: The output values
:return: theta params found by normal equation
"""
return np.linalg.pinv(np.transpose(x) * x) * np.transpose(x) * y
def feature_normalize(x):
"""
Normalizes the features in x. Normalization helps gradient descent to converge faster.
:param x: Features to normalize.
:return: A normalized version of x where the mean value of each feature is 0 and
the standard deviation is 1. This is often a good preprocessing step to do when
working with learning algorithms.
"""
mu = np.mean(x, axis=0)
sigma = np.std(x, axis=0)
x_norm = np.divide((x - mu), sigma)
return x_norm, mu, sigma
def compute_cost(x, y, theta):
"""
Computes the cost of using theta as the parameter for linear regression
to fit the data points in X and y.
:param X: The training set
:param y: The result set
:param theta: The parameters
:return: The cost of using theta to predict y
"""
m = y.shape[0] # number of training examples
h = x * theta # hypothesis
errors = (h - y)
# Calculates the cost function as the average of the squared errors
j = (1 / (2 * m)) * np.transpose(errors) * errors
return j[0, 0]
def gradient_descent_multi(x, y, theta, alpha, num_iters):
"""
Performs gradient descent to learn theta params
theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by
taking num_iters gradient steps with learning rate alpha
:param x: The training data
:param y: The values
:param theta: The parameters
:param alpha: The learning rate
:param num_iters: The number of iterations
:return: A tuple object where index 0 is the values of theta found by gradient descent
and index 1 is the history of the cost function for the computed values.
"""
# Initialize some useful values
m = y.shape[0] # number of training examples
j_history = np.zeros((num_iters, 1))
for iter in range(0, num_iters):
h = (x * theta) # The hypothesis for the given theta params
errors = (h - y)
# The slope of the cost function
derivative_term = (1 / m) * (np.transpose(x) * errors)
# Simultaneously update all theta values
theta -= alpha * derivative_term
# Save the cost function for the current iteration.
# A way to debug if the algorithm is running ok is to plot
# J_history and check if it is decreasing.
j_history[iter, 0] = compute_cost(x, y, theta)
return theta, j_history
if __name__ == '__main__':
print('Loading data...')
data = np.loadtxt('data.txt', delimiter=',')
x = np.matrix(data[:, 0:-1]) # input
y = np.transpose(np.matrix(data[:, -1])) # output
m = y.shape[0] # number of training examples
# Normalizing features
print('Normalizing features...')
x, mu, sigma = feature_normalize(x)
# Adding the bias term to x. The bias term is the independent term
# I.e: ax + b, b is the bias term.
x = np.hstack((np.ones((m, 1)), x))
# Gradient descent
print('Running gradient descent...')
num_iters = 60
alpha = 1 # The learning rate
theta = np.zeros((x.shape[1], 1)) # The initial value of theta
[theta, J_history] = gradient_descent_multi(x, y, theta, alpha, num_iters)
# You can check if the gradient descent is performing ok
# through the normal equation. But notice that the normal equation is
# only suitable for small number of features (inputs). For a large number
# of features the calculation of the inverse of (x' * x) is too expensive
# and gradient descent performs better.
# theta = normal_equation(x,y) # theta found by normal equation
# Plotting the convergence graph
print('Plotting the convergence graph...')
plt.plot(range(0, J_history.shape[0]), J_history, '-b')
plt.xlabel('Number of iterations')
plt.ylabel('Cost J')
plt.show()
# Display the optimal parameters
print('Theta found: ')
print(theta)
# Estimate the price of a 1650 sq-ft, 3 br house
# Recall that the first column of X is all-ones. Thus, it does
# not need to be normalized.
size = 1650
n_bathrooms = 3
x = np.matrix((size, n_bathrooms)) # input data
x = np.divide((x - mu), sigma) # normalized
x = np.hstack((np.matrix('1'), x)) # bias term
price = x * theta
print(f'Predicted price of a {size} sq-ft, {n_bathrooms} br house: ', end = '' )
print(price[0, 0])
print()
print('THE END')
|
7d549abcfbaea95a1b63fbd443b3574a27c5fa1f | vabramson/CS115 | /lab4.py | 773 | 3.75 | 4 | """
I pledge my honor that I have abided by the Stevens Honor System
By Tim Zheng
29 Sep 2017
"""
from cs115 import filter
def knapsack(capacity, itemList):
"""which returns both the maximum value and the list of items (itemList) that make this value, without exceeding the capacity of your knapsack"""
if itemList == []:
return [0,[]]
if capacity == 0:
return [0, []]
if capacity - itemList[0][0] < 0:
return knapsack(capacity, itemList[1:])
use_it = knapsack(capacity - itemList[0][0], itemList[1:])
lose_it = knapsack(capacity, itemList[1:])
if itemList[0][1] + use_it[0] >= lose_it[0]:
return [itemList[0][1] + use_it[0]] + [[itemList[0]] + use_it[1]]
else:
return [lose_it[0]] + [lose_it[1]]
|
6d463667d3385ad9a72f46c849b8465e79ab73df | uxrishu/python-codes | /stack.py | 583 | 3.796875 | 4 | class Stack:
def __init__(self):
self.values = list()
def push(self,element):
self.values.append(element)
def isEmpty(self):
return len(self.values) == 0
def pop(self):
if not(self.isEmpty()):
return self.values.pop()
else:
print('Stack Underflow')
return None
def top(self):
if not(self.isEmpty()):
return self.values[-1]
else:
print('Stack Empty')
return None
def size(self):
return len(self.values)
def __str__(self):
stringRepr = ' '
for i in reversed(self.values):
stringRepr += str(i)+ '\t'
return stringRepr
self = [1,3,6,8,4] |
e171706b710f600ffc05c255b7db0099ee483f39 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2219/60767/237566.py | 346 | 3.75 | 4 | import math
def isAddition(num):
n = int(math.sqrt(num))
left = 1
right = n
while(left<=right):
val = left*left+right*right
if(val == num):
return True
elif(val<num):
left = left+1
else:
right = right-1
return False
num = int(input())
print(isAddition(num))
|
e945111e311e5503f97f46caebb2b4bbc645d104 | janos01/esti2020Python | /Format/iteracio.py | 206 | 3.65625 | 4 |
# Számok bekérése 0 végjelig
# Adja össze a bekért számokat
osszeg = 0
szam = -1
while szam != 0 :
szam = int(input('Szám: '))
osszeg = osszeg + szam
print('Összeg: {}'.format(osszeg))
|
d3ebc479ca67b66359afdb83f4035fe281c04d1d | javacode123/oj | /test/huawei/3.py | 1,206 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019-08-24 15:41
# @Author : Zhangjialuo
# @mail : zhang_jia_luo@foxmail.com
# @File : __init__.py.py
# @Software: PyCharm
import sys
class Solution:
def find_num(self, a, b):
length = len(a)
count = [0]*length
for m in range(length):
temp = 0
for i in range(length):
# print("the i is ", i)
flag = a[i]
# print("the first flag is ", flag)
for j in range(temp, length):
# print("the length is ", length)
# print("the temp is ", j)
# print("the test num is", b[temp])
if flag == b[j]:
# print("the like num is ", flag)
count[m] += 1
temp = j+1
continue
return length-max(count)
if __name__ == '__main__':
for line in sys.stdin: # 读作数组
s = Solution()
n = line.split()
a_arr = [int(i) for i in sys.stdin.readline().strip().split()]
b_arr = [int(i) for i in sys.stdin.readline().strip().split()]
print(s.find_num(a_arr, b_arr)) |
57be43bee40cf47a621e798bc08dd823a71a2319 | KarenYesenia/PythonCourse-Lists | /exercises/Dicts_exercise_1.py | 506 | 4.34375 | 4 | # We need to receive the basic info of user
#(first_name,last_name,age,email)
# and save them as keys into a dict call user.
#After recive the data, shw the info in the console
user = {}
user["first_name"] = input("hey bro, cual es tu nombre?:")
user["last_name"] = input("como dices que se apellidan tus gfes?: ")
user["age"] = input("ya alcanzar el timbre?: ")
user["email"] =input("pasame tu correo para enviarte unas fotos: ")
for key, value in user.items():
print(f"{key.capitalize()}: {value}") |
7a9210e5dde71427c639b4e1b6eb28c38ad2977d | Ravinder-agg/python_gui | /1_digi.py | 760 | 3.625 | 4 | import tkinter as tk
from tkinter import font
from tkinter import ttk
import datetime
import time
def quit(*args):
root.destroy()
def clock_time():
time = datetime.datetime.now()
time = (time.strftime("%d-%b-%y \n%I:%M:%S %p"))
txt.set(time)
root.after(1000,clock_time)
root = tk.Tk()
root.geometry('1000x400')
root.title("CLOCK with DATE")
root.attributes("-fullscreen",False)
root.configure(background='black')
root.bind('x',quit) # when you press x program will quit
root.after(1000,clock_time)
fnt = font.Font(family="Halvetica", weight="bold", size=120)
txt = tk.StringVar()
lbl = ttk.Label(root, textvariable=txt, font=fnt, foreground='white', background="black")
lbl.place(relx=0.5,rely=0.5,anchor=tk.CENTER)
root.mainloop() |
b2cb8b71f1d64d685110d7151c9c950859275367 | bekkam/code-challenges-python-easy | /dec2bin.py | 2,632 | 4.375 | 4 | """Convert a decimal number to binary representation.
For example::
>>> dec2bin_backwards(0)
'0'
>>> dec2bin_backwards(1)
'1'
>>> dec2bin_backwards(2)
'10'
>>> dec2bin_backwards(4)
'100'
>>> dec2bin_backwards(15)
'1111'
For example, using our alternate solution::
>>> dec2bin_forwards(0)
'0'
>>> dec2bin_forwards(1)
'1'
>>> dec2bin_forwards(2)
'10'
>>> dec2bin_forwards(4)
'100'
>>> dec2bin_forwards(15)
'1111'
"""
# Solution 1: convert decimal to binary using a stack
class Stack(object):
def __init__(self):
self._stack = []
def push(self, item):
"""Push item onto to top of stack"""
self._stack.append(item)
def pop(self):
"""Remove top item of stack"""
return self._stack.pop()
def peek(self):
"""Return, but don't remove, top item of stack"""
return self._stack[-1]
def is_empty(self):
"""Return true if stack is empty, else return false"""
return not self._stack
def dec2bin(num):
"""Convert a decimal number to binary representation."""
result = ""
stack = Stack()
# if the remainder of num/2 is even, push 0 to stack. otherwise, push 1 to stack.
# num = num/2
while num >= 1:
remainder = num % 2
stack.push(0) if remainder % 2 == 0 else stack.push(1)
num = num/2
while stack.is_empty() is False:
result += str(stack.pop())
return result
# print dec2bin(15)
# ##############################################################
# Solution 2
def dec2bin_forwards(num):
"""Convert decimal to binary by first calculating the number of bits(places)"""
out = ""
# Figure out how many bits(place-values) this will have
num_bits = 1
while 2 ** num_bits <= num:
print num_bits
num_bits += 1
"""For every place value, starting with the highest place-value:
subtract [2 to the exponent of place-value] from num.
If the result is greater than 0, add 1 to out. Else add 0 to out
"""
for position in range(num_bits - 1, -1, -1):
print "num is ", num
print "position is ", position
if 2 ** position <= num:
num -= 2 ** position
out += "1"
print "added 1 to out"
else:
print "added 0 to out"
out += "0"
print "out is ", out
return out
print dec2bin_forwards(5)
# if __name__ == '__main__':
# import doctest
# if doctest.testmod().failed == 0:
# print "\n*** ALL TEST PASSED. W00T!\n"
|
0be6f317bd9daab3ac4f570deaaa211b9689661f | edwardmasih/Python-School-Level | /Class 11/11-Programs/Projectile motion.py | 586 | 4 | 4 | import math
u=int(input("Enter The Initial Velocity of The Object to be Projected (in m/s)==> "))
a=int(input("Enter The Angle of Projection (in degrees)==> "))
g=9.8
sin = (math.sin(math.radians(a)))
cos = (math.cos(math.radians(a)))
T =(2*u*sin)/g
H =(u**2)*((sin)**2)/(2*g)
R =(2*(u**2)*(sin)*(cos))/g
print()
print()
print("The Time Taken By the Projectile is ",T)
print()
print("The Height is ",H)
print()
print("The Range of the Projectile is ",R)
|
9c037f794aa0ea5b8c876c6f23f3f70ab4dbdf6a | Pranav-21/psm | /Employee contact management.py | 15,684 | 3.59375 | 4 |
from tkinter import *
import sqlite3
import tkinter.ttk as ttk
import tkinter.messagebox as tkMessageBox
root = Tk()
root.title("Employee Contact List")
width = 1200
height = 600
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(1, 1)
#============================VARIABLES===================================#
NAME = StringVar()
GENDER = StringVar()
ADDRESS = StringVar()
CONTACT = StringVar()
EMAIL = StringVar()
QUALIFICATION = StringVar()
SKILLS = StringVar()
DEPARTMENT = StringVar()
WORK = StringVar()
#============================METHODS=====================================#
def Database():
conn = sqlite3.connect("employee.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT, gender TEXT, address TEXT, contact TEXT, email TEXT, qualification TEXT, skills TEXT, department TEXT, work TEXT)")
cursor.execute("SELECT * FROM `member` ORDER BY `department` ASC")
fetch = cursor.fetchall()
for data in fetch:
tree.insert('', 'end', values=(data))
cursor.close()
conn.close()
def SubmitData():
if NAME.get() == "" or QUALIFICATION.get() == "" or DEPARTMENT.get() == "" or GENDER.get() == "" or SKILLS.get() == "" or ADDRESS.get() == "" or CONTACT.get() == "" or EMAIL.get() == ""or WORK.get() == "":
result = tkMessageBox.showwarning('', 'Please Complete The Required Field', icon="warning")
else:
tree.delete(*tree.get_children())
conn = sqlite3.connect("employee.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO `member` (name, gender, address, contact,email,qualification, skills, department,work) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", (str(NAME.get()), str(GENDER.get()), str(ADDRESS.get()), int(CONTACT.get()), str(EMAIL.get()),str(QUALIFICATION.get()), str(SKILLS.get()), str(DEPARTMENT.get()), str(WORK.get())))
conn.commit()
cursor.execute("SELECT * FROM `member` ORDER BY `department` ASC")
fetch = cursor.fetchall()
for data in fetch:
tree.insert('', 'end', values=(data))
cursor.close()
conn.close()
NAME.set("")
GENDER.set("")
ADDRESS.set("")
CONTACT.set("")
EMAIL.set("")
QUALIFICATION.set("")
SKILLS.set("")
DEPARTMENT.set("")
WORK.set("")
def UpdateData():
if NAME.get() == "" or QUALIFICATION.get() == "" or DEPARTMENT.get() == "" or GENDER.get() == "" or SKILLS.get() == "" or ADDRESS.get() == "" or CONTACT.get() == "" or EMAIL.get() == ""or WORK.get() == "":
result = tkMessageBox.showwarning('', 'Please Complete The Required Field', icon="warning")
else:
tree.delete(*tree.get_children())
conn = sqlite3.connect("employee.db")
cursor = conn.cursor()
cursor.execute("UPDATE `member` SET `name` = ?, `gender` =?, `address` = ?, `contact` = ?, `email` = ?, `qualification` = ?, `skills` = ?, `department` = ?, `work` = ? WHERE `mem_id` = ?", (str(NAME.get()), str(GENDER.get()), str(ADDRESS.get()), int(CONTACT.get()), str(EMAIL.get()),str(QUALIFICATION.get()), str(SKILLS.get()) , str(DEPARTMENT.get()), str(WORK.get()), int(mem_id)))
conn.commit()
cursor.execute("SELECT * FROM `member` ORDER BY `department` ASC")
fetch = cursor.fetchall()
for data in fetch:
tree.insert('', 'end', values=(data))
cursor.close()
conn.close()
NAME.set("")
GENDER.set("")
ADDRESS.set("")
CONTACT.set("")
EMAIL.set("")
QUALIFICATION.set("")
SKILLS.set("")
DEPARTMENT.set("")
WORK.set("")
def OnSelected(event):
global mem_id, UpdateWindow
curItem = tree.focus()
contents =(tree.item(curItem))
selecteditem = contents['values']
mem_id = selecteditem[0]
NAME.set("")
GENDER.set("")
ADDRESS.set("")
CONTACT.set("")
EMAIL.set("")
QUALIFICATION.set("")
SKILLS.set("")
DEPARTMENT.set("")
WORK.set("")
NAME.set(selecteditem[1])
ADDRESS.set(selecteditem[3])
CONTACT.set(selecteditem[4])
EMAIL.set(selecteditem[5])
QUALIFICATION.set(selecteditem[6])
SKILLS.set(selecteditem[7])
DEPARTMENT.set(selecteditem[8])
WORK.set(selecteditem[9])
UpdateWindow = Toplevel()
UpdateWindow.title("Employee Contact List")
width = 600
height = 400
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = ((screen_width/2) + 450) - (width/2)
y = ((screen_height/2) + 20) - (height/2)
UpdateWindow.resizable(0, 0)
UpdateWindow.geometry("%dx%d+%d+%d" % (width, height, x, y))
if 'NewWindow' in globals():
NewWindow.destroy()
#===================FRAMES==============================#
FormTitle = Frame(UpdateWindow)
FormTitle.pack(side=TOP)
ContactForm = Frame(UpdateWindow)
ContactForm.pack(side=TOP, pady=10)
RadioGroup = Frame(ContactForm)
Male = Radiobutton(RadioGroup, text="Male", variable=GENDER, value="Male", font=('arial', 14)).pack(side=LEFT)
Female = Radiobutton(RadioGroup, text="Female", variable=GENDER, value="Female", font=('arial', 14)).pack(side=LEFT)
#===================LABELS==============================#
lbl_title = Label(FormTitle, text="Updating Contacts", font=('arial', 16), bg="yellow", width = 300)
lbl_title.pack(fill=X)
lbl_name = Label(ContactForm, text="Name", font=('arial', 14), bd=5)
lbl_name.grid(row=0, sticky=W)
lbl_gender = Label(ContactForm, text="Gender", font=('arial', 14), bd=5)
lbl_gender.grid(row=1, sticky=W)
lbl_address = Label(ContactForm, text="Address", font=('arial', 14), bd=5)
lbl_address.grid(row=2, sticky=W)
lbl_contact = Label(ContactForm, text="Contact", font=('arial', 14), bd=5)
lbl_contact.grid(row=3, sticky=W)
lbl_email = Label(ContactForm, text="email", font=('arial', 14), bd=5)
lbl_email.grid(row=4, sticky=W)
lbl_qualification = Label(ContactForm, text="Qualification", font=('arial', 14), bd=5)
lbl_qualification.grid(row=5, sticky=W)
lbl_skills = Label(ContactForm, text="SKILLS", font=('arial', 14), bd=5)
lbl_skills.grid(row=6, sticky=W)
lbl_department = Label(ContactForm, text="Department", font=('arial', 14), bd=5)
lbl_department.grid(row=7, sticky=W)
lbl_work = Label(ContactForm, text="work", font=('arial', 14), bd=5)
lbl_work.grid(row=8, sticky=W)
#===================ENTRY===============================#
name = Entry(ContactForm, textvariable=NAME, font=('arial', 14))
name.grid(row=0, column=1)
RadioGroup.grid(row=1, column=1)
address = Entry(ContactForm, textvariable=ADDRESS, font=('arial', 14))
address.grid(row=2, column=1)
contact = Entry(ContactForm, textvariable=CONTACT, font=('arial', 14))
contact.grid(row=3, column=1)
email = Entry(ContactForm, textvariable=EMAIL, font=('arial', 14))
email.grid(row=4, column=1)
qualification = Entry(ContactForm, textvariable=QUALIFICATION, font=('arial', 14))
qualification.grid(row=5, column=1)
department = Entry(ContactForm, textvariable=DEPARTMENT, font=('arial', 14))
department.grid(row=6, column=1)
skills = Entry(ContactForm, textvariable=SKILLS, font=('arial', 14))
skills.grid(row=7, column=1)
work = Entry(ContactForm, textvariable=WORK, font=('arial', 14))
work.grid(row=8, column=1)
#==================BUTTONS==============================#
btn_updatecon = Button(ContactForm, text="Update", width=50,border = "10",activebackground="orange", command=UpdateData)
btn_updatecon.grid(row=9, columnspan=2, pady=10)
def DeleteData():
if not tree.selection():
result = tkMessageBox.showwarning('', 'Please Select Something First!', icon="warning")
else:
result = tkMessageBox.askquestion('', 'Are you sure you want to delete this record?', icon="warning")
if result == 'yes':
curItem = tree.focus()
contents =(tree.item(curItem))
selecteditem = contents['values']
tree.delete(curItem)
conn = sqlite3.connect("employee.db")
cursor = conn.cursor()
cursor.execute("DELETE FROM `member` WHERE `mem_id` = %d" % selecteditem[0])
conn.commit()
cursor.close()
conn.close()
def AddNewWindow():
global NewWindow
NAME.set("")
GENDER.set("")
ADDRESS.set("")
CONTACT.set("")
EMAIL.set("")
QUALIFICATION.set("")
SKILLS.set("")
DEPARTMENT.set("")
WORK.set("")
NewWindow = Toplevel()
NewWindow.title("Employee Contact List")
width = 600
height = 400
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = ((screen_width/2) - 455) - (width/2)
y = ((screen_height/2) + 20) - (height/2)
NewWindow.resizable(0, 0)
NewWindow.geometry("%dx%d+%d+%d" % (width, height, x, y))
if 'UpdateWindow' in globals():
UpdateWindow.destroy()
#===================FRAMES==============================#
FormTitle = Frame(NewWindow)
FormTitle.pack(side=TOP)
ContactForm = Frame(NewWindow)
ContactForm.pack(side=TOP, pady=10)
RadioGroup = Frame(ContactForm)
Male = Radiobutton(RadioGroup, text="Male", variable=GENDER, value="Male", font=('arial', 14)).pack(side=LEFT)
Female = Radiobutton(RadioGroup, text="Female", variable=GENDER, value="Female", font=('arial', 14)).pack(side=LEFT)
#===================LABELS==============================#
lbl_title = Label(FormTitle, text="Add New Employee Contact", font=('arial', 16), bg="#66ff66", width = 300)
lbl_title.pack(fill=X)
lbl_name = Label(ContactForm, text="Name", font=('arial', 14), bd=5)
lbl_name.grid(row=0, sticky=W)
lbl_gender = Label(ContactForm, text="Gender", font=('arial', 14), bd=5)
lbl_gender.grid(row=1, sticky=W)
lbl_address = Label(ContactForm, text="Address", font=('arial', 14), bd=5)
lbl_address.grid(row=2, sticky=W)
lbl_contact = Label(ContactForm, text="Contact", font=('arial', 14), bd=5)
lbl_contact.grid(row=3, sticky=W)
lbl_email = Label(ContactForm, text="email", font=('arial', 14), bd=5)
lbl_email.grid(row=4, sticky=W)
lbl_qualification = Label(ContactForm, text="Qualification", font=('arial', 14), bd=5)
lbl_qualification.grid(row=5, sticky=W)
lbl_skills = Label(ContactForm, text="SKILLS", font=('arial', 14), bd=5)
lbl_skills.grid(row=6, sticky=W)
lbl_department = Label(ContactForm, text="Department", font=('arial', 14), bd=5)
lbl_department.grid(row=7, sticky=W)
lbl_work = Label(ContactForm, text="work", font=('arial', 14), bd=5)
lbl_work.grid(row=8, sticky=W)
#===================ENTRY===============================#
name = Entry(ContactForm, textvariable=NAME, font=('arial', 14))
name.grid(row=0, column=1)
RadioGroup.grid(row=1, column=1)
address = Entry(ContactForm, textvariable=ADDRESS, font=('arial', 14))
address.grid(row=2, column=1)
contact = Entry(ContactForm, textvariable=CONTACT, font=('arial', 14))
contact.grid(row=3, column=1)
email = Entry(ContactForm, textvariable=EMAIL, font=('arial', 14))
email.grid(row=4, column=1)
qualification = Entry(ContactForm, textvariable=QUALIFICATION, font=('arial', 14))
qualification.grid(row=5, column=1)
department = Entry(ContactForm, textvariable=DEPARTMENT, font=('arial', 14))
department.grid(row=6, column=1)
skills = Entry(ContactForm, textvariable=SKILLS, font=('arial', 14))
skills.grid(row=7, column=1)
work = Entry(ContactForm, textvariable=WORK, font=('arial', 14))
work.grid(row=8, column=1)
#==================BUTTONS==============================#
btn_addcon = Button(ContactForm, text="Save", width=50,border = "10",activebackground="orange", command=SubmitData)
btn_addcon.grid(row=9, columnspan=2, pady=10)
#============================FRAMES======================================#
Top = Frame(root, width=500, bd=1, relief=SOLID)
Top.pack(side=TOP)
Mid = Frame(root, width=500 )
Mid.pack(side=TOP)
MidLeft = Frame(Mid, width=100)
MidLeft.pack(side=LEFT, pady=10)
MidLeftPadding = Frame(Mid, width=370)
MidLeftPadding.pack(side=LEFT)
MidRight = Frame(Mid, width=100)
MidRight.pack(side=RIGHT, pady=10)
TableMargin = Frame(root, width=500)
TableMargin.pack(side=TOP)
#============================LABELS======================================#
lbl_title = Label(Top, text="Employee Contact Management System", font=('arial', 16), width=500,background="orange")
lbl_title.pack(fill=X)
#============================ENTRY=======================================#
#============================BUTTONS=====================================#
btn_add = Button(MidLeft, text="ADD", bg="#66ff66",border = "10",activebackground="orange",width=40,height=5, command=AddNewWindow)
btn_add.pack()
btn_delete = Button(MidRight, text="REMOVE", bg="red",border = "10",activebackground="orange",width=40,height=5, command=DeleteData)
btn_delete.pack(side=RIGHT)
#============================TABLES======================================#
scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL)
scrollbary = Scrollbar(TableMargin, orient=VERTICAL)
tree = ttk.Treeview(TableMargin, columns=("MemberID", "name", "Gender", "Address", "Contact", "qualification", "Skills","department" ,"email","work"), height=400, selectmode="extended", yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
scrollbary.config(command=tree.yview)
scrollbary.pack(side=RIGHT, fill=Y)
scrollbarx.config(command=tree.xview)
scrollbarx.pack(side=BOTTOM, fill=X)
style = ttk.Style()
style.configure("Treeview.Heading",foreground="blue",background="orange", font=(None, 12,'bold'))
style.configure("Treeview.column",fieldbackground="green")
tree.heading('MemberID', text="MemberID", anchor=W)
tree.heading('name', text="Name", anchor=W)
tree.heading('Gender', text="Gender", anchor=W)
tree.heading('Address', text="Address", anchor=W)
tree.heading('Contact', text="Contact", anchor=W)
tree.heading('qualification', text="Qualification", anchor=W)
tree.heading('Skills', text="Skills", anchor=W)
tree.heading('department', text="Department", anchor=W)
tree.heading('email', text="email", anchor=W)
tree.heading('work', text="work", anchor=W)
tree.column('#0', stretch=NO, minwidth=0, width=0)
tree.column('#1', stretch=NO, minwidth=0, width=120)
tree.column('#2', stretch=NO, minwidth=0, width=120)
tree.column('#3', stretch=NO, minwidth=0, width=120)
tree.column('#4', stretch=NO, minwidth=0, width=120)
tree.column('#5', stretch=NO, minwidth=0, width=120)
tree.column('#6', stretch=NO, minwidth=0, width=120)
tree.column('#7', stretch=NO, minwidth=0, width=120)
tree.column('#8', stretch=NO, minwidth=0, width=120)
tree.column('#9', stretch=NO, minwidth=0, width=120)
tree.column('#10', stretch=NO, minwidth=0, width=120)
tree.pack()
tree.bind('<Double-Button-1>', OnSelected)
# INITIALIZATION #
if __name__ == '__main__':
Database()
root.mainloop() |
d51109538231a86744851112ae160615c077b8eb | cs-learning-2019/python2sat | /Lessons/Week21/Python_Classes_1/Python_Classes_1.pyde | 5,115 | 4.625 | 5 | # Focus Learning: Python Level 2
# Python Classes
# Kavan Lam
# Feb 19, 2021
"""
We already learned about the different data types in Python. For example, str, float, bool, int and list.
Now we will go through how to create our own data types
In Python there are already pre-made data type such as list, dictionary, int, float and string. When
we think of list we think of it like a container that can hold things right? So when programming if we
needed something to be able to hold things for us we can use a list which is an object.
Alright, what if we wanted to represent people in code? Can we use an int? Well no... a person has an age, height, name
and etc. So a simple int will not be enough to represent a person. What about a list? We could store the age, height
name and etc in the list. Well... that works but is not a very good way to represent people. The better solution
will be to create a new data type that represents a person. Below is how we do it.
"""
class Person:
def __init__(self, the_age, the_name, the_person_height):
self.age = the_age
self.name = the_name
self.person_height = the_person_height
def get_name(self):
return self.name
def get_age(self):
return self.age
def get_height(self):
return self.person_height
def __lt__(self, other_person):
if self.age < other_person.age:
return True
else:
return False
def __eq__(self, other_person):
if self.age == other_person.age:
return True
else:
return False
def __len__(self):
return self.person_height
def __str__(self):
return "Hi my name is " + self.name
john = Person(10, "Jonny", 130)
joy = Person(10, "Joy", 131)
print(john.get_age())
print(joy.get_age())
if john == joy:
print("They are the same age!")
else:
print("They are not the same age")
print(john)
print(len(john))
"""
Alright looks a bit confusing right? No worries we will go through each piece.
To tell Python that you want to define a new object you use the "class" keyword.
Directly after the class keyword you give the object a name in this case we
named it Person (case-sensitive). After that, define all the components and contents
of the new object. The first four are easy to understand and you have seen stuff like this before.
The only difference now is that these belong to a class so they are no longer called functions
and instead they are called methods. In particular, they are methods for the class/object Person.
The first method __init__ is a special kind on method. It is what we call a constructor. This special
method will exist for a lot of classes you write, but is not required. Think of this special method as a blueprint for Python to
know how to build and initialize a person when you tell Python to make one. The last part you should
be confused about is the keyword "self". There are many definitions online, but think of self as a
placeholder for an actual object. When we defined the get_name method we had to do self.name and
not just print name. The reason is because there can be multiple people so how does Python know which
name to print? This is why we need to use self. self is a placeholder for the actual object that calls the method.
When we define the method we do it generally so it works for all Person objects. So when we do john.get_age()
the person object stored inside the var john calls the get_age method which does return self.age, but the self
gets replaced with john so it really does return john.name which makes a lot more sense. Got it?
Ok now lets do harder examples. One more thing course_code and student_names are what we call attributes.
"""
print("------------------------------------------------")
class Course:
def __init__(self, code):
self.course_code = code
self.student_names = []
def get_course_code(self):
return self.course_code
def print_course_code(self):
print(self.course_code)
def add_student(self, new_student):
self.student_names.append(new_student)
def print_student_names(self):
print(self.student_names)
"""
Lets use our class and see if everything works as expected
"""
a_course = Course("ICS4U")
a_course.add_student("zBob")
a_course.add_student("Lee")
a_course.add_student("Ding")
a_course.add_student("Dong")
a_course.print_student_names()
print("------------------------------------------------")
"""
Write and design a class called AreaFinder. AreaFinder will have one method for each shape.
AreaFinder needs to be able to take care of circles, rectangles and triangles.
"""
class AreaFinder:
def get_area_rec(self, height, width):
return height * width
def get_area_circle(self, radius):
return 3.14 * (radius ** 2)
def get_are_trianlge(self, base, height):
return (base * height) // 2
x = AreaFinder()
print (x.get_area_rec(6, 10))
|
76191734f9f965d49a7bba942185199ef7e64970 | drcpcg/codebase | /Array/equilibrium-index-of-an-array.py | 1,537 | 4.09375 | 4 | # https://www.geeksforgeeks.org/equilibrium-index-of-an-array/
"""
refer to cpp version
Input: A[] = {-7, 1, 5, 2, -4, 3, 0}
Output: 3
3 is an equilibrium index, because:
A[0] + A[1] + A[2] = A[4] + A[5] + A[6]
"""
# Python program to find the equilibrium
# index of an array
# function to find the equilibrium index
def equilibrium(arr):
# finding the sum of whole array
total_sum = sum(arr)
leftsum = 0
for i, num in enumerate(arr):
# total_sum is now right sum
# for index i
total_sum -= num
#print("RighSum {}".format(total_sum))
#print("LeftSum {} \n".format(leftsum))
if leftsum == total_sum:
return i
leftsum += num
# If no equilibrium index found,
# then return -1
return -1
def equilibriumEasy(arr):
n = len(arr)
for i in range(n):
leftsum = 0
rightsum = 0
# get left sum
for j in range(i):
leftsum += arr[j]
# get right sum
for j in range(i + 1, n):
rightsum += arr[j]
# if leftsum and rightsum are same, then we are done
if leftsum == rightsum:
return i
# return -1 if no equilibrium index is found
return -1
# Driver code
arr = [1, 3, 5, 2, 2]
print ('First equilibrium index is Efficient ', equilibrium(arr))
print ('First equilibrium index is EasyMethod ', equilibriumEasy(arr))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.