blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
8eddcd6f8233db0f57f508f7dc69dc7acc870aea | yubaoliu/PythonFromScratch | /basics/directory.py | 1,518 | 3.890625 | 4 | import os
import tempfile
# define the access rights
access_rights = 0o755
print("===========================")
print("Creating a Directory ")
# define the name of the directory to be created
path = "/tmp/year"
print("Create directory: %s" % path)
try:
os.mkdir(path, access_rights)
except OSError as error:
print(error)
print("Creation of the directory %s failed" % path)
else:
print("Successfully created the directory %s" % path)
print("===========================")
print("Creating a Directory with Subdirectories")
path = "/tmp/year/month/week/day"
print("Create directory (mkdir -p): %s" % path)
try:
os.makedirs(path, access_rights)
except OSError as error:
print(error)
print("Creation of the directory %s failed" % path)
else:
print("Successfully created the directory %s" % path)
# print("===========================")
# print("create a temporary directory")
# with tempfile.TemporaryFile() as directory:
# print('The created temporary directory is %s' % directory)
print("===========================")
path = "/tmp/year"
print("Delete directory: %s" % path)
try:
if os.path.exists(path):
os.rmdir(path)
except OSError as error:
print(error)
print("Deletion of the directory %s failed" % path)
else:
print("Successfully deleted the directory %s" % path)
print("===========================")
path = "/tmp/year"
print("Simple method: %s" % path)
print("Delete directory: %s" % path)
if os.path.exists(path):
os.system("rm -r /tmp/year")
|
753239b3b82d38acc5ef487a3c2b29a0344a7584 | SarcoImp682/Zookeeper | /Topics/Program with numbers/Difference of times/main.py | 391 | 3.953125 | 4 | # put your python code here
# start time
hour_start = int(input())
minutes_start = int(input())
seconds_start = int(input())
# stop time
hour_stop = int(input())
minutes_stop = int(input())
seconds_stop = int(input())
# conversion
start = hour_start * 3600 + minutes_start * 60 + seconds_start
stop = hour_stop * 3600 + minutes_stop * 60 + seconds_stop
# result
print(abs(start - stop))
|
9ad802d0eac6567184e459e7ce6f4e82bf8110c0 | agupta7/COMP6700 | /softwareprocess/test/AngleTest.py | 4,471 | 3.875 | 4 | import unittest
import softwareprocess.Angle as A
class AngleTest(unittest.TestCase):
def setUp(self):
self.strDegreesFormatError = "String should in format XdY.Y where X is degrees and Y.Y is floating point minutes"
# ---------
# ----Acceptance tests
# ----100 Constructor
# ----Boundary value confidence
# ----input : string containing the degrees and minutes in the form XdY.Y for X is degrees Y.Y is minutes
# ----output : an instance of Angle
# ----Happy path analysis:
# degreeMinutesStr -> nominal value = 50d30.9
# degreeMinutesStr -> low value = -10d0.0
# degreeMinutesStr -> high value = 999d59.9
# ---Sad path analysis
# degreeMinutesStr -> None / not specified
# degreeMinutesStr -> '' empty string
# degreeMinutesStr -> '0d60.0' minutes is too high
# degreeMinutesStr -> '0d-0.1' minutes is too low
# degreeMintuesStr -> '0.5d10.0' degrees is non integer
# degreeMinutesStr -> '1ad10.0' wrong format
# degreeMintuesStr -> '12d1' minutes must have decimal
# degreeMinutesStr -> '12d12.0m' minutes in the wrong format
def test100_010_ShouldConstructAngle(self):
angle = A.Angle('50d30.9')
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '50d30.9')
self.assertAlmostEquals(angle.getDegreesFloat(), 50.515, 3)
def test100_020_ShouldConstructAngleLow(self):
angle = A.Angle('-10d0.0')
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '-10d0.0')
self.assertAlmostEquals(angle.getDegreesFloat(), -10, 3)
def test100_030_ShouldConstructAngleHigh(self):
angle = A.Angle('999d59.9')
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '999d59.9')
self.assertAlmostEquals(angle.getDegreesFloat(), 999.99833, 3)
def test100_040_ShouldConstructAngleInteger(self):
angle = A.Angle(12.5)
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '12d30.0')
self.assertEquals(angle.getDegreesFloat(), 12.5)
def test100_050_ShouldConstructAngleNegative(self):
angle = A.Angle('-0d03.0')
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '-0d3.0')
self.assertAlmostEquals(angle.getDegreesFloat(), -(3.0/60), 3)
def test100_060_ShouldCOnstructAngleOverflow(self):
angle = A.Angle(13.999999999)
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '14d0.0')
self.assertAlmostEquals(angle.getDegreesFloat(), 13.999999999, 3)
def test900_010_ShouldErrorNoneAngle(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle(None)
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_030_ExceptionBlankAngle(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_040_ExceptionMinutesHigh(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('0d60.0')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_050_ExceptionMinutesLow(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('0d-0.1')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_060_ExceptionNonIntegerDegree(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('0.5d10.0')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_070_ExceptionDegreeInvalidFormat(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('1ad10.0')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_080_ExceptionMinutesInvalidFormat(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('12d1')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_090_ExceptionMinutesWrongFormat(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('12d12.0m')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError) |
6093dccc4f5ed895fb8f69572589deb55c086102 | talivaro/Generadores-aleatorios | /CongruCombinado.py | 417 | 3.8125 | 4 | __author__ = 'Talivaro'
xo1=int(input("Ingrese el valor de xo1: "))
xo2=int(input("Ingrese el valor de xo2: "))
xo3=int(input("Ingrese el valor de xo3: "))
repe=int(input("Numero de valores: "))
for i in range(repe):
xn1=float((171*xo1)%30269)
xn2=float((172*xo2)%30307)
xn3=float((173*xo3)%30323)
ui=float(((xn1/30269)+(xn2/30307)+(xn3/30323))%1)
print(ui)
xo1=xn1;
xo2=xn2;
xo3=xn3;
|
a6b2127082c3e3eccf8098d8e370d701c5a876db | BlackMetall/trash | /lesson 9 (practice1).py | 959 | 4.1875 | 4 | #Задача 1. Курьер
#Вам известен номер квартиры, этажность дома и количество квартир на этаже.
#Задача: написать функцию, которая по заданным параметрам напишет вам,
#в какой подъезд и на какой этаж подняться, чтобы найти искомую квартиру.
room = int(input('Введите номер квартиры ')) # кол-во квартир
floor = int(5) # кол-во этажей
roomfloor = int(3) # кол-во квартир на этаже
c = floor * roomfloor # кол-во квартир в подъезде
x = room // c
y = (x + 1) # узнаём в каком подъезде квартира
z = room % c
d = z // roomfloor
s = (d + 1) # узнаём на каком этаже
print(str(y) + ' Подъезд')
print(str(s) + ' Этаж') |
a40410c97ef48d989ce91b6d23262720f60138dc | rajeshberwal/dsalib | /dsalib/Stack/Stack.py | 1,232 | 4.25 | 4 | class Stack:
def __init__(self):
self._top = -1
self.stack = []
def __len__(self):
return self._top + 1
def is_empty(self):
"""Returns True is stack is empty otherwise returns False
Returns:
bool: True if stack is empty otherwise returns False
"""
return self._top == -1
def push(self, data):
"""Add data at the end of the stack.
Args:
data (Any): element that we want to add
"""
self.stack.append(data)
self._top += 1
def pop(self):
"""Remove the last element from stack and returns it's value.
Raises:
IndexError: If stack is empty raise an Index error
Returns:
Any: element that we have removed from stack"""
if self.is_empty():
raise IndexError("stack is empty")
self._top += 1
return self.stack.pop()
def peek(self):
"""returns the current top element of the stack."""
if self.is_empty():
raise IndexError("stack is empty")
return self.stack[self._top]
def __str__(self):
return ''.join([str(elem) for elem in self.arr])
|
04d70de92bfca1f7b293f344884ec1e23489b7e4 | rajeshberwal/dsalib | /dsalib/Sorting/insertion_sort.py | 547 | 4.375 | 4 | def insertion_sort(array: list) -> None:
"""Sort given list using Merge Sort Technique.
Time Complexity:
Best Case: O(n),
Average Case: O(n ^ 2)
Worst Case: O(n ^ 2)
Args:
array (list): list of elements
"""
for i in range(1, len(array)):
current_num = array[i]
for j in range(i - 1, -1, -1):
if array[j] > current_num:
array[j], array[j + 1] = array[j + 1], array[j]
else:
array[j + 1] = current_num
break |
a0f2d86b20acd3f19756667801f081902827b8d7 | Manoj-sahu/datastructre | /Stack/StackUsingList.py | 414 | 3.875 | 4 | class StackUsingList():
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def peek(self):
return self.stack[-1]
def pop(self):
self.stack.pop()
if __name__ == '__main__':
stack = StackUsingList()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek())
stack.pop()
print(stack.peek()) |
8c7ab2d2161d94f612f7102e05c04c8e4e888a71 | Manoj-sahu/datastructre | /LinkedList/1.1.py | 1,083 | 3.53125 | 4 | """for finding duplicate first approach iterate to loop and maintain count in dictionary
and if you find then remove the refrence of that loop. brute force approcah could be take head item and keep checking for all the items"""
#import IP.LinkedList.10
#from IP.LinkedList.L import LinkedList
import L
newLinkedList = L.LinkedList()
newLinkedList.insertAtStart(1)
newLinkedList.insertAtEnd(2)
newLinkedList.insertAtEnd(2)
def removeDup(n):
dupList = []
previous = None
while(n is not None):
if n.data in dupList:
previous.next = n.next
else:
dupList.append(n.data)
previous = n
n = n.next
def removeDupWT(n):
current = n
while current is not None:
runner = current
while( runner.next is not None):
if runner.next.data == current.data:
runner.next = runner.next.next
else:
runner = runner.next
current = current.next
#removeDup(newLinkedList.head)
removeDupWT(newLinkedList.head)
newLinkedList.traverseList()
|
7d1221ec5c9cdbb8435ecaf0be51a6daa11ae3d2 | nishthagoel712/DSA | /Graph/TopologicalSorting.py | 575 | 3.828125 | 4 | from collections import defaultdict
visited=defaultdict(bool)
stack=[]
def topological_sort_util(adj,vertex):
visited[vertex]=True
for node in adj[vertex]:
if not visited[node]:
topological_sort_util(adj,node)
stack.append(vertex)
def topological_sort(adj):
for vertex in adj:
if not visited[vertex]:
topological_sort_util(adj,vertex)
return stack[::-1]
adj=defaultdict(list)
m=int(input())
for _ in range(m):
a,b=input().split()
adj[a].append(b)
print(*topological_sort(adj)) |
3009a3a33a23b282111c2fc0fba9cf050e0fe599 | nishthagoel712/DSA | /Dynamic Programming/Maximum size reactangle of all 1's.py | 1,543 | 3.59375 | 4 | # arr represent given 2D matrix of 0's and 1's
# n is the number of rows in a matrix
# m is the number of columns in each row of a matrix
def rectangle(arr, n, m):
maxi = float("-inf")
temp = [0] * m
for i in range(n):
for j in range(m):
if arr[i][j] == 0:
temp[j] = 0
else:
temp[j] += arr[i][j]
w = histogram(temp)
if w > maxi:
maxi = w
return maxi
def histogram(a):
s = []
maxarea = float("-inf")
for j in range(len(a)):
if len(s) < 1:
s.append(j)
elif a[j] >= a[s[-1]]:
s.append(j)
else:
while len(s) > 0 and a[s[-1]] > a[j]:
b = s.pop()
if len(s) < 1:
area = a[b] * j
if area > maxarea:
maxarea = area
else:
area = a[b] * (j - s[-1] - 1)
if area > maxarea:
maxarea = area
s.append(j)
j = j + 1
while len(s) > 0:
b = s.pop()
if len(s) < 1:
area = a[b] * j
if area > maxarea:
maxarea = area
else:
area = a[b] * (j - s[-1] - 1)
if area > maxarea:
maxarea = area
return maxarea
n = 4
m = 6
arr = [[1, 0, 0, 1, 1, 1], [1, 0, 1, 1, 0, 1], [0, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1]]
print(rectangle(arr, n, m)) |
fc89a46754b7a31c7335517bc4b639aa5eab6e12 | darksinge/rmb-search-engine | /bill_files/clean_empty_bills.py | 471 | 3.6875 | 4 | import glob, os
"""
Simple script to detect and remove files that have no information on them in this folder
"""
"""
files = glob.glob('*.txt')
for file in files:
f = open(file, 'r')
contents = f.read()
should_delete = False
if 'The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.' in\
contents:
should_delete = True
f.close()
if should_delete:
os.remove(file)
"""
|
93a955fcd9477724d916877075fac5b29227857a | darksinge/rmb-search-engine | /create_sparse_matrix.py | 3,142 | 3.703125 | 4 | """
Creates a sparse inverse dictionary for tf-idf searches. The CSV file produced by bill_data_analysis.py is so large
that this file is needed to produce something much smaller to be used for the searches
"""
import pandas as pd
import os
import json
import pickle
import sys
from default_path import default_path
def make_matrix(matrix_file=None):
"""
Takes an already saved dense matrix (csv format) and creates a dictionary with each word as a key and a dictionary
of docs and tf_idf values as the value.
Parameters:
matrix_file: a path string for a csv dense matrix file. The first column must include the name of the documents
and the rest be for terms, otherwise an error will be thrown.
Returns:
dictionary: A sparse matrix dictionary for each term in the dense matrix.
"""
if matrix_file:
dense_matrix = pd.read_csv(matrix_file)
else:
dense_matrix = pd.read_csv(os.path.join(default_path, "analysis", "dense_matrix.csv"))
terms = dense_matrix.columns
dense_matrix = dense_matrix.rename(columns = {terms[0]: "doc"})
sparse_matrix = {}
for term in terms[1:]:
doc_matches = dense_matrix[dense_matrix[term] > 0]
just_docs_and_values = doc_matches[["doc", term]]
just_docs_and_values.set_index("doc", inplace=True)
just_docs_and_values.reset_index()
transposed = just_docs_and_values.transpose()
doc_dictionary = transposed.to_dict("list")
if len(doc_dictionary) > 0:
sparse_matrix[term] = doc_dictionary
return sparse_matrix
def make_matrix_json(matrix_file=None):
"""
Takes the file name of a csv for the dense matrix, and creates and saves a json with a sparse matrix.
Parameters:
matrix_file: a path string for a csv dense matrix file. The first column must include the name of the documents
and the rest be for terms, otherwise an error will be thrown.
Returns:
None
"""
full_matrix = make_matrix(matrix_file)
# TODO: still save a pre-built matrix, load that up, rebuild the new data
matrix_json = json.dumps(full_matrix)
file = open(os.path.join(default_path, "analysis", "sparse.json"), 'w')
file.write(matrix_json)
file.close()
def reverse_matrix(matrix):
from collections import OrderedDict
"""
Takes a sparse matrix, reverses the inner dictionary into OrderedDictionary objects
:param matrix:
:return:
"""
new_matrix = {}
for term, outer_dict in matrix.items():
sorted_inner = OrderedDict(sorted(outer_dict.items(), key=lambda t: t[1]), reverse=True)
new_matrix[term] = sorted_inner
return new_matrix
def make_pickle(matrix_file=None):
"""
Reads the dense_matrix.csv file (or a file given as an argument) and creates a matrix
Returns:
None
"""
matrix = make_matrix(matrix_file)
pickle.dump(matrix, open(os.path.join(default_path, "analysis", "sparse_p.pickle"), 'wb'))
if __name__ == '__main__':
#make_matrix_json()
make_pickle()
#data = reverse_matrix(data)
#make_pickle(data)
|
22e56d8ab2a43434aac7d3c8c5aa589a3af5b2c5 | kori07/prak_asd_b | /UAS_044_047_053/aplikasi.py | 20,086 | 3.828125 | 4 | #Program by Kelompok Susi Triana Wati,Program Pencarian Serta Pengurutan dengan Bubble Sort.
from Tkinter import Tk,Frame,Menu
from Tkinter import*
import tkMessageBox as psn
import ttk
import tkFileDialog as bk
from tkMessageBox import *
import Tkinter as tk
from winsound import *
import platform
os = platform.system()
class MouseWheel(object): # Kelas untuk mengatur scroolbar
def __init__(self, root, factor = 2):
global os
self.activeArea = None
if type(factor) == int:
self.factor = factor
else:
raise Exception("Factor must be an integer.")
if os == "Linux" :
root.bind_all('<4>', self.onMouseWheel, add='+')
root.bind_all('<5>', self.onMouseWheel, add='+')
else:
# Windows and MacOS
root.bind_all("<MouseWheel>", self.onMouseWheel, add='+')
def onMouseWheel(self,event):
if self.activeArea:
self.activeArea.onMouseWheel(event)
def mouseWheel_bind(self, widget):
self.activeArea = widget
def mouseWheel_unbind(self):
self.activeArea = None
@staticmethod
def build_function_onMouseWheel(widget, orient, factor = 1):
view_command = getattr(widget, orient+'view')
if os == 'Linux':
def onMouseWheel(event):
if event.num == 4:
view_command("scroll",(-1)*factor,"units" )
elif event.num == 5:
view_command("scroll",factor,"units" )
elif os == 'Windows':
def onMouseWheel(event):
view_command("scroll",(-1)*int((event.delta/120)*factor),"units" )
elif os == 'Darwin':
def onMouseWheel(event):
view_command("scroll",event.delta,"units" )
return onMouseWheel
def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None):
scrollingArea.bind('<Enter>',lambda event: self.mouseWheel_bind(scrollingArea))
scrollingArea.bind('<Leave>', lambda event: self.mouseWheel_unbind())
if xscrollbar and not hasattr(xscrollbar, 'onMouseWheel'):
setattr(xscrollbar, 'onMouseWheel', self.build_function_onMouseWheel(scrollingArea,'x', self.factor) )
if yscrollbar and not hasattr(yscrollbar, 'onMouseWheel'):
setattr(yscrollbar, 'onMouseWheel', self.build_function_onMouseWheel(scrollingArea,'y', self.factor) )
active_scrollbar_on_mouse_wheel = yscrollbar or xscrollbar
if active_scrollbar_on_mouse_wheel:
setattr(scrollingArea, 'onMouseWheel', active_scrollbar_on_mouse_wheel.onMouseWheel)
for scrollbar in (xscrollbar, yscrollbar):
if scrollbar:
scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self.mouseWheel_bind(scrollbar) )
scrollbar.bind('<Leave>', lambda event: self.mouseWheel_unbind())
class simpul():
'''Membuat kelas simpul'''
def __init__(self, data=None):
self.data = data
self.link = None
class Tugas_GUI(Frame):
'''Membuat kelas GUI'''
def __init__(self,parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
self.list = None
# membuat canvas pada frame utama
self.canvas = Canvas(parent, background="grey")
self.frame = Frame(self.canvas, background="purple")
# mengedit style untuk scrollbar
s = ttk.Style()
s.theme_use('classic')
s.configure("coba.Vertical.TScrollbar", foreground = 'pink',background='teal')
# membuat scrollbar pada canvas
self.vsb = ttk.Scrollbar(parent, style="coba.Vertical.TScrollbar", orient="vertical", command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(side="right", fill="y")
self.canvas.pack(side="left", fill="both", expand=True)
self.canvas.create_window((0,0), window=self.frame, anchor="nw",
tags="self.frame")
self.frame.bind("<Configure>", self.OnFrameConfigure)
# agar scrool bar dapat di scroll
MouseWheel(root).add_scrolling(self.canvas, yscrollbar=self.vsb)
def OnFrameConfigure(self, event):
'''Reset the scroll region to encompass the inner frame'''
self.canvas.configure(scrollregion=self.canvas.bbox("all"),width=400)
def initUI(self):
self.parent.title("Tabel Data Item Di Toko Alat Tulis Kampus")
menubar = Menu(self.parent)
self.parent.config(menu = menubar, bg = 'purple')
# Membuat dan mengatur Button dan frame
self.btnKeluar = Button(self.parent,cursor = 'pirate',text="\n\n\n\nK\n\nE\n\nL\n\nU\n\nA\n\nR\n\n\n\n",
relief=RIDGE, bd=5, bg='burlywood',
fg='red',command=self.onExit)
self.btnKeluar.pack(side=RIGHT, fill=X)
self.btnimpor = Button(self.parent,text="\n\n\n\nI\n\nM\n\nP\n\nO\n\nR\n\nT\n\n\n\n",
relief=RIDGE, bd=5, bg='burlywood',
fg='red',command=self.impor)
self.btnimpor.pack(side=LEFT, fill=X)
fr_atas = Frame(self.parent)
fr_atas.pack(fill = BOTH)
self.btnnomor = Button(fr_atas,text="NO",
bd=1, bg='brown', width=14,
fg='green',command=self.nomor)
self.btnnomor.pack(side=LEFT, fill=BOTH)
self.btnnomor.configure(state=DISABLED)
self.btntanggal = Button(fr_atas,text="TANGGAL CEK",
bd=1, bg='brown',width=14,
fg='green',command=self.nomor)
self.btntanggal.pack(side=LEFT, fill=BOTH)
self.btntanggal.configure(state=DISABLED)
self.btnnama = Button(fr_atas,text="NAMA BARANG",
bd=1, bg='brown',width=14,
fg='green',command=self.nama)
self.btnnama.pack(side=LEFT, fill=BOTH)
self.btnnama.configure(state=DISABLED)
self.btnjumlah = Button(fr_atas,text="JUMLAH BARANG",
bd=1, bg='brown',width=14,
fg='green',command=self.jumlah)
self.btnjumlah.pack(side=LEFT, fill=BOTH)
self.btnjumlah.configure(state=DISABLED)
self.btnharga = Button(fr_atas,text="HARGA BARANG",
bd=1, bg='brown',width=14,
fg='green',command=self.harga)
self.btnharga.pack(side=LEFT, fill=BOTH)
self.btnharga.configure(state=DISABLED)
self.btnmodal = Button(fr_atas,text="MODAL",
bd=1, bg='brown',width=14,
fg='green',command=self.modal)
self.btnmodal.pack(side=LEFT, fill=BOTH)
self.btnmodal.configure(state=DISABLED)
self.btnsales = Button(fr_atas,text="SALES",
bd=1, bg='brown',width=14,
fg='green',command=self.sales)
self.btnsales.pack(side=LEFT, fill=BOTH)
self.btnsales.configure(state=DISABLED)
self.btncari = Button(self.parent,cursor = 'target',text="CARI",
bd=5, bg='burlywood',
fg='red',command=self.carisemua)
self.btncari.pack(side=BOTTOM, fill=X)
self.btncari.configure(state=DISABLED)
self.lblStatus = Button(self.parent,
text='TAMPILKAN',
bd=5,fg='red',bg='pink',command=self.tampilkan)
self.lblStatus.pack(side=BOTTOM, fill=X)
self.lblStatus.configure(state=DISABLED)
def kejadian(self): # Fungsi Mengubah Button menjadi aktif
self.btncari.configure(state=NORMAL)
self.btnnomor.configure(state=NORMAL)
self.btntanggal.configure(state=NORMAL)
self.btnnama.configure(state=NORMAL)
self.btnjumlah.configure(state=NORMAL)
self.btnharga.configure(state=NORMAL)
self.btnmodal.configure(state=NORMAL)
self.btnsales.configure(state=NORMAL)
def carisemua(self): # Fungsi untuk pencarian data
## p=self.list
def show_entry_fields():
coba = []
cek = False
p=self.list
while p.link is not None:
p=p.link
if p.data.no == target.get()or \
p.data.tanggal[:2] == target.get() or p.data.tanggal[3:5] == target.get() or p.data.tanggal[6:] == target.get() or \
p.data.nama == target.get() or \
p.data.jumlah == target.get() or \
p.data.harga == target.get() or \
p.data.modal == target.get() or \
p.data.sales == target.get():
data = (p.data.no,p.data.tanggal,p.data.nama,p.data.jumlah,p.data.harga,p.data.modal,p.data.sales.rstrip('\n'))
coba.append(data)
cek=True
p=self.list
while p.link is not None:
p=p.link
if p.data.no != target.get()and \
p.data.tanggal[:2] != target.get() and p.data.tanggal[3:5] != target.get() and p.data.tanggal[6:] != target.get() and \
p.data.nama != target.get() and \
p.data.jumlah != target.get() and \
p.data.harga != target.get() and \
p.data.modal != target.get() and \
p.data.sales != target.get():
coba.append(('','','','','','',''))
if cek == False:
psn.showwarning("Peringatan !", "Data Tidak Sesuai")
data_tampil = coba
for bariske in range(len(coba)):
baris = data_tampil[bariske]
for kolomke in range(len(coba[0])):
nilai = baris[kolomke]
widget = self._widgets[bariske][kolomke]
widget.configure(text=nilai)
cari = Tk()
cari.title('PENCARIAN DATA')
cari.config(bg='grey')
Label(cari, text="Masukan Data Yang Ingin Di Cari",fg='dark blue',bg='light blue').grid(row=0)
target = Entry(cari)
target.grid(row=0, column=1)
Button(cari, text='batal', command=cari.destroy,bg='#ff0000',fg='white').grid(row=3, column=1, sticky=W, padx=20,ipadx=30,pady=4)
Button(cari, text=' cari ', command=show_entry_fields,bg='red',fg='white').grid(ipadx=30,row=3, column=0, sticky=W, padx=15)
mainloop( )
def diam(self):
pass
def tampilsortir(self): # Fungsi untuk menampilkan hasil sortiran
data_tampil = self.data_mhs
for row in range(self.rows):
baris = data_tampil[row]
for column in range(self.columns):
nilai = baris[column]
widget = self._widgets[row][column]
widget.configure(text=nilai)
############################## pengurutan data menggunakan Bubble Sort ####################################
def bubbleSort(self,Data,indeks):
'''fungsi untuk mengurutkan data dengan Bubble Sort
input berupa list bernama Data'''
n = len(Data) # n adalah jumlah data
#mengurutkan berdasarkan atribut nomor
if indeks == 'nomor':
for k in range(1,n): # ulangi sebanyak n-1 kali
for i in range(n-1): # lakukan dari posisi paling kiri hingga ke kanan
if int(Data[i].data.no) > int(Data[i+1].data.no): # bandingkan dua data yang berdekatan
Data[i], Data[i+1] = Data[i+1], Data[i] # menukar posisi data
#mengurutkan berdasarkan atribut nama
elif indeks == 'nama':
for k in range(1,n):
for i in range(n-1):
if (Data[i].data.nama) > (Data[i+1].data.nama):
Data[i], Data[i+1] = Data[i+1], Data[i]
#mengurutkan berdasarkan atribut jumlah
elif indeks == 'jumlah':
for k in range(1,n):
for i in range(n-1):
if int(Data[i].data.jumlah) > int(Data[i+1].data.jumlah):
Data[i], Data[i+1] = Data[i+1], Data[i]
#mengurutkan berdasarkan atribut harga
elif indeks == 'harga':
for k in range(1,n):
for i in range(n-1):
if int(Data[i].data.harga) > int(Data[i+1].data.harga):
Data[i], Data[i+1] = Data[i+1], Data[i]
#mengurutkan berdasarkan atribut modal
elif indeks == 'modal':
for k in range(1,n):
for i in range(n-1):
if int(Data[i].data.modal) > int(Data[i+1].data.modal):
Data[i], Data[i+1] = Data[i+1], Data[i]
#mengurutkan berdasarkan atribut sales
elif indeks == 'sales':
for k in range(1,n):
for i in range(n-1):
if (Data[i].data.sales) > (Data[i+1].data.sales):
Data[i], Data[i+1] = Data[i+1], Data[i]
def bubble(self,LL,indeks):
'''mengurutkan linked list dengan Bubble Sort
Tricky: dengan mengkonversi linked menjadi array, bubble sort lalu
dikembalikan menjadi array'''
# konversi dari Linked List ke python list
li = []
p = LL.link
while p != None:
li.append(p)
p = p.link
# memanggil fungsi bubble sort
self.bubbleSort(li,indeks)
# konversi dari python list ke Linked List
p = LL
for simpul in li:
p.link = simpul
simpul.link = None
p = p.link
p=LL.link
self.data_mhs = []
while p is not None:
data=(p.data.no,p.data.tanggal,p.data.nama,p.data.jumlah,p.data.harga,p.data.modal,p.data.sales.rstrip('\n'))
self.data_mhs.append(data)
p=p.link
def nomor(self): # Fungsi untuk mengurutkan nomor
data = self.list_tampil
self.bubble(data,'nomor')
self.tampilsortir()
def nama(self): # Fungsi untuk mengurutkan nama barang
data=self.list_tampil
self.bubble(data,'nama')
self.tampilsortir()
def jumlah(self): # Fungsi untuk mengurutkan jumlah barang
data=self.list_tampil
self.bubble(data,'jumlah')
self.tampilsortir()
def harga(self): # Fungsi untuk mengurutkan harga barang
data=self.list_tampil
self.bubble(data,'harga')
self.tampilsortir()
def modal(self): # Fungsi untuk mengurutkan modal
data=self.list_tampil
self.bubble(data,'modal')
self.tampilsortir()
def sales(self): # Fungsi untuk mengurutkan sales
data=self.list_tampil
self.bubble(data,'sales')
self.tampilsortir()
def impor(self): # Funsi untuk mengimport file csv
try :
File = bk.askopenfilename()
x=open(File) # membuka file csv
x.readline() # membaca file csv dengan mengabaikan baris pertama
baca=x.readlines() #membaca semua data file csv dan menjadikannya sebuah list didalam variabel 'baca'
self.list = simpul() #self.list adalah kepala dari linked list yang akan dibuat ==> berisi None
p=self.list
for k in range (len(baca)): #
z=baca[k].split(';') #
L=data_transaksi(z[0],z[1],z[2],z[3],z[4],z[5],z[6]) # membuat isi linked list
p.link=simpul(L) #
p=p.link #
psn.showinfo("Pemberitahuan","import berhasil")
x.close()
self.list_tampil = self.list # membuat duplikat self.list
self.lblStatus.configure(state=NORMAL) # mengaktifkan button tampilkan
except IOError :
psn.showwarning("Pemberitahuan","Import dibatalkan")
except IndexError :
psn.showwarning("Peringatan !","file anda tidak sesuai")
def tampilkan(self): # Fungsi untuk menampilkan data
try :
p=self.list
self.data_mhs = []
while p.link is not None:
data=(p.link.data.no,p.link.data.tanggal,p.link.data.nama,p.link.data.jumlah,p.link.data.harga,p.link.data.modal,p.link.data.sales.rstrip('\n'))
self.data_mhs.append(data)
p=p.link
# bagian yang ditambahkan untuk menampilkan data
self.rows = len(self.data_mhs) # jumlah baris
self.columns = len(self.data_mhs[0]) # jumlah kolom
self._widgets = list()
for row in range(self.rows):
self.current_row = list()
for column in range(self.columns):
tampil = ''
label = Label(self.frame, text="%s" % tampil, width=14, bg = 'black',fg = 'aqua')
label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
self.current_row.append(label)
self._widgets.append(self.current_row)
for column in range(self.columns):
self.grid_columnconfigure(column, weight=1)
self.pack(side="top", fill="x")
# akhir bagian yang ditambahkan untuk menampilkan data
data_tampil = self.data_mhs
for row in range(self.rows):
baris = data_tampil[row]
for column in range(self.columns):
nilai = baris[column]
widget = self._widgets[row][column]
widget.configure(text=nilai)
self.kejadian()
psn.showinfo("pemberitahuan","Berhasil Ditampilkan")
## self.lblStatus.configure(state=DISABLED) # ini bisa di gunakan untuk maximize dan minimize
except :
psn.showwarning("Peringatan !", "Tidak ada file yang terbaca")
def onExit(self): # Fungsi untuk keluar dari program
if askyesno('Peringatan!', 'Anda ingin keluar?'):
play1 = PlaySound('ahem_x.wav', SND_FILENAME)
self.parent.destroy()
else:
showinfo('Pemberitahuan', 'Keluar dibatalkan')
class data_transaksi():
'''Membuat kelas data transaksi'''
def __init__(self,no=None,tanggal=None,nama=None,jumlah=None,harga=None,modal=None,sales=None):
self.no = no
self.tanggal = tanggal
self.nama = nama
self.jumlah = jumlah
self.harga = harga
self.modal = modal
self.sales = sales
if __name__ =='__main__': # Untuk menjalankan Tkinter atau GUI
root = Tk()
root.geometry("813x294+400+400")
root.resizable(False,False)
app = Tugas_GUI(root)
root.mainloop()
|
6705bd7dfa677bd27dbcf200aaa3f7dc6cd6cb55 | laurenc176/PythonCrashCourse | /Lists/simple_lists_cars.py | 938 | 4.5 | 4 | #organizing a list
#sorting a list permanently with the sort() method, can never revert
#to original order
cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
#can also do reverse
cars.sort(reverse=True)
print(cars)
# sorted() function sorts a list temporarily
cars = ['bmw','audi','toyota','subaru']
print("Here is the orginal list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
# Can print a list in reverse order using reverse() method, changes it permanently
# doesnt sort backward alphabetically, simply reverses order of the list
cars = ['bmw','audi','toyota','subaru']
print(cars)
cars.reverse()
print(cars)
#other methods I already know:
len(cars) # length of the list
cars[-1] # using -1 as an index will always return the last item in a list unless list is empty, then will get an error
|
68654f6011396a2f0337ba2d591a7939d609b3ed | laurenc176/PythonCrashCourse | /Files and Exceptions/exceptions.py | 2,711 | 4.125 | 4 | #Handling exceptions
#ZeroDivisionError Exception, use try-except blocks
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
#Using Exceptions to Prevent Crashes
print("Give me two numbers, and I'll divide them")
print("Enter 'q' to quit.")
#This will crash if second number is 0
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("\nSecond number: ")
if second_number == 'q':
break
answer = int(first_number) / int(second_number)
#Prevent crash:
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("\nSecond number: ")
if second_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer)
#FileNotFoundError Exception
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist")
#Analyzing Text
#Many classic lit are available as simple text files because they are in public domain
#Texts in this section come from Project Gutenberg(http://gutenberg.org/)
title = "Alice in Wonderland"
title.split()
filename = 'alice.txt'
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist")
else:
#Count the approx number of words in the file.
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.")
#Working with Multiple files, create a function
def count_words(filename):
"""Count the approx number of words in the file."""
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist")
else:
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.")
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)
#Fail silently - you don't need to report every exception
#write a block as usual, but tell Python to do nothing in the except block:
def count_words(filename):
"""Count the approx number of words in the file."""
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
pass #will fail silently, acts as a placeholder
else:
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.") |
b52ad63f303e4160d7a942cad8481f2f77edf1f0 | laurenc176/PythonCrashCourse | /Testing your code/testing_a_class.py | 3,250 | 4.40625 | 4 | # Six commonly used assert methods from the unittest.TestCase class:
#assertEqual(a, b) Verify a==b
#assertNotEqual(a, b) Verify a != b
#assertTrue(x) Verify x is True
#assertFalse(x) Verify x is False
#assertIn(item, list) Verify that item is in list
#assertNotIn(item, list) Verify that item is not in list
# Testing a class is very similar to testing a function but with a few differences
class AnonymousSurvey():
"""Collect anonymous answers to a survey question."""
def __init__(self, question):
"""Store a question, and prepare to store responses"""
self.question = question
self.responses = []
def show_question(self):
print(self.question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
"""Show all responses that have been given"""
print("Survey results:")
for response in self.responses:
print(f"- {response}")
# Define a question, and make a survey
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.show_question()
print("Enter 'q' at any time to quit")
while True:
response = input("Language: ")
if response == 'q':
break
my_survey.store_response(response)
my_survey.show_results()
#Testing the AnonomousSurvey class
import unittest
class TestAnonymousSurvey(unittest.TestCase):
def test_store_single_response(self):
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
def test_store_three_responses(self):
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
responses = ['English', 'Spanish', 'Mandarin']
for response in responses:
my_survey.store_response(response)
for response in responses:
self.assertIn(response, my_survey.responses)
if __name__ == '__main__':
unittest.main()
# Above testing are a bit repetitive - can be made more efficient:
-------------------------------------------------------------------------
# The setUp() Method
# unittest.TestCase has a setUp() method - allows you to create these objects once and then use
# them in each of your test methods
# when included, Python runs the setUp() method before running each methos starting with test_
# any objects created in the setUp() method are then available in each test method you write
import unittest
class TestAnonymousSurvey(unittest.TestCase):
def setUp(self):
"""
Create a survey and a set of responses for use in all test methods.
"""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
responses = ['English', 'Spanish', 'Mandarin']
def test_store_single_response(self):
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_responses(self):
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
if __name__ == '__main__':
unittest.main() |
4ec62e344d96dbd9db5860338526bb608a702a99 | honzaKovar/docker_unittest | /prime_numbers.py | 423 | 3.90625 | 4 | import math
from random import randint
def is_prime(number):
if number < 2:
return False
for i in range(2, int(math.sqrt(number) + 1)):
if number % i == 0:
return False
return True
if __name__ == '__main__':
MIN_VALUE = 0
MAX_VALUE = 999
random_number = randint(MIN_VALUE, MAX_VALUE)
print(f'Is number \'{random_number}\' a prime? - {is_prime(random_number)}')
|
fbc01f2c549fae60235064d839c55d98939ae775 | martinskillings/tempConverter | /tempConverter.py | 2,231 | 4.3125 | 4 |
#Write a program that converts Celsius to Fahrenheit or Kelvin
continueLoop = 'f'
while continueLoop == 'f':
celsius = eval(input("Enter a degree in Celsius: "))
fahrenheit = (9 / 5 * celsius + 32)
print(celsius, "Celsius is", format(fahrenheit, ".2f"), "Fahrenheit")
#User prompt to switch to different temperature setting or terminate program
continueLoop = input("Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: ")
if continueLoop == 'k':
celsius = eval(input("Enter a degree in Celsius: "))
kelvin = celsius + 273.15
print(celsius, "Celsius is", format(kelvin, ".2f"), "Kelvin")
continueLoop = input("Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: ")
if continueLoop == 'q':
print ("Good-Bye")
'''
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
RESTART: C:/Users/marti/AppData/Local/Programs/Python/Python36-32/tempConverter.py
Enter a degree in Celsius: 43
43 Celsius is 109.40 Fahrenheit
Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k
Enter a degree in Celsius: 43
43 Celsius is 316.15 Kelvin
Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f
Enter a degree in Celsius: 0
0 Celsius is 32.00 Fahrenheit
Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k
Enter a degree in Celsius: 0
0 Celsius is 273.15 Kelvin
Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f
Enter a degree in Celsius: 100
100 Celsius is 212.00 Fahrenheit
Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k
Enter a degree in Celsius: 100
100 Celsius is 373.15 Kelvin
Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f
Enter a degree in Celsius: 37
37 Celsius is 98.60 Fahrenheit
Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k
Enter a degree in Celsius: 37
37 Celsius is 310.15 Kelvin
Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: q
Good-Bye
>>>
'''
|
3f6b3832e8c1b33cb1e03ae6a026236f1d82a171 | StarryLeo/learnpython | /day0/do_if.py | 286 | 4 | 4 | height = 1.75
weight = 80.5
bmi = weight/height * height
if bmi < 18.5:
print('过轻')
elif bmi >= 18.5 and bmi < 25:
print('正常')
elif bmi >= 25 and bmi < 28:
print('过重')
elif bmi >= 28 and bmi < 32:
print('肥胖')
else:
print('严重肥胖')
|
6d9c2f166469c4767ad6815edccc79f5306ae3c1 | est/snippets | /sort_coroutine/mergesort.py | 1,417 | 4.03125 | 4 | import random
def merge1(left, right):
result = []
left_idx, right_idx = 0, 0
while left_idx < len(left) and right_idx < len(right):
# change the direction of this comparison to change the direction of the sort
if left[left_idx] <= right[right_idx]:
result.append(left[left_idx])
left_idx += 1
else:
result.append(right[right_idx])
right_idx += 1
if left:
result.extend(left[left_idx:])
if right:
result.extend(right[right_idx:])
return result
from heapq import merge as merge2
def merge3(left,right):
if not left or not right:
return left + right
elif left[0] <= right[0]:
return [left[0]] + merge3(left[1:], right)
else:
return merge3(right,left)
def merge_sort(l):
# Assuming l is a list, returns an
# iterator on a sorted version of
# the list.
L = len(l)
if L <= 1:
return l
else:
m = L/2
left = merge_sort(l[0:m])
right = merge_sort(l[m:])
return merge(left, right)
if '__main__' == __name__:
l = [random.randint(0, 5) for x in range(10)]
s0 = sorted(l)
merge = merge1
s1 = merge_sort(l)
merge = merge2
s2 = list(merge_sort(l))
merge = merge3
s3 = merge_sort(l)
print s0==s1==s2==s3, s0, s1, s2, s3 |
fae09bb082a160bfc2cf1c165250c551d6f70387 | cdpruitt/CribbageAI | /GameActions.py | 5,135 | 3.5625 | 4 | from Card import *
from itertools import *
class History():
def __init__(self, playerToLead):
self.rounds = [RoundTo31(playerToLead)]
def isTerminal(self):
totalCardsPlayed = 0
for roundTo31 in self.rounds:
for play in roundTo31.board:
if(play=="PASS"):
break
else:
totalCardsPlayed += 1
if(totalCardsPlayed==8):
return True
else:
return False
def __repr__(self):
historyRepr = "Rounds:"
for roundTo31 in self.rounds:
historyRepr += " " + str(roundTo31)
return historyRepr
class RoundTo31():
def __init__(self, playerToLead):
self.playerToLead = playerToLead
self.board = []
def __repr__(self):
roundTo31Repr = "Cards played:"
for card in self.board:
roundTo31Repr += " " + str(card)
return roundTo31Repr
# Create a new deck at the start of the game
def createDeck():
RANKS = [1,2,3,4,5,6,7,8,9,10,11,12,13]
SUITS = ["spades","hearts","diamonds","clubs"]
return list(Card(rank, suit) for rank, suit in product(RANKS,
SUITS))
# Create a new deck at the start of a hand
def createSuitlessDeck():
RANKS = [1,2,3,4,5,6,7,8,9,10,11,12,13]
SUITS = ["spades","hearts","diamonds","clubs"]
deck = list(SuitlessCard(rank) for rank, suit in product(RANKS, SUITS))
return deck
# Score a given hand, provided the identity of the flip card and whether the
# hand is a crib or not
def scoreHand(hand,isCrib,flipCard):
score = 0
# check for His Nobs
for card in hand:
if (card.rank=="11")&(card.suit==flipCard.suit):
score += 1
# check for flush
if all(card.suit==flipCard.suit for card in hand):
score += 5
elif all(card.suit==hand[0].suit for card in hand):
score += 4
hand.append(flipCard)
hand = sorted(hand)
# check for 15s
for i in range(1,len(hand)+1):
for subHand in combinations(hand,i):
sum = 0
for card in subHand:
sum += card.value
if sum==15:
score += 2
# check for pairs
for cardPair in combinations(hand,2):
if cardPair[0].rank==cardPair[1].rank:
score += 2
# check for runs
foundRuns = False
for i in range(len(hand),2,-1):
if foundRuns == False:
for subHand in combinations(hand,i):
it = (card.rank for card in subHand)
first = next(it)
if all(a==b for a, b in enumerate(it, first+1)):
score += i
foundRuns = True
return score
# Count up the total points showing on the board
def totalTheBoard(board):
boardValue = 0
for card in board:
boardValue += card.value
return boardValue
def score(roundTo31, newCard):
currentBoard = roundTo31.board
if(roundTo31.playerToLead==0):
# first player's turn
total = scoreTheBoard(currentBoard, newCard)
else:
# second player's turn
total = -scoreTheBoard(currentBoard, newCard)
#print "For " + str(currentBoard) + " " + str(newCard) + ", total = " + str(total)
return total
def consecutive(runCards):
sortedCards = runCards[:]
sortedCards.sort(key=lambda x: x.rank)
for i, card in enumerate(sortedCards):
if(card.rank==(sortedCards[0].rank+i)):
continue
else:
return False
return True
# Compute the play points if newCard is played on the current board
def scoreTheBoard(b, newCard):
board = b[:]
board.append(newCard)
#print board
score = 0
# check for 31s and 15s
boardValue = totalTheBoard(board)
if (boardValue==15 or boardValue==31):
#print "31 or 15 for 2"
score += 2
reversedBoard = board[::-1]
# check for pairs
pairCards = []
for card in reversedBoard:
if reversedBoard[0].rank==card.rank:
pairCards.append(card)
else:
break
for x in combinations(pairCards,2):
#print "pairs for 2"
score += 2
# check for runs
runs = 0
while(len(reversedBoard)>2):
#print reversedBoard
if(consecutive(reversedBoard)):
runs = len(reversedBoard)
#print "runs for " + str(runs)
break
reversedBoard.pop()
score += runs
#if(score>0):
# print score
return score
def evaluateTerminalState(cards, roundTo31):
total = 0
playerToLead = roundTo31.playerToLead
if(playerToLead==0):
total += score(roundTo31,cards[playerToLead][0])
else:
total -= score(roundTo31,cards[playerToLead][0])
roundTo31.board.append(cards[playerToLead][0])
roundTo31.playerToLead = 1-playerToLead
if(len(cards[1-playerToLead])>0):
if(1-playerToLead==0):
total -= score(roundTo31,cards[1-playerToLead][0])
else:
total += score(roundTo31,cards[1-playerToLead][0])
return total
|
22c396d0cb06c25ea3162191dfa536672be1bd7c | GiPyoK/Sprint-Challenge--Data-Structures-Python | /names/binary_search_tree.py | 4,965 | 3.828125 | 4 | from dll_queue import Queue
from dll_stack import Stack
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
# This would be only needed if there was deleted method to BST
# because BST is always initialized with the root.
# check for empty root (base case)
if self == None:
# create a new tree with given value
self = BinarySearchTree(value)
return
# compare with root
# less than the root, move left
if value < self.value:
# check left
# if left exists, move left
if self.left:
self.left.insert(value)
# else, create new value and connect left to it
else:
self.left = BinarySearchTree(value)
return
# greater or equal to the root, move right
else:
# check right
# if right extist, move right
if self.right:
self.right.insert(value)
# else, create new value and connect right to it
else:
self.right = BinarySearchTree(value)
return
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
# check for empty root
if self == None:
return False
# if the value is the target, return true
if target == self.value:
return True
# else if the value is less than the target, move left
elif target < self.value:
if self.left:
return self.left.contains(target)
# else if the value is greater than the target, move right
else:
if self.right:
return self.right.contains(target)
return False
# Return the maximum value found in the tree
def get_max(self):
# go to very right of the tree
while self.right:
self = self.right
return self.value
# Call the function `cb` on the value of each node
# You may use a recursive or iterative approach
def for_each(self, cb):
if self == None:
return
# call the function
cb(self.value)
# if left is not None, go to left
if self.left:
self.left.for_each(cb)
# if right is not None, go to right
if self.right:
self.right.for_each(cb)
# DAY 2 Project -----------------------
# Print all the values in order from low to high
# Hint: Use a recursive, depth first traversal
def in_order_print(self, node):
# left -> root -> right
if node.left:
self.in_order_print(node.left)
print(node.value)
if node.right:
self.in_order_print(node.right)
# Print the value of every node, starting with the given node,
# in an iterative breadth first traversal
def bft_print(self, root):
# create queue and enqueue the root of the BST
q = Queue()
q.enqueue(root)
# loop until the queue is empty
while q.len() > 0:
# grab the first item of the queue
node = q.dequeue()
# print the first item and enqueue any children
print(node.value)
if node.left:
q.enqueue(node.left)
if node.right:
q.enqueue(node.right)
# Print the value of every node, starting with the given node,
# in an iterative depth first traversal
def dft_print(self, root):
# create stack and push the root
stack = Stack()
stack.push(root)
# loop until the stack is empty
while stack.len() > 0:
node = stack.pop()
# print the last item and push and children
print(node.value)
if node.left:
stack.push(node.left)
if node.right:
stack.push(node.right)
# STRETCH Goals -------------------------
# Note: Research may be required
# Print Pre-order recursive DFT
def pre_order_dft(self, node):
if node:
print(node.value)
if node.left:
self.pre_order_dft(node.left)
if node.right:
self.pre_order_dft(node.right)
# Print Post-order recursive DFT
def post_order_dft(self, node):
if node.left:
self.post_order_dft(node.left)
if node.right:
self.post_order_dft(node.right)
print(node.value)
# # test
# bst = BinarySearchTree(1)
# bst.insert(8)
# bst.insert(5)
# bst.insert(7)
# bst.insert(6)
# bst.insert(3)
# bst.insert(4)
# bst.insert(2)
# bst.post_order_dft(bst) |
39a26f9febc2acc3ce0e3291c1dbe45801418275 | deep-compute/deeputil | /deeputil/keep_running.py | 5,090 | 3.84375 | 4 | """Keeps running a function running even on error
"""
import time
import inspect
class KeepRunningTerminate(Exception):
pass
def keeprunning(
wait_secs=0, exit_on_success=False, on_success=None, on_error=None, on_done=None
):
"""
Example 1: dosomething needs to run until completion condition
without needing to have a loop in its code. Also, when error
happens, we should NOT terminate execution
>>> from deeputil import AttrDict
>>> @keeprunning(wait_secs=1)
... def dosomething(state):
... state.i += 1
... print (state)
... if state.i % 2 == 0:
... print("Error happened")
... 1 / 0 # create an error condition
... if state.i >= 7:
... print ("Done")
... raise keeprunning.terminate
...
>>> state = AttrDict(i=0)
>>> dosomething(state)
AttrDict({'i': 1})
AttrDict({'i': 2})
Error happened
AttrDict({'i': 3})
AttrDict({'i': 4})
Error happened
AttrDict({'i': 5})
AttrDict({'i': 6})
Error happened
AttrDict({'i': 7})
Done
Example 2: In case you want to log exceptions while
dosomething keeps running, or perform any other action
when an exceptions arise
>>> def some_error(__exc__):
... print (__exc__)
...
>>> @keeprunning(on_error=some_error)
... def dosomething(state):
... state.i += 1
... print (state)
... if state.i % 2 == 0:
... print("Error happened")
... 1 / 0 # create an error condition
... if state.i >= 7:
... print ("Done")
... raise keeprunning.terminate
...
>>> state = AttrDict(i=0)
>>> dosomething(state)
AttrDict({'i': 1})
AttrDict({'i': 2})
Error happened
division by zero
AttrDict({'i': 3})
AttrDict({'i': 4})
Error happened
division by zero
AttrDict({'i': 5})
AttrDict({'i': 6})
Error happened
division by zero
AttrDict({'i': 7})
Done
Example 3: Full set of arguments that can be passed in @keeprunning()
with class implementations
>>> # Class that has some class variables
... class Demo(object):
... SUCCESS_MSG = 'Yay!!'
... DONE_MSG = 'STOPPED AT NOTHING!'
... ERROR_MSG = 'Error'
...
... # Functions to be called by @keeprunning
... def success(self):
... print((self.SUCCESS_MSG))
...
... def failure(self, __exc__):
... print((self.ERROR_MSG, __exc__))
...
... def task_done(self):
... print((self.DONE_MSG))
...
... #Actual use of keeprunning with all arguments passed
... @keeprunning(wait_secs=1, exit_on_success=False,
... on_success=success, on_error=failure, on_done=task_done)
... def dosomething(self, state):
... state.i += 1
... print (state)
... if state.i % 2 == 0:
... print("Error happened")
... # create an error condition
... 1 / 0
... if state.i >= 7:
... print ("Done")
... raise keeprunning.terminate
...
>>> demo = Demo()
>>> state = AttrDict(i=0)
>>> demo.dosomething(state)
AttrDict({'i': 1})
Yay!!
AttrDict({'i': 2})
Error happened
('Error', ZeroDivisionError('division by zero'))
AttrDict({'i': 3})
Yay!!
AttrDict({'i': 4})
Error happened
('Error', ZeroDivisionError('division by zero'))
AttrDict({'i': 5})
Yay!!
AttrDict({'i': 6})
Error happened
('Error', ZeroDivisionError('division by zero'))
AttrDict({'i': 7})
Done
STOPPED AT NOTHING!
"""
def decfn(fn):
def _call_callback(cb, fargs):
if not cb:
return
# get the getargspec fn in inspect module (python 2/3 support)
G = getattr(inspect, "getfullargspec", getattr(inspect, "getargspec"))
cb_args = G(cb).args
cb_args = dict([(a, fargs.get(a, None)) for a in cb_args])
cb(**cb_args)
def _fn(*args, **kwargs):
fargs = inspect.getcallargs(fn, *args, **kwargs)
fargs.update(dict(__fn__=fn, __exc__=None))
while 1:
try:
fn(*args, **kwargs)
if exit_on_success:
break
except (SystemExit, KeyboardInterrupt):
raise
except KeepRunningTerminate:
break
except Exception as exc:
fargs.update(dict(__exc__=exc))
_call_callback(on_error, fargs)
fargs.update(dict(__exc__=None))
if wait_secs:
time.sleep(wait_secs)
continue
_call_callback(on_success, fargs)
_call_callback(on_done, fargs)
return _fn
return decfn
keeprunning.terminate = KeepRunningTerminate
|
7011bfd3326ccb843859999aaf89c71a3137cdd4 | skylway/leetcode | /python/0344. 反转字符串/solution.py | 472 | 3.71875 | 4 | #!/usr/bin/python
from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
# s.reverse()
# s[:] = s[::-1]
i = 0
len_list = len(s)
while i < len_list/2:
s[i], s[len_list-i-1] = s[len_list-i-1], s[i]
i += 1
"""
Do not return anything, modify s in-place instead.
"""
solution = Solution()
l = ['Google', 'Runoob']
solution.reverseString(l)
print(l)
|
79723bc580e8f7ccd63a8b86c182c783a56d3329 | SuzanneRioue/programmering1python | /Lärobok/kap 8/kap. 8, sid. 103 - list comprehensions.py | 1,297 | 4.34375 | 4 | #!/usr/local/bin/python3.9
# Filnamn: kap. kap. 8, sid. 103 - list comprehensions.py
# Kapitel 8 - Listor och tipplar
# Programmering 1 med Python - Lärobok
# Exempeldata
listaEtt = [9, 3, 7]
# Med listomfattningar (list comprehensions) menas att man skapar en ny lista
# där varje element är resultatet av någon operation på en annan
# itererbar variabel eventuella villkor måste också uppfyllas
# Här skapar vi en ny lista med uppräkning av t, talen finns ej från början
listaTvå = [t for t in range(10)]
print(listaTvå)
# Skapar en ny lista med utgångspunkt av t i range-inställningarna
listaTre = [t for t in range(3, 10, 3)]
print('listaTre:', listaTre)
# Skapar en ny lista med utgångspunkt av att kvadrera t utifrån
# range-inställningarna
listaFyra = [t**2 for t in range(3, 10, 3)]
print('listaFyra:', listaFyra)
# Skapa en ny lista där villkoret att inte ta med tal som är jämt delbara med 5
listaFem = [t for t in range(1, 26) if t % 5 != 0]
print('listaFem:', listaFem)
# Slå samman listor (konkatenera)
listaEtt = listaEtt + listaFyra
print('Efter sammanslagning med listaFyra är listaEtt:', listaEtt)
# Med metoden append så skapar du en lista i en lista
listaEtt.append(listaTre)
print('Efter sammanslagning med listaTre är listaEtt:', listaEtt) |
417e9bbc0a001695bc2cd7586b71b5a8b89832ee | SuzanneRioue/programmering1python | /Arbetsbok/kap 14/övn 14.1, sid. 36 - söka tal.py | 1,443 | 3.921875 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 14.1, sid. 36 - söka tal.py
# Sökning
# Programmeringsövningar till kapitel 14
# Programmet slumpar först fram 20 tal mellan 1 och 100 och lagrar alla talen i
# en lista och sedan skrivs listan ut på skärmen. Därefter frågar programmet
# användaren efter ett tal som ska eftersökas. Slutligen undersöker programmet
# om talet finns i listan och om det finns, skriva ut på indexet det finns på.
# Om inte talet finns så ska användaren informeras om att det inte finns.
# Sökmetod: Linjär sökning
# Import av modul
from random import randint
# Funktionsdefinitioner
# Huvudprogram
def main():
lista = []
# Slumpa 20 st heltal mellan 1 och 100 och lägg dem eftervarandra i listan
for c in range(20):
lista.append(randint(1,100))
# Skriv ut listan
print(lista)
# Fråga användaren efte tal som eftersöks
tal = int(input('Anget tal som eftersöks: '))
# Utför en linjär sökning i hela listan
# Utgå ifrån att talet inte finns
index = -1
for i in range(len(lista)):
if tal == lista[i]:
# Om talet hittas sätt index till det och avbryt loopen
index = i
break
if index >= 0:
print('Talet ' + str(tal) + ' finns på index ' + str(index) + ' i listan.')
else:
print('Talet ' + str(tal) + ' finns inte i listan.')
## Huvudprogram anropas
main() |
f38757087bf31b61d8238f3e98798a8799f1b6f8 | SuzanneRioue/programmering1python | /Lärobok/kap 8/kap. 8, sid. 104 - sammanfattning med exempel.py | 2,712 | 4.1875 | 4 | #!/usr/local/bin/python3.9
# Filnamn: kap. 8, sid. 104 - sammanfattning med exempel.py
# Kapitel 8 - Listor och tipplar
# Programmering 1 med Python - Lärobok
# Exempeldata
lista = [7, 21, 3, 12]
listaLäggTill = [35, 42]
listaSortera = [6, 2, 9, 1]
listaNamn = ['Kalle', 'Ada', 'Pelle', 'Lisa']
# len(x) Ta reda på antal element i en lista samt vilket nr sista index är
antalElement = len(lista)
sistaIndex = antalElement - 1
print('lista: ', lista, 'består av', antalElement, ' element och sista indexposten är',sistaIndex)
# sorted() Skapar en ny lista som är sorterad
print('listaSortera:', listaSortera)
nySorteradLista = sorted(listaSortera)
print('nySorteradLista baserad på en sorterad listaSortera:', nySorteradLista)
# sort() returnerar en sorterad lista
print('En numrerad lista för sortering:', lista)
lista.sort()
print('En numrerad lista efter sortering:', lista)
print('En alfabetisk lista för sortering:', listaNamn)
listaNamn.sort()
print('En alfabetisk lista efter sortering:', listaNamn)
# append(x) lägg till element i slutet av befintlig lista
print('lista före tillägg:', lista)
lista.append(28)
print('lista efter tillägg:', lista)
# extend(lista) sammanfoga/konkatenera två listor, går med +
print('lista före sammanfogning:', lista)
print('med listaLäggTill:', listaLäggTill)
# lista.extend(listaLäggTill) ¤ Krånglig metod
lista = lista + listaLäggTill # Bättre och enklare metod
print('lista efter sammanfogning:', lista)
# insert(x) infoga elemet på indexposition x
print('listaNamn före infogandet av ett namn till:', listaNamn)
listaNamn.insert(1, 'Agnes')
print('listaNamn efter infogandet av ett namn till:', listaNamn)
# remove(x) tar bort första elementet i en lista med värdet/strängen x
print('listaNamn före borttagande av namnet Kalle:', listaNamn)
listaNamn.remove('Kalle')
print('listaNamn efter borttagande av namnet Kalle:', listaNamn)
# pop(x) ta bort element med index x, utelämnas x tas sista elemnt bort
print('lista före borttag av index 0 och sista index:', lista)
lista.pop(0)
lista.pop()
print('lista efter bottag av index 0 och sista index:', lista)
# index(x) tar reda på index nummer för element x
print('listaNamn:', listaNamn)
finnsPåIndex = listaNamn.index('Lisa')
print('Lisa finns på indexposition:', finnsPåIndex)
# count(x) räkna antal förekomster av element x
lista.append(7) # Vi lägger till en 7:a till lista
antal7or = lista.count(7)
print('lista ser nu ut så här:', lista)
print('Det finns', antal7or, 'st 7:or i lista')
# reversed() Vänder listan bak och fram
print('lista ser nu ut så här:', lista)
lista.reverse()
print('efter att vi vänt på listan så ser den ut så här:', lista)
|
d5448c074c4419908d4c5246e1d87f792fd28731 | SuzanneRioue/programmering1python | /Arbetsbok/kap 14/övn 14.3, sid. 37 - gissa ett tal.py | 1,650 | 3.921875 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 14.2, sid. 36 - söka tal med funktion.py
# Sökning
# Programmeringsövningar till kapitel 14
# Programmet slumpar först fram ett tal mellan 1 och 99 och lagrar det talet.
# Därefter frågar datorn användaren vilke tal datorn tänker på och användaren
# får gissa tills han/hon gissat rätt och då får man även reda på hur många
# gissningar man gjort. Om användaren gissar ett för lågt tal så sägger datorn
# att det är för lågt och för högt om det är tvärs om.
# Import av modul
from random import randint
# Funktionsdefinitioner
# Huvudprogram
def main():
# Variabeldeklarationer och initieringar
# Talet som datorn tänker på
talDator = randint(1,100)
# Antal gissningar som användaren gjort
gissningar = 1
# Skriv ut en programrubrik
print('Gissa vilket tal jag tänker på')
print('==============================\n')
# Fråga användaren vilket tal datorn tänker på
talAnvändare = int(input('Vilket tal tänker jag på? '))
while talDator != talAnvändare:
# Beroende på om användarens gissade tal är för högt eller lågt
# i förhållande till vad datorn tänker på för tal,skriv ut en ledtråd
if talAnvändare > talDator:
print('För högt!')
else:
print('För lågt!')
# Öka antal gissningar
gissningar += 1
# Låt användaren gissa på ett nytt tal
talAnvändare = int(input('Vilket tal tänker jag på? '))
print('Rätt gissat på ' + str(gissningar) + ' försök.')
## Huvudprogram anropas
main() |
60febc4082a4c46d7a0da215bc70e5531777ad75 | SuzanneRioue/programmering1python | /Arbetsbok/kap 3/övn 3.4 - ange valfri rabatt på vara - kap 3, sid. 5.py | 1,098 | 4.09375 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 3.4 - ange valfri rabatt på vara - kap 3, sid. 5.py
# Skapa program eller skript
# Programmeringsövningar till kapitel 3 - Arbetsbok
# Programmet frågar först efter ordinarie pris på en vara. Därefter frågar det
# efter en godtycklig rabattprocent
# Till sist skriver det ut ett extrapris som ger den inmatade rabatten på
# ordinariepris
# Skriv ut programmets rubrik
print('Extrapris')
print('=========\n')
# Fråga efter ordinarie pris och rabattprocent. Därefter omvandla siffrorna från sträng till decimaltal
ordinariePris = float(input('Ange ordinarie pris: '))
rabattProcent = float(input('Ange rabattprocenten: '))
decimalRabattProcent = rabattProcent / 100 # Omvandlar procenttalet till ett decimaltal för senare beräkning
# Beräkna extrapriset 100% - rabattProcent * ordinarie pris
extraPris = (1 - decimalRabattProcent) * ordinariePris
# Skriv ut rabattprocenten med noll decimaler och extrapriset med två decimalers noggranhet
print('Extrapriset blir med {0:.0f} % rabatt: {1:.2f} kr.'.format(rabattProcent, extraPris))
|
4ceb64bae252b6c7acd59332297c3ccc02023694 | SuzanneRioue/programmering1python | /Arbetsbok/kap 10/övn 10.1 - lottorad.py | 1,306 | 3.546875 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 10.1 - lottorad.py
# Slumptal i programmering
# Programmeringsövningar till kapitel 10
# Programmet slumpar fram en lottorad, 7 tal i intervallet 1 - 35 där samma
# nummer inte får uppkomma 2 gånger
from random import randrange
# Funktionsdefinitioner
def lottorad(): # Funktionshuvud
# Variabeldeklarationer
tal = 0 # Lagrar ett slumptal temporärt
lottorad = [0, 0, 0, 0, 0, 0, 0] # Lottorad som ska returneras senare
i = 0
# Slumpa fram 7 tal mellan 1-35 och lagra i listan lottorad
# talen som lagras måste vara olika
while i < 7:
tal = randrange(1,36)
lottorad[i] = tal
i += 1
# Kontroll om tal finns som dublett
for c in range(i):
# om tal och listans tal c är lika och c samt i-1 är skilda från
# varandra då är det en dublett
if tal == lottorad[c] and c != (i-1):
# Vi ska fixa ett nytt slumptal på samma index
# då det gamla var en dublett därav i -1 och break
i -= 1
break
# Återgå till anropande program med en sorterad lista
return sorted(lottorad)
# Huvudprogram
def main():
print(lottorad())
## Huvudprogram anropas
main() |
a969e3ff963ef2ed1980e8ff48bf4c048dfefde9 | SuzanneRioue/programmering1python | /Lärobok/kap 6/kap. 6, sid. 76 - kontrollera innehåll och tomma strängar.py | 842 | 3.703125 | 4 | #!/usr/local/bin/python3.9
# Filnamn: kap. 6, sid. 76 - kontrollera innehåll och tomma strängar.py
# Kapitel 6 - Mer om teckensträngar i Python
# Programmering 1 med Python - Lärobok
# Kontrollera innehåll i en sträng med operatorn in
if 'r' in 'Räven raskar över isen': # Kontroll av enstaka tecken
print('Bokstaven r finns!')
if 'rask' in 'Räven raskar över isen': # Kontroll av fras/ord/orddel
print('Frasen/ordet eller orddelen finns!')
'''
Exempel på tom sträng
En tom sträng tolkas alltid som falsk (False) vid villkorstestning
och undertrycker alltid en radframmatning i print-satser
Övriga strängar tolkas som sanna (True)
'''
s = ''
if s:
print('Strängen är inte tom')
else:
print('Strängen är tom')
s = 'Nisse'
if s:
print('Strängen är inte tom')
else:
print('Strängen är tom') |
e415fc6296d368d63a75ef1a8a50e7182820a49c | SuzanneRioue/programmering1python | /Arbetsbok/kap 3/övn 3.7 - Additionsövning med formaterad utskrift med flyttal - kap 3, sid. 6.py | 759 | 3.90625 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 3.7 - Additionsövning med formaterad utskrift med flyttal - kap 3
# sid. 6.py
# Skapa program eller skript
# Programmeringsövningar till kapitel 3 - Arbetsbok
# Additionsövning med formaterad utskrift
# Programmet skriver ut tal i en snygg additionsuppställning
# Skriv ut programmets rubrik
print('Enkel addition med tre siffror i decimalform')
print('============================================\n')
# Deklaration och initiering av 3 tal
tal1 = 123.45
tal2 = 6.7
tal3 = 89.01
# Beräkna summan av de tre talen
summa = tal1 + tal2 + tal3
# Skriv ut ett kvitto
print('{:>8.2f}'.format(tal1))
print('{:>8.2f}'.format(tal2))
print('+{:>7.2f}'.format(tal3))
print('========')
print('{:>8.2f}'.format(summa))
|
1a6cf574b1498ca03608892dcfe185605b909bd5 | SuzanneRioue/programmering1python | /Lärobok/kap 16/kap. 16, sid. 186 - omvandla dictionary till olika listor.py | 929 | 3.609375 | 4 | #!/usr/local/bin/python3.9
# Filnamn: kap. 16, sid. 186 - omvandla dictionary till olika listor.py
# Kapitel 16 - Mer om listor samt dictionaries
# Programmering 1 med Python - Lärobok
# Kodexempel från boken med förklaringar
# Skapa en associativ array (dictionary) med namn som nycklar och anknytningsnr
# som värde
anknytning = {'Eva':4530, 'Ola':4839, 'Niklas':6386, 'Agnes':4823}
# Skriv ut dictionaryn
print(anknytning)
# Skapa en ny lista med tipplar utav dictionaryn och skriv ut den
listaMedTipplar = list(anknytning.items())
print(listaMedTipplar)
# Skriv ut tippel 1
print(listaMedTipplar[1])
enTippel = listaMedTipplar[1]
# Skriv ut första indexet i tippeln
print(enTippel[0])
# Skapa en ny lista av listor utav dictionaryn och skriv ut den
listaMedListor = [[namn, ankn] for namn, ankn in anknytning.items()]
print(listaMedListor)
# Skriv ut endast ut ett av namnen i listan
print(listaMedListor[2][0]) |
38bfae3b5387684afe8dc8b4787087bdd786d2c0 | SuzanneRioue/programmering1python | /Arbetsbok/kap 8/övn 8.3 - beräkna summa och medelvärde av lista - kap. 8, sid. 21.py | 1,289 | 4.03125 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 8.3 - beräkna summa och medelvärde av lista - kap. 8, sid. 21.py
# Listor och tipplar
# Programmeringsövningar till kapitel 8
# Programmet frågar efter hur många tal du vill mata in, låter dig sedan mata
# in dessa en i taget. Efter varje inmatning läggs det inmatade talet till
# listan. Därefter beräknar programmet summan och medelvärdet av listans tal.
# Slutligen skrivs listans summa och medelvärdet ut på konsolen
listaTal = [] # Tom lista som lagrar antTal element innehållande tal
# Fråga användaren hur många tal som ska matas in
antTal = int(input('Hur många tal vill du mata in? '))
# Be användaren mata in antTal st tal och lagra dem som varsit nytt element i
# listan listaTal
for i in range(antTal):
listaTal.append(float(input('Ange tal ' + str(i+1) + ': ')))
# Beräkna summan av alla inmatade tal
summa = 0 # Måste inieras denna annars tror systemet att summa också är en lista
for i in range(antTal):
summa += listaTal[i] # Här är det viktigt att summa initierats innan
# Beräkna medelvärdet av listan alla tal
medel = summa / antTal
# Skriv ut summan och medelvärdet på konsolen
print('Summan av alla inmatade tal blev ' + str(summa) + ' och medelvärdet blev ' + str(medel)) |
43b89ba2d0757f49a5d86da45c98930f65d600d4 | SuzanneRioue/programmering1python | /Arbetsbok/kap 14/övn 14.6, sid. 38 - datorn gissar ett tal.py | 2,362 | 3.78125 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 14.6, sid. 38 - datorn gissar ett tal.py
# Sökning
# Programmeringsövningar till kapitel 14
# Programmet låter dig tänka på ett tal mellan 1 och 99.
# Första gången gissar datorn på talet i mitten utifrån det givna intervallet 1
# till 99. Dvs. talet 50. Svarar användaren at det är för högt
# gissar dator på nedre halvans mitt, dvs 25, sedan tillfrågas användaren igen.
#
# Import av modul
from random import randint
# Funktionsdefinitioner
def binGissning(ngräns, ögräns):
return (ögräns - ngräns) // 2
# Huvudprogram
def main():
# Variabeldeklarationer och initieringar
# Talet som datorn tror människan tänker på
talMänniska = 0
# Antal gissningar som datorn gjort
gissningar = 1
# Talgränser
nedre = 1
övre = 100
# Svar som ska anges av användaren
svar = ''
# Skriv ut en programrubrik
print('Jag gissar vilket tal du tänker på')
print('==================================\n')
print('Får jag be dig att tänka på ett tal mellan 1 och 100.')
# Gissa i mitten av talgränserna
talMänniska = binGissning(nedre, övre)
# Skriv ut gissningen
print('Jag gissar att du tänker på talet ' + str(talMänniska) + '.')
# Fråga användaren om det är rätt, för högt eller lågt
svar = input('Är det [r]ätt, för [h]ögt eller [l]ågt: ')
while svar not in ['r', 'rätt']:
if svar in ['h', 'högt']:
övre = talMänniska - 1
oldtal = talMänniska
talMänniska -= binGissning(nedre, övre)
if oldtal == talMänniska:
talMänniska -= 1
if svar in ['l', 'lågt']:
nedre = talMänniska + 1
oldtal = talMänniska
talMänniska += binGissning(nedre, övre)
if oldtal == talMänniska:
talMänniska += 1
# Öka antal gissningar
gissningar += 1
# Skriv ut gissningen
print('Jag gissar att du tänker på talet ' + str(talMänniska) + '.')
# Och fråga användaren återigen om det är rätt, för högt eller lågt
svar = input('Är det [r]ätt, för [h]ögt eller [l]ågt: ')
print('Jag gissat rätt efter ' + str(gissningar) + ' försök.')
# Huvudprogram anropas
main() |
c183615f347834216b4f3f12cd97e6e22a07d472 | SuzanneRioue/programmering1python | /Arbetsbok/kap 4/övn 4.4 - priskoll på bensin - kap 4, sid. 7.py | 831 | 3.671875 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 4.4 - priskoll på bensin - kap 4, sid. 7.py
# Skapa program eller skript
# Programmeringsövningar till kapitel 4 - Arbetsbok
# Programmet frågar efter bensinpris och som sedan med villkor talar om
# om det är billigt eller inte.
# Skriv ut programmets rubrik
print('Priskoll på bensin')
print('==================\n')
# Fråga efter bensinpriset och omvandla siffrorna från sträng till decimaltal
bensinPris = float(input('Vad kostar bensinen per liter: '))
# Utifrån bensinpriset, testa med villkor och berätta för användaren om det är
# billigt eller dyrt
if bensinPris > 20:
print('Nu säljer jag bilen och cyklar istället')
elif bensinPris > 15:
print('Tanka tio liter')
elif bensinPris > 10:
print('Tanka full tank')
else:
print('Det var billigt')
|
281e7f4dd1ef0495d3213f59afd0007d0426134a | SuzanneRioue/programmering1python | /Arbetsbok/kap 6/övn 6.4 - vänder på meningen - kap. 6, sid. 15.py | 313 | 3.5 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 6.4 - vänder på meningen - kap. 6, sid. 15.py
# Mer om teckensträngar i Python
# Programmeringsövningar till kapitel 6
# Programmet ber användaren mata in en meninig och skriver sedan ut den
# baklänges
mening = input('Skriv en mening: ')
print(mening[::-1])
|
e691e8b4c3ad89fdc107b6b9bb2a37f4ba34091d | AmishiBisht/PythonProject | /Calculator.py | 6,120 | 4.1875 | 4 | from tkinter import *
from math import *
win = Tk()
win.title("Calculator") # this title will be displayed on the top of the app
#win.geometry("300x400") # this defines the size of the app of window
input_box = StringVar() # It gets the contents of the entry box
e = Entry(win,width = 50, borderwidth = 5, textvariable = input_box) # this defines the size of the entry box for user input
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) # this displays the entry box on the top
expression = "" # Initiate the variable expression
def button_click(num): # this function generates expression when any button is clicked
global expression
expression = expression + str(num)
input_box.set(expression)
return
def Button_Clear(): # clears the contents of the entry box
global expression
expression = ""
input_box.set(expression)
return
def Button_Equal(): # evaluates the expression in the entr box and displays the result
global expression
result = str(eval(expression))
round(result,2)
expression = result
input_box.set(expression)
return
def Button_Factor():
result = str(eval(expression))
a=int(result)
Factors=[]
for i in range(1,a+1):
if a% i==0:
Factors.append(i)
Factors.append(',')
e.insert(0,Factors)
return
def Button_Fctrl():
global expression
result = str(eval(expression))
num =int(result)
factorial = 1
if num == 0:
e.insert(0,1)
else:
for i in range(1,num + 1):
factorial = factorial*i
e.delete(0,END)
e.insert(0,factorial)
expression = str(factorial)
return
def Button_PrimeOrComposite():
a = int(eval(e.get()))
Button_Clear()
factors = []
for i in range(1,a+1):
if a % i== 0:
factors.append(a)
if len(factors)==2:
input_box.set("Is prime.")
else:
input_box.set("Is composite.")
return
def Button_Abs():
result = abs(eval(e.get()))
e.delete(0,END)
global expression
expression = result
input_box.set(expression)
return
#Defining Buttons (what they should display and what they should do)
button_1 = Button(win, text="1", padx=40, pady=20, font=("Courier",11), fg='turquoise', bg='white', command = lambda: button_click(1))
button_2 = Button(win, text="2", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(2))
button_3 = Button(win, text="3", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click(3))
button_4 = Button(win, text="4", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(4))
button_5 = Button(win, text="5", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click(5))
button_6 = Button(win, text="6", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(6))
button_7 = Button(win, text="7", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click(7))
button_8 = Button(win, text="8", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(8))
button_9 = Button(win, text="9", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click(9))
button_0 = Button(win, text="0", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(0))
button_sum = Button(win, text="+", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click('+'))
button_diff = Button(win, text="-", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click('-'))
button_equal = Button(win, text="=", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: Button_Equal())
button_clear = Button(win, text="AC", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: Button_Clear())
button_mul = Button(win, text="*", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click('*'))
button_div = Button(win, text="/", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click('/'))
button_fac = Button(win, text=" factor", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: Button_Factor())
button_fctrl = Button(win, text="fctrl", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: Button_Fctrl())
button_bracket = Button(win, text="(", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click("("))
button_bracket1 = Button(win, text=")", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(')'))
button_primeorcomp = Button(win, text="CheckPrime", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: Button_PrimeOrComposite())
button_abs = Button(win, text="Abs", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: Button_Abs())
#To display buttons
#The following code displays the buttons created
button_1.grid(row=1, column=0)
button_2.grid(row=1, column=1)
button_3.grid(row=1, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=3, column=0)
button_8.grid(row=3, column=1)
button_9.grid(row=3, column=2)
button_0.grid(row=4, column=0)
button_sum.grid(row=2, column=3)
button_diff.grid(row=3, column=3)
button_equal.grid(row=4, column=2)
button_clear.grid(row=4, column=1)
button_mul.grid(row=1, column=3)
button_div.grid(row=4, column=3)
button_fac.grid(row=5, column=2)
button_bracket.grid(row=5, column=0)
button_bracket1.grid(row=5, column=1)
button_fctrl.grid(row=5, column=3)
button_primeorcomp.grid(row=6, column=0)
button_abs.grid(row=6, column=1)
win.mainloop()
|
3a96ab91401def3cb21863b4eeb3d0f082d07811 | zhenya-paitash/course-python-ormedia | /lesson__6_homework.py | 4,806 | 4.34375 | 4 | from math import pi # число ПИ для 2ого задания
import random as R # для генерации рандомных чисел в решении заданий
# 1. Определите класс Apple с четырьмя переменными экземпляра, представляющими четыре свойства яблока
class Apple:
def __init__(self, c, w, s, v):
self.color = c
self.weight = w
self.size = s
self.view = v
print("1: ")
# 2. Создайте класс Circle с методом area, подсчитывающим и возвращающим площадь круга. Затем создайте объект Circle,
# вызовите в нем метод area и выведите результат. Воспользуйтесь функцией pi из встроенного в Python модуля math
class Circle:
def __init__(self, n):
self.number = n
self.square = 0
def area(self, r): # s = pi*r^2
self.square = pi * (r ** 2)
crcl = Circle(1)
radius = R.randint(5, 30)
crcl.area(radius)
print(f"2: Радиус круга: {radius} Площадь круга: {round(crcl.square, 3)}") # площадь округляю до 3х знаков после точки
# 3. Есть класс Person, конструктор которого принимает три параметра (не учитывая self) – имя, фамилию и квалификацию
# специалиста. Квалификация имеет значение заданное по умолчанию, равное единице.
class Person:
def __init__(self, n, srn, q=1):
self.name = n
self.surname = srn
self.qualification = q
# 3(2) У класса Person есть метод, который возвращает строку, включающую в себя всю информацию о сотруднике
def pers(self, person):
print(f" Сотрудник {person.surname} {person.name} имеет квалификацию {person.qualification}.")
prs1, prs2 = Person('Евгений', 'Пайташ', 'Junior'), Person('Вейдер', 'Дарт', 'Space Lord')
print("3: ")
prs1.pers(prs1)
prs2.pers(prs2)
# 4. Создайте класс Triangle с методом area, подсчитывающим и возвращающим площадь треугольника. Затем создайте
# объект Triangle, вызовите в нем area и выведите результат
class Triangle:
def __init__(self, n):
self.number = n
self.thr = 0
def area(self, a, h):
self.thr = 0.5 * a * h
tr1 = Triangle(1)
base, height = R.randint(5, 30), R.randint(10, 20)
tr1.area(base, height)
print(f"4: При основании {base} см и высоте {height} см, площадь треугольника {tr1.thr} см²")
# 5. Создайте классы Rectangle и Square с методом calculate_perimeter, вычисляющим периметр фигур, которые эти классы
# представляют. Создайте объекты Rectangle и Square вызовите в них этот метод
class Rectangle():
def __init__(self, one, two):
self.one_side, self.two_side = one, two
self.perimeter = 0
def calculate_perimeter(self):
self.perimeter = (self.one_side + self.two_side) * 2
class Square():
def __init__(self, side):
self.side = side
def calculate_perimeter(self):
self.perimeter = 4 * self.side
def change_size(self, inp):
self.side += inp
rect, squ = Rectangle(R.randint(5, 100), R.randint(5, 100)), Square(R.randint(5, 50))
rect.calculate_perimeter(), squ.calculate_perimeter()
print(f"5: Периметр прямоугольника со сторонами {rect.one_side} cm и {rect.two_side} cm равен {rect.perimeter} cm,\n "
f" периметр квадрата со стороной {squ.side} cm равен {squ.perimeter} cm.")
# 6. В классе Square определите метод change_size, позволяющий передавать ему число, которое увеличивает или уменьшает
# (если оно отрицательное) каждую сторону объекта Square на соответствующее значение
squ.change_size(int(input('6: Введите число, на которе хотите изменить грань квадрата :')))
squ.calculate_perimeter()
print(f" Новый периметр квадрата со стороной {squ.side}cm равен {squ.perimeter} cm.")
|
faa30b2222bde8849d6d452736f025f0bd80ecdb | HelloYuiYui/Fun-with-PyTurtle | /Dots.py | 759 | 3.796875 | 4 |
from turtle import *
import random
#setting up the environment.
bgcolor("#ffebc6")
color("blue", "yellow")
speed(10)
def dots():
#hiding turtle and pen to avoid creating unwanted lines between dots.
penup()
hideturtle()
dotnum = 0
limit = 200 #change number to create more or less dots.
while dotnum <= limit:
#random coordinates for dots.
dotx = random.randint(-300, 300)
doty = random.randint(-300, 300)
#random size for dots.
dotsize = random.randint(1, 200)
dotsize = dotsize/10
goto(dotx, doty)
dot(dotsize, "black")
dotnum += 1
#to stop program when reached to the limit.
if dotnum > limit:
done()
break
dots() |
aefe923d857f9ab74c65429ebfae3d539b7fb007 | Snowerest/leetcodeQuestion-Python | /stack.py | 399 | 3.8125 | 4 | class Stack(object):
def __init__(self):
self.__v = []
def is_empty(self) -> bool:
return self.__v == []
def push(self, value: object) -> None:
self.__v.append(value)
def pop(self) -> object:
if self.is_empty():
return None
value = self.__v[-1]
self.__v = self.__v[:-1]
return value
|
968c16becdcdaaea847617224ea4fb776865d839 | Snowerest/leetcodeQuestion-Python | /ball_sort.py | 291 | 3.609375 | 4 | def ball_sort(nums: list) -> list:
ln = len(nums)
if ln <= 1:
return nums
i = 0
while i < ln:
j = i
while j < ln:
if nums[j] <= nums[i]:
nums[j], nums[i] = nums[i], nums[j]
j += 1
i += 1
return nums
|
78ed8e3e2072193899cc73f9224cbec04e10e593 | kushagrasurana/Minuet-server | /app/responses.py | 1,429 | 3.546875 | 4 | from flask import jsonify
from . import app
def make_response(code, message):
"""Creates an HTTP response
Creates an HTTP response to be sent to client with status code as 'code'
and data - message
:param code: the http status code
:param message: the main message to be sent to client
:return: returns the HTTP response
"""
if code == 400:
return bad_request(message)
elif code == 401:
return unauthorized(message)
elif code == 403:
return forbidden(message)
elif code == 500:
return internal_server_handler(message)
else:
return ok(message)
@app.errorhandler(400)
def bad_request(message):
response = jsonify({'error': 'bad request', 'message': message})
response.status_code = 400
return response
@app.errorhandler(401)
def unauthorized(message):
response = jsonify({'error': 'unauthorized', 'message': message})
response.status_code = 401
return response
@app.errorhandler(403)
def forbidden(message):
response = jsonify({'error': 'forbidden', 'message': message})
response.status_code = 403
return response
@app.errorhandler(500)
def internal_server_handler(message):
response = jsonify({'error': 'server error', 'message': message})
response.status_code = 500
return response
def ok(message):
response = jsonify(message)
response.status_code = 200
return response |
17aa9df4e57e711c87f41b3e101d894ce19c50ba | DrakeVorndran/Tweet-Generator | /Code/reaarrange.py | 602 | 3.84375 | 4 | import sys
import random
def reaarrange(words):
for i in reversed(range(1,len(words))):
pos = random.randint(0,i-1)
words[i], words[pos] = words[pos], words[i]
return(words)
def reverseString(string, seperator=""):
if(seperator == ""):
return_string = list(string)
else:
return_string = string.split(seperator)
return_string.reverse()
return return_string
def anagram(word):
return "".join(reaarrange(list(word)))
if __name__ == '__main__':
l = sys.argv[1:]
print(*reaarrange(l))
# print(reverseString("hello my name is bob", " "))
# print(anagram("anagram")) |
be6b2ac375fb83d117835be397d7aa411afb94a8 | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/005闰年判断.py | 425 | 3.890625 | 4 | print('------------酸饺子学Python------------')
#判断一个年份是否是闰年
#Coding 酸饺子
temp = input('输入一个年份吧:\n')
while not temp.isdigit():
print('这个不是年份吧……')
year = int(temp)
if year/400 == int(year/400):
print('闰年!')
else:
if (year/4 == int(year/4)) and (year/100 != int(year/100)):
print('闰年!')
else:
print('平年!')
|
5eadae3b9e4e99640a7ec52cf0483eaf9c2fbf4b | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/030搜索文件.py | 667 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-06-16 23:11:30
# @Author : 酸饺子 ([email protected])
# @Link : http://bbs.fishc.com/space-uid-437297.html
# @Version : $Id$
import os
content = input('请输入待查找的目录:')
file_name = input('请输入待查找的目标文件:')
def Search(path, file_name):
path_list = os.listdir(path)
os.chdir(path)
for each in path_list:
if os.path.isdir(each):
Search(os.path.join(path, each), file_name)
os.chdir(path)
else:
if each == file_name:
print(os.path.join(path, each))
return
Search(content, file_name)
|
2feef38d5f8ce0751dbecbb098d0936c5df0cf17 | SourDumplings/CodeSolutions | /OJ practices/PAT甲级真题练习/1039. Course List for Student-超时.py | 1,188 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-12-06 16:05:13
# @Author : 酸饺子 ([email protected])
# @Link : https://github.com/SourDumplings
# @Version : $Id$
'''
https://www.patest.cn/contests/pat-a-practise/1039
'''
def main():
temp = input().split(' ')
N = int(temp[0])
K = int(temp[1])
students = {}
for i in range(K):
c_info = input().split(' ')
c = int(c_info[0])
n = int(c_info[1])
if n:
namelist = input().split(' ')
for each_name in namelist:
if each_name in students.keys():
students[each_name].append(c)
else:
students[each_name] = [c]
if N:
query = input().split(' ')
for each_name in query:
if each_name not in students.keys():
print("%s 0" % each_name)
continue
print("%s %d" % (each_name, len(students[each_name])), end='')
students[each_name].sort()
for each_course in students[each_name]:
print(" %d" % each_course, end='')
print()
if __name__ == '__main__':
main()
|
e33f3ad1ed5312c6c2e9726f243b005719f02ee4 | SourDumplings/CodeSolutions | /Book practices/《简单粗暴 TensorFlow 2.0》练习代码/1.基础/2.自动求导机制.py | 929 | 3.53125 | 4 | import tensorflow as tf
# 计算函数 y = x^2 在 x = 3 处的导数
# x = tf.Variable(initial_value=3.)
# with tf.GradientTape() as tape: # 在 tf.GradientTape() 的上下文内,所有计算步骤都会被记录以用于求导
# y = tf.square(x)
# y_grad = tape.gradient(y, x) # 计算y关于x的导数
# print([y, y_grad])
# 多元函数,对向量的求导
X = tf.constant([[1., 2.], [3., 4.]])
y = tf.constant([[1.], [2.]])
w = tf.Variable(initial_value=[[1.], [2.]])
b = tf.Variable(initial_value=1.)
temp0 = tf.matmul(X, w)
print(temp0)
temp1 = temp0 + b
print(temp1)
temp2 = temp1 - y
print(temp2)
temp3 = tf.square(temp2)
print(temp3)
temp4 = tf.reduce_sum(temp3)
print(temp4)
with tf.GradientTape() as tape:
L = 0.5 * tf.reduce_sum(tf.square(tf.matmul(X, w) + b - y))
w_grad, b_grad = tape.gradient(L, [w, b]) # 计算L(w, b)关于w, b的偏导数
print([L.numpy(), w_grad.numpy(), b_grad.numpy()])
|
d070a6c21e6788543c94e042ddc9a1a6e6822029 | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/014check.py | 1,957 | 3.859375 | 4 | #密码安全检查
#Coding 酸饺子
# 密码安全性检查代码
#
# 低级密码要求:
# 1. 密码由单纯的数字或字母组成
# 2. 密码长度小于等于8位
#
# 中级密码要求:
# 1. 密码必须由数字、字母或特殊字符(仅限:~!@#$%^&*()_=-/,.?<>;:[]{}|\)任意两种组合
# 2. 密码长度不能低于8位
#
# 高级密码要求:
# 1. 密码必须由数字、字母及特殊字符(仅限:~!@#$%^&*()_=-/,.?<>;:[]{}|\)三种组合
# 2. 密码只能由字母开头
# 3. 密码长度不能低于16位
print('-------------酸饺子学Python-------------')
symbols = r'''`!@#$%^&*()_+-=/*{}[]\|'";:/?,.<>'''
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
nums = '0123456789'
passwd = input('请输入需要检查的密码组合:')
# 判断长度
length = len(passwd)
while (passwd.isspace() or length == 0) :
passwd = input("您输入的密码为空(或空格),请重新输入:")
length = len(passwd)
if length <= 8:
flag_len = 1
elif 8 < length < 16:
flag_len = 2
else:
flag_len = 3
flag_con = 0
# 判断是否包含特殊字符
for each in passwd:
if each in symbols:
flag_con += 1
break
# 判断是否包含字母
for each in passwd:
if each in chars:
flag_con += 1
break
# 判断是否包含数字
for each in passwd:
if each in nums:
flag_con += 1
break
# 打印结果
while 1 :
print("您的密码安全级别评定为:", end='')
if flag_len == 1 or flag_con == 1 :
print("低")
elif flag_len == 2 or flag_con == 2 :
print("中")
else :
print("高")
print("请继续保持")
break
print("请按以下方式提升您的密码安全级别:\n\
\t1. 密码必须由数字、字母及特殊字符三种组合\n\
\t2. 密码只能由字母开头\n\
\t3. 密码长度不能低于16位'")
break
|
3b17c72973b952d716cdd263b5faf377f3ec143c | SourDumplings/CodeSolutions | /OJ practices/牛客网:PAT真题练兵场-乙级/有理数四则运算.py | 2,615 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-16 10:28:17
# @Author : 酸饺子 ([email protected])
# @Link : https://github.com/SourDumplings
# @Version : $Id$
'''
https://www.nowcoder.com/pat/6/problem/4060
'''
import math as m
def main():
def gcd(a, b):
r = a % b
while r:
a = b
b = r
r = a % b
gcd = b
return gcd
def ToInt(n):
if n - int(n):
n *= 10
return n
s = input()
s = s.replace(' ', '/')
a1 = int(s.split('/')[0])
b1 = int(s.split('/')[1])
a2 = int(s.split('/')[2])
b2 = int(s.split('/')[3])
# print(a1, b1, a2, b2)
def OutPut(a, b):
# print("$$a = %.2f, b = %.2f$$" % (a, b))
if not a:
print(0, end='')
else:
temp_a = a
temp_b = b
g = gcd(temp_a, temp_b)
temp_a /= g
temp_b /= g
if a / b < 0:
print('(', end='')
k = int(m.fabs(temp_a) // m.fabs(temp_b))
if a / b < 0:
k *= -1
# print("$$k = %d$$" % k)
if k:
print(k, end='')
if temp_a < 0 and temp_b > 0:
temp_a *= -1
if temp_a > 0 and temp_b < 0:
temp_b *= -1
temp_a = temp_a - m.fabs(k) * temp_b
if temp_a:
print(" %d/%d" % (temp_a, temp_b), end='')
else:
if temp_a > 0 and temp_b < 0:
print("-%d/%d" % (temp_a, -temp_b), end='')
else:
print("%d/%d" % (temp_a, temp_b), end='')
if a / b < 0:
print(')', end='')
return
# 和
OutPut(a1, b1)
print(" + ", end='')
OutPut(a2, b2)
print(" = ", end='')
a = a1 * b2 + a2 * b1
b = b1 * b2
OutPut(a, b)
print()
# 差
OutPut(a1, b1)
print(" - ", end='')
OutPut(a2, b2)
print(" = ", end='')
a = a1 * b2 - a2 * b1
b = b1 * b2
OutPut(a, b)
print()
# 积
OutPut(a1, b1)
print(" * ", end='')
OutPut(a2, b2)
print(" = ", end='')
a = a1 * a2
b = b1 * b2
OutPut(a, b)
print()
# 商
OutPut(a1, b1)
print(" / ", end='')
OutPut(a2, b2)
print(" = ", end='')
if not a2:
print("Inf")
else:
a = ToInt(a1 / a2)
b = ToInt(b1 / b2)
# print("$$a = %.2f, b = %.2f$$" % (a, b))
OutPut(a, b)
return
if __name__ == '__main__':
main()
|
5d0e1b4504139b2166783311414a30d8ed0e3be7 | SourDumplings/CodeSolutions | /OJ practices/PAT甲级真题练习/1012. The Best Rank.py | 2,536 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-28 19:18:52
# @Author : 酸饺子 ([email protected])
# @Link : https://github.com/SourDumplings
# @Version : $Id$
'''
https://www.patest.cn/contests/pat-a-practise/1012
'''
def main():
temp = input()
temp = temp.split(' ')
N = int(temp[0])
M = int(temp[1])
Agrade = {}
Cgrade = {}
Mgrade = {}
Egrade = {}
for i in range(N):
s = input()
s = s.split(' ')
ID = s[0]
C = int(s[1])
m = int(s[2])
E = int(s[3])
A = (C + m + E) / 3
Agrade[ID] = A
Cgrade[ID] = C
Mgrade[ID] = m
Egrade[ID] = E
def readrankdata(rankdata, ranklist, index, N):
r = 1
# print(ranklist)
count = 0
for i in range(N):
if not rankdata.get(ranklist[i][0]):
rankdata[ranklist[i][0]] = [0, 0, 0, 0]
rankdata[ranklist[i][0]][index] = r
count += 1
if i < N - 1 and ranklist[i][1] > ranklist[i + 1][1]:
r += count
count = 0
# print(rankdata)
return
rankdata = {} # id : [Arank, Crank, Mrank, Ernak]
A_ranklist = sorted(Agrade.items(), key=lambda d: d[1], reverse=True)
readrankdata(rankdata, A_ranklist, 0, N)
C_ranklist = sorted(Cgrade.items(), key=lambda d: d[1], reverse=True)
readrankdata(rankdata, C_ranklist, 1, N)
M_ranklist = sorted(Mgrade.items(), key=lambda d: d[1], reverse=True)
readrankdata(rankdata, M_ranklist, 2, N)
E_ranklist = sorted(Egrade.items(), key=lambda d: d[1], reverse=True)
readrankdata(rankdata, E_ranklist, 3, N)
items = ['A', 'C', 'M', 'E']
bestrankdata = {} # id : [bestrank, best]
for each in rankdata:
bestrank = rankdata[each][0]
for each_rank in rankdata[each]:
if each_rank < bestrank:
bestrank = each_rank
best = rankdata[each].index(bestrank)
if not bestrankdata.get(each):
bestrankdata[each] = [0, 0]
bestrankdata[each][0] = bestrank
bestrankdata[each][1] = best
# print(bestrankdata)
checklist = []
for i in range(M):
temp = input()
# print(temp)
checklist.append(temp)
# print(checklist)
for each_id in checklist:
data = bestrankdata.get(each_id)
if data:
print("%d %s" % (data[0], items[data[1]]))
else:
print("N/A")
if __name__ == '__main__':
main()
|
00f241c31584d25d9a8eb0c93aeb1fdff2c5a5bc | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/025通讯录.py | 1,712 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-06-13 17:22:08
# @Author : 酸饺子 ([email protected])
# @Link : http://bbs.fishc.com/space-uid-437297.html
# @Version : $Id$
contact = {}
print('''|--- 欢迎进入通讯录程序---|
|--- 1 :查询联系人资料 ---|
|--- 2 :插入新的联系人 ---|
|--- 3 : 删除已有联系人 ---|
|--- 4 : 退出通讯录程序 ---|\n''')
while 1:
order = int(input('请输入相关指令代码:'))
if order == 2:
name2 = input('请输入联系人姓名:')
if name2 in contact:
print('您输入的用户名在通讯录中已存在!')
print(name2, ':', contact[name2])
edit = input('是否修改该用户的资料?(Yes/No)')
if (edit != 'Yes') and (edit != 'No'):
print('输入错误!')
elif edit == 'Yes':
contact[name2] = input('请输入用户联系电话:')
print('修改成功!')
else:
continue
else:
phone2 = input('请输入用户联系电话:')
contact[name2] = phone2
print('插入成功!')
if order == 1:
name1 = input('请输入联系人姓名:')
if name1 in contact:
print(name1, ':', contact[name1])
else:
print('该联系人不存在!')
if order == 3:
name3 = input('请输入联系人姓名:')
if name3 in contact:
contact.pop(name3)
print('删除成功!')
else:
print('该联系人不存在!')
if order == 4:
break
print('|--- 感谢使用通讯录程序 ---|')
|
89a06671ad98cebf5590a4ece8ad192d2954819b | SourDumplings/CodeSolutions | /OJ practices/PAT甲级真题练习/1035. Password.py | 957 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-12-05 20:30:26
# @Author : 酸饺子 ([email protected])
# @Link : https://github.com/SourDumplings
# @Version : $Id$
'''
https://www.patest.cn/contests/pat-a-practise/1035
'''
def main():
N = int(input())
modified = []
flag = 0
for i in range(N):
account = input().split()
pw0 = account[1]
pw = pw0
pw = pw.replace('1', '@')
pw = pw.replace('0', '%')
pw = pw.replace('O', 'o')
pw = pw.replace('l', 'L')
if pw != pw0:
modified.append([account[0], pw])
flag += 1
if (flag):
print(flag)
for each_modified in modified:
print(each_modified[0], each_modified[1])
elif N > 1:
print("There are %d accounts and no account is modified" % N)
else:
print("There is 1 account and no account is modified")
if __name__ == '__main__':
main()
|
ae952d0a06fff2b4f8ced902cd7355a19e0b17a1 | SourDumplings/CodeSolutions | /OJ practices/LeetCode题目集/88. Merge Sorted Array(easy).py | 943 | 3.65625 | 4 | '''
@Author: SourDumplings
@Date: 2020-02-16 19:37:18
@Link: https://github.com/SourDumplings/
@Email: [email protected]
@Description: https://leetcode-cn.com/problems/merge-sorted-array/
双指针法,从后往前填
'''
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
p = m + n - 1
p1 = m - 1
p2 = n - 1
while 0 <= p1 and 0 <= p2:
num1 = nums1[p1]
num2 = nums2[p2]
if num1 < num2:
nums1[p] = nums2[p2]
p2 -= 1
else:
nums1[p] = nums1[p1]
p1 -= 1
p -= 1
while 0 <= p2:
nums1[p] = nums2[p2]
p -= 1
p2 -= 1
while 0 <= p1:
nums1[p] = nums1[p1]
p -= 1
p1 -= 1
|
70a075b1fba763f3a12d1baecbc20c50930c0c3d | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/010向列表中添加成绩.py | 287 | 4.21875 | 4 | #向列表中添加成绩
#Coding 酸饺子
print('-------------酸饺子学Python-------------')
member = ['小甲鱼', '黑夜', '迷途', '怡静', '秋舞斜阳']
member.insert(1, 88)
member.insert(3, 90)
member.insert(5, 85)
member.insert(7, 90)
member.insert(9, 88)
print(member)
|
ebc51cdc6f85317dc3e53bd614184c5b9a15519b | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/064tk2.py | 692 | 3.53125 | 4 | # encoding: utf-8
"""
@author: 酸饺子
@contact: [email protected]
@license: Apache Licence
@file: tk2.py
@time: 2017/7/25 10:00
tkinter演示实例2,打招呼
"""
import tkinter as tk
def main():
class APP:
def __init__(self, master):
frame = tk.Frame(master)
frame.pack(side=tk.LEFT, padx=10, pady=10)
self.hi_there = tk.Button(frame, text='打招呼', fg='white',
command=self.say_hi, bg='black')
self.hi_there.pack()
def say_hi(self):
print('hello!我是酸饺子!')
root = tk.Tk()
app = APP(root)
root.mainloop()
if __name__ == '__main__':
main()
|
de09ee49797be6b1931cec7a4b4a17c50aa78b0f | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/009输入密码.py | 483 | 4.09375 | 4 | #输入密码
#Coding 酸饺子
print('-------------酸饺子学Python-------------')
count = 3
code = 'SourDumplings'
while count != 0:
guess = input('您好,请输入密码:')
if guess == code:
print('密码正确!')
break
elif '*' in guess:
print('密码中不能含有*!')
print('您还有', count, '次机会')
else:
count -= 1
print('密码错误。您还有', count, '次机会!')
|
6df6963f07c1073e3ae63b8ab99850fe90355a76 | SourDumplings/CodeSolutions | /OJ practices/PAT甲级真题练习/1023. Have Fun with Numbers.py | 692 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-12-01 20:52:18
# @Author : 酸饺子 ([email protected])
# @Link : https://github.com/SourDumplings
# @Version : $Id$
'''
https://www.patest.cn/contests/pat-a-practise/1023
'''
def main():
n = input()
num = int(n)
num *= 2
doubled_n = str(num)
flag = 1
for d in doubled_n:
# print("n = %s, d = %s" % (n, d))
i = n.find(d)
if i == -1:
flag = 0
break
n = n.replace(d, '', 1)
if len(n) > 0:
flag = 0
# print(n)
if flag:
print("Yes")
else:
print("No")
print(doubled_n)
if __name__ == '__main__':
main()
|
9348714135c920044a7664b82b4b8648b88a424f | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/042字符串ASCII码四则运算.py | 1,054 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-06-30 18:23:48
# @Author : 酸饺子 ([email protected])
# @Link : http://bbs.fishc.com/space-uid-437297.html
# @Version : $Id$
class Nstr(str):
def __add__(self, other):
a = 0
b = 0
for each in self:
a += ord(each)
for each in other:
b += ord(each)
return (a + b)
def __sub__(self, other):
a = 0
b = 0
for each in self:
a += ord(each)
for each in other:
b += ord(each)
return (a - b)
def __mul__(self, other):
a = 0
b = 0
for each in self:
a += ord(each)
for each in other:
b += ord(each)
return (a * b)
def __truediv__(self, other):
a = 0
b = 0
for each in self:
a += ord(each)
for each in other:
b += ord(each)
return (a / b)
a = Nstr('FishC')
b = Nstr('love')
print(a + b)
print(a - b)
print(a * b)
print(a / b)
|
6baa21538651c4b215d774f883d17b0824f23a6a | guilfojm/01-IntroductionToPython-201930 | /src/m6_your_turtles.py | 2,180 | 3.703125 | 4 | """
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Aaron Wilkin, their colleagues, and Justin Guilfoyle.
"""
########################################################################
# DONE: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
########################################################################
########################################################################
# DONE: 2.
# You should have RUN the m5e_loopy_turtles module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOU WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT-and-PUSH when you are done with this module.
#
#######################################################################
import rosegraphics as rg
window = rg.TurtleWindow()
size = 150
blue_turtle = rg.SimpleTurtle('turtle')
blue_turtle.pen = rg.Pen('midnight blue',5)
blue_turtle.speed = 15
for k in range(15):
# Put the pen down, then draw a square of the given size:
blue_turtle.draw_square(size)
# Move a little below and to the right of where the previous
# square started. Do this with the pen up (so nothing is drawn).
blue_turtle.pen_up()
blue_turtle.right(30)
blue_turtle.forward(10)
blue_turtle.left(5)
# Put the pen down again (so drawing resumes).
# Make the size for the NEXT square be 12 pixels smaller.
blue_turtle.pen_down()
size = size - 12
green_turtle = rg.SimpleTurtle('turtle')
green_turtle.pen = rg.Pen('green',2)
green_turtle.speed = 4
for k in range(35):
green_turtle.left(k)
green_turtle.forward(20)
green_turtle.right(35)
green_turtle.backward(30)
window.close_on_mouse_click()
|
a4f4a928befdb63ceaf7f834d6b6641a7922674a | Debonairesnake6/ClashBot | /src/player_ranks.py | 2,521 | 3.75 | 4 | """
This file will gather all of the information needed to create a table showing each player's rank
"""
from text_to_image import CreateImage
class PlayerRanks:
"""
Handle creating the player ranks table
"""
def __init__(self, api_results: object):
"""
Handle creating the player ranks table
:param api_results: Results from the api_queries file
"""
self.api_results = api_results
self.titles = None
self.columns = []
self.player_column = []
self.rank_column = []
self.colour_columns = []
self.titles = ['Player', 'Rank']
self.player_ranked_info = None
self.player_name = None
self.setup()
def setup(self):
"""
Run the major functions of the object
"""
self.process_every_player()
self.set_colour_columns()
self.create_image()
def create_image(self):
"""
Create the image from the processed results
"""
CreateImage(self.titles, self.columns, '../extra_files/player_ranks.png',
colour=self.colour_columns, convert_columns=True)
def process_every_player(self):
"""
Process every player to grab their rank
"""
for player_name in self.api_results.player_information:
self.player_name = player_name
self.player_ranked_info = self.api_results.player_information[player_name]['ranked_info']
self.process_single_player()
self.columns.append(self.player_column)
self.columns.append(self.rank_column)
def process_single_player(self):
"""
Process a single player to grab their rank
"""
self.player_column.append(self.player_name)
try:
self.rank_column.append(f'{self.player_ranked_info["tier"]} {self.player_ranked_info["rank"]}')
# If the player has not been placed in ranked
except KeyError:
self.rank_column.append('UNRANKED')
def set_colour_columns(self):
"""
Set the colour depending on the player ranks
"""
colours = []
for row in self.rank_column:
colours.append(row.split()[0].lower())
self.colour_columns.append(colours)
self.colour_columns.append(colours)
if __name__ == '__main__':
import shelve
from api_queries import APIQueries
api_info = shelve.open('my_api')['api']
tmp = PlayerRanks(api_info)
print()
|
9d7c247e69d6d3a3f39d5124275746beb844ef77 | kaarthikalagappan/sonos-jukebox | /rfidOperations.py | 3,561 | 4.03125 | 4 | #!/usr/bin/env python
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
def writeToTag(data):
""" Function to write to the tag """
reader = SimpleMFRC522()
#Only 48 characters can be written using the mfrc522 library
if len(data) > 48:
print("""Can accept only string less than 48 characters,
but given data is > 48 chars, so writing only first 48 characters""")
print("Place Tag to write")
reader.write((str(data)[:48]))
print("Successfully written")
def start():
""" A method that manages writing to the RFID tag """
flag = True
"""
Grammar of the instruction embedded to the tags (jukebox uses this grammar)
An instruction that starts with '1' means it is a system command (play, pause...)
An instruction that starts with '2' means the following text is a Spotify URI and is followed
by the media name (the media name will be announced when the tag is used)
TODO: an instruction that starts with '3' means the following text is an Apply Music ID
TODO: an instruction that starts with '4' means the following text is an Amazon Music ID
"""
reader = SimpleMFRC522()
while flag:
flag = False
userInput = input("1. System Command\n2. Spotify URI\n3. Read RFID Tag\n")
if int(userInput) == 1:
systemInput = input("\n1. play\n2. pause\n3. playpause\n4. mute/unmute\n5. next\n6. previous\n7. shuffle\n8. clearqueue\n9. toggle night mode\n10. toggle enhanced speech mode\n11. custom\n")
if int(systemInput) == 1:
writeToTag("1;play")
elif int(systemInput) == 2:
writeToTag("1;pause")
elif int(systemInput) == 3:
writeToTag("1;playpause")
elif int(systemInput) == 4:
writeToTag("1;togglemute")
elif int(systemInput) == 5:
writeToTag("1;next")
elif int(systemInput) == 6:
writeToTag("1;previous")
elif int(systemInput) == 7:
writeToTag("1;shuffle")
elif int(systemInput) == 8:
writeToTag("1;clearqueue")
elif int(systemInput) == 9:
writeToTag("1;togglenightmode")
elif int(systemInput) == 10:
writeToTag("1;togglespeechmode")
elif int(systemInput) == 11:
data = input("Custom command (max 48 characters): ")
writeToTag("1;" + data)
else:
print("Invalid selection, please try again")
flag = True
continue
elif int(userInput) == 2:
URI = input("Enter the Spotify URI in the format given by Spotify ('spotify:{track/playlist/NO-ARTIST}:{ID}):'")
mediaName = input("What is the name of the album, track, or playlist: ")
writeToTag("2;" + URI[8:] + ";"+ mediaName)
print("Successfully written")
elif int(userInput) == 3:
print("Place the card on top of the reader")
id, text = reader.read()
print(text)
else:
print("Invalid selection, please try again")
flag = True
continue
userInput = input("""\n1. Write or read another tag\n2. Exit\n""")
if int(userInput) == 1:
flag = True
else:
GPIO.cleanup()
flag = False
if __name__ == '__main__':
start()
|
332db90717d18029d34aa1bbca1ce2d43fdd2a1d | InfiniteWing/Solves | /zerojudge.tw/a780.py | 361 | 3.53125 | 4 | def main():
while True:
try:
s = input()
except EOFError:
break
o, e, a = float(s.split()[0]),float(s.split()[1]),float(s.split()[2])
if(o == 0 and e == 0 and a == 0):
break
m = o / e
f = a / m
print('{0:.2f}'.format(round(m,2)),'{0:.2f}'.format(round(f,2)))
main() |
d3e7eed51bfb47b69c552328c2c584658200f54e | InfiniteWing/Solves | /zerojudge.tw/c082.py | 1,507 | 3.515625 | 4 | alert=[]
class Robot:
def __init__(self,x, y, d,map,alert):
self.x = x
self.y = y
self.alive = 1
self.alert=alert
self.lastLocation = map
if(d=='W'):
self.d = 1
if(d=='N'):
self.d = 2
if(d=='E'):
self.d = 3
if(d=='S'):
self.d = 4
self.map=map
def Action(self,c):
if(c=='L'):
self.d=self.d-1
if(self.d<1):
self.d=4
if(c=='R'):
self.d=self.d+1
if(self.d>4):
self.d=1
if(c=='F'):
self.Walk()
if(self.x>map.x or self.y>map.y or self.x<0 or self.y<0):
if(self.lastLocation in self.alert):
self.x=self.lastLocation.x
self.y=self.lastLocation.y
return 1
self.x=self.lastLocation.x
self.y=self.lastLocation.y
self.alive=0
return 0
return 1
def Walk(self):
self.lastLocation=Location(self.x,self.y)
if(self.d==1):
self.x-=1
if(self.d==2):
self.y+=1
if(self.d==3):
self.x+=1
if(self.d==4):
self.y-=1
class Location:
def __init__(self,x,y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
l=input()
data=l.split()
map=Location(int(data[0]),int(data[1]))
face=["","W","N","E","S"]
while True:
try:
l=input()
except EOFError:
break
data=l.split()
robot=Robot(int(data[0]),int(data[1]),data[2],map,alert)
l=input()
for s in l:
c=robot.Action(s)
if(c==0):
alert.append(robot.lastLocation)
break
if(robot.alive):
print(robot.x,robot.y,face[robot.d],sep=" ")
else:
print(robot.x,robot.y,face[robot.d],"LOST",sep=" ")
|
ec8bf34b460455bd32a2607fa7bab4ee23f15e4a | InfiniteWing/Solves | /zerojudge.tw/c419.py | 274 | 3.546875 | 4 | def main():
while True:
try:
n = int(input())
except EOFError:
break
for i in range(n-1,-1,-1):
ans = ''
for j in range(n):
ans += '*' if(j>=i) else '_'
print(ans)
main() |
e7ef5b40ececc2999a68c6873dde147dd5e725e3 | gahogg/Cracking-the-Coding-Interview-6th-Edition-Answers | /linked_lists/Return kth to last 2.py | 406 | 3.90625 | 4 | # Implement an algorithm to find the kth to last element
# of a singly linked list
from singly_linked_list_node import SinglyLinkedListNode
# O(n) runtime, O(1) space
def kth_to_last(head, k):
cur = head
while True:
k -= 1
if k == 0:
return cur
cur = cur.next
head = SinglyLinkedListNode.linkify([3, 3, 2, 2, 1, 4, 1])
print(head)
print(kth_to_last(head, 8)) |
d5a296818f6bd02b8c03c76b2aa042abbcb4ee17 | AlexanderOHara/programming | /week03/absolute.py | 336 | 4.15625 | 4 | # Give the absolute value of a number
# Author Alexander O'Hara
# In the question, number is ambiguous but the output implies we should be
# dealing with floats so I am casting the input to a flat
number = float (input ("Enter a number: "))
absoluteValue = abs (number)
print ('The absolute value of {} is {}'. format (number, absoluteValue))
|
027ae9177f91395fd0b224ace53b431bad3af815 | BaselECE/Assignment1 | /Question_1/B.py | 435 | 4.09375 | 4 | number1 =eval (input ("enter the first number : "))
number2 =eval (input ("enter the second number : "))
process =input ("enter the process(*,/,+,-):") # ask user to type process
# test what process to do
if (process=='*') :
print (number1*number2)
elif (process=='/') :
print (number1/number2)
elif (process=='+') :
print(number1+number2)
else :
print(number1-number2)
|
11a6a3f01707ad71dd18ea2e9a7bd330791ca7bb | fenghui2018/python | /lesson_9/op_oo.py | 929 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def getup(name):
print(name+' is getting up')
def eat(name):
print(name+' eats something')
def go_to_school(name):
print(name+' goes to school')
def op():
person1 = 'xiaoming'
getup(person1)
eat(person1)
go_to_school(person1)
person2 = 'xiaohong'
getup(person2)
eat(person2)
go_to_school(person2)
class Person:
name = ''
def __init__(self, name):
self.name = name
def getup(self):
print(self.name+' is getting up')
def eat(self):
print(self.name+' eats something')
def go_to_school(self):
print(self.name+' goes to school')
def oo():
person1 = Person('xiaoming')
person1.getup()
person1.eat()
person1.go_to_school()
person2 = Person('xiaohong')
person2.getup()
person2.eat()
person2.go_to_school()
if __name__ == "__main__":
op()
oo()
|
3c4bf7743c3aa9b70eaf040e8ed461bc6c8d9c6f | kyleedwardsny/monty_hall | /monty_hall.py | 627 | 3.6875 | 4 | import random
def monty_hall(size, omniscient, switch):
prize = random.randint(1, size)
choice = random.randint(1, size)
if not omniscient or choice == prize:
unopened = random.randint(1, size)
while unopened == choice:
unopened = random.randint(1, size)
else:
unopened = prize
if switch:
return unopened == prize
else:
return choice == prize
win = 0
lose = 0
for i in range(10000):
if monty_hall(3, True, True):
win += 1
else:
lose += 1
print("Win: %i" % win)
print("Lose: %i" % lose)
print("Total: %i" % (win + lose))
|
607120b19311605f418307cffc49981af62672c5 | miker7790/Arcade | /manager/games/hangman.py | 3,456 | 3.734375 | 4 | import os
import csv
import random
class HANGMAN:
def __init__(self, word=None, attempts=None):
self.word = word.lower() if word else self._selectRandomWord()
self.remainingAttempts = attempts if attempts else self._getInitialRemainingAttempts()
self.remainingLetters = list(self.word)
self.allGuesses = []
self.correctGuesses = []
self.incorrectGuesses = []
self.lastGuess = None
self._maskWord()
self._updateGameStatus()
# sets rules/ initalizes game
def playGame(self):
while self.remainingAttempts > 0 and len(self.remainingLetters) > 0:
print('Unknown Word: {}'.format(self.maskedWord))
print('Current Available Attempts: {}'.format(self.remainingAttempts))
while True:
guess=input('Please guess a single lowercase letter: ')
if guess and len(guess) == 1 and guess.isalpha() == True:
break
self.lastGuess = guess.lower()
self._guessLetter()
for key, item in self.gameStatus.items():
print('{}: {}'.format(key, item))
print()
self.gameStatus['word'] = self.word
self.gameStatus['win'] = True if len(self.remainingLetters) == 0 else False
message = 'Congrats, the word guessed was: {}' if len(self.remainingLetters) == 0 else 'You lost, you did not guess the word which was: {}'
print(message.format(self.word), '\n')
return(self.gameStatus)
# updates word after each guess
def _guessLetter(self):
if self.lastGuess in self.remainingLetters:
self._correctGuess()
elif self.lastGuess not in self.allGuesses:
self._incorrectGuess()
self.allGuesses.append(self.lastGuess)
self._updateGameStatus()
# updates word/ records guess
def _correctGuess(self):
self.remainingLetters = [i for i in self.remainingLetters if i != self.lastGuess]
self.correctGuesses.append(self.lastGuess)
self.remainingAttempts = self.remainingAttempts - 1
self._maskWord()
# records guess
def _incorrectGuess(self):
self.incorrectGuesses.append(self.lastGuess)
self.remainingAttempts = self.remainingAttempts - 1
# provides game details as you play
def _updateGameStatus(self):
self.gameStatus = {
'correctGuesses': self.correctGuesses,
'incorrectGuesses': self.incorrectGuesses,
'lastGuess': self.lastGuess,
}
# masks the word and reveals it for each correct guess
def _maskWord(self):
self.maskedWord = ''.join([' _ ' if i in self.remainingLetters else i for i in self.word])
# selects random word from file of words
def _selectRandomWord(self):
with open(os.path.dirname(os.path.abspath(__file__)) + '/gameInput/hangman/words.csv') as file:
words = list(csv.reader(file))
randomWord = random.choice(words)[0].lower()
return randomWord
# initializes the amount of attemps for the game based on the length of the word
def _getInitialRemainingAttempts(self):
return len(self.word) + 3 |
d50309f43cb772cdc2f212c0b6437a1c444a24a3 | tanmay-raichur/assignment-one | /morrisons/csv_converter.py | 4,728 | 3.84375 | 4 | """ This is a CSV file converter module.
It reads CSV file and creates a json file
with parent-child structure.
"""
import sys
import pandas as pd
import json
import logging as log
log.basicConfig(level=log.INFO)
def csv_to_json(ip_path: str, op_path: str) -> None:
""" Converts given csv file into json file.
Csv file needs to be in agreed format, below points are important
1. Base URL is first column and need not be displayed in the output Json
2. Each level of data will have 3 columns Label, ID and Link in said order
3. File can have any number of columns or rows
4. Duplicate IDs at any level will be ignored
5. First row is the header
:parameter
ip_path : csv filename or path to the file including filename
op_path : json filename or path to the file including filename
"""
try:
file_data, headers = _read_edit_data(ip_path)
NO_ATTR = 3
no_levels = int(len(headers)/NO_ATTR)
list_levels = [['label', 'id', 'link'] for i in range(no_levels)]
all_items = _filedata_to_flatlist(file_data, no_levels,
list_levels, NO_ATTR)
final = _flatlist_to_tree(all_items, no_levels)
_create_json(final, op_path)
except FileNotFoundError:
log.error('The CSV data file is missing.')
except PermissionError:
log.error('The required permissions missing on CSV file.')
except Exception:
log.error('Some other error occurred.', exc_info=True)
def _read_edit_data(ip_path: str) -> list:
""" This function will read the csv data and
make necessary transformations to the data frame
"""
file_data = pd.read_csv(ip_path)
headers = list(file_data.columns)
headers.pop(0)
file_data = file_data[headers[:]]
file_data.dropna(subset=[headers[0]], inplace=True)
return file_data, headers
def _filedata_to_flatlist(file_data: list, no_levels: int,
list_levels: list, NO_ATTR: int) -> list:
""" This function creates a list with flat structure. """
all_items = []
id_list = []
curr_id = 0
for line in file_data.values:
level_grp = _split_line(line, no_levels, NO_ATTR)
for level in range(0, (no_levels)):
data = {list_levels[level][i]: level_grp[level][i] for i in range(NO_ATTR)}
data['children'] = []
prev_id = curr_id
curr_id = data['id']
id_isnull = (curr_id != curr_id)
id_exists = (curr_id in id_list)
if not id_exists and not id_isnull:
data['id'] = int(data['id'])
if level == 0:
all_items.append(data.copy())
else:
data['level'] = level
data['parent'] = prev_id
all_items.append(data.copy())
id_list.append(curr_id)
data.clear()
return all_items
def _split_line(line: list, no_levels: int, NO_ATTR: int) -> list:
""" This function splits the line into one list per level. """
level_grp = []
for level in range(no_levels):
level_grp.append(line[level * NO_ATTR:(level + 1) * NO_ATTR])
return level_grp
def _flatlist_to_tree(all_items: list, no_levels: int) -> list:
""" This function will convert flat list into
a tree structure as requested.
"""
pop_list = []
final = []
for j in reversed(range(1, no_levels)):
for i in range(len(all_items)):
if 'level' in all_items[i].keys() and all_items[i]['level'] == j:
pop_list.append(i)
data = all_items[i].copy()
parent = all_items[i]['parent']
for k in range(len(all_items)):
if all_items[k]['id'] == parent:
data.pop('level')
data.pop('parent')
all_items[k]['children'].append(data.copy())
break
for i in range(len(all_items)):
if 'level' not in all_items[i].keys():
final.append(all_items[i])
return final
def _create_json(final: list, op_path: str) -> None:
""" Creates a json file at output path. """
json_dump = json.dumps(final)
json_str = json.loads(json_dump, parse_int=str)
final_json = json.dumps(json_str, indent=4)
with open(op_path, 'w') as outfile:
outfile.write(final_json)
log.info("Json file successfully created.")
if __name__ == "__main__":
csv_to_json(sys.argv[1],sys.argv[2])
|
a43ea1df7cbf7ab62ae50e8385d8d70c127d16b4 | PhillipDHK/Recommender | /RecommenderMaker.py | 1,488 | 3.546875 | 4 | '''
@author: Phillip Kang
'''
import RecommenderEngine
def makerecs(name, items, ratings, numUsers, top):
'''
This function calculates the top recommendations and returns a two-tuple consisting of two lists.
The first list is the top items rated by the rater called name (string).
The second list is the top items not seen/rated by name (string)
'''
recommend = RecommenderEngine.recommendations(name, items, ratings, numUsers)
recommend = recommend[:top]
lst = []
lst1 = []
for i in RecommenderEngine.recommendations(name, items, ratings, numUsers):
if ratings[name][items.index(i[0])] == 0:
lst.append(i)
if ratings[name][items.index(i[0])] != 0:
lst1.append(i)
return lst1[:top], lst[:top]
if __name__ == '__main__':
name = 'student1367'
items = ['127 Hours', 'The Godfather', '50 First Dates', 'A Beautiful Mind',
'A Nightmare on Elm Street', 'Alice in Wonderland',
'Anchorman: The Legend of Ron Burgundy',
'Austin Powers in Goldmember', 'Avatar', 'Black Swan']
ratings = {'student1367': [0, 3, -5, 0, 0, 1, 5, 1, 3, 0],
'student1046': [0, 0, 0, 3, 0, 0, 0, 0, 3, 5],
'student1206': [-5, 0, 1, 0, 3, 0, 5, 3, 3, 0],
'student1103': [-3, 3, -3, 5, 0, 0, 5, 3, 5, 5]}
numUsers = 2
top = 3
print(makerecs(name, items, ratings, numUsers, top))
|
87b052581e7ad1fe51f8e06fe1658b9d3d69ee26 | vdeangelis/Flask | /routes.py | 936 | 3.59375 | 4 | from flask import Flask, url_for, request, render_template
from app import app
# server/
@app.route('/')
def hello():
createLink = "<a href='" + url_for('create') + "'>Create a question</a>"
return """<html>
<head>
<title>Ciao Mondo!!'</title>
</head>
<body>
""" + createLink + """
<h1>Hello Vitto!</h1>
</body>
</html>"""
#server/create
@app.route('/create')
def create():
if request.method == 'GET':
#send user the format
return render_template('CreateQuestion.html')
elif request.method == 'POST':
#read form and data and save it
title = request.form['title']
answer = request.form['answer']
question = request.form['question']
#Store data in data store
return render_tempalte('CreatedQuestion.html',question = question)
else:
return "<h2>Invalid request</h2>"
#server/question/<tile>
@app.route('/question/<title>')
def question(title):
return "<h2>" + title + "</h2>"
|
6859cc2ba2ed3ba969b42861bc701dd1d0ca59fe | Neraverin/codewars-python | /Simple Encryption #1 - Alternating Split/main.py | 2,128 | 3.609375 | 4 | import unittest
class KataTest(unittest.TestCase):
@staticmethod
def decrypt(encrypted_text, n):
for i in range(n):
first = encrypted_text[:int(len(encrypted_text)/2)]
second = encrypted_text[int(len(encrypted_text)/2):]
if len(first) < len(second):
first += ' '
encrypted_text = ''.join(i for j in zip(second, first) for i in j).rstrip()
return encrypted_text
@staticmethod
def encrypt(text, n):
for i in range(n):
text = text[1::2] + text[0::2]
return text
def test_empty_case(self):
self.assertEqual(self.encrypt("", 0), "")
self.assertEqual(self.decrypt("", 0), "")
self.assertEqual(self.encrypt(None, 0), None)
self.assertEqual(self.decrypt(None, 0), None)
def test_encrypt_case(self):
self.assertEqual(self.encrypt("This is a test!", 0), "This is a test!")
self.assertEqual(self.encrypt("This is a test!", 1), "hsi etTi sats!")
self.assertEqual(self.encrypt("This is a test!", 2), "s eT ashi tist!")
self.assertEqual(self.encrypt("This is a test!", 3), " Tah itse sits!")
self.assertEqual(self.encrypt("This is a test!", 4), "This is a test!")
self.assertEqual(self.encrypt("This is a test!", -1), "This is a test!")
self.assertEqual(self.encrypt("This kata is very interesting!", 1), "hskt svr neetn!Ti aai eyitrsig")
def test_decrypt_case(self):
self.assertEqual(self.decrypt("This is a test!", 0), "This is a test!")
self.assertEqual(self.decrypt("hsi etTi sats!", 1), "This is a test!")
self.assertEqual(self.decrypt("s eT ashi tist!", 2), "This is a test!")
self.assertEqual(self.decrypt(" Tah itse sits!", 3), "This is a test!")
self.assertEqual(self.decrypt("This is a test!", 4), "This is a test!")
self.assertEqual(self.decrypt("This is a test!", -1), "This is a test!")
self.assertEqual(self.decrypt("hskt svr neetn!Ti aai eyitrsig", 1), "This kata is very interesting!")
if __name__ == "__main__":
unittest.main()
|
ddb2e24756117bf6869a1b10b93237566c9d1eae | LavaTime/Envelopes | /forthStrategy.py | 1,767 | 3.78125 | 4 | from envelope import Envelope
class N_max_strategy:
"""
can run the forth strategy on a set of envelops
Attributes:
envelops (list): list of envelops to run the strategy one
N (int): holds the N for the strategy
"""
def __init__(self, envelops):
self.envelops = envelops
self._N = None
@property
def N(self):
return self._N
@N.setter
def N(self, newN):
if newN is int:
self._N = newN
else:
print('N can only be an integer')
def display(self):
return "This is a strategy that opens N - 1 evelopes are are bigger than the first one"
def play(self):
"""
performs the strategy using the N and the object
Args:
self: the object
Returns:
None
Raises:
None
Warnings:
self.N must have been set before calling
"""
self.perform_strategy(self.N)
def perform_strategy(self, counter):
"""
perform the forth strategy, that opens envelopes that are bigger with some count
Args:
counter (int): how many bigger envelops to open before stopping
Returns:
None
"""
n_biggest = [self.envelops[0].money]
i = 0
while len(n_biggest) < counter:
if i == len(self.envelops):
print('Not enough numbers')
break
if self.envelops[i].money > n_biggest[-1]:
n_biggest.append(self.envelops[i].money)
i += 1
print(str(n_biggest))
#envs = []
#for i in range(10000000):
# envs.append(Envelope())
#stra = N_max_strategy(envs)
#stra.N = 100
#stra.play()
|
bfd3fe14514baab0e66c20b18a6ff2e098781415 | hamzahibrahim/Projects-with-python | /Tkinter/YouTube video downloader.py | 1,236 | 3.5625 | 4 | from pytube import YouTube
print('===================')
# =========================
rerun = "y"
while rerun == "y":
try:
url = input('Enter the YouTube link for the video u want: \n')
the_video = YouTube(url)
# =========================
print('===================')
print('your video title: ', the_video.title)
# =========================
print('===================')
choices = the_video.streams.filter(progressive=True)
print('please choose one:','\n==================')
for i in choices:
print(i)
user_choice = int(input('Please enter your choice (by nubers(1,2,3,....)): '))
the_choice = choices[user_choice-1]
# =========================
print('===================')
print('Please wait until it finsh downloding ......')
the_choice.download()
# =========================
print('Done\' -_- \' (the video is installed in the folder you are in)')
print('===================')
except:
print('Sorrry somethng went wrong')
print('===================')
rerun = input("Enter y to rerun or any thing else to end: ")
print('===================')
|
faf268ea926783569bf7e2714589f264ed4f3554 | Teddy-Sannan/ICS3U-Unit2-02-Python | /area_and_perimeter_of_circle.py | 606 | 4.1875 | 4 | #!/usr/bin/env python3
# Created by: Teddy Sannan
# Created on: September 16
# This program calculates the area and perimeter of a rectangle
def main():
# main function
print("We will be calculating the area and perimeter of a rectangle")
print("")
# input
length = int(input("Enter the length (mm): "))
width = int(input("Enter the width (mm): "))
# process
perimeter = 2 * (length + width)
area = length * width
print("")
# output
print("Perimeter is {} mm".format(perimeter))
print("Area is {} mm^2".format(area))
if __name__ == "__main__":
main()
|
c3c084946fd1e0634b9670fc1ef058fbc4c98045 | theguythatdoes/coding-assignments | /CreateAcronym.py | 381 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 15:34:58 2020
@author: reube
"""
def acronym(phrase):
y=phrase
phrase=phrase.split(' ')
mystring=len(phrase)
s=''
for k in range(0,mystring):
n=phrase[k]
s+=n[0]
return s
if __name__=="__main__":
print(acronym("dog ate my homework"))
|
3c337c5a29d43444e3b4c51af2dc22ea4284c5e7 | theguythatdoes/coding-assignments | /EatingGood.py | 499 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 27 15:43:53 2020
@author: reube
"""
def howMany(meals,restaurant):
wyt=[]
rest=[]
numrest=0
for bob in range(len(meals)):
if meals[bob] not in rest:
rest+=[meals[bob] ]
for k in range (len(rest)):
wyt+=rest[k].split(":")
y=wyt.count(restaurant)
return y
if __name__==("__main__"):
print(howMany(["Sue:Elmos", "Sue:Elmos", "Sue:Pitchforks"],"Elmos"))
|
a3908afeefdba6d570fdbea0dd5a5b20112a1593 | hugessen/Advent-of-Code-2016 | /Code/d3q1.py | 628 | 3.53125 | 4 | def is_valid(vals):
max_side = max(vals)
return sum(vals) > (2 * max_side)
pinput = open('Inputs/d3.txt').read().split('\n')
num_triangles = 0
for line in pinput:
sides = [int(side) for side in line.split()]
if is_valid(sides):
num_triangles += 1
print num_triangles |
17d9bf545ec17e744a53e7adc120100d293f3f40 | hugessen/Advent-of-Code-2016 | /Code/d1q1.py | 951 | 3.609375 | 4 | def turn(left_or_right):
global c_dir
if c_dir[X] == 1:
c_dir = [0, -1*left_or_right]
elif c_dir[X] == -1:
c_dir = [0, 1*left_or_right]
elif c_dir[Y] == 1:
c_dir = [1*left_or_right, 0]
elif c_dir[Y] == -1:
c_dir = [-1*left_or_right, 0]
pinput = open('Inputs/d1.txt').read().split(", ")
X = 0
Y = 1
LEFT = -1
RIGHT = 1
c_dir = [0,1]
pos = [0,0]
visited = dict()
for move in pinput:
if move[0] == 'L':
turn(LEFT)
elif move[0] == 'R':
turn(RIGHT)
for i in range(int(move[1:])):
pos[X] += c_dir[X]
pos[Y] += c_dir[Y]
key = str(pos[X] + pos[Y])
if key in visited:
found = False
for visited_pos in visited[key]:
if visited_pos == tuple(pos):
found = True
print "Distance to closest double visit = %d" % (abs(pos[X]) + abs(pos[Y]))
break
if found is False:
visited[key].append( (pos[X], pos[Y]) )
else:
visited[key] = [(pos[X], pos[Y])]
print "Distance = %d" % (abs(pos[X]) + abs(pos[Y])) |
c4a724e06eda95e28c9ad081698f1c08f0272467 | tsixit/python | /PycharmProjects/formation/poo.py | 10,517 | 3.75 | 4 | unite1 = {
'nom': 'méchant',
'x': 12,
'y': 7,
'vie': 42,
'force': 9
}
unite2 = {
'nom': 'gentil',
'x': 11,
'y': 7,
'vie': 8,
'force': 3
}
def attaque(attaquant, cible):
print("{} attaque {} !".format(attaquant['nom'], cible['nom']))
cible['vie'] -= attaquant['force']
attaque(unite1, unite2)
print(unite2)
class CategorieOuModele:
pass
class Unite(object):
"""
Cette classe représente une unité dans un jeu que nous vendons 1 milliards d'euros / pièce.
"""
# nom = None
# x = None
# y = None
# vie = None
# force = None
VIE_MAX = 100
def __init__(self, nom, x, y, vie, force):
"""
Constructeur de la classe unité.
:param nom: nom de l'unité
:type nom: str
:param x: abscisse de l'unité
:type x: int
:param y: ordonnée de l'unité
:type y: int
:param vie: points de vie de l'unité
:type vie: int
:param force: force de l'unité
:type force: int
"""
super().__init__()
self._nom = nom # attribut protégé
self.x = x
self.y = y
self.vie = vie
self.force = force
self.__fichier = 'unite.json' # attribut privé
def attaque(self, cible):
"""
Cette méthode sert à attaquer une unité.
:param cible: cible de l'attaque
:type cible: Unite
"""
print("{} attaque {} !".format(self._nom, cible._nom))
cible.vie -= self.force
def se_repose(self):
"""
Sert à regagner un point de vie.
"""
print("{} se repose et regagne 1 point de vie.".format(self._nom))
self.vie += 1
def __str__(self):
"""
Renvoie une représentation de l'unité sous forme de chaîne de caractères.
:return: la chaîne de caractère représentant l'unité
:rtype: str
"""
return "<Unite nom:{} x:{} y:{} vie:{} force:{}>".format(self._nom, self.x, self.y, self.vie, self.force)
def __lt__(self, autre): # lt = lower than <
return self.vie < autre.vie
def __gt__(self, autre): # gt = greater than >
return self.vie > autre.vie
def __le__(self, autre): # le = lower or equal <=
return self.vie <= autre.vie
def __ge__(self, autre): # ge = greater or equal >=
return self.vie >= autre.vie
def __eq__(self, autre): # eq = equals
return self.vie == autre.vie
def __ne__(self, autre): # ne = not equals
return self.vie != autre.vie
mechant = Unite('méchant', 12, 7, 42, 9) # instanciation de l'objet
# mechant est une instance de la classe Unite
# mechant.nom = 'méchant'
# mechant.x = 12
# mechant.y = 7
# mechant.vie = 42
# mechant.force = 9
mechant.defense = 5
print(mechant.defense)
gentil = Unite('gentil', 11, 7, 8, 3)
# print(gentil.defense)
gentil.attaque(mechant)
print(mechant.vie)
Unite.attaque(gentil, mechant)
print(mechant.vie)
mechant.se_repose()
# méchant se repose et regagne 1 point de vie.
print(mechant.vie)
print(mechant)
print(str(mechant))
print(mechant.__str__())
chaine = mechant.__str__()
# gentil.attaque(123)
# >>> import poo
# >>> help(poo)
# >>> help(poo.Unite)
# >>> help(poo.Unite.attaque)
# >>> help(print)
# >>> poo.Unite.__doc__
# >>> poo.Unite.attaque.__doc__
print(dir()) # liste de toutes les variables de notre programme
print(dir(mechant))
print(Unite.__lt__)
print(mechant < gentil)
print(mechant.__dict__)
# Héritage
# ========
# class Guerrier(Unite, Tank, Affichable):
class Guerrier(Unite):
# Unite est la superclasse de Guerrier
def __init__(self, nom, x, y, vie, force, rage=100):
# super().__init__(nom, x, y, vie, force) # Python 3
# Tank.__init__(self)
# Affichable.__init__(self)
Unite.__init__(self, nom, x, y, vie, force)
self.rage = rage
# self.__fichier = 'guerrier.json'
# print("***", dir(self))
# print(self.__fichier)
# print(self._Unite__fichier) # déconseillé
def __str__(self):
return "<Guerrier nom:{} x:{} y:{} vie:{} force:{} rage:{}>".format(self._nom, self.x, self.y, self.vie, self.force, self.rage)
def frappe_heroique(self, cible):
"""
Exécute une frappe héroïque.
:param cible: cible de la frapep
:type cible: Unite
"""
# if not isinstance(cible, Unite):
# print("*** La cible n'est pas une Unite !")
# return
if self.rage < 20:
print("*** Echec de la frappe héroïque !")
return
print("{} exécute une frappe héroïque sur {} !".format(self._nom, cible._nom))
cible.vie -= self.force * 2
self.rage -= 20
conan = Guerrier('Conan', 11, 8, 10000, 20, 50)
conan.attaque(mechant)
print(mechant)
print(conan)
conan.frappe_heroique(mechant)
conan.frappe_heroique(mechant)
conan.frappe_heroique(mechant)
print(mechant)
# Une frappe héroïque consomme 20 de rage
# 1) Si le guerrier n'a pas assez de rage pour exécuter la frappe
# héroïque, afficher un message d'erreur, et annuler la frappe.
# 2) Gérer la consommation de la rage.
# 3) Afficher la rage dans __str__
# 4) Par défaut, un guerrier a 100 de rage.
# Attributs publics, protégés, privés
# ===================================
print(conan._nom) # déconseillé
#conan._nom = 'fichier.json'
print(conan._Unite__fichier) # déconseillé
hercule = Guerrier('Hercule', 1, 2, 3, 4)
hercule.frappe_heroique(conan)
print(conan)
# isinstance
# ==========
print(isinstance(gentil, Unite)) # permet de tester l'héritage
print(isinstance(gentil, Guerrier))
print(isinstance(conan, Unite))
print(isinstance(conan, Guerrier))
print(type(conan))
print(type(conan) is Guerrier) # test s'ils sont de même type
print(type(conan) is Unite)
# Classe de service
# =================
# Sert à grouper les fonctions
class TextFormat:
def souligner(self, texte):
print(texte)
print('=' * len(texte))
@staticmethod # permet de ne pas mettre self
def encadrer(texte):
print('#' * (len(texte) + 4))
print('#', texte, '#')
print('#' * (len(texte) + 4))
def espacer(self, texte):
caracteres = list(texte)
# print(caracteres)
print(' '.join(caracteres))
t = TextFormat()
t.souligner("Appel de souligner()")
t.encadrer("Est-ce que ça marche ?")
TextFormat.encadrer("Texte à encadrer")
# Agrégation
# ==========
class Familier:
proprietaire = None # agrégation
chien = Familier()
chien.proprietaire = conan
class Personnage:
inventaire = [] # agrégation
def ramasse(self, accessoire):
self.inventaire.append(accessoire)
class Accessoire:
pass
harry = Personnage()
baguette = Accessoire()
harry.ramasse(baguette)
# Les exceptions : sont des class
# ===============
# 1/0 # ZeroDivisionError: division by zero
# l = [1, 2, 3]
# l[100] # IndexError: list index out of range
try:
print("On va faire quelque chose de mal :")
1 / 0
print("Ceci ne s'affiche jamais.")
except ArithmeticError as e:
print("*** Vous avez fait une erreur arithmétique !")
print(e)
print(type(e))
# except ZeroDivisionError:
# print("*** Vous avez divisé par zéro !")
except:
print("*** Une exception s'est déclenchée, ceci capture toute les excéptions !")
# protocole = 'gsfdgfsdgsd'
protocole = 'http'
if protocole not in ('http', 'https', 'ftp', 'ssh'):
raise ValueError("Protocole non supporté !") # Déclenche une exception crée à la main
# Le bubbling avec les exceptions
# ===============================
def a():
b()
def b():
c(10, 0)
def c(dividende, diviseur):
f = None
try:
f = open('fichier.txt') # dans try s'il y a une excéption, alors les autres blocs ne seront pas exécute,
dividende / diviseur # direcement dans except, try, except et finally vont ensemble
# f.close()
except IndexError:
print("*** Cette fois-ci, vous avez dépassé les bornes !")
else:
print("Tout s'est bien passé, aucune exception n'a été déclenchée.")
finally:
print("Ceci s'exécute tout le temps à la sortie du bloc de capture d'exception.")
f.close()
try:
a()
except ZeroDivisionError:
print("*** Vous avez divisé par zéro !")
# Créer nos propres exceptions
# ============================
class ProblemeMajeurError(Exception): # Exception est une class de base python
pass
try:
raise ProblemeMajeurError()
except ProblemeMajeurError:
print("*** Un problème grave est survenu !!!")
# Les accesseurs (getter, setter)
# ===============================
# C'est pour accéder aux attibuts privée
class Personnage:
def __init__(self, nom, age):
self.__nom = nom
self.__age = age
# Accesseurs façon Java et PHP :
def set_nom(self, valeur):
if type(valeur) is not str:
raise ValueError("Cher collègue, tu as écrit n'importe quoi !")
self.__nom = valeur
def get_nom(self):
return "Monsieur " + self.__nom
# Accesseur façon Python :
@property # decorateur de base de python
def age(self):
print("Appel du getter de age...")
return self.__age
@age.setter
def age(self, valeur):
print("Appel du setter de age...")
self.__age = valeur
harry = Personnage('Harry Potter', 12)
harry.set_nom('Voldemort')
print(harry.get_nom())
# harry.set_nom(123)
print(harry.age)
harry.age = 13
# Décorateurs
#============
from time import time
def decorateur(autre_fonction):
def fonction_de_remplacement():
print("Exécuter quelque chose avant...")
start = time()
autre_fonction()
end = time()
print("Exécuter quelque chose après...")
print("Nombre de secondes pour exécuter la fonction :", end - start)
return fonction_de_remplacement
@decorateur # appel du decorateur sur la fonction compteur
def compteur():
for i in range(5):
print(i)
#compteur = decorateur(compteur) # une autre facon d'appeler le décorateur
compteur()
# Contextes
# =========
class Chrono:
def __enter__(self):
self.start = time()
def __exit__(self, *exc):
self.end = time()
print(self.end - self.start)
with Chrono() as c:
for i in range(1000000):
print(i)
|
38c35c919afd61c749c0c521943d9fd821a44818 | Tcake/py_leetcode | /leetcode/Guess Number Higher or Lower II.py | 686 | 3.5 | 4 | class Solution:
def getMoneyAmount(self, n):
"""
:type n: int
:rtype: int
"""
left = 1
right = n
result = 0
while right - left >= 6:
left = (right + left) // 2
result += left
if left is not 1:
left += 1
tmp = right - left
if tmp == 1:
result += left
elif tmp == 2:
result += left + 1
elif tmp == 3:
result += left * 2 + 2
elif tmp == 4:
result += left * 2 + 4
elif tmp == 5:
result += left * 2 + 6
return result
a = Solution()
print(a.getMoneyAmount(7))
|
599b529c6e4cfc0e0ce04753c26c2bd543ef3dcb | logotip123/py_merge | /merge.py | 799 | 4.03125 | 4 | """Two list sort module"""
from typing import List
def merge(array1: List[int], array2: List[int]) -> List[int]:
"""
Two list sort function
:param array1: first list for sort
:param array2: second list for sort
:return: array1 + array2 sorted list
"""
array1index = 0
array2index = 0
result = []
while True:
if array1index >= len(array1):
result.extend(array2[array2index:])
break
if array2index >= len(array2):
result.extend(array1[array1index:])
break
if array1[array1index] < array2[array2index]:
result.append(array1[array1index])
array1index += 1
else:
result.append(array2[array2index])
array2index += 1
return result
|
95ecfbc9b444f09586e7fa1dbc8a752e846ef8f7 | jaaaaaaaaack/xpilot-bots | /old-files/evstrat/neuralNet.py | 5,221 | 3.734375 | 4 | # Jack Beal and Lydia Morneault
# COM-407 CI
# 2018-05-07 Final project
# Based on neuralnet.py by Jessy Quint and Rishma Mendhekar
from random import*
import math
def sigmoid(x):
return (1/(1+math.exp(-1*x)))
def perceptron(thing, weights):
summation = 0 # initialize sum
counter = 0 # variable to assign correct weight to correct bit
for digit in thing: # for each bit
summation += (int(digit)*weights[counter]) # calculate weighted sum
counter += 1
summation += (-1 * weights[-1]) # subtract the threshold in order to shift the decision boundary
output = sigmoid(summation) # keep output between 0 and 1
return output
# perceptron for hidden layer to output neuron
# inputs into output neuron are float values that we do not want to round to integers
def perceptron2(thing, weights):
summation = 0 # initialize sum
counter = 0 # variable to assign correct weight to correct bit
for digit in thing: # for each bit
summation += digit*weights[counter] # calculate sum based on weights
counter += 1
summation += (-1 * weights[-1]) # subtract the threshold in order to shift the decision boundary
output = sigmoid(summation)
return output
def trainingPercepton(iterations):
learningRate = 0.1 # Epsilon
weightsA = [] # weights for each input for neuron A
weightsB = [] # '' for neuron B
weightsC = [] # '' for neuron C
# Weights from hidden layer to output neuron and threshold
weightFinal = [round(uniform(-0.48, 0.48), 2), round(uniform(-0.48, 0.48), 2), round(uniform(-0.48, 0.48), 2), round(uniform(-0.48, 0.48), 2)]
# Assign random initial weights, with values between -r and +r where r = 2.4/# of inputs see p.179
for w in range(4):
weightsA.append(round(uniform(-0.48, 0.48), 2))
weightsB.append(round(uniform(-0.48, 0.48), 2))
weightsC.append(round(uniform(-0.48, 0.48), 2))
#print(weightsA)
#print(weightsB)
trainingInput = [ ['000', 1],
['025', 1],
['050', 1],
['075', 0.9],
['100', 0.8],
['125', 0.7],
['150', 0.7],
['175', 0.6],
['200', 0.6],
['225', 0.5],
['250', 0.5],
['275', 0.4],
['300', 0.3],
['325', 0.2],
['350', 0.1],
['375', 0],
['400', 0],
['425', 0],
['450', 0],
['500', 0]]
for j in range(iterations): # Loop through the list, number of loops depends on user input
outputList = [] # Print output list to see accuracy
for train in trainingInput:
outputA = perceptron(train[0],weightsA) # output for neuron A
outputB = perceptron(train[0],weightsB) # output for neuron B
outputC = perceptron(train[0],weightsC) # output for neuron C
outputsABC = [outputA, outputB, outputC] # inputs for the final neuron
finalOutput = perceptron2(outputsABC, weightFinal)
# Error is calculated by subtracting the program output from the desired output
error = train[1] - finalOutput
# Calculate error gradients
# error gradient for output layer based on formula
errorGradient = finalOutput * (1-finalOutput) * error
# Add the previous neuron's weight to (learning rate * input * error gradient)
for i in range(len(weightFinal)-1):
weightFinal[i] += (learningRate * outputsABC[i] * errorGradient)
weightFinal[3] = weightFinal[3] + (learningRate * -1 * errorGradient) # for threshold
# Error gradient for hidden layer
# Don't have desired outputs for hidden layer, therefore cannot calculate error
# Instead of error, use sumGradient = error gradient for output neuron * weight of the input
sumGradientA = (errorGradient * weightFinal[0])
sumGradientB = (errorGradient * weightFinal[1])
sumGradientC = (errorGradient * weightFinal[2])
hiddenGradientA = (outputA * (1-outputA) * sumGradientA)
hiddenGradientB = (outputB * (1-outputB) * sumGradientB)
hiddenGradientC = (outputC * (1-outputC) * sumGradientC)
# Using error gradients, update the weights
for i in range(len(weightsA)-1):
weightsA[i] += (learningRate * int(train[0][i]) * hiddenGradientA)
weightsB[i] += (learningRate * int(train[0][i]) * hiddenGradientB)
weightsC[i] += (learningRate * int(train[0][i]) * hiddenGradientC)
weightsA[3] += (learningRate * -1 * hiddenGradientA)
weightsB[3] += (learningRate * -1 * hiddenGradientB)
weightsC[3] += (learningRate * -1 * hiddenGradientC)
outputList.append([])
outputList[-1].append(train[0])
outputList[-1].append(finalOutput)
# for temp in outputList:
# print(temp[0], "->", temp[1])
|
9e0cd81ea1e65c22f141d4d08e4177860876a5c6 | kutakieu/AI-class | /Assignment-1-Search-master-63318a771170bfa64d905052bc0e733cfd3b576e/code/heuristics.py | 4,813 | 3.828125 | 4 | # heuristics.py
# ----------------
# COMP3620/6320 Artificial Intelligence
# The Australian National University
# For full attributions, see attributions.txt on Wattle at the end of the course
""" This class contains heuristics which are used for the search procedures that
you write in search_strategies.py.
The first part of the file contains heuristics to be used with the algorithms
that you will write in search_strategies.py.
In the second part you will write a heuristic for Q4 to be used with a
MultiplePositionSearchProblem.
"""
#-------------------------------------------------------------------------------
# A set of heuristics which are used with a PositionSearchProblem
# You do not need to modify any of these.
#-------------------------------------------------------------------------------
def null_heuristic(pos, problem):
""" The null heuristic. It is fast but uninformative. It always returns 0.
(State, SearchProblem) -> int
"""
return 0
def manhattan_heuristic(pos, problem):
""" The Manhattan distance heuristic for a PositionSearchProblem.
((int, int), PositionSearchProblem) -> int
"""
# print("mahattan")
return abs(pos[0] - problem.goal_pos[0]) + abs(pos[1] - problem.goal_pos[1])
def euclidean_heuristic(pos, problem):
""" The Euclidean distance heuristic for a PositionSearchProblem
((int, int), PositionSearchProblem) -> float
"""
return ((pos[0] - problem.goal_pos[0]) ** 2 + (pos[1] - problem.goal_pos[1]) ** 2) ** 0.5
#Abbreviations
null = null_heuristic
manhattan = manhattan_heuristic
euclidean = euclidean_heuristic
#-------------------------------------------------------------------------------
# You have to implement the following heuristics for Q4 of the assignment.
# It is used with a MultiplePositionSearchProblem
#-------------------------------------------------------------------------------
#You can make helper functions here, if you need them
def bird_counting_heuristic(state, problem) :
position, yellow_birds = state
heuristic_value = 0
""" *** YOUR CODE HERE *** """
heuristic_value = len(yellow_birds)
# print(heuristic_value)
return heuristic_value
bch = bird_counting_heuristic
def MHdis(pos1, pos2):
return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
def ECdis(pos1, pos2):
return ((pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2) ** 0.5
def every_bird_heuristic(state, problem):
"""
(((int, int), ((int, int))), MultiplePositionSearchProblem) -> number
"""
position, yellow_birds = state
yellow_birds = list(yellow_birds)
heuristic_value = 0
if len(yellow_birds) == 0:
return heuristic_value
""" *** YOUR CODE HERE *** """
#find nearest yellow bird and add the distance to the heuristic value
nearest_yb_distance = 10000
nearest_yb = None
for yb in yellow_birds:
distance = problem.maze_distance(yb, position)
if distance < nearest_yb_distance:
nearest_yb = yb
nearest_yb_distance = distance
heuristic_value += nearest_yb_distance
"""calculate Minimum Spanning Tree as a heuristic function"""
#prepare a dictionary {yellow_bird : [distances_between_other_yellow_birds, yellow_bird_position]}
dis_YandYs = {}
for yb1 in yellow_birds:
dis_YandY = []
for yb2 in yellow_birds:
if yb1 != yb2:
distance = problem.maze_distance(yb1, yb2)
dis_YandY.append([distance, yb2])
dis_YandY.sort()
dis_YandYs[yb1] = dis_YandY
# choose yellow_birds until the tree covers the all unvisited yellow_birds
YB_set = set()
YB_set.add(nearest_yb)
"""repeat finding nearest yellow bird from YB_set which is a set of yellow bird already achieved a path to go, until you get minimun edeges to go to all yellow birds"""
while len(YB_set) < len(yellow_birds):
nearest_yb_distance = 10000
nearest_yb = None
from_yb = None
for yb in YB_set:
dis_YandY = dis_YandYs[yb]
temp_yb_distance, temp_yb = dis_YandY[0]
if temp_yb_distance < nearest_yb_distance:
nearest_yb_distance = temp_yb_distance
nearest_yb = temp_yb
from_yb = yb
if nearest_yb not in YB_set:
YB_set.add(nearest_yb)
heuristic_value += nearest_yb_distance
# print("yb = " + str(from_yb) + "TO" + str(nearest_yb) + " dis = " + str(nearest_yb_distance))
dis_YandY = dis_YandYs[nearest_yb]
dis_YandY.remove([nearest_yb_distance, from_yb])
dis_YandY = dis_YandYs[from_yb]
dis_YandY.remove([nearest_yb_distance, nearest_yb])
return heuristic_value
every_bird = every_bird_heuristic
|
ab79b8c878f465cac0131bf55f802a6b64cfdfb5 | MatejBabis/AdventOfCode2k18 | /day5/part1.py | 799 | 3.765625 | 4 | def read_input(filename):
f = open(filename)
# only one line, and remove '\n'
output = f.readline().strip()
f.close()
return output
# helper function that checks if two letters are equal are diffent case
def conflict(a, b):
return a.lower() == b.lower() and ((a.isupper() and b.islower()) or (a.islower() and b.isupper()))
# recation function
def polymer_reaction(string, ignored=None):
stack = []
for c in string:
if c.lower() == ignored:
continue # skip
if len(stack) == 0:
stack.append(c)
elif conflict(stack[-1], c):
stack.pop()
else:
stack.append(c)
return stack
if __name__ == "__main__":
s = read_input("input.txt")
print("Answer:", len(polymer_reaction(s)))
|
d5273f7320cae0c86a36327e9defa268b7bca045 | MatejBabis/AdventOfCode2k18 | /day4/part1.py | 2,591 | 3.5 | 4 | import re
import numpy as np
# strings to match
ASLEEP = 'falls asleep'
AWAKE = 'wakes up'
GUARD = 'Guard'
# process the input file
def process_file(filename):
f = open(filename)
records_list = []
for line in f.readlines():
raw = line[6:-1] # first six letter carry no information
month = int(raw[:2])
day = int(raw[3:5])
hour = int(raw[6:8])
minute = int(raw[9:11])
message = raw[13:]
records_list += [(month, day, hour, minute, message)]
f.close()
# sort the items based on timestamps
records_list.sort(key=lambda x: (x[0], x[1], x[2], x[3]))
return records_list
# create a dictionary with data for each guard
def organise_records(array):
output = {}
# sleeping = False # flag
# initialise variable
guard_id = None
asleep_from = None
asleep_to = None
for log in array:
msg = log[4]
# only minutes as sleep happens between 00:00 and 00:59
time = log[3]
# initialise
if guard_id not in output:
output[guard_id] = []
# get ID from string 'Guard #X begins shift'
if msg.startswith(GUARD):
guard_id = int(re.findall(r'\d+', msg)[0])
# get 'falls asleep' time
elif msg == ASLEEP:
# sleeping = True
asleep_from = time
# get 'wakes up' time and stores in dictionary
elif msg == AWAKE:
asleep_to = time
# store datum
output[guard_id] += [(asleep_from, asleep_to)]
# unexpected input
else:
raise ValueError('Unexpected input: ', log)
return output
# return a triple used to computer answers:
# 1. minutes asleep,
# 2. the minute the guard is asleep most often
# 3. the maximum value at 2.
def count_sleeps(g, data):
asleep_at_minute = np.zeros(60)
for timestamp in data[g]:
for minute in range(timestamp[0], timestamp[1]):
asleep_at_minute[minute] = asleep_at_minute[minute] + 1
return np.sum(asleep_at_minute), np.argmax(asleep_at_minute), max(asleep_at_minute)
if __name__ == "__main__":
sorted_data = process_file("input.txt")
dataset = organise_records(sorted_data)
# hold the record (GuardID, how much sleep, "most asleep" minute)
maximum = (None, 0, None)
for guard in dataset:
time_asleep, most_sleepy_minute, _ = count_sleeps(guard, dataset)
if time_asleep > maximum[1]:
maximum = (guard, time_asleep, most_sleepy_minute)
print("Answer:", maximum[0] * maximum[2])
|
bc7b865e579f10ee6632e9b10099d106727bdd14 | petrakov1/foodbot | /dataAnal.py | 3,617 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import _json
import math
def valueByTag(place,arrPerson):
value = 0
for tag in arrPerson:
if (tag in place):
value += place[tag]*arrPerson[tag]
return (value)
def sortByValue(arr):
for i in range(len(arr)):
for j in range(len(arr)-1, i, -1):
if arr[j][1] > arr[j - 1][1]:
test1 = arr[j][0]
test2 = arr[j][1]
test3 = arr[j][2]
arr[j][0] = arr[j - 1][0]
arr[j][1] = arr[j - 1][1]
arr[j][2] = arr[j - 1][2]
arr[j - 1][0] = test1
arr[j - 1][1] = test2
arr[j - 1][2] = test3
def getTopPlaces (json_Plase, json_Person,clientPoint):
arrPerson = json_Person["tags"]
personPrise = json_Person["price"]
arrPlaces = []
for place in json_Plase:
distance = distance_([place["location"]["lon"], place["location"]["lat"]], clientPoint)
if (distance < 3):
arrPlaces.append([place["id"], valueByTag(place["tags"], arrPerson), distance])
#print (arrPlaces)
sortByValue(arrPlaces)
if (arrPlaces.__len__()==0): arrPlaces.append([0,0,0])
if (arrPlaces[0][1] != 0):
for i in range(1, arrPlaces.__len__()):
arrPlaces[i][1] = arrPlaces[i][1] / float(arrPlaces[0][1])
arrPlaces[0][1] = 1
arrValueOfPrices = []
for place in json_Plase:
arrValueOfPrices.append([place["id"], place["price"]])
for i in range(0, arrValueOfPrices.__len__()):
arrValueOfPrices[i][1] = (personPrise - arrValueOfPrices[i][1]) / 2.0
for i in range(0, arrPlaces.__len__()):
for j in range(0, arrValueOfPrices.__len__()):
if (arrPlaces[i][0]==arrValueOfPrices[j][0]):
arrPlaces[i][1] = 2 * arrPlaces[i][1] + arrValueOfPrices[j][1]
sortByValue(arrPlaces)
while arrPlaces.__len__()>5:
arrPlaces.pop()
#print (arrPlaces)
return (arrPlaces)
def distance_(point1, point2):
R = 6371
dLat = math.radians(point2[0] - point1[0])
dLon = math.radians(point2[1] - point1[1])
a = math.sin(dLat / 2) * math.sin(dLat / 2) + math.cos(math.radians(point1[0])) * math.cos(math.radians(point2[0])) * math.sin(dLon / 2) * math.sin(dLon / 2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = R * c
return d
#jsonPlaces = [{"name": "\u0422\u0435\u0441\u0442", "tags": {"burger": 1}, "price": 1, "location": {"lat":59.9317145,"lon":30.3457811}, "id": 1, "desc": "@"},
# {"name": "\u0422\u0435\u0441\u0442", "tags": {"burger": 1}, "price": 1, "location": {"lat":59.9317405,"lon":30.3457811}, "id": 2, "desc": "@"},
# {"name": "\u0422\u0435\u0441\u0442", "tags": {"burger": 1}, "price": 1, "location": {"lat":59.9317145,"lon":30.3456811}, "id": 3, "desc": "@"},
# {"name": "Pizaa", "tags": {"pasta": 1}, "price": 1, "location": {"lat":59.9317145,"lon":30.3457854}, "id": 4, "desc": ""},
# {"name": "a", "tags": {"pasta": 1, "fri": 1}, "price": 2, "location": {"lat":59.9317405,"lon":30.3457811}, "id": 5, "desc": ""},
# {"name": "Pizaa", "tags": {"fri": 2}, "price": 1, "location": {"lat":59.9317405,"lon":30.3457811}, "id": 6, "desc": ""},
# {"name": "a", "tags": {"burger": 1, "fri": 1}, "price": 2, "location": {"lat":59.9317405,"lon":30.3457811}, "id": 7, "desc": ""}]
#jsonPerson = {"tags": {"burger":1,"pizza":2}, "price": 1, "places": 0}
#clientPoint = (59.9368993,30.3154044)
#getTopPlaces(jsonPlaces,jsonPerson,clientPoint)
|
158450f4cb59c6890e6de4931de18e66a4f5ef48 | FraserTooth/python_algorithms | /01_balanced_symbols_stack/stack.py | 865 | 4.21875 | 4 | class Stack:
def __init__(self):
self.items = []
def push(self, item):
"""Adds an item to end
Returns Nothing
Time Complexity = O(1)
"""
self.items.append(item)
def pop(self):
"""Removes Last Item
Returns Item
Time Complexity = O(1)
"""
if self.items:
return self.items.pop()
return None
def peek(self):
"""Returns Last Item
Time Complexity = O(1)
"""
if self.items:
return self.items[-1]
return None
def size(self):
"""Returns Size of Stack
Time Complexity = O(1)
"""
return len(self.items)
def is_empty(self):
"""Returns Boolean of whether list is empty
Time Complexity = O(1)
"""
return self.items == []
|
9ea5c9748f2a37bf51ed41905b601704b629c2d8 | Alver23/CursoPython | /clase1/EjerciciosHechosClase/eres.py | 191 | 4.09375 | 4 | nombre = input("Cual es tu nombre")
if nombre == "Alver":
print ("Que man tan chevere")
elif nombre == "Jorge":
print ("Que Onda Jorge")
else:
print ("Eres Otro que no es Alver o Jorge") |
462662bb1d616d434d6df18dabe53e424ac5b297 | habc0d3r/100-Days-Of-Code | /Day-5/highest-score/main.py | 323 | 3.75 | 4 | student_scores = input("Input a list of student scores ").split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
heighest = 0
for score in student_scores:
if score > heighest:
heighest = score
print(f"The heighest score in the class is: {heighest}")
|
98b239868170d72f40abdf73dc38172bfaf24f1d | habc0d3r/100-Days-Of-Code | /Day-18/challenge4.py | 483 | 3.5 | 4 | import turtle
from turtle import Turtle, Screen
import random as rd
tim = Turtle()
# tim.hideturtle()
turtle.colormode(255)
def random_color():
r = rd.randint(0, 255)
g = rd.randint(0, 255)
b = rd.randint(0, 255)
final_color = (r, g, b)
return final_color
directions = [0, 90, 180, 270]
tim.speed(0)
tim.pensize(10)
for _ in range(200):
tim.color(random_color())
tim.fd(20)
tim.seth(rd.choice(directions))
screen = Screen()
screen.exitonclick()
|
aac8aac901bd84af8b37b384aae3f0607e023c34 | habc0d3r/100-Days-Of-Code | /Day-18/challenge3.py | 571 | 3.890625 | 4 | from turtle import Turtle, Screen
import random as rd
colors = ['chartreuse', 'deep sky blue', 'sandy brown', 'medium orchid', 'magenta', 'royal blue', 'burlywood']
tim = Turtle()
tim.shape("arrow")
def change_color():
tim.color(rd.random(), rd.random(), rd.random())
def draw_shape(num_of_sides):
angle = 360/num_of_sides
for _ in range(num_of_sides):
tim.forward(100)
tim.right(angle)
change_color()
# tim.color(rd.choice(colors))
for side in range(3, 11):
draw_shape(side)
screen = Screen()
screen.exitonclick()
|
66c93a7b70637fd2ebbabe192b10d52cca68ee1c | karthikyadav09/deep_learning_for_vision | /ASN3/Solution/ASN3/lstmMNISTStarterCode.py | 2,867 | 3.546875 | 4 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib import rnn
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #call mnist function
learningRate = 0.0025
trainingIters = 100000
batchSize = 256
displayStep = 10
nInput =28 #we want the input to take the 28 pixels
nSteps =28 #every 28
nHidden =256 #number of neurons for the RNN
nClasses =10 #this is MNIST so you know
x = tf.placeholder('float', [None, nSteps, nInput])
y = tf.placeholder('float', [None, nClasses])
weights = {
'out': tf.Variable(tf.random_normal([nHidden, nClasses]))
}
biases = {
'out': tf.Variable(tf.random_normal([nClasses]))
}
def RNN(x, weights, biases):
x = tf.transpose(x, [1,0,2])
x = tf.reshape(x, [-1, nInput])
x = tf.split(x, nSteps, 0) #configuring so you can get it as needed for the 28 pixels
lstmCell = rnn.BasicLSTMCell(nHidden, forget_bias=1.0) #find which lstm to use in the documentation
rnnCell = rnn.BasicRNNCell(nHidden)
gruCell = rnn.GRUCell(nHidden)
outputs, states = rnn.static_rnn(lstmCell, x, dtype=tf.float32) #for the rnn where to get the output and hidden state
return tf.matmul(outputs[-1], weights['out'])+ biases['out']
pred = RNN(x, weights, biases)
#optimization
#create the cost, optimization, evaluation, and accuracy
#for the cost softmax_cross_entropy_with_logits seems really good
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred))
optimizer = tf.train.AdamOptimizer(learningRate).minimize(cost)
correctPred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correctPred, tf.float32))
init = tf.global_variables_initializer()
train_accuracy = []
train_loss = []
idx = []
with tf.Session() as sess:
sess.run(init)
step = 1
while step* batchSize < trainingIters:
batchX, batchY = mnist.train.next_batch(batchSize) #mnist has a way to get the next batch
batchX = batchX.reshape((batchSize, nSteps, nInput))
sess.run(optimizer, feed_dict={x: batchX, y: batchY})
if step % displayStep == 0:
acc = sess.run(accuracy, feed_dict={x: batchX, y: batchY})
loss = sess.run(cost, feed_dict={x: batchX, y: batchY})
train_accuracy.append(acc)
train_loss.append(loss)
print("Iter " + str(step*batchSize) + ", Minibatch Loss= " + \
"{:.6f}".format(loss) + ", Training Accuracy= " + \
"{:.5f}".format(acc))
step +=1
print('Optimization finished')
testData = mnist.test.images.reshape((-1, nSteps, nInput))
testLabel = mnist.test.labels
print("Testing Accuracy:", \
sess.run(accuracy, feed_dict={x: testData, y: testLabel}))
print "Training Accuracy :"
print train_accuracy
print "Train Loss"
print train_loss
|
447204f56fb361002c5d1ad231d25d8aaef4ff80 | lerandc/project-euler | /python/p29.py | 2,179 | 3.765625 | 4 | """
Luis RD
April 12, 2020
------------------------------------------------
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
22=4, 23=8, 24=16, 25=32
32=9, 33=27, 34=81, 35=243
42=16, 43=64, 44=256, 45=1024
52=25, 53=125, 54=625, 55=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
"""
from algorithms import factorize
def prod(vals):
"""
List product
"""
product = 1
for i in vals:
product *= i
return product
def countDuplicates(vals):
"""
Count duplicates in sorted tuple list
"""
count = 0
for i in range(1,len(vals)):
if vals[i] == vals[i-1]:
count+=1
return count
def main():
#strategy is to reduce numbers to their prime factorizations
#keep prime factors in one list, ordered; exponents in corresponding list, also ordered
#generate prime factors for 2-100
factors = []
exponents = []
for i in range(2,101):
f, e = factorize(i)
if len(f) > 0:
factors.append(f)
if len(e) > 0:
exponents.append(e)
else:
exponents.append([1])
else:
factors.append([i])
exponents.append([1])
factors_a = []
exponents_b = []
for i in range(0,len(factors)):
for b in range(2,101):
factors_a.append(factors[i])
exponents_b.append([j*b for j in exponents[i]])
#join lists
union = []
for i in range(0,len(factors_a)):
union.append((factors_a[i],exponents_b[i]))
# print(union[0:100])
union = sorted(union, key=lambda x: (prod(x[0]),x[1]))
# count = countDuplicates(union)
new_union = [union[0]]
for i in range(1,len(union)):
if union[i] != union[i-1]:
new_union.append(union[i])
print(len(union))
print(len(new_union))
print(new_union)
if __name__ == '__main__':
main() |
1f2bf332f201dbede1ce368cb977533ff440bc0d | forest-data/luffy_py_algorithm | /算法入门/merge_sort.py | 1,934 | 3.65625 | 4 |
#归并排序 时间复杂度 O(nlogn)
# 假设左右已排序
def merge(li, low, mid, high):
i = low
j = mid + 1
ltmp = []
while i<=mid and j<=high:
if li[i] < li[j]:
ltmp.append(li[i])
i += 1
else:
ltmp.append(li[j])
j += 1
# while 执行完,肯定有一部分没数了
while i <= mid:
ltmp.append(li[i])
i+=1
while j <= high:
ltmp.append(li[j])
j+=1
li[low:high+1] = ltmp
#
def merge_sort(li, low, high):
if low < high:
mid = (low + high) //2
merge_sort(li, low, mid) # 递归左边
merge_sort(li, mid+1, high) # 递归右边
merge(li, low, mid, high)
print(li[low:high+1])
li = list(range(10))
import random
random.shuffle(li)
print(li)
merge_sort(li, 0, len(li)-1)
print(li)
'''
#
def merge_sort(li):
n = len(li)
# 递归结束条件
if n<=1:
return li
# 中间位置
mid = n // 2
# 递归拆分左侧
left_li = merge_sort(li[:mid])
# 递归拆分右侧
right_li = merge_sort(li[mid:])
# 需要2个游标, 分别指向左列表和右列表第一个元素
left_point, right_point = 0, 0
# 定义最终返回的结果集
result = []
# 循环合并数据
while left_point < len(left_li) and right_point < len(right_li):
# 谁小放前面
if left_li[left_point] <= right_li[right_point]:
# 放进结果集
result.append(left_li[left_point])
left_point += 1
else:
result.append(right_li[right_point])
right_point += 1
# 退出循环是,形成左右两个序列
result += left_li[left_point:]
result += right_li[right_point:]
return result
if __name__ == '__main__':
li = [53, 26, 93, 17, 77, 31, 44, 55, 21]
print(li)
print(merge_sort(li))
''' |
dc55a27810a351d729e80b1ad96d09c5de314db3 | forest-data/luffy_py_algorithm | /数据结构/stack.py | 1,214 | 4.0625 | 4 |
# 栈: 是一个数据集合,只能在一段进行插入或删除操作
class Stack:
def __init__(self):
self.stack = []
def push(self, element):
self.stack.append(element)
# 删除栈顶元素
def pop(self):
return self.stack.pop()
# 获取栈顶元素
def get_top(self):
if len(self.stack) > 0:
return self.stack[-1]
else:
return None
def is_empty(self):
return len(self.stack) == 0
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.get_top()) # 3
print(stack.pop()) # 3
# 匹配字符串问题
#
def brace_match(s):
match = {')':'(', ']':'[', '}':'{'}
stack = Stack()
for ch in s:
if ch in {'(','[','{'}:
stack.push(ch)
else:
if stack.get_top() == match[ch]: # ({}[])
stack.pop()
elif stack.is_empty(): # 首次进来的是 ] ) }
return False
elif stack.get_top() != match[ch]: # ({)}
return False
if stack.is_empty(): #解决无结尾情况 ({}[]
return True
else:
return False
print(brace_match('{{}()[]}'))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.