Dataset Viewer (First 5GB)
max_stars_repo_path
null | max_stars_repo_name
null | max_stars_count
null | id
null | text
string | score
float64 | int_score
int64 | from
string | blob_id
string | repo_name
string | path
string | length_bytes
int64 |
---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | null |
#Python Program to Display the multiplication Table
print("ENTER NUMBER FOR CACULATE MULTIPLICATION TABLE")
var1=int(input())
i=1
while(i<=10):
res=int(var1)*int(i)
print(var1,"*",i,"=",res,"\n")
i=i+1
| 4.4375 | 4 |
smollm
|
e4abe21c4a158dbf1381926f63cce2925edc4fea
|
The-Smashers-Design/multiplication-Table.github.io
|
/NINE.py
| 230 |
null | null | null | null |
OKONOMIYAKI_MENU = {
'Aメニュー': {'もち', '明太子', '豚肉'},
'Bメニュー': {'キムチ', '明太子', '牛肉'},
'Cメニュー': {'チーズ', '天かす', '牛肉'},
'Dメニュー': {'もち', 'チーズ', 'イカ'},
}
def output_complement_menu(want_to_eat):
for menu_name, gu_set in OKONOMIYAKI_MENU.items():
gu_issubset = want_to_eat <= gu_set # 食べたいものが全て含まれている
gu_intersection = want_to_eat & gu_set # 一部、食べたいものが含まれる
if gu_issubset:
print('{}に食べたい具が全て揃っています:{}'.format(menu_name, gu_set))
elif gu_intersection:
print('{}に食べたい具が一部あります:{}'.format(menu_name, gu_intersection))
additional_topping = want_to_eat - gu_set
print(' 追加トッピングは{}です'.format(additional_topping))
else:
print('{}には、食べたい具が含まれません'.format(menu_name))
def main():
want_to_eat = {'明太子', 'もち'}
print('食べたい具: {}'.format(want_to_eat))
output_complement_menu(want_to_eat)
if __name__ == '__main__':
main()
| 3.53125 | 4 |
smollm
|
55eb46725962e31c569c37e8789eed0dfa59760f
|
Hiroto710281/Okonomiyaki_Menu
|
/Okonomiyaki_Menu.py
| 1,265 |
null | null | null | null |
print(''' 5. При помощи циклов и логики реализовать вывод в консоль фигуры песочных часов из символов "*",
пользователь задаёт высоту и ширину(в количестве элементов).
Примечание: числа, вводимые пользователем должны быть чётными для корректной -"отрисовки".
''')
import numpy
while True:
try:
n = int(input("Высота: "))
d = float(input("Ширина: "))
if n == 0 or d == 0:
print("значения не могут быть 0")
break
except ValueError:
print("Ведите Целое число")
s = [n, d]
bl = max(s)/min(s)
bh = min(s)/max(s)
max = max(s)
if max%2 == 0:
r = int(max)
else:
r = int(max+1)
if n==d or (n%2 == 0):
poz1_end = round((1/2)*n)
poz2_start = poz1_end
elif n>d or n<d:
poz1_end = round(((1 / 2) * n) - 0.5)
poz2_start = round(((1 / 2) * n) + 0.5)
# print(poz1_end)
# print(poz2_start)
list_L = [X for X in numpy.arange(1, d+1, bl)]
list_H = [Y for Y in numpy.arange(1, d+1, bh)]
# print(list_L)
# print(list_H)
if n<=d:
koef = list_L
elif n>d:
koef = list_H
# print(koef)
poz = -1
poz = poz2_start
for i in range(n-1, 1, -1):
poz -= 1
kol = int(round(koef[poz]))
# print("*" * kol)
cen = ("*" * kol)
print(cen.center(r))
if i == poz1_end:
break
for i in range(1, n):
poz += 1
kol = int(round(koef[poz]))
# print("*" * kol)
cen = ("*" * kol)
print(cen.center(r))
if i == poz1_end:
break
| 4.03125 | 4 |
smollm
|
b4d6e950e768099470f0ab2163e49a96c6d8c8cd
|
LoyalSkm/Home_work_2_base
|
/hw2_task_5.py
| 1,692 |
null | null | null | null |
def q1_a(i1, i2):
items = [4, 5, 6, 8]
result = items[i1] * items[i2]
return result
def q1_b():
names = ["apples" , "bananas", "grapes"]
values = [5, 3, 7]
for idx, name in enumerate(names):
if name == "apples":
return values[idx]
else:
return None
def q1_c():
d = {"apples" : 5, "bananas": 3, "grapes": 7}
return d["apples"]
def q1_d():
"""
Finds and returns the maximum value inside a list
"""
vector = [2,4,5,6]
max_value = 0
for item in vector:
if item > max_value:
max_value = item
return max_value
def q1_e():
"""
Finds and returns the maximum value inside nested two lists (like a matrix)
"""
# Here we have a matrix, 2x4 (2 rows, 4 columns)
matrix = [[2,4,5,6],
[1,0,0,7]]
max_value = 0
for row in matrix:
for item in row:
if item > max_value:
max_value = item
return max_value
def q1_f():
"""
Finds and returns the maximum value inside nested three lists (like a matrix)
"""
# Here we have a matrix, 2x3x4 two matrices of (3 rows, 4 columns) ~ tensor.
tensor =[[[2, 4, 5, 6],
[1, 0, 9, 7],
[2, 3, 4, 5]],
[[5, 4, 5, 8],
[2, 3, 3, 4],
[7, 1, 1, 5]]]
max_value = 0
for matrix in tensor:
for row in matrix:
for item in row:
if item > max_value:
max_value = item
return max_value
if __name__ == "__main__":
print("A: ", q1_a(1,2))
print("B: ", q1_b())
print("C: ", q1_c())
print("D: ", q1_d())
print("E: ", q1_e())
print("F: ", q1_f())
| 3.75 | 4 |
smollm
|
48762a2476746ae43c6d40624178877527d66db4
|
KocUniversity/COMP100-2021S-Week10-StudyQuestions
|
/q1.py
| 1,656 |
null | null | null | null |
#!/usr/bin/env python
import sys
def main():
if len(sys.argv) < 4:
print "Usage:", sys.argv[0], "<mode> <key> <input>"
print " <mode> can be 'encrypt'/'e' or 'decrypt'/'d'"
print " <key> is the encryption/decryption key"
print " <input> plaintext/ciphertext"
sys.exit()
mode = sys.argv[1]
key = sys.argv[2]
intxt = sys.argv[3]
if len(intxt) % len(key) != 0:
print 'incorrect keylength'
sys.exit(1)
#TODO key checking
if mode == 'e' or mode == 'encrypt':
m = i = 0
while True:
j = 0
while j < len(key):
if i == len(intxt):
sys.exit(0)
sys.stdout.write(intxt[int(key[j]) + m - 1])
j += 1
i += 1
m += len(key)
if mode == 'd' or mode == 'decrypt':
m = i = 0
outtxt = []
while True:
j = 0
while j < len(key):
if i == len(intxt):
print ''.join(outtxt)
sys.exit(0)
outtxt.insert(int(key[j]) + m - 1, intxt[i])
j += 1
i += 1
m += len(key)
if __name__ == '__main__':
main()
| 3.734375 | 4 |
smollm
|
5e3d5c8a99d5fa409732882f66ec3c1a079dd188
|
viren-nadkarni/codu
|
/ccns/transposition.py
| 1,319 |
null | null | null | null |
# Sorting a List using Quicksort in Python
# 2011-05-16
def quickSort(toSort):
if len(toSort) <= 1:
return toSort
end = len(toSort) - 1
pivot = toSort[end]
low = []
high = []
for num in toSort[:end]:
if num <= pivot:
low.append(num)
else:
high.append(num)
sortedList = quickSort(low)
sortedList.append(pivot)
sortedList.extend(quickSort(high))
return sortedList
def main():
l = [187,62,155,343,184,958,365,427,78,121,388]
sortedList = quickSort(l)
print sortedList
if __name__ == '__main__':
main()
| 4.03125 | 4 |
smollm
|
48b22ecf30770a737885664b5f0dca66c9fd82eb
|
viren-nadkarni/codu
|
/madf/qs.py
| 536 |
null | null | null | null |
score = input("Enter score between 0.1 and 1.0:")
if float(score) > 1.0 or float(score) < 0.0 :
print("Score out of range!")
if float(score) >= 0.9 :
print("A")
elif float(score) >= 0.8 :
print("B")
elif float(score) >= 0.7 :
print("C")
elif float(score) >= 0.6 :
print("D")
elif float(score) < 0.6 :
print("F)")
| 3.984375 | 4 |
smollm
|
508640c5384ee8e87acf75f6cdc37236b4b99df1
|
crash48/python-class
|
/assignment3_3.py
| 339 |
null | null | null | null |
# Date created: 23/01/2019
# Dice rolling simulation
from random import randrange
cont = 1
while cont == 1:
print("Roll dice: ", randrange(1,7,1))
cont = int(input("Continue? 0/1 "))
while cont != 0 and cont != 1:
print("Input invalid")
cont = int(input("Continue? 0/1 "))
| 3.6875 | 4 |
smollm
|
b1429e355b5fe50fbee168f41d5a477ebd71de13
|
NhanNgocThien/IlearnPython
|
/dice_rolling.py
| 303 |
null | null | null | null |
#This program adds twelves student name and their average grades
#to grades.txt file
def main():
#open and write student grades.txt file
try:
student_grade = open('grades.txt', 'w')
#create a for loop
for students in range(12):
#Get student name
name = input('Enter student name: ')
ave_grade = float(input('Enter average grade: '))
#Append the data to the file.
student_grade.write(name +'\n')
student_grade.write(str(ave_grade) +'\n')
#close the file
student_grade.close()
print('Data appended to grades.txt')
except ValueError as err:
print('An error occured. Grade entered is out of range 1 and 100.')
try:
#open the grades.txt file
grades = open('grades.txt','r')
#read the first name field
name = grades.readline()
#read the rest of the file
while name != '':
#read the aveage grade field
average = float(grades.readline())
#strip the \n from student name
name = name.rstrip('\n')
#display the record.
print('Name: ', name)
print('Average Grade: ', average)
#read the next student name
name = grades.readline()
#close the student grade file
grades.close()
except IOError:
print('An error occured trying to read the file')
print('Enter the correct file name.')
except ImportError:
print('An error occured trying to read the file')
#call the main function
main ()
| 4.21875 | 4 |
smollm
|
7cae26c784017ac8402f8d80d72cebcb539870b2
|
sharlenemutto/Big-Data
|
/Student Data.py
| 1,764 |
null | null | null | null |
#!/usr/local/bin/python3
import os
def rename():
path = os.path.abspath('.') # 获得当前工作目录
filelist = os.listdir(path) # 该文件夹下所有的文件(包括文件夹)
for files in filelist: # 遍历所有文件
Olddir = os.path.join(path, files) # 原来的文件路径
if os.path.isdir(Olddir): # 如果是文件夹则跳过
continue
filename = os.path.splitext(files)[0] # 文件名
if "_jiagu_" in filename:
filename = "BCZP"
elif "_1_" in filename:
filename = "BCZP_360"
elif "_2_" in filename:
filename = "BCZP_sjqq"
elif "_3_" in filename:
filename = "BCZP_wandoujia"
elif "_4_" in filename:
filename = "BCZP_baidu"
elif "_5_" in filename:
filename = "BCZP_xiaomi"
elif "_6_" in filename:
filename = "BCZP_huawei"
elif "_7_" in filename:
filename = "BCZP_oppo"
elif "_8_" in filename:
filename = "BCZP_vivo"
filetype = os.path.splitext(files)[1] # 文件扩展名
Newdir = os.path.join(path, filename + filetype) # 新的文件路径
os.rename(Olddir, Newdir) # 重命名
rename()
| 3.546875 | 4 |
smollm
|
50aa78f15817ad87ab8342ddd73252e42ea68a37
|
xuchengcan/MyPythonDemo
|
/rename.py
| 1,281 |
null | null | null | null |
#Simple GUI test
# import all tkinter in the program's global scope
from tkinter import *
# import requests for the http fetch
import requests
# create a root window
root = Tk()
#modify the window
root.title("Simple GUI")
root.geometry("200x100")
#create frame in the window to hold other widgets
app = Frame(root)
#invoque grid() method
app.grid()
#Window anf fram are now in place
##
#create a label in the frame
lbl = Label(app,text = "this is a label")
# invoke the lbl object's grid method
lbl.grid()
##
#create a button in the frame
button1 = Button(app,text = "Button1")
button1.grid()
button2 = Button(app)
button2.grid()
button3 = Button(app)
button3.grid()
#alternative 1 to label property
button2.configure(text = "Button2")
#alternative 2 to label property
button3["text"] = "button 3"
#test - modify label with currency valur
r = requests.get("http://www.apilayer.net/api/live?access_key=7a0b7a73ad149f3f992ffe00606675e6&format=1")
data = r.json()
a=data['quotes']['USDCAD']
#display new label for button 3
button3["text"] = str(a)
#kick off the window's event loop
root.mainloop()
| 3.609375 | 4 |
smollm
|
707af793ad820c69cf7cec40b8cd9919026e2fef
|
Pacane99/Test-Public
|
/simpleGUI.py
| 1,097 |
null | null | null | null |
mensaje='hola'
print(mensaje)
class miClase:
def __init__(self,a,b):
self.a=a
self.b=b
def valor(self):
return self.a+self.b
#esto es un comentario
a=1
print (id(a))
a +=2
print(id(a))
| 3.546875 | 4 |
smollm
|
8639787d174d85b1bd6e788e89762d2e027bc525
|
rodrigosecko/python
|
/src/repaso.py
| 229 |
null | null | null | null |
s = set()
s.add(1)
s.add(3)
s.add(3)
s.add(5)
# Output is {1, 3, 5}
# If we add number which is in the set already it will be printed once
# The sets have unique values
print(s)
| 4.03125 | 4 |
smollm
|
a51b482d9987b524d8ac89986cecffc6126667aa
|
MarianKanev/lecture1
|
/sets.py
| 177 |
null | null | null | null |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 19 17:05:20 2020
@author: Mabel
referenced from Ken Jee - Github username: PlayingNumbers
url: https://github.com/PlayingNumbers/ds_salary_proj
"""
import pandas as pd
pd.set_option('display.max_columns', None) # display all columns in Pycharm
dataFrame = pd.read_csv('glassdoor_jobs.csv')
#To-Do List
# remove rows with -1 (missing values) for Salary Estimates - DONE
# parsing out salaries with lambda functions - DONE
# Removing numbers for Company Name, text only - DONE
# Age of Company - DONE
# add Province column for Location (Containing city names) - DONE
# parsing thru job description (python, etc.)
"""
Note to self: lambda - small anonymous function
lambda args : expression
Ex. x = lamda a, b, c : a + b + c
print(x(5, 6, 2))
13
"""
# parsing out salaries
dataFrame = dataFrame[dataFrame['Salary Estimate'] != '-1']
salary = dataFrame['Salary Estimate'].apply(lambda x: x.split('(')[0])
minus_kDInSalary = salary.apply(lambda x: x.replace('k','').replace('$','')
.replace('CA',''))
dataFrame['min_salary'] = minus_kDInSalary.apply(lambda x: int(x.split('-')[0]))
dataFrame['max_salary'] = minus_kDInSalary.apply(lambda x: int(x.split('-')[1]))
dataFrame['avg_salary'] = (dataFrame.min_salary+dataFrame.max_salary)/2
# parsing company names
dataFrame['company_name_text'] = dataFrame.apply(lambda x: x['Company Name']
if x['Rating'] < 0
else x['Company Name'][:-3],
axis = 1)
# Age of Company
dataFrame['company_age'] = dataFrame['Founded'].apply(lambda x: x if x < 0
else 2020 - x)
# add Province column for Locations
switchCase = {
'calgary': 'AB',
'edmonton': 'AB',
'burnaby': 'BC',
'vancouver': 'BC',
'brampton': 'ON',
'markham': 'ON',
'missisauga': 'ON',
'ottawa': 'ON',
'toronto': 'ON',
'waterloo': 'ON',
'regina': 'SK',
'montreal': 'QC',
'saint-laurent': 'QC',
}
def checkProvince(cityName):
return switchCase.get(cityName.lower(), "-1")
dataFrame['Province'] = dataFrame['Location'].apply(lambda x: checkProvince(x))
# parsing thru job descriptions based some top data science languages & tools
#python
dataFrame['python_yn'] = dataFrame['Job Description'].apply(lambda x:
1 if 'python' in x.lower() else 0)
dataFrame.python_yn.value_counts()
#r studio
dataFrame['rstudio_yn'] = dataFrame['Job Description'].apply(lambda x:
1 if 'r studio' in x.lower() else 0)
dataFrame.rstudio_yn.value_counts()
#spark
dataFrame['spark'] = dataFrame['Job Description'].apply(lambda x:
1 if 'spark' in x.lower() else 0)
dataFrame.spark.value_counts()
#excel
dataFrame['excel'] = dataFrame['Job Description'].apply(lambda x:
1 if 'spark' in x.lower() else 0)
dataFrame.excel.value_counts()
#aws
dataFrame['aws'] = dataFrame['Job Description'].apply(lambda x:
1 if 'aws' in x.lower() else 0)
dataFrame.aws.value_counts()
# dataFrame.columns
dataFrame.to_csv('glassdoor_salary_data_cleaned.csv', index=False)
print(pd.read_csv('glassdoor_salary_data_cleaned.csv'))
"""
Extra code for parsing out salaries
If data includes values 'per hour' and 'employer provided salary' in
Salary estimate column, create a separate column for each
dataFrame['hourly'] = dataFrame['Salary'].apply(lambda x: 1 if 'per hour' in
x.lower() else 0)
dataFrame['employer_provided'] = dataFrame['Salary Estimate'].apply(lambda x:
1 if 'employer provided salary:' in x.lower() else 0)
min_hr = minus_kDInSalary.apply(lambda x: x.lower().replace('per hour', '')
.replace('exployer provided salary',''))
dataFrame['min_salary'] = min_hr.apply(lambda x: int(x.split('-')[0]))
dataFrame['max_salary'] = min_hr.apply(lambda x: int(x.split('-')[1]))
dataFrame['avg_salary'] = (dataFrame.min_salary+dataFrame.max_salary)/2
If not in Spyder IDE, can check for type in console
Ex. dataFrame['min_salary'].dtype
"""
| 3.859375 | 4 |
smollm
|
aa5a8e84ab66aa0d4b8cc1e2eb4adfd72d9def57
|
mabelleky/data_science_salary_predictor
|
/data_cleaning.py
| 4,332 |
null | null | null | null |
import scipy
import networkx
import pandas
import pdb
class FabNetwork(object):
def __init__(self, distData):
self.distData = pandas.read_csv(distData)
self.fromNode = self.distData.From
self.toNode = self.distData.To
self.time = self.distData.Time
#We define the basic graph of the fab
self.fabgraph = networkx.DiGraph()
for i in range(len(self.fromNode)):
self.fabgraph.add_edge(self.fromNode[i],self.toNode[i],length=self.time[i])
'''
ALGORITHM 1 (Base Algorithm): Daifuku Dynamic Dijkstra's Algorithm (DDD)
We define a graph where time taken by a vehicle to travel on edge is:
f = k + t*n
where,
k = time to taken to travel on an empty edge
t = some constant additional time per additional vehicle on an edge
n = number of vehicles on the edge
We update this graph in a separate function below
'''
self.fabgraphDDD = networkx.DiGraph()
'''
ALGORITHM 2: Dynamic Dijkstra's Algorithm 1 (DD1)
We define a graph where time taken by a vehicle to travel on edge is:
f = k + t*n, n <= maxVehLimit
f = k + M*n, n > maxVehLimit
where,
k = time to taken to travel on an empty edge
t = some constant additional time per additional vehicle on an edge
n = number of vehicles on the edge
M = really large positive number chosen to set a high edge cost to repel
vehicles
maxVehLimit = Maximum number of vehicles wanted on a route
We update this graph in a separate function below
'''
self.fabgraphDD1 = networkx.DiGraph()
'''
ALGORITHM 3: Dynamic Dijkstra's Algorithm 2 (DD1)
We define a graph where time taken by a vehicle to travel on edge is:
f = k + t1*n, n <= maxVehLimit
f = k + t2*n, n > maxVehLimit
t1 < t2
where,
k = time to taken to travel on an empty edge
t1 = some constant additional time per additional vehicle on an edge
t2 = some constant additional time per additional vehicle on an edge,
t2 is chosen to set a high edge cost to repel vehicles from chosing
jammed or heavy-traffic routes
n = number of vehicles on the edge
maxVehLimit = Maximum number of vehicles wanted on a route
We update this graph in a separate function below
'''
self.fabgraphDD2 = networkx.DiGraph()
def shortestPath(self, startNode, destNode):
return networkx.shortest_path(self.fabgraph,startNode,destNode,weight='length')
def shortestPathTime(self, startNode, destNode):
return networkx.shortest_path_length(self.fabgraph,startNode,destNode,weight='length')
def edges(self, startNode, destNode):
return self.fabgraph.edges
def makeFabDDD(self, numVehs, t=0.0028):
#pdb.set_trace()
for i in range(len(self.fromNode)):
#pdb.set_trace()
self.fabgraphDDD.add_edge(self.fromNode[i],self.toNode[i],length=float(self.time[i])+(t*float(numVehs[(str(self.fromNode[i]),str(self.toNode[i]))])))
def shortestPathDDD(self, startNode, destNode):
#pdb.set_trace()
return networkx.shortest_path(self.fabgraphDDD,startNode,destNode,weight='length')
def shortestPathTimeDDD(self, startNode, destNode):
#pdb.set_trace()
return networkx.shortest_path_length(self.fabgraphDDD,startNode,destNode,weight='length')
def makeFabDD1(self, numVehs, maxVehLimit, t=0.0028, M=10000.000):
for i in range(len(self.fromNode)):
numVehOnEdge = numVehs[(str(self.fromNode[i]),str(self.toNode[i]))]
if numVehOnEdge<=maxVehLimit:
self.fabgraphDD1.add_edge(self.fromNode[i],self.toNode[i],length=float(self.time[i])+(t*numVehOnEdge))
else:
self.fabgraphDD1.add_edge(self.fromNode[i],self.toNode[i],length=float(self.time[i])+(M*numVehOnEdge))
def shortestPathDD1(self, startNode, destNode):
#pdb.set_trace()
return networkx.shortest_path(self.fabgraphDD1,startNode,destNode,weight='length')
def shortestPathTimeDD1(self, startNode, destNode):
#pdb.set_trace()
return networkx.shortest_path_length(self.fabgraphDD1,startNode,destNode,weight='length')
def makeFabDD2(self, numVehs, maxVehLimit, t1=0.0028, t2=0.05): #Add 15secs more than maxVehLimit on an edge
for i in range(len(self.fromNode)):
numVehOnEdge = numVehs[(str(self.fromNode[i]),str(self.toNode[i]))]
if numVehOnEdge<=maxVehLimit:
self.fabgraphDD2.add_edge(self.fromNode[i],self.toNode[i],length=self.time[i]+(t1*numVehOnEdge))
else:
#pdb.set_trace()
self.fabgraphDD2.add_edge(self.fromNode[i],self.toNode[i],length=self.time[i]-(t1*maxVehLimit)+(t2*numVehOnEdge))
#pdb.set_trace()
def shortestPathDD2(self, startNode, destNode):
#pdb.set_trace()
return networkx.shortest_path(self.fabgraphDD2,startNode,destNode,weight='length')
def shortestPathTimeDD2(self, startNode, destNode):
#pdb.set_trace()
return networkx.shortest_path_length(self.fabgraphDD2,startNode,destNode,weight='length')
if __name__ == '__main__' :
fabnetwork = FabNetwork('FabNodeData.csv')
print fabnetwork.shortestPath('STK1','STB2')
print fabnetwork.shortestPathTime('STK1','STB2')
print fabnetwork.edges
| 3.546875 | 4 |
smollm
|
ea148afad310703280de204dad97dfdf32dbf4f8
|
shreyagupta/PhD_Dissertation
|
/FabConstructorDDD4.py
| 6,041 |
null | null | null | null |
from tkinter import *
import sys
import logging
import pymysql
from school import Student
# global instance
# student = Student()
class Credentials(Frame):
"""Create a login frame that opens database upon
successful login or prints relevant message if credentials are
incorrect """
def __init__(self, root ,master):
""" Initiaize frame"""
super(Credentials, self).__init__(master)
self.root = root
self.conn = None
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create login widgets. """
Label(self, text="Username").grid(row=2, column=3, columnspan=1, sticky=W)
# username input
self.username = Entry(self)
self.username.grid(row=5, column=3, columnspan=4, sticky=W)
Label(self, text="Password").grid(row=6, column=3, columnspan=1, sticky=W)
self.password = Entry(self, show="*")
self.password.grid(row=7, column=3, columnspan=4, sticky=W)
# create cancel button
self.cancel_button = Button(self, text="Cancel", command=self.cancel)
self.cancel_button.grid(row=10, column=3)
# create a login button
self.login_button = Button(self, text="Login", command=self.login)
self.login_button.grid(row=10, column=5)
def login(self):
""" Open database GUI if credentials are correct"""
try:
if self.conn is None:
self.conn = pymysql.connect(host="localhost",
user=self.username.get(),
password=self.password.get(),
# database="stm",
database="cookbook",
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
self.main_root = Tk()
Student(self.main_root, self.conn)
self.root.destroy()
except pymysql.MySQLError as e:
# wrong password
self.incorrect_pass_label = Label(self, text="Wrong credentials")
self.incorrect_pass_label.grid(row=12,column=3, columnspan=2,rowspan=4, sticky=W)
# main()
finally:
if self.conn:
self.conn.close()
self.conn = None
def cancel(self):
"""Destroy windows all together. """
self.root.destroy()
sys.exit()
def main():
"""Interact with class """
root = Tk()
root.title("Login to School Database")
root.geometry("500x205")
app = Credentials(root,root)
root.mainloop()
return
if __name__ == '__main__':
main()
| 3.578125 | 4 |
smollm
|
295a7170d92439a92631a48539060d329f7262cd
|
Wangenye/school_database_system
|
/database_login.py
| 2,825 |
null | null | null | null |
#!/bin/usr/env python3
# -*- coding: utf-8 -*-
# -------------------------------
# Author: SuphxLin
# CreateTime: 2020/07/22 12:18
# FileName: 2048_tkinter.py
# Description:
# Question:
import random
import copy
# 棋盘初始化
board = [[0, 0, 0, 0] for i in range(4)]
# 分数初始化
score = 0
# 重置
def reset():
# 分数清0
global score
score = 0
'''重新设置游戏数据,将地图恢复为初始状态,并加入两个数据 2 作用初始状态'''
board[:] = [] # _map_data.clear()
board.append([0, 0, 0, 0])
board.append([0, 0, 0, 0])
board.append([0, 0, 0, 0])
board.append([0, 0, 0, 0])
# 在空白地图上填充两个2
fill2()
fill2()
# 随机生成2
def fill2():
i = random.randint(0, 3)
j = random.randint(0, 3)
# 当且仅当这个位置数字为0才能在该位置生成2
while board[i][j] != 0:
i = random.randint(0, 3)
j = random.randint(0, 3)
board[i][j] = 2
# 合并算法
def mergeRow(col):
global score
# col -> list
# 合并前,先删除这一行中所有的0
# 删完以后,其他数字之间不会有0间隔
while 0 in col:
col.remove(0)
# 对于剩下的数字,从左向右遍历col
# 在遍历中判断相邻两位是否相等
# 若第i位与第i+1位相等
# 即可对col[i]自更新原来的两倍
# 删除第i+1位
i = 0
while i < len(col)-1:
if col[i] == col[i+1]:
col[i] *= 2
score += col[i]
col.pop(i+1)
i += 1
# 用0补足4位
col = col + [0] * (4 - len(col))
return col
# 判断输
def isGameOver():
# list.count(value) 统计value出现的次数
# 仍有空格
defeat = sum([row.count(0) for row in board])
if defeat:
return False
# 横向仍可合并
for row in board:
for i in range(3):
if row[i] == row[i+1]:
return False
# 纵向仍可合并
for c in range(4):
for r in range(3):
if board[r][c] == board[r+1][c]:
return False
# 以上条件都不满足,则游戏结束
return True
# 移动算法
def left():
"""游戏左键按下时或向左滑动屏幕时的算法"""
temp = copy.deepcopy(board) # 深拷贝,与board本身独立
for i in range(len(board)):
board[i] = mergeRow(board[i])
if temp != board:
return True
return False
def right():
temp = copy.deepcopy(board)
for i in range(len(board)):
row = board[i][::-1]
row = mergeRow(row)
board[i] = row[::-1]
if temp != board:
return True
return False
def up():
temp = copy.deepcopy(board)
for i in range(len(board)):
col = [board[0][i], board[1][i], board[2][i], board[3][i]]
col = mergeRow(col)
board[0][i], board[1][i], board[2][i], board[3][i] = \
col[0], col[1], col[2], col[3]
if temp != board:
return True
return False
def down():
temp = copy.deepcopy(board)
for i in range(len(board)):
col = [board[0][i], board[1][i], board[2][i], board[3][i]][::-1]
col = mergeRow(col)[::-1]
board[0][i], board[1][i], board[2][i], board[3][i] = \
col[0], col[1], col[2], col[3]
if temp != board:
return True
return False
from tkinter import *
from tkinter import messagebox
def main():
reset() # 先重新设置游戏数据
root = Tk() # 创建tkinter窗口
root.title('2048游戏') # 设置标题文字
root.resizable(width=False, height=False) # 固定宽和高
# 以下是键盘映射
keymap = {
'a': left,
'd': right,
'w': up,
's': down,
'Left': left,
'Right': right,
'Up': up,
'Down': down,
'q': root.quit,
}
game_bg_color = "#bbada0" # 设置背景颜色
# 设置游戏中每个数据对应色块的颜色
mapcolor = {
0: ("#cdc1b4", "#776e65"),
2: ("#eee4da", "#776e65"),
4: ("#ede0c8", "#f9f6f2"),
8: ("#f2b179", "#f9f6f2"),
16: ("#f59563", "#f9f6f2"),
32: ("#f67c5f", "#f9f6f2"),
64: ("#f65e3b", "#f9f6f2"),
128: ("#edcf72", "#f9f6f2"),
256: ("#edcc61", "#f9f6f2"),
512: ("#e4c02a", "#f9f6f2"),
1024: ("#e2ba13", "#f9f6f2"),
2048: ("#ecc400", "#f9f6f2"),
4096: ("#ae84a8", "#f9f6f2"),
8192: ("#b06ca8", "#f9f6f2"),
# ----其它颜色都与8192相同---------
2 ** 14: ("#b06ca8", "#f9f6f2"),
2 ** 15: ("#b06ca8", "#f9f6f2"),
2 ** 16: ("#b06ca8", "#f9f6f2"),
2 ** 17: ("#b06ca8", "#f9f6f2"),
2 ** 18: ("#b06ca8", "#f9f6f2"),
2 ** 19: ("#b06ca8", "#f9f6f2"),
2 ** 20: ("#b06ca8", "#f9f6f2"),
}
def on_key_down(event):
'键盘按下处理函数'
keysym = event.keysym
if keysym in keymap:
if keymap[keysym](): # 如果有数字移动
fill2() # 填充一个新的2
update_ui()
if isGameOver():
mb = messagebox.askyesno(
title="gameover", message="游戏结束!\n是否退出游戏!")
if mb:
root.quit()
else:
reset()
update_ui()
def update_ui():
'''刷新界面函数
根据计算出的f地图数据,更新各个Label的设置
'''
for r in range(4):
for c in range(len(board[0])):
number = board[r][c] # 设置数字
label = map_labels[r][c] # 选中Lable控件
label['text'] = str(number) if number else ''
label['bg'] = mapcolor[number][0]
label['foreground'] = mapcolor[number][1]
label_score['text'] = str(score) # 重设置分数
# 创建一个frame窗口,此创建将容纳全部的widget部件
frame = Frame(root, bg=game_bg_color)
frame.grid(sticky=N + E + W + S)
# 设置焦点能接收按键事件
frame.focus_set()
frame.bind("<Key>", on_key_down)
# 初始化图形界面
map_labels = []
for r in range(4):
row = []
for c in range(len(board[0])):
value = board[r][c]
text = str(value) if value else ''
label = Label(frame, text=text, width=4, height=2,
font=("黑体", 30, "bold"))
label.grid(row=r, column=c, padx=5, pady=5, sticky=N + E + W + S)
row.append(label)
map_labels.append(row)
# 设置显示分数的Lable
label = Label(frame, text='分数', font=("黑体", 30, "bold"),
bg="#bbada0", fg="#eee4da")
label.grid(row=4, column=0, padx=5, pady=5)
label_score = Label(frame, text='0', font=("黑体", 30, "bold"),
bg="#bbada0", fg="#ffffff")
label_score.grid(row=4, columnspan=2, column=1, padx=5, pady=5)
# 以下设置重新开始按钮
def reset_game():
reset()
update_ui()
restart_button = Button(frame, text='重新开始', font=("黑体", 12, "bold"),
bg="#8f7a66", fg="#f9f6f2", command=reset_game)
restart_button.grid(row=4, column=3, padx=5, pady=5)
update_ui() # 更新界面
root.mainloop() # 进入tkinter主事件循环
main() # 启动游戏
| 3.53125 | 4 |
smollm
|
102b243eee4133b1f75d06796c48c3093653745c
|
Suphx/python_project_repository
|
/01.BoardGame/05.2048/2048_tkinter.py
| 7,439 |
null | null | null | null |
#!/bin/usr/env python3
# -*- coding: utf-8 -*-
# -------------------------------
# Author: SuphxLin
# CreateTime: 2020/8/4 15:08
# FileName: 03.HotDog
# Description:
# Question:
class HotDog:
def __init__(self):
self.cooked_level = 0
self.cooked_string = "生的"
self.condiments = []
def __str__(self):
msg = "热狗"
if len(self.condiments) == 0:
return self.cooked_string + "原味" + msg
if len(self.condiments) > 0:
msg += "浇上了"
for i in self.condiments:
msg += i + ","
msg = msg.strip(",")
msg = self.cooked_string + msg
return msg
def cook(self, time):
self.cooked_level += time
if self.cooked_level > 8:
self.cooked_string = "焦的"
elif self.cooked_level > 5:
self.cooked_string = "熟的"
elif self.cooked_level > 3:
self.cooked_string = "半生不熟的"
else:
self.cooked_string = "生的"
def addcondiment(self, condiment):
self.condiments.append(condiment)
myHotDog = HotDog()
print(myHotDog)
myHotDog.cook(4)
print(myHotDog)
myHotDog.cook(2)
print(myHotDog)
myHotDog.addcondiment("番茄酱")
myHotDog.addcondiment("芥末酱")
print(myHotDog)
| 3.875 | 4 |
smollm
|
4c531727d6f28d4233e01638979a773da207fd4b
|
Suphx/python_project_repository
|
/06.Python Basic/01.Object Oriented/03.HotDog.py
| 1,304 |
null | null | null | null |
#!/bin/usr/env python3
# -*- coding: utf-8 -*-
# -------------------------------
# Author: SuphxLin
# CreateTime: 2020/07/22 12:11
# FileName: 2048_terminal.py
# Description:
# Question:
#
# 2048
# 1. 初始化一个4*4的棋盘
# 声明board、show为全局变量
global board, show
board = [[0, 0, 0, 0] for i in range(4)]
show = [[0, 0, 0, 0] for i in range(4)]
# 2. 输出2048界面的函数
def display():
# 我新增的
for i in range(4):
for j in range(4):
if board[i][j] == 0:
show[i][j] = " "
else:
show[i][j] = board[i][j]
print("+----+----+----+----+")
for row in range(len(board)):
# 格式化输出(%d -> 十进制数)
print("| %2s | %2s | %2s | %2s |" % (show[row][0], show[row][1], show[row][2], show[row][3]))
print("+----+----+----+----+")
# 3.生成2
# 随机生成两个下标,范围是0-3
import random
def fill2():
i = random.randint(0, 3)
j = random.randint(0, 3)
# 2应当生成在空白的位置(0)
while board[i][j] != 0:
i = random.randint(0, 3)
j = random.randint(0, 3)
board[i][j] = 2
# 4.开局,随机生成两个2,显示棋盘
fill2()
fill2()
display()
# 5.合并函数(上下左右移动)
def mergeRow(col):
# col -> list
# 合并前,先删除这一个一维列表中的所有的0
# 删完以后,其他数字之间不会有0间隔
while 0 in col:
col.remove(0)
# 对于剩下的数字,从左向右遍历col
# 判断相邻的2个数字是否相同
# 相同就合并
# 合并后删除第i+1位
i = 0
while i < len(col) - 1:
if col[i] == col[i + 1]:
col[i] *= 2
col.pop(i + 1)
i += 1
# [4,2] + [0] * (4-len(col))
col = col + [0] * (4 - len(col))
return col
# 6.进入游戏循环
while True:
move = input("请输入你想移动的方向(adws):")
if move == "a":
for i in range(4):
board[i] = mergeRow(board[i])
fill2()
display()
# 向右合并
elif move == "d":
for i in range(4):
row = board[i][::-1]
row = mergeRow(row)
board[i] = row[::-1]
fill2()
display()
# 向上合并
elif move == "w":
for j in range(4):
col = [board[0][j], board[1][j], board[2][j], board[3][j]]
col = mergeRow(col)
board[0][j], board[1][j], board[2][j], board[3][j] = col[0], col[1], col[2], col[3]
fill2()
display()
elif move == "s":
for j in range(4):
col = [board[3][j], board[2][j], board[1][j], board[0][j]]
col = mergeRow(col)
board[3][j], board[2][j], board[1][j], board[0][j] = col[0], col[1], col[2], col[3]
fill2()
display()
| 3.8125 | 4 |
smollm
|
3243d0505dd1e9e465409d2e7342a9076e3bfb1d
|
Suphx/python_project_repository
|
/01.BoardGame/05.2048/2048_terminal.py
| 2,871 |
null | null | null | null |
import matplotlib.pyplot as plt
from get_train_info import get_class_per_image
def plot_class_per_image_hist(df_train):
"""
Function that plots histograms of label patterns & number of labels
per images (for the Kaggle cloud classification competition project).
Parameters
----------
df_train: DataFrame
Data Frame with the run length encoded segmentations for each image-label
pair in the train_images (provided by Kaggle)
Returns
-------
Plots:
Two histograms: 1) histogram of label patterns per image_id
2) histogram of number of labels per image_id
"""
# Get the Data Frame with the cloud labels identified per image_id (in the
# training images)
df_class_per_image = get_class_per_image(df_train.dropna().Image_Label)
# Get label patterns per image_id
class_pattern = df_class_per_image.cloud_label.value_counts()
fig, ax = plt.subplots(ncols=2, figsize=(9.2, 7))
# Plot the histogram of label patterns per image_id
class_pattern.plot.barh(ax=ax[0])
ax[0].set_title('Number of each label patterns per images')
ax[0].set_ylabel('Label patterns')
ax[0].set_xlabel('Number of images')
ax[0].grid()
# Get number of labels per image_id
num_class_per_image = df_class_per_image.cloud_label.apply(lambda x: \
x.count(',')+1).value_counts()
num_class_per_image = num_class_per_image.sort_index()
# Plot the histogram of number of labels per image_id
num_class_per_image.plot.barh(ax=ax[1])
ax[1].set_title('Number of labels per images')
ax[1].set_ylabel('Number of cloud labels')
ax[1].set_xlabel('Number of images')
ax[1].grid()
plt.show()
| 3.515625 | 4 |
smollm
|
a5477271fa7c96c61175cd6e792b7de87fcf6f07
|
Team-Cloudbusters/cloudbusting
|
/lib/cloudbusting/EDA/plot_EDA.py
| 1,760 |
null | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
a = 10 / 3
b = 10 // 3
c = 10 % 3
d = 10 / 3.0
e = 10 // 3.0
f = 10.5 % 3.0
print(a, b, c)
print(d, e, f)
print("-----------------------")
str1 = r"this is \a \string! \n and you is son of beach!"
str2 = "this is \a \string! \n and you is son of beach! hahaha\n"
print(str2, str1)
print("-----------------------")
aa = '444444444444'
bb = aa
aa = '5555555555555'
print(aa, bb)
| 4.125 | 4 |
smollm
|
fbb42c4f19f45eee93eace4e19d84a733f782d14
|
redhead520/LearningCode
|
/python/demo/01.dataStructure-demo/01.dataStructure-demo.py
| 430 |
null | null | null | null |
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 700))#创建游戏主窗口
bg = pygame.image.load("./images/background.png")#绘制背景图 加载图像
screen.blit(bg, (0, 0))#绘制在屏幕
#pygame.display.update()#更新显示
hero=pygame.image.load('./images/hero.gif')#加载图像
screen.blit(hero,(200,500))#绘制屏幕的什么位置
pygame.display.update()#更新显示
clock=pygame.time.Clock()#创建游戏时钟对象
#i=0#创建游戏时钟对象
hero_rect=pygame.Rect(200,500,102,126)#定义英雄的初始位置
enemy = EnemySprite()
enemy = EnemySprite()
enemy1.rect.x = 50
enemy1.rect.y = 700
enemy1.speed = -2
enemy_group = pygame.sprite.Group(enemy,enemy)
while True:#游戏循环
clock.tick(60)#一秒刷新60次
hero_rect.y-=5#相当速度
screen.blit(bg,(0,0))
screen.blit(hero, hero_rect)
if hero_rect.bottom<=0: #如果移除屏幕
hero_rect.top=700 #则英雄的顶部移动到屏幕底部
enemy_group.update()
enmey_group.draw(scteen)
'''
for event in pygame.event.get():
# 判断用户是否点击了关闭按钮
if event.type == pygame.QUIT:
print("退出游戏...")
pygame.quit()
# 直接退出系统
exit()
'''
# pygame.display.update()
#while True:#游戏循环
# pass
pygame.quit()#更新显示
| 3.53125 | 4 |
smollm
|
de3fab9c065c1088c3b46443559eaee139da677b
|
ZiHaoYa/1807-2
|
/08day/02-飞机大战.py
| 1,280 |
null | null | null | null |
import math
inFile = open("input.txt", "r")
outFile = open("output.txt", "w")
def getSpace(desired, length):
space = ""
for i in range(0, (desired - length)):
space += " "
return space
charCount = 0
dictionary = {}
discluded = ["\n", " "]
print("Reading Input File.")
for line in inFile:
for char in line:
if char in discluded:
continue
elif char.lower() in dictionary:
dictionary[char.lower()] += 1
else:
dictionary[char.lower()] = 1
charCount += 1
print("Recording Data")
outFile.write("---------- CHARACTER FREQUENCIES ----------- \n" + str(len(dictionary))+ " UNIQUE CHARACTERS | " + str(charCount) + " TOTAL CHARACTERS\n")
outFile.write("--------------------------------------------\n")
for char, num in sorted(dictionary.items(), key=lambda tup: tup[1])[::-1]:
charNum = str(num)
charFreq = str(round((num / charCount * 100), 2))
outFile.write(" " + char + " | " + charNum + getSpace(6, len(charNum)) + " | " + getSpace(8, len(charFreq)) + charFreq + "%" + "\n")
outFile.write("--------------------------------------------\n")
outFile.write("DISCLUDED CHARACTERS: space, newline")
outFile.close()
print("Process Complete.")
| 3.546875 | 4 |
smollm
|
25ce22bcd4b248e6baf3b655d2f120d6eec7bc34
|
andyruwruw-old/coding-challenge-for-kids
|
/Labs_Python/3._Advanced_Python/2._Input_and_Output_Files/Character_Frequencies/solution.py
| 1,248 |
null | null | null | null |
class WaterBottle:
def __init__(self, color, capacity, volume):
self.color = color
self.capacity = capacity
self.volume = volume
def drink(self, amount):
self.volume -= amount
if self.volume < 0:
self.volume = 0
def refill(self, amount):
self.volume += amount
if self.volume > self.capacity:
self.volume = self.capacity
# Further Challenges
def __add__(self, other):
self.capacity += other.capacity
self.volume += other.volume
return self
def __repr__(self):
return "A " + self.color + " Waterbottle | Capacity: " + str(self.capacity) + "mL | Volume: " + str(self.volume) + "mL"
| 3.796875 | 4 |
smollm
|
8c6fc5017958a2c8c0c08de409aacb53284d382e
|
andyruwruw-old/coding-challenge-for-kids
|
/Labs_Python/2._Intermediate_Python/2._Objects_and_Classes/Water_Bottle_Object/solution.py
| 727 |
null | null | null | null |
sentence = "" # Place the sentence here.
lastWord = ""
result = ""
for word in sentence.split():
if word != lastWord:
result += word + " "
lastWord = word
print(result)
| 4.03125 | 4 |
smollm
|
342cb7cdcc69c48b5d54fc6edd6c98aad0948bb9
|
andyruwruw-old/coding-challenge-for-kids
|
/Labs_Python/2._Intermediate_Python/1._Strings/Repeating_Words/solution.py
| 192 |
null | null | null | null |
import numpy
import csv
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def view_pc(pcs, fig=None, color='b', marker='o'):
"""Visualize a pc.
inputs:
pc - a list of numpy 3 x 1 matrices that represent the points.
color - specifies the color of each point cloud.
if a single value all point clouds will have that color.
if an array of the same length as pcs each pc will be the color corresponding to the
element of color.
marker - specifies the marker of each point cloud.
if a single value all point clouds will have that marker.
if an array of the same length as pcs each pc will be the marker corresponding to the
element of marker.
outputs:
fig - the pyplot figure that the point clouds are plotted on
"""
# Construct the color and marker arrays
if hasattr(color, '__iter__'):
if len(color) != len(pcs):
raise Exception('color is not the same length as pcs')
else:
color = [color] * len(pcs)
if hasattr(marker, '__iter__'):
if len(marker) != len(pcs):
raise Exception('marker is not the same length as pcs')
else:
marker = [marker] * len(pcs)
# Start plt in interactive mode
ax = []
if fig == None:
plt.ion()
# Make a 3D figure
fig = plt.figure()
# Draw each point cloud
for pc, c, m in zip(pcs, color, marker):
x = []
y = []
for pt in pc:
x.append(pt[0, 0])
y.append(pt[1, 0])
plt.scatter(x, y, color=c, marker=m)
# Set the labels
plt.xlabel('X')
plt.ylabel('Y')
# Update the figure
plt.show()
# Return a handle to the figure so the user can make adjustments
return fig
def add_noise(pc, variance,distribution='gaussian'):
"""Add Gaussian noise to pc.
For each dimension randomly sample from a Gaussian (N(0, Variance)) and add the result
to the dimension dimension.
inputs:
pc - a list of numpy 3 x 1 matrices that represent the points.
variance - the variance of a 0 mean Gaussian to add to each point or width of the uniform distribution
distribution - the distribution to use (gaussian or uniform)
outputs:
pc_out - pc with added noise.
"""
pc_out = []
if distribution=='gaussian':
for pt in pc:
pc_out.append(pt + numpy.random.normal(0, variance, (2, 1)))
elif distribution=='uniform':
for pt in pc:
pc_out.append(pt + numpy.random.uniform(-variance, variance, (2, 1)))
else:
raise ValueError(['Unknown distribution type: ', distribution])
return pc_out
def merge_clouds(pc1, pc2):
"""Add Gaussian noise to pc.
Merge two point clouds
inputs:
pc1 - a list of numpy 2 x 1 matrices that represent one set of points.
pc2 - a list of numpy 2 x 1 matrices that represent another set of points.
outputs:
pc_out - merged point cloud
"""
pc_out = pc1
for pt in pc2:
pc_out.append(pt)
return pc_out
def add_outliers(pc, multiple_of_data, variance, distribution='gaussian'):
"""Add outliers to pc.
inputs:
pc - a list of numpy 2 x 1 matrices that represent the points.
multiple_of_data - how many outliers to add in terms of multiple of data. Must be an integer >= 1.
variance - the variance of a 0 mean Gaussian to add to each point.
distribution - the distribution to use (gaussian or uniform)
outputs:
pc_out - pc with added outliers.
"""
pc_out = pc
for i in range(0,multiple_of_data):
pc_outliers = add_noise(pc_out, variance,distribution)
pc_out = merge_clouds(pc_out,pc_outliers)
return pc_out
def add_outliers_centroid(pc, num_outliers, variance, distribution='gaussian'):
"""Add outliers to pc (reference to centroid).
inputs:
pc - a list of numpy 3 x 1 matrices that represent the points.
num_outliers - how many outliers to add
variance - the variance of a 0 mean Gaussian to add to each point.
distribution - the distribution to use (gaussian or uniform)
outputs:
pc_out - pc with added outliers.
"""
centroid = numpy.zeros((2, 1))
for pt in pc:
centroid = centroid + pt
centroid = centroid/len(pc)
newpoints = []
for i in range(0,num_outliers):
newpoints.append(numpy.matrix(centroid))
return merge_clouds(pc, add_noise(newpoints,variance,distribution))
def convert_pc_to_matrix(pc):
"""Coverts a point cloud to a numpy matrix.
Inputs:
pc - a list of 2 by 1 numpy matrices.
outputs:
numpy_pc - a 2 by n numpy matrix where each column is a point.
"""
numpy_pc = numpy.matrix(numpy.zeros((2, len(pc))))
for index, pt in enumerate(pc):
numpy_pc[0:2, index] = pt
return numpy_pc
def convert_matrix_to_pc(numpy_pc):
"""Coverts a numpy matrix to a point cloud (useful for plotting).
Inputs:
numpy_pc - a 2 by n numpy matrix where each column is a point.
outputs:
pc - a list of 2 by 1 numpy matrices.
"""
pc = []
for i in range(0,numpy_pc.shape[1]):
pc.append((numpy_pc[0:2,i]))
return pc
| 3.546875 | 4 |
smollm
|
1db7f92153daf022ee54243189c922f697144b49
|
cxchance/Algorithmic-Robotics
|
/utils2d.py
| 5,361 |
null | null | null | null |
import numpy
def circle(radius, size, circle_centre=(0, 0), origin="middle"):
"""
Create a 2-D array: elements equal 1 within a circle and 0 outside.
The default centre of the coordinate system is in the middle of the array:
circle_centre=(0,0), origin="middle"
This means:
if size is odd : the centre is in the middle of the central pixel
if size is even : centre is in the corner where the central 4 pixels meet
origin = "corner" is used e.g. by psfAnalysis:radialAvg()
Examples:
circle(1,5) circle(0,5) circle(2,5) circle(0,4) circle(0.8,4) circle(2,4)
00000 00000 00100 0000 0000 0110
00100 00000 01110 0000 0110 1111
01110 00100 11111 0000 0110 1111
00100 00000 01110 0000 0000 0110
00000 00000 00100
circle(1,5,(0.5,0.5)) circle(1,4,(0.5,0.5))
.-->+
| 00000 0000
| 00000 0010
+V 00110 0111
00110 0010
00000
Args:
radius (float) : radius of the circle
size (int) : size of the 2-D array in which the circle lies
circle_centre (tuple): coords of the centre of the circle
origin (str) : where is the origin of the coordinate system
in which circle_centre is given;
allowed values: {"middle", "corner"}
Returns:
ndarray (float64) : the circle array
Raises:
TypeError if input is of wrong type
Exception if a bug in generation of coordinates is detected (see code)
"""
# (2) Generate the output array:
C = numpy.zeros((size, size))
# (3.a) Generate the 1-D coordinates of the pixel's centres:
# coords = numpy.linspace(-size/2.,size/2.,size) # Wrong!!:
# size = 5: coords = array([-2.5 , -1.25, 0. , 1.25, 2.5 ])
# size = 6: coords = array([-3. , -1.8, -0.6, 0.6, 1.8, 3. ])
# (2015 Mar 30; delete this comment after Dec 2015 at the latest.)
# Before 2015 Apr 7 (delete 2015 Dec at the latest):
# coords = numpy.arange(-size/2.+0.5, size/2.-0.4, 1.0)
# size = 5: coords = array([-2., -1., 0., 1., 2.])
# size = 6: coords = array([-2.5, -1.5, -0.5, 0.5, 1.5, 2.5])
coords = numpy.arange(0.5, size, 1.0)
# size = 5: coords = [ 0.5 1.5 2.5 3.5 4.5]
# size = 6: coords = [ 0.5 1.5 2.5 3.5 4.5 5.5]
# (3.b) Just an internal sanity check:
if len(coords) != size:
raise exceptions.Bug("len(coords) = {0}, ".format(len(coords)) +
"size = {0}. They must be equal.".format(size) +
"\n Debug the line \"coords = ...\".")
# (3.c) Generate the 2-D coordinates of the pixel's centres:
x, y = numpy.meshgrid(coords, coords)
# (3.d) Move the circle origin to the middle of the grid, if required:
if origin == "middle":
x -= size / 2.
y -= size / 2.
# (3.e) Move the circle centre to the alternative position, if provided:
x -= circle_centre[0]
y -= circle_centre[1]
# (4) Calculate the output:
# if distance(pixel's centre, circle_centre) <= radius:
# output = 1
# else:
# output = 0
mask = x * x + y * y <= radius * radius
C[mask] = 1
# (5) Return:
return C
| 4.53125 | 5 |
smollm
|
08964e794e1436aa0e6c2faeb95100652bf0a8aa
|
agb32/aotools
|
/aotools/functions/pupil.py
| 3,494 |
null | null | null | null |
#print exercise and f exercise
my_name = 'super xiang'
my_age = 35 # really
my_height = 172 # cm
my_weight = 70 #kg
print(f"The boy's name is {my_name}, ")
print(f"he is {my_age} years old, {my_height} cm height, and {my_weight} kgs weight.")
print (f"My name is {my_name}")
print (f"I am {my_age} years old, {my_height} cm height, and {my_height} kgs weight.")
| 4 | 4 |
smollm
|
6bbb311e2d911a7ce8869adaf8b2af204e3895ca
|
superxiangsx/python-ex
|
/ex5.py
| 362 |
null | null | null | null |
import sys
import random
import myfuncs
class FlashCard:
def __init__(self, question, answer):
self.question = question
self.answer = answer
def getQuestion(self):
return self.question
def getAnswer(self):
return self.answer
class FlashCardSet:
def __init__(self, fileName=None):
self.flashCards = []
if fileName is not None:
lines = open(fileName).readlines()
for line in lines:
question, answer = line.strip().split(',')
newFlashCard = FlashCard(question, answer)
self.addFlashCard(newFlashCard)
def addFlashCard(self, card):
self.flashCards.append(card)
def removeFlashCard(self, card):
self.flashCards.remove(card)
def getRandomFlashCard(self):
return random.choice(self.flashCards)
def cardsRemaining(self):
if self.flashCards:
return True
return False
class Game:
def __init__(self):
self.questionsAsked = 0
self.correctlyAnswered = 0
print("New game started")
def runGame(self, flashCardSet):
# keep asking questions till 'exit' is entered by user
# or until no flash cards remain
while flashCardSet.cardsRemaining():
# get random question
randomFlashCard = flashCardSet.getRandomFlashCard()
question = randomFlashCard.getQuestion()
answer = randomFlashCard.getAnswer()
# get user's guess for current question
guess = myfuncs.getUserGuess(question)
if (guess == 'exit'):
break
self.questionsAsked += 1
if (myfuncs.isSame(guess, answer)):
self.correctlyAnswered += 1
flashCardSet.removeFlashCard(randomFlashCard)
print("Correct! Nice job.")
else:
print("Incorrect! The correct answer is " + answer)
def getNumQuestionsAsked(self):
return self.questionsAsked
def getNumCorrectlyAnswered(self):
return self.correctlyAnswered
def printStats(self):
print("Total attempts : ", self.questionsAsked)
print("Correctly answered : ", self.correctlyAnswered)
if __name__ == "__main__":
if (len(sys.argv) < 2):
print("No input file provided")
flashCardSet = FlashCardSet()
else:
fileName = sys.argv[1]
# if file does not exist in current directory, exit
if not myfuncs.fileExists(fileName):
print("Input file does not exist in current directory")
exit()
flashCardSet = FlashCardSet(fileName)
newGame = Game()
newGame.runGame(flashCardSet)
newGame.printStats()
| 3.5625 | 4 |
smollm
|
9728f668f6e4dfbbf60768dea262bc851c56b64c
|
DrNightmare/flashcards
|
/flashcards.py
| 2,772 |
null | null | null | null |
import time
choose=input("Plese enter 'E' if you want to Encrypt and 'D' if you want to Decrypt:")
#We will ask User to Enter E for Encryption and D for Decryption into variable Choose
if choose=='E':
key=input("Please Enter the secret Key:")
key=key.upper()
keylist=[]
ciphertext=[]
keymatrix=[]
value1=0
value2=0
value3=0
value4=0
alpha="ABCDEFGHIKLMNOPQRSTUVWXYZ"
#We will make alist Key List,that will take the input we provide at Key and enter unique characters once followed by the remaining characters in alphabet except J
message=input("Please Enter your Plaintext")
for i in range(len(key)):
if key[i]=='\s':
i+=1
if key[i] not in keylist:
keylist.append(key[i])
for i in range(len(alpha)):
if alpha[i] not in keylist:
keylist.append(alpha[i])
print(keylist)
#We will Use Keymatrix to display keylist as 5*5 Matrix
keymatrix.insert(0,keylist[0:5])
keymatrix.insert(1,keylist[5:10])
keymatrix.insert(2,keylist[10:15])
keymatrix.insert(3,keylist[15:20])
keymatrix.insert(4,keylist[20:25])
#We will Enter the Plain Text Message into message
print("The Plain Text is:",message)
message=message.upper()
count=0
#We remove spaces and make Key and Message Upper Case
messagelist=list(message)
for i in range(len(messagelist)):
if message[i]=='\s':
del messagelist[i]
x=len(messagelist)
print(x)
i=0
#We use count variable to denote odd or even number of blocks 0=even, 1=odd
while i<x:
count=count+1
if count%2==0:
count=0
#If last character makes Message into odd number of characters add Z to make the message even.
if i==(x-1) and count%2==1:
if messagelist[i]=='Z':
messagelist.insert(i+1,'Q')
else:
messagelist.insert(i+1,'Z')
x=x+1
#If the ith and i+1th Character is same, insert X after ith character
if count%2==1 and (messagelist[i]==messagelist[i+1]):
messagelist.insert(i+1,'X')
x+=1
#If the ith and i+1th Character is X, insert Y after ith character
if count%2==1 and (messagelist[i]==messagelist[i+1] and messagelist[i]=='X'):
messagelist.insert(i+1,'Y')
x+=1
#Replace J with I
if messagelist[i]=='J':
messagelist[i]=='I'
i+=1
message=''.join(messagelist)
print("The Plain Text is:",message)
#Traverse through the message, if message is found in key, take the values of ith and i+1th Character into values value 1, value2,and value 3,value4 Respectively
for i in range(0,len(message),2):
for j in range(5):
for k in range(5):
if message[i]==keymatrix[j][k]:
value1=j
value2=k
if message[i+1]==keymatrix[j][k]:
value3=j
value4=k
#if both characters fall in same Row in Key Matrix, if value is not the last column, take value2+1th and value4+1th Column into ciphertext
if value1==value3:
if value2==4 and value4!=4:
value2=0
value4+=1
elif value4==4 and value2!=4:
value4=0
value2+=1
else:
value2+=1
value4+=1
#if both characters fall in same Column in Key Matrix, if value is not the last Row, take value1+1th and value3+1th Row into ciphertext
if value2==value4:
if value1==4 and value3!=4:
value1=0
value3+=1
elif value3==4 and value1!=4:
value3=0
value1+=1
else:
value1+=1
value3+=1
#if both characters are in different rows and columns of the key matrix, form a rectange, and take the other ends of the rectangle into ciphertext
if value1!=value3 and value2!=value4:
temp=value2
value2=value4
value4=temp
ciphertext.append(keymatrix[value1][value2])
ciphertext.append(keymatrix[value3][value4])
#Display Cipher Text
ciphertext=''.join(ciphertext)
print("The Cipher Text is:",ciphertext)
elif choose=='D':
#If Choose=D,
#We will make alist Key List,that will take the input we provide at Key and enter unique characters once followed by the remaining characters in alphabet except J
#We will Use Keymatrix to display keylist as 5*5 Matrix
#We will Enter the Cipher Text Message into ciphertext
#We remove spaces and make Key and ciphertext Upper Case
key=input("Please Enter the secret Key:")
key=key.upper()
keylist=[]
message=[]
keymatrix=[]
value1=0
value2=0
value3=0
value4=0
alpha="ABCDEFGHIKLMNOPQRSTUVWXYZ"
for i in range(len(key)):
if key[i] not in keylist:
keylist.append(key[i])
for i in range(len(alpha)):
if alpha[i] not in keylist:
keylist.append(alpha[i])
keymatrix.insert(0,keylist[0:5])
keymatrix.insert(1,keylist[5:10])
keymatrix.insert(2,keylist[10:15])
keymatrix.insert(3,keylist[15:20])
keymatrix.insert(4,keylist[20:25])
print(keymatrix)
ciphertext=input("Please Enter your ciphertext:")
ciphertext=ciphertext.upper()
#We will search ciphertext's ith and i+1th value with key matrix, and if found store the 1st value positions into value 1 and value 2 and 2nd value's positions into value3 and value4
for i in range(0,len(ciphertext),2):
for j in range(5):
for k in range(5):
if ciphertext[i]==keymatrix[j][k]:
value1=j
value2=k
if ciphertext[i+1]==keymatrix[j][k]:
value3=j
value4=k
#if both characters fall in same Row in Key Matrix, if value is not the last column, take value2-1th and value4-1th Column into message
if value1==value3:
if value2==0 and value4!=0:
value2=4
value4-=1
elif value4==0 and value2!=0:
value4=4
value2-=1
else:
value2-=1
value4-=1
#if both characters fall in same Column in Key Matrix, if value is not the last Row, take value111th and value311th Row into message
if value2==value4:
if value1==0 and value3!=0:
value1=4
value3-=1
elif value3==0 and value1!=0:
value3=4
value1-=1
else:
value1-=1
value3-=1
#if both characters are in different rows and columns of the key matrix, form a rectange, and take the other ends of the rectangle into message
if value1!=value3 and value2!=value4:
temp=value4
value4=value2
value2=temp
message.append(keymatrix[value1][value2])
message.append(keymatrix[value3][value4])
message=''.join(message)
messagelist=list(message)
x=len(messagelist)
print(x)
count=0
for i in range(x):
count=count+1
#If last character is Q and the 2nd last character is Z remove Q, if last character is Z and 2nd last character is something else, remove Z
if messagelist[-1]=='Q' and messagelist[-2]=='Z' and count%2==0:
messagelist.pop()
x=x-1
if messagelist[-1]=='Z' and messagelist[-2]!='Z' and count%2==0:
messagelist.pop()
x=x-1
if count%2==0:
count=0
#If ith value and i+2th value is same and X lies in i+1th value remove X
if(i+2<x-2 and messagelist[i]==messagelist[i+2] and messagelist[i+1]=='X'):
del messagelist[i+1]
message=''.join(messagelist)
#print message
print("The Plain Text is:",message)
time.sleep(100)
| 4.09375 | 4 |
smollm
|
dfc3588a2e1957dcbbb363e9e75397224090db79
|
SIDDHARTHSS93/Computer-Security-Assignments
|
/1802772/PlayFair/playfair18812.py
| 8,361 |
null | null | null | null |
def getLotteryPrizings():
numbers = input("Enter Values separated by commas ");
people = input("Enter participants names ");
#convert to list
numbersList = list(numbers)
peopleList = list(people)
peopleNumber = len(peopleList)
numberListTotal = 0
for i in numbersList:
numberListTotal = numberListTotal + i
#highest person shuld get , first identify if the total is even
if numberListTotal % peopleNumber == 0:
averageNumber = numberListTotal / peopleNumber
people_assigned = []
numbers_assigned = []
dic = {}
#check in the list if the averagenumber is in the list, if so assign to one person
if averageNumber in numbersList:
numbers_assigned.append(averageNumber)
l = len(numbers_assigned)
for p in peopleList[0:l]:
people_assigned.append(p)
#create a dictionary that stores persons and average prize number
dic[p] = averageNumber
numbersList.remove(averageNumber)
peopleList.remove(p)
#distribute the rest
for pple in peopleList:
dic[pple] = ""
return dic
print getLotteryPrizings()
| 3.96875 | 4 |
smollm
|
74315ced7ff681627a23317aeb22808dae287aba
|
mayreeh/Lottery
|
/Quiz.py
| 1,303 |
null | null | null | null |
class Product:
def __init__(self, name, price, owner=None, release=None):
self.name = name
self.price = price
self.owner = owner
self.release = release
def __repr__(self):
return f"{self.__class__.__name__}{self.name, self.price}"
if __name__ == "__main__":
iphone = Product("Iphone Max", "12K")
mac = Product("Macbook Pro", "30K")
lenovo = Product("Lenovo Thinkpad", "25K")
print(iphone)
print(mac)
print(lenovo)
items = [iphone, mac, lenovo]
print(items)
items = [{"item": item.name, "price": item.price} for item in items]
print(items)
items = [
{"item": "Iphone Max", "price": "12K"},
{"item": "Macbook Pro", "price": "30K"},
{"item": "Lenovo Thinkpad", "price": "25K"},
]
| 3.5625 | 4 |
smollm
|
638746a93b3d8b9dca38787301df51dce1429b81
|
NagahShinawy/dev.to
|
/tips-tricks/4-comp.py
| 803 |
null | null | null | null |
# https://dev.to/natec425/inspecting-function-annotations-in-python-1hfd
import inspect
users = [
{"username": "john", "password": "123456"},
{"username": "loen", "password": "123456"},
{"username": "smith", "password": "123456"},
]
def login(username: str, password: str) -> bool:
for user in users:
if user["username"] == username and user["password"] == password:
print("You Are Logged In")
return True
return False
login_sig = inspect.signature(login)
print(login_sig)
usrname = login_sig.parameters["username"]
pwd = login_sig.parameters["password"]
print(usrname) # username: str
print(pwd) # password: str
print(usrname.annotation) # <class 'str'>
print(pwd.annotation) # <class 'str'>
print(login_sig.return_annotation) # <class 'bool'>
| 3.828125 | 4 |
smollm
|
22a08c6eec4cb06d758ed873857b68f6d95efbd0
|
NagahShinawy/dev.to
|
/advanced-python/inspecting-function-annotations-in-python-1hfd.py
| 821 |
null | null | null | null |
def trace_of_matrix(order,matrix):
trace=0
for i in range(order):
trace += matrix[i][i]
return trace
NUM_ROWS = 25
NUM_COLS = 25
# construct a matrix
my_matrix = []
for row in range(NUM_ROWS):
new_row = []
for col in range(NUM_COLS):
new_row.append(row * col)
my_matrix.append(new_row)
print(trace_of_matrix(NUM_ROWS,my_matrix))
| 3.703125 | 4 |
smollm
|
8d6a57e58c126d6bec3153ea5bc44135b3e9f200
|
NamitaKalra/PractisePgms
|
/Trace_Matrix.py
| 386 |
null | null | null | null |
def payingOffInAyear(balance, annualInterestRate):
monthlyInterestRate = annualInterestRate / 12
payment = 10
while balance > 0:
bal = balance
for i in range(12):
unpaidBalance = bal - payment
bal = unpaidBalance + unpaidBalance*monthlyInterestRate
if bal <= 0:
return payment
payment += 10
print("lowest payment: "+str(payingOffInAyear(50000000, 0.20)))
| 3.65625 | 4 |
smollm
|
ca7f76acc2fbd0ae6597078708b9dacaa96a7258
|
dsweed12/My-Projects
|
/Project II - Python MITx/venv/problem set 2/problem 2.py
| 434 |
null | null | null | null |
from random import randint
GREETING = 'What number is missing in the progression?'
length_progression = 10
def generate_data():
start = randint(1, 10)
step = randint(1, 10)
hidden_number = randint(0, length_progression - 1)
question = ''
j = 0
while j < length_progression:
if question:
question += ' '
if j != hidden_number:
question = question + str((start + (step * j)))
j += 1
else:
question += '..'
result = str(start + (step * j))
j += 1
return question, result
| 3.921875 | 4 |
smollm
|
e14f066aedbced30d075718c0fb6f24cf285b0d8
|
PolyMaG/python-project-lvl1
|
/brain_games/games/progression.py
| 595 |
null | null | null | null |
'''
Code to create a secret santa generator
Karl Zodda
'''
## Importing packages
import random
def secret_santa(people_to_pick, people_tobe_picked):
## empty dictionary holding who has what person to keep track.
dict = {}
## Now we have two lists. One to pick and one to be picked
#While there are still people to pick
while len(people_to_pick) > 0:
#Enter a name
name = input('Please Enter Your Name:')
#If the name does not match up have them re-enter a new name
if name not in people_to_pick:
continue
# Creating a new list of choices
choices = people_tobe_picked.copy()
## Removing the person picking's name from choices
if name in choices:
choices.remove(name)
i = 0
threshold = min(3, len(choices))
while i < threshold:
random_int = random.randint(0,(len(choices)-1))
print('Here is your choice:', choices[random_int])
if (threshold - i) > 1:
selection = input('To skip press 0, To confirm press any other key:')
else:
selection = 'Required'
## If they don't like the selection
if selection == '0':
## pop the value from the list
choices.pop(random_int)
## update i so there is a count
i += 1
## If selection is yes they are sticking with it
else:
if selection == 'Required':
print("Can't reject, as you are out of choices\n")
else:
print('Choice confirmed \n')
people_tobe_picked.remove(choices[random_int])
people_to_pick.remove(name)
dict[name] = choices[random_int]
break
return dict
| 4.0625 | 4 |
smollm
|
382ed860bc0ba4c6555a69e98cd62ea497312330
|
kzodda/secret_santa
|
/secret_santa.py
| 1,873 |
null | null | null | null |
#Son listas inmutables, es decir, no se pueden modificar despues de su creacion
# no perminten añadir, eliminar, mover elementos (no append, exten, remove)
# si permiten extraer porciones, pero el resultado de la extraccion es una tupla nueva
# si permiten comprobar si un elemento esta en la tupla
# nombreLiSTA=(elem1, elem2, elem3)
mitupla=("Juan", 13, 1, 1995)
print(mitupla[2])
#convertir una lista a tupla o tupla a lista
#nota: sabemos que es una lista por los corchetes []
milista=list(mitupla)
print(milista)
milista1=["Milista", 13,2]
mitupla2=tuple(milista1)
print(mitupla2)
#encontrar un elemento en una tupla
#devolvera True/False
print ("Juan" in mitupla)
#metodo count, cuantos elementos hay un elemento.
print (mitupla.count(13))
#metodo len. para la longitud de la tupla (num elementos)
print (len(mitupla))
#tupla UNITARIA
tuplaUnitaria=("Juan",)
#empaquetado/desempaquetado de una tupla
nombre, dia, mes, agno=mitupla
#esto asigna directamente por orden a estas variables en estas variables
#desempaquetado de tupla
mitupla3="Juana", 2, 3, 1996
print(mitupla3)
nombre1,dia1,mes1,agno1=mitupla3
| 4.1875 | 4 |
smollm
|
e82b1b5c74572b7119c916bf9e4253002603f596
|
fatimaig/Python
|
/ejemplo4_Las tuplas.py
| 1,179 |
null | null | null | null |
# -*- coding: utf-8 -*-
import logging
from collections import namedtuple
Recipe = namedtuple("ClassifiedRecipe", "id, ingredients")
ClassifiedRecipe = namedtuple("ClassifiedRecipe", "id, cuisine, ingredients")
"""
Uses ingredients to categorize the cuisine of a recipe.
@author: Alan Kha
"""
class Cuisinier:
def __init__(self):
self.recipes = {} # <id, Recipe>
self.cuisineCount = {} # <cuisine, frequency>
self.cuisineMatrix = {} # <cuisine, <ingredient, frequency>>
self.ingredientCount = {} # <ingredient, frequency>
self.ingredientMatrix = {} # <ingredient, <cuisine, frequency>>
"""
Returns the algorithm identifier.
@return Algorithm identifier
"""
@abstractmethod
def getAlgorithmType(self):
return "N/A"
"""
Adds a ClassifiedRecipe to the knowledge base.
@param recipe ClassifiedRecipe Recipe to be added
@return True if successful, false otherwise
"""
def addRecipe(self, recipe):
if not isinstance(recipe, ClassifiedRecipe):
raise TypeError("Cuisinier.addRecipe() takes a ClassifiedRecipe")
# Add new recipes to knowledge base
if recipe.id not in self.recipes:
self.recipes[recipe.id] = recipe
# Add to ingredient counter
if recipe.cuisine not in self.cuisineCount:
self.cuisineCount[recipe.cuisine] = 0
self.cuisineCount[recipe.cuisine] += 1
# Initialize cuisine matrix entry
if recipe.cuisine not in self.cuisineMatrix:
self.cuisineMatrix[recipe.cuisine] = {}
# Iterate through ingredients
for ingredient in recipe.ingredients:
# Add to cuisine matrix
if ingredient not in self.cuisineMatrix[recipe.cuisine]:
self.cuisineMatrix[recipe.cuisine][ingredient] = 0
self.cuisineMatrix[recipe.cuisine][ingredient] += 1
# Add to ingredient counter
if ingredient not in self.ingredientCount:
self.ingredientCount[ingredient] = 0
self.ingredientCount[ingredient] += 1
# Add to ingredient matrix
if ingredient not in self.ingredientMatrix:
self.ingredientMatrix[ingredient] = {}
if recipe.cuisine not in self.ingredientMatrix[ingredient]:
self.ingredientMatrix[ingredient][recipe.cuisine] = 0
self.ingredientMatrix[ingredient][recipe.cuisine] += 1
# Return true if successful
logging.info("Add recipe " + str(recipe.id) + ":\tSUCCESS")
return True
logging.info("Add recipe " + str(recipe.id) + ":\tFAIL")
return False
"""
Add a list of ClassfiedRecipes.
@param recipes List of ClassifedRecipes
"""
def addRecipes(self, recipes):
success = 0
for recipe in recipes:
if (self.addRecipe(recipe)):
success += 1
logging.info(str(success) + "/" + str(len(recipes)) + " recipes added")
"""
<<<<<<< HEAD
=======
Run any preprocessing necessary before classification after any change to
the knowledgebase.
"""
@abstractmethod
def preprocess(self):
self.preprocessed = True
"""
Classifies a given Recipe (called by classifyRecipe() after preprocessing).
@param recipe Recipe to be classified
@return ClassfiedRecipe
"""
@abstractmethod
def classify(self, recipe):
# TODO Perform classification
return ClassifiedRecipe(recipe.id, "unknown", recipe.ingredients)
"""
>>>>>>> origin/master
Classifies a given Recipe.
@param recipe Recipe to be classified
@return ClassfiedRecipe
"""
def classifyRecipe(self, recipe):
if not isinstance(recipe, Recipe):
raise TypeError("Cuisinier.classifyRecipe() takes a Recipe")
# TODO Perform
cuisineRecipeClassification = {} # <cuisine, <ingredient, 1 or 0>>
CuisineProb = {} # <cuisine, <ingredient, probability>>
possibleCusineChoices = [] # cuisines who have all the specified recipe
cuisineIngredCt = {} # <cuisine, <ingredient from recipe, frequency>
chosenCuisine = "" #correct Cuisine
chosenCuisineIngredFreq = 0
#loop through the databse of cuisine
for cuisine in self.cuisineCount:
cuisineRecipeClassification[cuisine] = {}
#loop through all the ingredients in the recipe we are given
for ingredient in recipe.ingredients:
#now mark whether ingredient exists in specific cusine
#1, for it does
#0, for it does not
if ingredient not in self.cuisineMatrix[cuisine]:
cuisineRecipeClassification[cuisine][ingredient] = 0
else:
if self.cuisineMatrix[cuisine][ingredient] > 0:
cuisineRecipeClassification[cuisine][ingredient] = 1
else:
cuisineRecipeClassification[cuisine][ingredient] = 0
#choose only the cuisine that has all the listed ingredients
for cuisine in cuisineRecipeClassification:
totalIngredCt = 0
#loop through all the ingredients in the recipe we are given
for ingredient in recipe.ingredients:
totalIngredCt += cuisineRecipeClassification[cuisine][ingredient]
#sum one the 1's must equal to # of ingredients in recipe
if totalIngredCt == (len(recipe.ingredients)):
possibleCusineChoices.append(cuisine)
#now to compare among the remaining cuisines
#if there exist only one possible Cusine choice, we have found it
if len(possibleCusineChoices) == 1:
chosenCuisine = possibleCusineChoices[0]
else:
recipeIngredCt = {} # <ingredient in recipe, frequency>
#now we will find the ingredient with lowest frequency out of all cuisines
for ingredient in recipe.ingredients:
recipeIngredCt[ingredient] = self.ingredientCount[ingredient]
ingredWithLowFreq = ""
for ingredient in recipeIngredCt:
if ingredWithLowFreq == "":
ingredWithLowFreq = ingredient
elif recipeIngredCt[ingredient] < recipeIngredCt[ingredWithLowFreq]:
ingredWithLowFreq = ingredient
#now find the cuisine with the highest frequency of the ingredients with lowest overall frequency
for cuisine in possibleCusineChoices:
cuisineIngredFreq = self.cuisineMatrix[cuisine][ingredWithLowFreq]
print(cuisine)
print(cuisineIngredFreq)
if chosenCuisine == "":
chosenCuisine = cuisine
chosenCuisineIngredFreq = cuisineIngredFreq
elif cuisineIngredFreq > chosenCuisineIngredFreq:
chosenCuisine = cuisine
chosenCuisineIngredFreq = cuisineIngredFreq
print(ingredWithLowFreq)
print(chosenCuisineIngredFreq)
return ClassifiedRecipe(recipe.id, chosenCuisine, recipe.ingredients)
"""
Classifies a list of Recipes.
@param recipes List of Recipes
@return List of ClassfiedRecipes
"""
def classifyRecipes(self, recipes):
# Iterate through recipes
return [self.classifyRecipe(recipe) for recipe in recipes]
| 3.59375 | 4 |
smollm
|
7decf7fa1f875c05f6fdb0eede09bc804d993342
|
tracyyu/UCLA-CS-145-Cuisiner
|
/Cuisinier-Tracy/Cuisinier.py
| 7,687 |
null | null | null | null |
import math
num = int(input("Enter a number: "))
guess = int(input("Guess its square root: "))
new_guess = 0
while new_guess < (guess + .5):
quotient = num / guess
print(quotient," m")
average = (quotient + guess) / 2
new_guess = average
if(new_guess >= (guess + .5)):
print(new_guess, " g" )
break
| 4.0625 | 4 |
smollm
|
fd9b08cac785bb85f45d42dd13aab2ecdbec6934
|
tboydv1/project_python
|
/practice/squareRoot.py
| 383 |
null | null | null | null |
import string
file_name = input("Enter file name: ")
dict_obj = open('dictionary.txt', 'w')
bad_char = string.punctuation + string.whitespace
while True:
try:
file_obj = open(file_name, 'r')
letter = ''
count = 0
for line in file_obj:
for char in line:
# if char == letter:
count += 1
print(char, "and ", count)
file_obj.close()
except FileNotFoundError:
print("Try again")
file_obj = open(file_name, 'r')
| 3.53125 | 4 |
smollm
|
ecc188ab7773345497bbc6ea10745d1f7843f1f5
|
tboydv1/project_python
|
/Python_book_exercises/chapter5/exercise7/word_occurence.py
| 538 |
null | null | null | null |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 10:54:21 2019
@author: tboydev
"""
name_str = "homebody"
print(name_str[:(name_str.find('b'))])
print(name_str[(name_str.find('b')):name_str.find('y')+1])
| 3.796875 | 4 |
smollm
|
aad012a5511de97fc0285fcafb44f21b83202d33
|
tboydv1/project_python
|
/Python_book_exercises/chapter4/string2.py
| 229 |
null | null | null | null |
#read a particular line from a file. User provides bothe the line
#numbe and the file name
file_str = input("Open what file: ")
status = True
while status:
try:
input_file = open(file_str)
find_line_str = input("Which line (integer): ")
find_line_int = int(find_line_str)
for count, line_str in enumerate(input_file):
if count == find_line_int:
print("Line {} of file {} is {}".format(find_line_int, file_str, line_str))
status = False
break
else:
print("Line {} of file {} not found ".format(find_line_int, file_str))
input_file.close()
except FileNotFoundError:
print("File not foundf")
file_str = input("Open what file:")
except ValueError:
print("Line", find_line_str, "isn't a legal line number")
find_line_str = input("Which line (integer): ")
print("End of program")
| 4.28125 | 4 |
smollm
|
0b4a21bbd39170d02f0cb77d8f2d1a73c7f074cc
|
tboydv1/project_python
|
/Python_book_exercises/chapter5/examples/exception_handling.py
| 942 |
null | null | null | null |
#Anagram test
def are_anagrams(word1, word2):
"""Return true if words are not anagrams"""
word1_sorted = sorted(word1)
word2_sorted = sorted(word2)
return word1_sorted == word2_sorted
print("Anagram Test")
#validate user input
valid_input = False
while(not valid_input):
try:
two_word = input("Enter two space seperated words")
word1, word2 = two_word.split(" ")
valid_input = True
except ValueError as e:
print("Bad Input")
if are_anagrams(word1, word2):
print("The words {} and {} are anagrams".format(word1, word2))
else:
print("The words {} and {} are anagrams".format(word1, word2))
| 4.34375 | 4 |
smollm
|
2a852e6885e008fd7a2dac97172feeebe3489fb4
|
tboydv1/project_python
|
/Python_book_exercises/chapter7/examples/Anagram_test.py
| 657 |
null | null | null | null |
#classify a range of numbers with respect to perfect, abundant or deficient
top_num = int(input("What is the upper number for the range: "))
number = 2
while number <= top_num:
#sum the divisors of the number
divisor = 1
sum_of_divisors = 0
while divisor < number:
if number % divisor == 0:
sum_of_divisors += divisor
divisor += 1
#classify the number based on it divisor sum
if sum_of_divisors == number:
print(number, "is perfect")
if sum_of_divisors > number:
print(number, 'is abundant')
if sum_of_divisors < number:
print(number, 'is deficient')
number += 1
| 3.953125 | 4 |
smollm
|
3044e68af4494f010d8ebbd1b960a631e6bfdd00
|
tboydv1/project_python
|
/Python_book_exercises/chapter1/classifyInt.py
| 695 |
null | null | null | null |
#Body mass index calculator
## prompt for metrics weight and height
weight = int(input("Enter weigth in kilograms "))
height = int(input("Enter heigth in meteres "))
BMI = weight / (height**2)
print("Body mass index is: ", BMI)
| 4.1875 | 4 |
smollm
|
4579f5cb3cc38dfcf56785cb85b7935aa687b2b8
|
tboydv1/project_python
|
/Python_book_exercises/chapter1/BMI_calculator.py
| 234 |
null | null | null | null |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 15:16:18 2019
@author: tboydev
"""
def celcius_to_fahrenheit(celcius_float):
"""Convert Celsius to Fahrenheit"""
return celcius_float * 1.8 + 32
| 3.703125 | 4 |
smollm
|
8f172b0ed5edaf81b5e1e351b7a8faac4c78f4a6
|
tboydv1/project_python
|
/Python_book_exercises/chapter1/temperature.py
| 223 |
null | null | null | null |
#importing the necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#reading the csv file
yelp_df = pd.read_csv("yelp.csv")
#description of yelp dataset
yelp_df.describe()
#some more information on the yelp dataset
yelp_df.info() #There is no missing data
#adding length of words to our dataframe
yelp_df['length'] = yelp_df['text'].apply(len)
#now that length column is added lets visualize our histogram
yelp_df['length'].plot(bins=100,kind='hist')
#lets find out some more information about our length column
yelp_df['length'].describe() #so the maximum word length is 4997 and the minimum word length is 1
#lets see the max word i.e. 4997
yelp_df[yelp_df['length']==4997]['text'].iloc[0]
#lets see our minimum word i.e. 1
yelp_df[yelp_df['length']==1]['text'].iloc[0]
#lets visualise the count plot to see actually how many numbers of 1,2,3,4 and 5 stars do we have
sns.countplot(y='stars',data=yelp_df)
#lets plot a facetgrid graph
g = sns.FacetGrid(data=yelp_df , col='stars', col_wrap=3)
g.map(plt.hist,'length',bins=20,color='g')
#dividing the data frames into stars
df_1 = yelp_df[yelp_df['stars']==1]
df_5 = yelp_df[yelp_df['stars']==5]
#concatinating the datasets
df_all = pd.concat([df_1,df_5])
#lets the precentage of stars in the data set
print("The percentage of 1 star reviews are ",(len(df_1)/len(df_all))*100,"%")
print("The percentage of 5 star reviews are ",(len(df_5)/len(df_all))*100,"%")
#ploting the count plot
sns.countplot(df_all['stars'],label='count')
#importing nltk and punctuation library
import string
string.punctuation
import nltk
from nltk.corpus import stopwords
#nltk.download('stopwords')
stopwords.words('english')
#lets clean our data set
def message_cleaning(message):
text_punc_rem = [char for char in message if char not in string.punctuation]
text_punc_rem_join = ''.join(text_punc_rem)
text_punc_rem_join_clean = [word for word in text_punc_rem_join.split() if word.lower() not in stopwords.words('english')]
return text_punc_rem_join_clean
df_clean = df_all['text'].apply(message_cleaning)
#printing the zeroth text value of the cleaned dataframe
print(df_clean[0])
#printing the zeroth text value of the normal dataframe
print(df_all['text'][0])
#applying countvectorizer
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(analyzer = message_cleaning)
cv_df = cv.fit_transform(df_all['text'])
#printing all the feature names
print(cv.get_feature_names())
print(cv_df.toarray())
#dividing our dataset/dataframe into training and testing dataframes
label= df_all['stars'].values
x=cv_df
y= label
from sklearn.model_selection import train_test_split
xtrain,xtest,ytrain,ytest = train_test_split(x,y,test_size=0.2)
#training the model using naive bayes
from sklearn.naive_bayes import MultinomialNB
nb = MultinomialNB()
nb.fit(xtrain,ytrain)
#predicting the training set,test set , calculating its accuracy , finding its classfication report and ploting a heat map
ypred_train = nb.predict(xtrain)
ypred_test = nb.predict(xtest)
from sklearn.metrics import confusion_matrix,classification_report,accuracy_score
cm = confusion_matrix(ytrain,ypred_train)
sns.heatmap(cm, annot=True)
print(classification_report(ytrain,ypred_train))
accuracy_score(ytrain,ypred_train)
cms = confusion_matrix(ytest,ypred_test)
sns.heatmap(cms, annot=True)
print(classification_report(ytest,ypred_test))
accuracy_score(ytest,ypred_test)
# [1] represents that the customer is unsatisfied and [5] represents that the customer is happy
test = input('enter your review here')
test1 = []
test1.append(test)
test1i = cv.transform(test1)
py = nb.predict(test1i)
if(py == [1]):
print("The customer is not satisfied")
else :
print("The customer is satisfied")
| 3.765625 | 4 |
smollm
|
a5e426073e06007a83bcdceb622a571797a02a78
|
SujayDas1999/Yelp-review-classification-
|
/yelp_review_classification.py
| 3,846 |
null | null | null | null |
# def my_function(str1, str2):
# print('This is my function!')
# print(str1)
# print(str2)
# my_function('hello', 'world')
# def print_something(name="Jonny", age=50):
# print('My name is', name, ' and my age is ', age)
# print_something(age=32)
# def print_people(*people):
# for person in people:
# print("This person is", person)
# print_people("Jonny", "Leigh", "Charlie")
# def do_math(num1, num2):
# return num1 + num2
# print(do_math(5, 7))
# import re
# # This is Regex
# string = '"I AM NOT YELLING", she said. Thought I know it to be strong'
# print(string)
# new = re.sub('[A-Z]', '', string)
# print(new)
# new = re.sub('[^0-9]', '', string)
# # This one removes everything apart from numbers
# BASIC CALCULATOR BUILD
# import re
# print('Our Calculator')
# print('Type "quit" to exit\n')
# previous = 0
# run = True
# def perform_math():
# global run
# global previous
# equation = input ('Enter equation: ')
# if equation == "quit":
# run = False
# else:
# equation = re.sub('[a-zA-Z,.:()" "]', '', equation)
# previous = eval(equation)
# print ("You Typed", previous)
# while run:
# perform_math()
| 3.84375 | 4 |
smollm
|
eedb068d426db3e062c422820cd8d08466f9fa44
|
jonnysfarmer/python-learning
|
/main.py
| 1,225 |
null | null | null | null |
"""$$$ datatypes(17) $$$"""
"""int,float,string,none,bool,list,set,dictionary,string"""
"""int datatype"""
# n=2;m=3;o=5
# print(n,type(n))
# print(m,type(m))
# print(o,type(o))
"""convert int-->float"""
# a=12
# print(a)
# print(int(a))
# print(float(a))
"""float datatype"""
# p=2.3;q=3.4;r=5.6
# print(p,type(p))
# print(q,type(q))
# print(r,type(r))
"""convert float-->int"""
# b=2.2
# print(b)
# print(float(b))
# print(int(b))
"""string datatype"""
# a="hello"
# print(a) #hello
# print(a,type(a)) #hello <class 'str'>
'''convert str-->int,float'''
# n="python"
# m=int(n)
# o=float(n)
# print(n)
# print(m) #ValueError: invalid literal for int() with base 10: 'pyhton'
# print(o) #ValueError: could not convert string to float: 'python'
# s="hello"
# print(s) #hello
# print(s[0]) #h
# print("%c"%s[0]) #h
# print("%c"%s[1]) #e
# print("%c"%s[2]) #l
# print("%c"%s[3]) #l
# print("%c"%s[4]) #o
# # print("%c"%s[5]) #IndexError: string index out of range
# print("%c"%s[-1]) #o
# print("%c"%s[-2]) #l
# print("%c"%s[-3]) #l
# print("%c"%s[-4]) #e
# print("%c"%s[-5]) #h
"""None datatype"""
# b=None
# print(b,type(b)) #None <class 'NoneType'>
"""boolean datatype"""
# a=True
# print(a,type(a)) #True <class 'bool'>
# b=False
# print(b,type(b)) #False <class 'bool'>
# print(3<5) #True
# print(3>5 #False
"""List datatype"""
# a=[]
# print(a,type(a)) #[] <class 'list'>
# p=["sri",23,1.0,None,True]
# print(p,type(p)) #['sri', 23, 1.0, None, True] <class 'list'>
# print(p[0],type(p[0])) #sri <class 'str'>
# print(p[1],type(p[1])) #23 <class 'int'>
# print(p[2],type(p[2])) #1.0 <class 'float'>
# print(p[3],type(p[3])) #None <class 'NoneType'>
# print(p[4],type(p[4])) #True <class 'bool'>
# print(p[5],type(p[5])) #IndexError: list index out of range
# r=[4,3.1,"python"]
# r[0]="H"
# r[2]="programming"
# print(r) #['H', 3.1, 'programming']
""" Tuple datatype """
# a=(1.1,2,'hello',)
# print(a,type(a)) #(1.1, 2, 'hello') <class 'tuple'>
# print(a[-1]) #hello
# m=('apple',"moto","onle+","nokia","mi","xiomi","vivo","oppo")
# print(m) #('apple', 'moto', 'onle+', 'nokia', 'mi', 'xiomi', 'vivo', 'oppo')
# n="hello","python"
# print(n,type(n)) #('hello', 'python') <class 'tuple'>
# print(n[0]) # hello
""" set datatype"""
# a={}
# print(a,type(a)) #{} <class 'dict'>
# b={1,2,3}
# print(b,type(b)) #{1, 2, 3} <class 'set'>
# c={3,5.5,"hi",("hey",9)}
# print(c,type(c)) #{('hey', 9), 3, 'hi', 5.5} <class 'set'>
# n={1,2,3}
# print(n[1]) #TypeError: 'set' object is not subscriptable
# d={1,3,5}
# print(d,type(d)) #{1, 3, 5} <class 'set'>
# k=frozenset(d)
# print(k) #frozenset({1, 3, 5})
# print(k,type(k)) #frozenset({1, 3, 5}) <class 'frozenset'>
# print(k[1]) #TypeError: 'frozenset' object is not subscriptable
""" dictionary datatype """
# book={1:"python",2:"html",3:"css",4:"javascript"}
# print(book) #{1: 'python', 2: 'html', 3: 'css', 4: 'javascript'}
# print(book,type(book)) #{1: 'python', 2: 'html', 3: 'css', 4: 'javascript'} <class 'dict'>
# print(book[3]) #css
# a={1:"",2:"python",3:5,4:3.3,5:[1,1],6:(3,4),7:{1,2},8:"yes"}
# print(a[1],type(a[1])) # <class 'str'>
# print(a[2],type(a[2])) #python <class 'str'>
# print(a[3],type(a[3])) #5 <class 'int'>
# print(a[4],type(a[4])) #3.3 <class 'float'>
# print(a[5],type(a[5])) #[1, 1] <class 'list'>
# print(a[6],type(a[6])) #(3, 4) <class 'tuple'>
# print(a[7],type(a[7])) #{1, 2} <class 'set'>
# print(a[8],type(a[8])) #yes <class 'str'>
# print(a,type(a)) #{1: '', 2: 'python', 3: 5, 4: 3.3, 5: [1, 1], 6: (3, 4), 7: {1, 2}, 8: 'yes'} <class 'dict'>
# print(a.keys()) #dict_keys([1, 2, 3, 4, 5, 6, 7, 8])
# print(a.values()) #dict_values(['', 'python', 5, 3.3, [1, 1], (3, 4), {1, 2}, 'yes'])
# print(a.items()) #dict_items([(1, ''), (2, 'python'), (3, 5), (4, 3.3), (5, [1, 1]), (6, (3, 4)), (7, {1, 2}), (8, 'yes')])
# t=range(5)
# print(t,type(t)) #range(0, 5) <class 'range'>
# z=b"hello"
# print(z,type(z)) #b'hello' <class 'bytes'>
# d=bytearray(b"hello")
# print(d) #bytearray(b'hello')
""" string datatype"""
# a="hello python programming"
# print(a,type(a)) #hello python programming <class 'str'>
# print(len("python programing")) #17
a="python"
# print(a[0]) #p
# print("python"[0]) #p
# print("python"[1]) #y
# print("python"[2]) #t
# print("python"[3]) #h
# print("python"[4]) #o
# print("python"[5]) #n
# print("python"[6]) #IndexError: string index out of range
# print("python"[-1]) #n
# print("python"[-2]) #o
# print("python"[-3]) #h
# print("python"[-4]) #t
# print("python"[-5]) #y
# print("python"[-6]) #p
# print("python"[-7]) #IndexError: string index out of range
w="python"
# print(w[:]) #python
# print(w[0:]) #python
# print(w[0:6]) #python
# print(w[-6:6]) #python
# print(w[0:1]) #p
# print(w[0:2]) #py
# print(w[0:3]) #pyt
# print(w[0:4]) #pyth
# print(w[0:5]) #pytho
# print(w[0:6]) #python
# print(w[0:7]) #python
# print(w[0:8]) #python
# print(w[0:0]) #empty line
# print(w[0:-1]) #pytho
# print(w[0:-2]) #pyth
# print(w[0:-3]) #pyt
# print(w[0:-4]) #py
# print(w[0:-5]) #p
# print(w[0:-6]) #empty line
"""string methods(47)"""
"""'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs',\
'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', \
'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix',\
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', \
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'"""
# a="String methods"
# print(a.capitalize()) #Stringmethods
# print(a.casefold()) #stringmethods
# print(a.swapcase()) #sTRINGMETHODS
# print(a.title()) #Stringmethods
# print(a.istitle()) #True
# print(a.upper()) #STRINGMETHODS
# print(a.isupper()) #False
# print(a.lower()) #stringmethods
# print(a.islower()) #False
# print(a.center()) #TypeError: center expected at least 1 argument, got 0
# print(a.center(10)) #Stringmethods
# print(a.center(20)) # Stringmethods
# print(a.center(30)) # Stringmethods
# print(a.center(40)) # Stringmethods
# print(a.center(50)) # Stringmethods
# print(a.count()) #TypeError: count() takes at least 1 argument (0 given)
# print(a.count('a')) #0
# print(a.count('s')) #1
# print(a.count('r')) #1
# print(a.isspace())#false
# print(a.startswith("S"))#True
# print(a.startswith(" "))#false
# print(a.endswith(""))#true
# print(a.endswith("s"))#true
# print(a.endswith('m'))#false
# x=" string "
# y=" string * "
# z=" * string "
# # print(x.strip())#string
# print(y.strip())#string *
# print(z.strip())#* string
# print(x.lstrip())#string
# print(y.lstrip())#string *
# print(z.lstrip())#* string
# print(x.rstrip())# string
# print(y.rstrip())# string *
# print(z.rstrip())# * string
# n="happy dusshera"
# a=print(n.encode()) #b'happy dusshera'
# n=b'happy dessra'
# print(n.decode()) #happy dusshra
# g="happy diwali"
# print(g.index('d')) #6
# print(g.rindex('i')) #11
# r="hello google"
# print(len(r)) #12j
# print(r.find('g'))
# print(r.rfind('o')) #12
# k="happy new year"
# print(k.replace("new","old")) #happy old year
# print(k.replace("new",str(5))) #happy 5 year
# print(k.replace('e','a',1)) #happy naw year
# print(k.replace('e','a',2)) #happy naw yaar
# a="ipl14"
# print(a.isalnum())#True
# b="ipl "
# print(b.isalnum()) #False
# c="core python"
# print(c.isalpha()) #False
# d="corepython"
# print(d.isalpha()) #True
# print(d.isascii()) #True
# a={'x':1,'y':4,'z':6}
# print('{}{}{}'.format(*a)) #xyz
# print('{x}{y}{z}'.format(**a)) #146
# print('{x}{y}{z}'.format(**a)) #146
# print('{x}{y}{z}'.format_map(a)) #146
# x="hello\tworld"
# print(x.expandtabs()) #hello world
# print(x.expandtabs(10)) #hello world
# print(x.expandtabs(20)) #hello world
# y="h\te\tl\tl\to"
# print(y.expandtabs(5)) #h e l l o
# print(y.expandtabs(10)) #h e l l o
# print(y.expandtabs(15)) #h e l l o
# print(y.expandtabs(20)) #h e l l o
# print(y.expandtabs(25)) #h e l l o
# q="2021"
# print(q.zfill(1)) #2021
# print(q.zfill(2)) #2021
# print(q.zfill(3)) #2021
# print(q.zfill(4)) #2021
# print(q.zfill(5)) #02021
# print(q.zfill(10)) #0000002021
# i="\b"
# j="\n"
# g=""
# k=" "
# print(i.isprintable())#False
# print(j.isprintable())#False
# print(g.isprintable())#True
# print(k.isprintable())#True
# p="2"
# print(p.isdecimal())#True
# l="3e"
# print(l.isdecimal())#False
# w= "hello"
# print(w.ljust(30),"is my favorite fruit.")#hello is my favorite fruit.
""" set methods (17) """
a=['add', 'clear', 'copy', 'difference', 'difference_update',
'discard', 'intersection', 'intersection_update', 'isdisjoint', \
'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference',\
'symmetric_difference_update', 'union', 'update']
# print(len(a))
# a={1,2,3,4,5};b="python",3,5,7
# a.add(b)
# print(a) #{1, 2, 3, 4, 5, ('python', 3, 5, 7)}
# b={1,2,3}
# b.clear()
# print(b) #set()
# a={3,4,5,6}
# x=a.copy()
# print(a) # {3, 4, 5, 6}
# a={1,2,3,4,5,6};b={3,5,7}
# print(a.difference(b)) #{1, 2, 4, 6}
# print(b.difference(a)) #{7}
# print(a-b) #{1, 2, 4, 6}
# print(b-a) #{7}
# a.difference_update(b)
# b.difference_update(a)
# print(a) #{1, 2, 4, 6}
# print(b) #{7}
# x={11,22,33,44,55,66}
# x.discard(2)
# print(x) #{33, 66, 22, 55, 11, 44}
# x.discard(33)
# print(x) #{66, 22, 55, 11, 44}
# a={1,2,3,4,5};b={3,4,5,6,7};c={5,6,7,};d={3,5,7}
# print(a.union(b)) #{1, 2, 3, 4, 5, 6, 7}
# print(a.intersection(b)) #{3, 4, 5}
# print(a.union(c)) #{1, 2, 3, 4, 5, 6, 7}
# print(a.intersection(c)) #{5}
# # print(b.union(d)) #{3, 4, 5, 6, 7}
# print(b.intersection(d)) #{3, 5, 7}
# # print(c.union(d)) #{3, 5, 6, 7}
# print(c.intersection(d)) #{5, 7}
# print(a.intersection(b)) #{3, 4, 5}
# a.intersection_update(b)
# print(a) #{3, 4, 5}
# x={12,23,34,22,66,};y={56,67,78};z={12,77,90,87,88}
# print("are a and b disjoint?",x.isdisjoint(y) ) #are a and b disjoint? True
# print("are a and b disjoint?",y.isdisjoint(a) ) #are a and b disjoint? True
# print("are a and b disjoint?",x.isdisjoint(z) ) #are a and b disjoint? False
# print("are a and b disjoint?",y.isdisjoint(z) ) #are a and b disjoint? True
# x={1,2,3,4,5,6,7};y={2,4,5,3,6,7};z={3,6,7}
# print(y.issubset(x)) #True
# print(y.issubset(z)) #False
# print(x.issubset(z)) #False
# print(y.issuperset(x)) #False
# print(y.issuperset(z)) #True
# print(x.issuperset(z)) #True
# c={6,5,8,14}
# c.pop()
# print(c) #{5, 6, 14}
# x={1,2,3,4,5,6,7}
# x.remove(3)
# print(x) #{1, 2, 4, 5, 6, 7}
# a={1,2,3,4,5};b={3,4,5,6,7};c={5,6,7,8};d={3,5,7,9}
# a.update(b)
# b.update(c)
# c.update(d)
# print(a) #{1, 2, 3, 4, 5, 6, 7}
# print(b) #{3, 4, 5, 6, 7, 8}
# print(c) #{3, 5, 6, 7, 8, 9}
# print(a.symmetric_difference(b)) #{1, 2, 6, 7}
# print(a) #{1, 2, 3, 4, 5}
# a.symmetric_difference_update(b)
# print(a) #{1, 2, 6, 7}
""" list datatype(11)"""
"""['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort' """
# print(len(a))
n=[1,2.2,"python",[11,22],(1,1),]
# print(n,type(n)) #[1, 2.2, 'python', [11, 22], (1, 1)] <class 'list'>
# print(n[0],type(n[0])) #1 <class 'int'>
# print(n[1],type(n[1])) #2.2 <class 'float'>
# print(n[2],type(n[2])) #python <class 'str'>
# print(n[3],type(n[3])) #[11, 22] <class 'list'>
# print(n[4],type(n[4])) #(1, 1) <class 'tuple'>
n=[1,2.2,"python",[11,22],(1,1),]
# n.append("hello")
# print(n) #[1, 2.2, 'python', [11, 22], (1, 1), 'hello']
# n.clear()
# print(n) #[]
# m=n.copy()
# print(m) #[1, 2.2, 'python', [11, 22], (1, 1)]
# print(n.count(5))#0
# print(n.count(1))#1
# m=[11,22,33,"web"]
# n.extend(m)
# m.extend(n)
# print(n) #[1, 2.2, 'python', [11, 22], (1, 1), 11, 22, 33, 'web']
# print(m) #[11, 22, 33, 'web', 1, 2.2, 'python', [11, 22], (1, 1), 11, 22, 33, 'web']
# m=[11,22,33,"web"]
# print(m.index())#TypeError: index expected at least 1 argument, got 0
# print(m.index(22))#1
# print(m.index("web"))#3
# m.insert(1,"55")#[11, '55', 22, 33, 'web']
# m.insert(4,"development")
# print(m) #[11, 22, 33, 'web', 'development']
# m.pop()
# print(m) #[11, 22, 33]
# m.pop(1)
# print(m) #[11, 33]
# m.remove("web")
# print(m) #[11, 22, 33]
# n=[5,7,3,5,1]
# n.sort()
# print(n) #[1, 3, 5, 5, 7]
# n.sort(reverse=True)
# print(n) #[7, 5, 5, 3, 1]
# n.sort(reverse=False)
# print(n) #[1, 3, 5, 5, 7]
# k=["se","tf","hg","ii"]
# k.sort()
# print(k) #['hg', 'ii', 'se', 'tf']
""" tuple methods(2)"""
"""'count', 'index'"""
# print(dir(tuple))
# a=(1,4,8,12,23,56,78,54,4,133,66,88,2,99)
# print(a.count(4)) #2
# print(a.index(54)) #7
""" dictionary methods(11)"""
""" 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop',
'popitem', 'setdefault', 'update', 'values'"""
# print(dir(dict))
# h={1:1,2:"hello",3:2.2,4:(1,2),5:[2,2],6:{5,8}}
# print(h[1],type(h[1]))#1 <class 'int'>
# print(h[2],type(h[2]))#hello <class 'str'>
# print(h,type(h))#{1: 1, 2: 'hello', 3: 2.2, 4: (1, 2), 5: [2, 2], 6: {8, 5}} <class 'dict'
# print(h.keys())#dict_keys([1, 2, 3, 4, 5, 6])
# print(h.values())#dict_values([1, 'hello', 2.2, (1, 2), [2, 2], {8, 5}])
# print(h.items())#dict_items([(1, 1), (2, 'hello'), (3, 2.2), (4, (1, 2)), (5, [2, 2]), (6, {8, 5})])
# h.clear()
# print(h) #{}
# a=[100,101,102,103,104,105,106]
# b=dict.fromkeys(a)
# print(b,type(b)) #{100: None, 101: None, 102: None, 103: None, 104: None, 105: None, 106: None} <class 'dict'>
# print(dict.fromkeys(a,"python")) #{100: 'python', 101: 'python', 102: 'python', 103: 'python', 104: 'python', 105: 'python', 106: 'python'}
# h={1:1,2:"hello",3:2.2,4:(1,2),5:[2,2],6:{5,8}}
# print(h.get(2)) #hello
# print(h.get(10)) #None
# print(h[2]) #hello
# print(h[10]) #KeyError: 10
# h.pop(3)
# print(h) #{1: 1, 2: 'hello', 4: (1, 2), 5: [2, 2], 6: {8, 5}}
# h.popitem()
# print(h) #{1: 1, 2: 'hello', 3: 2.2, 4: (1, 2), 5: [2, 2]}
# h={1:1,2:"hello",3:2.2,4:(1,2),5:[2,2],6:{5,8}}
# h.update({7:"python"})
# print(h) #{1: 1, 2: 'hello', 3: 2.2, 4: (1, 2), 5: [2, 2], 6: {8, 5}, 7: 'python'}
# h.setdefault(8,[11,22])
# print(h) #{1: 1, 2: 'hello', 3: 2.2, 4: (1, 2), 5: [2, 2], 6: {8, 5}, 7: 'python'}
| 4.03125 | 4 |
smollm
|
81a8392519494f877be2ca6271b0dc1c9ebb2c28
|
sree-07/PYTHON
|
/data types.py
| 18,266 |
null | null | null | null |
class Player:
def __init__(self, name, age, country, chips):
self.name = name
self.age = age
self.country = country
self.chips = chips
self.bet = 0
self.__hand = []
self.__value = 0
self.stand = False
self.won = False
self.exceeded = False
def set_bet(self, bet):
self.bet = bet
self.chips = self.chips - self.bet
def pick_card(self, deck):
self.__hand.append(deck.pick_card())
self.__calculate_value()
self.__chech_score()
def __chech_score(self):
if self.__value == 21:
self.won = True
if self.__value > 21:
self.exceeded = True
def __calculate_value(self):
self.__value = 0
aces_found = 0
for card in self.__hand:
if card.value in "2 3 4 5 6 7 8 9 10".split(" "):
self.__value = self.__value + int(card.value)
elif card.value in "J Q K".split(" "):
self.__value = self.__value + 10
else:
self.__value = self.__value + 11
aces_found = aces_found + 1
for index in range(aces_found):
if self.__value <= 21:
break
self.__value = self.__value - 10
def get_hand(self):
return self.__hand
def clear_hand(self):
self.__hand = []
def get_value(self):
return self.__value
def display_hand(self):
for card in self.__hand:
print(str(card))
def __str__(self):
return "Player [{}, {}, {}, {}, Hand value: {}, Stand: {}, Exceeded: {}, Won: {}]".format(self.name, self.age, self.country, self.chips, self.__value, self.stand, self.exceeded, self.won)
| 3.5 | 4 |
smollm
|
3454f1a2e85eb63ea875ebdc3d63d419c773f721
|
mariantirlea/python-blackjack
|
/entity/Player.py
| 1,852 |
null | null | null | null |
# -*- coding:utf-8 -*-
import random
secret = random.randint(1,10)
temp = input("请输入一个10以内的数字:")
while temp.isdigit() != True:
temp = input("你的输入有误,请输入一个10以内的数字:")
guess = int(temp)
while guess < 0 or guess > 10 :
temp = input("你输入的范围不对哦!请输入一个10以内的数字:")
guess = int(temp)
t = 0
if guess == secret:
print("太厉害了!")
print("你只用一次就猜对了!!!")
t = 4
while t < 3:
if guess == secret:
print("你猜对啦!!")
t = 4
else:
if guess > secret :
t = t + 1
print("猜的太大啦~你只剩%d次机会啦" % (3-t))
temp = input("请重新输入:")
guess = int(temp)
else:
t = t + 1
print("猜小啦~你只剩%d次机会啦" % (3-t))
temp = input("请重新输入:")
guess = int(temp)
if t == 3:
print("你的机会用光啦~")
| 3.578125 | 4 |
smollm
|
37dd22aa8cca15c9c0eee5c3b618fd93669b0291
|
javenxww/Python_Study_Recode
|
/WordGame/WordGame.py
| 887 |
null | null | null | null |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 9 19:22:40 2018
@author: virajdeshwal
"""
print('Lets begin with the Kmeans Clustering.\n')
#intake = input('Press any key to continue....\n\n')
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
file = pd.read_csv('Mall_Customers.csv')
X = file.iloc[:,[3,4]].values
'''to find the optimal clusters use Elbow method... remove these comments and use the beolw code to check the elbow graph
# Now lets use the Elbow method to define the optioal number of clusters
#metric for clusters
wcss = []
from sklearn.cluster import KMeans
#for loop to check the clusters from 1 to 10
for i in range(1,11):
#intialization of the model
kmeans = KMeans(n_clusters=3, init='k-means++', n_init=10, max_iter=300, random_state=0)
#fitting the kmeans to the independent variables
#Now lets calculate the centroid of the cluster
wcss.append(kmeans.inertia_)
plt.plot(range(1,11),wcss)
plt.title('The Elbow Method')
plt.xlabel('Numbers of Clusters')
plt.ylabel('WCSS')
plt.show()'''
'''Now as we got the idea from the elbow graph about the optimal no. of clusters.
we will take the 5 clusters for our dataset.'''
#applying k-means to the dataset
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=5, init='k-means++', n_init=10, max_iter=300, random_state=0)
y_means =kmeans.fit_predict(X)
plt.scatter(X[y_means==0,0], X[y_means==0,1], s=100, c='red', label = 'Careful pals')
plt.scatter(X[y_means==1,0], X[y_means==1,1], s=100, c='blue', label = 'average')
plt.scatter(X[y_means==2,0], X[y_means==2,1], s=100, c='green', label = 'Targets')
plt.scatter(X[y_means==3,0], X[y_means==3,1], s=100, c='magenta', label = 'Freak')
plt.scatter(X[y_means==4,0], X[y_means==4,1], s=100, c='cyan', label = 'Sensible')
plt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], s=300, c='yellow', label = 'Centroids')
plt.title('clusters of client')
plt.xlabel('Annual Income(K$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show()
print('\nDone ;)')
| 3.90625 | 4 |
smollm
|
d64b781daefef1110feddb5e2744a760069ebee6
|
VirajDeshwal/KMeans-Clustering
|
/KmeansClustering.py
| 2,094 |
null | null | null | null |
class Node():
def __init__(self, _data, _next):
self.data = _data
self.next = _next
class LinkedList():
def __init__(self, _list):
self.head = None
self.tail = None
self.count = None
for i in _list:
self.append(i)
def append(self, _data, pos=None):
node = Node(_data, None)
if (self.head == None):
self.head = node
self.tail = node
return
if (pos == None):
self.tail.next = node
self.tail = node
else:
tmp = self.head
if (pos == 0):
node.next = tmp
self.head = node
return
for i in range(pos-1):
tmp = tmp.next
if tmp == None: break
if (tmp == None):
self.tail.next = node
self.tail = node
else:
node.next = tmp.next
tmp.next = node
self.tail = node
def pop(self, pos=None):
tmp = self.head
if pos == None:
while (tmp.next != self.tail):
tmp = tmp.next
data = tmp.next.data
self.tail = tmp
del tmp.next
self.tail.next = None
elif pos == 1:
data = tmp.data
self.head = tmp.next
del tmp
else:
for i in range(pos-2):
tmp = tmp.next
popEle = tmp.next
data = popEle.data
tmp.next = popEle.next
if tmp.next == None:
self.tail = tmp
del popEle
return data
def remove(self, pos):
self.pop(pos)
def __str__(self):
ll = ""
tmp = self.head
while (tmp != None):
ll += str(tmp.data) + " -> "
tmp = tmp.next
return ll
def findNthElement(self, node, pos):
if node == None:
n = 1
return n
n = self.findNthElement(node.next, pos)
if (pos == n):
print (node.data)
return n + 1
def findNthElementFromLast(self, pos):
n = self.findNthElement(self.head, pos)
#print (n)
def findNthElementfromEnd(self, pos):
p2 = self.head
p1= self.head
while (pos != 0):
if p2 == None:
return
p2 = p2.next
pos -= 1
while (p2 != None):
p1 = p1.next
p2 = p2.next
print (p1.data)
def findMiddleElement(self):
p1 = self.head
p2 = self.head
while p2 != None and p2.next != None:
p1 = p1.next
p2 = p2.next.next
print ("Middle element :: ", p1.data)
def reverseLinkedList(self):
tmp = self.head
self.head = None
self.tail = None
while tmp != None:
self.append(tmp.data, 0)
tmp = tmp.next
def isListLoop(self):
tmp = self.head
for i in range(8):
tmp = tmp.next
self.tail.next = tmp
self.tail = tmp
print ("tail at :: ", self.tail.data)
p1 = self.head
p2 = p1.next
while (p1 != None and p2 != None and p2.next !=None and p1 != p2):
p1 = p1.next
p2 = p2.next.next
if (p1 == p2):
print ("points crossed at :: ", p1.data)
# To verify where the loop starts
# Find the loop in the list as above
# Get the node where the two pointers crossed
# Create 2 linked lists 1 from Head to Crossed node, another from next of Crossed node to crossed node
# So 2 lists having same tail and different heads and intersection at some point
# if both the lists are same int intersection point is same
# l1 > l2, then leave l1 - l2 nodes and start traversing both lists to meet intersection
# l2 > l1, then leave l2 - l1 nodes and start traversing both lists to meet intersection
h1 = self.head
t1 = p1
h2 = p1.next
t2 = p1
p1.next = None
c1 = 0
tr1 = h1
while tr1 != None:
c1 += 1
tr1 = tr1.next
c2 = 0
tr2 = h2
while tr2 != None:
c2 += 1
tr2 = tr2.next
if c1 > c2:
for i in range(c1-c2):
h1 = h1.next
else:
for i in range(c2-c1):
h2 = h2.next
while h1 != None and h1 != h2:
h1 = h1.next
h2 = h2.next
print ("Loop starts :: ", h1.data)
o = LinkedList([1,4,2,8,5,9,7,56])
#print (list(range(9-1)))
o.append(99, 0)
o.append(75, 0)
o.append(66, 0)
o.append(45, 0)
o.append(23, 0)
o.append(3, 0)
print (o, o.head.data, o.tail.data)
#o.remove(2)
#print (o, o.head.data, o.tail.data)
o.findNthElementFromLast(9)
o.findNthElementfromEnd(9)
o.findMiddleElement()
#o.reverseLinkedList()
#print (o, o.head.data, o.tail.data)
o.isListLoop()
| 3.71875 | 4 |
smollm
|
6fb8797f42744798083c7eb456f3c97a66a6e3e3
|
ramu-jan23/Competitive-Programming
|
/linkedlist.py
| 5,824 |
null | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Determine if rectangles overlap.
"""
import collections
Point = collections.namedtuple('Point', 'x y')
class Rectangle(object):
def __init__(self, min_x=None, max_x=None, min_y=None, max_y=None):
for coord in (min_x, max_x, min_y, max_y):
if coord is None:
raise ValueError("All coordinates must be provided")
if min_x >= max_x:
raise ValueError("min_x must be < max_x")
if min_y >= max_y:
raise ValueError("min_y must be < max_y")
self.min_x = min_x
self.max_x = max_x
self.min_y = min_y
self.max_y = max_y
def overlaps_rectangle(self, other):
# check x-axis
if other.max_x <= self.min_x or other.min_x >= self.max_x:
return False
# check y-axis
if other.max_y <= self.min_y or other.min_y >= self.max_y:
return False
return True
if __name__ == '__main__':
import unittest
class TestRectanglesOverlap(unittest.TestCase):
def setUp(self):
self.rect = Rectangle(min_x=5, max_x=15, min_y=5, max_y=10)
def test_overlap__top_left(self):
"""Verify that rectangle with top left corner overlapping is detected.
"""
other_rect = Rectangle(min_x=7, max_x=20, min_y=1, max_y=7)
self.assertTrue(self.rect.overlaps_rectangle(other_rect))
self.assertTrue(other_rect.overlaps_rectangle(self.rect))
def test_overlap__bottom_right(self):
"""Verify that rectangle with bottom right corner overlapping is detected.
"""
other_rect = Rectangle(min_x=1, max_x=10, min_y=1, max_y=20)
self.assertTrue(self.rect.overlaps_rectangle(other_rect))
self.assertTrue(other_rect.overlaps_rectangle(self.rect))
def test_overlap__to_the_left__false(self):
"""Verify that rectangle on the left is not detected as overlapping.
"""
other_rect = Rectangle(min_x=1, max_x=4, min_y=7, max_y=15)
self.assertFalse(self.rect.overlaps_rectangle(other_rect))
self.assertFalse(other_rect.overlaps_rectangle(self.rect))
def test_overlap__to_the_right__false(self):
"""Verify that rectangle on the right is not detected as overlapping.
"""
other_rect = Rectangle(min_x=20, max_x=24, min_y=7, max_y=15)
self.assertFalse(self.rect.overlaps_rectangle(other_rect))
self.assertFalse(other_rect.overlaps_rectangle(self.rect))
def test_overlap__above__false(self):
"""Verify that rectangle above is not detected as overlapping.
"""
other_rect = Rectangle(min_x=7, max_x=10, min_y=11, max_y=15)
self.assertFalse(self.rect.overlaps_rectangle(other_rect))
self.assertFalse(other_rect.overlaps_rectangle(self.rect))
def test_overlap__below__false(self):
"""Verify that rectangle below is not detected as overlapping.
"""
other_rect = Rectangle(min_x=7, max_x=10, min_y=1, max_y=4)
self.assertFalse(self.rect.overlaps_rectangle(other_rect))
self.assertFalse(other_rect.overlaps_rectangle(self.rect))
def test_overlap__contained(self):
"""Verify that interior rectangle is detected as overlapping.
"""
other_rect = Rectangle(min_x=7, max_x=12, min_y=7, max_y=9)
self.assertTrue(self.rect.overlaps_rectangle(other_rect))
self.assertTrue(other_rect.overlaps_rectangle(self.rect))
def test_overlap__containing(self):
"""Verify that framing rectangle is detected as overlapping.
"""
other_rect = Rectangle(min_x=1, max_x=16, min_y=1, max_y=12)
self.assertTrue(self.rect.overlaps_rectangle(other_rect))
self.assertTrue(other_rect.overlaps_rectangle(self.rect))
# run tests
unittest.main()
| 4.03125 | 4 |
smollm
|
769ad3f5fd085f96fdba74053b2182d4911590b0
|
jpowerwa/coding-examples
|
/overlapping_rectangles.py
| 4,049 |
null | null | null | null |
#Given an array of strings, group anagrams together.
#
#
#For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
#Return:
#
#[
# ["ate", "eat","tea"],
# ["nat","tan"],
# ["bat"]
#]
#
#Note: All inputs will be in lower-case.
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
dict = collections.defaultdict(list)
ret = []
for str in strs:
key = ''.join(sorted(str))
dict[key].append(str)
return dict.values()
# flag = False
# for key in dict.keys():
# if self.isAnagrams(key,i):
# dict[key].append(i)
# flag = True
# break
# if flag == False:
# dict[i] = [i]
# ret = []
# for i in dict.values():
# ret.append(i)
# return ret
# def isAnagrams(self,str1,str2):
# dict = {}
# for i in str1:
# if dict.has_key(i):
# dict[i] += 1
# else: dict[i] = 1
# for i in str2:
# if dict.has_key(i):
# dict[i] -= 1
# else: return False
# for i in dict:
# if dict[i] != 0:return False
# return True
# return sorted(str1) == sorted(str2)
| 3.828125 | 4 |
smollm
|
4947ec1842adb95ace0097ad356ca6831b294f72
|
zhongpei0820/LeetCode-Solution
|
/Python/1-99/049_Group_Anagrams.py
| 1,478 |
null | null | null | null |
#
#Find the contiguous subarray within an array (containing at least one number) which has the largest product.
#
#
#
#For example, given the array [2,3,-2,4],
#the contiguous subarray [2,3] has the largest product = 6.
#
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0 : return 0
currMax = nums[0]
currMin = nums[0]
preMax = nums[0]
preMin = nums[0]
ret = currMax
for i in range(1,len(nums)):
currMax = max(max(preMax * nums[i],preMin * nums[i]),nums[i])
currMin = min(min(preMax * nums[i],preMin * nums[i]),nums[i])
ret = max(ret,currMax)
preMax = currMax
preMin = currMin
return ret
| 3.859375 | 4 |
smollm
|
f2f6a4e8972c9d61a9e1938033e8314d6fb2e8dc
|
zhongpei0820/LeetCode-Solution
|
/Python/100-199/152_Maximum_Product_Subarray.py
| 849 |
null | null | null | null |
#
#Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.
#
#
#Examples 1
#Input:
#
# 5
# / \
#2 -3
#
#return [2, -3, 4], since all the values happen only once, return all of them in any order.
#
#
#Examples 2
#Input:
#
# 5
# / \
#2 -5
#
#return [2], since 2 happens twice, however -5 only occur once.
#
#
#Note:
#You may assume the sum of values in any subtree is in the range of 32-bit signed integer.
#
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None : return []
dict = collections.defaultdict(int)
self.treeSum(root,dict)
max_freq = max(dict.values())
return [candidate for candidate in dict if dict[candidate] == max_freq]
def treeSum(self,root,dict):
if root == None : return 0
curr_sum = self.treeSum(root.left,dict) + self.treeSum(root.right,dict) + root.val
dict[curr_sum] += 1
return curr_sum
| 4 | 4 |
smollm
|
0dd913e84f909c3164ed912177ee49d13bb9dad1
|
zhongpei0820/LeetCode-Solution
|
/Python/500-599/508_Most_Frequent_Subtree_Sum.py
| 1,516 |
null | null | null | null |
#
#Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
#
#
#You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
#
#
#
#Example 1:
#
#Input:
# Tree 1 Tree 2
# 1 2
# / \ / \
# 3 2 1 3
# / \ \
# 5 4 7
#Output:
#Merged tree:
# 3
# / \
# 4 5
# / \ \
# 5 4 7
#
#
#
#
#Note:
#The merging process must start from the root nodes of both trees.
#
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 == None and t2 == None: return None
t1_val = t1.val if t1 else 0
t2_val = t2.val if t2 else 0
t1_left = t1.left if t1 else None
t2_left = t2.left if t2 else None
t1_right = t1.right if t1 else None
t2_right = t2.right if t2 else None
root = TreeNode(t1_val + t2_val)
root.left = self.mergeTrees(t1_left, t2_left)
root.right = self.mergeTrees(t1_right, t2_right)
return root
| 4.40625 | 4 |
smollm
|
e525d56774a95c3c003bb205aee5ac687b644937
|
zhongpei0820/LeetCode-Solution
|
/Python/600-699/617_Merge_Two_Binary_Trees.py
| 1,810 |
null | null | null | null |
#Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
#
#
# For example, given array S = {-1 2 1 -4}, and target = 1.
#
# The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
#
import sys
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums = sorted(nums)
low,high = 0, len(nums) - 1
res = sys.maxint
min_diff = sys.maxint
for i in range(0,len(nums) - 2):
low,high = i + 1,len(nums) - 1
diff = sys.maxint
while(low < high):
s = nums[i] + nums[low] + nums[high]
# if abs(s - target) < abs(res - target):
# res = s
if s < target:
low += 1
elif s > target:
high -= 1
else:
return s
diff = abs(s - target)
if diff < min_diff:
min_diff = diff
res = s
return res
| 3.796875 | 4 |
smollm
|
f451f7b16b7d54fe3659c61652461770796d7781
|
zhongpei0820/LeetCode-Solution
|
/Python/1-99/016_3Sum_Closest.py
| 1,367 |
null | null | null | null |
#Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.
#
#Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
#
#Could you do this in O(n) runtime?
#
#Example:
#
#Input: [3, 10, 5, 25, 2, 8]
#
#Output: 28
#
#Explanation: The maximum result is 5 ^ 25 = 28.
#
#
class Solution(object):
def findMaximumXOR(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ret = mask = 0
for i in range(31,-1,-1):
mask = mask | 1 << i
hashset = set()
for num in nums:
hashset.add(num & mask)
candidate = ret | 1 << i
for ele in hashset:
if candidate ^ ele in hashset : ret = candidate
return ret
| 3.515625 | 4 |
smollm
|
2cc84859e76700d76f17259ac1dfb8e0cfdd747d
|
zhongpei0820/LeetCode-Solution
|
/Python/400-499/421_Maximum_XOR_of_Two_Numbers_in_an_Array.py
| 803 |
null | null | null | null |
#
#Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys.
#
#Rules for a valid pattern:
#
#Each pattern must connect at least m keys and at most n keys.
#All the keys must be distinct.
#If the line connecting two consecutive keys in the pattern passes through any other keys, the other keys must have previously selected in the pattern. No jumps through non selected key is allowed.
#The order of keys used matters.
#
#
#
#
#
#Explanation:
#
#| 1 | 2 | 3 |
#| 4 | 5 | 6 |
#| 7 | 8 | 9 |
#
#
#
#Invalid move: 4 - 1 - 3 - 6
#
#Line 1 - 3 passes through key 2 which had not been selected in the pattern.
#
#Invalid move: 4 - 1 - 9 - 2
#
#Line 1 - 9 passes through key 5 which had not been selected in the pattern.
#
#Valid move: 2 - 4 - 1 - 3 - 6
#
#Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern
#
#Valid move: 6 - 5 - 4 - 1 - 9 - 2
#
#Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern.
#
#Example:
#Given m = 1, n = 1, return 9.
#
#
#Credits:Special thanks to @elmirap for adding this problem and creating all test cases.
class Solution(object):
def numberOfPatterns(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
ret = 0
skip = [[0 for i in xrange(10)] for i in xrange(10)]
visit = [0 for i in xrange(10)]
skip[1][3] = skip[3][1] = 2
skip[1][7] = skip[7][1] = 4
skip[3][9] = skip[9][3] = 6
skip[1][9] = skip[9][1] = skip[3][7] = skip[7][3] = skip[2][8] = skip[8][2] = skip[4][6] = skip[6][4] = 5
skip[7][9] = skip[9][7] = 8
for i in range(m,n + 1):
ret += 4 * self.backTracking(visit,skip,1,i - 1)
ret += 4 * self.backTracking(visit,skip,2,i - 1)
ret += self.backTracking(visit,skip,5,i - 1)
return ret
def backTracking(self,visit,skip,curr,remain):
if remain == 0 : return 1
if remain < 0 : return 0
ret = 0
visit[curr] = 1
for i in range(1,10):
if (not visit[i]) and (skip[curr][i] == 0 or visit[skip[curr][i]]):
ret += self.backTracking(visit,skip,i,remain - 1)
visit[curr] = 0
return ret
| 3.6875 | 4 |
smollm
|
5dad91f25be1225d7a8acb4e0aa4361db0d0dcf1
|
zhongpei0820/LeetCode-Solution
|
/Python/300-399/351_Android_Unlock_Patterns.py
| 2,493 |
null | null | null | null |
#!/usr/bin/env python
import random
class Maths:
"""Static mathematical helper functions for RSA encryption"""
@staticmethod
def probably_prime(p):
"""Fermat's Primality Test"""
for i in range(0, 50):
a = random.randint(2, p-1)
if Maths.powermod(a, (p - 1), p) != 1:
return False
return True
@staticmethod
def powermod(a, p, m):
"""Right-to-left binary method for modular exponentiation"""
if p == 0: return 1
if (p & 1) == 1:
return (a * Maths.powermod((a * a) % m, p >> 1, m)) % m
else:
return 1 * Maths.powermod((a * a) % m, p >> 1, m)
@staticmethod
def is_coprime(a, b):
if b == 0: return a == 1
return Maths.is_coprime(b, a % b)
@staticmethod
def extended_gcd(a, b):
"""Find Greatest Common Divisor"""
x = 0
y = 1
lastx = 1
lasty = 0
while b != 0:
quotient = a / b
temp = b
b = a % b
a = temp
temp = x
x = lastx - quotient * x
lastx = temp
temp = y
y = lasty - quotient * y
lasty = temp
return lastx, lasty, a
@staticmethod
def next_prime(p):
"""Get the next prime number from the given odd number"""
if p < 4: return p
while True:
if Maths.probably_prime(p):
return p
else:
return Maths.next_prime(p + 2)
@staticmethod
def generate_prime(bitlength):
"""Generate a prime number of the given bitlength"""
p = 1
for x in range(0, bitlength):
p = p * 2 + random.randint(0, 1)
p = (p << 1) + 1
return Maths.next_prime(p)
| 3.859375 | 4 |
smollm
|
5692cda5ac34699078b3d1555d54d1d17e2fa701
|
reality/PyRSA
|
/maths.py
| 1,833 |
null | null | null | null |
def main():
users = []
activenames = []
x=0
infile = open("users.txt" ,"r")
for line in infile:
subLine = (line.rstrip()).split()
users.append(subLine)
while True:
username = input("Enter User Name: ")
password = input("Enter Password: ")
output = authentication(username,password,users,activenames)
print(output)
def authentication(username,password,users,activenames):
userPass = [username , password]
if userPass in users:
if username in activenames:
return "Already logged in."
activenames.append(username)
return "Success!"
else:
return "Username or password Invalid!"
main()
| 3.6875 | 4 |
smollm
|
67a21872db4a07f4a3f26ebeb96a0fc5233ee476
|
ntrallosgeorgios/python_Add_remove_org
|
/authentication.py
| 882 |
null | null | null | null |
from socket import * # import functions from socket module
def main():
clientSocket = clientConnection()
username = input("Enter User Name: ")
clientSocket.send(username.encode("utf-8")) # send the username in the server
password = input("Enter password: ")
clientSocket.send(username.encode("utf-8")) # send the username in the server
checkUser = clientSocket.recv(1024).decode("utf-8")
if checkUser == "True":
correct = "correct"
clientSocket.send(correct.encode("utf-8")
choice = ''
while choice != '5': # check if the choice is not 5 and continue to exec the while
menu() # call the function menu
choice = input('Enter relevent number:')
messageToSend = choice # take the choice from the user
print("Sending choice to server...")
clientSocket.send(messageToSend.encode("utf-8")) # send the choice to the server
if choice == '1':
displayRecieved = clientSocket.recv(1024).decode("utf-8")
print("message recieved from server")
messageToSend = input(displayRecieved)
clientSocket.send(messageToSend.encode("utf-8"))
messageRecieved = clientSocket.recv(1024).decode("utf-8")
print(messageRecieved)
elif choice == '2':
submenu()
subChoice = ''
subChoice = input("What stat you want? ")
clientSocket.send(subChoice.encode("utf-8"))
print(clientSocket.recv(1024).decode("utf-8"))
elif choice == '3':
addOrgNew = str(addOrgInput())
clientSocket.send(addOrgNew.encode("utf-8"))
print(addOrgNew + "\n Above record was successfully added!")
elif choice == '4':
removeOrg = input("Enter name of the Organization to remove: ")
clientSocket.send(removeOrg.encode("utf-8"))
print(clientSocket.recv(1024).decode("utf-8"))
else:
print("Invalid input!!!")
messageToSend = choice
print("Closing Connection!")
clientSocket.send(messageToSend.encode("utf-8"))
elif checkUser == "already":
print("Already logged in.")
else:
print("Not valid user!!!")
clientSocket.close() # close the connection
#print("connected to " + serverName + "at" + gethostname(serverName))
#messageToSend = input("Enter Message to send: ")
#print("Sending Message")
#clientSocket.send(messageToSend.encode("utf-8"))
#messageRecieved = clientSocket.recv(1024)
#print("Message came back from the server")
#print(messageRecieved.decode("utf-8"))
#if messageToSend == 'exit':
#print("Closing connection")
#print("Connection Closed")
# a function to create the connection with the server
def clientConnection():
serverName = gethostname()
serverPort = 5000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
return clientSocket
def menu():
print("1.Get server name and IP")
print("2.Get Ststistics")
print("3.Add new organization")
print("4.Remove organization")
print("5.Quit program.")
def submenu():
print("1.Max")
print("2.Min")
print("3.Median")
print("4.Mean")
def addOrgInput():
orgName = input("Enter Organization Name:")
orgDomain = input("Enter Organization Domain Name:")
orgIp = input("Enter Enter Ip Adress:")
orgTime = input("Enter connection time:")
orgInput = (orgName + '\t' + orgDomain +'\t'+ orgIp +'\t'+ orgTime)
return orgInput
main()
| 3.71875 | 4 |
smollm
|
312afa909bdf3a0947db1e5a2ee26bb624242fd6
|
ntrallosgeorgios/python_Add_remove_org
|
/test/ClientNew.py
| 3,995 |
null | null | null | null |
import pygame
from pygame.sprite import Sprite
import game_functions as gf
class Ship(Sprite):
'''a class to manage the contents and settings of the ship'''
def __init__(self, screen):
super().__init__()
#initialize ship attributes
self.idle = pygame.image.load('images/ship_idle.png')
self.up = pygame.image.load('images/sprite_10.png')
self.down = pygame.image.load('images/sprite_02.png')
self.screen = screen
self.screen_rect = self.screen.get_rect()
self.img = self.idle
self.rect = self.img.get_rect()
self.rect.left = self.screen_rect.left + 100
self.rect.centery = self.screen_rect.centery
# store a decimal value for the ship's center
self.center_x = float(self.rect.centerx)
self.center_y = float(self.rect.centery)
#set ship flags
self.moving_right = False
self.moving_left = False
self.moving_up = False
self.moving_down = False
#set ship speed
self.x_speed = 3
self.y_speed = 5
self.hp = 5
def update(self, settings):
if self.moving_right and self.rect.right < ((self.screen_rect.right /4)*3):
self.center_x += self.x_speed
if self.moving_left and self.rect.left > 0:
self.center_x -= self.x_speed
if self.moving_up and self.rect.top > 0:
self.center_y -= self.y_speed
if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
self.center_y += self.y_speed
self.rect.centerx = self.center_x
self.rect.centery = self.center_y
self.image_update()
gf.check_hp(self, settings)
def image_update(self):
if self.moving_up and self.moving_down:
self.img = self.idle
elif self.moving_up:
self.img = self.up
elif self.moving_down:
self.img = self.down
else:
self.img = self.idle
def blitme(self):
self.screen.blit(self.img, self.rect)
def damage(self, damage):
self.hp -= damage
print(str(self.hp))
| 3.5625 | 4 |
smollm
|
62b48cb89753a2e00553b2332496635358c69c09
|
Defcon88/type_x
|
/ship.py
| 1,850 |
null | null | null | null |
from itertools import cycle
#itertools Python标准库 专门用来创建迭代器的
import time
mylist = [1,2,3] #var中的数据 取决于 来源的有序对象
#mylist: 列表 线性的方向
var = cycle(mylist) #无法动态改变的
print(dir(var))
for v in var:
time.sleep(0.5)
print(v)
mystr = 'abcdefg' #C语言 常量指针 无法修改
#序列类型会帮你多创建一些空间
chr mystr[7] = "abcdefg"
#hash表
#红黑二叉树(链表) 遍历检索非常快 游戏 精灵
#双向链表
#门禁系统 队列 双向链表 在任意节点位置都可以 insert pop
#栈 先进后出 头部可以写入,头部可以弹出,屁股啥都不能看
#Python 模块 函数 学会调用就行了
| 3.984375 | 4 |
smollm
|
f77ea7de422425cfd6cf3f766082f56e528a987d
|
yht414802577/python
|
/写着玩玩/3.py
| 715 |
null | null | null | null |
#funcao para determinar as relacoes
def relaciona(c1, c2):
#declara o conjunto a ser retornado
conjunto = []
#declara a variavel de decisao
val = 0
#para todo i em c1(conjunto1)
for i in c1:
#para todo x em c2(conjunto2)
for x in c2:
#pergunta ao usuario se os elementos se relacionam
print(i," se relaciona com:",x,"?(0-Não, 1-Sim)")
val = int(input())
#se sim, adicione ao conjunto
if val == 1:
conjunto.append([i,x])
#retorne o conjunto
return conjunto
#lendo os conjuntos
print("Entre com os elementos do conjunto A separados por um espaco(ex: a b c 2)")
conjuntoA = input().split(" ")
print("Entre com os elementos do conjunto B separados por um espaco(ex: a b c 2)")
conjuntoB = input().split(" ")
print("Entre com os elementos do conjunto C separados por um espaco(ex: a b c 2)")
conjuntoC = input().split(" ")
#chama a funcao para determinar a relacao entra A e B
relAB = relaciona(conjuntoA,conjuntoB)
#chama a funcao para determinar a relacao entra B e C
relBC = relaciona(conjuntoB,conjuntoC)
#declarando a relacao entre A e C
relAC = []
#para todo z em AB
for z in relAB:
#para todo w em BC
for w in relBC:
#se o segundo termo de z for igual o primeiro termo de w (z = <a;b> w = <b;c> se b=b)
if z[1] == w[0]:
#adicione o primeiro termo de z e o segundo termo de w a relacao AC
#(z = <a;b> w = <b;c> relAC = <a;c>)
relAC.append([z[0],w[1]])
#para todo y em AC
for y in relAC:
#imprima o primeiro termo de y se relaciona com o segundo termo de y (y = <a;c>)
print(y[0]," se relaciona com:",y[1])
| 4 | 4 |
smollm
|
c6b0ba367d259de97876da3aa9e327381b733dbc
|
toledompm/Matematica-Discreta
|
/programas_1_prova/composicao.py
| 1,711 |
null | null | null | null |
#1. Can you sort a numerical list in Python?
lst = ["5", "8", "1", "2", "10"]
lst = [int(i) for i in lst]
lst.sort()
print(lst)
#Write a code to count the number of capital letters in the “drivers_table.csv” file.
with open('drivers_summary.csv') as countletter:
count = 0
text = countletter.read()
for character in text:
if character.isupper():
count += 1
print(count)
#Write a function that lists the files in a path with a specific file extension.
def path_files(path, file_extension):
import os
text_files = [f for f in os.listdir(path) if f.endswith(file_extension)]
return text_files
#Could you provide a code that executes the query you have created previously
#in question 6 of SQL and export the result to a CSV?
I don't know how to integrate a query in python and export a query into a CSV
#Can you write a code that executes a query in one database and insert the data
#in a different database?
I know there's the import sqlite to establish the connection to a sql database but i don't know how to do it. I could copy paste it but it wouldn't be real.
| 4.03125 | 4 |
smollm
|
031158014b8abca312fce0f26aefcff32c3002f8
|
jgrau90/paack_tech_task
|
/python_task.py
| 1,121 |
null | null | null | null |
def ChessboardTraveling(str):
# get base and height of rectangle
coords = str.strip('()').split(')(')
start = coords[0].split()
end = coords[1].split()
b = int(end[0]) - int(start[0]) + 1
h = int(end[1]) - int(start[1]) + 1
# create matrix of 0's
matrix = [[0 for x in range(b)] for y in range(h)]
# set all number of route options in first row to 1
matrix[0][:] = [1]*len(matrix[0])
# set first route options of every row to 1
for item in matrix:
item[0] = 1
# iterate over every row but first, start index at 1
for y, row in enumerate(matrix[1:], 1):
# iterate over every route options in the row except the first, start index at 1
for x, routes in enumerate(row[1:], 1):
# number of routes is the sum of routes below and to the left
row[x] = row[x - 1] + matrix[y - 1][x]
#return last item in last row of matrix
return matrix[-1][-1]
# keep this function call here
print ChessboardTraveling(raw_input())
| 3.671875 | 4 |
smollm
|
770bdd618f5b3cbd9604f598cf874361621cd8f6
|
BarryMolina/coderbyte
|
/traveling.py
| 1,048 |
null | null | null | null |
######################################################
#
# (C) Michael Kane 2017
#
# Student No: C14402048
# Course: DT211C
# Date: 03/010/2017
#
# Title: Caesar Cipher Decryption Alogorithm.
#
# References:
#
# Al Sweigart. (2013). Hacking The Caesar Cipher With The Brute-Force Technique. In: Hacking Secret Ciphers with Python.
# United States: Creative Commons BY-NC-SA. p88-95.
class CaesarCipher(object):
"""
The purpose of this class is to take Cipher text and key from a user and decrypt the text.
"""
def __init__(self, key=0, message=""):
self.key = key
self.message = message
def user_input(self):
"""
Take a cipher text and key from the user.
Strip the line endings off the cipher text so they dont interfere with the decription.
Call the Decrypt function.
:return:
"""
try:
filename = input("Please enter a filename, which contains your encrypted string.")
self.message = [line.rstrip('\n') for line in open(filename)]
self.message = list("".join(self.message))
self.key = int(input("Hello please enter a key."))
decrypted_string = self.decrypt(self.key, self.message)
print(decrypted_string)
except IOError:
print("file could not be found")
def decrypt(self, key, message):
"""
Code is taken from the above source with minor alterations.
:param key:
:param message:
:return:
"""
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
decrypted_string = ""
for char in message:
if char in letters:
num = letters.find(char)
num = num - key
if num < 0:
num += len(letters)
decrypted_string += letters[num]
else:
decrypted_string = decrypted_string + char
return str(decrypted_string)
if __name__ == '__main__':
CaesarCipher().user_input()
| 4.1875 | 4 |
smollm
|
21fbbacf97f2b41c5010154030e8d0e8c9f0563d
|
MichaelKane428/PracticingPythonAndGit
|
/Encryption-Decryption/CaesarCipher.py
| 2,049 |
null | null | null | null |
from ast import literal_eval
class Produto:
"""
Classe para manipular dados dos produtos cadastrados.
Permite cadastrar, listar, alterar, pesquisar por categoria e excluir produtos.
"""
caminho_banco = "../BancoDados/produtos.txt"
def __init__(self):
"""
Método para criar o arquivo de banco dos produtos caso ainda não exista.
"""
with open(self.caminho_banco, "a") as file:
pass
def cadastrar_produto(self, produto: dict) -> bool:
"""
Método para cadastrar um novo produto.
Caso o produto não esteja cadastrado, um novo produto será registrado no arquivo e retornará True.
Caso o produto já esteja cadastrado, retornará False.
:param produto: dict
:return bool
"""
if self.verificar_produto(produto["codigo"]):
return False
else:
with open(self.caminho_banco, "a") as file:
file.write(f"{produto}\n")
return True
def listar_produtos(self) -> list:
"""
Método para listar os produtos cadastrados.
Verifica o arquivo e retorna uma lista de produtos no formato de dicionário.
Caso ocorra erro na leitura do arquivo ou nenhum produto esteja cadastrado, retorna uma lista vazia.
:return list
"""
produtos = list()
try:
with open(self.caminho_banco, "r") as file:
for p in list([i.strip() for i in file.readlines()]):
produto = literal_eval(p)
produtos.append(produto)
return produtos
except:
pass
finally:
return produtos
def pesquisar_produtos(self, nome_categoria: str) -> list:
"""
Método para pesquisar os produtos cadastrados por categoria.
Verifica o arquivo e retorna uma lista de produtos no formato de dicionário que possuírem a categoria pesquisada.
Caso ocorra erro na leitura do arquivo ou nenhum produto for encontrado, retorna uma lista vazia.
:param nome_categoria: str
:return list
"""
produtos = list()
try:
with open(self.caminho_banco, "r") as file:
for p in list([i.strip() for i in file.readlines()]):
produto = literal_eval(p)
if produto["categoria"] == nome_categoria:
produtos.append(produto)
return produtos
except:
pass
finally:
return produtos
def alterar_produto(self, produto_alterado: dict) -> bool:
"""
Método para alterar os dados de um produto cadastrado.
Caso for encontrado um produto que possua o código pesquisado, este terá seus dados atualizados e reescrito no arquivo.
Demais dados serão reescritos sem alteração e será retornado True.
Caso nenhum produto possua o código pesquisado, retornará False.
:param produto_alterado: dict
:return bool
"""
if self.verificar_produto(produto_alterado["codigo"]):
with open(self.caminho_banco, "r+") as file:
produtos = list()
for p in list([i.strip() for i in file.readlines()]):
produto = literal_eval(p)
if produto_alterado["codigo"] == produto["codigo"]:
produto["nome"] = produto_alterado["nome"]
produto["preco"] = produto_alterado["preco"]
produto["categoria"] = produto_alterado["categoria"]
produtos.append(produto)
file.seek(0)
for p in produtos:
file.write(f"{p}\n")
file.truncate()
return True
else:
return False
def excluir_produto(self, codigo_produto: str) -> bool:
"""
Método para excluir um produto cadastrado.
Caso for encontrado um produto que possua o código pesquisado, este será excluído do arquivo e retornará True.
Caso nenhum produto possua o código pesquisado, retornará False.
As vendas que possuírem o produto excluído não serão alteradas.
:param codigo_produto: str
:return bool
"""
if self.verificar_produto(codigo_produto):
with open(self.caminho_banco, "r+") as file:
produtos = list()
for p in list([i.strip() for i in file.readlines()]):
produto = literal_eval(p)
if codigo_produto != produto["codigo"]:
produtos.append(produto)
file.seek(0)
for p in produtos:
file.write(f"{p}\n")
file.truncate()
return True
else:
return False
def verificar_produto(self, codigo_produto: str) -> bool:
"""
Método para verificar se o código do produto já está cadastrado.
Caso o código for encontrado no arquivo de dados, retorna True.
Caso não for encontrado, retorna False.
:param codigo_produto: str
:return bool
"""
produtos = self.listar_produtos()
if produtos:
for p in produtos:
if p["codigo"] == codigo_produto:
return True
else:
return False
| 3.65625 | 4 |
smollm
|
6f1bca72a9542d10a1068b1d74b7e969aeac21c6
|
GuilhermePeyflo/loja-python
|
/Sistema/Produto.py
| 5,492 |
null | null | null | null |
import csv
class GetData:
def __init__(self, file_name):
self.__data = []
self.__file_name = "./data/" + file_name
def readData(self):
f = open(self.__file_name, "r")
csv_reader = csv.reader(f)
next(csv_reader)
for line in csv_reader:
self.__data.append(line)
return self.__data
| 3.515625 | 4 |
smollm
|
626edf32edf126e1fe2a85cf1d9393aded093a18
|
birna17/Lokaverkefni_Bilaleiga
|
/repo/GetData.py
| 361 |
null | null | null | null |
import os
import glob
count=0
location = input("Please Enter Location: ")
file_type=input("Please Enter Type of file")
try:
if(os.path.exists(location)):
for loc,var,file in os.walk(location):
right_type = "*" + file_type
count = count + len(glob.glob1(loc,right_type))
print("Number of items " ,count)
else:
print("The given path doesn't Exist")
except OSError as e:
print(e)
| 3.859375 | 4 |
smollm
|
b07f6ebd6383be946bd480636019c2e7bda04a03
|
skyborn-git/Python-Random-projects
|
/County.py
| 448 |
null | null | null | null |
# dict 예제
def define_dict():
"""
사전의 정의
"""
# 기본적인 사전의 생성
dct = dict() # 빈사전
print(dct, type(dct))
# literal 이용한 생성 {}
dct = {"backetball":5, "baseball":9}
# 키에 접근
print(dct["baseball"]) # baseball 키에 연결된 값을 참조
# print(dct["soccer"]) -> KEY ERROR, 없는 키값에 접근
# 새 값을 넣을 경우 새로운 키값 설정
dct["soccer"] = 11
print("dct:", dct)
# dict의 경우 순서가 없기 때문에 len, 포함여부만 확인 가능 -> 대상은 key 값
print(dct, "length:", len(dct))
print("soccer in dct?", "soccer" in dct)
print("volleyball in dct?", "volleyball" not in dct)
# dict은 복합자료형으로서 키의 목록과 값의 목록을 별도로 뽑아낼수 있음
print("KEYS of dct:", dct.keys()) # keys() 매서드 사용
print("TYPE of dct:", type(dct.keys()))
print("VALUES of dct:", dct.values()) # values() 메서드 사용
print("TYPES of dct:", type(dct.values()))
# 값의 포함 여부를 판단하려면 .values() 메서드로 dict_values 추출 후 확인 가능
# dct안에 9가 포함되어 있는가?
print("9 in dct.values()?", 9 in dct.values())
# 사전을 생성하는 다른 방법들
# 키워드 인자를 이용한 사전의 생성
d1 = dict(key1="value1", key2="value2", key3="value3")
print("d1:", d1, type(d1))
# 튜플의 리스트로 사전의 생성
d2 = dict([("key1", 1), ("key2", 2), ("key3", 3)])
print("d2:", d2, type(d2))
# 키의 목록과 값의 목록이 이미 존재하는 경우 -> zip 객체로 묶어서 dict에 전달
keys = ("one", "two", "three", "four")
values = (1, 2, 3, 4)
d3 = dict(zip(keys, values))
print("d3:", d3, type(d3))
# 사전의 키는 immutable 자료형이여야 한다
# bool, 수치형, 문자열, 튜플 등 불변 자료형 가능
d4 = {}
d4[True] = "true"
d4[10] = 10
d4["eleven"] = 11
d4[("홍길동", 23)] = "홍길동 23"
# d4[["홍길동", 23]] = "홍길동 23" -> ERROR
print("d4:", d4, type(d4))
def dict_methods():
"""
사전의 메서드
"""
dct = {"soccer": 11, "baseball": 9, "volleyball": 6}
print("dct:", dct)
# key의 목록 추출 : keys 메서드
keys = dct.keys()
print("keys of dct:", keys, type(keys))
# dict_keys 는 순차자료형으로 변환할 수 있다
keys_list = list(keys)
print(keys_list)
# value의 목록 추출 : values 메서드
values = dct.values()
print("values of dct:", values, type(values))
# 키-값 쌍튜플의 목록 추출
pairs = dct.items()
print("key-value pair of dct:", pairs)
# 비우기
dct.clear()
print("dct:", dct)
def using_dict():
"""
사전 사용 연습
"""
phones = {
"홍길동": "010-1234-5678",
"장길산": "010-2345-6789",
"임꺽정": "010-3456-7890"
}
print(phones)
# 새로운 키의 추가
phones['일지매'] = "010-4567-8901"
print(phones)
# 키의 직접접근 vs get메서드
if "고길동" in phones:
print(phones['고길동']) # 키값의 직접접근은 키가 없는경우 에러발생
else:
print(phones.get('고길동')) # get메서드는 키값이 없는 경우 None 리턴
# 없는 키값을 검색할 때 기본값을 리턴하고자 하는 경우 get메서드의 두번째 인자로 기본값을 부여할 수 있다
print(phones.get("고길동", "미등록"))
# 삭제 : del
if "일지매" in phones:
del phones['일지매']
print(phones)
# pop메서드 : 값을 가져오고 해당 객체를 삭제
print(phones.pop('장길산'))
print(phones)
# popitem 메서드 : 키-밸류 쌍튜플을 반환하고 키를 삭제
item = phones.popitem() # 가장마지막객체 반환
print("Name:", item[0], item[1]) # 0번인덱스에는 키값, 1번인덱스에는 전화번호
def loop():
"""
사전 객체의 조회
"""
phones = {
"홍길동": "010-1234-5678",
"장길산": "010-2345-6789",
"임꺽정": "010-3456-7890"
}
print(phones)
# 기본적인 loop : keys() 목록을 대상으로 한다
for key in phones:
print(key, ":", phones[key])
print()
# 키와 값을 함께 loop : items 메서드는 키-값 쌍튜플의 목록
for key, value in phones.items():
print(key, ":", value)
if __name__ == "__main__":
#define_dict()
#dict_methods()
#using_dict()
loop()
| 3.515625 | 4 |
smollm
|
8118d49bc09eb58c4b80b47a1b2a396e73e0a749
|
min-yeong/Python-Basic
|
/basic_dict.py
| 4,628 |
null | null | null | null |
def order_digits(number):
number = str(number)
ordered_digits = []
for digit in number:
ordered_digits.append(digit)
ordered_digits.sort()
return ordered_digits
def check_multiples(number):
for i in range(2, 7):
if order_digits(number) != order_digits(i * number):
return 0
return 1
def main():
current_number = 1
while True:
if check_multiples(current_number) == 1:
print(current_number)
break
else:
current_number += 1
if __name__ == "__main__":
main()
| 4 | 4 |
smollm
|
f9470aa701c5fbf9a29e76077d0338acb08912d5
|
wieczszy/Project-Euler
|
/problem052.py
| 581 |
null | null | null | null |
for x in range(1, 1000):
for y in range(1, 1000):
for z in range(1, 1000):
if x*x + y*y == z*z and x + y + z == 1000:
print(x * y * z)
break
| 3.53125 | 4 |
smollm
|
14f09a8235931d65fe0101796b2d3b5221e52781
|
wieczszy/Project-Euler
|
/problem009.py
| 205 |
null | null | null | null |
from math import sqrt
def factors(number):
counter = 0
s_root = int(sqrt(number))
for i in range(1, s_root):
if number % i == 0:
counter += 2
if (s_root*s_root == number):
counter -= 1
return counter
number = 1
to_add = 2
while(factors(number) < 500):
number += to_add
to_add += 1
print(number)
| 3.609375 | 4 |
smollm
|
c1f94701c868f067d54746ab8aa99fd5a85772db
|
wieczszy/Project-Euler
|
/problem012.py
| 356 |
null | null | null | null |
import math
def is_pentagonal(x):
n = (math.sqrt(24 * x + 1) + 1) / 6
return n == int(n)
i = 144
while True:
result = i * (2 * i - 1)
if is_pentagonal(result):
print(i, result)
break
else:
i += 1
| 3.71875 | 4 |
smollm
|
508f3a150c324ecf7d91dac89783c9fba22541cf
|
wieczszy/Project-Euler
|
/problem045.py
| 244 |
null | null | null | null |
# Things you should be able to do.
number_list = [-5, 6, 4, 8, 15, 16, 23, 42, 2, 7]
word_list = [ "What", "about", "the", "Spam", "sausage", "spam", "spam", "bacon", "spam", "tomato", "and", "spam"]
# Write a function that takes a list of numbers and returns a new list with only the odd numbers.
def all_odd(number_list):
new_list = []
for num in number_list:
if num % 2 != 0:
new_list.append(num)
return new_list
#print all_odd(number_list)
# Write a function that takes a list of numbers and returns a new list with only the even numbers.
def all_even(number_list):
new_list = []
for num in number_list:
if num % 2 == 0:
new_list.append(num)
return new_list
#print all_even(number_list)
# Write a function that takes a list of strings and returns a new list with all strings of length 4 or greater.
def long_words(word_list):
new_list = []
for word in word_list:
if len(word) >= 4:
new_list.append(word)
return new_list
#print long_words(word_list)
# Write a function that finds the smallest element in a list of integers and returns it.
def smallest(number_list):
min_ = number_list[0]
for num in number_list:
if num < min_:
min_ = num
return min_
#print smallest(number_list)
# Write a function that finds the largest element in a list of integers and returns it.
def largest(number_list):
max_ = number_list[0]
for num in number_list:
if num > max_:
max_ = num
return max_
#print largest(number_list)
# Write a function that takes a list of numbers and returns a new list of all those numbers divided by two.
def halvesies(number_list):
new_list = []
for num in number_list:
half_num = num / 2.0
new_list.append(half_num)
return new_list
#print halvesies(number_list)
# Write a function that takes a list of words and returns a list of all the lengths of those words.
def word_lengths(word_list):
new_list = []
for word in word_list:
wrdlength = len(word)
new_list.append(wrdlength)
return new_list
#print word_lengths(word_list)
# Write a function (using iteration) that sums all the numbers in a list.
def sum_numbers(number_list):
total = 0
for num in number_list:
total += num
return total
#print sum_numbers(number_list)
# Write a function that multiplies all the numbers in a list together.
def mult_numbers(number_list):
product = 1
for num in number_list:
product *= num
return product
#print mult_numbers(number_list)
# Write a function that joins all the strings in a list together (without using the join method) and returns a single string.
def join_strings(word_list):
new_string = ''
for word in word_list:
new_string += word
return new_string
#print join_strings(word_list)
# Write a function that takes a list of integers and returns the average (without using the avg method)
def average(number_list):
total = 0
for num in number_list:
total += num
avg_ = total / float((len(number_list)))
return avg_
print average(number_list)
#This works as well:
#return sum_numbers(number_list) / float(len(number_list))
| 4.09375 | 4 |
smollm
|
0e32236efb0734572089250e54b1c5b0dbebe805
|
jabrad0/Skills_Test
|
/Skill1_1.py
| 3,277 |
null | null | null | null |
userletter = str(input("Choose a letter in the English alphabet: "))
if userletter == ("a") or userletter == ("e") or userletter == ("i") or userletter == ("o") or userletter == ("u") :
print("Your letter is a vowel.")
else:
print("Your letter is a consonant.")
| 4.1875 | 4 |
smollm
|
09a09f3b0339ee6c9b87d051ec912aa06e7b421d
|
MOGAAAAAAAAAA/magajiabraham
|
/Vowel or consonant.py
| 269 |
null | null | null | null |
num = int(input("Pick a number: "))
check = int(input("Pick a number to divide it by: "))
if num %check == 0:
print("Your number is divisible by", check)
else:
print("Your number is not divisible by", check)
| 4.3125 | 4 |
smollm
|
2b2561fd1bf8f3bd957e7395f4c560b183706388
|
MOGAAAAAAAAAA/magajiabraham
|
/Division2.py
| 216 |
null | null | null | null |
def two_sum(nums, target):
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return[i, j]
# two_sum함수에 숫자 리스트와 '특정 수'를 인자로 넘기면, 더해서 '특정 수'가 나오는 index를 배열에 담아 return해 주세요.
# nums은 [4, 9, 11, 14]
# target은 13
# nums[0] + nums[1] = 4 + 9 = 13 이죠?
# 그러면 [0, 1]이 return 되어야 합니다.
| 3.59375 | 4 |
smollm
|
4c02f8c3b5e4d77e36905413471c6e8c482f0a15
|
cheesepuff90/code-kata
|
/day1.py
| 458 |
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 22