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 |
|---|---|---|---|---|---|---|
0516cf4a9993dc466b921122bedb4c085fd55124 | Trevor-droid/TDR | /grading system.py | 513 | 3.921875 | 4 | mark = 56
"""
0 - 35 - F9
36 - 44 - P8
45 - 49 - P7
50 - 54 - C6
55 - 59 - C5
60 - 65 - C4
66 - 74 - C3
75 - 79 - D2
80 - 100 - D1
Grading system that assigns grade to students based on marks
"""
if mark <= 35:
print("F9")
elif mark <= 44:
print("P8")
elif mark <= 49:
print("P7")
elif mark <= 54:
print("C6")
elif mark <= 59:
print("C5")
elif mark <= 65:
print("C4")
elif mark <= 74:
print("C3")
elif mark <= 79:
print("D2")
else:
print("D1") |
b8df8b021f762b6701830929db14a706e0f9e70c | KKrishnendu1998/COMPUTATIONAL_PHYSICS_ASSIGNMENT_1 | /Gauss_Elimination.py | 344 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 15:11:06 2020
@author: krishnendu
code: solve a set of linear eqaution using numpy.linalg.solve
"""
import numpy as np
A=np.array([[1,0.67,0.33],[0.45,1,0.55],[0.67,0.33,1]]) #the given matrix
b=np.array([2,2,2])
print(np.linalg.solve(A,b)) #printing the solution
|
1ad53b3e8ce734ee3d5ef4b24963ad0c0a2c978e | endreujhelyi/endreujhelyi | /week-03/guess_game/guess_the_number.py | 4,231 | 3.921875 | 4 | import random
def escape_from_hell(bottom, top, tries):
number_of_guesses = 0
tries_remaining = tries
### welcome sentences and adding name
print ("\n>>>>>>>>>>>>>> ESCAPE FROM HELL <<<<<<<<<<<<<<\n")
print ("OK human! My name is Beelzebub the King of the Hell.\nIf you wanna be free you have to guess the number that I\'m thinking of!\nBut before you die, let me know your name!\n")
player_name = input()
## input field for the player name
random_number = random.randint(bottom, top)
print ("\nWell " + str(player_name) + ", let\'s get it started!\nYou have " + str(tries) + " chances to find that number between " + str(bottom) + " and " + str(top) + ".\nHurry, before I get angry. Soooo?")
attemp = -1
### start of the loop
while attemp != random_number:
attemp = -1
if tries_remaining > 1:
attemp = int(input("What is the number?\n\n"))
tries_remaining -= 1
elif tries_remaining == 1:
attemp = int(input("Soo, what is it " + str(player_name) + "?\n\n"))
tries_remaining -= 1
elif tries_remaining == 0:
print ("HAHAHA, your soul is mine and lost forever!\n<<<<<--------- * - -- - * --------->>>>>>\n")
return False
## bad inputs
if type(attemp) != int:
if tries_remaining > 1:
print ("\nDo you wanna die right now? This is not a whole number.")
elif tries_remaining == 1:
print ("\nDo you wanna die right now? This is not a whole number. This is your last chance.")
else:
print ("HAHAHA, your soul is mine and lost forever!\n<<<<<--------- * - -- - * --------->>>>>>\n")
return False
elif attemp < bottom_number or attemp > top_number:
if tries_remaining > 1:
print ("You piss me off human! This number is not between " + str(bottom_number) + " and " + str(top_number) + ".")
elif tries_remaining == 1:
print ("You piss me off human! This number is not between " + str(bottom_number) + " and " + str(top_number) + ". This is your last chance.")
else:
return False
### number is found
if attemp == random_number:
print ("Noooooooooooo! How did you find my lucky number? " + str(random_number) + " is my favorite.\nPlease, play with me one more. I\'m so lonely! Soo?\nDo you wanna play again, or just walk away before I change my mind.")
repeat = False
next_game = 'nothin'
while next_game == 'nothin':
next_game = input("Yes or No?\n\n")
if next_game[0].lower() == "y":
return escape_from_hell(bottom_number, top_number, tries_number)
elif next_game[0].lower() == "n":
print ("See ya soon in the Hell!\n\n")
return False
else:
next_game == 'nothin'
while repeat == True:
repeat = escape_from_hell(bottom_number, top_number, tries_number)
### number is too small
elif attemp < random_number:
if tries_remaining > 1:
print("My number is bigger! You have only " + str(tries_remaining) + " chances to find it. Hurry up!")
elif tries_remaining == 1:
print("Hahaha, my number is bigger! 1 more left and you will pass away!\n.. FOREVER.... hahaha")
else:
pass
### number is too big
else:
if tries_remaining > 1:
print("My number is smaller! You have only " + str(tries_remaining) + " chances to find it. Hurry up!")
elif tries_remaining == 1:
print("Hahaha, my number is smaller! 1 more left and you will pass away!\n.. FOREVER.... hahaha")
else:
pass
#######################################################
# ----- u can give the default numbers in the game here --------|
#######################################################
bottom_number = 1
top_number = 100
tries_number = 10
escape_from_hell(bottom_number, top_number, tries_number)
|
adfdfcef8df2c83bf122fef38b54335628aef52b | endreujhelyi/endreujhelyi | /week-05/day-3/number_1_2_3.py | 1,050 | 3.953125 | 4 |
# create a function that takes a number and divides ten with it and prints the result
# it should print "fail" if it is divided by 0
def divider(user_num):
try:
return (10 / user_num)
except ZeroDivisionError:
return ('fail')
# write a function that takes a filename and returns the number of lines the
# file consists. It should return zero if the file not exists.
def line_counter(file_name):
try:
f = open(file_name, 'r')
length = len(f.readlines())
f.close()
return length
except IOError:
return (0)
# Write a Person class that have a name and a birth_date property
# It should raise an error of the birthdate is less than 0 or more than 2016
class HorrorError(Exception):
pass
class Person:
def __init__(self, name, birth_date):
self.name = name
self.birth_date = birth_date
self.birth_date_check()
def birth_date_check(self):
if 0 >= self.birth_date or self.birth_date > 2016:
raise HorrorError
|
5e447702f51cd3318fd5595a131da34c2bc498d5 | endreujhelyi/endreujhelyi | /week-04/day-3/04.py | 528 | 4.3125 | 4 | # create a 300x300 canvas.
# create a line drawing function that takes 2 parameters:
# the x and y coordinates of the line's starting point
# and draws a line from that point to the center of the canvas.
# draw 3 lines with that function.
from tkinter import *
top = Tk()
size = 300
canvas = Canvas(top, bg="#222", height=size, width=size)
def line_drawer(x, y):
return canvas.create_line(x, y, size/2, size/2, fill='coral')
line_drawer(20, 40)
line_drawer(130, 50)
line_drawer(220, 100)
canvas.pack()
top.mainloop()
|
0c2563d42a29e81071c4a2667ace0495477ac241 | endreujhelyi/endreujhelyi | /week-04/day-3/08.py | 534 | 4.1875 | 4 | # create a 300x300 canvas.
# create a square drawing function that takes 2 parameters:
# the x and y coordinates of the square's top left corner
# and draws a 50x50 square from that point.
# draw 3 squares with that function.
from tkinter import *
top = Tk()
size = 300
lines = 3
canvas = Canvas(top, bg="#222", height=size, width=size)
def square_drawer(x, y):
return canvas.create_rectangle(x, y, x+50, y+50, fill='coral')
square_drawer(20, 40)
square_drawer(130, 50)
square_drawer(220, 100)
canvas.pack()
top.mainloop()
|
4d61e0d7c4ba7e4c7bd85e9952a9b38ba32c5545 | endreujhelyi/endreujhelyi | /week-04/day-3/03.py | 286 | 3.90625 | 4 | # create a 300x300 canvas.
# draw its diagonals in green.
from tkinter import *
top = Tk()
x = 300
canvas = Canvas(top, bg="#333", height=x, width=x)
canvas.create_line(0, 0, x, x, fill='light green')
canvas.create_line(0, x, x, 0, fill='light green')
canvas.pack()
top.mainloop()
|
02a8078775b4475bc6452f44aa6ee23226433427 | endreujhelyi/endreujhelyi | /week-04/day-3/11.py | 707 | 3.859375 | 4 | # create a 300x300 canvas.
# create a square drawing function that takes 2 parameters:
# the square size, and the fill color,
# and draws a square of that size and color to the center of the canvas.
# create a loop that fills the canvas with rainbow colored squares.
from tkinter import *
import webcolors
top = Tk()
size = 300
canvas = Canvas(top, bg="#0d355a", height=size, width=size)
def rainbow_rect(x, color):
canvas.create_rectangle(size/2-x/2, size/2-x/2 , size/2+x/2, size/2+x/2, fill=color)
rainbow_colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'violet']
i = 6
while i >= 0:
rainbow_rect((i+1)*(size/7), rainbow_colors[i])
i -= 1
canvas.pack()
top.mainloop()
|
a2490191fa88fa20e923235a2f7f4dff1177cbfe | endreujhelyi/endreujhelyi | /week-03/day-2/40.py | 552 | 3.671875 | 4 | students = [
{'name': 'Rezso', 'age': 9.5, 'candies': 2},
{'name': 'Gerzson', 'age': 10, 'candies': 1},
{'name': 'Aurel', 'age': 7, 'candies': 3},
{'name': 'Zsombor', 'age': 12, 'candies': 5}
]
# create a function that takes a list of students,
# then returns how many candies are own by students
# under 10
def ill_find_you(inventory):
limit = 10
candies_sum = 0
for x in inventory:
if x['age'] < limit:
candies_sum += x['candies']
return candies_sum
print(ill_find_you(students))
|
02ea4490a77eb5991c68828967de8b95480393bd | endreujhelyi/endreujhelyi | /week-04/day-2_dojo/03.py | 188 | 4.09375 | 4 | m1 = 124
m2 = 456
# tell if m1 and m2 are both even numbers
def is_even(x,y):
if x % 2 == 0 and y % 2 == 0:
return True
else:
return False
print (is_even(m1,m2))
|
506d0bbf89cbbeeb0a5343c43d955b853a526556 | endreujhelyi/endreujhelyi | /week-04/day-4/02.py | 212 | 4.1875 | 4 | # 2. write a recursive function
# that takes one parameter: n
# and adds numbers from 1 to n
def recursive(n):
if n == 1:
return (n)
else:
return n + recursive(n-1)
print (recursive(5))
|
13faefce6f80192d15de6da93614a22936c1b75c | Calata/PythonLearningShit | /Vectores.py | 878 | 3.71875 | 4 |
def vectorProporcional():
print "Introduzca el Vector 1"
vector1a = int(raw_input())
vector1b = int(raw_input())
print "Introduzca el vector 2"
vector2a = int(raw_input())
vector2b = int(raw_input())
Cociente1 = vector1a/vector1b
Cociente2 = vector2a/vector2b
if Cociente1 == Cociente2:
print "Los Vectores son Proporcionales"
else:
print "Los vectores son linealmente Independientes"
print "Quieres Calcular el vector que forman?"
print "S/N"
Cond = raw_input()
if Cond == "S":
vector3a = int(vector1a + vector1b)
vector3b = int(vector2b + vector2b)
print "El Vector resultante es "
print vector3a
print vector3b
print "Quiere calcular otro vector"
print "S/N"
Cond2 = raw_input()
if Cond2 == "S":
vectorProporcional()
else:
print "Hasta Luego!"
#||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vectorProporcional()
|
cfe575c3753cddfb1ce180cb1ac4b35f524368cd | anithashok1910/pythonautomationscripts | /directory reader.py | 1,609 | 4.03125 | 4 |
# Script file to read all the files of the specified directory and
# store it in a text file called "file content.txt" in the current
# working directory
import os
# for functions os.listdir(), os.path.join() and os.path.getsize() functions
fout = open('file contents.txt','w')
# opens the text file or creates if not created of the name "file contents.txt"
# in the current working directory which can be accessed by fout object in
# writing mode
line1 = "File name Size \n"
# for giving the heading of the columns (File name and Size)
fout.write(line1)
# writes the above line in the file through its file object (fout)
files = os.listdir('H:\\backup\\docx') # location of the directory
# storing the names of all the files in the files variables in the form of list
# using the os.listdir() function
for file in files:
# for loop for reading the list's each item and finding each file's size in
# the directory
location = os.path.join('H:\\backup\\docx\\',file)
# joins both the path and the file name together
# stores the complete location in the location variable
line = file +" "+ str(os.path.getsize(location)) + "\n"
# stores the filename along with its size in the variable line
# os.path.getsize() returns a long value n must be converted
# to string before writing it into the file
fout.write(line)
# the line variables content are written inside the file object (fout) and
# hence to the the text file ("file contents.txt")
fout.close()
# closes the file object and the file which is opened through the file object
|
8ab3f8149c94c31f738d48eeb7681c0b8a66cc9d | pentazoid/Computer-programming-projects | /bar_chart_lecture_89.py | 293 | 3.6875 | 4 | import matplotlib.pyplot as plt
x=[2,4,6,8,10]
x2=[1,3,5,7,9]
y=[4,7,4,7,3]
y2=[5,3,2,6,2]
plt.bar(x,y,label="One",color='m')
plt.bar(x2,y2,label="Two",color='g')
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('Bar Chart tutorial')
plt.legend()
plt.show()
|
3f3d4ccb46d3788720412c8b47058a6aabdda539 | sunshield123/PythonTotal | /Controlflow.py | 265 | 4.03125 | 4 |
# for i in range(1,11):
# print(i)
# i=1
# while i<=10:
# print(i)
# i=i+1
# a=10
# b=20
# if a<b:
# print("{} is less than {}".format(a,b))
# elif a==20:
# print("{} is equal to {}".format(a,b))
# else:
# print("{} is greater than {}".format(a,b)) |
5a10b290ea8db139050502ebd0fd98d5afb3f47a | CTEC-121-Spring-2020/mod-3-programming-assignment-EPisano526 | /Prob-1/Prob-1.py | 516 | 3.953125 | 4 | # Module 3
# Programming Assignment 4
# Prob-1.py
# Esther Pisano
def shippingCost(orderSubTotal):
shippingCost = 2.99
# enter code here to test for free
if orderSubTotal >= 10:
shippingCost = 0
return shippingCost
def unitTest():
print("Shipping cost if subtotal < 10.00:\n", shippingCost(5.99))
print("Shipping cost if subtotal = 10.00:\n", shippingCost(10.00))
print("Shipping cost if subtotal > 10.00:\n", shippingCost(11.99))
if __name__ == "__main__":
unitTest()
|
ce4e17153201cab5095bff5ef5bf7df3b769987e | Miguel-Fuentes/Spam_Ham_ML | /spam_ham_util.py | 906 | 3.609375 | 4 | from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
import pandas as pd
def df_to_numeric(train_df, test_df):
# This will ingore any words that appear in more than 85% of documents
# or less than %5 of documents
count_vec = CountVectorizer(max_df=0.85,min_df=0.05)
# Here we train the vectorizer on the training set, her it learn the vocabulary
X_train = count_vec.fit_transform(train_df['text']).toarray()
X_train = np.hstack((X_train, np.ones((X_train.shape[0],1))))
Y_train = (train_df['class'] == 'spam').values.astype(int)
# Here we transform the test set using the vocabulary from the training set
X_test = count_vec.transform(test_df['text']).toarray()
X_test = np.hstack((X_test, np.ones((X_test.shape[0],1))))
Y_test = (test_df['class'] == 'spam').values.astype(int)
return X_train, X_test, Y_train, Y_test |
7003ea04149f15b591f728fc505da70218a1a9c8 | fengjixuchui/Image_Processing_Practice | /XYZ/Digital-Image-Processing-master/collage_pics_divider/collage_border_detection.py | 2,090 | 3.78125 | 4 |
import cv2 as cv #import OpenCV
#This method is used to show images without being enlarged. Try only with `cv.imshow` to see the difference
def showimage(img):
screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)
cv.namedWindow('image', cv.WINDOW_NORMAL)
cv.resizeWindow('image', window_width, window_height)
cv.imshow('image', img)
cv.waitKey(0)
cv.destroyAllWindows()
c=0 #counter for number of images in the collage
im = cv.imread('collage5.jpg') #input the image
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY) #convert it to Gray Scale image
ret, thresh = cv.threshold(imgray, 250, 255, 0) #convert it into a binary image(0 or 255). We only care about the threshold image.
im2, conts, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) #finding continous blobs of pixels. We only care about conts.
#cv.RETR_TREE will find continous blobs of pixels within the picture. Try with cv.RETR_EXTERNAL to see the difference
#cv.CHAIN_APPROX_SIMPLE will give only few and extreme coordinates of contours. cv.CHAIN_APPROX_NONE will detect all the continous blobs of pixels
cv.drawContours(im, conts, -1, (0,255,0), 3) #drawing those contours on the image.
q=3 #this is to eliminate the contours line from the cropped images
for cnt in conts:
area = cv.contourArea(cnt) #area of contours detected.
if area > 20: #eliminate small contours
c+=1
x1, y1, w, h = cv.boundingRect(cnt) #finding rectangles
x2 = x1 + w
y2 = y1 + h
print("x1:", x1, " y1:", y1, " x2:", x2, " y2:", y2) #(x1, y1): coordinates of rectangles for 1st vertex. (x2, y2): coordinates of rectangles for diagonally opposite vertex.
crop_img = im[y1+q:y1+h-q, x1+q:x1+w-q] #remove q from this line to understand what it really does
cv.imwrite("cropped"+str(c)+'.jpg', crop_img) #saving the cropped images
showimage(im)
|
4082583f119dc9702058674bcb3de779be24b5e4 | a7med-tal3at/Data-Structure | /Queue/linkedListQueue.py | 1,003 | 3.9375 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next = None
class Queue:
def __init__(self):
self.front = self.rear = None
def isEmpty(self):
return not self.front
def enQueue(self, val):
newNode = Node(val)
if self.isEmpty():
self.front = self.rear = newNode
else:
self.rear.next = newNode
self.rear = self.rear.next
def deQueue(self):
if self.isEmpty():
print("Can't deQueue")
return
value = self.front.val
self.front = self.front.next
return value
def display(self):
if self.isEmpty():
print("Can't deQueue")
return
while True:
if self.isEmpty():
break
print(self.deQueue())
if __name__ == "__main__":
q = Queue()
q.enQueue(5)
q.enQueue(10)
q.enQueue(15)
q.enQueue(20)
q.deQueue()
q.display() |
0a76c3c5203cdd4f81775984fe7d8a6af9e811d8 | chpurdy/pgzero-blackjack | /main.py | 1,290 | 3.59375 | 4 | from random import shuffle
WIDTH = 1024
HEIGHT = 768
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f"{self.rank} of {self.suit}"
def value(self):
# return a tuple of values to handle the Ace
face = ['J','Q','K']
if self.rank in face:
return (10,10)
elif self.rank=='A':
return (1,11)
else:
return (int(self.rank),int(self.rank))
class Deck:
def __init__(self):
self.cards = []
ranks = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
suits = ['Club','Diamonds','Hearts','Spades']
for suit in suits:
for rank in ranks:
self.cards.append(Card(suit,rank))
shuffle(self.cards)
class Game:
def __init__(self):
self.deck = Deck()
self.player = [self.deck.cards.pop(),self.deck.cards.pop()]
self.dealer = [self.deck.cards.pop(),self.deck.cards.pop()]
def check_hands(self):
player_score = [0,0]
for card in self.player:
pass
# need to check player score
# check dealer score
|
589dc8e59bb0c5f46839e25ef1b5aebd60c82db7 | mtsznowak/pjn | /lab3/dict.py | 357 | 3.515625 | 4 | class Dict:
def __init__(self):
filepath = 'polimorfologik-2.1/polimorfologik-2.1.txt'
self.dict = set()
with open(filepath) as fp:
line = fp.readline()
while line:
splitted = line.split(';')
self.dict.add(splitted[1].lower())
line = fp.readline()
def has_key(self, word):
return word in self.dict
|
17a2337bfd3ee42411d71e76757dcdbe6feb6cb2 | dmckenzie79/web-336 | /week-8/if_else_ex01.py | 343 | 4 | 4 | even_numbers = [2,4,6,8,10]
odd_numbers = [1,3,5,7,9]
number01 = 4
number02 = 7
if number01 in even_numbers:
print(str(number01) + " is an even number")
else:
print(str(number01) + " is an odd number")
if number02 in odd_numbers:
print(str(number02) + " is an odd number")
else:
print(str(number02) + " is an even number") |
b03233c66c8b5f19b835c70816db5690ce5600d6 | Georgia2308/StrongPasswordChecker | /password.py | 10,477 | 3.890625 | 4 | # Strong Password Checker
# written by Georgia Berar as a technical test for UMT Software
# password checker class
# validates a strong password and constructs the strongest password with minimal changes
class PasswordChecker:
def __init__(self, password):
self.password = password
self.__lowercase = None # positions of lowercase characters
self.__uppercase = None # positions of uppercase characters
self.__digits = None # positions of digit characters
self.__repeated = None # repeated character positions to be replaced
self.__symbols = None # positions of symbols
self.count = 0 # keeps count of changes made
self.__conditions() # initialises the condition checking variables
# verifies the password and constructs the associated variables
def __conditions(self):
self.__lowercase = []
self.__uppercase = []
self.__digits = []
self.__repeated = []
self.__symbols = []
repeating = 1 # keeps count of adjacent repeating characters
for pos in range(len(self.password)):
if pos > 0:
if self.password[pos] == self.password[pos - 1]:
repeating += 1
if self.password[pos] != self.password[pos - 1]:
for i in range(pos - repeating + 2, pos, 3):
self.__repeated.append(i)
repeating = 1
elif pos == len(self.password) - 1:
for i in range(pos - repeating + 3, pos + 1, 3):
self.__repeated.append(i)
repeating = 1
if self.password[pos].islower():
self.__lowercase.append(pos)
elif self.password[pos].isupper():
self.__uppercase.append(pos)
elif self.password[pos].isdigit():
self.__digits.append(pos)
else:
self.__symbols.append(pos)
# receives a character and a position
# checks if new character conflicts with neighbours
# returns recommended value for replacement
def __recommended(self, char, pos):
recommended = char
next_char, prev_char = None, None
if pos + 1 < len(self.password):
next_char = self.password[pos + 1]
if pos - 1 > 0:
prev_char = self.password[pos - 1]
if char.islower():
while recommended == next_char or recommended == prev_char:
new = chr(ord(char) + 1)
if recommended == 'z':
new = 'a'
recommended = new
if char.isupper():
while recommended == next_char or recommended == prev_char:
new = chr(ord(char) + 1)
if recommended == 'Z':
new = 'A'
recommended = new
if char.isdigit():
while recommended == next_char or recommended == prev_char:
new = str(int(next_char) + 1)
if recommended == '9':
new = '0'
recommended = new
return recommended
# receives a character and a position
# updates password and variables according to one change (insertion/replacement of given char on pos)
def __update(self, char, pos):
new = self.__recommended(char, pos)
if char.islower():
self.__lowercase.append(pos)
elif char.isupper():
self.__uppercase.append(pos)
elif char.isdigit():
self.__digits.append(pos)
else:
self.__symbols.append(pos)
if pos == len(self.password):
self.password += new
else:
old = self.password[pos]
if pos in self.__repeated:
self.__repeated.remove(pos)
if old.islower():
self.__lowercase.remove(pos)
elif old.isupper():
self.__uppercase.remove(pos)
elif old.isdigit():
self.__digits.remove(pos)
else:
self.__symbols.remove(pos)
self.password = self.password[:pos] + new + self.password[pos + 1:]
self.count += 1
# finds appropriate position and replaces with given character
def __replace(self, char):
pos = None
# if length is insufficient, insert new character
if len(self.password) < 6:
pos = len(self.password)
# if there are repeating characters, replace one of them
elif len(self.__repeated) > 0:
pos = self.__repeated[-1]
# if there is any symbol position, replace it
elif len(self.__symbols) > 0:
pos = self.__symbols[-1]
# if there are available uppercase/lowercase/digit positions, replace
else:
if char.islower():
if len(self.__uppercase) > 1:
pos = self.__uppercase[-1]
elif len(self.__digits) > 1:
pos = self.__digits[-1]
if char.isupper():
if len(self.__lowercase) > 1:
pos = self.__lowercase[-1]
elif len(self.__digits) > 1:
pos = self.__digits[-1]
if char.isdigit():
if len(self.__uppercase) > 1:
pos = self.__uppercase[-1]
elif len(self.__lowercase) > 1:
pos = self.__lowercase[-1]
# insert new character
if pos is None:
pos = len(self.password)
self.__update(char, pos)
# eliminates unnecessary characters
def __remove(self):
# attempts to remove problematic repeating characters
while len(self.__repeated) > 0:
pos = self.__repeated[0]
self.password = self.password[:pos] + self.password[pos + 1:]
self.__conditions()
self.count += 1
if len(self.password) <= 20:
return
# removes characters if it doesn't break conditions
i = 0
while i < len(self.password):
if 0 < i < len(self.password):
if self.password[i - 1] != self.password[i + 1]:
if self.password[i].islower():
if len(self.__lowercase) > 1:
self.password = self.password[:i] + self.password[i + 1:]
self.__conditions()
self.count += 1
elif self.password[i].isupper():
if len(self.__uppercase) > 1:
self.password = self.password[:i] + self.password[i + 1:]
self.__conditions()
self.count += 1
elif self.password[i].isdigit():
if len(self.__digits) > 1:
self.password = self.password[:i] + self.password[i + 1:]
self.__conditions()
self.count += 1
else:
self.password = self.password[:i] + self.password[i + 1:]
self.__conditions()
self.count += 1
else:
if self.password[i].islower():
if len(self.__lowercase) > 1:
self.password = self.password[:i] + self.password[i + 1:]
self.__conditions()
self.count += 1
elif self.password[i].isupper():
if len(self.__uppercase) > 1:
self.password = self.password[:i] + self.password[i + 1:]
self.__conditions()
self.count += 1
elif self.password[i].isdigit():
if len(self.__digits) > 1:
self.password = self.password[:i] + self.password[i + 1:]
self.__conditions()
self.count += 1
else:
self.password = self.password[:i] + self.password[i + 1:]
self.__conditions()
self.count += 1
if len(self.password) <= 20:
return
i += 1
# performs least amount of changes to construct a strong password
# returns new password or 0 if password is already strong
def improve(self):
if ' ' in self.password:
raise Exception('Invalid password: no spaces allowed')
# if there are too many characters
if len(self.password) > 20:
self.__remove()
# if there are no lowercase letters
if len(self.__lowercase) == 0:
self.__replace('a')
# if there are no uppercase letters
if len(self.__uppercase) == 0:
self.__replace('A')
# if there are no digits
if len(self.__digits) == 0:
self.__replace('0')
# if there are repeating characters
while len(self.__repeated) > 0:
self.__update('a', self.__repeated[-1])
# if there are too few characters
while len(self.password) < 6:
self.__update('A', len(self.password))
if self.count == 0:
return 0
else:
return self.password
# application entry point
# main loop where user can input a password to check
def main():
print('\nInsert password or press enter to generate:')
print('[Press . to exit]')
while True:
try:
password = input('\n')
if password == ".":
return
else:
password_checker = PasswordChecker(password)
password = password_checker.improve()
if password == 0:
print(password)
else:
print('Improved password: ' + password)
print('Number of changes made: ' + str(password_checker.count))
except Exception as ex:
print(ex)
if __name__ == '__main__':
main()
|
c4a05684bbb0b0ae64be021d151ca65ffc826a07 | DistriI1/ProyectoPrimerParcial | /Cliente Check In/checkin.py | 5,992 | 3.609375 | 4 | #!/usr/bin/env python
import socket
import sys
import md5
import time
import datetime
import Turista
def get_specific_input(valid_length, datatype):
resp=None
prompt=' -> '# muestra > mientras espera input
if (datatype == 'int'):
resp = get_input(prompt, lambda x:x.isdigit(), "Maximo "+str(valid_length)+" caracteres numericos", valid_length) #lambda funcion en una sola linea, : para retornar
#resp = resp.rjust(valid_length,' ') #rjust para completar la longitud de un string con cualquier caracter
elif (datatype == 'dec'): #int and dec
resp = get_input(prompt, lambda x:not x.isalnum(), "Maximo "+str(valid_length)+" caracteres numericos dec",valid_length)
elif (datatype == 'var'):
resp= get_input(prompt,lambda x:len(x)<valid_length+1,"Maximo "+str(valid_length)+" caracteres",valid_length)
resp=resp.rjust(valid_length,' ')
return resp
def get_input(prompt, test, error="Invalid Input", length=200):
resp = None
while True:
resp = raw_input(prompt)
print str(resp.isalnum())
if test(resp) and len(str(resp))<=length:
break
print (error)
return resp
def validate_date(date_text):
try:
return datetime.datetime.strptime(date_text.strip(), '%Y-%m-%d')
except ValueError:
return datetime.datetime.strptime(time.strftime('%Y-%m-%d'), '%Y-%m-%d')
def validar_peso(tipo_tour,peso):
if((tipo_tour == 'AVMAGIC' or tipo_tour == 'AVIDEAL') and peso <= 25.0):
return True
elif (tipo_tour == 'AVEXTRE') and peso <= 32.0:
return True
else:
print 'Peso excedido.'
return False
def registro_maleta(skt):
print ' '
print '======================REGISTRO DE MALETAS=================================='
print 'Ingrese el codigo de reserva:'
cod_reserva = get_specific_input(10, 'var')
try:
envio_mensaje('LISTTURRES', cod_reserva,skt)
#Recibe respuesta
mensaje_recibido = skt.recv(180) #Cuantos bytes?
cabecera = mensaje_recibido[:66]
cuerpo = mensaje_recibido[66:]
mda = md5.new()
mda.update(cuerpo)
hashcode = mda.hexdigest()
print "Head>" + cabecera
print "Body>" + cuerpo
if hashcode == cabecera[34:]:
cuerpo_partes = cuerpo.split('|')
if cuerpo_partes[0] == 'OKK':
tipoTour = cuerpo_partes[1]
#identificacionTurista = identificaciones.split('|') #arrar identificaciones
print ' '
print '======================LISTADO DE TURISTAS=================================='
print ' > Reserva: ' + cod_reserva
if tipoTour == 'AVMAGIC':
tipoTour = 'Aventura Magica'
elif tipoTour == 'AVEXTRE':
tipoTour = 'Aventura Extrema'
elif tipoTour == 'AVIDEAL':
tipoTour = 'Aventura Ideal'
print ' > Tipo Tour: '+ tipoTour
for i in range(2, len(cuerpo_partes) - 1):
turista = cuerpo_partes[i]
print " > Turista " + str(i-1) + ": " + turista
print 'Ingrese el peso de la maleta:'
peso = get_specific_input(5, 'dec') #validar
print 'Enviar cambios? (y/n):'
resp = get_specific_input(1, 'var')
if resp == 'y' or resp == 'Y':
envio_mensaje('REGPESOMAL', turista + '|' + peso, skt)
mensaje_recibido = skt.recv(69) #Cuantos bytes?
cabecera = mensaje_recibido[:66]
cuerpo = mensaje_recibido[66:]
mda = md5.new()
mda.update(cuerpo)
hashcode = mda.hexdigest()
if hashcode == cabecera[34:]:
if cuerpo == 'OKK':
print 'Cambios guardados.'
elif cuerpo == 'BAD':
print 'ERROR. Algo salio mal. Intente nuevamente.'
else:
print 'ERROR. Falla de integridad en la cadena.\n'
elif resp == 'n' or resp == 'N':
break
elif cuerpo_partes[0] == 'BAD':
print 'ERROR. Algo salio mal. Intente nuevamente.'
else:
print 'ERROR. Falla de integridad en la cadena.\n'
finally:
print '================================================================================'
def envio_mensaje(id, cuerpo, skt):
tipo_mensaje = 'RQ'
originador = 'CHIN'
fecha_mensaje = time.strftime("%Y%m%d%H%M%S")
cuerpo_length = len(cuerpo)
mda = md5.new()
mda.update(cuerpo)
hash_cuerpo = mda.hexdigest()
cabecera = tipo_mensaje + originador + fecha_mensaje + id + ('000' if cuerpo_length < 10 else ('00' if cuerpo_length < 100 else ('0' if cuerpo_length < 1000 else ''))) + str(cuerpo_length) + hash_cuerpo
mensaje = cabecera + cuerpo
skt.send(mensaje)
def main():
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip='localhost'
puerto=2000
server_address = (ip, puerto)
print >> sys.stderr, 'Conectando a %s por el puerto %s' % server_address
sock.connect(server_address)
opc=-1
while int(opc)!=2:
print '\n=========================== MENU PRINCIPAL -CHECKIN- ============================'
print ' 1. Registro de maletas'
print ' 2. Salir'
print 'Seleccione una opcion:'
opc=get_specific_input(1,'int')
if int(opc)==1:
registro_maleta(sock)
#opcion_registrarusuario(tipo_mensaje,originador,sock)
print '================================================================================'
print >>sys.stderr, 'Cerrando socket'
sock.close()
main() |
8cc92ae7e896ec6538591b73a49dd7850058a2ef | LVicBlack/learn-python | /demo/hifun_closure.py | 1,375 | 3.53125 | 4 | # 函数作为返回值
# 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
# 闭包
### 返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量。
def count():
fs = []
for i in range(1, 4):
def f():
return i * i
fs.append(f)
return fs
# print(count()[0]())
# # 元组拆封
# f1, f2, f3 = count()
# f4 = count()
# print(f1())
# print(f2())
# print(f3())
# print(f4[0]())
def counts():
def f(j):
def g():
return j * j
return g
fs = []
for i in range(1, 4):
fs.append(f(i))
return fs
# # 元组拆封
# f1, f2, f3 = counts()
# f4 = counts()
# print(f1())
# print(f2())
# print(f3())
# print(f4[0]())
# 练习
# 利用闭包返回一个计数器函数,每次调用它返回递增整数
def createCounter():
def num_gene():
num = 0
while True:
num = num + 1
yield num
n = num_gene()
def counter():
return next(n)
return counter
# 测试:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
print('测试通过!')
else:
print('测试失败!')
|
c9482831e1ae58563407a1266ed7ddf816ae3542 | LVicBlack/learn-python | /demo/hifun_filter.py | 1,527 | 3.859375 | 4 | # 和map()类似,filter()也接收一个函数和一个序列。
# 和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
def not_empty(s):
return s and s.strip()
# print(list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])))
# 素数
def arr_start_2():
num = 2
while True:
yield num
num = num + 1
def is_primes(prime):
return lambda x: x % prime > 0
def primes():
arr = arr_start_2() # 初始序列
while True:
prime = next(arr)
yield prime
arr = filter(is_primes(prime), arr)
primes_arr = []
for n in primes():
if n < 10:
primes_arr.append(n)
else:
break
# print(primes_arr)
# 练习
# 回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数:
# 二分法
def is_palindrome(n):
str_n = str(n)
half_len_n = len(str_n) // 2
if half_len_n < 1:
return True
else:
return str_n[:half_len_n] == str_n[::-1][:half_len_n]
# is_palindrome = lambda n: str(n) == str(n)[::-1]
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101,
111, 121, 131, 141, 151, 161, 171, 181, 191]:
print('测试成功!')
else:
print('测试失败!')
|
68ecde6a54b0be44c15b86e0fbdec4400c0d6f3c | vidyasridhar0/Coding-puzzles | /LCP_horizontal.py | 580 | 3.6875 | 4 |
#LCP(string)= LCP(LCP(string1, string2), string3)
def LCP(str):
new = ""
prefix = str[0]
for x in str:
new = find(prefix, x)
if new == "":
print ("No LCP")
quit()
prefix = new
return prefix
def find(str1, str2):
newstring = ""
for i, j in zip(str1, str2):
if i is j:
newstring = newstring + i
else:
break
return newstring
words = ["flower", "flow", "flight"]
lcp = LCP(words)
if (len(lcp)):
print("Longest common prefix:" , lcp)
else:
print("No LCP")
|
8502202133de46f0b14432650b3f149cdc966efe | Sai-Ram-Adidela/hackerrank | /challenges/strings/string_formatting.py | 127 | 3.765625 | 4 | def dec_to_oct(n):
n = int(input())
for i in range(1, n):
print(i+' '+dec_to_oct(i)+' '+dec_to_hex(i)+' '+dec_to_bin(i)) |
2f0dde5084c3803098b9edfd67164e5918c51de4 | Sai-Ram-Adidela/hackerrank | /30_days_Of_Code/day2_operators.py | 545 | 3.59375 | 4 | """
Title : day2_operators
Subdomain : 30 days of code
Domain : Python
Author : Sai Ram Adidela
Created : 18 April 2018
"""
if __name__ == "__main__":
meal_cost = float(input().strip())
tip_percent = int(input().strip())
tax_percent = int(input().strip())
tip = float(meal_cost*(tip_percent/100))
# print("tip: ",tip)
tax = float(meal_cost*(tax_percent/100))
# print("tax: ",tax)
totalCost = round(meal_cost+tip+tax)
# print(totalCost)
print('The total meal cost is %d dollars.' % totalCost)
|
561e22ed476f75f9ad72c5e72d7955f8ddde91e2 | Sai-Ram-Adidela/hackerrank | /challenges/sets/set_symmetric_difference.py | 692 | 3.71875 | 4 | """
Title : Set Symmetric Difference
Subdomain : HackerRank/Python/Challenges/sets
Domain : Python
Author : Sai Ram Adidela
Created : 2 May 2018
"""
if __name__ == '__main__':
set1_n = int(input())
set1 = set(map(int, input().split()))
set2_n = int(input())
set2 = set(map(int, input().split()))
# print("set1: ",set1)
# print("set2: ",set2)
result = set1.symmetric_difference(set2)
# print(type(result))
# print("result: ",result)
sorted_result = sorted(result)
sorted_result = map(str, sorted_result)
# print(type(sorted_result))
# print("sorted_result: ",sorted_result)
print('\n'.join(sorted_result))
|
6ce3b9e2e4084d4a5a94765d7f3a1abeef5e9a51 | Sai-Ram-Adidela/hackerrank | /challenges/collections/collections.counter().py | 521 | 3.546875 | 4 | """
Title : collections.Counter()
Subdomain : HackerRank/Python/Challenges/Collections
Domain : Python
Author : Sai Ram Adidela
Created : 15 May 2018
"""
from collections import Counter
no_of_shoes = int(input())
shoe_sizes = Counter(map(int, input().split()))
no_of_customers = int(input())
total_money = 0
for i in range(no_of_customers):
(size, price) = map(int, input().split())
if shoe_sizes[size] > 0:
shoe_sizes[size] -= 1
total_money += price
print(total_money)
|
25664d3446b179d6ebc6de7d329a5ff94c8d65e0 | Sai-Ram-Adidela/hackerrank | /challenges/basic data types/lists.py | 728 | 3.796875 | 4 | """
Title : Lists
Subdomain : HackerRank/Python3/Challenges/Basic Data Types
Domain : Python
Author : Sai Ram Adidela
Created : 23 April 2018
"""
if __name__ == '__main__':
N = int(input())
L = []
for i in range(0, N):
tokens = input().split()
if tokens[0] == 'insert':
L.insert(int(tokens[1]), int(tokens[2]))
elif tokens[0] == 'print':
print(L)
elif tokens[0] == 'remove':
L.remove(int(tokens[1]))
elif tokens[0] == 'append':
L.append(int(tokens[1]))
elif tokens[0] == 'sort':
L.sort()
elif tokens[0] == 'pop':
L.pop()
elif tokens[0] == 'reverse':
L.reverse()
|
e1371fb9d9c3b4f9f7b938d9b5421f5c4aad4b87 | Sai-Ram-Adidela/hackerrank | /challenges/collections/company_logo.py | 389 | 3.578125 | 4 | """
Title : Company Logo
Subdomain : HackerRank/Python/Challenges/Collections
Domain : Python
Author : Sai Ram Adidela
Created : 22 May 2018
"""
from collections import Counter
s = sorted(input().strip())
s_counter = Counter(s).most_common()
s_counter = sorted(s_counter, key=lambda x: (x[1] * -1, x[0]))
for i in range(0, 3):
print(s_counter[i][0], s_counter[i][1])
|
07e837def498b93c4f3091bce2af0eb45395f318 | mjpinsk/python-challenge | /PyBank/main.py | 3,142 | 4.34375 | 4 | """
The following script opens a csv file with bank data and returns the following
results: 1) The total number of months included in the dataset 2) The net total
amount of "Profit/Losses" over the entire period 3) The average of the changes in
"Profit/Losses" over the entire period 4) The greatest increase in profits
(date and amount) over the entire period 5) The greatest decrease in losses
(date and amount) over the entire period
"""
# Import the necessary modules
import os
import csv
# Path to collect data from the Resources folder
bank_csv = os.path.join('Resources', 'budget_data.csv')
# Read in the CSV file
with open(bank_csv, 'r') as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, delimiter=',')
# Initialize these variables
num_months = 0
current_profit = 0
greatest_increase = 0
greatest_decrease = 0
total_profit = 0
worst_month = "month"
difference = []
# Assign the first row in the file as the header
header = next(csvreader)
# Iterate to the end of the file performing some simple comparisons
# and calculations
for row in csvreader:
# Caculate the change in profit from month to month
change_profit = int(row[1]) - current_profit
# Create a list of month to month differences
difference.append(change_profit)
# Determine the month and corresponding amount with greatest increase and decrease
if change_profit > greatest_increase and change_profit != difference[0]:
greatest_increase = change_profit
greatest_month = row[0]
elif change_profit < greatest_decrease and change_profit != difference[0]:
greatest_decrease = change_profit
worst_month = row[0]
# Update the current profit of the corresponding month
current_profit = int(row[1])
# Calculate the total profit of all the months
total_profit = total_profit + int(row[1])
# Calculate the total number of months
num_months += 1
# Remove the first month from difference (change_profit) list
# which is just the first month profit
difference.remove(difference[0])
# Caluculate the average of the changes in "Profit/Losses"
# Note the total numer of changes is one less than the total number of months
average_change = sum(difference) / (num_months - 1)
# Create and open the file poll_results and print results to file
with open('financial_analysis.txt', 'w+', newline="") as file:
file.write(f"Financial Analysis\n")
file.write(f"----------------------------\n")
file.write(f"Total Months: {num_months}\n")
file.write(f"Total: ${total_profit}\n")
file.write(f"Average Change: ${average_change:.2f}\n")
file.write(f"Greatest Increase in Profits: {greatest_month} (${greatest_increase})\n")
file.write(f"Greatest Decrease in Profits: {worst_month} (${greatest_decrease})\n")
# Go to the beginning of file and read & print to the terminal
file.seek(0)
print(file.read())
|
1ed8060c5b681b02ccc7f188adb825ef0617c598 | ramya-nagarajan/Academic-Research-Network-Generator | /project/project/keyphrase_extraction/phraseSelect.py | 4,562 | 3.578125 | 4 | import string;
import fileHandle;
patterns = [('JJ', 'NN'), ('NN', 'NN'), ('JJ', 'NNS'), ('NN', 'NNS'), ('NN'), ('NN', 'NN', 'NN')]; #make 3 word patters also
#forget noun phrase idea.. find better patterns
#write a learning algorithm to find patterns --- any database of keywords should do to get candidates since POS is being relied on
def tagAcronym(tokens):
keyPhrase = [];
#caps = string.uppercase;
small = string.lowercase;
i = 0;
count = len(tokens);
while i < count:
j = 0;
strlen = len(tokens[i]);
if strlen > 1:
while j < strlen:
if tokens[i][j] in small:
break;
j = j + 1;
if j == strlen:
keyPhrase.append(tokens[i]);
i = i + 1;
return keyPhrase;
def readPatterns(name):
f = fileHandle.openFile(name, "r");
patterns = [];
pat = fileHandle.readLine(f);
while pat != "":
if '#' not in pat:
patList = pat.split(" ");
patList.pop();
patterns.append(patList);
pat = fileHandle.readLine(f);
return patterns;
def posPhrase(tagged, patterns): #acronyms might come twice since they are also part of candidates
#print patterns;
candidates = [];
i = 0;
count = len(tagged);
posList = [];
while i < count:
posList. append(tagged[i][1]);
#print "posList = ", posList;
if posList in patterns and tagged[i][0] not in candidates:
candidates.append(tagged[i][0]);
posList = [];
i = i + 1;
i = 0;
posList = [];
#count = len(tagged);
while i < count:
if i != count - 1:
posList. append(tagged[i][1]);
posList. append(tagged[i + 1][1]);
if posList in patterns:
if tagged[i][0] + " " + tagged[i + 1][0] not in candidates:
candidates.append(tagged[i][0] + " " + tagged[i + 1][0]);
posList = [];
i = i + 1;
i = 0;
posList = [];
#count = len(tagged);
while i < count:
if i < count - 2:
posList. append(tagged[i][1]);
posList. append(tagged[i + 1][1]);
posList. append(tagged[i + 2][1]);
if posList in patterns:
if tagged[i][0] + " " + tagged[i + 1][0] + " " + tagged[i + 2][0] not in candidates:
candidates.append(tagged[i][0] + " " + tagged[i + 1][0] + " " + tagged[i + 2][0]);
posList = [];
i = i + 1;
#if tagged[i][1] == 'NN':
# candidates.append(tagged[i][0]);
#if i != count - 1:
# if tagged[i][1] == 'NN' and tagged[i + 1][1] == 'NN':
# candidates.append(tagged[i][0] + " " + tagged[i + 1][0]);
# if tagged[i][1] == 'JJ' and tagged[i + 1][1] == 'NN':
# candidates.append(tagged[i][0] + " " + tagged[i + 1][0]);
# if tagged[i][1] == 'JJ' and tagged[i + 1][1] == 'NNS':
# candidates.append(tagged[i][0] + " " + tagged[i + 1][0]);
# if tagged[i][1] == 'NN' and tagged[i + 1][1] == 'NNS':
# candidates.append(tagged[i][0] + " " + tagged[i + 1][0]);
#if i < count - 2: #verify these and see if more to be added
# if tagged[i][1] == 'NN' and tagged[i + 1][1] == 'NN' and tagged[i + 2][1] == 'NN':
# candidates.append(tagged[i][0] + " " + tagged[i + 1][0] + " " + tagged[i + 2][0]);
# if tagged[i][1] == 'NN' and tagged[i + 1][1] == 'NN' and tagged[i + 2][1] == 'NNS':
# candidates.append(tagged[i][0] + " " + tagged[i + 1][0] + " " + tagged[i + 2][0]);
# if tagged[i][1] == 'JJ' and tagged[i + 1][1] == 'NN' and tagged[i + 2][1] == 'NNS':
# candidates.append(tagged[i][0] + " " + tagged[i + 1][0] + " " + tagged[i + 2][0]);
# if tagged[i][1] == 'JJ' and tagged[i + 1][1] == 'NN' and tagged[i + 2][1] == 'NN':
# candidates.append(tagged[i][0] + " " + tagged[i + 1][0] + " " + tagged[i + 2][0]);
#i = i + 1;
return candidates; |
a0de4bef78d37450f14b7cac40fb380814980845 | malikyilmaz/Class4-PythonModule-Week2 | /1.lucky numbers.py | 1,661 | 4.0625 | 4 | """
Write a programme to generate the lucky numbers from the range(n).
These are generated starting with the sequence s=[1,2,...,n].
At the first pass, we remove every second element from the sequence, resulting in s2.
At the second pass, we remove every third element from the sequence s2, resulting in s3,
and we proceed in this way until no elements can be removed.
The resulting sequence are the numbers lucky enough to have survived elimination.
The following example describes the entire process for n=22:
Original sequence: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
Remove 2nd elements: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
Remove 3rd elements: [1, 3, 7, 9, 13, 15, 19, 21]
Remove 4th elements: [1, 3, 7, 13, 15, 19]
Remove 5th elements: [1, 3, 7, 13, 19]
We cannot remove every other 6th element as there is no 6th element.
Input>>> 22
Output>>> Lucky numbers are [1, 3, 7, 13, 19]
"""
print("******************************************************\n"
"*** Find Lucky Number ***\n"
"******************************************************")
x = int(input("please enter a number: "))
main_list = list(range(1, x+1)) # ana liste olusturulur
i = 1
while True:
if i < len(main_list): # liste uzunlugu kadar döngü olusturulur
del main_list[i:x:i+1] # her döngüde liste index numarası bir artırılarak liste silinir
i += 1
else:
print("your lucky numbers: {}".format(main_list)) # döngü bittiğinde listede kalanlar yazdırılır.
break
|
dc27b4d07c81d4faed52867851a4b623ac3a7ca3 | jonathan-potter/MathStuff | /primes/SieveOfAtkin.py | 1,824 | 4.21875 | 4 | ##########################################################################
#
# Programmer: Jonathan Potter
#
##########################################################################
import numpy as np
##########################################################################
# Determine the sum of all prime numbers less than an input number
##########################################################################
def SieveOfAtkin(limit):
"""usage SieveOfAtkin(limit)
This function returns a list of all primes below a given limit.
It is an implimentation of the Sieve of Atkin. The primary logic
is a reimplimentation of the example on Wikipedia.
en.m.wikipedia/wiki/Sieve_of_Atkin"""
# calculate and store the square root of the limit
sqrtLimit = np.int(np.ceil(np.sqrt(limit)));
# initialize the sieve
isPrime = [False] * limit;
# this script considers 1 to be prime. If you don't like it,
# subtract 1 from the result
isPrime[1:3] = [True] * 3;
# impliment the sieve
for x in range (1,sqrtLimit+1):
for y in range(1,sqrtLimit+1):
n = 4 * x**2 + y**2;
if (n <= limit and (n % 12 == 1 or n % 12 == 5)):
isPrime[n] = not(isPrime[n]);
n = 3 * x**2 + y**2;
if (n <= limit and n % 12 == 7):
isPrime[n] = not(isPrime[n]);
n = 3 * x**2 - y**2;
if (n <= limit and x > y and n % 12 == 11):
isPrime[n] = not(isPrime[n]);
# for prime n: ensure that all of the multiples of n^2 are not flagged as prime
for n in range(5,sqrtLimit+1):
if isPrime[n]:
isPrime[n**2::n**2] = [False] * len(isPrime[n**2::n**2]);
# create array of prime numbers below limit
primeArray = [];
for n in range(limit + 1):
if isPrime[n] == True:
primeArray.append(n);
# return the result
return primeArray;
|
2923cb3c964c77b3925aefced32818e3f56a3bdc | TeMU-BSC/mesinesp-workflow | /Evaluation/scripts/excel_utils.py | 2,430 | 3.71875 | 4 | '''
Util functions to analyze Excel files for the initial phase of indexers'
selection for MESINESP task.
Author: alejandro.asensio@bsc.es
Based on the original script made by: aitor.gonzalez@bsc.es
'''
import re
import os
import xlrd
from typing import List
def read_excel_file(filename: str) -> List[list]:
'''Return a list with the rows in the Excel file.
Each row is a list with its cells as its elements.
Source: https://stackoverflow.com/a/20105297
'''
wb = xlrd.open_workbook(filename)
# sh = wb.sheet_by_name('Sheet1')
sh = wb.sheet_by_index(0)
all_rows = [sh.row_values(rownum) for rownum in range(sh.nrows)]
return all_rows
def parse_excel_file(filename: str) -> dict:
'''Return an indexed doc object.'''
# Get all rows from the Excel file
all_rows = read_excel_file(filename)
# Purge empty lines and the final row (num. 200) starting with 'BSC-2019' string
data_rows = [row for row in all_rows if not ('' in set(row) and len(set(row)) == 1 or row[0] == 'BSC-2019')]
# Define the different row categories inside the Excel files
docIds = data_rows[0]
difficulties = data_rows[1]
middle_rows = data_rows[2:17]
final_rows = data_rows[17:]
# Construct the result list
docs = dict()
for i, docId in enumerate(docIds):
try:
# Try to convert the docId into an integer
docId = int(docId)
# Get the decsCodes only for those rows with an "X" or "x"
precoded_decs = [int(re.match('^\d+', middle_row[0]).group(0)) for middle_row in middle_rows if middle_row[i].upper() == 'X']
# Get the decsCodes typed in manually
manual_decs = [int(decsCodes[i]) for decsCodes in final_rows if decsCodes[i] != '']
indexed_doc = {str(docId): precoded_decs + manual_decs}
docs.update(indexed_doc)
except Exception:
pass
return docs
def extract_indexings_from_excels_dir(excels_dir: str) -> dict:
'''Extract the DeCS codes from Excel files inside excel_dir input directory name.'''
indexings = dict()
for root, dirs, files in os.walk(excels_dir):
for file in files:
if file.endswith('.xlsx'):
file_relative_path = os.path.join(root, file)
filename = re.sub('\.xlsx$', '', file)
indexings[filename] = parse_excel_file(file_relative_path)
return indexings
|
29f8bd56a5591f9caf22f96dfde852172aae6938 | RameshVasudev-Shankar/Assignment1 | /Ramesh Vasudev Shankar A1.py | 3,102 | 3.8125 | 4 | # '''
# CP5632 Assignment 1 2016
# Items for Hire
# Shankar Ramesh V - 3rd April 2016
#
# Pseudocode:
#
# function main():
#
# display Welcome Message
# display list of items loaded from file
# display menu
# choice
# while choice not Q
# if choice = L
# function list_all_items()
# elif choice = H
# function hire_an_item()
# elif choice = R
# function return_an_item()
# elif choice = 'A'
# function add_item()
# else:
# Display Invalid Menu Message
# display Menu
# choice
# display Farewell message
#
# '''
#
def main():
print("\t Items for Hire - by Shankar Ramesh Vasudev")
MENU = "Menu: \n(L)ist all items\n(H)ire an item\n(R)eturn an item\n(A)dd new items to stock\n(Q)uit"
items = load_item()
print(MENU)
choice = input(">>> ").upper()
while choice != 'Q':
if choice == 'L':
list_all_item(items)
if choice == 'H':
hire_an_item(items)
if choice == 'R':
return_an_item(items)
print(MENU)
choice = input(">>> ").upper()
# save_item()
print("Farewell Message") # change it - just for reference
def load_item():
file = open('items.csv')
items = []
for line in file:
item_in_list = line.strip().split(',')
item_in_list[2] = float(item_in_list[2])
items.append(item_in_list)
file.close()
return items
def list_all_item(items):
print("All items on file ( '*' indicates item is currently out):")
for line in range(len(items)):
item_name = items[line][0]
item_desc = items[line][1]
item_cost = items[line][2]
item_position = items[line][3]
if item_position == 'out':
item_sign = "*"
else:
item_sign = ""
print("{} - {:20} {:30} = $ {:>4.2f} {}".format(line, item_name, '('+item_desc+')', item_cost, item_sign))
# load_all_item()
def hire_an_item(items):
items = []
for line in range (len(items)):
if items[line][3] == 'in':
print("{} - {} {} = $ {:>6.2f} ".format(line, items[line][0], ' ( '+items[line][1]+' ) ', items[line][2]))
items.append(line)
if len(items) == 0:
print("no item to hire ")
else:
choice = int(input("\n Enter the number of an item to hire : "))
print("{} hired for $ {:2.2f} ".format(items[choice][0], float(items[choice][2])))
items.remove(choice)
items[choice][3] = 'out'
def return_an_item(items):
items = []
for line in range (len(items)):
if items[line][3] == 'out':
print("{} - {} {} = $ {:>6.2f} ".format(line, items[line][0], ' ( '+items[line][1]+' ) ', items[line][2]))
items.append(line)
if len(items) != 0:
print("No items to return ")
else:
choice = int(input("\n Enter the number of an item to return : "))
print("{} returned".format(items[choice][0]))
items.append(choice)
items[choice][3] = 'in'
main()
|
6733b7b848e1e271f7f3d313284348f9e9fab0a8 | gyhou/DS-Unit-3-Sprint-2-SQL-and-Databases | /SC/northwind.py | 2,546 | 4.5625 | 5 | import sqlite3
# Connect to sqlite3 file
conn = sqlite3.connect('northwind_small.sqlite3')
curs = conn.cursor()
# Get names of table in database
print(curs.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;").fetchall())
# What are the ten most expensive items (per unit price) in the database?
"""[('Côte de Blaye',),
('Thüringer Rostbratwurst',),
('Mishi Kobe Niku',),
("Sir Rodney's Marmalade",),
('Carnarvon Tigers',),
('Raclette Courdavault',),
('Manjimup Dried Apples',),
('Tarte au sucre',),
('Ipoh Coffee',),
('Rössle Sauerkraut',)]"""
print(curs.execute("""
SELECT ProductName, SupplierId
FROM Product
ORDER BY UnitPrice DESC
LIMIT 10;""").fetchall())
# What is the average age of an employee at the time of their hiring? (Hint: a lot of arithmetic works with dates.)
# 37.22 years old
print(curs.execute("""
SELECT AVG(age)
FROM (
SELECT HireDate-BirthDate AS age
FROM Employee
GROUP BY Id);""").fetchall())
# (Stretch) How does the average age of employee at hire vary by city?
"""[('Kirkland', 29.0),
('London', 32.5),
('Redmond', 56.0),
('Seattle', 40.0),
('Tacoma', 40.0)]"""
print(curs.execute("""
SELECT City, AVG(age)
FROM (
SELECT City, HireDate-BirthDate AS age
FROM Employee
GROUP BY Id)
GROUP BY City;""").fetchall())
# What are the ten most expensive items (per unit price) in the database and their suppliers?
"""[('Côte de Blaye', 'Aux joyeux ecclésiastiques'),
('Thüringer Rostbratwurst', 'Plutzer Lebensmittelgroßmärkte AG'),
('Mishi Kobe Niku', 'Tokyo Traders'),
("Sir Rodney's Marmalade", 'Specialty Biscuits, Ltd.'),
('Carnarvon Tigers', 'Pavlova, Ltd.'),
('Raclette Courdavault', 'Gai pâturage'),
('Manjimup Dried Apples', "G'day, Mate"),
('Tarte au sucre', "Forêts d'érables"),
('Ipoh Coffee', 'Leka Trading'),
('Rössle Sauerkraut', 'Plutzer Lebensmittelgroßmärkte AG')]"""
print(curs.execute("""
SELECT ProductName, CompanyName
FROM Supplier, (
SELECT ProductName, SupplierId
FROM Product
ORDER BY UnitPrice DESC)
WHERE Id=SupplierId
LIMIT 10;""").fetchall())
# What is the largest category (by number of unique products in it)?
# Category: Confections (13 unique products)
"""[('Confections', 13)]"""
print(curs.execute("""
SELECT CategoryName, MAX(cat_id_count)
FROM Category, (
SELECT CategoryId, COUNT(CategoryId) AS cat_id_count
FROM Product
GROUP BY CategoryId)
WHERE Id=CategoryId;""").fetchall())
# (Stretch) Who's the employee with the most territories?
# Robert King with 10 territories
"""[('King', 'Robert', 10)]"""
print(curs.execute("""
SELECT LastName, FirstName, MAX(terri_id_count)
FROM Employee, (
SELECT EmployeeId, COUNT(TerritoryID) AS terri_id_count
FROM EmployeeTerritory
GROUP BY EmployeeId)
WHERE EmployeeId=Id;""").fetchall())
|
7a456406252bf4050a51e609fc33d15e327b3021 | trauzti/CompetitiveProgramming | /datastructures/priorityqueue.py | 711 | 3.921875 | 4 | from Queue import PriorityQueue
""" Entries are typically tuples of the form: (priority number, data). """
class minpriorityqueue():
def __init__(self):
self.pq = PriorityQueue()
def push(self, x):
rank, key = x
self.pq.put((rank, key))
def pop(self):
rank, key = self.pq.get()
return (rank, key)
def empty(self):
return self.pq.empty()
class maxpriorityqueue():
def __init__(self):
self.pq = PriorityQueue()
def push(self, x):
rank, key = x
self.pq.put((-rank, key))
def pop(self):
rank, key = self.pq.get()
return (-rank, key)
def empty(self):
return self.pq.empty()
|
8a85cbbaab5aaa7f332e4d332425e15d3964d980 | vasanthigopisetti/Becomecoder | /descending sort list.py | 100 | 3.703125 | 4 | list = [int(i) for i in input('Enter values: ').split()]
list.sort()
list.reverse()
print(list)
|
125317f1ea8b7693528e0c6ea2993680faff2e3b | vasanthigopisetti/Becomecoder | /pattern.py | 259 | 3.828125 | 4 | num=int(input())
for i in range(1,num+1):
if i%2:
temp=1
else:
temp=0
for j in range(1,num+1):
print(temp,end="")
if temp==0:
temp=1
else:
temp=0
print()
|
26a64398a7d8c3b757bdd05c0f81efdcb6ba1b7f | vasanthigopisetti/Becomecoder | /list_4.py | 127 | 3.625 | 4 | n=int(input())
data=[0 for i in range(n)]
for i in range(n):
val=int(input())
data.append(val)
print(data)
|
433779fb71af65a1a40717aa1b22340802a1c150 | wesky93/studyML_base | /from_scratch/1_perceptron_basic2.py | 1,226 | 3.78125 | 4 | import unittest
# 계산한 값과 편향(theta)를 비교하지 않고 0과 비교 할수 있도록 식을 변경
# func <= theta --> func-theta <= theta-theta --> func-theta <= 0
def AND( v1, v2 ) :
w1,w2,theta = 0.5,0.5,0.7
func = v1*w1+v2*w2
if func <= theta:
return 0
elif func > theta:
return 1
def OR( v1, v2 ) :
w1,w2,theta = 0.5,0.5,0.2
func = v1 * w1 + v2 * w2
if func <= theta:
return 0
elif func > theta:
return 1
def NAND( v1, v2 ) :
w1, w2, theta = -0.5, -0.5, -0.7
func = v1 * w1 + v2 * w2
if func <= theta :
return 0
elif func > theta :
return 1
Q = [ (0, 0), (0, 1), (1, 0), (1, 1) ]
class MyTestCase( unittest.TestCase ) :
def test_and( self ) :
A = [ 0,0,0,1]
for q, a in zip( Q, A ) :
self.assertEqual( a, AND( q[ 0 ], q[ 1 ] ) )
def test_or( self ) :
A = [0,1,1,1 ]
for q, a in zip( Q, A ) :
self.assertEqual( a, OR( q[ 0 ], q[ 1 ] ) )
def test_nand( self ) :
A = [ 1,1,1,0]
for q, a in zip( Q, A ) :
self.assertEqual( a, NAND( q[ 0 ], q[ 1 ] ) )
if __name__ == '__main__' :
unittest.main( )
|
86fb110e3756aea836e2bd40ffdd2bb4edfba728 | brekimanason/TileTraveller | /TileTraveller.py | 2,492 | 3.8125 | 4 |
# https://github.com/brekimanason/TileTraveller
# Geri Fall fyrir hvert herbergi og svo hoppar notandi milli falla og þar með milli herbergja
def room1_1():
print("You can travel (N)orth.")
direction = input("Direction: ")
if direction == "n" or direction == "N":
room1_2()
else:
print("Not a valid direction!")
room1_1()
def room1_2():
print("You can travel: (N)orth or (E)ast or (S)outh.")
direction = input("Direction: ")
if direction == "n" or direction == "N":
room1_3()
elif direction == "e" or direction == "E":
room2_2()
elif direction == "s" or direction == "S":
room1_1()
else:
print("Not a valid direction!")
room1_2()
def room1_3():
print("You can travel: (E)ast or (S)outh.")
direction = input("Direction: ")
if direction == "e" or direction == "E":
room2_3()
elif direction == "s" or direction == "S":
room1_2()
else:
print("Not a valid direction!")
room1_3()
def room2_1():
print("You can travel: (N)orth.")
direction = input("Direction: ")
if direction == "n" or direction == "N":
room2_2()
else:
print("Not a valid direction!")
room2_1()
def room2_2():
print("You can travel: (S)outh or (W)est.")
direction = input("Direction: ")
if direction == "s" or direction == "S":
room2_1()
elif direction == "w" or direction == "W":
room1_2()
else:
print("Not a valid direction!")
room2_2()
def room2_3():
print("You can travel: (E)ast or (W)est.")
direction = input("Direction: ")
if direction == "e" or direction == "E":
room3_3()
elif direction == "w" or direction == "W":
room1_3()
else:
print("Not a valid direction!")
room2_3()
def room3_1():
print("Victory!")
def room3_2():
print("You can travel: (N)orth or (S)outh.")
direction = input("Direction: ")
if direction == "n" or direction == "N":
room3_3()
elif direction == "s" or direction == "S":
room3_1()
else:
print("Not a valid direction!")
room3_2()
def room3_3():
print("You can travel: (S)outh or (W)est.")
direction = input("Direction: ")
if direction == "s" or direction == "S":
room3_2()
elif direction == "w" or direction == "W":
room2_3()
else:
print("Not a valid direction!")
room3_3()
room1_1() |
42d09562d90592f53f1e6e4ba4df03b1a3257869 | GeorgianaLoba/Python-Games | /obstruction/gui/gui.py | 2,565 | 3.921875 | 4 | import tkinter
from tkinter import Button
class Gui:
#TODO: GUI prettier
def __init__(self, master, game):
self.master = master
self.game = game
master.title("OBSTRUCTION")
self.start()
def start(self):
"""
Our board consists of buttons. When we click on a button, a specific
function is called and is given as parameters the row and column
of the button.
"""
rows = self.game.board.get_lines()
columns = self.game.board.get_columns()
self.buttons = []
for row in range(rows):
button_row=[]
for column in range(columns):
button = Button(self.master, text=" ", bg='green', command = lambda x=row, y=column:
self.send_param(x, y))
button.grid(row=row, column=column)
button_row.append(button)
self.buttons.append(button_row)
def send_param(self, x, y):
"""
This buttons receive as parameters the line and column of the cell
the computer or used placed its move. Will switch the buttons in
the gui accordingly.
"""
lst1=self.game.player_move(self.game.p1, x, y)
game_status, winner = self.game.is_over()
if game_status is True: #checks for game over
self.finish_frame(winner)
lst2=self.game.computer_move(self.game.p2)
game_status, winner = self.game.is_over()
if game_status is True:
self.finish_frame(winner)
else:
self.buttons[lst1[0]][lst1[1]]["text"] = "x"
self.buttons[lst1[0]][lst1[1]]["bg"] = "red"
for i, j in lst1[2]:
self.buttons[i][j]["bg"]='white'
self.buttons[lst2[0]][lst2[1]]["text"] = "0"
self.buttons[lst2[0]][lst2[1]]["bg"] = "red"
for i, j in lst2[2]:
self.buttons[i][j]["bg"] = 'white'
def finish_frame(self, winner):
"""
If the game is over, the game frame is destroyed and another one appears
with a specific message (depending on who won, user or computer)
"""
self.master.destroy()
window = tkinter.Tk()
window.title("Game Over")
if winner == "x":
text = "You won. GG, WP!"
else:
text = "Computer won. Loser!"
label = tkinter.Label(window, text = text)
label.grid()
window.mainloop()
|
adc2d2ef1ac83d912f4488ea51fa426fb531cf92 | AHipWhale/Machine-Learning | /P3/code/neuron.py | 940 | 3.625 | 4 | import math
class Neuron:
def __init__(self, weights, bias):
self.bias = bias
self.weights = weights
self.sumInvoer = None
def calculate_input(self, invoer: [float]):
"""Deze functie berekent de som van de inputs met we weights en telt daarbij de bias op"""
self.sumInvoer = 0
for index in range(len(self.weights)):
self.sumInvoer += invoer[index] * self.weights[index]
self.sumInvoer += self.bias
return self.sumInvoer
def activation_function(self, invoer: [float]):
"""Deze functie berekent de sigmoid en returnt dat als output"""
return 1/(1+math.exp(-self.calculate_input(invoer)))
def __str__(self):
"""Deze functie returnt de belangrijke informatie van de neuron"""
return "De weights waren %s en een bias van %s. De output van de neuron was %s" % \
(self.weights, self.bias, self.sumInvoer) |
c0069c46ea1866f745746d24ea3e3f6fb23ca8cd | strixcuriosus/sierpinski | /triangulator.py | 801 | 3.65625 | 4 | numGens = int(raw_input("how many generations? (enter an integer)"))
G1 = [0 , 1, 0]
rules = {7:0, 6:0, 5:0, 4:1, 3:0, 2:0, 1:1, 0:0}
G2 = []
output = ''
baselength = len(G1) + numGens * 2
def printout(myList):
global baselength
while len(myList) < baselength:
myList.insert(0,0)
myList.append(0)
output = ''
for i in range(0, baselength):
if myList[i] == 0:
output += ' '
else:
output += 'X'
print output
def getnextgen(currentgen):
global numGens, baselength
newgen =[]
for i in range(1, baselength - 1):
minilist = currentgen[i-1:i+2]
minilist.reverse()
rule = 0
for j in range(0,3):
rule += (2**j)*minilist[j]
newgen.append(rules[rule])
newgen.insert(0,0)
newgen.append(0)
return newgen
for i in range(0,numGens):
printout(G1)
G1 = getnextgen(G1)
|
331dcf92483afb69c9f9493cb094112dbb3da1fa | rakshith-mand/my-first-blog | /python_intro.py | 148 | 3.75 | 4 | def hi(name):
print('Hi ' + name + '!')
people = ['Rakshith','silu','harvester','tracter','manchester']
for name in range(1,6):
print(name)
|
4ebf0c7a8bfd10b7aea07f9d6e7f2557ba0dc3d9 | woleywa/python_for_everybody | /1_class/Week6/ex_04_02.py | 210 | 3.875 | 4 | def computepay():
hrs = input("Enter Hours:")
rate = input("Enter rate:")
h = float(hrs)
r = float(rate)
if h<41 :
pay=h*r
else :
ot=h-40
pay=(h-ot)*r+ot*(1.5*r)
return(pay)
print(computepay())
|
797e49abfd0e26dadc39b70a907fc6accd56150d | TakezoCan/sandbox | /trafficLight.py | 2,185 | 3.859375 | 4 | #!/usr/bin/env python3
#
# Filename: trafficLight.py
# Date: 2018.10.31
# Author: Curtis Girling
# Function: Runs three LEDs as a traffic light when button is pressed
#
from time import sleep # import sleep function for delay timing
import RPi.GPIO as GPIO # import GPIO library to use GPIO pins
# Lables for BCM pin numbers
greenLed = 18
yellowLed = 22
redLed = 25
pushNum = 4
GPIO.setwarnings(False) # stop warnings from displaying
GPIO.setmode(GPIO.BCM) # BCM numbering scheme for breakout board
GPIO.setup(greenLed,GPIO.OUT) # sets variable greenLed to an output
GPIO.setup(yellowLed,GPIO.OUT) # sets variable yellowLed to an output
GPIO.setup(redLed,GPIO.OUT) # sets variable redLed to an output
GPIO.setup(pushNum,GPIO.IN, pull_up_down=GPIO.PUD_UP) # sets variable pushNum to an input
print("Traffic lights OFF")
try:
while True:
state = GPIO.input(pushNum) # Must be in while loop to work
if (state): # start traffic lights
GPIO.output(redLed,GPIO.LOW) # Turns off redLed
GPIO.output(yellowLed,GPIO.LOW) # Turns off yellowLed
GPIO.output(greenLed,GPIO.LOW) # Turns off greenLed
else:
print("Traffic lights ON - (CTRL C) to quit")
while True: # This will continue to run until you press Ctrl-C
GPIO.output(redLed,GPIO.LOW) # Turns off redLed
GPIO.output(yellowLed,GPIO.LOW) # Turns off yellowLed
GPIO.output(greenLed,GPIO.HIGH) # Turns on greenLed
sleep(3.0) # Wait 3 seconds
GPIO.output(greenLed,GPIO.LOW) # Turns off greenLed
GPIO.output(redLed,GPIO.LOW) # Turns off redLed
GPIO.output(yellowLed,GPIO.HIGH)# Turns on yellowLed
sleep(3.0) # Wait 3 seconds
GPIO.output(yellowLed,GPIO.LOW) # Turns off yellowLed
GPIO.output(greenLed,GPIO.LOW) # Turns off greenLed
GPIO.output(redLed,GPIO.HIGH) # Turns on redLed
sleep(3.0) # Wait 3 seconds
sleep(0.1) #Wait 0.1 seconds
finally: # This block will run no matter how the try block exits
GPIO.cleanup() # Clean up GPIO pins |
52047b3445a5e24f1975fe4c882a56b4fe0dcce6 | li2ui2/Python_Personal_DEMO | /sqrt_.py | 183 | 3.78125 | 4 | def _sqrt(a):
x1 = a
x2 = a/2
while abs(x1-x2) > 0.00000001:
x1 = x2
x2 = (x1+a/x1)/2
return x1
if __name__ == '__main__':
print(int(_sqrt(25)))
|
654a1ce712b7ec83e861feb4097434684707fe72 | li2ui2/Python_Personal_DEMO | /DATA_STRUCTURE/jianzhi_offer/Tree/二叉搜索树与双向链表.py | 1,038 | 3.8125 | 4 | """
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
要求不能创建任何新的结点,只能调整树中结点指针的指向。
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write code here
if pRootOfTree is None:
return None
leftNode = self.Convert(pRootOfTree.left)
rightNode = self.Convert(pRootOfTree.right)
def find(leftNode):
while leftNode.right:
leftNode = leftNode.right
return leftNode
ret = leftNode
if leftNode:
leftNode = find(leftNode)
else:
ret = pRootOfTree
pRootOfTree.left = leftNode
if leftNode is not None:
leftNode.right = pRootOfTree
pRootOfTree.right = rightNode
if rightNode is not None:
rightNode.left = pRootOfTree
return ret |
1cb0122ab0cef46e5def7cad03c68a870462a97e | li2ui2/Python_Personal_DEMO | /DATA_STRUCTURE/leetcode/矩阵置零.py | 440 | 3.78125 | 4 | def setZeroes(matrix):
n = len(matrix)
if n == 0:
return []
m = len(matrix[0])
for i, li in enumerate(matrix):
for j in range(len(li)):
if li[j] == 0:
matrix[i] = [0 for _ in range(m)]
for i in range(n):
matrix[i][j] = 0
return matrix
if __name__ == '__main__':
matrix = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
print(setZeroes(matrix))
|
581f3ce15faa2ff8ebd8cdc0207023a42ff6c8f4 | li2ui2/Python_Personal_DEMO | /DATA_STRUCTURE/jianzhi_offer/其他/翻转单词顺序列.py | 797 | 4.03125 | 4 | """
将像"I am a student."这样的字符串进行翻转,翻转后结果为:"student. a am I"。
思路:先转单词,再转句子。
"""
def reverse(words):
for i in range(len(words) >> 1):
words[i], words[-i - 1] = words[-i - 1], words[i]
return words
def ReverseSentence(s):
# write code here
wordstart = 0
s = list(s)
for i in range(len(s)):
if s[i] == ' ':
s[wordstart:i] = reverse(s[wordstart:i])
wordstart = i + 1
s[wordstart:] = reverse(s[wordstart:])
s = reverse(s)
return ''.join(s)
def ReverseSentence2(s):
# write code here
s = s.split(" ")
return " ".join(s[::-1])
if __name__ == '__main__':
s = "I am a student."
print(ReverseSentence(s))
print(ReverseSentence2(s))
|
fca4ea31aa9d970b6b3c2d5985a80f1a71977ff0 | li2ui2/Python_Personal_DEMO | /DATA_STRUCTURE/jianzhi_offer/其他/数值的整数次方.py | 520 | 4 | 4 | """
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
"""
class Solution:
def Power(self, base, exponent):
# write code here
if exponent == 0:
return 1
ret = base
if exponent > 0:
for i in range(1, exponent):
ret *= base
return ret
else:
for i in range(1, abs(exponent)):
ret *= base
return 1/ret |
7e2d0e3179c141d8c7df35e8ecc62e9f8410c1d8 | li2ui2/Python_Personal_DEMO | /DATA_STRUCTURE/leetcode/滑动窗口/找到字符串中所有字母异位词.py | 1,031 | 3.703125 | 4 | """
leetcode 438
给定一个字符串 s 和一个非空字符串 p,
找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。
输入:
s: "cbaebabacd" p: "abc"
输出:
[0, 6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。
"""
import collections
def findAnagrams(s, p):
pLen = len(p)
sLen = len(s)
if sLen < pLen or s == [] or p == []:
return []
count = collections.Counter(p)
left = 0
result = []
tempLen = 0
for right in range(sLen):
count[s[right]] -= 1
if count[s[right]] >= 0:
tempLen += 1
if right >= pLen:
count[s[left]] += 1
if count[s[left]] >= 1:
tempLen -= 1
left += 1
if pLen == tempLen:
result.append(left)
return result
if __name__ == '__main__':
s = "cbaebabacd"
p = "abc"
print(findAnagrams(s, p))
|
75ee01282c6ac7032782e7c7c5e41918976ea2f4 | mattwu4/Python-Easy-Questions | /Check Primality Functions/Solution.py | 638 | 4.15625 | 4 | while True:
number = input("Choose any number you want! ")
number = int(number)
if number == 2:
print("PRIME!")
elif number == 3:
print("PRIME!")
elif number == 5:
print("PRIME!")
elif number == 7:
print("PRIME!")
elif number == 11:
print("PRIME!")
elif (number % 2) == 0:
print("NOT PRIME!!")
elif (number % 3) == 0:
print("NOT PRIME!!")
elif (number % 5) == 0:
print("NOT PRIME!!")
elif (number % 7) == 0:
print("NOT PRIME!!")
elif (number % 11) == 0:
print("NOT PRIME!!")
else:
print("PRIME!!")
|
26360515333bf4face0c980dc1c89243b5383b96 | Gilvenf/GilvenfransiscoL_064002100039_PrakAlgo2 | /Prak2Elkom2.py | 220 | 3.796875 | 4 | a = int(input("masukan nilai a: "))
b = int(input("masukan nilai b: "))
c = int(input("masukan nilai c: "))
maks = 0
if a > b:
maks = a
else:
maks = b
if c > maks:
maks = c
print ("terbesar:",maks) |
c653a1e85345ac2bd9dabf58da510c86a43afdac | jrabin/GenCyber-2016 | /Base_Day.py | 309 | 4.21875 | 4 | # -*- coding: utf-8 -*
"""
Created on Wed Jul 6 10:24:01 2016
@author: student
"""
#Create your own command for binary conversion
#// gives quotient and % gives remainder
'''
hex_digit=input("Hex input:")
print(chr(int("0x"+hex_digit,16)))
'''
letter=input("Enter letter:")
print(hex(int(ord(letter)))) |
f39cf918e485fe5795fcb269bb424f2d841fa887 | QAKyle/qacourse2 | /qacourse3.py | 1,128 | 3.796875 | 4 | import random
import sys
secret_number = random.randint(1, 100)
#secret_number = 50
#wish statement
print "Use your 3 wishes to guess the magic number!"
print "If you fail you will be fed to the Kraken!"
#wish checker function
def process_user_guess(asked_count):
print "With your {} wish, which number would you like to wish upon?".format(asked_count)
value = sys.stdin.readline()
value = value.strip()
int_value = int(value)
if int_value == secret_number:
print "You good sir have chosen wisely. You shall be spared, go on your way"
return True
elif int_value > secret_number:
print "You have too high of a wish in mind,try again but think smaller!"
else:
int_value < secret_number
print "You need a grander mind! Wish bigger!"
return False
#checking for wished number if not guessed and proceeds to next one
guessed = process_user_guess("First")
if not guessed:
guessed = process_user_guess("Second")
if not guessed:
guessed = process_user_guess("Third")
#Wish number print
print "The magical number was:{}".format(secret_number) |
e77d25be0d2652163b0366a06a2e610c9b632a33 | jirvingphd/dsc-1-07-07-object-oriented-shopping-cart-lab-online-ds-ft-021119 | /shopping_cart.py | 1,896 | 3.765625 | 4 | class ShoppingCart:
# write your code here
def __init__(self, employee_discount=None): #, total=0 , items=[]):
self.employee_discount = employee_discount
self.total=0
self.items=[]
def add_item(self, name, price, quantity=1):
q=0
while q <quantity :
self.items.append({name : price})
self.total+= price
q+=1
return self.total
def get_list_of_prices(self):
list_items=self.items
list_list_prices = []
for item in list_items:
list_list_prices.append(list(item.values()))
list_prices=[val for sublist in list_list_prices for val in sublist]
return list_prices
def mean_item_price(self):
price_list=self.get_list_of_prices()
return sum(price_list)/len(price_list)
def median_item_price(self):
s =sorted(self.get_list_of_prices())
# Check for even/odd and perform calculations accordingly - use if-else
if len(s) % 2 == 0 :
mid_idx=int((len(s)/2)-1)
med=(sum(s[mid_idx:mid_idx+2]))/2
else:
mid_idx=int(len(s)//2)
med= s[mid_idx]
return med
def apply_discount(self):
if self.employee_discount:
new_total=self.total*((100-self.employee_discount)/100)
return new_total
else:
return print('Sorry, there is no discount to apply to your cart :("')
def void_last_item(self):
if len(self.items)==0:
return print('There are no items in your cart!')
else:
last_item=self.items[-1]
for k,v in last_item.items():
print(k,v)
self.total-=last_item[k] #.values(0)
self.items.pop()
|
7fad66210bb197c684aec12fc9581c7aa1cc835f | Buffer0x7cd/fabulous | /fabulous/services/google.py | 1,321 | 3.53125 | 4 | """~google <search term> will return three results from the google search for <search term>"""
import re
import requests
from random import shuffle
from googleapiclient.discovery import build
import logging
my_api_key = "Your API Key(Link: https://console.developers.google.com/apis/dashboard)"
my_cse_id = "Your Custom Search Engine ID(Link: https://cse.google.co.in/cse/)"
"""fuction to fetch data from Google Custom Search Engine API"""
def google(searchterm, api_key, cse_id, **kwargs):
service = build("customsearch", "v1", developerKey=api_key, cache_discovery=False)
res = service.cse().list(q=searchterm, cx=cse_id, **kwargs).execute()
return res['items']
"""fuction to return first three search results"""
def google_search(searchterm):
results = google(searchterm, my_api_key, my_cse_id, num=10)
length = len(results)
retval = ""
if length < 3:
for index in range(length):
retval += results[index]['link'] + "\n"
else:
for index in range(3):
retval += results[index]['link'] + "\n"
return retval
def on_message(msg, server):
text = msg.get("text", "")
match = re.findall(r"~google (.*)", text)
if not match:
return
searchterm = match[0]
return google_search(searchterm)
on_bot_message = on_message
|
8de2a3d8d21d1ccc75b71500424728f5ec707a5f | yestodorrow/py | /init.py | 486 | 4.15625 | 4 | print("hello, Python");
if True:
print("true")
else:
print("flase")
# 需要连字符的情况
item_one=1
item_two=2
item_three=3
total = item_one+\
item_two+\
item_three
print(total)
item_one="hello"
item_two=","
item_three="python"
total = item_one+\
item_two+\
item_three
print(total)
# 不需要连字符的情况
days=["Monday","Tuesday","Wednesday","Thursday",
"Friday"]
print(days)
name="this is a comment" # this is a comment
|
56a0882cfc7bd368133f7dec3d265f3800550958 | zhanna-naumenko/test | /home_work_13_naumenko.py | 1,982 | 3.625 | 4 | from random import randint
import io
import os
import random
class EmailGenerator:
def __init__(self, path_domains, path_names):
self.path_domains = path_domains
self.path_names = path_names
self.get_names()
self.get_domains()
def get_domains(self):
"""Opens file domains.txt and return domains names without dot"""
with open(self.path_domains, "r") as file_domains:
domains_name = []
for line in file_domains.readlines():
domains_name.append(line.replace(".", "").strip())
return (domains_name)
def get_names(self):
"""Opens file names.txt and return only surnames"""
with open(self.path_names, "r") as data_persons:
surnames = []
for line in data_persons.readlines():
surnames.append(line.split()[1])
return (surnames)
def random_domain(self):
"""Return random domain name"""
return random.choices(self.get_domains())
def random_name(self):
"""Return random surname"""
return random.choice(self.get_names())
def random_number(self):
"""Create random number"""
return random.randint(100, 1000)
def random_word(self):
"""Create random word"""
return "".join(chr(randint(ord("a"), ord("z"))) for _ in range(randint(5, 7)))
def generate_email(self):
"""Create random e-mail"""
print(self.random_name() + "." + str(self.random_number()) + "@" + self.random_word() + "." + str(*self.random_domain()))
def __repr__(self):
return f"len domains = {len(self.get_domains())}, len names = {len(self.get_names())}"
path_domains = "D:/IT/Phyton/test/domains.txt"
path_names = "D:/IT/Phyton/test/names.txt"
email_generator = EmailGenerator(path_domains, path_names)
print(email_generator.get_domains())
print(email_generator.get_names())
print(email_generator)
email_generator.generate_email()
|
f7c954329701b44dd381aa844cf6f7a11ba1461e | KritiBhardwaj/PythonExercises | /loops.py | 1,940 | 4.28125 | 4 | # # Q1) Continuously ask the user to enter a number until they provide a blank input. Output the sum of all the
# # numbers
# # number = 0
# # sum = 0
# # while number != '':
# # number = input("Enter a number: ")
# # if number:
# # sum = sum + int(number)
# # print(sum)
# # sum = 0
# # number = 'number'
# # while len(number) > 0:
# # number = input("Enter number: ")
# # sum = sum + int(number)
# # print(f"The sum is {sum}")
number = 0
sum = 0
while number != "":
sum = sum + int(number)
number = input("Enter a number:")
print(sum)
# Q2) Use a for loop to format and print the following list:
mailing_list = [
["Roary", "roary@moth.catchers"],
["Remus", "remus@kapers.dog"],
["Prince Thomas of Whitepaw", "hrh.thomas@royalty.wp"],
["Biscuit", "biscuit@whippies.park"],
["Rory", "rory@whippies.park"],
]
for contact in mailing_list:
# print(f"{item[0]: <20} ${item[1]: .2f}")
print(f"{contact[0]:} : {contact[1]}")
# Q3) Use a while loop to ask the user for three names and append them to a list, use a for loop to print the list.
count = 0
nameList = []
while count < 3:
name = input("Enter name: ")
nameList.append(name)
count += 1
print()
for name in nameList:
print(name)
#4 Ask the user how many units of each item they bought, then output the corresponding receipt
groceries = [
["Baby Spinach", 2.78],
["Hot Chocolate", 3.70],
["Crackers", 2.10],
["Bacon", 9.00],
["Carrots", 0.56],
["Oranges", 3.08]
]
newList = []
groceryCost = 0
for item in groceries:
n = input(f"How many {item[0]}: ")
totalItemCost = item[1] * int(n)
groceryCost = groceryCost + totalItemCost
# print(f"{item[0]:<20} : {totalItemCost:}")
newList.append([item[0], totalItemCost])
print(newList)
print()
print(f"====Izzy's Food Emporium====")
for item in newList:
# print(f"{newList[0]:<20} : {newList[1]:2f}")
print(f"{item[0]:<20} : ${item[1]:.2f}")
print('============================')
print(f"{'$':>24}{groceryCost:.2f}")
|
8ec78f5a756a67b986ec892397bf0774816c955b | mathcoder3141/doomsday | /doomsday.py | 8,410 | 4.34375 | 4 | import math
from constants import *
def date_prompt():
"""
Prompts the user to enter a month, year, and date.
:return: A tuple of the entered month, date as an integer, and the year.
"""
month = input('Enter a month: ')
while month not in months:
month = input('Enter a valid month: ')
year = input('Enter a year greater than 1582: ')
while float(year) < 1582:
year = input('Enter a valid year: ')
day = input('Enter a day: ')
if month == "February" and float(year) % 4 != 0:
while float(day) > 28:
day = input('Enter a valid day: ')
if month in days30:
while float(day) > 30:
day = input('Enter a valid day: ')
if month in days31:
while float(day) > 31:
day = input('Enter a valid day: ')
return month, int(day), year
def doomsday_calc(year):
"""
Calculates the doomsday for a given year.
:param year: The year parameter that the user entered.
:return: An integer representing the doomsday for a given year.
"""
ltd = year[2:]
ftd = year[:2]
mil = ftd + "00"
if int(mil) % 400 == 0:
coeff = 2
d_ca = (coeff + int(ltd) + math.floor(int(ltd) / 4)) % 7
elif int(mil) % 400 == 100:
coeff = 0
d_ca = (coeff + int(ltd) + math.floor(int(ltd) / 4)) % 7
elif int(mil) % 400 == 200:
coeff = 5
d_ca = (coeff + int(ltd) + math.floor(int(ltd) / 4)) % 7
elif int(mil) % 400 == 300:
coeff = 3
d_ca = (coeff + int(ltd) + math.floor(int(ltd) / 4)) % 7
return d_ca
def doomsday_dec(d_cal, month, day, year, doo):
"""
Function prints what day of the week of the entered day.
:param d_cal: The calculated doomsday from the `doomsday_calc()` function.
:param month: The month the user entered.
:param day: The day the user entered.
:param year: The year the user entered.
:param doo: The doomsday for the given month.
:return: This function returns nothing because it prints the output.
"""
if d_cal == 0:
while day < doo:
doo -= 7
daydiff = abs(doo - day)
if daydiff == 0:
print("{} {} {} was a Sunday".format(month, day, year))
elif daydiff == 1:
print("{} {} {} was a Monday".format(month, day, year))
elif daydiff == 2:
print("{} {} {} was a Tuesday".format(month, day, year))
elif daydiff == 3:
print("{} {} {} was a Wednesday".format(month, day, year))
elif daydiff == 4:
print("{} {} {} was a Thursday".format(month, day, year))
elif daydiff == 5:
print("{} {} {} was a Friday".format(month, day, year))
elif daydiff == 6:
print("{} {} {} was a Saturday".format(month, day, year))
elif d_cal == 1:
while doo > day:
doo -= 7
daydiff = abs(doo - day)
if daydiff == 0:
print("{} {} {} was a Monday".format(month, day, year))
elif daydiff == 1:
print("{} {} {} was a Tuesday".format(month, day, year))
elif daydiff == 2:
print("{} {} {} was a Wednesday".format(month, day, year))
elif daydiff == 3:
print("{} {} {} was a Thursday".format(month, day, year))
elif daydiff == 4:
print("{} {} {} was a Friday".format(month, day, year))
elif daydiff == 5:
print("{} {} {} was a Saturday".format(month, day, year))
elif daydiff == 6:
print("{} {} {} was a Sunday".format(month, day, year))
elif d_cal == 2:
while doo > day:
doo -= 7
daydiff = abs(doo - day)
if daydiff == 0:
print("{} {} {} was a Tuesday".format(month, day, year))
elif daydiff == 1:
print("{} {} {} was a Wednesday".format(month, day, year))
elif daydiff == 2:
print("{} {} {} was a Thursday".format(month, day, year))
elif daydiff == 3:
print("{} {} {} was a Friday".format(month, day, year))
elif daydiff == 4:
print("{} {} {} was a Saturday".format(month, day, year))
elif daydiff == 5:
print("{} {} {} was a Sunday".format(month, day, year))
elif daydiff == 6:
print("{} {} {} was a Monday".format(month, day, year))
elif d_cal == 3:
while doo > day:
doo -= 7
daydiff = abs(doo - day)
if daydiff == 0:
print("{} {} {} was a Wednesday".format(month, day, year))
elif daydiff == 1:
print("{} {} {} was a Thursday".format(month, day, year))
elif daydiff == 2:
print("{} {} {} was a Friday".format(month, day, year))
elif daydiff == 3:
print("{} {} {} was a Saturday".format(month, day, year))
elif daydiff == 4:
print("{} {} {} was a Sunday".format(month, day, year))
elif daydiff == 5:
print("{} {} {} was a Monday".format(month, day, year))
elif daydiff == 6:
print("{} {} {} was a Tuesday".format(month, day, year))
elif d_cal == 4:
while doo > day:
doo -= 7
daydiff = abs(doo - day)
if daydiff == 0:
print("{} {} {} was a Thursday".format(month, day, year))
elif daydiff == 1:
print("{} {} {} was a Friday".format(month, day, year))
elif daydiff == 2:
print("{} {} {} was a Saturday".format(month, day, year))
elif daydiff == 3:
print("{} {} {} was a Sunday".format(month, day, year))
elif daydiff == 4:
print("{} {} {} was a Monday".format(month, day, year))
elif daydiff == 5:
print("{} {} {} was a Tuesday".format(month, day, year))
elif daydiff == 6:
print("{} {} {} was a Wednesday".format(month, day, year))
elif d_cal == 5:
while doo > day:
doo -= - 7
daydiff = abs(doo - day)
if daydiff == 0:
print("{} {} {} was a Friday".format(month, day, year))
elif daydiff == 1:
print("{} {} {} was a Saturday".format(month, day, year))
elif daydiff == 2:
print("{} {} {} was a Sunday".format(month, day, year))
elif daydiff == 3:
print("{} {} {} was a Monday".format(month, day, year))
elif daydiff == 4:
print("{} {} {} was a Tuesday".format(month, day, year))
elif daydiff == 5:
print("{} {} {} was a Saturday".format(month, day, year))
elif daydiff == 6:
print("{} {} {} was a Sunday".format(month, day, year))
else:
while doo > day:
doo -= 7
daydiff = abs(doo - day)
if daydiff == 0:
print("{} {} {} was a Saturday".format(month, day, year))
elif daydiff == 1:
print("{} {} {} was a Sunday".format(month, day, year))
elif daydiff == 2:
print("{} {} {} was a Monday".format(month, day, year))
elif daydiff == 3:
print("{} {} {} was a Tuesday".format(month, day, year))
elif daydiff == 4:
print("{} {} {} was a Wednesday".format(month, day, year))
elif daydiff == 5:
print("{} {} {} was a Thursday".format(month, day, year))
elif daydiff == 6:
print("{} {} {} was a Friday".format(month, day, year))
def doomsday():
user_m, user_d, user_y = date_prompt()
confirm = input(f"You entered {user_d} {user_m} {user_y}. Is this correct (y/n)? ")
while confirm.lower().startswith('n'):
date_prompt()
confirm = input(f"You entered {user_d} {user_m} {user_y}. Is this correct (y/n)? ")
if int(user_y) % 400 == 0 and int(user_y) % 4 == 0:
doomsday = doomsday_calc(user_y)
doom = doomsday_LY[user_m]
result = str(doomsday_dec(doomsday, user_m, user_d, user_y, doo=doom))
elif int(user_y) % 4 == 0:
doomsday = doomsday_calc(user_y)
doom = doomsday_LY[user_m]
result = str(doomsday_dec(doomsday, user_m, user_d, user_y, doo=doom))
else:
doomsday = doomsday_calc(user_y)
doom = doomsday_NLY[user_m]
statement = doomsday_dec(doomsday, user_m, user_d, user_y, doo=doom)
result = str(statement)
return result
if __name__ == "__main__":
doomsday() |
2be618d75a390af1e6ebb7a4c8b87fb327d613de | Nevilli/unit_ten | /class_file.py | 1,259 | 4.0625 | 4 | # Liam Neville
# 12/11/18
# This program draws a 5 layer brick pyramid of different colors
import brick
import pygame, sys
from pygame.locals import*
GREEN = (0, 102, 71)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GOLD = (255, 209, 63)
PURPLE = (255, 0, 255)
SPACE = 5
HEIGHT = 20
x_number_bricks = 9
colors = [RED, BLUE, GOLD, PURPLE, GREEN]
pygame.init()
# Window dimensions
main_surface = pygame.display.set_mode((500, 250), 0, 32)
pygame.display.set_caption("Brick pyramid")
# This calculates the width of the bricks
WIDTH = (500 - (x_number_bricks * SPACE))/x_number_bricks
x = 0
y = 250 - HEIGHT
# This double loop draws the bricks in 5 rows of different colors
for q in range(5):
x = (WIDTH + SPACE) * q
color = colors[q]
for b in range(x_number_bricks):
bricks = brick.Brick(WIDTH, HEIGHT, color, main_surface)
bricks.draw_brick(x, y)
# This changes the x coordinate for the bricks in each row
x = x + WIDTH + SPACE
pygame.display.update()
x_number_bricks = x_number_bricks - 2
# This changes the y coordinate for the bricks in each row
y = y - HEIGHT - SPACE
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
|
3c95d2c49f74342f1b17f6653607b22774d5af66 | sensito/Aprendiendo-py | /pruebas.py | 1,401 | 3.78125 | 4 | # -*- coding: utf-8 -*-
import os
MENU = ''' -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
1.-Agregar nueva moneda
2.-Borra una moneda
2.-Cambio de divisa
3.-Salida'''
class modifi_coins():
"""docstring for coin."""
def add_coin(coins):
coins_clas = dict(**coins)
print(coins_clas)
print(type(coins_clas))
currency = str(input('Nombre de tu monesa: '))
value = float(input('Ingresa el valor de te moneda: '))
coins_clas[currency] = value
return coins_clas
def menu_currency(arg):
for keys, values in prueba.items():
print("{}.-{}".format(keys, values))
def currency_exchange():
pass
def run():
prueba = modifi_coins()
exit = False
coins = {"Dolar":15.15,"pesos":1.1}
while not exit:
os.system('cls')
print_menu()
option = int(input("Escoje una opcion >> "))
if option is 1:
print(coins)
coins = prueba.add_coin(coins)
print(coins)
os.system('pause')
elif option is 2:
currency_exchange()
elif option is 3:
exit = True
else:
print("Opcion invalida")
os.system('pause')
print("Adios")
os.system('pause')
os.system('cls')
def print_menu():
print(MENU)
if __name__ == "__main__":
run()
|
f4fad1a73dd03e6fe1cb2a18d77a7a82f853d107 | sensito/Aprendiendo-py | /13.py | 489 | 3.90625 | 4 | # -*- coding : utf-8 -*-
import random
def run():
number_foud = False
rand_number = random.randint(0, 20)
while not number_foud:
number = int(input('Intenta un numero: '))
if number == rand_number:
print('Felicidades encontraste el numero')
number_foud = True
elif number > rand_number:
print('El numero es pequeno')
else:
print('El numero es mas grande')
if __name__ == '__main__':
run()
|
7f5c247cf0525364ff168c36d11cc9309cd201d6 | KingOfBraves/ChatClient | /ChatWindow.py | 1,065 | 3.6875 | 4 | import curses
def main(stdscr):
newline = False
userinput = ""
chatlog = []
# Clear screen
begin_x = 0; begin_y = 0
height = 24; width = 80
stdscr = curses.newwin(height, width, begin_y, begin_x)
myscreen = curses.initscr()
stdscr.border(0)
stdscr.addstr(0, 0, "Python curses in action!")
stdscr.refresh()
while not newline:
newchar = stdscr.getch()
if chr(newchar) == '\n':
chatlog.append(userinput)
userinput = ""
clear_user_input(stdscr)
update_screen(stdscr, chatlog)
else:
userinput = userinput + chr(newchar)
stdscr.addstr(22, 1, ">" + userinput)
stdscr.refresh()
def user_input():
print "test"
def clear_user_input(stdscr):
stdscr.addstr(22, 1, "> ")
stdscr.refresh()
def update_screen(stdscr, chatlog):
height = 1
for chat in chatlog:
stdscr.addstr(height, 1, chat)
height = height + 1
if __name__ == '__main__':
curses.wrapper(main)
|
efe3953f77767369a3490903b0ee91f27db552d6 | nao-tarrillo/trabajo06 | /doble8.py | 777 | 3.609375 | 4 | import os
# BOLETA DE VENTA
# Declarar variables
cliente,kg,P.u ="",0,0.0
# Input
cliente=os.sys.argv[1]
kg=int(os.sys.argv[2])
P.u=float(os.sys.argv[3])
#Procesing
total= (p.u * kg)
#Verificador
comprador_compulsivo=(total>30)
#Output
print("#########################")
print("######Boleta de venta########")
print("#########################")
print("#")
print("# cliente:", cliente)
print("#item: ",kg,"kg")
print("#P.U: S/.", P.U)
print("#total: S/.",total)
print("##########################")
print("comprador compulsivo", comprador_compulsivo)
# Si el total es mayor a 30 obtendran un bono especial
if (comrador_compulsivo == True)
print ("OBTUVISTE UN BONO ESPECIAL")
else:
print ("GANASTE UN PREMIO ")
#FIN_IF
|
288b522a5b80d0f0388988f41bb5792e688cff65 | nao-tarrillo/trabajo06 | /doble1.py | 791 | 3.5625 | 4 | import os
# BOLETA DE VENTA
# Declarar variables
cliente,nro_granadillas,p.u = "",0,0.0
# Input
cliente=os.sys.argv[1]
nro_granadillas=int(os.sys.argv[2]
p.u=float(os.sys.argv[3])
#Procesing
total= (p.u * nro_granadillas)
#Verificador
comprador_compulsivo=( total > 34 )
#Output
print("#######################")
print("######Boleta de venta######")
print("#")
print("# cliente:", cliente)
print("#item: ",nro_granadillas,"nro_granadillas")
print("#p.u: S/.", p.u)
print("#total: S/.",total)
print("#######################")
print("comprador compulsivo", comprador_compulsivo)
# Si el total es mayor que 34 entonces gana una rifa
if (comrador_compulsivo ==True)
print ("GANASTE UNA RIFA")
else:
print ("GANASTE UN PREMIO")
#FIN_IF
|
011e851683a46a904c0a736522cfd67fc1839469 | nao-tarrillo/trabajo06 | /multiple11.py | 1,587 | 3.59375 | 4 | import os
# BOLETA DE VENTA
# declarar variables
cliente,RUC,carro01,carro02,carro03,precio_del_carro01,precio_del_carro02,precio_del_carro03="",0,"","","",0.0,0.0,0.0
# INPUT
cliente=os.sys.argv[1]
RUC=int(os.sys.argv[2])
carro01=os.sys.argv[3]
carro02=os.sys.argv[4]
carro03=os.sys.argv[5]
precio_del_carro01=float(os.sys.argv[6])
precio_del_carro02=float(os.sys.argv[7])
precio_del_carro03=float(os.sys.argv[8])
# PROCESSING
total=(precio_del_carro01+precio_del_carro02+precio_del_carro03)
# VERIFICADOR
ganancia_de_vendedor=(total==100000)
#OUTPUT
print("#########################")
print("# SAC. TOYOTA-PERU")
print("#########################")
print("# cliente:", cliente)
print("# RUC:", RUC)
print("# carro:", carro01," precio: S/.", precio_del_carro01)
print("# carro:", carro02," precio: S/.", precio_del_carro02)
print("# carro:", carro03," precio: S/.", precio_del_carro03)
print("total: S/.", total)
print("#########################")
print("# ganancia del vendedor:", ganancia_de_vendedor)
# CONDICIONAL MULTIPLE
# si el total supera los S/. 1 000 000.00, ganaste un auto mas
if( total>1000000):
print("Ud ha ganado un auto mas")
# fin_if
# si el total es igual a S/. 1 000 000.00, ganaste una moto
if( total==1000000):
print("Ud ha ganado una moto")
# fin_if
# si el trabajo es menor a S/. 1 000 000.00, ganaste una bicicleta
if( total<1000000):
print("Ud ha ganado una bicicleta")
# fin_if
|
56a9cc1f77675f8e1c51a85c6d52d97a9d858795 | Pratyush576/python | /src/com/python/coding/magicNumber.py | 563 | 3.984375 | 4 | '''
Created on 16-Jun-2018
@author: pratyusk
WAP to return kth magic number where magic number is defined as M=5^m+s^n and m,n>=0
'''
def getMagicNumber(k):
m = 0
n = 0
index = 1
if k == index:
print m,n
return 5 ** m + 5 ** n
while True:
if m == n:
m=0
n += 1
else:
m += 1
index += 1
if index == k:
print m,n
return 5 ** m + 5 ** n
print getMagicNumber(1)
print getMagicNumber(3)
print getMagicNumber(6)
print getMagicNumber(100) |
9c37bf9b3d645c2d319dd0e8aee018c1cf81d548 | Risoko/Algorithm | /sorting_algorithm.py | 6,355 | 3.78125 | 4 | from random import randint
class Sorting:
def __init__(self, table):
assert type(table) == list, "Must be list"
self.table = table
def sort(self, number_sort=4):
"""You can check sorting algorithm
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Quick Sort
5. Merge Sort
6. Radix Sort
7. Counting Sort
"""
dict_with_algo = {
1 : self._bubble_sort_classic(),
2 : self._selection_sort(),
3 : self._insertion_sort(),
4 : self._quick_sort(),
5 : self._merge_sort(),
6 : self._counting_sort(),
7 : self._radix_sort()
}
return dict_with_algo.get(number_sort, 'No algorithm')
def _bubble_sort_classic(self):
"""Bubble Sort Algorithm:
Tmax = theta(n**2)
Tave = theta(n**2)
Tmin = theta(n**2)
Stable: Yes
"""
copyL = self.table[:]
for index in range(len(copyL) - 2, -1, -1):
for idx in range(0, index + 1):
if copyL[idx] > copyL[idx+1]:
copyL[idx], copyL[idx+1] = copyL[idx+1], copyL[idx]
return copyL
def _selection_sort(self):
"""Selection Sort Algorithm:
Tmax = theta(n**2)
Tave = theta(n**2)
Tmin = theta(n**2)
Stable: No
"""
copyL = self.table[:]
for index in range(len(copyL) - 1):
min_idx = index
for index2 in range(index + 1, len(copyL)):
if copyL[min_idx] > copyL[index2]:
min_idx = index2
copyL[index], copyL[min_idx] = copyL[min_idx], copyL[index]
return copyL
def _insertion_sort(self):
"""Insertion Sort Algorithm:
Tmax = theta(n)
Tave = theta(n**2)
Tmin = theta(n**2)
Stable: Yes
"""
copyL = self.table[:]
for index in range(len(copyL) - 1, -1, -1):
idx, key = index + 1, copyL[index]
while idx < len(copyL) and key > copyL[idx]:
copyL[idx-1] = copyL[idx]
idx += 1
copyL[idx-1] = key
return copyL
def _quick_sort(self, A=None, first=0, last=None):
"""Merge Sort Algorithm:
Tmax = theta(nlgn)
Tave = theta(nlgn)
Tmin = O(n**2)
Stable: Yes or No (depends on implementation) my algorithm is no stable
"""
if A is None:
A = self.table[:]
if last is None:
last = len(A) - 1
if first < last:
make_partitaion = self._partition(A, first, last)
self._quick_sort(A, first, make_partitaion - 1)
self._quick_sort(A, make_partitaion + 1, last)
return A
def _partition(self, A, first, last):
"""Function Partition:
Complexity = theta(n)
"""
indicator = first
piwot = A[last]
for index in range(first, last): #bez ostatniego bo tam jest piwot
if A[index] <= piwot:
A[index], A[indicator] = A[indicator], A[index]
indicator += 1
A[indicator], A[last] = A[last], A[indicator]
return indicator
def _merge_sort(self, table=None):
"""Merge Sort Algorithm:
Tmax = theta(nlgn)
Tave = theta(nlgn)
Tmin = theta(nlgn)
Stable: Yes or No (depends on implementation Merge) my algorithm is stable
"""
if table is None:
table = self.table[:]
if len(table) <= 1:
return table
mid = len(table) // 2
left = self._merge_sort(table[mid:])
right = self._merge_sort(table[:mid])
return self._merge(left, right)
def _merge(self, left, right):
"""Function Merge:
Complexity = theta(n)
"""
helpty, idx_left, idx_right = [], 0, 0
while idx_left < len(left) and idx_right < len(right):
if left[idx_left] < right[idx_right]:
helpty.append(left[idx_left])
idx_left += 1
else:
helpty.append(right[idx_right])
idx_right += 1
helpty += left[idx_left:]
helpty += right[idx_right:]
return helpty
def _counting_sort(self):
"""Counting Sort Algorithm:
Tmax = theta(n)
Tave = theta(n)
Tmin = theta(n)
Stable: Yes
"""
A = self.table[:]
counts = [0 for i in range(max(A) + 1)]
for element in A:
counts[element] += 1
for index in range(1, len(counts)):
counts[index] = counts[index-1] + counts[index]
output = [0 for _ in range(len(A))]
for element in A:
index = counts[element] - 1
output[index] = element
counts[element] -= 1
return output
def _radix_sort(self):
"""Counting Sort Algorithm:
Tmax = theta(n)
Tave = theta(n)
Tmin = theta(n)
Stable: Yes
"""
A = self.table[:]
max_value = max(A)
start = 1
while max_value // start > 0:
A = self._counting_sort_radix(A, start)
start *= 10
return A
def _counting_sort_radix(self, A, start):
"""Function Counting Sort:
Complexity = theta(n)
"""
b = [0] * len(A)
count = [0] * 10
for i in range(0, len(A)):
index = A[i] // start
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i-1]
begin = len(A) - 1
while begin >= 0:
index = A[begin] // start
b[count[index % 10] - 1] = A[begin]
count[index % 10] -= 1
begin -= 1
return b
def __repr__(self):
"""Representation object dunder repr"""
return f'{self.table}'
if __name__ == "__main__":
lista = [randint(0, 300) for _ in range(1, 31)]
lista_counting = [randint(0, 9) for _ in range(1, 31)]
test = Sorting(lista)
test2 = Sorting(lista_counting)
print(f'List not sorting: {test} \nList sorting: {test.sort(7)}')
print(f'List not sorting: {test2} \nList sorting: {test2.sort(6)}')
|
5ccb8364af409094c7017bc46701e2978bbf1f40 | Risoko/Algorithm | /hash_table_the_chain_method.py | 1,931 | 3.859375 | 4 | from collections import namedtuple
Position = namedtuple('Position', 'Index_in_HT Data')
class HashTable:
"""Hash table using chain method."""
def __init__(self, size):
assert type(size) == int, "Must be type int"
self.size = size
self.table = [[] for _ in range(size)]
def _function_hash(self, key):
"""Hashing Function"""
return key % self.size
def insert(self, key, data):
"""Insert on hash table:
Tmin = O(1)
Tave = O(1)
Tmax = Theta(n)
"""
bucket = self.table[self._function_hash(key)]
for index in range(len(bucket)):
if bucket[index][0] == key:
bucket[index][1] = data
return
bucket.append([key, data])
return
def search(self, key):
"""Insert on hash table:
Tmin = O(1)
Tave = O(1)
Tmax = Theta(n)
"""
index = self._function_hash(key)
bucket = self.table[index]
for idx in range(len(bucket)):
if bucket[idx][0] == key:
return Position(index, bucket[idx][1])
return Position(False, False)
def delete(self, key):
"""Insert on hash table:
Tmin = O(1)
Tave = O(1)
Tmax = Theta(n)
"""
index = self._function_hash(key)
bucket = self.table[index]
for idx in range(len(bucket)):
if bucket[idx][0] == key:
del bucket[idx]
return True
return False
def __repr__(self):
return f'{self.table}'
if __name__ == "__main__":
a = HashTable(9)
print(a)
print(100 * '*')
for x in range(21):
a.insert(x, x**2)
print(a)
print(100 * '*')
a.insert(0, 100000000)
print(a)
print(a.search(10))
print(100 * '*')
print(a.delete(10))
print(a)
a.insert(1, 11111)
print(a)
|
c5b507b6029076bafb35dc6879dc402f2449eefc | jvasallo/madness-calc | /madness_calc.py | 1,645 | 3.84375 | 4 | #!/usr/bin/python
'''
Every year, I play a March Madness pool where we pay out based on the last digits of the score.
This year, I am too busy to watch all the games or even keep track. So I created this to calculate
how much money I will win!
Sign up for API access @ https://www.kimonolabs.com/signup
'''
import json
import urllib
import pprint
# use your api-key
API_KEY = ""
# change the magic numbers to your win loss numbers.
MAGIC_NUMBERS = [{"w": 2, "l": 6},
{"w": 8, "l": 9},
{"w": 0, "l": 0}]
# Modify the payouts to what your pool pays out
PAYOUTS = {"Play-in": 0.0, "Round of 64": 2.5, "Round of 32": 5.0, "Round of 16": 10.0, "Round of 8": 20.0, "Round of 4": 40.0}
def calculate_win_loss(score1, score2):
if score1 > score2:
win = score1
loss = score2
else:
win = score2
loss = score1
return win, loss
def main():
games = json.load(urllib.urlopen("http://marchmadness.kimonolabs.com/api/games?tournamentGame=true&apikey=%s" % API_KEY))
total_won = 0.0
for each_game in games:
win, loss = calculate_win_loss(each_game['homeScore'], each_game['awayScore'])
for magic_number_set in MAGIC_NUMBERS:
if magic_number_set['w'] == win % 10 and magic_number_set['l'] == loss % 10:
game_round = each_game['tournamentGameInfo']['round']
total_won += PAYOUTS[game_round]
print "Score match in %s: %s - %s" % (game_round, each_game['homeTeamName'], each_game['awayTeamName'])
print "You have won a total of: $%.2f" % total_won
if __name__ == '__main__':
main()
|
079850ec49ec482a6407feb5e5c975e36d896a10 | stelzriede/iRobot | /coloreye.py | 1,871 | 3.75 | 4 |
# PIL Image module (create or load images) is explained here:
# http://effbot.org/imagingbook/image.htm
# PIL ImageDraw module (draw shapes to images) explained here:
# http://effbot.org/imagingbook/imagedraw.htm
from PIL import Image
from PIL import ImageDraw
import time
from rgbmatrix import RGBMatrix, RGBMatrixOptions
# Configuration for the matrix
options = RGBMatrixOptions()
options.rows = 64
options.cols = 64
options.chain_length = 1
options.parallel = 1
options.hardware_mapping = 'adafruit-hat' # If you have an Adafruit HAT: 'adafruit-hat'
options.led_rgb_sequence = 'RBG'
matrix = RGBMatrix(options = options)
# RGB example w/graphics prims.
# Note, only "RGB" mode is supported currently.
# image = Image.new("RGB", (64, 64)) # Can be larger than matrix if wanted!!
# draw = ImageDraw.Draw(image) # Declare Draw instance before prims
# # Draw some shapes into image (no immediate effect on matrix)...
# draw.rectangle((0, 0, 31, 31), fill=(0, 0, 0), outline=(0, 0, 255))
# draw.line((0, 0, 31, 31), fill=(255, 0, 0))
# draw.line((0, 31, 31, 0), fill=(0, 255, 0))
# # Then scroll image across matrix...
# for n in range(-32, 33): # Start off top-left, move off bottom-right
# matrix.Clear()
# matrix.SetImage(image, n, n)
# time.sleep(0.05)
# matrix.Clear()
eye_open = Image.open("colorfuleye.gif").convert('RGB')
matrix.SetImage(eye_open, 0, 0)
eye_half = Image.open("colorfuleye_mid.gif").convert('RGB')
matrix.SetImage(eye_half, 0, 0)
eye_slit = Image.open("colorfuleye_low.gif").convert('RGB')
matrix.SetImage(eye_slit, 0, 0)
eye_closed = Image.open("blank.gif").convert('RGB')
matrix.SetImage(eye_closed, 0, 0)
while True:
matrix.SetImage(eye_open, 0, 0)
time.sleep(2.5)
matrix.SetImage(eye_half, 0, 0)
time.sleep(0.08)
matrix.SetImage(eye_slit, 0, 0)
time.sleep(0.08)
matrix.SetImage(eye_closed, 0, 0)
time.sleep(0.08) |
151272434faf8bfb07b328227b8357c9f19aee83 | geekidharsh/elements-of-programming | /primitive-types/palindrome_number.py | 1,405 | 3.765625 | 4 | import math
# solution 1
def palindrome_num(x):
#brute force algorithm
# considering x>0
# complexity is O(n) where n is the number of digits in x
# space complexity is O(n).
# idea:
# We can use log10 function to cut down space complexity to O(1)
reverse = 0
temp = x
if x<=0:
return 0
else:
try:
while temp:
reverse = reverse*10 + (temp%10)
temp//=10
if x == reverse:
return True
else:
return False
except e:
return e
# test
print(palindrome_num(11))
print(palindrome_num(2221))
print(palindrome_num(1221))
print(palindrome_num(-2221))
# solution 2: time: O(n), space: O(1)
def palindrome_optmized(x):
if x<=0:
return 0
number_of_digits = math.floor(math.log10(x))+1
msd_mask = 10**(number_of_digits-1)
for i in range(number_of_digits//2):
if x//msd_mask != x%10:
return False
else:
x%=msd_mask #removes the msd in x
x//=10 # removes the lsd in x
msd_mask//=100 #100 because we are getting rid of 2 digits every operation, one from either side
return True
# test
print(palindrome_optmized(121))
print(palindrome_optmized(111))
print(palindrome_optmized(1221))
print(palindrome_optmized(12214324325))
# scrap:
# # using an array
# while x:
# x_arr.append(x%10)
# x//=10
# for i in range(len(x_arr)//2):
# if x_arr[i] != x_arr[len(x_arr)-1-x]:
# state = False
# else:
# state = True
# return state |
dbe0e4b02b87fc67dd2e4de9cbaa7c0226f9e58e | geekidharsh/elements-of-programming | /primitive-types/bits.py | 1,870 | 4.5 | 4 | # The Operators:
# x << y
# Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros).
# This is the same as multiplying x by 2**y.
# ex: 2 or 0010, so 2<<2 = 8 or 1000.
# x >> y
# Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
# ex: 8 or 1000, so 8>>2 = 2 or 0010.
# x & y
# Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1,
# otherwise it's 0.
# x | y
# Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0,
# otherwise it's 1.
# ~ x
# Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1.
# This is the same as -x - 1.
# x ^ y
# Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if
# that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.
# https://www.hackerearth.com/practice/notes/bit-manipulation/
# bit fiddle trick is that:
# 1. numbers that are a power of 2, have only one bit set.
# all other numbers will have more than one bit set i.e 1 in more that one places
# in their binary representation
# so 2, 4, 8, 16 etc.
# 2. binary representation of (x-1) can be obtained by simply flipping all the bits
# to the right of rightmost 1 in x and also including the rightmost 1.
# so, x&(x-1) is basically,
# will have all the bits equal to the x except for the rightmost 1 in x.
# 3.
def number_of_bits(x):
# as in number of set bits
bits = 0
while x:
bits += x&1
# right shift by 1 bit every move
x >>=1
return bits
def pos_of_bits(x):
# input: integer
output:
bit_pos = []
bits = 0
while x:
bit_pos.append(x&1)
x >>=1
return ''.join([str(i) for i in reversed(bit_pos)])
print(pos_of_bits('a'))
|
456b6a62ba7b9c3c6a0493d74ff483498ed58ab3 | geekidharsh/elements-of-programming | /linked-lists/listNode.py | 592 | 3.90625 | 4 | class ListNode:
"""docstring for ListNode.
implementing a singly linked list class"""
def __init__(self, data=0, next=None):
self.data = data
self.next = next
def search_list(L, key):
while L and L.data != key:
L = L.next
# if key is not present then None will return
return L
def insert_after(node, newnode):
newnode.next = node.next
node.next = newnode
def delete_after(node):
node.next = node.next.next
def traverse(node):
items = []
while node != None:
items.append(node.data)
node = node.next
return items
if __name__ == '__main__':
main() |
3a60bae93f01f1e9205430277f924390825c598f | geekidharsh/elements-of-programming | /binary-trees/binary-search-tree.py | 1,229 | 4.15625 | 4 | """a binary search tree, in which for every node x
and it's left and right nodes y and z, respectively.
y <= x >= z"""
class BinaryTreeNode:
"""docstring for BT Node"""
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
# TRAVERSING OPERATION
def preorder(root):
# preorder processes root before left and then finally right child
if root:
print(root.data)
preorder(root.left)
preorder(root.right)
def inorder(root):
# inorder processes left then root and then finally right child
if root:
inorder(root.left)
print(root.data)
inorder(root.right)
def postorder(root):
if root:
postorder(root.right)
postorder(root.left)
print(root.data)
# SEARCH in a Binary search tree
def bst_search_recursive(root, key):
if key == root.data or root is None:
return root
if key < root.data:
return bst_search_recursive(root.left, key)
if key > root.data:
return bst_search_recursive(root.right, key)
# TEST
# ----
# sample node a
a = BinaryTreeNode(18)
a.left = BinaryTreeNode(15)
a.right= BinaryTreeNode(21)
# TRAVERSING a binary search tree
inorder(a)
preorder(a)
postorder(a)
# searching
print(bst_search_recursive(a, 14))
|
4c05bf6d559bd0275323dbdb217edc1a2208f59c | geekidharsh/elements-of-programming | /arrays/generate_primes.py | 613 | 4.1875 | 4 | # Take an integer argument 'n' and generate all primes between 1 and that integer n
# example: n = 18
# return: 2,3,5,7,11,13,17
def generate_primes(n):
# run i, 2 to n
# any val between i to n is prime, store integer
# remove any multiples of i from computation
primes = []
#generate a flag array for all element in 0 till n. initialize all items to True
is_primes = [False, False] + [True]*(n-1)
for p in range(2,n+1):
if is_primes[p]:
primes.append(p)
# remove all multiples of p
for i in range(p,n+1,p):
is_primes[i] = False
return primes
print(generate_primes(35))
|
0c41b846d2ff0652d15e6301af071e71b0ad3ebf | premeromb/sistemas_multimedia | /kew_word.py | 355 | 3.53125 | 4 | import speech_recognition as sr
r = sr.Recognizer()
file = sr.AudioFile("output.wav")
print("eeee")
while(True):
with file as source:
r.adjust_for_ambient_noise(source)
audio = r.record(source)
result = r.recognize_google(audio,language='es')
if "hola" in result.split(' '):
break
print("Done!")
print(result) |
c19d6e9bca7165a6876df918ca2914fba4b8c21d | jinger02/testcodes | /1.py | 211 | 3.953125 | 4 | x=float(input('Enter number of hours...\n'))
while True:
try:
type (x) != float
print('Please enter a number')
except:
print ('Number of hours is', x)
break
|
4c281a3e6b6ff68ee870dc9914072507f649d105 | iepping1/DataProcessing | /Week 1/tvscraper.py | 2,244 | 3.875 | 4 | #!/usr/bin/env python
# Name: Ian Epping
# Student number: N/A
'''
This script scrapes IMDB and outputs a CSV file with highest rated tv series.
'''
import csv
from pattern.web import URL, DOM
TARGET_URL = "http://www.imdb.com/search/title?num_votes=5000,&sort=user_rating,desc&start=1&title_type=tv_series"
BACKUP_HTML = 'tvseries.html'
OUTPUT_CSV = 'tvseries.csv'
rows = []
def extract_tvseries(dom):
'''
Extract a list of highest rated TV series from DOM (of IMDB page).
Each TV series entry should contain the following fields:
- TV Title
- Rating
- Genres (comma separated if more than one)
- Actors/actresses (comma separated if more than one)
- Runtime (only a number!)
'''
#print dom.body.content
for element in dom.by_class('lister-item-content'):
Title = element.by_class('lister-item-header')[0].by_tag('a')[0].content
Rating = element.by_class('ratings-bar')[0].by_tag('strong')[0].content
Genre = element.by_class('genre')[0].content
Stars = element.by_tag('p')[2].by_tag('a')
Stars = [s.content for s in Stars]
Stars = ','.join(Stars)
Runtime = element.by_class('runtime')[0].content
Runtime = Runtime.split()[0]
IMDB = [Title, Rating, Genre, Stars, Runtime]
rows.append(IMDB)
return Title, Rating, Genre, Stars, Runtime
def save_csv(f, tvseries):
'''
Output a CSV file containing highest rated TV-series.
'''
writer = csv.writer(f)
writer.writerow(['Title', 'Rating', 'Genre', 'Stars', 'Runtime'])
# python write file to disk
writer.writerows(rows)
if __name__ == '__main__':
# Download the HTML file
url = URL(TARGET_URL)
html = url.download()
# Save a copy to disk in the current directory, this serves as an backup
# of the original HTML, will be used in grading.
with open(BACKUP_HTML, 'wb') as f:
f.write(html)
# Parse the HTML file into a DOM representation
dom = DOM(html)
# Extract the tv series (using the function you implemented)
tvseries = extract_tvseries(dom)
# Write the CSV file to disk (including a header)
with open(OUTPUT_CSV, 'wb') as output_file:
save_csv(output_file, tvseries)
|
416311218b2fd044c5d9e6ad0e3d51e55e93b722 | laganojunior/Toy-FS | /FSNode_File.py | 1,077 | 3.78125 | 4 | from FSNode import FSNode
class FSNode_File(FSNode):
"""
A file in the file system. Just contains text data
"""
def __init__(self, name, parent):
FSNode.__init__(self, name, parent)
self.data = ""
def get_type(self):
return "FSNODE_FILE"
def write(self, offset, data):
"""
Writes data to the buffer starting at the desired offset. The buffer
will be extended to the needed size.
"""
# Check if the data buffer needs to grow
if offset + len(data) > len(self.data):
# Grow with spaces
self.data = self.data + " " * (offset + len(data) - len(self.data))
# Overwrite the desired area
self.data = self.data[:offset] + data + self.data[offset+len(data):]
def read(self, offset, length):
"""
Reads data from the buffer starting at the desired offset up to the
desired length. If the offset is larger than the file, then an empty
string is returned
"""
return self.data[offset:offset+length]
|
51a3ae2e607f52ab2c79c59344699e52030e1c15 | justindarcy/CodefightsProjects | /isCryptSolution.py | 2,657 | 4.46875 | 4 | #A cryptarithm is a mathematical puzzle for which the goal is to find the correspondence between letters and digits,
#such that the given arithmetic equation consisting of letters holds true when the letters are converted to digits.
#You have an array of strings crypt, the cryptarithm, and an an array containing the mapping of letters and digits,
#solution. The array crypt will contain three non-empty strings that follow the structure: [word1, word2, word3],
#which should be interpreted as the word1 + word2 = word3 cryptarithm.
#If crypt, when it is decoded by replacing all of the letters in the cryptarithm with digits using the mapping in
#solution, becomes a valid arithmetic equation containing no numbers with leading zeroes, the answer is true. If it
#does not become a valid arithmetic solution, the answer is false.
def isCryptSolution(crypt, solution):
word3len=len(crypt[2])
num1 = []
num2 = []
num3 = []
def wordgrab(crypt, solution):
#here i pull a single word from crypt and pass it to wordtonum. I also pass which # word i'm sending
word_count=0
for word in crypt:
word_count=word_count+1
word_letter(word,word_count, solution)
def word_letter(word, word_count, solution):
#here i will pass in a single word and this will pull out each letter #in turn and pass it to letter_num
letter_count=0
for letter in word:
letter_count+=1
letter_num(letter, word_count, solution,letter_count)
def letter_num(letter, word_count, solution,letter_count):
# here i take a letter and use solution to translate the letter to a #num and create num1-3
for list in solution:
if letter == list[0] and word_count==1:
num1.append(list[1])
elif letter == list[0] and word_count==2:
num2.append(list[1])
elif letter == list[0] and word_count==3:
num3.append(list[1])
if word_count==3 and letter_count==word3len:
global answer
answer = output(num1, num2, num3)
def output(num1, num2, num3):
if num1[0]=='0' and len(num1)>1:
return False
elif num2[0]=='0' and len(num2)>1:
return False
elif num3[0]=='0' and len(num3)>1:
return False
number1=int("".join(num1))
number2=int("".join(num2))
number3=int("".join(num3))
if number1 + number2==number3:
return True
else:
return False
wordgrab(crypt, solution)
return(answer)
|
ce6aaa278d8068d8c31bbf5b3dd7ecae192b4019 | Naesen8585/dlive-auto-bot | /text_generator.py | 491 | 3.609375 | 4 | """
Use AI TextGen to generate a response in kind based on the given input.
"""
from aitextgen import aitextgen
import random
ai=aitextgen(model="minimaxir/reddit")
#ai=aitextgen(model="minimaxir/hacker-news")
#ai=aitextgen()
def returngeneratedtext(inputtext,minsize=20, maxsize=50):
return random.choice(ai.generate(n=1, prompt=inputtext, max_length=len(inputtext) + maxsize, return_as_list=True,
min_length=(len(inputtext) + minsize))).split(inputtext)[-1] |
9c01fc72c243846886a7e1f44e5a0ebcce008f7b | sgirimont/projecteuler | /euler1.py | 1,153 | 4.15625 | 4 | ###################################
# Each new term in the Fibonacci sequence is generated by adding the previous two terms.
# By starting with 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values do not exceed four million,
# find the sum of the even-valued terms.
###################################
def product_finder(factors, limit):
product_list = []
x = 0
if 0 in factors:
print('Cannot have a zero as one of the factors.')
else:
while x < len(factors):
if factors[x] > limit:
print('Cannot have a factor larger than the limit value.')
exit()
multiplier = 1
while multiplier <= limit:
if factors[x] * multiplier <= limit and factors[x] * multiplier not in product_list:
product_list.append(factors[x] * multiplier)
else:
break
multiplier += 1
x += 1
product_list.sort()
print(product_list)
product_finder([2001, 5032, 8674], 10000)
|
47c8701c1157d685b845423b8dfd66db568c03fa | dayelu/PythonLearning | /automate-the-boring-stuff-with-python/imgs_operate/img_operte.py | 2,013 | 3.734375 | 4 | import os
from PIL import Image #Pillow库的模块名是PIL,与python的Python Image Library向后兼容所以不是from Pillow ....
class ImgOperate():
"""图像处理的几个例子"""
def __init__(self):
# def __init__(self, catIm):
self.catIm = Image.open("zophie.png") #生成图片对象
def save_as(self):
"""图片另存为其他格式"""
try:
catIm = self.catIm
print(catIm.size)
width,height = catIm.size
print("图片宽为:"+str(width)+",高为:"+str(height))
print("图片格式为:"+catIm.format)
print("图片格式描述:"+catIm.format_description)
catIm.save("zophie.jpg")
print(os.listdir("./"))
except Exception as e:
print(e)
def paint(self,size,file_name,color=0,color_model="RGBA"):
"""简单地绘图"""
try:
im = Image.new(color_model,size,color)
im.save(file_name)
except Exception as e:
print(e)
def copy_paste(self):
"""图片的剪切与复制粘贴"""
try:
catIm = self.catIm
cropedIm = catIm.crop((335,345,565,560))
cropedIm.save("cropped.png")
catCopyIm = catIm.copy()
faceIm = catIm.crop((335,345,565,560))
print(faceIm.size)
catCopyIm.paste(faceIm,(0,0))
catCopyIm.paste(faceIm,(400,500))
catCopyIm.save("pasted.png")
print("复制完成")
except Exception as e:
print(e)
def paste_fill(self):
try:
catIm = self.catIm
faceIm = catIm.crop((335,345,565,560))
catImWidth,catImHeight = catIm.size
faceImWidth,faceImHeight = faceIm.size
catCopyTwo = catIm.copy()
for left in range(0,catImWidth,faceImWidth):
for top in range(0,catImHeight,faceImHeight):
print(left,top)
catCopyTwo.paste(faceIm,(left,top))
catCopyTwo.save("tiled.png")
print("copy完成")
except Exception as e:
print(e)
obj = ImgOperate()
size1 = (100,200)
file_name1 = "purpleImage.png"
color1 = "purple"
size2 = (20,20)
file_name2 = "transparentImage.png"
obj.save_as()
obj.paint(size2,file_name2)
obj.copy_paste()
obj.paste_fill()
|
69feee82e499cc62d01de5fd4bcba5bf94dcd9e9 | prasadboyane/tictactoe | /tictactoe.py | 2,507 | 3.671875 | 4 | from os import system, name
cnt=1
move_player=1
p1=''
p2=''
win_flag=0
l_row1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
def clear():
if name == 'nt':
_ = system('cls')
def print_board():
global win_flag
clear()
b1=' {} | {} | {} '.format(l_row1[0],l_row1[1],l_row1[2])
b3=' {} | {} | {} '.format(l_row1[3],l_row1[4],l_row1[5])
b5=' {} | {} | {} '.format(l_row1[6],l_row1[7],l_row1[8])
print(b1)
print(' ---+---+----')
print(b3)
print(' ---+---+----')
print(b5)
def take_player_names():
print()
print()
p1=input('Enter Player1 Name: ')
print()
p2=input('Enter Player2 Name: ')
print()
print()
start_msg='Lets start the game {} Vs. {}'.format(p1,p2)
print(start_msg)
return p1,p2
def end_win(player,symbol):
global win_flag
win_msg="Player {} with symbol {} has WON the Match!!".format(player,symbol)
print()
print(win_msg)
win_flag=1
def check_if_win(player,l_row1,symbol):
if l_row1[:3]== [symbol,symbol,symbol] or l_row1[3:6]== [symbol,symbol,symbol] or l_row1[6:] == [symbol,symbol,symbol] or l_row1[0]+l_row1[3]+l_row1[6]== symbol+symbol+symbol or l_row1[1]+l_row1[4]+l_row1[7]== symbol+symbol+symbol or l_row1[2]+l_row1[5]+l_row1[8]== symbol+symbol+symbol or l_row1[0]+l_row1[4]+l_row1[8]== symbol+symbol+symbol or l_row1[2]+l_row1[4]+l_row1[6]== symbol+symbol+symbol:
end_win(player,symbol)
def perform_move(player,move,symbol):
if l_row1[int(move)-1] == 'X' or l_row1[int(move)-1] == 'O':
print('This field is already used ! Please choose another one')
take_move_from_player(player,symbol)
l_row1[int(move)-1]=symbol
print_board()
check_if_win(player,l_row1,symbol)
def take_move_from_player(player,symbol):
print()
move_msg='{}, Enter block number: '.format(player)
move= input(move_msg)
perform_move(player,move,symbol)
def take_ip_from_p2():
pass
def start_game(cnt,p1,p2,move_player):
global win_flag
while cnt<=10:
if move_player%2 != 0:
player=p1
symbol='X'
else:
player=p2
symbol='O'
move_player=move_player+1
if win_flag==1:
break
take_move_from_player(player,symbol)
cnt=cnt+1
if __name__== '__main__':
print_board()
p1,p2=take_player_names()
start_game(cnt,p1,p2,move_player) |
1a927dd83e50b1cb4839a5dcb26f2de25b65c336 | elimanzodeleon/simple-ftp | /client/client.py | 5,963 | 3.5 | 4 | import socket
import sys
HEADER = 10
MAX_SIZE = 65536
# ________________
# HELPER FUNCTIONS
# ________________
# Send all data, either control or data connection
# from the specified socket
def send_msg(sock, data):
bytes_sent = 0
# Keep sending till all is sent
while len(data) > bytes_sent:
bytes_sent += sock.send(data[bytes_sent:])
def create_header(msg):
# append white space to len of the data that is being sent
# used to notify server how many bytes to read in from buffer
return f'{len(msg):<{HEADER}}'
# __________
# MAIN LOGIC
# __________
# exit if incorrect number of arguments
if len(sys.argv) != 3:
sys.exit('USAGE python: client.py <SERVER MACHINE> <SERVER PORT>')
# server name, ip, port
server_name = sys.argv[1]
server_ip = socket.gethostbyname(server_name)
server_port = int(sys.argv[2])
server_addr = (server_ip, server_port)
# client socket used for connection to server
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect client socket to server socket at 127.0.0.1:9999
client_socket.connect(server_addr)
# TEST
m_len = int(client_socket.recv(HEADER).strip().decode()) # welcome message len
msg = client_socket.recv(m_len).decode() # receive actual message len
# msg = recv_all(client_socket)
print(msg)
while True:
cmd = input('FTP > ').lower()
action = cmd.split(' ')[0]
if action == 'quit':
# header if user entered quit
cmd_len = create_header(cmd)
# send user cmd to server (header(len of cmd)+cmd)
send_msg(client_socket, cmd_len.encode()+cmd.encode())
print('successfully disconnected from server')
break
elif action in ['get', 'put', 'ls']:
# create eph port
client_data_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to port 0
client_data_socket.bind(('', 0))
# Retrieve the ephemeral port number
client_data_port = client_data_socket.getsockname()[1]
# Start listening on the socket (client side)
client_data_socket.listen(1)
# header if user entered get <FILE>, this header includes eph port
cmd = f'{cmd} {str(client_data_port)}'
cmd_len = create_header(cmd)
send_msg(client_socket, cmd_len.encode()+cmd.encode())
# accept connection from server
server_data_socket, server_data_addr = client_data_socket.accept()
if action == 'get':
# name under which file sent from server will be saved
file_name = cmd.split(' ')[1]
# check msg from server on file status
status_len = int(client_socket.recv(HEADER).decode().strip())
# reveive the next 'status_len' bytes from the buffer
file_status = client_socket.recv(status_len).decode()
# notify user if file dne on server
if file_status[0] == '1':
print(file_status[2:])
continue
bytes_received = 0
while True:
# receive file chunk size
file_chunk_size = int(server_data_socket.recv(HEADER).decode().strip())
# receive file chunk
file_chunk = server_data_socket.recv(file_chunk_size)
# print(f'chunk received: {file_chunk.decode()} with size {file_chunk_size}')
# write file chunk to file
# 'ab': if file dne, new file created
# else the chunk is appended to the file
with open(file_name, 'ab') as new_file:
new_file.write(file_chunk)
if file_chunk_size < MAX_SIZE:
# last chunk received, we can exit
break
# close socket
client_data_socket.close()
elif action == 'put':
file_name = cmd.split(' ')[1]
try:
with open(file_name, 'rb') as f:
file_content = f.read()
# size of file to keep track of how much needs to be sent
file_size = len(file_content)
# num of bytes keeps track of bytes sent
bytes_sent = 0
# send file in chunks
while bytes_sent < file_size:
if bytes_sent + MAX_SIZE < file_size:
file_chunk = file_content[bytes_sent:bytes_sent+MAX_SIZE]
else:
file_chunk = file_content[bytes_sent:]
# send file chunk to server
file_chunk_header = create_header(file_chunk)
send_msg(server_data_socket,
file_chunk_header.encode()+file_chunk)
bytes_sent += MAX_SIZE
except FileNotFoundError:
print('File does not exist')
# close socket
client_data_socket.close()
elif action == 'ls':
bytes_received = 0
while True:
# size of chunk sent by server
chunk_size = int(server_data_socket.recv(HEADER).decode().strip())
# receive chunk from server and decode since printing to console
ls_chunk = server_data_socket.recv(chunk_size).decode()
# print server ls output in client
print(ls_chunk)
if chunk_size < MAX_SIZE:
# last chunk so we can exit loop
break
# close server data socket
server_data_socket.close()
else:
print('USAGE:\
\n\tFTP > get <FILENAME> # download <FILENAME> from server\
\n\tFTP > put <FILENAME> # upload <FILENAME> to server\
\n\tFTP > ls # list files on server\
\n\tFTP > quit # disconnect from server and exit')
# close persistent control connection
client_socket.close()
|
b0b771a0664e93a79f4a83accee25ba5ef25b28e | schipkovalina/Programming | /hw12/hw12.py | 577 | 3.625 | 4 | #Вариант3
import os
import re
def search():
folders = []
for folder in os.listdir():
if os.path.isdir(folder):
dirpath, filename = os.path.split(folder)
r = re.search("[a-zA-Z0-9]|[,—\[\]↑№!\"\'«»?.,;:-|/+*{}<>@#$%-^&()]", filename)
if not r:
folders.append(filename)
return folders
def count(folders):
print("Папок, название которых состоит только из кириллических символов:", int(len(folders)))
count(search())
|
d0017e98c44520ead1b1220b3b6fdb38be5f9c4e | schipkovalina/Programming | /hw3/homework3.py | 204 | 3.921875 | 4 | #Вариант3
word = input('Введите слово ')
print(word)
for i in range(0, len(word)-1):
a = []
a.append(word[1:])
a.append(word[0])
b="".join(a)
word = b
print(b)
|
625d06f5ed42042e6c4b30527a0f374f5e22cb4e | Hikari9/Matching | /clustering.py | 7,441 | 3.78125 | 4 | from collections import defaultdict
from suffix import SuffixArray
from edistance import *
import numpy as np
'''
Algorithm: stem_cluster(data [, mode, length_at_least] )
A clustering algorithm that bases from word frequency
and stem trimming/lemmatizing. The goal of the algorithm
is to reduce the data into a list of important words
that can be used for machine learning and analysis.
Parameters:
data
- string [...]
- a list of string data to cluster
- assumed to be already clean
mode
- int [0, INF)
- the allowed frequency that includes the word as
part of the list
length_at_least
- int [0, INF)
- the minimum length that determines if a word
can be part of the list
'''
stemmer = None
def stem_cluster(data, mode = 10, length_at_least = 3):
global stemmer
# load default stemmer (nltk lemmatizer)
if stemmer == None:
try: # import if corpus exists
from nltk.stem import WordNetLemmatizer
except: # download corpora if does not exist
import nltk
if not nltk.download('wordnet'):
raise Exception('Error in downloading wordnet. \
Please make sure you are connected to the network, \
or try downloading manually.')
from nltk.stem import WordNetLemmatizer
# cache the default stemmer
stemmer = WordNetLemmatizer()
# port the lemmatizer as the stemmer
stemmer.stem = stemmer.lemmatize
from algoutils import flatten, split
from collections import defaultdict
# split data into words
words = flatten(split(data, ' '))
# collect frequency of individual words
frequency = defaultdict(int)
for word in words:
if len(word) >= length_at_least:
frequency[word] += 1
# filter words by frequency
words = filter(lambda (word,freq): freq >= mode, frequency.items())
words = list(zip(*words)[0])
# trim stems
stem_map = defaultdict(list)
stem = stemmer.stem
for word in words:
stem_map[stem(word)].append(word)
# only return representative
# aka. the word with least length
return map(lambda rep: min(rep, key=len), stem_map.values())
'''
Algorithm: double_cluster(data)
A recursive double-clustering algorithm that is dependent on
common substring length and pairwise Levenshtein (edit) distances.
The first step of this algorithm is grabbing clusters of data
(see cluster method) using the current min_common substring length
threshold. After which, the algorithm checks if subclusters are
expandable. In this case, the parameter min_common increments
by step amount.
Parameters:
data
- string [...]
- a list of string data to cluster
min_common (optional)
- float (0, INF)
- the minimum common substring length that
would be considered to be 'similar'
step (optional)
- float (0, INF)
- value for which min_common would increment
when a next level of clustering is needed
eps (optional)
- float (0, 1]
- allowed median edit ratio for a cluster
to be considered final
leaf_size (optional)
- int [1, INF)
- the maximum leaf-cluster size
- threshold for when to calculate for
brute force pairwise edit distances
algorithm (optional)
- 'lattice' or 'dense'
- lattice: uses strict integer-based common
substring length clustering
- dense: uses density-based common
substring length clustering
heirarchy (optional)
- boolean
- display clusters in a heirarchy or not
'''
def double_cluster(data, min_common = 3, step = 1, eps = 0.4, leaf_size = 60, algorithm = 'lattice', heirarchy = True):
# immediately instantiate into suffix array for later
if isinstance(data, SuffixArray):
suffix_array = data
data = suffix_array.data
else:
# base case: check first if singleton
if len(data) == 1: return data
suffix_array = SuffixArray(data)
# draft initial clusters
if algorithm == 'lattice':
draft = lattice_spanning(suffix_array, min_common)
elif algorithm == 'dense':
draft = dense_spanning(suffix_array, min_common)
if len(draft) == 1:
# special case
# no valid clustering found using current parameters
# reuse suffix array to avoid recomputation
return double_cluster(suffix_array, min_common + step, step, eps, leaf_size, algorithm, heirarchy)
final_clustering = []
for subcluster in draft:
# check first if subcluster is expandable or not
if len(subcluster) <= leaf_size and edit_radius(subcluster, eps) <= eps:
# subcluster is ok, no need for expansion
final_clustering.append(subcluster)
else:
# subcluster can still be expanded
expanded = double_cluster(subcluster, min_common + step, step, eps, leaf_size, algorithm, heirarchy)
if heirarchy: final_clustering.append(expanded)
else: final_clustering.extend(expanded)
# keep big clusters in front
return sorted(final_clustering, key=len, reverse=True)
# filters noise based on expected feature count
def dense_spanning(data, min_common = 8):
if isinstance(data, SuffixArray):
suffix_array = data
data = suffix_array.data
else:
suffix_array = SuffixArray(data)
graph = suffix_array.similarity_graph()
eps = 2 ** min_common
graph = filter(lambda x: x[1] >= eps, graph)
ind = spanning_tree(graph, len(data))
return [map(lambda i: data[i], row) for row in ind]
# filters noise based on actual features count
def lattice_spanning(data, min_common = 10):
if isinstance(data, SuffixArray):
suffix_array = data
data = suffix_array.data
else:
suffix_array = SuffixArray(data)
f = range(len(data))
def find(x):
if x == f[x]:
return x
f[x] = find(f[x])
return f[x]
for conn in suffix_array.connectivity(min_common):
for i in xrange(conn.start + 1, conn.stop):
a = suffix_array.G[suffix_array[i-1]]
b = suffix_array.G[suffix_array[i]]
f[find(a)] = find(b)
m = [[] for x in xrange(len(data))]
for i in xrange(len(f)):
m[find(i)].append(data[i])
all = filter(lambda x: len(x) != 0, m)
return all
# O(nlogn) clustering, maximum cost DATA spanning forest
def spanning_forest(data, n_clusters = 2):
graph = data.similarity_graph() if isinstance(data, SuffixArray) else SuffixArray(data).similarity_graph()
ind = spanning_tree(graph, len(data), n_clusters)
return [map(lambda i: data[i], row) for row in ind]
# O(nlogn) clustering, maximum cost spanning forest
def spanning_tree(graph, n, n_clusters = 1):
needed = n - n_clusters
if needed <= 0: return [[i] for i in xrange(n)]
edges = sorted(graph, key=lambda x:x[1], reverse=True)
f = range(n)
def find(x):
if x == f[x]: return x
f[x] = find(f[x])
return f[x]
for e in edges:
a = find(e[0][0])
b = find(e[0][1])
if a != b:
f[a] = b
needed -= 1
if needed == 0:
break
# collect clusters
clusters = [[] for i in f]
for i in xrange(n):
clusters[find(i)].append(i)
return filter(lambda x: len(x) > 0, clusters)
# assigns a representative for each subcluster
# uses minimal pairwise Levenshtein distance
depth = 0
def test_label_heirarchy(tree, verbose = True):
global depth
depth += 1
if not isinstance(tree, list):
if verbose: print ('-' * depth) + '+ %s' % (tree)
depth -= 1
return (tree, None)
subtree = map(label_heirarchy, tree)
label, child = zip(*subtree)
dist = [np.average([edit_ratio(a, b) for b in label]) for a in label]
id = min(range(len(dist)), key=lambda x: dist[x])
if verbose: print ('-' * depth) + '+ %s' % (label[id])
depth -= 1
return (label[id], list(zip(label, child)))
|
0cb9e3c2b63ef3790fedf2bc06b7a6e15e4c7e1d | dmangialino/shopping-cart | /shopping_cart.py | 7,433 | 3.890625 | 4 | # shopping_cart.py
# Program utilizes to_usd function provided by Professor Rossetti to convert values to USD format
def to_usd(my_price):
"""
Converts a numeric value to usd-formatted string, for printing and display purposes.
Param: my_price (int or float) like 4000.444444
Example: to_usd(4000.444444)
Returns: $4,000.44
"""
return f"${my_price:,.2f}" #> $12,000.71
# Import os to read variables from .env file
# Import read_csv from pandas to process CSV
# Import requirements for sendgrid to enable emailing receipts
import os
from dotenv import load_dotenv
from pandas import read_csv
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
load_dotenv()
# Get tax rate from .env file
TAX_RATE = os.getenv("TAX_RATE", default="0.0875")
# Capture date and time at beginning of checkout process
# Code for date and time adopted from thispointer.com and Stack Overflow for AM/PM (links below)
# https://thispointer.com/python-how-to-get-current-date-and-time-or-timestamp/
# https://stackoverflow.com/questions/1759455/how-can-i-account-for-period-am-pm-using-strftime
from datetime import datetime
timestamp = datetime.now()
timestampStr = timestamp.strftime("%b-%d-%Y %I:%M %p")
# Read products.csv file to create DataFrame and convert to Python dictionary
csv_filepath = "products.csv"
products_df = read_csv(csv_filepath)
products = products_df.to_dict("records")
# Create list of valid IDs against which to compare user input
# When creating list, covert values from int to str to enable comparison with user input
valid_ids = []
for identifier in products:
valid_ids.append(str(identifier["id"]))
# Create list of IDs with prices per pound
price_per_pound = []
for identifier in products:
if(identifier["price_per"] == "pound"):
price_per_pound.append(str(identifier["id"]))
# Welcome user and provide instructions on how to use the app
print("Hello, welcome to Ollie's Grocery's checkout application!")
print("---------------------------------")
print("You will be prompted to enter the product identifiers for each product.")
print("When you are done entering all product identifiers, enter 'DONE'.")
print("---------------------------------")
# Capture product IDs until user is finished using an infinite while loop using modified code based on that provided in class
# If user enters a product that is priced per pound, prompt user to indicate number of pounds and add value to pounds list
selected_ids = []
pounds = []
while True:
selected_id = input("Please input a product identifier: ")
if selected_id.upper() == "DONE":
break
else:
# Verify that the product ID is valid
if(selected_id in valid_ids):
if(selected_id in price_per_pound):
# Error handling to ensure input provided by user is a valid number
# Utilized Python documentation for error handling code (https://docs.python.org/3/tutorial/errors.html)
try:
lbs = float(input("How many pounds? "))
pounds.append(float(lbs))
# If valid, append to the selected_ids list
selected_ids.append(selected_id)
except ValueError:
print("Oops! That was not a valid number. Please re-enter the product identifier to try again.")
else:
selected_ids.append(selected_id)
# If it is not valid, print error message and return to beginning of while loop
else:
print("Are you sure that product identifier is correct? Please try again!")
print("---------------------------------")
# Ask user if they want an email receipt
while True:
email_receipt = input("Would you like your receipt via email? Please enter 'y' for yes or 'n' for no: ")
email_address = ""
if(email_receipt == "y"):
# Prompt user to provide email address to which the receipt will be sent
email_address = input("Please enter the email address to which you would like the receipt to be sent: ")
print("Ok, we will send an email receipt to ", email_address)
break
elif(email_receipt == "n"):
print("Ok, we will not send a receipt via email.")
break
else:
print("We're sorry, that input was invalid. Please try again!")
# Print top portion of receipt, including timestamp (date and time)
print("---------------------------------")
print("OLLIE'S GROCERY")
print("WWW.OLLIES-GROCERY.COM")
print("---------------------------------")
# Print timestamp (date and time) of checkout
print("CHECKOUT AT:", timestampStr)
print("---------------------------------")
print("SELECTED PRODUCTS:")
# Perform product lookups to determine each product's name and price
subtotal = 0
counter = 0
html_list_items = []
for id in selected_ids:
# Display the selected product's name and price
matching_products = [p for p in products if str(p["id"]) == str(id)]
matching_product = matching_products[0]
if(matching_product["price_per"] == "pound"):
subtotal += float(matching_product["price"]) * pounds[counter]
price = to_usd(float(matching_product["price"]) * float(pounds[counter]))
counter = counter + 1
else:
subtotal += float(matching_product["price"])
price = to_usd(matching_product["price"])
print(" ...", matching_product["name"], f"({price})")
html_list_items.append(f'{matching_product["name"]}, ({price})')
# Print subtotal
print("---------------------------------")
subtotal_usd = to_usd(subtotal)
print("SUBTOTAL:", subtotal_usd)
# Print tax and total with tax (sum of subtotal and tax) using tax rate specified in .env file
# Need to convert TAX_RATE from .env file from str to float before performing multiplication with subtotal
tax = subtotal * float(TAX_RATE)
tax_usd = to_usd(tax)
print("TAX:", tax_usd)
total_usd = to_usd(subtotal+tax)
print("TOTAL:", total_usd)
print("---------------------------------")
# Send email receipt
# Modified code provided by Professor Rossetti (link below)
# https://github.com/prof-rossetti/intro-to-python/blob/main/notes/python/packages/sendgrid.md
SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY", default="OOPS, please set env var called 'SENDGRID_API_KEY'")
SENDER_ADDRESS = os.getenv("SENDER_ADDRESS", default="OOPS, please set env var called 'SENDER_ADDRESS'")
client = SendGridAPIClient(SENDGRID_API_KEY)
subject = "Your Receipt from Ollie's Grocery"
html_content = f"""
<h3>Your Receipt from Ollie's Grocery</h3>
<p>WWW.OLLIES-GROCERY.COM</p>
<p>------------------------------------------------</p>
<p>CHECKOUT AT: {timestampStr}</p>
<p>------------------------------------------------</p>
<p>ITEMS PURCHASED:</p>
<ol>
{html_list_items}
</ol>
<p>------------------------------------------------</p>
<p>SUBTOTAL: {subtotal_usd}</p>
<p>TAX: {to_usd(tax)}</p>
<p>TOTAL: {to_usd(subtotal+tax)}</p>
"""
message = Mail(from_email=SENDER_ADDRESS, to_emails=email_address, subject=subject, html_content=html_content)
try:
response = client.send(message)
if(response.status_code == 202):
print("Email receipt sent successfully!")
except Exception as err:
print("No email receipt sent.")
# Display thank you message to user
print("---------------------------------")
print("Thank you! See you again soon!")
print("---------------------------------")
|
a9b4eca6c841bea81483fb8e048c53323b2c49d1 | paulionele/particle-diffusion | /misc/cell_creator.py | 574 | 3.6875 | 4 | '''
This script is functioning as expected.
Creates a list of values, elements of either 1 or 0 depending on specifications.
'''
j = 1 #flip the j,k bits to start with cellular or extracellular.
k = 0
lic = 4 #number of cells in intracellular unit cell.
lec = 2 #number of cells in extracellular unit cell.
lsc = 7 #total number of super cells, odd number for symmetry.
ct = [] #generated array
for i in range(0, lsc):
if j!=0:
for cell in range(0,lic):
ct.append(1)
j = 0
k = 1
elif k!=0:
for cell in range(0,lec):
ct.append(0)
j = 1
k = 0
print(ct)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.