blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
f7096392602abe5e76af20de9fe6dd2f94e68deb | pete5431/PKI-Implementation | /shared_info.py | 5,677 | 3.5625 | 4 | # The DES algorithm used is from the pycryptodome package.
from Crypto.Cipher import DES
import random
import string
import base64
"""
The pycryptodome package uses C language code. Therefore in order use strings with pycryptodome functions, bytes objects are used.
"""
class SharedInfo:
"""
Class that holds the infomration for ports, and host. Also contains encryption/decryption functions and keys.
"""
HOST = '127.0.0.1'
PORT_CA = 54643
PORT_S = 57894
ID_CA = "ID-CA"
ID_Server = "ID-Server"
DEFAULT_KEY = b'default_'
def __init__(self, KEY = DEFAULT_KEY):
"""
Constructor for ServerInfo.
-Uses default values if none are provided.
"""
self.DESKEY = KEY
self.HMACKEY = KEY
# DES object from pycryptodome used for DES encryption.
self.DES = DES.new(self.DESKEY, DES.MODE_ECB)
def read_des_key(self, filename):
"""
Reads the des key from des_key.txt
-Will read the first 8 bytes because key is 8-bytes.
"""
key_file = open(filename, 'r')
self.DESKEY = bytes(key_file.read(8), 'utf-8')
self.DES = DES.new(self.DESKEY, DES.MODE_ECB)
key_file.close()
def set_des_key(self, key):
"""
Set the des key to the passed key.
"""
self.DESKEY = key
self.DES = DES.new(self.DESKEY, DES.MODE_ECB)
def generate_des_key(self):
"""
Generates a random key of size 8 with alphanumeric + special characters.
"""
chars = string.ascii_letters + string.digits + string.punctuation;
key_list = []
for i in range(0,8):
key_list.append(random.choice(chars))
key = ''.join(key_list)
return key
def encrypt_message(self, plain_text):
"""
Takes the plaintext and returns the DES encrypted ciphertext.
-The DES algorithm is the one given by pycryptodome.
-ECB mode is used.
-Encodes resulting ciphertext with base64.
-Encodes plaintext to bytes because of pycryptodome using C.
-Expects plain_text to be a string argument.
-Returned cipher_text is in bytes.
-Uses PKCS5 padding to ensure message is multiple of 8.
-Pads with byte that are the same value as the number of padding bytes to be added.
"""
# Convert to bytes using utf-8 encoding.
plain_text = bytes(plain_text, 'utf-8')
# Calculates the number of padding bytes required.
pad_value = (8 - len(plain_text) % 8)
# If 8, then the message is ok as is.
if pad_value != 8:
# Convert the padding value to ASCII and multiply by itself and append to message.
plain_text += (pad_value * bytes(chr(pad_value), 'utf-8'))
cipher_text = self.DES.encrypt(plain_text)
cipher_text = base64.b64encode(cipher_text)
return cipher_text
def decrypt_message(self, cipher_text):
"""
Takes the ciphertext and key and returns the DES decrypted plaintext.
-The DES algorithm is the one given by pycryptodome.
-ECB mode is used.
-Decodes base64 then uses decrypt function of the DES object.
-Argument is in bytes.
-Returned plain_text is a string.
"""
cipher_text = base64.b64decode(cipher_text)
plain_text = self.DES.decrypt(cipher_text)
return self.unpad_message(plain_text.decode('utf-8'))
def split_message(self, message):
"""
Takes a string input with prepended lengths and fetches all components of the string and puts them in a list.
"""
new_list = []
part = ''
index = 0
while index != len(message):
b_length = bytes(message[index:index+2], 'latin-1')
length = int.from_bytes(b_length, 'little')
index += 2
for c in message[index:index+length]:
part += c
index += 1
new_list.append(part)
part = ''
return new_list
def prepend_length(self, message):
"""
Prepends the length of the message.
-Max 2 bytes.
-A max length of 65535 characters should be enough.
"""
length = len(message)
if length >= 65536:
print("Error: length too large")
return ''
b_length = length.to_bytes(2, 'little')
return b_length.decode('latin-1') + message
def unpad_message(self, message):
"""
Unpads the message so that original message is obtained.
-Checks the last value in the message, which will be the padding value if padding was added.
-Then checks to make sure the count of the padding value matches the padding value.
"""
# If length of message is zero. Return message.
if(len(message) == 0):
return message
# Uses ord() to convert last value to int value.
pad_value = ord(message[-1])
# If the padded value is not 1-7, then no padding was added.
if pad_value not in range(1,8):
return message
i = -2
counter = 1
# Loop to count the number of padding values.
while message[i] == message[-1]:
counter+=1;
i-=1;
# If the number of padding values equals the padding value then padding was used.
if counter == pad_value:
# Return the message without the padding.
return message[0:-pad_value]
else:
return message
|
0de2b02083c8ce7beb247e33ddc95e7f5bc40cfd | UWSEDS/hw2-using-functions-PrivacyEngineer | /analysis/usingfunctions.py | 2,662 | 3.859375 | 4 | # Data 515, Software Engineering for Data Scientists
# Homework 2
# M.S. Data Science, University of Washington, Spr. 2019.
# Francisco Javier Salido Magos.
import requests
import io
import pandas as pd
def test_create_dataframe(newdf):
"""
Compares a preselected dataframe to a new dataframe for similarity.
The function takes a preselected dataframe (df) and compares it to a new
dataframe (newdf), to see if a set of similarity conditions are met.
Similarity conditions are: a) The schema of newdf, its columns and column
data types are the same as those of df, and b) If the number of rows in
newdf is 10 or greater. The only input parameter is newdf, but two global
variables that describe df are also expected: A LIST type variable
(columns_df) containing the column names of df, listed in alphabetical
order. A LIST type variable (data_types_df) containing the data type for
each column in df, listed in the same order as columns_df. Output will be
True if all conditions are met, and False otherwise.
"""
# First compare the shape of newdf to see if it matches requirements.
if(newdf.shape[0] >= 10 and newdf.shape[1] == len(columns_df)):
# Sort newdf columns to compare column names and data types to df.
newdf = newdf.reindex(sorted(newdf.columns), axis=1)
if(list(newdf.columns) == columns_df and
list(newdf.dtypes) == data_types_df):
return True
pass
return False
pass
return False
# Read data from original online source and create dataframe from question 1.
url = ("http://data-seattlecitygis.opendata.arcgis.com/datasets/"
"a2e1128bd7a041358ce455c628ec9834_8.csv")
req = requests.get(url)
assert req.status_code == 200
raw_df = pd.read_csv(io.StringIO(req.text))
# Creating dataframe (df) for question 1 from raw data downloaded from Seattle
# city website.
df = raw_df[["X", "Y", "TYPE", "SCHOOL", "WEBSITE"]]
df = df.reindex(sorted(df.columns), axis=1)
# Extracting column names and data types.
columns_df = list(df.columns)
data_types_df = list(df.dtypes)
# Comparing the full (raw) dataframe downloaded from Seattle city website
# and df.
if test_create_dataframe(raw_df):
print("\nConditions hold\n")
else:
print("Fail: Conditions do not hold\n")
# Comparing df to a subset of df.
if test_create_dataframe(df.iloc[:11]):
print("Conditions hold\n")
else:
print("Fail: Conditions do not hold\n")
# Comparing df to a subset of df, but the subset is too small.
if test_create_dataframe(df.iloc[:5]):
print("Conditions hold\n")
else:
print("Fail: Conditions do not hold\n")
|
4fdc509cf7ccd024cbb5a462ec7b6fc5963c7fe6 | Novandev/interview_prep_python | /interview_questions/permutation_backtracking.py | 2,305 | 3.96875 | 4 | """
"""
def permutation_maker(a, n, k, depth, used, current_permutation = [], permutations = []):
'''
Implement permutation of k items out of n items
a: the list we will make permutations out of
n: the length of the list as a sentonel value
k: The sentinel value that tracks how deep the recursion should go
depth: start from 0, and represent the depth of the search
used: track what items are in the partial solution from the set of n
current_permutation: the current partial solution
permutations: collect all the valide solutions
Algorithm:
1. check the base case of k, if k ( the number of times we want the permutation to run) is equal to the depth
if it does appendthe list that we will make below to the permutations array, with a deep copy and return
2. for each element in the array
if in the used array, the position hasnt been processed:
append the current variable to the current permutation
set the position of this in the used array to True to signalits been processed
recurse the function, but increse the depth
'''
if depth == k: # if the "depth" is equal to the stopping point k
permutations.append(current_permutation[::]) # use deepcopy because current_permutation is tracking all partial solution, it eventually becomes []
return #return up the stak as the work is done here
for i in range(n): # go over every variable in ever recursive call
print(i)
print(used)
if not used[i]: # If the used array that tracks whats been used in the recursive call for this iteration of n hasent been done
current_permutation.append(a[i]) # To the current permutation array, append the data at the current postision to the array we're in
used[i] = True # For this current iteration
print(current_permutation)
# move to the next solution
permutation_maker(a, n, k, depth+1, used, current_permutation, permutations)
# When the recursion has finished
current_permutation.pop()
print('backtrack: ', current_permutation)
used[i] = False
return
a = [1, 2, 3,4]
n = len(a)
k = len(a)
# Used is a list that will track wether or not
used = [False] * len(a)
ans = []
permutation_maker(a, n, k, 0, used, [], ans)
print(ans) |
31a04058a3931c405cd83d47aa20d8ade4bc514e | viktoriasin/crypto_mai | /sem2/task2/gcd_lib.py | 1,033 | 3.8125 | 4 | import typing as tp
# рекурсивная реализация - плохо для больших чисел
def gcd_recursive(a: int, b: int) -> int:
a = abs(a)
b = abs(b)
if a == 0:
return b
if b == 0:
return a
if a >= b:
return gcd_recursive(a % b, b)
else:
return gcd_recursive(a, b % a)
# нерекурсивная реализация
def gcd_not_recursive(a: int, b: int) -> int:
a = abs(a)
b = abs(b)
if a < b:
a, b = b, a
while b != 0:
temp = a % b
a = b
b = temp
return a
# двоичная реализация - наиболее эффективная
def gcd_binary(a: int, b: int) -> int:
g = 1
while (a % 2 == 0) and (b % 2 == 0):
a /= 2
b /= 2
g *= 2
while a != 0:
while a % 2 == 0:
a /= 2
while b % 2 == 0:
b /= 2
if a >= b:
a = (a - b) / 2
else:
b = (b - a) / 2
return g * b
|
6690f507189ad0cff4d8a6e239436fefcf7e8b62 | hector81/Aprendiendo_Python | /Excepciones/Ejercicio3_posicion_lista_ValueError.py | 869 | 4.21875 | 4 | '''
EJERCICIOS EXCEPCIONES
3. Función que recibe una lista y el elemento a buscar, devolviendo
su posición si existe, y -1 en caso de que no (ValueError)
[Pista: podemos usar la función list.index(value)]
'''
def encontrarPosicion_Elemento_enLista(lista,elemento):
while True:
try:
return lista.index(elemento)
break
except ValueError:
return -1
listaAnimales = ["Perro", "Gato", "Murcielago", "Cobra", "Avispa"]
print(listaAnimales)
animal1 = "Cobra"
print(f"El elemento 1 a buscar es {animal1}")
print(f"El elemento está en la posición = {encontrarPosicion_Elemento_enLista(listaAnimales,animal1)}")
animal2 = "Orca"
print(f"El elemento 2 a buscar es {animal2}")
print(f"El elemento está en la posición = {encontrarPosicion_Elemento_enLista(listaAnimales,animal2)}")
|
21d93929d4b288ca88ab29ae8ea0a31f8c36910f | JudyXhen/2017A2CS | /Ch27/Task27.08.py | 1,302 | 3.6875 | 4 | class Assessment:
def __init__(self, t, m):
self.__AssessmentTitle = t
self.__MaxMarks = m
def OutputAssessmentDetails(self):
print(self.__AssessmentTitle, "Marks: ", self.__MaxMarks)
class Course:
def __init__(self, t, m): # sets up a new course
self.__CourseTitle = t
self.__MaxStudents = m
self.__NumberOfLessons = 0
self.__CourseLesson = []
self.__CourseAssessment = Assessment
def AddLesson(self, t, d, r):
self.__NumberOfLessons = self.__NumberOfLessons+ 1
self.__CourseLesson.append(Lesson(t, d, r))
def AddAssessment(self, t, m):
CourseAssessment = Assessment(t, m)
def OutputCourseDetails(self):
print(self.__CourseTitle, end=' ')
print( "Maximum number of students: ", self.__MaxStudents)
for i in range(self.__NumberOfLessons):
print(self.__CourseLesson[i].OutputLessonDetails())
class Lesson:
def __init__(self, t, d, r):
self.__LessonTitle = t
self.__DurationMinutes = d
self.__requiresLab = r
def OutputLessonDetails(self):
print(self.__LessonTitle, self.__DurationMinutes)
def Main():
MyCourse = Course("CS", 10)
MyCourse.AddAssessment("Business", 20)
MyCourse.AddLesson("Maths", 30, False)
MyCourse.AddLesson("EnglishB", 40, True)
MyCourse.AddLesson("Physics", 50, False)
MyCourse.OutputCourseDetails()
Main()
|
c4f856003eb61a5a3b37d59d6a98e12ff0472eda | DBordeleau/YOFHLDraftLottery | /lottery.py | 877 | 3.859375 | 4 | import numpy as np
lotteryTeams = []
x = 14
#Prompt user to enter the 6 lottery teams
for _ in range(6):
team = input('Enter the owner of the ' + str(x) + 'th place seed: ')
x = x-1
lotteryTeams.append(team)
#Select a winner based on the probabilities specified
Winner = np.random.choice(lotteryTeams, 1, p=[0.35, 0.25, 0.15, 0.10, 0.085, 0.065])
#print(Winner)
#Remove the winner from the draft order and re-insert them in the #1 position
lotteryTeams.remove(Winner)
lotteryTeams.insert(0, Winner)
#Print our draft order in reverse order requiring user input with each pick for added dramatic effect
x = 6
for team in reversed(lotteryTeams):
if x==1 :
input('The team with the first overall pick and the winner of the 2021 YOFHL draft lottery is ' + str(Winner) + '! Congratulations!')
else:
input('The team with pick #' + str(x) + ' is ' + str(team))
x = x-1 |
f4021e8727f0afecf7a0bdc8479df954272d1dde | rafaelperazzo/programacao-web | /moodledata/vpl_data/131/usersdata/172/37508/submittedfiles/al10.py | 199 | 3.734375 | 4 | # -*- coding: utf-8 -*-
#NÃO APAGUE A LINHA ACIMA. COMECE ABAIXO DESTA LINHA
n=int(input('digite um valor'))
i=2
d=3
while 0<n
soma=4*((i/d)*((i+2)/d))
i=i+2
d=d+2
print('%.5d'%soma) |
739903e438fef6c28869523b51671b9c9be9a949 | Jfprado11/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 534 | 3.765625 | 4 | #!/usr/bin/python3
def no_c(my_string):
count_lower_C = my_string.count("c")
count_upper_C = my_string.count("C")
if count_lower_C > 0:
my_string = list(my_string)
while count_lower_C:
my_string.remove("c")
count_lower_C -= 1
my_string = "" .join(my_string)
if count_upper_C > 0:
my_string = list(my_string)
while count_upper_C:
my_string.remove("C")
count_upper_C -= 1
my_string = "".join(my_string)
return my_string
|
9520f8d870009121837bd0a2c02c2abb8a2b12cd | naturecreator/mini_projects | /Python/calendar_generation.py | 403 | 4.34375 | 4 | import calendar
year = int(input("enter the year: "))
month = 1
print("\n********Calendar*********")
print()
# An instance of TextCalendar class is created and calendar.SUNDAY means that we need to start displaying the calendar froom Sunday
cal = calendar.TextCalendar(calendar.SUNDAY)
while month<=12:
cal.prmonth(year,month) # prmonth() prints the calendar for given month and year
month+=1
|
90200c88721e64ee1b8d9088a0072076c0884cc3 | kamilsieklucki/python_examples | /dict_union.py | 2,101 | 4.65625 | 5 | # example of using dict ----------------------------------------
# Declare a dict
student = {'name': 'John', 'age': 14}
# Get a value
age = student['age']
# age is 14
# Update a value
student['age'] = 15
# student becomes {'name': 'John', 'age': 15}
# Insert a key-value pair
student['score'] = 'A'
# student becomes {'name': 'John', 'age': 15, 'score': 'A'}
# example data for union dict problem --------------------------
# two dicts to start with
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d2a = {'a': 10, 'c': 3, 'd': 4}
# target dict
d3 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Using the update() method ------------------------------------
# create a copy of d1, as update() modifies the dict in-place
d3 = d1.copy()
# d3 is {'a': 1, 'b': 2}
# update the d3 with d2
d3.update(d2)
# d3 now is {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(d3)
d3 = d1.copy()
d3.update(d2a)
# d3 now is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# This is not the way that we want
print(d3)
d3 = d2a.copy()
d3.update(d1)
# d3 now is {'a': 1, 'c': 3, 'd': 4, 'b': 2}
# This is the way that we want
print(d3)
# Unpacking dictionaries -------------------------
# unpacking
d3 = {**d1, **d2a}
# d3 is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# Not right
print(d3)
d3 = {**d2a, **d1}
# d3 is {'a': 1, 'c': 3, 'd': 4, 'b': 2}
# Good
print(d3)
# Using dict(iterable, **kwarg) ------------------
d3 = dict(d1, **d2)
# d3 is {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Good, it's what we want
print(d3)
d3 = dict(d1, **d2a)
# d3 is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# Not right, 'a' value got replaced
print(d3)
# in this method key must be a string !!!
dict({'a': 1}, **{2: 3})
dict({'a': 1}, **{'2': 3})
# Merging Dictionaries since Python 3.9.0a4 ---------------
# use the merging operator |
d3 = d1 | d2
# d3 is now {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# good
d3 = d1 | d2a
# d3 is now {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# not good
# Create a copy for d1
d3 = d1.copy()
# Use the augmented assignment of the merge operator
d3 |= d2
# d3 now is {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# good
d3 |= d2a
# d3 now is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# not good
|
febcd1aca6029792bb521a90c383063a648486e8 | jmrafferty/python-challenge | /PyBank/budget_data -- Final Submission.py | 4,548 | 3.875 | 4 | # First we'll import the os module
import os
# Module for reading CSV files
import csv
#Store csvpath as variable.
csvpath = os.path.join("Resources", "budget_data.csv")
# Read w/ CSV Module
with open (csvpath, newline="") as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=",")
#print(csvreader)
# Read the header row first (skip this step if there is now header)
csv_header = next(csvreader)
print(f"CSV Header: {csv_header}")
total_months = 0
total_pnl = 0
total_change = 0
Increase = 0
Decrease = 0
#variable for next row -- This skips line 1
#nxt_row = next(csvreader)
File = []
changes = [0]
profit = 0
loss = 0
# Read each row of data after the header
for row in csvreader:
#File.append([row[0], row[1]])
File.append(row)
#add 1 to month total for each line
total_months = total_months + 1
#Sum = sum + index 1 of row as integer
total_pnl = total_pnl + int(row[1])
#Loop through rows
#File[[row][column]]
#0..85
for row in range(len(File)):
#Set current to the value of index 1 or 'row'
current = int(File[row][1])
#initiate 'previous' as 0 -- for first line
previous = 0
#if current is > 0 add 'current' to 'profit'
if current > 0:
profit = profit + current
else:
loss = loss + current
if row != 0:
previous = int(File[row - 1][1])
changes.append(current - previous)
#Print 'File' list and test month over month changes
#print(str(row) + str(File[row]) + str(changes[row]))
print("Total Months = " + str(len(changes)))
print("Net P&L = " + str(total_pnl))
print("Total Change = " + str(sum(changes)))
print("Average Change = " + str(sum(changes)/(len(changes) - 1)))
print("Greatest Profit Increase = " + str(max(changes)))
print("Month of Greatest Increase = " + str(File[changes.index(max(changes))][0]))
print("Greatest Decrease in Profits = " + str(min(changes)))
print("Month of Greatest Decrease = " + str(File[changes.index(min(changes))][0]))
results_dict = {"Total Months": str(len(changes)),
"Net P&L" : str(total_pnl),
"Average Change" : str(sum(changes)/(len(changes) - 1)),
"Greatest Profit Increase": str(max(changes)),
"Month of Greatest Increase" : str(File[changes.index(max(changes))][0]),
"Greatest Decrease in Profits" : str(min(changes)),
"Month of Greatest Decrease" : str(File[changes.index(min(changes))][0])}
# Specify the file to write to
output_path = os.path.join("output", "pybank_results.csv")
# Open the file using "write" mode. Specify the variable to hold the contents
with open(output_path, 'w', newline='') as csvfile:
# Initialize csv.writer
csvwriter = csv.writer(csvfile, delimiter=',')
# Write the first row (header)
csvwriter.writerow(csv_header)
csvwriter.writerow(results_dict)
# Write the data lines
#csvwriter.writerow("Total Months", "str(len(changes))")
#csvwriter.writerow("Net P&L", str(total_pnl))
#csvwriter.writerow("Average Change", str(sum(changes)/(len(changes) - 1)))
#csvwriter.writerow("Greatest Profit Increase", str(max(changes)))
#csvwriter.writerow("Month of Greatest Increase", str(File[changes.index(max(changes))][0]))
#csvwriter.writerow("Greatest Profit Decrease", str(min(changes)))
#csvwriter.writerow("Month of Greatest Decrease", str(File[changes.index(min(changes))][0]))
#print(File[0][0])
# create variable to hold the value of index 1 in the next line (row +1)
#if row == len(File) - 1:
#change = 0
#else:
#new = int(File[row + 1][1])
#print(new)
#print(next(row))
#change = new - initial
#changes.append(change)
#Gives 0? --
#total_change = total_change + change
#av_change = total_change / total_months
#print("Total # of months = " + str(total_months))
#print("Total change = " + str(total_change))
#print("Average change = " + str(av_change))
#print("Total of Profits (only) = " + str(profit))
#print("Total of Losses (only) = " + str(loss))
#to test month over month change
#for change in changes:
#print(change)
|
d74c6a525216caa933f7792fd64952653f538bab | henrikmidtiby/TeacherTools | /extract photo name pairs from blackboard/parser.py | 2,724 | 3.734375 | 4 | # Script for extracting student names and associated images
# from an e-learn / blackboard page with the students.
# The data should afterwards be imported into mnemosyne, to aid me
# in learning names of all the students.
#
# Author: Henrik Skov Midtiby
# Date: 2018-10-17
# User guide
# 1. Open the relevant course on elearn / blackboard.
# 2. Find the list of participants with photos.
# 3. Select "show all".
# 4. Save the webpage with a name like "coursecode-year", avoid spaces in the filename.
# 5. Put this script in the directory containing the just saved html file ("coursecode-year.html").
# 6. Run the script and save the output to a text file (python3 parser.py coursecode-year.html > cardsformnemosyne.txt).
# 7. Copy the directory with images to the directory "/home/henrik/.local/share/mnemosyne/default.db_media/".
# 8. Remove the first three lines in cardsformnemosyne.txt
# 9. Import the generated textfile into mnemosyne (files -> import).
# Be aware of many hardcoded elements in this file.
from html.parser import HTMLParser
import argparse
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.printing_stuff = False
self.current_student_name = None
self.current_student_email = None
self.current_student_image = None
self.collecting_name = False
self.collecting_email = False
def handle_starttag(self, tag, attrs):
if tag == "tr":
self.printing_stuff = True
if tag == "img":
for attr in attrs:
if attr[0] == 'src':
self.current_student_image = attr[1]
if tag == "a":
self.collecting_email = True
if tag == "h2":
self.collecting_name = True
def handle_endtag(self, tag):
if tag == "tr":
self.printing_stuff = False
print('<img = src="%s"/>\t%s' % (self.current_student_image, self.current_student_name))
if tag == "a":
self.collecting_email = False
if tag == "h2":
self.collecting_name = False
def handle_data(self, data):
if self.collecting_name:
self.current_student_name = data
if self.collecting_email:
self.current_student_email = data
def parse_file(filename):
htmlparser = MyHTMLParser()
with open(filename) as fh:
for line in fh:
htmlparser.feed(line)
def main():
argparser = argparse.ArgumentParser(description = "Small tool to extract name / image pairs from blackboards list of participants with photos.")
argparser.add_argument("inputfilename")
args = argparser.parse_args()
parse_file(args.inputfilename)
main()
|
85942135a0f37c93db63fe063ccdb58770bc1ed1 | Prince-linux/python_for_everyone | /ch03/P3.16/lex.py | 516 | 4.0625 | 4 | #Question: P3.16: Write a program that reads in three strings and sorts them lexicographically.
#Enter a string: Charlie
#Enter a string: Able
#Enter a string: Baker
#Able
#Baker
#Charlie
#Author: Prince Oppong Boamah<regioths@gmail.com>
#Date: 28th February, 2019
string1 = input("Please enter three strings: ")
string2 = input("Please enter another string: ")
string3 = input("Please enter your last string: ")
words= [string1, string2, string3]
srted = sorted(words)
words.sort()
print(words[0])
print(words[1])
print(words[2])
|
3d8e3458a29482640ab1b022320f704a1824f60a | Zepk/DailyCodingProblems | /Problem 4/#4.py | 1,162 | 3.859375 | 4 | '''
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space.
In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.
'''
#hard4me
def solver(thislist):
thisbool = True
for number in range(len(thislist)):
while thisbool:
thislist, thisbool = swap(thislist, number)
thisbool = True
for number in range(len(thislist)):
if number+1 != thislist[number]:
return number+1
return len(thislist)
def swap(thislist, number):
if thislist[number] != number + 1 and thislist[number] <= len(thislist) and thislist[number] > 0:
primero = thislist[number]
segundo = thislist[thislist[number] - 1]
thislist[thislist[number] - 1] = primero
thislist[number] = segundo
return thislist, True
return thislist, False
print(solver([3, 4, -1, 1]))
print(solver([1,2,0]))
|
d6a168f495df8ac49e1978894d405479085e16c9 | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/bttchr004/question3.py | 505 | 3.734375 | 4 | message = input("Enter the message:\n")
y = eval(input("Enter the message repeat count:\n"))
thickness = eval(input("Enter the frame thickness:\n"))
a=len(message)+2*thickness
b=len(message)+2
gap = 0
for i in range(a,b-2,-2):
print('|'*gap,'+','-'*i,'+','|'*gap,sep="")
gap=gap+1
for h in range(y):
print('|'*thickness, message.center(a-2*thickness),'|'*thickness)
gap = thickness - 1
for l in range(b, a+1, 2):
print('|'*gap,'+','-'*l,'+','|'*gap, sep="")
gap = gap - 1 |
df3dc1420791d5283202851effc43090d365b9fc | AB-Yusuf/Blockchain_Project- | /blockChain.py | 4,288 | 3.875 | 4 | # A global blockchain variable as a list structure
genesis_block = {
'previous_hash': '',
'index': 0,
'transactions': []
}
blockChain = [genesis_block]
open_transactions = []
owner = 'Abu'
# To add a value to the block chain List
def record_transactions(recipient, sender=owner, amount=1.0):
""" It adds a new transaction to the new block,
as well as adding the previous transaction from the former block
in the blockchain.
Parameters:
:sender: The one who sends a particular amount of coins
:recipient: The one who recieves a particular amount of coins
:amount: The numeric value of coins to be used in transactions (default = 1.0)
"""
#We want to add a new transaction to our list of open transactions
new_transaction = {'sender': sender, 'recipent':recipient, 'amount':amount}
open_transactions.append(new_transaction)
def mine_new_block():
last_block = blockChain[-1]
block = {'previous_hash': 'XYZ',
'index':len(blockChain),
'transactions': open_transactions
}
blockChain.append(block)
print(blockChain)
def get_last_block_transactions():
""" It returns the last value of the current block in the blockchain."""
if len(blockChain) < 1:
return None
return blockChain[-1]
def add_new_transaction():
""" It prompts users to enter the required details for a transaction, which includes
name of sender,
name of recipent,
amount of coins to be transferred
"""
transaction_recipient = input('Enter the recipent of the transaction: ')
transaction_amount = float(input('Amount: '))
return(transaction_recipient, transaction_amount)
def get_user_choice():
user_choice = input('Your choice: ')
return user_choice
def display_each_block():
# Displaying each block in the blockchain
if blockChain:
print('Displaying each Block in the Blockchain')
for block in blockChain:
print(block)
else:
print('- '*20)
else:
print('BlockChain is empty')
def verify_chain():
# block_index = 0
is_chain_valid = True
for block_index in range(len(blockChain)):
if block_index == 0:
continue
elif blockChain[block_index][0] == blockChain[block_index - 1]:
is_chain_valid = True
else:
is_chain_valid = False
break
return is_chain_valid
# for block in blockChain:
# if block_index == 0:
# block_index += 1
# continue
# elif block[0] == blockChain[block_index-1]:
# is_chain_valid = True
# else:
# is_chain_valid = False
# break
# block_index += 1
# return is_chain_valid
waiting_for_input = True
while waiting_for_input:
print('Please choose\n')
print('1: Add a new transaction\n')
print('2: Display each block in the blockchain\n')
print('3: Manipulate the chain\n')
print('4: Quit blockchain application\n')
user_choice = get_user_choice()
if user_choice == '1':
#Get the details of a new transaction
transaction_data = add_new_transaction()
recipient, amount = transaction_data
record_transactions(recipient, amount = amount)
print(open_transactions)
mine_new_block()
elif user_choice == '2':
display_each_block()
elif user_choice == '3':
print("valid BlockChain")
print(blockChain, end='\n\n')
if len(blockChain) >= 1:
blockChain[0] = [2]
print('Blockchain first value has been changed to 2')
print(blockChain, end='\n\n')
elif user_choice == '11':
verify_chain()
elif user_choice == '4':
waiting_for_input = False
else:
print('Input was invalid, please pick a value from the list!')
# if not verify_chain():
# display_each_block()
# print('Invalid Blockchain!')
# break
# else:
# print('user left!')
print('Done!')
|
6cfaf71dc861e1de5294e07c5af3df0adbc72a51 | Sarthak2601/Python_Basics | /guessing_game.py | 296 | 3.84375 | 4 | secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
input_number = int(input("Guess?"))
guess_count +=1
if input_number == secret_number :
print("Congratulations, you won!")
break # Exits the loop
else:
print("Sorry, you failed")
|
d72bd0b14fe3cbbc2ce97720db8737ccd58996d1 | PemLer/Journey_of_Algorithm | /leetcode/801-/T845_longestMountain.py | 704 | 3.90625 | 4 | from typing import List
class Solution:
def longestMountain(self, A: List[int]) -> int:
i, n = 0, len(A)
if n < 3:
return 0
res = 0
while i < n:
end = i
if end + 1 < n and A[end] < A[end+1]:
while end + 1 < n and A[end] < A[end+1]:
end += 1
if end + 1 < n and A[end] > A[end+1]:
while end + 1 < n and A[end] > A[end+1]:
end += 1
res = max(res, end - i + 1)
i = max(end, i+1)
return res
if __name__ == '__main__':
sol = Solution()
A = [1, 2, 3, 1]
print(sol.longestMountain(A))
|
9f909f6b590f6834bb2f20de03744d6a23129e26 | wherculano/Curso-em-Video-Python | /Desafio028.py | 377 | 3.90625 | 4 | #Desafio28
import random
from time import sleep
n = random.randint(0,5)
op = int(input('\nDigite um numero entre 0 e 5: '))
print('\nLoading...')
sleep(3) #espera 3 segundos para mostrar a linha abaixo
print('\nPC = {} Você = {}'.format(n, op))
if n == op:
print('\nParabens! Você acertou o número')
else:
print('\nQue pena, você errou!')
|
4888cd2e8826537b4efca18753324f328a8a8839 | nicklogin/MasterMLCoursePracticals | /practical1.py | 7,548 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from io import StringIO
from functools import partial
# 1. Use the Tree data structure below; write code to build the tree from figure 1.2 in Daumé.
class Tree:
'''Create a binary tree; keyword-only arguments `data`, `left`, `right`.
Examples:
l1 = Tree.leaf("leaf1")
l2 = Tree.leaf("leaf2")
tree = Tree(data="root", left=l1, right=Tree(right=l2))
'''
@staticmethod
def leaf(data):
'''Create a leaf tree
'''
return Tree(data=data)
# pretty-print trees
def __repr__(self):
if self.is_leaf():
return "Leaf(%r)" % self.data
else:
return "Tree(%r) { left = %r, right = %r }" % (self.data, self.left, self.right)
# all arguments after `*` are *keyword-only*!
def __init__(self, *, data = None, left = None, right = None):
self.data = data
self.left = left
self.right = right
def is_leaf(self):
'''Check if this tree is a leaf tree
'''
return self.left == None and self.right == None
def children(self):
'''List of child subtrees
'''
return [x for x in [self.left, self.right] if x]
def depth(self):
'''Compute the depth of a tree
A leaf is depth-1, and a child is one deeper than the parent.
'''
return max([x.depth() for x in self.children()], default=0) + 1
## create leaves:
l1, l2, l3, l4, l5 = (Tree.leaf("like"), Tree.leaf("like"),
Tree.leaf('nah'), Tree.leaf("nah"), Tree.leaf("like"))
node1 = Tree(data="morning?", left=l2, right=l3)
node2 = Tree(data="likedOtherSys?", left=l4, right=l5)
node3 = Tree(data="takenOtherSys?", left=node1, right=node2)
root = Tree(data="isSystems?", left=l1, right=node3)
# 2. In your python code, load the following dataset and add a boolean "ok" column, where "True" means the rating is non-negative and "False" means the rating is negative.
csv_string = """rating,easy,ai,systems,theory,morning
2,True,True,False,True,False
2,True,True,False,True,False
2,False,True,False,False,False
2,False,False,False,True,False
2,False,True,True,False,True
1,True,True,False,False,False
1,True,True,False,True,False
1,False,True,False,True,False
0,False,False,False,False,True
0,True,False,False,True,True
0,False,True,False,True,False
0,True,True,True,True,True
-1,True,True,True,False,True
-1,False,False,True,True,False
-1,False,False,True,False,True
-1,True,False,True,False,True
-2,False,False,True,True,False
-2,False,True,True,False,True
-2,True,False,True,False,False
-2,True,False,True,False,True"""
df = pd.read_csv(StringIO(csv_string))
df["ok"] = df["rating"] >= 0
# 3. Write a function which takes a feature and computes the performance of the corresponding single-feature classifier:
def single_feature_score(data, goal, feature):
pos_class = goal[data[feature] == True].value_counts().idxmax()
neg_class = goal[data[feature] == False].value_counts().idxmax()
clf = lambda x: pos_class if x else neg_class
predicted = data[feature].apply(clf)
acc = (predicted == goal).mean()
return acc
# Use this to find the best feature:
def best_feature(data, goal, features):
# optional: avoid the lambda using `functools.partial`
return max(features, key=lambda f: single_feature_score(data, goal, f))
X = df.drop(["ok","rating"], axis=1)
y = df["ok"]
print(f"The best feature for single-feature classifier is '{best_feature(X, y, X.columns)}''")
# Which feature is best? Which feature is worst?
# We can see that the best feature is "systems". Now. let's look at other features:
def feature_scores(data, goal, features):
return sorted([(feat, single_feature_score(data, goal, feat)) for feat in features],
key=lambda x: x[1])
score_dict = feature_scores(X, y, X.columns)
print(f"Scores for the features in the decision tree: {score_dict}")
best_performance = max(score_dict, key = lambda x: x[1])[1]
# The worst feature is "easy"
# 4. Implement the DecisionTreeTrain and DecisionTreeTest algorithms from Daumé, returning Trees. (Note: our dataset and his are different; we won't get the same tree.)
#
# How does the performance compare to the single-feature classifiers?
def nanz(x):
if np.isnan(x):
return 0
return x
def decision_tree_train(X, y, features):
guess = y.value_counts().idxmax()
if len(y.unique()) == 1 or not features:
return Tree.leaf(guess)
else:
score = dict()
for feat in features:
no = X[feat] == False
yes = X[feat] == True
score[feat] = nanz(y[no].value_counts().max())+nanz(y[yes].value_counts().max())
feat = pd.Series(score).idxmax()
no = X[feat] == False
yes = X[feat] == True
X_no, y_no = X[no], y[no]
X_yes, y_yes = X[yes], y[yes]
if len(X_no) == 0 or len(X_yes) == 0:
return Tree.leaf(guess)
left = decision_tree_train(X_no, y_no, [f for f in features if f!=feat])
right = decision_tree_train(X_yes, y_yes, [f for f in features if f!=feat])
return Tree(data=feat, left=left, right=right)
t = decision_tree_train(X, y, list(X.columns))
def decision_tree_test(tree, test_point):
if tree.right is None and tree.left is None:
return tree.data
else:
if not test_point[tree.data]:
return decision_tree_test(tree.left, test_point)
else:
return decision_tree_test(tree.right, test_point)
predict = lambda x: decision_tree_test(t, x)
predicted = X.apply(predict, axis=1)
improved_performance = (predicted == y).mean()
print(f"Now the performance is {improved_performance} which is by {improved_performance-best_performance} higher than the best single-feature performance.")
# Now the score is higher by 5%
# 5. Add an optional maxdepth parameter to DecisionTreeTrain, which limits the depth of the tree produced. Plot performance against maxdepth.
def decision_tree_train(X, y, features, max_depth, depth=0):
guess = y.value_counts().idxmax()
if len(y.unique()) == 1 or not features or depth==max_depth:
return Tree.leaf(guess)
else:
score = dict()
for feat in features:
no = X[feat] == False
yes = X[feat] == True
score[feat] = nanz(y[no].value_counts().max())+nanz(y[yes].value_counts().max())
feat = pd.Series(score).idxmax()
no = X[feat] == False
yes = X[feat] == True
X_no, y_no = X[no], y[no]
X_yes, y_yes = X[yes], y[yes]
if len(X_no) == 0 or len(X_yes) == 0:
return Tree.leaf(guess)
left = decision_tree_train(X_no, y_no, [f for f in features if f!=feat], max_depth, depth+1)
right = decision_tree_train(X_yes, y_yes, [f for f in features if f!=feat], max_depth, depth+1)
return Tree(data=feat, left=left, right=right)
def predict(tree, X):
predictor = lambda x: decision_tree_test(tree, x)
return X.apply(predictor, axis=1)
def score(tree, X, y):
predicted = predict(tree, X)
return (predicted == y).mean()
features = list(X.columns)
depth = [i for i in range(len(features)+1)]
score = [score(decision_tree_train(X, y, features, i), X, y) for i in depth]
plt.plot(depth, score)
plt.xlabel("depth")
plt.ylabel("accuracy")
plt.show() |
3f49fe7f00091bdeaccc6c78e915338dbbc1806a | wangruichens/algorithms | /蓄水池采样.py | 834 | 3.5625 | 4 | # leetcode 382
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
import numpy as np
class Solution(object):
def __init__(self, head):
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
:type head: ListNode
"""
self.head = head
def getRandom(self):
"""
Returns a random node's value.
:rtype: int
"""
i = 0
selected = self.head.val
tmp = self.head.next
while tmp:
replace = np.random.randint(0, i + 2)
if replace == 0:
selected = tmp.val
tmp = tmp.next
i += 1
return selected
|
8175d375d6dca905786624bf0fb13d7f72ba1e93 | Candy0701/python | /class/20210328/for.py | 131 | 3.75 | 4 | a=int(input('輸入數字:'))
total=0
if a>1:
for i in range(1,a+1):
total+=i
print(total)
else:
print('error') |
54d794668f28e5f36f494da3f12477105a3ff2d3 | razstvien01/2D-Console-Resizable-Tictactoe-Game-in-Python | /playTictactoe.py | 12,539 | 3.6875 | 4 | import math
from random import randrange
from time import sleep
from tictactoe import Tictactoe
from tictactoe import CompAI
from record import Record
class PlayTictactoe:
def drawRoof(self, limit):
for i in range(limit):
print(end="-")
print()
def drawSpaces(self, limit):
for i in range(limit):
print(end=" ")
def centralizeWord(self, limit, word):
gSpaceSize = lambda: int((limit - len(word)) / 2) if len(word) % 2 == 0 else int(((limit - len(word)) / 2) + 1)
size = gSpaceSize()
print()
print(end="|")
self.drawSpaces(size)
print(end=word)
self.drawSpaces(size)
print("|")
def menu(self):
sizeX = 50
self.drawRoof(sizeX)
self.centralizeWord(sizeX - 2, "W E L C O M E")
self.centralizeWord(sizeX - 2, "T O T H E ")
self.centralizeWord(sizeX - 2, "T I C T A C T O E ")
self.centralizeWord(sizeX - 2, "G A M E")
self.drawRoof(sizeX)
input("Press enter to continue . . .")
def enterPos(self, name, symbol, rounds):
strError = "ERROR: Invalid position. Make sure the inputs are > -1 or <"
if rounds != 0:
while True:
try:
sPos = input(f"Enter a position of '{symbol}', {name} <eg. 0 1>: ").split(" ")
posX = int(sPos[0])
posY = int(sPos[1])
if posX < 0 or posX > self.tic.sizeX - 1:
print(end=f"{strError} {self.tic.sizeX}. ")
raise IndexError
if posY < 0 or posY > self.tic.sizeY - 1:
print(end=f"{strError} {self.tic.sizeY}. ")
raise IndexError
if self.tic.tuple[posX][posY] != "-":
raise Exception
self.tic.tuple[posX][posY] = symbol
if self.tic.checkWin(symbol):
self.tic.drawBoard()
print(f"{name} wins.")
Record(name, self.dimen)
return -1
break
except IndexError:
print("Invalid inputted index. Please try again.")
except ValueError:
print("Invalid input. Please try again.")
except:
print(f"The position has already a value. Please try again.")
self.tic.drawBoard()
return rounds - 1
self.tic.drawBoard()
return 0
def posAI(self, name, symbol, rounds):
doWin = CompAI.thinkWin(self.tic.tuple, symbol)
temp = lambda: "O" if symbol == "X" else "X"
doDefend = (False, None)
if not doWin[0]:
doDefend = CompAI.doDefend(self.tic.tuple, temp())
if rounds != 0 and doWin[0]:
posX, posY = doWin[1]
self.tic.tuple[posX][posY] = symbol
print(f"{name} is thinking . . . ")
sleep(randrange(2, 5))
self.tic.drawBoard()
print(f"{name} inputted x: {posX} and y: {posY}\n")
print(f"{name} wins.")
Record(name, self.dimen)
return 0
elif rounds != 0 and doDefend[0]:
posX, posY = doDefend[1]
self.tic.tuple[posX][posY] = symbol
print(f"{name} is thinking . . . ")
sleep(randrange(2, 5))
self.tic.drawBoard()
print(f"{name} inputted x: {posX} and y: {posY}\n")
return rounds - 1
elif rounds != 0:
while True:
posX = abs(randrange(0, self.tic.sizeX + 1))
posY = abs(randrange(0, self.tic.sizeY + 1))
if posX < 0 or posX > self.tic.sizeX - 1:
continue
if posY < 0 or posY > self.tic.sizeY - 1:
continue
if self.tic.tuple[posX][posY] != "-":
continue
self.tic.tuple[posX][posY] = symbol
print(f"{name} is thinking . . .")
sleep(randrange(2, 5))
self.tic.drawBoard()
print(f"{name} inputted x: {posX} and y: {posY}\n")
if not self.tic.checkWin(symbol):
break
self.tic.drawBoard()
print(f"{name} wins.")
Record(name, self.dimen)
return -1
return rounds - 1
return 0
def doPvAI(self, brLoop):
x = self.tic.symbolList[0]
o = self.tic.symbolList[1]
turns = self.tic.noOfTurns
if self.sym1 == 0:
turns = self.enterPos(self.name, x, turns)
if brLoop(turns):
return False
turns = self.posAI("Computer AI", o, turns)
if brLoop(turns):
return False
else:
turns = self.posAI("Computer AI", x, turns)
if brLoop(turns):
return False
turns = self.enterPos(self.name, o, turns)
if brLoop(turns):
return False
self.tic.noOfTurns = turns
return not False
def doPvP(self, brLoop):
x = self.tic.symbolList[0]
o = self.tic.symbolList[1]
turns = self.tic.noOfTurns
if self.sym1 == 0:
turns = self.enterPos(self.p1name, x, turns)
if brLoop(turns):
return False
turns = self.enterPos(self.p2name, x, turns)
if brLoop(turns):
return False
else:
turns = self.enterPos(self.p2name, x, turns)
if brLoop(turns):
return False
turns = self.enterPos(self.p1name, o, turns)
if brLoop(turns):
return False
self.tic.noOfTurns = turns
return not False
def doAiVsAi(self, brLoop):
x = self.tic.symbolList[0]
o = self.tic.symbolList[1]
turns = self.tic.noOfTurns
if self.sym1 == 0:
turns = self.posAI(self.nameAI1, x, turns)
if brLoop(turns):
return False
turns = self.posAI(self.nameAI2, o, turns)
if brLoop(turns):
return False
else:
turns = self.posAI(self.nameAI2, x, turns)
if brLoop(turns):
return False
turns = self.posAI(self.nameAI1, o, turns)
if brLoop(turns):
return False
self.tic.noOfTurns = turns
return not False
def playGame(self):
loop = True
i = self.tic.noOfTurns
totTurns = lambda: int(i / 2) if i % 2 == 0 else int((i / 2) + 1)
brLoop = lambda i: True if i == -1 or i == 0 else False
rounds = totTurns()
while loop:
print(f"No of rounds left: {rounds}\n")
if self.ai:
loop = self.doAiVsAi(brLoop)
elif self.pvp:
loop = self.doPvP(brLoop)
else:
loop = self.doPvAI(brLoop)
if brLoop(self.tic.noOfTurns):
loop = False
rounds -= 1
if rounds == 0:
print("Both competetors tied.")
print("Game Over")
def dimensions(self):
while True:
try:
self.dimen = input("\nEnter the tictactoe's dimensions <eg. 3x3>: ")
val = self.dimen.lower().split("x")
row = int(val[0])
col = int(val[1])
if row < 3 or col < 3 or row > 15 or col > 15:
raise ValueError
return row, col
except ValueError:
print("The value must be an integer or not lesser than three or greater than 15.")
except IndexError:
print("Invalid inputted index.")
def gameMode(self):
print("Please choose:\n")
print("\t1. Player vs AI")
print("\t2. Player vs Player")
print("\t3. AI vs AI")
while True:
try:
choice = int(input("\nChoose <1, 2 & 3 only>: "))
if choice > 0 and choice < 4:
return choice
raise ValueError
except ValueError:
print("ERROR: Invalid input. Make sure you entered 1, 2 and 3 only.")
def inputP1S(self):
mode = self.gameMode()
if mode == 1:
self.nameAI = "Computer"
self.name = input("\nEnter your name: ")
while True:
try:
symbol = input("Choose between 'X' and 'O': ").capitalize()
if symbol == 'X' or symbol == 'O':
return symbol
raise ValueError
except ValueError:
print("ERROR: Invalid input. Choose only between 'X' and 'O'.")
elif mode == 2:
self.p1name = input("\nEnter your name player 1: ")
self.pvp = True
while True:
try:
symbol = input("Choose between 'X 'and 'O': ").capitalize()
if symbol == 'X' or symbol == 'O':
break
raise ValueError
except ValueError:
print("ERROR: Invalid input. Choose only between 'X' and 'O'.")
except:
print("ERRoR: Invalid input. Choose only between 'X' and 'O'.")
self.p2name = input("Enter your name player 2: ")
return symbol
self.nameAI1 = input("\nEnter the name of AI 1: ")
self.nameAI1 = self.nameAI1 + " AI"
self.ai = True
while True:
try:
symbol = input("Choose between 'X 'and 'O': ").capitalize()
if symbol == 'X' or symbol == 'O':
break
raise ValueError
except ValueError:
print("ERROR: Invalid input. Choose only between 'X' and 'O'.")
except:
print("ERRoR: Invalid input. Choose only between 'X' and 'O'.")
self.nameAI2 = input("Enter the name of AI 2: ")
self.nameAI2 = self.nameAI2 + " AI"
return symbol
def __init__(self):
self.tic = None
self.pvp = False
self.ai = False
self.dimen = "3x3"
self.menu()
temp = lambda: 0 if self.inputP1S() == "X" else 1
self.sym1 = temp()
row, col = self.dimensions()
self.tic = Tictactoe(row, col)
self.tic.drawBoard()
self.playGame()
PlayTictactoe() |
a264e42d0757d08a445544038d79e8d28fe1f0bb | QMJT/myedu | /dy03/while_demo.py | 186 | 3.734375 | 4 | def while_qq():
a=0
while a<5:
print(a)
a+=1
def while_tt():
a=0
while a<8:
print(a)
a+=1
if __name__ == '__main__':
while_tt() |
66f1ad47c9fb7a6619a30bbd9615a3aa21b15ff2 | mchoimis/Python-Practice | /20130813_0051_wrting-reading-files.py | 360 | 3.8125 | 4 | # Writing
outfile = open('tmp.txt', 'w')
outfile.write('This is line #1\n')
outfile.write('This is line #2\n')
outfile.close()
# Reading an entire file
infile = file('tmp.txt', 'r')
content = infile.read()
print content
infile.close()
# Reading a file one line at a time
infile = file('tmp.txt', 'r')
for line in infile:
print '$', line
infile.close()
|
cf72f43dae71db477ebe44ee1bfb9f2be8cfb0d8 | Sofista23/Aula1_Python | /Aulas/Aulas-Mundo3/Aula021/Aula021c.py | 195 | 3.875 | 4 | def par(num):
if num%2==0:
return True
else:
return False
n=int(input("Digite um número:"))
if par(n)==True:
print(f"{n} é Par!")
else:
print(f"{n} é Ímpar!") |
e7a5be11574def59dfb49210f433ea65102cfa90 | Tiltedprogrammer/HwProj1 | /3.py | 71 | 3.609375 | 4 | a = int(input())
b = int(input())
a += b
b = a -b
a = a - b
print(a,b)
|
ad4543e56fb7419afb6bc8ba500610e109fdfeae | maximvegorov/hackerrank-python | /src/02-basic-data-types/nested-list.py | 318 | 3.546875 | 4 | if __name__ == '__main__':
n = int(input())
l = list()
for i in range(n):
name = input()
score = float(input())
l.append([name, score])
second_lower = sorted({p[1] for p in l}, reverse=True)[-2]
print(*sorted((p[0] for p in l if abs(p[1] - second_lower) < 1e-6)), sep='\n')
|
ce391661556760c189e74ebd4e64d751ee44dd0d | Samanvay96/python-ds | /data_structures/array/duplicate.py | 485 | 3.75 | 4 | # Find duplicate in an array of integers given that the integers are in random order and
# not necessarily each integer i is 0 <= i <= N where N = length of array
def duplicate(arr):
tortoise = arr[0]
hare = arr[0]
while True:
tortoise = arr[tortoise]
hare = arr[arr[hare]]
if tortoise == hare:
break
ptr1 = nums[0]
ptr2 = tortoise
while ptr1 != ptr2:
ptr1 = nums[ptr1]
ptr2 = nums[ptr2]
return ptr1
|
e0dbe0b887b2406645c25eedaa2449cbf8f44c4f | DinakarBijili/Python-Preparation | /Problem Solving/Loops/sum_os_squares.py | 166 | 4.09375 | 4 |
"""Sum of Squares"""
def sum_of_squares(n):
sum = n*(n+1)*(2*n+1)
return sum
num = int(input("Enter a number : "))
result = sum_of_squares(num)
print(result) |
e5ef579e45c79fa861798813b133acd670cb0a0d | MarciaCarolinaCarastel/Python | /ex039.py | 594 | 3.859375 | 4 | from datetime import date
print('\033[35mDescubra quanto tempo falta para se alistar no exército.')
nome = str(input('Me informe o sue nome:')).strip() .split()
ano = int(input('Qual o seu ano de nascimento?'))
c = date.today().year - ano
if c < 18:
print('\033[33m',nome[0], ', você vai se alistar ao serviço militar em {} anos.'.format(18 - c))
elif c == 18:
print('\033[32m', nome[0],', você precisa se alistar ao serviço militar este ano. Boa sorte.')
else:
print('\033[31m',nome[0],', infelizmente já passou o seu período de alistamento há {} anos.'.format(c - 18))
|
90f9af0e73db5712e947e1bcd43be8bd0e773ee6 | Jordy281/Tic_Tac_Toe_SuperComputer | /gym.py | 11,706 | 3.59375 | 4 | """
Here we will train the Rewards function
"""
import numpy as np
import copy
from random import randrange
import game.py
def trainingAgainstRand1(states, t):
nStates = np.shape(t)[0]
nActions = np.shape(t)[1]
Q = np.zeros((nStates,nActions))
numberOfTimesStateVisted = np.zeros((nStates))
setQNoBacktrack(Q,t)
mu = 0.7
gamma = 0.25
epsilon = .15
epsilon2 = 1
nits = 0
TDWinns=0
TDDraww=0
TDLosss=0
while nits < 1000000:
# Pick initial state
s = 0
# Stop when the accepting state is reached
turn=0
while game.threecheck(states[s]) is False and turn<8:
# epsilon-greedy
if (np.random.rand()<epsilon):
indices=[]
for i in range(0,9):
if t[s][i]>-1:
indices.append(i)
pick = randrange(len(indices))
a = indices[pick]
else:
a = np.argmax(Q[s,:])
sprime = t[s][a]
numberOfTimesStateVisted[sprime]+=1
turn+=1
#If this move wins us the game
if game.threecheck(states[sprime]) is True:
Q[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (100 + gamma*np.max(Q[sprime,:]) - Q[s,a])
TDWinns= TDWinns+1
s=sprime
elif turn==8:
TDDraww+=1
#If not, let the computer pick
else:
Q[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (gamma*np.max(Q[sprime,:]) - Q[s,a])
# Have the computer chooses a random action -> epsilon2 = 1
if (np.random.rand()<epsilon2):
#we need to chose a random action
indices=[]
for i in range(0,9):
if t[sprime][i]>-1:
indices.append(i)
pick = randrange(len(indices))
a2 = indices[pick]
#a is the index of the next state to move to
else:
a2 = np.argmax(Q[sprime,:])
"""
if threecheck(board) is True:
Q[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (r + gamma*np.min(Q[sprime,np.where(t[s,:]>-1)]) - Q[s,a])
"""
sDoublePrime = t[sprime][a2]
if game.threecheck(states[sDoublePrime]):
r=-100.
else:
r=0
Q[sprime,a2] += mu/(numberOfTimesStateVisted[sDoublePrime]+1) * (r + gamma*np.max(Q[sDoublePrime,:]) - Q[sprime,a2])
numberOfTimesStateVisted[sDoublePrime]+=1
s = sDoublePrime
turn+=1
if game.threecheck(states[s])is True:
TDLosss+=1
elif turn ==8:
TDDraww+=1
nits = nits+1
if nits%100==0:
TDWinPercentageTrainingFirst.append(TDWinns/float(nits))
TDDrawPercentageTrainingFirst.append(TDDraww/float(nits))
TDLossPercentageTrainingFirst.append(TDLosss/float(nits))
return Q
#print Q[0]
def trainingAgainstRand2(states, t):
nStates = np.shape(t)[0]
nActions = np.shape(t)[1]
Q = np.zeros((nStates,nActions))
numberOfTimesStateVisted = np.zeros((nStates))
setQNoBacktrack(Q,t)
mu = 0.7
gamma = 0.25
epsilon = 1
epsilon2 = .15
nits = 0
TDWins=0
TDDraw=0
TDLoss=0
while nits < 1000000:
# Pick initial state
s = 0
# Stop when the accepting state is reached
turn=0
while game.threecheck(states[s]) is False and turn<8:
# epsilon-greedy
if (np.random.rand()<epsilon):
"""
we need to chose a random action
"""
indices=[]
for i in range(0,9):
if t[s][i]>-1:
indices.append(i)
pick = randrange(len(indices))
a = indices[pick]
"""
a is the index of the next state to move to
"""
#print s,a
else:
a = np.argmax(Q[s,:])
# For this example, new state is the chosen action
sprime = t[s][a]
numberOfTimesStateVisted[sprime]+=1
turn+=1
#If this move wins us the game
if game.threecheck(states[sprime]) is True:
Q[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (-100 + gamma*np.max(Q[sprime,:]) - Q[s,a])
TDLoss+=1
s=sprime
elif turn==8:
Q[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (20 + gamma*np.max(Q[sprime,:]) - Q[s,a])
TDDraw+=1
#If not, let the computer pick
else:
Q[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (gamma*np.max(Q[sprime,:]) - Q[s,a])
# Have the computer chooses a random action -> epsilon2 = 1
if (np.random.rand()<epsilon2):
#we need to chose a random action
indices=[]
for i in range(0,9):
if t[sprime][i]>-1:
indices.append(i)
pick = randrange(len(indices))
a2 = indices[pick]
#a is the index of the next state to move to
else:
a2 = np.argmax(Q[sprime,:])
"""
if game.threecheck(board) is True:
Q[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (r + gamma*np.min(Q[sprime,np.where(t[s,:]>-1)]) - Q[s,a])
"""
sDoublePrime = t[sprime][a2]
if game.threecheck(states[sDoublePrime]):
r=80
elif turn ==7:
r=20
TDDraw+=1
else:
r=0
#print "here"
Q[sprime,a2] += mu/(numberOfTimesStateVisted[sDoublePrime]+1) * (r + gamma*np.max(Q[sDoublePrime,:]) - Q[sprime,a2])
numberOfTimesStateVisted[sDoublePrime]+=1
s = sDoublePrime
turn+=1
if game.threecheck(states[s])is True:
TDWins+=1
nits = nits+1
if nits%100==0:
TDWinPercentageTrainingSec.append(TDWins/float(nits))
TDDrawPercentageTrainingSec.append(TDDraw/float(nits))
TDLossPercentageTrainingSec.append(TDLoss/float(nits))
return Q
#print Q[0]
def trainingAgainstLearner(states, t):
nStates = np.shape(t)[0]
nActions = np.shape(t)[1]
Qplayer1 = np.zeros((nStates,nActions))
Qplayer2 = np.zeros((nStates,nActions))
numberOfTimesStateVisted = np.zeros((nStates))
setQNoBacktrack(Qplayer1,t)
setQNoBacktrack(Qplayer2,t)
mu = 0.7
gamma = 0.25
epsilon = .1
epsilon2 = .15
nits = 0
Player1Win=0
Draw=0
Player2Win=0
while nits < 1000000:
# Pick initial state
s = 0
# Stop when the accepting state is reached
turn=0
while game.threecheck(states[s]) is False and turn<8:
# epsilon-greedy
if (np.random.rand()<epsilon):
"""
we need to chose a random action
"""
indices=[]
for i in range(0,9):
if t[s][i]>-1:
indices.append(i)
pick = randrange(len(indices))
a = indices[pick]
"""
a is the index of the next state to move to
"""
#print s,a
else:
a = np.argmax(Qplayer1[s,:])
# For this example, new state is the chosen action
sprime = t[s][a]
turn+=1
numberOfTimesStateVisted[sprime]+=1
#If this move wins us the game
if game.threecheck(states[sprime]) is True:
Qplayer2[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (-100 + gamma*np.max(Qplayer2[sprime,:]) - Qplayer2[s,a])
Qplayer1[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (100 + gamma*np.max(Qplayer1[sprime,:]) - Qplayer1[s,a])
Player1Win+=1
s=sprime
elif turn==8:
Qplayer2[s,a]+= mu/(numberOfTimesStateVisted[sprime]+1) * (20 + gamma*np.max(Qplayer2[sprime,:]) - Qplayer2[s,a])
Qplayer1[s,a]+= mu/(numberOfTimesStateVisted[sprime]+1) * (gamma*np.max(Qplayer1[sprime,:]) - Qplayer1[s,a])
#If not, let the computer pick
Draw+=1
else:
Qplayer1[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (gamma*np.max(Qplayer1[sprime,:]) - Qplayer1[s,a])
Qplayer2[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (gamma*np.max(Qplayer2[sprime,:]) - Qplayer2[s,a])
# Have the computer chooses a random action -> epsilon2 = 1
if (np.random.rand()<epsilon2):
#we need to chose a random action
indices=[]
for i in range(0,9):
if t[sprime][i]>-1:
indices.append(i)
pick = randrange(len(indices))
a2 = indices[pick]
#a is the index of the next state to move to
else:
a2 = np.argmax(Qplayer2[sprime,:])
"""
if game.threecheck(board) is True:
Q[s,a] += mu/(numberOfTimesStateVisted[sprime]+1) * (r + gamma*np.min(Q[sprime,np.where(t[s,:]>-1)]) - Q[s,a])
"""
sDoublePrime = t[sprime][a2]
if game.threecheck(states[sDoublePrime]):
r1=-100
r2=80
elif turn==7:
r1=0
r2=20
Draw+=1
else:
r1=0
r2=0
#print "here"
Qplayer2[sprime,a2] += mu/(numberOfTimesStateVisted[sDoublePrime]+1) * (r2 + gamma*np.max(Qplayer2[sDoublePrime,:]) - Qplayer2[sprime,a2])
Qplayer1[sprime,a2] += mu/(numberOfTimesStateVisted[sDoublePrime]+1) * (r1 + gamma*np.max(Qplayer1[sDoublePrime,:]) - Qplayer1[sprime,a2])
numberOfTimesStateVisted[sDoublePrime]+=1
s = sDoublePrime
turn+=1
if game.threecheck(states[s])is True:
Player2Win+=1
nits = nits+1
if nits%100==0:
Player1PercentageTraining.append(Player1Win/float(nits))
DrawPercentageTraining.append(Draw/float(nits))
Player2PercentageTraining.append(Player2Win/float(nits))
#print Q[0]
return [Qplayer1, Qplayer2]
|
544521eae045094f50a98d82ae7078988bc13b3f | sendurr/spring-grading | /submission - lab6/set2/JEFFERSON LEWIS LANGSTON_9455_assignsubmission_file_Lab 6 JL/Lab 6/f2c_qa2.py | 126 | 3.546875 | 4 | import sys
Farhenheit = float(sys.argy[1])
Celcius = ((F-32)*(5.0/9))
print 'The temperature in Celcius is:'
print Celcius
|
e80097b9a98cbfe4f9cebb1d791be1d35857ebe2 | bengeos/HomeIOT_Rasp | /Threading/TestThread.py | 543 | 3.65625 | 4 | import threading
import time
class MyThread(threading.Thread):
def __init__(self,sleep,name):
threading.Thread.__init__(self)
self.Sleep = sleep
self.Name = name
self.Count = 0
def run(self):
while(True):
print self.Name+">> Time is: "+str(time.time())
time.sleep(self.Sleep)
self.Count += 1
th1 = MyThread(1,"One")
th2 = MyThread(2.3,"Two")
th1.start()
th2.start()
time.sleep(5)
th1.join()
print "One--> "+str(th1.Count)
print "Two--> "+str(th2.Count)
|
19be3f4b680315d4823b027b8b0c88d41c1585c2 | root676/G08_python_for_geosciences | /homework1/player.py | 5,056 | 4.125 | 4 | #-------------------------------------------------------------------------------
# Name: Player
# Purpose: saves the data like money, name of the player an his bets for
# playing Roulette
#
# Author: Stefan Fnord, Clemens Raffler, Daniel Zamojski
#
# Created: 25.03.2015
# Copyright: (c) Stefan Fnord, Clemens Raffler, Daniel Zamojski 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
# purpose of player.py
# player.py contains code for the construction of a player-class
# a player can play on the roulette table and win or lose money
class Player:
# definition of player properties (name, money he brings, bets he sets on the table)
def __init__(self,playername,money_set):
"""
constructor-function of the player-object
stores username, money brought to table and betted options to player-object
Paramters
---------
playername: string
input username
money_set: int
input amount of money
Returns
-------
Player: object
player-object which stores username,
money brought to table and betted options
"""
self.name=playername
self.money=money_set
self.bet={}
# save the bets for the specific user
def bets(self,mainoption,option,money):
"""
method for storing information about bets, made at
the RouletteTable-object to the bet-attribute of the player-object
Paramters
---------
mainoption: int
primary bet specification
option: int
secondary bet specification
money: float
money betted on specified options
returns
-------
self.bet: dict
nested dict containing all specified bet-options
and betted amount of money following this
dict-pattern {mainoption:{option:money}}
"""
bet_mainoptions = self.bet.get(mainoption)
# if main-option does not exists, create it otherwise...
if bet_mainoptions == None:
self.bet[mainoption] = {option:money}
else:
# check if options (for specific main options) exists - if yes update otherwise create
currentmoney = bet_mainoptions.get(option)
if currentmoney == None:
bet_mainoptions[option] = money
self.bet[mainoption] = bet_mainoptions
else:
self.bet[mainoption] = {option:currentmoney+money}
# give back all main bet options which are set
def getbetoptions(self):
"""
method that lists the dicts with infomration about
made bets, stored in the player-object
returns
-------
list
list containing the betted options
"""
return self.bet.keys()
def getbettedmoney(self,mainoption,option):
"""
method that returns the amount of money, bettet on a specific option.
Parameters
----------
mainoption: int
primary bet specification
option: int
secondary bet specification
returns
-------
float
money betted by the on options
"""
return self.bet[mainoption].get(option)
def wins(self,money):
"""
adds the money that was won through bets from the players budget
Parameters
----------
money: float
won money paid out by the RouletteTable
returns
-------
money: float
return total amount of money owned by player
"""
#print('You have won {} Euro'.format(money))
self.money += money
return money
# take money from players money
def loses(self,money):
"""
subtracts the money that was lost through bets from the players budget
Parameters
----------
money: float
money lost through bets on the RouletteTable
returns
-------
False if money lost through bet is greater than the players
budget, else returns True
money: float
returns the total amount of money owned by player
"""
if money > self.money:
return False
self.money -= money
return True
# give back the money status
def getmoneystatus(self):
"""
returns the current budget of the player
returns:
--------
money: float
current budget of the player-object
"""
return self.money
# erase all bets for a new game
def cleanupbets(self):
"""
erases all information about bets stored in the bet dict
"""
self.bet = {}
|
98d057d7fd021546d33dfeb6352865f14bb2f57e | janarqb/Notes_Week2 | /List_day3.py | 1,526 | 3.515625 | 4 | nums = 1, 2, 3
# print(type(words))
# print(words[:2])
# one, two, three = num(s
# print(two)
# a = ()
# b = ()
# print(a is b)
# print(id(a))
# print(id(b))
# a = (1, 2, 3)
# print(id(a))
# del a
# b = (1, 2, 3)
# print(id(b))
countries = (
('Germany', 80.2, (('Berlin', 3.326), ('Huburg', 1.718))),
('France', 66, (('Paris', 2.2, ('Marsel', 1.6))))
)
for country in countries:
country_name, country_population, cities = country
print('\nCountry: {} population: {}'.format(country_name, country_population))
for city in cities:
city_name, city_population = city
print('City: {} population: {}'.format(city_name, city_population))
print(country)
print(country_name)
print(country_population)
print(cities)
print('===============')
# nested = (1, [1, 2, 4], 'do', ('param', 10, 20))
# nested[3].append('new')
# print(nested)
users = {1: 'Tom', 2: 'Bob', 3: 'Bill'}
objects = {}
elements = {'Au': 'Gold', 'Fe': 'Железо', 'H':'Водород', 'O': 'Oxygen'}
new = ((1, True), (2, False), (3, 'Echo'))
# new_ = dict(new)
# print(type(new_dict))
# print(type(users))
# print(type(objects))
# new = dict(a=1, b=2, c=3)
# print(new)
# # elements['Au'] = 'Золото'
# # print(elements)
# users[4] = 'Aybek'
# print(users)
# print(users.get(10))
# del users [2]
# print(users.fromkeys(range(1,9), ['one', 'two']))
# print(users.items())
# print(users.pop(3))
# print(users.popitem())
# for id_, user in users.items():
# print(id_, "*****", user) |
dd0d90aa01ced332c66ac1891e1b16c88b4c1ed0 | Platform53/Yes | /yes.py | 14,532 | 3.53125 | 4 | import hashlib
from pathlib import Path
import time
import sys
firsttimecheck = ()
#first time setup
try:
#If it does it prints it in text
d = open('firsttimecheck','r').read()
firsttimecheck = ('')
except IOError:
#if there was not a file it says so
firsttimecheck = ('1')
if firsttimecheck == ('1'):
print ('I see this is your first time using this program')
print ('')
firsttimeusername = input("Admin Username: ")
firsttimepassword = input('Admin Password: ')
firsttimecode = input('Admin Code: ')
hashedpassword =hashlib.sha256(str.encode(firsttimepassword)).hexdigest()
hashedusername =hashlib.sha256(str.encode(firsttimeusername)).hexdigest()
hashedadmincode =hashlib.sha256(str.encode(firsttimecode)).hexdigest()
open('adminusername','w+').write(hashedusername)
open('adminpassword','w+').write(hashedpassword)
open('admincode','w+').write(hashedadmincode)
open('firsttimecheck','w').write('2')
open('loginattempts','w').write('')
#login system
usernameloop = True
passwordloop = True
adminloginuser = False
while usernameloop == True:
userexist = (True)
while userexist == (True):
inputusername = input ("Input Username ")
adminusername = open('adminusername','r').read()
inputusername = hashlib.sha256(str.encode(inputusername)).hexdigest()
if inputusername == (adminusername):
username = ('')
print ('admin user')
adminloginuser = True
userexist = False
else:
adminloginuser = False
try:
username = open(inputusername,'r').read()
userexist = False
except IOError:
print ('User does not exist')
if (inputusername) == (username) or adminloginuser == True:
print ("correct")
usernameloop = False
else:
print ("incorrect")
usernameloop = True
while passwordloop == True:
failedcheck = open('loginattempts','r').read()
if failedcheck == ('5'):
print ('you have failed to many times wait 1 minute')
only = (0)
taken = ('')
while taken == (''):
time.sleep(1)
only = only + 1
print (only)
if only == (60):
taken = ('i')
taken = ('')
print ('time is up have another go')
open('loginattempts','w').write('')
passwordexists = True
Password = ('')
inputpassword = ('')
adminlogin = False
inputpassword = input("Input Password ")
inputpassword = hashlib.sha256(str.encode(inputpassword)).hexdigest()
AdminPassword = open('adminpassword','r').read()
if inputpassword == AdminPassword and adminloginuser == True:
print ('adminlogin')
passwordexists = False
passwordloop = False
adminlogin = True
else:
try:
(Password) = open(inputpassword,'r').read()
except IOError:
print ('You were Incorrect')
passwordexists = True
if (Password) == (inputpassword) or adminlogin == True:
print ('correct')
print (adminlogin)
passwordexists = False
passwordloop = False
else:
loginattempts = open('loginattempts','r').read()
if loginattempts == ('1'):
open('loginattempts','w+').write('2')
elif loginattempts == ('2'):
open('loginattempts','w+').write('3')
elif loginattempts == ('3'):
open('loginattempts','w+').write('4')
elif loginattempts == ('4'):
open('loginattempts','w+').write('5')
else:
open('loginattempts','w+').write('1')
print ("incorrect")
#Menu from here you can go to view edit or create scores
menuactive = (True)
scorechecker = ()
while menuactive == True:
print ("")
print ("")
print ("main menu")
print ("")
print ("press 1 to view scores")
print ("press 2 to add new scores")
if adminlogin == True:
print ("press 3 to add a new teacher")
print ('press enter to exit the program')
chosen = input('')
if chosen == ('1'):
yearchosen = ('')
classchosen = ('')
subjectchosen = ('')
testname = ('')
name = ('')
txt = ('')
#View scores
viewer = ('')
#checks the class
classchosen = input('Class Name: ')
viewer = viewer + classchosen
addsubjectcheck = True
while addsubjectcheck == True:
addaccesscode = input('Access Code: ')
addaccesscode = hashlib.sha256(str.encode(addaccesscode)).hexdigest()
admincode = open('admincode','r').read()
if addaccesscode == admincode:
admincode1 = True
print ('Admin Access')
addsubjectcheck = False
codesubjects = ()
else:
try:
codesubjects = open(addaccesscode,'r').read()
addsubjectcheck = False
except IOError:
print ('make sure you put in the code correctly')
addsubjectcheck = True
subject = True
accessgranted = False
while subject == True:
print ('type in the subject that you wish to view')
print ('or enter 1 to go to menu')
subjectchosen = input('')
if (subjectchosen) in (codesubjects) or admincode1 == True:
subject = False
accessgranted = True
elif subjectchosen == ('1'):
subject = False
accessgranted = False
else:
print ('make sure you put in the subject right')
if accessgranted == True:
viewer = viewer + subjectchosen
#choose your test that you want to view
print ('1 for autumn assesment')
print ('2 for december assesment')
print ('3 for january assesment')
print ('4 for spring assesments')
print ('5 for end of year assesments')
print ('either use the following as a guideline for some of the assesments you have done or type in the neame you gave when scoring')
testname = input ('')
viewer = viewer + testname
#Now the pupils name
viewperson = True
while viewperson == True:
print ('')
print('now the pupil in the format')
print ('firstname.lastname')
print ('or type average for a class average')
name = input('')
viewernamed = viewer + name
#checks whether the file exists
try:
z = open(viewernamed,'r').read()
fileexists2 = ('')
except IOError:
#if there was not a file it says so
fileexists2 = ('1')
if fileexists2 == ('1'):
print('File does not exist, make sure you put in the information correctly or that the test has already been scored')
print ('')
print ('')
viewperson = False
elif fileexists2 == (''):
tempaccess = open(viewernamed,'r').read()
print (tempaccess,'%')
print ('press enter to view another student ')
print ('type 1 to go to menu')
homeornot = input('')
if homeornot == ('1'):
viewperson = False
elif chosen == ('2'):
viewer = ('')
classchosen = input('Class Name: )')
viewer = viewer + classchosen
addsubjectcheck = True
while addsubjectcheck == True:
addaccesscode = input('Access Code: ')
addaccesscode = hashlib.sha256(str.encode(addaccesscode)).hexdigest()
admincode = open('admincode','r').read()
accessgranted = False
if addaccesscode == admincode:
addsubjectcheck = False
codesubjects = ()
admincode1 = True
else:
try:
codesubjects = open(addaccesscode,'r').read()
addsubjectcheck = False
except IOError:
print ('make sure you put in the code correctly')
addsubjectcheck = True
subject = True
while subject == True:
print ('type in the subject that you wish to view')
print ('or enter 1 to go to menu')
subjectchosen = input('')
if (subjectchosen) in (codesubjects) or admincode1 == True:
print ('go ahead')
subject = False
accessgranted = True
elif subjectchosen == ('1'):
subject = False
accessgranted = False
else:
print ('make sure you put in the subject right')
if accessgranted == True:
viewer = viewer + subjectchosen
print ('1 for autumn assesment')
print ('2 for december assesment')
print ('3 for january assesment')
print ('4 for spring assesments')
print ('5 for end of year assesments')
print ('either use the following as a guideline for some of the assesments you have done or type in the neame you gave when scoring')
testname = input ('')
viewer = viewer + testname
testagain = True
average = (0)
averagenumber = (0)
while testagain == True:
print ('')
print('now the pupil in the format')
print ('firstname.lastname')
name = input('')
viewernamed = viewer + name
percentagecheck = True
while percentagecheck == True:
averagenumber = averagenumber + 1
print ('what percentage did they get')
try:
tempscore = input ()
average = average + int(tempscore)
percentagechecker = True
except ValueError:
print ('There was an error')
percentagechecker = False
if percentagechecker == True:
percentagecheck = False
open(viewernamed,'w+').write(tempscore)
print ('1 to go to menu')
print ('or press enter to score again')
scoreagain = input('')
if scoreagain == ('1'):
chosen = ('')
vieweraverage = viewer + ('average')
testagain = False
averagesaved = average/averagenumber
open(vieweraverage,'w+').write(str(averagesaved))
exit
else:
viewernamed = viewer
exit
elif chosen == (''):
sys.exit()
elif chosen == ('3') and adminlogin == True:
print ('here you add new Accounts')
newusername = input('Username? ')
newpassword = input ('Password? ')
subjectcode = input ('This code gives them access to only the subjects they should have access to ')
hashedusername = hashlib.sha256(str.encode(newusername)).hexdigest()
hashedpassword = hashlib.sha256(str.encode(newpassword)).hexdigest()
hashedcode = hashlib.sha256(str.encode(subjectcode)).hexdigest()
print ('which of the following subjects do you want this teacher to have')
print ('geography')
print ('maths')
print ('english')
print ('it')
print ('art')
print ('awe')
print ('citizenship')
print ('business studies')
print ('drama')
print ('dt')
print ('foodtech')
print ('geography')
print ('history')
print ('spanish')
print ('german')
print ('french')
print ('music')
print ('pe')
print ('rs')
print ('science')
print ('physics')
print ('chemistry')
print ('bilogy')
print ('')
SubjectAgain = True
Subjects10 = ('')
SubjectAgain100 = ('')
while SubjectAgain == True:
print ('enter to add subject')
print ('1 to finalise account creation')
SubjectAgain1 = input('')
if SubjectAgain1 == (''):
SubjectAgain = True
print ('')
SubjectAgain100 = input('Subject? ')
Subjects10 = Subjects10 + ('') + (SubjectAgain100)
elif SubjectAgain1 == ('1'):
open(hashedcode,'w+').write(Subjects10)
open(hashedusername,'w+').write(hashedusername)
open(hashedpassword,'w+').write(hashedpassword)
SubjectAgain = False
exit
|
24858d172d0415abe33840073e0d8ac5fc200a55 | byterotate/lintcode-answer | /binary-tree/109-triangle.conquer-memorize.py | 780 | 3.53125 | 4 | class Solution:
"""
@param triangle: a list of lists of integers
@return: An integer, minimum path sum
"""
def minimumTotal(self, triangle):
self.cache = [[None for y in range(len(triangle[-1]))] for x in range(len(triangle))]
return self._minimumTotal(triangle, 0, 0)
def _minimumTotal(self, triangle, Y, X):
if Y == len(triangle) - 1:
return triangle[Y][X]
if self.cache[Y+1][X]:
below = self.cache[Y+1][X]
else:
below = self.cache[Y+1][X] = self._minimumTotal(triangle, Y+1, X)
if self.cache[Y+1][X+1]:
belowRight = self.cache[Y+1][X+1]
else:
belowRight = self.cache[Y+1][X+1] = self._minimumTotal(triangle, Y+1, X+1)
return min(belowRight, below) + triangle[Y][X] |
93358c79f6be3b7ab77ae89e9e58039fb450a325 | FloHab/Project-Euler | /Problem 2.py | 635 | 3.96875 | 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.
fibonacci=[1,2]
count_a=0
count_b=1
while (fibonacci[-1]<4000000):
to_append=(fibonacci[count_a]+fibonacci[count_b])
fibonacci.append(to_append)
count_a=count_a+1
count_b=count_b+1
del fibonacci[-1]
fibonacci_2=[]
for x in fibonacci:
if (x%2)==0:
fibonacci_2.append(x)
print(sum(fibonacci_2)) |
0fa73411cdbcccb779e5f5c1f479767985d20454 | sourabh1983/music-festival | /festival/music_festival.py | 1,928 | 3.546875 | 4 | import operator
# Record label object consists of record label name and list of bands
class RecordLabel:
def __init__(self, name):
self.name = name
self.bands = []
def add_band(self, band):
if not self.band_exists_in_record_label(band):
self.bands.append(band)
self.bands = sorted(self.bands, key=operator.attrgetter('name'))
def band_exists_in_record_label(self, band):
if any(mf.name == band.name for mf in self.bands):
return True
return False
'''
Formats Output in below format:
Still Bottom Records
Wild Antelope
Trainerella
XS Recordings
Werewolf Weekday
LOL-palooza
unknownLabel
Squint-281
Twisted Tour
'''
def __str__(self):
return self.name + '\n' + '\n'.join(
[
'\t' + band.name + '\n'.join(
[
'\n\t\t' + mfest.name for mfest in band.music_festivals
]
) for band in self.bands
]
)
# Band object consist of band name and list of music festivals
class Band:
name = None
music_festivals = []
def __init__(self, name):
self.name = name
self.music_festivals = []
def add_music_festival(self, music_festival):
if not self.music_festival_exists_in_band(music_festival):
self.music_festivals.append(music_festival)
self.music_festivals = sorted(self.music_festivals, key=operator.attrgetter('name'))
def music_festival_exists_in_band(self, music_festival):
if any(mf.name == music_festival.name for mf in self.music_festivals):
return True
return False
# Music festival object consists of name
class MusicFestival:
def __init__(self, name):
self.name = name
|
fa5cf1ed5ecd0ab88b9c163dea1c725340e7eae9 | mmarcolina/spreadsheet-comparison | /comparison.py | 1,087 | 3.71875 | 4 | import pandas as pd
import numpy as np
import openpyxl
# creates dataframes for each of the documents
# dataframes are a table or a two-dimensional array-like structure in which each column contains values of one variable and each row contains one set of values
# change the workbook name values inside of df1 and df2 to compare whatever workbooks you'd like
df1=pd.read_excel('HG_MSA_Copy.xlsx')
df2=pd.read_excel('HGMSASeptember.xlsx')
#ensures the shape and type of dataframes are equal
df1.equals(df2)
#compares dataframes - will print out true or false
comparison_values = df1.values == df2.values
print (comparison_values)
# tuple of rows and columns
# get index of all cells where the values differ
rows,cols=np.where(comparison_values==False)
#iterate over the cells and update df1 to display changed value in df2
for item in zip(rows,cols):
df1.iloc[item[0], item[1]] = '{} --> {}'.format(df1.iloc[item[0], item[1]],df2.iloc[item[0], item[1]])
#export the dataframe into an excel file called Excel_diff
df1.to_excel('./Excel_differences.xlsx',index=False,header=True)
|
7b7688a4d39a8b69e56615b44f21e7f3617e57d8 | Addlaw/Python-Cert | /world_series.py | 1,521 | 3.859375 | 4 | ################################################################################
# Author: Addison Lawrence
# Date: 4/11/2020
# Allows a year to be input and returns the world series winner that
# year and how many times they have won
################################################################################
world_series={}#intialize dict
winners=[]#intialize list
index=0#intialize index
with open('WorldSeriesWinners.txt') as fo:#open text file
for line in fo:
winners.append(line.rstrip())#make a list of all world series winners
for x in range(1903,2020,1):#loop for each year
if x==1904 or x==1994:#if during a year it was not played
world_series[x]='not played'#set key value to not played
else:#if was played then
world_series[x]=winners[index]#set year value to the winner that year
index+=1#update the index
year=int(input('Enter a year in the range 1903-2019: '))#ask user for year
winner=world_series.get(year)#get the winner that year
if winner==None:#if winner cannot be found
print(f'Data for the year {year} is not included in the database.')
elif winner=='not played':#if during a year not played
print(f"The world series wasn't played in the year {year}.")
else:#if valid winner
wins=winners.count(winner)#count the number of winns they have had
print(f'The {winner} won the World Series in {year}.')#print who won
print(f'They have won the World Series {wins} times.')#print how much they have won
|
29a026566a72864c29f3787d490187930b1c9935 | Taneil-Kew/Hw | /Chapter 12/Chapter12.py | 1,369 | 3.75 | 4 | import calendar
cal = calendar.TextCalendar() # Create an instance
cal.pryear(2018) # What happens here?
#C
cal = calendar.TextCalendar(6)
cal.prmonth(2018, 4)
#D
d= calendar.LocaleTextcalendar(6, "Greek")
d.pryar(2012)
#E
print(calendar.isleap(8))
#it expects a year
#it returns true or false
#boolean
#E2
#leo section F
#A
#there are 47 functions for math
#B
import math
myvar = math.floor(78.89)
print(myvar)
mvar = math.ceil(78.89)
print(myvar)
#floor rounds down cell round up
#C
#have been using the exponete with x**.5, which would give the square root because its a fraction
x**.5
#D
#there are 5 constrants for math
math.pi
math.e
math.tau
math.inf
math.nan
#math.inf and math.nan were made by mark dickinson. The inf function does not need an negative sign. math.tau was created by Lisa Roach.
#E3
#Copy
#shallow copy doesn't copy references in the lists, the refs stay the same. For example in one list if the variable changes then the copied variable will cahnged aswell. In a deep copy, the refrences are copied as well, so to simila objects will still have their nesscary differences.
#in excersise 3 from chapter 11 deep copy would have been resourceful
#E4
#namespace_test
import mymodule1.py
import mymodule2.py
print( (mymodule2.myage - mymodule1.myage) ==
(mymodule2.year - mymodule1.year) )
print("My name is", __name__)
|
dd83e0e8834bb8e3003f15506f3581a22e24f1c3 | RohanNankani/Computer-Fundamentals-CS50 | /Python/drivers_license.py | 704 | 4.3125 | 4 | # Author: Rohan Nankani
# Date: October 27, 2020
# Name of Program: DriverLicense
# Purpose: To determine if the user is able to get a driver's license
# Greets user and gives brief detail on what the program does
print("Hello and welcome to the Driver License program!")
print("")
print("I will help you determine if you can get your driver's license!")
print("")
input("Press enter to continue: ")
print("".center(60, "-"))
# Gets input from the user about their age
age = int(input("What is your age? "))
print("")
# Determines whether the user is able to get a driver's license
if age >= 16:
print("You are able to get the driver's license!")
else:
print("You are not able to get a driver's license!")
|
f208db81e1ddac9a885ff7eae0e2efa952ce9290 | nerutia/Leetcode | /Algorithm/521.py | 747 | 3.859375 | 4 | # 最长特殊序列 Ⅰ
# 给你两个字符串,请你从这两个字符串中找出最长的特殊序列。
# 「最长特殊序列」定义如下:该序列为某字符串独有的最长子序列(即不能是其他字符串的子序列)。
# 子序列 可以通过删去字符串中的某些字符实现,但不能改变剩余字符的相对顺序。空序列为所有字符串的子序列,任何字符串为其自身的子序列。
# 输入为两个字符串,输出最长特殊序列的长度。如果不存在,则返回 -1。
class Solution:
def findLUSlength(self, a: str, b: str) -> int:
if a == b:
return -1
return max(len(a),len(b))
c = Solution()
print(c.findLUSlength("aba", "cdc")) |
f65bd55b7d643b220b43442b58ae639ccd4e2c85 | leelakrishna16/PythonPracticePrgs | /reverse_string.py | 250 | 4.0625 | 4 | #! /usr/bin/python3
def main():
string = 'krishnakarri111'
print(string[::-1])
main()
def revers(num):
rev = num[::-1]
return rev
print(revers('krishnakarri99'))
def reverse_string(str):
print(str[::-1])
reverse_string('krishnakaka')
|
be4436f29c1a3ec4e39ca6aa80def2c884179653 | Roberta-bsouza/pyscripts | /exe037.py | 217 | 3.984375 | 4 | #analise de string
n = str(input('Informe seu nome completo: '))
nome = n.split()#fatia o nome informado
print('Seu primeiro nome é {}'.format(nome[0]))
print('Seu último nome é {}'.format(nome[len(nome)-1]))
|
fd465eec8a063a0bf9395420a4d3457099705bfc | imd93shk/Learning-Python | /E09_Guess_Random_Number.py | 1,083 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
www.practicepython.org
Exercise 09: Guess Random Number
Created on Wed Sep 12 19:01:18 2018
@author: Imaad Shaik
"""
print("This program allow user to guess the random number generated by the program")
import random
play = "Y"
i = 0
old_guess = []
def random_num_gen():
random_num = random.randint(1, 9)
return random_num
random_num = random_num_gen()
while play == "Y":
if i > 0:
old_guess.append(user_guessed_number)
old_guess = [str(x) for x in old_guess]
print("Wrong guesses:", ", ".join(old_guess))
user_guessed_number = input("Please guess a number between 1 to 9 (both included)\n")
user_guessed_number = int(user_guessed_number)
if user_guessed_number == random_num:
print("Congratulations!!! Your guess", user_guessed_number, "is right!!!")
print("You guessed the right number in", i+1, "guesses")
else:
print("Sorry. Your guess", user_guessed_number, "is wrong.")
i += 1
play = input("Do you want to play again? Type Y for Yes and N for No\n")
|
2dd17242084342c456cd678043116c14c5df823f | egetoz/solverman | /Mathematics.py | 13,487 | 3.609375 | 4 | #imports
from math import ceil
import random
import json
import urllib
import __future__
import os
import datetime
# functions list
mathfunctions = {
"Mathematics":{
"hy": "calculate hypotenuse given the two other sides of the triangle",
"qe": "solve quadratic equations (equations of the form ax^2 + bx + c)",
"av": "given numbers seperated by commas, calculate the average.",
"isprime": "is the number n prime?",
"listnprimes": "list n primes",
"listprimesuntil": "list all the primes until n",
"any mathematical expression": "if you type in a mathematical expression that is not on of the commands listed, the program will automatically solve it for you (example: 12+123*1234)"
},
"Science": {
"p": "find density from the formula p = m / V",
"m": "find mass from the formula p = m / V",
"V": "find volume from the formula p = m / V"
},
"Other": {
"exit": "close the program"
}
}
mainfunctions = {
"math problems": "solve various math problems",
"play games": "play a fun game in the command line",
"exit": "quit the program"
}
#functions
def qe(a, b, c):
determinant = b ** 2 - 4 * a * c
if determinant > 0:
x1 = (-b + (b ** 2 - 4 *a *c) ** 0.5 ) / (2 * a)
x2 = (-b - (b ** 2 - 4*a*c) ** 0.5) / (2 * a)
elif determinant == 0:
x1, x2 = -b / (2 * a)
elif determinant < 0:
x1 = (-b / 2 * a) + sqrt(-determinant / (2 * a))
x1 = (-b / 2 * a) - sqrt(-determinant / (2 * a))
else:
return "Can not be solved"
return "The two answers are: " + str(x1) + " and " + str(x2)
def hy(l, h):
if l <= 0 or h <= 0:
return "Can not be solved"
else:
return "The hyptoneuse's length is " + str((l ** 2 + h ** 2) ** 0.5)
def av(array):
if len(array) > 0:
return "The average is: " + str(sum(array) / len(array))
else:
return "The list is empty"
def ismath(string):
array = ["0","1","2","3","4","5","6","7","8","9","(",")","*","/","-","+"]
for i in [i for i in string if i != " "]:
if i not in array:
return False
if len([i for i in string if i != " "]) != 0:
return True
else:
return False
def Mass(p, V):
return "The mass is: " + str(p * V)
def Density(m, V):
return "The density is: " + str(m / V)
def Volume(p, m):
return "The volume is: " + str(m / p)
def Work(F, d):
return "The Work is: " + str(F * d)
def Force(W, d):
return "The Force is: " + str(W / d)
def Distance(W, F):
return "The Distance is: " + str(W / F)
#primes
def isprime(n): #dependencies: math.ceil()
if n == 1:
return False
elif n % 2 == 0:
return False
for i in range(3, int(ceil(n ** 0.5)), 2):
if n % i == 0:
return False
return True
def listnprimes(n): #dependencies: isprime()
list = [2]
cursor = 3
while len(list) < n:
if isprime(cursor):
list.append(cursor)
cursor += 2
return list
def listprimeston(n): #dependencies: isprime()
list = [2]
cursor = 3
while cursor < n:
if isprime(cursor):
list.append(cursor)
cursor += 2
return list
#init
print "Hi, I am solverman"
name = raw_input("What is your name?: ")
while True:
q = raw_input("Would you like to solve math problems or play games OR our new feature youtube citation? %s ?: "% (name))
if q == "math problems":
while True:
print "Write 'help' to get a list of commands and 'exit' to exit"
q2 = raw_input("Which math problem do you want to solve? (type 'help' to see a list of commands): ")
if q2 == "help":
print json.dumps(mathfunctions, indent=4)
elif q2 == "qe":
print "Write variables"
a = float(raw_input("a: "))
b = float(raw_input("b: "))
c = float(raw_input("c: "))
print qe(a, b, c)
elif q2 == "hy":
l = float(raw_input("l: "))
h = float(raw_input("h: "))
print hy(l, h)
elif q2 == "av":
array = raw_input("Type in the list of numbers seperated by commas (example: 1,2,3,4,5): ").split(",")
array = [float(i) for i in array]
print av(array)
elif q2 == "isprime":
n = int(raw_input("Type in a number to find out if it's prime: "))
if isprime(n):
print str(n) + " is prime!"
else:
print str(n) + " isn't prime!"
elif q2 == "listnprimes":
n = int(raw_input("How many primes do you want to list? "))
print listnprimes(n)
elif q2 == "listprimesuntil":
n = int(raw_input("List all the primes until number: "))
print listprimesuntil(n)
elif q2 == "Density":
m = float(raw_input("Enter mass: "))
V = float(raw_input("Enter volume: "))
if m != 0 and V != 0:
print Density(m, V)
else:
print "The variables can not be 0"
elif q2 == "Mass":
p = float(raw_input("Enter density: "))
V = float(raw_input("Enter volume: "))
if p != 0 and V != 0:
print Mass(p, V)
else:
print "The variables can not be 0"
elif q2 == "Volume":
m = float(raw_input("Enter mass: "))
p = float(raw_input("Enter density: "))
if m != 0 and p != 0:
print Volume(p, m)
else:
print "The variables can not be 0"
elif q2 == "Work":
F = float(raw_input("Enter Force: "))
d = float(raw_input("Enter Distance: "))
if F != 0 and d != 0:
print Work(F, d)
else:
print "The variables can not be 0"
elif q2 == "Force":
W = float(raw_input("Enter Work: "))
d = float(raw_input("Enter Distance: "))
if W != 0 and d != 0:
print Force(W, d)
else:
print "The variables can not be 0"
elif q2 == "Distance":
W = float(raw_input("Enter Work: "))
F = float(raw_input("Enter Force: "))
if W != 0 and F != 0:
print Distance(W, F)
else:
print "The variables can not be 0"
elif q2 == "exit":
print "Bye!"
exit()
else:
if ismath(q2):
print "Your answer is " + str(eval(compile("".join([i for i in q2 if i != " "]), '<string>', 'eval', __future__.division.compiler_flag)))
else:
print "Not a valid command. Type 'help' to see a list of commands"
print "I hope I could help you."
elif q in ["play a game","play games"]:
quizinput = raw_input("Here's a quiz game for you. There are 85 questions that will be randomly given to you, they are categorized easy, medium and hard. Easy questions gain 1 points, medium 2 points and hard 3 points. Type in anything to begin, 'exit' to exit and 'back' to go back.: ")
if quizinput == "back":
continue
elif quizinput == "exit":
print "Bye!"
exit()
else:
thisfolder = os.path.dirname(os.path.abspath(__file__))
myfile = os.path.join(thisfolder, 'trivia.json')
trivia = open(myfile, "r")
data = json.loads(trivia.read())["results"]
random.shuffle(data)
trivia.close()
score = 0
for i in range(len(data)):
print "Question number " + str(i + 1) + ":"
print data[i]["question"]
choices = [data[i]["correct_answer"]] + data[i]["incorrect_answers"]
random.shuffle(choices)
print "A) " + choices[0]
print "B) " + choices[1]
print "C) " + choices[2]
print "D) " + choices[3]
while True:
quizanswer = raw_input("Which one do you choose? A, B, C or D?: ")
if quizanswer in "Aa":
if choices[0] == data[i]["correct_answer"]:
if data[i]["difficulty"] == "easy":
score += 1
elif data[i]["difficulty"] == "medium":
score += 2
elif data[i]["difficulty"] == "hard":
score += 3
print "You are absolutely correct! Your new score is " + str(score)
break
else:
print "You are WRONG! Your score is still " + str(score)
break
elif quizanswer in "Bb":
if choices[1] == data[i]["correct_answer"]:
if data[i]["difficulty"] == "easy":
score += 1
elif data[i]["difficulty"] == "medium":
score += 2
elif data[i]["difficulty"] == "hard":
score += 3
print "You are absolutely correct! Your new score is " + str(score)
break
else:
print "You are WRONG! Your score is still " + str(score)
break
elif quizanswer in "Cc":
if choices[2] == data[i]["correct_answer"]:
if data[i]["difficulty"] == "easy":
score += 1
elif data[i]["difficulty"] == "medium":
score += 2
elif data[i]["difficulty"] == "hard":
score += 3
print "You are absolutely correct! Your new score is " + str(score)
break
else:
print "You are WRONG! Your score is still " + str(score)
break
elif quizanswer in "Dd":
if choices[3] == data[i]["correct_answer"]:
if data[i]["difficulty"] == "easy":
score += 1
elif data[i]["difficulty"] == "medium":
score += 2
elif data[i]["difficulty"] == "hard":
score += 3
print "You are absolutely correct! Your new score is " + str(score)
break
else:
print "You are WRONG! Your score is still " + str(score)
break
else:
print "Not a valid answer, type only A, B, C or D."
contprompt = raw_input("Wanna continue?: ")
if contprompt == "no":
break
print "End of trivia! You scored " + str(score)
elif q == "youtube citation":
while True:
citevideo = raw_input("Enter video id: ")
citeurl = "https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=" + citevideo + "&key=AIzaSyA8bDxbFTEsuAt3gu5eVnzQcxsFGPFF_qQ"
url = urllib.urlopen(citeurl)
data = json.loads(url.read())
datatitle = data["items"][0]["snippet"]["title"]
datadate = data["items"][0]["snippet"]["publishedAt"][:10].split("-")
dataurl = "https://www.youtube.com/watch?v=" + citevideo
datachannel = data["items"][0]["snippet"]["channelTitle"]
months = {
"01":"January",
"02":"February",
"03":"March",
"04":"April",
"05":"May",
"06":"June",
"07":"July",
"08":"August",
"09":"September",
"10":"October",
"11":"November",
"12":"December"
}
datadate[1] = datadate[1].replace(datadate[1], months[datadate[1]])
datadate = " ".join(datadate[::-1])
now = datetime.datetime.now()
now = now.strftime("%d-%m-%Y").split("-")
now[1] = now[1].replace(now[1], months[now[1]])
now = " ".join(now)
print '"' + datatitle + '" Youtube, ' + datachannel + ', ' + datadate + ', ' + dataurl + ' Accessed ' + now
citecont = raw_input("Wanna continue?: ")
if citecont == "yes":
continue
else:
break
elif q in ["exit","quit","exit()"]:
print "Bye!"
exit()
else:
print "not a valid command (type 'exit' to exit)"
|
3c092475049c2ee0197a9392535f224c8aba42a6 | Hashah1/Leetcode-Practice | /medium/59. Spiral Matrix II.py | 1,371 | 3.65625 | 4 | class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
# Create bounds for the new spiral matrix
tr = 0 # Top Row
br = n - 1 # Bot Row
lc = 0 # Left Col
rc = n - 1 # Right Col
# Create a var to keep track of the number to add
num_to_add = 1
dir_ = "right"
# Create matrix prepopulated with 0s as dummy data
matrix = [[0 for _ in range(n)] for _ in range(n)]
while num_to_add <= n**2:
if dir_ == "right":
for i in range(tr, rc + 1):
matrix[tr][i] = num_to_add
num_to_add += 1
dir_ = "down"
tr += 1
elif dir_ == "down":
for i in range(tr, br + 1):
matrix[i][rc] = num_to_add
num_to_add += 1
dir_ = "left"
rc -= 1
elif dir_ == "left":
for i in range(rc, lc - 1, -1):
matrix[br][i] = num_to_add
num_to_add += 1
dir_ = "up"
br -=1
elif dir_ == "up":
for i in range(br, tr - 1, -1):
matrix[i][lc] = num_to_add
num_to_add += 1
lc += 1
dir_ = "right"
return matrix |
af21c66b05880871686a5b370bf1977cf142e334 | techbkr3/DataProgramming | /DataProgramming/Reading/a04.py | 401 | 3.703125 | 4 | #!/usr/bin/env python
file = open("students.csv")
for line in file:
l = line.strip()
print("DEBUG: ", l)
student = l.split(",")
print(student)
print("FULLNAME is ", student[0])
print("GENDER is ", student[1])
print("COURSE is ", student[2])
print("DEPARTMENT_CODE is ", student[3])
print("COLLEGE is ", student[4])
print("DATE_OF_VISIT is ", student[5])
|
b2bc6643e9c1eb6f8ca58fc95d768309279af8a2 | thientt03/C4E26 | /C4E26/lab2_homework/draw_star.py | 319 | 3.828125 | 4 | import turtle
window = turtle.Screen()
window.title("Square")
zo = turtle.Turtle()
def draw_star(x,y,length):
zo.penup()
zo.goto(x,y)
zo.pendown()
for i in range(5):
zo.left(144)
zo.forward(length)
draw_star(10,10,100)
window.mainloop()
|
8b9729a17497336e1ccb37a8de0aaec7cc929298 | jacksonpradolima/ufpr-ci182-trabalhos | /201901/Agronomia/CI182A/Agropops/win.py | 3,045 | 3.625 | 4 | from tkinter import *
from datetime import datetime
import tkinter.ttk as ttk
import sqlite3
class janela():
#Janela
win = Tk()
win.title("AgropopsOS 2.0.0")
win.configure(background = "khaki1")
#Aqui ficam as variaveis, por isso o "Var"
nome = StringVar()
quant = StringVar()
preco = StringVar()
#Texto
label_nome = Label(win , text = "Nome:" , bg = "khaki1" , fg = "black" , font = "Arial 12")
label_quantidade = Label(win , text = "Quantidade:" , bg = "khaki1" , fg = "black" , font = "Arial 12")
label_preco = Label(win , text = "Preço unitário:" , bg = "khaki1" , fg = "black" , font = "Arial 12")
label_hora = Label(win , text = datetime.now() , bg = "khaki1" , fg = "black" , font = "Arial 8")
label_marca = Label(win , text = "AgropopsOS®" , bg = "khaki1" , fg = "black", font = "Arial 7")
#Caixa de entrada
entnome = Entry(win , width = 20 , bg = "white" , textvariable = nome)
entquant = Entry(win , width = 20 , bg = "white" , textvariable = quant)
entpreco = Entry(win , width = 20 , bg = "white" , textvariable = preco)
#botao
botao_adicionar = Button(win , width = 20 , bg = "gray" , fg = "white" , text = "Adicionar")
botao_atualizar = Button(win , width = 20 , bg = "gray" , fg = "white" , text = "Atualizar selecionado")
botao_fechar = Button(win , width = 20 , bg = "red" , fg = "white" , text = "Fechar")
botao_deletar = Button(win , width = 20 , bg = "gray" , fg = "white" , text = "Deletar selecionado")
botao_visualizar = Button(win , width = 20, bg = "gray" , fg = "white" , text = "Ver lista")
botao_pesquisar = Button(win , width = 20, bg = "gray" , fg = "white" , text = "Pesquisar")
#Lista
lista = Listbox(win , width = 100 , font = "Calibri 12" , selectmode = EXTENDED)
scroll_lista = Scrollbar(win)
scroll_listax = Scrollbar(win , width = 17)
#Posicionamento dos elementos na grade
label_nome.grid(row = 0 , column = 0 , sticky = W)
label_quantidade.grid(row = 1 , column = 0 , sticky = W)
label_preco.grid(row = 2 , column = 0)
entnome.grid(row = 0 , column = 1 , padx = 50)
entquant.grid(row = 1 , column = 1)
entpreco.grid(row = 2 , column = 1)
lista.grid(row = 0 , column = 2 , rowspan = 10 , sticky = NS)
scroll_lista.grid(row = 0 , column = 6 , rowspan = 10 , sticky = NS)
scroll_listax.grid(row = 10 , column = 2 , sticky = EW)
botao_adicionar.grid(row = 4 , column = 0 , columnspan = 2)
botao_atualizar.grid(row = 5 , column = 0 , columnspan = 2)
botao_pesquisar.grid(row = 6 , column = 0 , columnspan = 2)
botao_visualizar.grid(row = 7 , column = 0 , columnspan = 2)
botao_deletar.grid(row = 8 , column = 0 , columnspan = 2)
botao_fechar.grid(row = 9 , column = 0 , columnspan = 2)
label_marca.grid(row = 10 , column = 0 , sticky = W)
# Scroll
lista.configure(yscrollcommand = scroll_lista.set)
lista.configure(xscrollcommand = scroll_listax.set)
scroll_lista.configure(command = lista.yview)
scroll_listax.configure(command = lista.xview , orient = HORIZONTAL)
def run(self):
janela.win.mainloop() |
0ccf8885f08f816762f03743b0ad4d93a954cfd1 | MansourKef/holbertonschool-python | /0x07-python-test_driven_development/100-matrix_mul.py | 1,462 | 4.15625 | 4 | #!/usr/bin/python3
"""
Module to multiply 2 matrices
"""
def matrix_mul(m_a, m_b):
"""
Function to multiply 2 matrices and return the result
"""
if not isinstance(m_a, list):
raise TypeError("m_a must be a list")
if not isinstance(m_b, list):
raise TypeError("m_b must be a list")
if any(not isinstance(el, list) for el in m_a):
raise TypeError("m_a must be a list of lists")
if any(not isinstance(el, list) for el in m_b):
raise TypeError("m_b must be a list of lists")
if len(m_a) == 0:
raise TypeError("m_a must be a list of lists")
if len(m_b) == 0:
raise TypeError("m_b must be a list of lists")
for i in range(len(m_a)):
for j in range(len(m_a[0])):
if not isinstance(m_a[i][j], (float, int)):
raise TypeError("m_a should contain only integers or floats")
for i in range(len(m_b)):
for j in range(len(m_b[0])):
if not isinstance(m_b[i][j], (float, int)):
raise TypeError("m_b should contain only integers or floats")
if any((len(m_a[0]) != len(d)) for d in m_a):
raise TypeError("each row of m_a must be of the same size")
if any((len(m_b[0]) != len(d)) for d in m_b):
raise TypeError("each row of m_b must be of the same size")
result = [[sum(a*b for a, b in zip(m_a_row, m_b_col))
for m_b_col in zip(*m_b)] for m_a_row in m_a]
return result
|
8e0f477e9cc3fdc7c04106e49b0546e46ff93de5 | jashburn8020/design-patterns | /python/src/bridge/bridge_test.py | 5,358 | 3.84375 | 4 | """Bridge pattern example.
Circles, squares, and rectangles each can be rendered in vector or raster form.
One way to draw them is by having VectorCircle, VectorSquare, VectorRectangle,
RasterCircle, RasterSquare, and RasterRectangle.
Instead, split the concepts into shapes and renderers.
Based on example in "Design Patterns in Python for Engineers, Designers, and Architects"
"""
from abc import ABC, abstractmethod
from unittest import mock
import pytest
from pytest_mock import MockerFixture
class Renderer(ABC):
"""Implementor: shape renderer base class."""
@abstractmethod
def render_circle(self, radius: int) -> None:
"""Render a circle."""
# Note: Violates OCP - tied to the shape to be rendered - price to pay for
# additional flexibility
@abstractmethod
def render_square(self, side: int) -> None:
"""Render a square."""
@abstractmethod
def render_rectangle(self, horiz_side: int, vert_side: int) -> None:
"""Render a rectangle."""
class VectorRenderer(Renderer):
"""ConcreteImplementor: shape renderer in vector form."""
def render_circle(self, radius: int) -> None:
"""Render a circle in vector form."""
# Render as vector image
def render_square(self, side: int) -> None:
"""Render a square in vector form."""
# Render as vector image
def render_rectangle(self, horiz_side: int, vert_side: int) -> None:
"""Render a rectangle."""
# Render as vector image
class RasterRenderer(Renderer):
"""ConcreteImplementor: shape renderer in raster form."""
def render_circle(self, radius: int) -> None:
"""Render a circle in raster form."""
# Render as raster image
def render_square(self, side: int) -> None:
"""Render a square in raster form."""
# Render as raster image
def render_rectangle(self, horiz_side: int, vert_side: int) -> None:
"""Render a rectangle."""
# Render as raster image
class Shape(ABC):
"""Abstraction: shape base class."""
def __init__(self, renderer: Renderer):
self.renderer = renderer
@abstractmethod
def draw(self) -> None:
"""Draw the shape."""
@abstractmethod
def resize(self, factor: int) -> None:
"""Resize the shape."""
class Circle(Shape):
"""RefinedAbstraction: a circular shape."""
def __init__(self, renderer: Renderer, radius: int):
super().__init__(renderer)
self.radius = radius
def draw(self) -> None:
"""Draw the circle using the provided renderer."""
self.renderer.render_circle(self.radius)
def resize(self, factor: int) -> None:
"""Resize the circle by the specified factor applied to its radius."""
self.radius *= factor
class Square(Shape):
"""RefinedAbstraction: a square shape."""
def __init__(self, renderer: Renderer, side: int):
super().__init__(renderer)
self.side = side
def draw(self) -> None:
"""Draw the square using the provided renderer."""
self.renderer.render_square(self.side)
def resize(self, factor: int) -> None:
"""Resize the square by the specified factor applied to its sides."""
self.side *= factor
class Rectangle(Shape):
"""RefinedAbstraction: a rectangular shape."""
def __init__(self, renderer: Renderer, horiz_side: int, vert_side: int):
super().__init__(renderer)
self.horiz_side = horiz_side
self.vert_side = vert_side
def draw(self) -> None:
"""Draw the square using the provided renderer."""
self.renderer.render_rectangle(self.horiz_side, self.vert_side)
def resize(self, factor: int) -> None:
"""Resize the rectangle by the specified factor applied to its sides."""
self.horiz_side *= factor
self.vert_side *= factor
renderers = (
pytest.param(RasterRenderer(), id="raster"),
pytest.param(VectorRenderer(), id="vector"),
)
@pytest.mark.parametrize("renderer", renderers)
def test_circle_rendering(mocker: MockerFixture, renderer: Renderer) -> None:
"""Draw a circle using raster and vector renderers."""
spy_renderer = mocker.spy(renderer, "render_circle")
circle = Circle(renderer, 5)
circle.draw()
circle.resize(2)
circle.draw()
spy_renderer.assert_has_calls((mock.call(5), mock.call(10)))
assert spy_renderer.call_count == 2
@pytest.mark.parametrize("renderer", renderers)
def test_square_rendering(mocker: MockerFixture, renderer: Renderer) -> None:
"""Draw a square using raster and vector renderers."""
spy_renderer = mocker.spy(renderer, "render_square")
square = Square(renderer, 2)
square.draw()
square.resize(3)
square.draw()
spy_renderer.assert_has_calls((mock.call(2), mock.call(6)))
assert spy_renderer.call_count == 2
@pytest.mark.parametrize("renderer", renderers)
def test_rectangle_rendering(mocker: MockerFixture, renderer: Renderer) -> None:
"""Draw a square using raster and vector renderers."""
spy_renderer = mocker.spy(renderer, "render_rectangle")
rectangle = Rectangle(renderer, 1, 3)
rectangle.draw()
rectangle.resize(2)
rectangle.draw()
spy_renderer.assert_has_calls((mock.call(1, 3), mock.call(2, 6)))
assert spy_renderer.call_count == 2
|
7a69a428c75b05f0d697e7336c65d7bb73d18f44 | asperaa/back_to_grind | /Binary_Search/378. Kth Smallest Element in a Sorted Matrix [BS].py | 1,339 | 3.984375 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""378. Kth Smallest Element in a Sorted Matrix [Binary Search]
"""
import pdb
class Solution:
def less_than_equal_count(self, matrix, k, mid, length):
row, column = length-1, 0
count = 0
smaller, larger = matrix[0][0], matrix[length-1][length-1]
while row >= 0 and column <= length - 1:
if matrix[row][column] > mid:
larger = min(larger, matrix[row][column])
row -= 1
else:
count += row + 1
smaller = max(smaller, matrix[row][column])
column += 1
return count, smaller, larger
def kthSmallest(self, matrix, k):
n = len(matrix)
left, right = matrix[0][0], matrix[n-1][n-1]
while left < right:
mid = left + (right - left) // 2
count, smaller, larger = self.less_than_equal_count(matrix, k, mid, n)
if count == k:
return smaller
elif count < k:
left = larger
else:
right = smaller
return left
if __name__ == "__main__":
s = Solution()
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
]
print(s.kthSmallest(matrix, 8)) |
1e1db010af8c4cd1fde4efadb13c20ad8bbd0726 | No-Masc-Curt-17/1.2.1-Game- | /1.2.1.py | 1,898 | 3.59375 | 4 | import random as rand
import turtle as trtl
painter = trtl.Turtle()
painter.speed(0)
score_writer = trtl.Turtle()
font_setup = ("Times New Roman", 20, "normal")
timer = 5
counter_interval = 1000 #1000 represents 1 second
timer_up = False
#-----countdown writer-----
counter = trtl.Turtle()
#-----game functions-----
def countdown():
global timer, timer_up
counter.clear()
counter.penup()
counter.goto(-350,-300)
painter.pd()
if timer <= 0:
counter.write("Time's Up", font=font_setup)
timer_up = True
painter.ht()
else:
counter.write("Timer: " + str(timer), font=font_setup)
timer -= 1
counter.getscreen().ontimer(countdown, counter_interval)
def turtle_shape():
painter.shapesize(rand.randint(1,5))
colors = ["red", "gold", "black", "green", "purple", "brown", "silver"]
colors = colors[rand.randint(0,5)]
painter.color(colors)
painter.shape('circle')
score = 0
def change_position(x,y):
if timer_up == False:
score_writer.clear()
score_writer.penup()
score_writer.goto(-200, 200)
random_x = rand.randint(-200,200)
random_y = rand.randint(-150,150)
painter.penup()
painter.goto(random_x,random_y)
painter.pendown()
global score
score +=1
painter.shapesize(rand.randint(1,5))
colors = ["red", "gold", "black", "green", "purple", "brown", "silver"]
colors = colors[rand.randint(0,5)]
painter.color(colors)
painter.shape('circle')
colors_1 = ["cyan", "pink", "cornflower blue", "yellow", "orange", "magenta"]
colors_1 = colors_1[rand.randint(0,4)]
wn = trtl.Screen()
wn.bgcolor(colors_1)
score_writer.pendown()
score_writer.write(score, font=font_setup)
turtle_shape()
painter.onclick(change_position)
wn = trtl.Screen()
wn.ontimer(countdown, counter_interval)
wn.mainloop() |
282b4310b01b06cadacb649bd39382671ad03d82 | yugandharjavvadi/dialycoding | /day21.py | 507 | 3.6875 | 4 | '''Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required.
For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
'''
#solution
def classroomreq(l):
finishtimes=[]
for i in l:
finishtimes.append(i[1])
n=max(finishtimes)
d=[0]*(n+1)
for i in l:
for j in range(i[0],i[1]+1):
d[j]+=1
return max(d)
l=[(30, 75), (0, 50), (60, 150)]
print(classroomreq(l))
|
4cd8044e74404d46cfa3049049c423bb8b3da599 | ariannasg/python3-training | /advanced/class_computed_attrs.py | 3,680 | 4.53125 | 5 | #!usr/bin/env python3
# classes can use methods to control how attributes are accessed on an object.
# Whenever an object's attributes are retrieved or set, Python calls one of
# these functions to give your class an opportunity to perform any desired
# processing.
# getattribute and getattr, are called to retrieve an attribute value.
# getattr is called only when the requested attribute can't be found on the
# object.
# getattribute is called every time an attribute name is requested and when
# Python goes to look up any methods on your class.
# setattr is called when an attribute value is set on the object.
# delattr is called to delete an attribute.
# dir is called when the dir function is used on the object.
class Color:
def __init__(self):
self.red = 50
self.green = 75
self.blue = 100
# use getattr to dynamically return a value
def __getattr__(self, attr):
if attr == 'rgbcolor':
return self.red, self.green, self.blue
elif attr == 'hexcolor': # format the values to 2 char hex strings
return '#{0:02x}{1:02x}{2:02x}'.format(
self.red, self.green, self.blue)
else:
raise AttributeError
# use setattr to dynamically return a value
def __setattr__(self, attr, val):
if attr == 'rgbcolor':
self.red = val[0]
self.green = val[1]
self.blue = val[2]
else:
# always make sure you call the super class.
# reason: in the constructor I've got some existing attributes.
# when the class is initialized and the assignment statements
# are executed, the __setattr__ is going to be called for each
# attribute. if you don't call the super.setattr, then the
# __getattr__ function will be called instead. And since it's not
# one of the attr we have defined, an attribute error will be
# raised.
super().__setattr__(attr, val)
# use dir to list the available properties
def __dir__(self):
return 'rgbolor', 'hexcolor'
def main():
# create an instance of Color
cls1 = Color()
# print the value of a computed attribute
print(cls1.rgbcolor)
print(cls1.hexcolor)
# set the value of a computed attribute
cls1.rgbcolor = (125, 200, 86)
print(cls1.rgbcolor)
print(cls1.hexcolor)
# access a regular attribute
print(cls1.red)
# list the available properties
print(dir(cls1))
# list the available properties of the str class
print(dir(str))
if __name__ == "__main__":
main()
# CONSOLE OUTPUT:
# (50, 75, 100)
# #324b64
# (125, 200, 86)
# #7dc856
# 125
# ['hexcolor', 'rgbolor']
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
|
48517106cb9536ccdc90f9ec0f4df6e580f5a665 | DoctorSad/_Course | /Lesson_04/_3_for_while_str.py | 403 | 4.25 | 4 | """
Строки можно обойти циклом.
1. Перебрать все элементы строки циклом for.
2. Пройти по индексам элементов строки циклом for либо while.
"""
s = "Hello world!"
for i in s:
print(i)
for i in range(len(s)):
print(s[i])
i = 0
while i < len(s):
print(s[i], end=", ")
i += 1
|
a19b1760817c9cc4a2081cc1c70a60d7d4361426 | joanvaquer/SDV | /sdv/models/copulas.py | 5,636 | 3.5 | 4 | """Wrappers around copulas models."""
import numpy as np
from copulas import EPSILON
from copulas.multivariate import GaussianMultivariate
from copulas.univariate import GaussianUnivariate
from sdv.models.base import SDVModel
from sdv.tabular.utils import (
check_matrix_symmetric_positive_definite, flatten_dict, impute, make_positive_definite,
square_matrix, unflatten_dict)
class GaussianCopula(SDVModel):
"""Model wrapping ``copulas.multivariate.GaussianMultivariate`` copula.
Args:
distribution (copulas.univariate.Univariate or str):
Copulas univariate distribution to use.
Example:
The example below shows simple usage case where a ``GaussianMultivariate``
is being created and its ``fit`` and ``sample`` methods are being called.
>>> model = GaussianMultivariate()
>>> model.fit(pd.DataFrame({'a_field': list(range(10))}))
>>> model.sample(5)
a_field
0 4.796559
1 7.395329
2 7.400417
3 2.794212
4 1.925887
"""
DISTRIBUTION = GaussianUnivariate
distribution = None
model = None
def __init__(self, distribution=None):
self.distribution = distribution or self.DISTRIBUTION
def fit(self, table_data):
"""Fit the model to the table.
Impute the table data before fit the model.
Args:
table_data (pandas.DataFrame):
Data to be fitted.
"""
table_data = impute(table_data)
self.model = GaussianMultivariate(distribution=self.distribution)
self.model.fit(table_data)
def sample(self, num_samples):
"""Sample ``num_samples`` rows from the model.
Args:
num_samples (int):
Amount of rows to sample.
Returns:
pandas.DataFrame:
Sampled data with the number of rows specified in ``num_samples``.
"""
return self.model.sample(num_samples)
def get_parameters(self):
"""Get copula model parameters.
Compute model ``covariance`` and ``distribution.std``
before it returns the flatten dict.
Returns:
dict:
Copula flatten parameters.
"""
values = list()
triangle = np.tril(self.model.covariance)
for index, row in enumerate(triangle.tolist()):
values.append(row[:index + 1])
self.model.covariance = np.array(values)
params = self.model.to_dict()
univariates = dict()
for name, univariate in zip(params.pop('columns'), params['univariates']):
univariates[name] = univariate
if 'scale' in univariate:
scale = univariate['scale']
if scale == 0:
scale = EPSILON
univariate['scale'] = np.log(scale)
params['univariates'] = univariates
return flatten_dict(params)
def _prepare_sampled_covariance(self, covariance):
"""Prepare a covariance matrix.
Args:
covariance (list):
covariance after unflattening model parameters.
Result:
list[list]:
symmetric Positive semi-definite matrix.
"""
covariance = np.array(square_matrix(covariance))
covariance = (covariance + covariance.T - (np.identity(covariance.shape[0]) * covariance))
if not check_matrix_symmetric_positive_definite(covariance):
covariance = make_positive_definite(covariance)
return covariance.tolist()
def _unflatten_gaussian_copula(self, model_parameters):
"""Prepare unflattened model params to recreate Gaussian Multivariate instance.
The preparations consist basically in:
- Transform sampled negative standard deviations from distributions into positive
numbers
- Ensure the covariance matrix is a valid symmetric positive-semidefinite matrix.
- Add string parameters kept inside the class (as they can't be modelled),
like ``distribution_type``.
Args:
model_parameters (dict):
Sampled and reestructured model parameters.
Returns:
dict:
Model parameters ready to recreate the model.
"""
univariate_kwargs = {
'type': model_parameters['distribution']
}
columns = list()
univariates = list()
for column, univariate in model_parameters['univariates'].items():
columns.append(column)
univariate.update(univariate_kwargs)
univariate['scale'] = np.exp(univariate['scale'])
univariates.append(univariate)
model_parameters['univariates'] = univariates
model_parameters['columns'] = columns
covariance = model_parameters.get('covariance')
model_parameters['covariance'] = self._prepare_sampled_covariance(covariance)
return model_parameters
def set_parameters(self, parameters):
"""Set copula model parameters.
Add additional keys after unflatte the parameters
in order to set expected parameters for the copula.
Args:
dict:
Copula flatten parameters.
"""
parameters = unflatten_dict(parameters)
parameters.setdefault('fitted', True)
parameters.setdefault('distribution', self.distribution)
parameters = self._unflatten_gaussian_copula(parameters)
self.model = GaussianMultivariate.from_dict(parameters)
|
1ec088eaa67602456300fe0d4cde4ef27369a688 | imtanmays/Coding-Problems | /Strings/excel_col_num.py | 330 | 3.578125 | 4 | '''
Topic : Strings
Problem : Excel Sheet Column Number
Link : https://leetcode.com/problems/excel-sheet-column-number/
'''
def titleToNumber(s):
col_num = 0
len_s = len(s)
for i in range(1,len_s+1):
char = s[len_s - i].lower()
col_num += (ord(char)-96) * (26 ** (i-1))
return col_num |
f409af133ecaff01b9e063572339ff3651f18cca | Rifat951/PythonExercises | /ExercisesForInterview/Exercise5.py | 419 | 3.90625 | 4 | # Write a function to return True if the first and last number of a given list is same. If numbers are different then return False.
# Given list: [10, 20, 30, 40, 10]
# result is True
# numbers_y = [75, 65, 35, 75, 30]
# result is False
def TF(listofNum):
if(listofNum[0] == listofNum[-1]):
print("True")
else:
print("False")
listt = [75, 65, 35, 75, 30]
TF(listt)
|
95c1f942558ffdf0fa08de18a896a59a792e4bf4 | gaojianshuai/vpc-ui | /pycharm_practice/pycharm_practice_air_quality/pycharm_practice_quality_pachong5.py | 1,149 | 3.5625 | 4 | #coding=utf-8
"""
版本:6.0
作者:高建帅
功能:空气质量计算
日期:10/04/2019
新增功能:网络爬虫获取实时信息
新增功能:将数据保存到csv文件中
版本:6.0
"""
import requests
import csv
import pandas as pd
def main():
"""
主函数
"""
aqi_data = pd.read_csv('china_city_aqi.csv')
print('基本信息:')
print(aqi_data.info())
print('数据预览:')
print(aqi_data.head())
#基本统计
print('AQI最大值:', aqi_data['AQI'].max())
print('AQI最大值:', aqi_data['AQI'].min())
print('AQI最大值:', aqi_data['AQI'].mean())
#全中国top10
top10_cities = aqi_data.sort_values(by=['AQI']).head(10)
print('空气质量最好的城市:')
print(top10_cities)
#bottom10
bottom10_cities = aqi_data.sort_values(by=['AQI'], ascending=False).head(10)
print('空气质量最差的城市:')
print(bottom10_cities)
#保存成csv
top10_cities.to_csv('top10_aqi.csv', index=False)
bottom10_cities.to_csv('bottom10_aqi.csv', index=False)
if __name__ == '__main__':
main() |
ef62fa1d76d5fabeec4a7f334266af03390b6b3a | hsnckkgl/Python | /variablesAndConditions.py | 3,109 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
radius = float(input('give me a radius: '))
pi = 3.14
area = pi * radius**2
print('the area of the circle is: ', area)
fah = float(input('please give me a fahreneit tempereture '))
cel = (fah-32) * 5/9
print('this' ,fah, 'is equal to this' ,cel )
num1 = int(input('please give me the first number: '))
num2 = int(input('please give me the second number: '))
print('the first number is: ' + str(num1) + ' the second number is: ' + str(num2) + ' the sum is: ' + str(num1+num2))
num1 = int(input('write the first number: '))
num2 = int(input('write the second number: '))
sum = num1 * num2
print ('the sum is: ' ,sum)
num1,num2,num3 = 10,20,30
print(num1<25 and num3<25)
print(num2>40 or num1>5)
print('not True is: ', not True)
print('not False is: ', not False)
condition = False
if condition:
print('condition is True')
else:
print('condition is False')
temp = int(input('Please write a celcius tempereture: '))
if temp > 30:
print('t-shirt and sun cream')
elif temp <= 30 and temp > 20:
print('wear sweetshirt')
elif temp <= 20 and temp >10:
print('wear jacket')
else:
print('stay home')
myString = 'Python'
print(len(myString))
print(myString[0]) #first letter
print(myString[0:4]) #not include 4. index
print(myString[-1]) #last letter again
print(myString.upper()) #all upper case
print(myString.lower()) #all lower case
guess = input('guess what is the season: ')
guess = guess.lower()
if guess == 'summer':
print('Yes it is summer')
elif guess == 'winter':
print('No it is not winter')
elif guess == 'spring':
print('No it is not spring')
elif guess== 'autumn':
print('No it is not autumn')
else:
print(guess.capitalize(), ' is not a season!') #capitalize() first letter is upper case
number = int(input('please enter a number between 1 and 5: '))
if number == 1:
print('one')
elif number == 2:
print('two')
elif number == 3:
print('three')
elif number == 4:
print('four')
elif number == 5:
print('five')
else:
print('invalid number')
number = input('please enter a number as string between one and five: ')
numberLowerCase = number.lower()
if numberLowerCase == 'one':
print('1')
elif numberLowerCase == 'two':
print('2')
elif numberLowerCase == 'three':
print('3')
elif numberLowerCase == 'four':
print('4')
elif numberLowerCase == 'five':
print('5')
else:
print('enter a invalid number')
secretNumber = 5
guess = int(input('guess the number between 1 and 10: '))
if guess == secretNumber:
print('you are correct')
elif guess >= secretNumber and guess <= 10:
print('you say too high')
elif guess <= secretNumber and guess >= 1:
print('you say low')
else:
print('invalid guess')
name = input('please enter your name: ')
nameLenght = len(name)
if nameLenght > 3:
print('your name has ',nameLenght, 'chracter')
else:
print('it is too short, I will not write it')
|
c73edf62f0bb0f6e392c23442903b85e543cbbd3 | GeorgiTodorovDev/Python-Fundamental | /06.Exercise: Basic Syntax, Conditional Statements and Loops/04.double_char.py | 108 | 3.59375 | 4 | str_input = input()
double_char = ""
for index in str_input:
double_char += index * 2
print(double_char) |
d349ceef77e1fc813107badab3ffc0577d897c4f | larcat/create-games-python | /Chapter 3/Quiz -- Larcat.py | 1,924 | 4.34375 | 4 | print("This is a quiz you have to take.")
# Setting up initial variables
current_answer = ""
number_correct = 0
name = " "
# Question 1
print("Question 1:")
name = input("What is your name? ")
print()
print("Hi {!r}, good job getting the first question right!".format(name))
number_correct += 1
print()
# Question 2
print("What is the President's name?")
print()
print("A) RONALD REAGAN")
print("B) JIMMY BUTLER")
print("C) WOODY WOODPECKER")
print("D) BARACK OBAMA")
print()
current_answer = input("Your answer: ")
print()
#Checks for rightness of question 2
if current_answer == "D" or current_answer == "d":
print("You got it right! OB is pres!")
number_correct += 1
print()
else:
print("So sad. Wrong :\(")
print()
# Question 3
current_answer = input("What is 2 + 2? ")
print()
#Checks for rightness of question 3
if str.lower(current_answer) == "four" or int(current_answer) == 4:
print("You got it right! Four is correct!")
number_correct += 1
print()
else:
print("So sad. Wrong :\(")
print()
# Question 4
print("Bebe is ferocious. True or False? ")
print()
print("A) True")
print("B) False")
print()
current_answer = input("Your answer: ")
print()
#Checks for rightness of question 4
if str.lower(current_answer) == "a":
print("You got it right! Bebe IS ferocious.")
number_correct += 1
print()
else:
print("So sad. Wrong Everyone knows Bebe is ferocious :\(")
print()
# Question 5
print("Sinner is dorky. True or False? ")
print()
print("A) True")
print("B) False")
print()
current_answer = input("Your answer: ")
print()
#Checks for rightness of question 5
if str.lower(current_answer) == "a":
print("You got it right! Sinner IS dorky.")
number_correct += 1
print()
else:
print("So sad. Wrong Everyone knows Sinner is dorky :\(")
print()
print("Quiz complete! Computing score.")
print()
print(20 * number_correct, "% Correct.")
|
42e3aa451a3680252bebab00a91829b01be2f748 | isharajan/python_stuff | /find the great num.py | 129 | 3.984375 | 4 | a=int(input("enter num a:"))
b=int(input("enter num b:"))
if(a>b):
print("a is great")
else:
print("b is great")
|
0a066c124a8736649f301238720651b97bd5875b | yhw1234/network_dynamics | /network.py | 9,230 | 3.5625 | 4 | """
Luc Blassel
network object
"""
import networkx as nx
import matplotlib.pyplot as plt
import random as rd
from queue import Queue
from node import Node
from info import Info
class Reseau():
"""
Network of nodes
"""
def __init__(self,size,disposition,verbose):
if size <2:
print("A network must contain at least 2 nodes...")
return
self.size = size
self.nodes = {}
self.informations = []
self.verbose = verbose
self.frameCount = 0
self.edges = []
self.layout = None
self.dispo = nx.layout.spring_layout if disposition == 'spring' else nx.layout.shell_layout
self.draw = nx.draw_spring if disposition == 'spring' else nx.draw_shell
def initReseau(self):
"""
initializes nodes and connections in graph
"""
self.nodes = {i:Node(i,0.3,self.verbose) for i in range(self.size)}
for i in self.nodes:
self.nodes[i].connect(self.nodes)
def drawReseau(self):
"""
draws the network with networkX instead of graphviz
"""
G = nx.Graph()
G.add_nodes_from(self.nodes.keys())
edges = []
for key in self.nodes:
node = self.nodes[key]
for dest in node.connections:
edge = [key,dest.id]
edge.sort()
edge = tuple(edge)
edges.append(edge)
edges = set(edges)
G.add_edges_from(edges)
self.draw(G, with_labels=True, font_weight='bold')
plt.show()
def drawFrame(self):
"""
draws frame of animation to see the evolution of network
"""
G = nx.Graph()
edges = []
for key in self.nodes:
node = self.nodes[key]
color = 'r'
shape = 'o'
if node.hasLiked :
color = 'g'
if node.hasConsulted:
shape = 's'
G.add_node(node.id,shape = shape, color = color)
if not self.edges:
for dest in node.connections:
edge = [key,dest.id]
edge.sort()
edge = tuple(edge)
edges.append(edge)
if not self.edges: #dont find edges at each frame, find them once and save them
edges = set(edges)
self.edges = edges
for edge in self.edges:
if self.nodes[edge[0]].toSend is not None or self.nodes[edge[1]].toSend is not None : #either one of the nodes are sending info
G.add_edge(edge[0], edge[1], color = 'b', weight = 4)
else:
G.add_edge(edge[0], edge[1], color = 'k', weight = 2)
# G.add_edges_from(self.edges)
edgeColors = [G[u][v]['color'] for u,v in G.edges()]
edgeWeights = [G[u][v]['weight'] for u,v in G.edges()]
if self.layout is None:
nodePos = self.dispo(G)
self.layout = nodePos
else: #to keep nodes in same place during iterations
nodePos = self.layout
nodeShapes = set((aShape[1]["shape"] for aShape in G.nodes(data = True)))
fig = plt.figure(frameon = False)
fig.suptitle('step '+str(self.frameCount))
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
for shape in nodeShapes:
nodeList = [sNode[0] for sNode in filter(lambda x: x[1]["shape"] == shape,G.nodes(data = True))]
colorList = [sNode[1]["color"] for sNode in filter(lambda x: x[1]["shape"] == shape,G.nodes(data = True))]
nx.draw_networkx_nodes(G,nodePos,node_shape = shape, node_color = colorList , nodelist = nodeList)
nx.draw_networkx_edges(G, nodePos, width = edgeWeights, edge_color = edgeColors )
nx.draw_networkx_labels(G, pos = nodePos)
fig.savefig('frames/frame'+str(self.frameCount)+'.png', dpi = 200)
plt.close()
self.frameCount += 1
def breadthFirst(self,node,node2):
"""
breadth first search of graph starting from node, returns shortest path to node2
"""
queue = Queue(maxsize=len(self.nodes))
queue.put(self.nodes[node])
self.nodes[node].visited = True
path = []
prev = {}
prev[node]=None
if node == node2:
return
while not queue.empty():
node = queue.get()
# print(node.id)
for neighbour in node.connections:
neighbour = neighbour.id
if not self.nodes[neighbour].visited:
prev[neighbour] = node.id
queue.put(self.nodes[neighbour])
self.nodes[neighbour].visited = True
if neighbour == node2:
prevNode = node.id
path.append(neighbour)
while prevNode is not None:
path.append(prevNode)
prevNode = prev[prevNode]
path.reverse()
return path
def resetNodes(self):
"""
resets visited status of all nodes in network
"""
for node in self.nodes:
self.nodes[node].visited = False
def distance(self,node1,node2):
"""
returns minimum distance between 2 nodes
"""
path = self.breadthFirst(node1,node2)
return len(path)-1 if path is not None else None
def diametre(self):
"""
returns maximum possible distance between 2 nodes
"""
maxDist = 0
for node1 in range(len(self.nodes)):
for node2 in range(node1+1,len(self.nodes)): #no need to go through all nodes (bc. distance is symetrical)
self.resetNodes()
dist = self.distance(node1,node2)
if dist is not None and dist > maxDist:
maxDist = dist
return maxDist
def selectNode(self):
"""
selects a random node in the network and has it send a new information
"""
chosenNode = rd.choice(list(self.nodes.keys()))
self.introduceInfo()
self.nodes[chosenNode].toSend = self.informations[-1]
self.nodes[chosenNode].send()
def introduceInfo(self):
"""
creates an information in the network
"""
if not self.informations:
infoId = 0
else:
infoId = self.informations[-1].id+1
if self.verbose:
print("introducing information number "+str(infoId))
self.informations.append(Info(infoId,2,self.nodes.keys(),self.verbose))
def sendAll(self):
"""
send all information to send at the beginning of each timestep
"""
for node in self.nodes:
if self.nodes[node].toSend is not None:
self.nodes[node].send()
self.nodes[node].hasLiked = False
self.nodes[node].hasConsulted = False #to animate graph
def getConnections(self,netId):
"""
gets all unique connections in graph
"""
connections = []
for key in self.nodes:
node = self.nodes[key]
for dest in node.connections:
connection = [key,dest.id]
connection.sort()
connection = [netId] + connection
connection = tuple(connection)
connections.append(connection)
return connections
def getInfos(self,cursor,netId):
"""
get global informations id from local database
"""
cursor.execute('''SELECT informationId, internalId FROM informations WHERE networkId = ?''',(netId,))
infos = {}
for row in cursor:
infos[row[1]] = row[0]
return infos
def getNodes(self,cursor,netId):
"""
get global node id from local database
"""
cursor.execute('''SELECT nodeId, internalId FROM nodes WHERE networkId = ?''',(netId,))
nodes = {}
for row in cursor:
nodes[row[1]] = row[0]
return nodes
def saveNetwork(self,cursor,simId):
"""
saves relevant network info to local database
"""
cursor.execute('''INSERT INTO networks(networkId,size,simulationId) VALUES(?,?,?)''',(simId,self.size,simId))
for node in self.nodes:
self.nodes[node].saveNode(cursor,simId)
for info in self.informations:
info.saveInfo(cursor,simId)
connections = self.getConnections(simId)
cursor.executemany('''INSERT INTO connections(networkId,startNode,endNode) VALUES(?,?,?)''',connections)
infoIds = self.getInfos(cursor,simId)
nodeIds = self.getNodes(cursor,simId)
for node in self.nodes:
self.nodes[node].saveInteractions(cursor,infoIds,nodeIds,simId)
def main():
net = Reseau(10)
net.initReseau()
print('distance',net.distance(1,4))
print('diameter',net.diametre())
print(net.getConnections(1))
net.drawReseau()
if __name__ == '__main__':
main()
|
66f57bb7155b7d8a73dae4829260232eaab74000 | solareenlo/python_practice | /04_モジュールとパッケージ/defaultdict.py | 696 | 3.59375 | 4 | # Pythonにも標準ライブラリがたくさんある.
# その中のdefaultdictを試してみます.
# 文字列の中の文字の出現回数を数えてみます.
s = 'ksjdflkhasklfalkshfkahsdkjhfakjdhk'
# 方法その1
d = {}
for c in s:
if c not in d:
d[c] = 0
d[c] += 1
print(d)
# 方法その2 (少し短く書ける)
d = {}
for c in s:
d.setdefault(c, 0)
d[c] += 1
print(d)
# 方法その3 (さらに短く書ける)
from collections import defaultdict # 標準ライブライであるcollectionsの中のdefaultdictを呼び出してる
d = defaultdict(int) # dをdefaultdice(int)で, int型でdictionary型で初期化
for c in s:
d[c] += 1
print(d)
|
ed35ab48645c3c2e28cc841c05764db1866a0b0f | Davidbustamante/LenguajeNatural | /suma_enteros.py | 320 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 18:18:16 2019
@author: davidbellobustamante
"""
def sumatoria(X, num):
if(num > 0):
X = sumatoria(X, num-1)
X = X + num
return X
else:
X = 0
return X
X = 0
num = int(input("Ingresa un número entero\n"))
X = sumatoria(X, num)
print(X) |
9820f9d5715cb824445d784a0e6b4962cf365ab4 | Sigit-Wasis/Fundamental-Python | /dicoding/static_class_method.py | 720 | 3.796875 | 4 | # =========================================================
# Example @classmethod dan @staticmethod of Geeks for Geeks
# =========================================================
from datetime import date
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# metode kelas untuk membuat objek Person pada tahun kelahiran.
@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)
# metode statis untuk memeriksa apakah Seseorang sudah dewasa atau tidak.
@staticmethod
def isAdult(age):
return age > 18
person1 = Person('Sigit', 19)
person2 = Person.fromBirthYear('Sigit', 2001)
print person1.age
print person2.age
print Person.isAdult(19) |
5acca47788630bd5941b52fc325df6caa07dfd2c | akb9115/python_training | /using_modules.py | 181 | 3.765625 | 4 | import math
x = 16
my_number_sqrt = math.sqrt(x)
print("Square root of",x,"is",my_number_sqrt)
y = 6
my_number_fact = math.factorial(y)
print("Factorial of",y,"is",my_number_fact) |
a5d79288cb4b5c924994ca35eaf79dc320e72005 | jaymin1570/PythonTutorial | /chapter9/lc_with_if_else.py | 290 | 3.953125 | 4 | # list comprehension with if else
nums = [1,2,3,4,5,6,7,8,9,10]
# new_list = []
# for num in nums:
# if num%2==0:
# new_list.append(num*2)
# else:
# new_list.append(-num)
# print(new_list)
new_list = [num*2 if num%2==0 else -num for num in nums ]
print(new_list) |
0338c9c59ea6bdce50b7a6a7154878ad1ee21ce4 | nanihari/regular-expressions | /check for string and location.py | 369 | 4.3125 | 4 | #to search a literals string in a string and also find the location within the original string where the pattern occurs.
import re
pattern="fortune"
text="An aim in the life is the only fortune worth finding"
match=re.search(pattern,text)
s=match.start()
e=match.end()
print('found "%s" in "%s" from %d to %d ' % \
(match.re.pattern,match.string, s, e))
|
f0c4cef232721b8c43ace2b90a4917463b990c65 | git874997967/LeetCode_Python | /easy/leetCode231.py | 335 | 3.890625 | 4 | # 231. Power of Two
def isPowerOfTwo(n):
testNum = 1
while testNum < 2 ** 31 - 1:
if testNum - abs(n) != 0:
testNum = testNum << 1
else:
return True
return False
print(isPowerOfTwo(-64))
## approach 2
def isPowerOfTwo2(n):
return False if n == 0 else n & (n - 1) == 0 |
ca7c5bbfb75a761671dd3929e60b78221d776037 | IvayloValkov/Python_Fundamentals | /Final Exam 13 Dec 2020/task1_demo.py | 973 | 4.0625 | 4 | string = input()
data = input()
while not data == "Done":
command = data.split()[0]
if command == "Change":
char = data.split()[1]
replacement = data.split()[2]
string = string.replace(char, replacement)
print(string)
elif command == "Includes":
new_string = data.split()[1]
if new_string in string:
print("True")
else:
print("False")
elif command == "End":
new_end = data.split()[1]
if string.endswith(new_end):
print("True")
else:
print("False")
elif command == "Uppercase":
string = string.upper()
print(string)
elif command == "FindIndex":
char = data.split()[1]
print(string.find(char))
elif command == "Cut":
start = int(data.split()[1])
length = int(data.split()[2])
print(string[start:start+length])
data = input() |
e6610dacf1a02becba160f0fc6341020e8dee776 | nurgleth/data_analysis | /less 4/process 3.py | 772 | 3.65625 | 4 | import time
from multiprocessing import Pool
workers_number = 4 # количество процессов
final_fib_number = 40
def fib(n: int) -> int:
return fib(n - 1) + fib(n - 2) if n > 2 else 1
def main():
tasks = list(range(0, final_fib_number))
strt_time = time.perf_counter()
# уход в паралельные вычисления
with Pool(workers_number) as pool_of_processes:
answers = list(pool_of_processes.map(fib, tasks))
# выходим из режима многозадачности. Работает один родительский процесс
finish_time = time.perf_counter()
print("Время затрат:", finish_time - strt_time)
print(*answers)
if __name__ == '__main__':
main()
|
7e99c35bcc51054c01c37745479bb7ae9fe8936c | davidtweinberger/coding_interview | /algorithms pseudocode/dijkstra.py | 1,595 | 3.859375 | 4 | #! /usr/bin/python
####################################################
# Pseudocode for Dijkstra's Algorithm (Graph Search)
# Takes in:
# - the graph
# - the start node
# - the destination node
# Returns the shortest path
def cs141_dijkstra(graph, start, destination):
PQ = PriorityQueue()
PQ.push(0, [start])
V = {}
while not PQ.isEmpty():
cost, path = PQ.pop()
node = path[-1]
if node is not in V:
V.add(node)
if node is destination:
return path
for edge in graph.outgoingEdges(node)
PQ.push(cost + edge.cost, path + [edge.destination])
####################################################
# Pseudocode - in place decorates nodes with dist
# and prev pointers to retrace a path.
def cs16_dijkstra(graph, start):
for vertex in graph.vertices:
vertex.dist = infinity
vertex.prev = None
s.dist = 0
PQ = PriorityQueue()
PQ.add(node.dist, node) for node in graph.vertices
while not PQ.isEmpty():
current = PQ.removeMin()
for edge in graph.outgoingEdges(current)
neighbor = edge.destination
if neighbor.dist > current.dist + edge.cost:
neighbor.dist = current.dist + edge.cost
neighbor.prev = current
PQ.replaceKey(neighbor, neighbor.dist)
# RUNTIME FOR THIS ONE IS O((V+E)*LOG(V)) DEPENDING ON THE IMPLEMENTATION OF THE PQ
def cs16_bellman_ford(graph, start):
for vertex in graph.vertices:
vertex.dist = infinity
vertex.prev = null
start.dist = 0
for i in range(len(graph.vertices)-1):
for s, d in graph.edges:
if s.dist + cost(s, d) < d.dist:
d.dist = s.dist + cost(s, d)
d.prev = s
#RUNTIME IS O(V*E)
|
e73a627953f579fe33276ab81f08ed0693ee991f | CodeW1zard/DS | /Graph/Graph.py | 2,742 | 3.875 | 4 | class Graph():
'''
Undirected Graph
'''
def __init__(self, G=None):
if G:
self.nodes = G.nodes
self.adj = G.adj
else:
self.nodes = set()
self.adj = {}
def add_node(self, node):
if node not in self.nodes:
self.nodes.add(node)
self.adj[node] = {}
def add_edge(self, node1, node2, weight=1):
if not node1 in self.nodes:
self.add_node(node1)
if not node2 in self.nodes:
self.add_node(node2)
self.adj[node1][node2] = weight
self.adj[node2][node1] = weight
def add_nodes_from(self, nodes):
for node in nodes:
self.add_node(node)
def add_edges_from(self, edges):
for edge in edges:
if len(edge)==2:
self.add_edge(edge[0], edge[1])
elif len(edge)==3:
self.add_edge(edge[0], edge[1], edge[2])
else:
raise ValueError('edges shape mismatch')
def adjacency(self, node):
self.__check_node(node)
return self.adj[node]
def degree(self, node):
self.__check_node(node)
return len(self.nodes[node])
def remove_node(self, node):
self.__check_node(node)
for adj in self.adjacency(node):
self.adj[adj].pop(node, None)
self.adj.pop(node)
def remove_edge(self, node1, node2):
self.__check_node(node1)
self.__check_node(node2)
self.adj[node1].pop(node2, None)
self.adj[node2].pop(node1, None)
@property
def max_degree(self):
max_degree = 0
for node in self.nodes:
degree = self.degree(node)
if degree > max_degree:
max_degree = degree
return max_degree
@property
def average_degree(self):
V = self.number_of_nodes(self)
if V:
return self.number_of_edges(self)/V
else:
return 0
def to_string(self):
s = '%d verticies, %d edges \n '%(self.number_of_nodes, self.number_of_edges)
for node in self.nodes:
s += 'vertex {}: '.format(node)
for e, w in self.adjacency(node).items():
s += '{}, '.format(e)
s += '\n '
return s
@property
def number_of_nodes(self):
return len(self.nodes)
@property
def number_of_edges(self):
return sum([len(self.adjacency(node)) for node in self.nodes])
@property
def number_of_self_loops(self):
return len([node for node in self.nodes if node in self.adjacency(node)])
def __check_node(self, node):
assert node in self.nodes, "node not exists"
|
3851628b1598805c4fc769228995bdfdb715957e | engelspencer/semesterReview | /2problem.py | 369 | 4.03125 | 4 | story = input('Please enter a short story: ')
if('Spencer' in story and 'abhorrent' in story):
print('Please try again, that story could have been written cleaner.')
elif('Spencer' in story):
print("Great job, you've written an awesome story!")
elif('abhorrent' in story):
print('What an interesting story, but a little dark.')
else:
print("It's alright I guess.")
|
9c25f1f9b79c1cc753ed35aab5b6c66c77173ab3 | eflipe/python-exercises | /udemy-py/manejo_excepciones/03-Ejercicio-ManejoExcepciones-parte3.py | 589 | 3.734375 | 4 | resultado = None
try:
a = int(input("Primer número: "))
b = int(input("Segundo número: "))
resultado = a / b
except ZeroDivisionError as e:
print("Ocurrió un error con ZeroDivisionError", e)
print(type(e))
except TypeError as e:
print("Ocurrió un error con TypeError", e)
print(type(e))
#except ValueError as e:
# print("Ocurrió un error con ValueError", e)
# print(type(e))
except Exception as e: # clase de maypr jerarquia
print("Ocurrió un error con exception", e)
print(type(e))
print("resultado: ", resultado)
print("continuamos...")
|
8624b8e03b8d2844fa7f374206f045476df2d8c4 | victorhlcavalcante/python | /calculadora.py | 1,124 | 4.34375 | 4 | #calculadora em python
print("\n**************** Python Calculator by Victor *******************")
def add(x, y):
return x + y
def subtract(x,y):
return x - y
def divide(x,y):
return x / y
def multiplication(x,y):
return x * y
print('\nSelecione a operação matemática que deseja fazer: \n')
print('1 - Soma')
print('2 - Subtração')
print('3 - Divisão')
print('4 - Multiplicação')
escolha = input('\nDigite uma das opções acima (1/2/3/4): ')
num1 = int(input('\nDigite o primeiro número: '))
num2 = int(input('\nDigite o segundo número: '))
if escolha == '1':
print('\n')
print("O resultado de", num1, "+", num2, "é igual a: ", add(num1, num2))
print('\n')
elif escolha == '2':
print('\n')
print("O resultado de", num1, "-", num2, "é igual a: ", subtract(num1, num2))
print('\n')
elif escolha == '3':
print('\n')
print("O resultado de", num1, "/", num2, "é igual a: ", divide(num1, num2))
print('\n')
elif escolha == '4':
print('\n')
print("O resultado de", num1, "*", num2, "é igual a: ", multiplication(num1, num2))
print('\n')
else:
print('\nEscolha uma opção valida!')
|
600fb13c262df70d97c84c81199ab484e4c7ee37 | godspysonyou/everything | /pythonall/oo1.py | 572 | 3.515625 | 4 | def person(name, age, sex, job):
def walk(person):
print("person %s is walking..." % person['name'])
data = {
'name':name,
'age':age,
'sex':sex,
'job':job,
'walk':walk
}
return data
def dog(name, dog_type):
def bark(dog):
print("dog %s:wang.wang..wang..." % dog['name'])
data = {
'name':name,
'type':dog_type,
'bark':bark
}
return data
d1 = dog("haha","京吧")
p1 = person("闫帅",36,"F","运维")
p2 = person("egon",27,"F","Teacher")
d1['bark'](p1)
|
245aeea82b6d97f8b908e25e91d8f2ecd7cd1c5e | yatish27/learn-python-hackerank | /halloween/halloween.py | 172 | 3.5 | 4 | cnt = int(input())
for i in range(cnt):
k = int(input())
if(k % 2 == 0):
print(int((k/2) * (k/2)))
else:
print(int(int(k/2) * (int(k/2) + 1)))
|
2d2345b4a3faadf1da81bb9edca1d4d8f7173b83 | qiaozhu123/zhu | /day14zy.py | 1,303 | 3.6875 | 4 | import threading
import time
bread=0
class cook(threading.Thread):
username=""
def run(self) -> None:
global bread
while True:
if bread<500:
bread+=1
print(self.username,"做了一个面包","现有面包",bread)
time.sleep(3)
elif bread == 500:
print(self.username,"休息3秒")
time.sleep(3)
class buyer(threading.Thread):
username=""
money=1000
def run(self) -> None:
global bread
while True:
if bread>0:
if self.money>=2:
bread-=1
self.money-=2
print(self.username,"买了一个面包")
time.sleep(10)
else:
break
else:
print("没面包了,等两秒吧")
time.sleep(2)
c1=cook()
c2=cook()
c3=cook()
p1 = buyer()
p2 = buyer()
p3 = buyer()
p4 = buyer()
p5 = buyer()
p1.username = "顾客一"
p2.username = "顾客二"
p3.username = "顾客三"
p4.username = "顾客四"
p5.username = "顾客五"
c1.username="厨师一"
c2.username="厨师二"
c3.username="厨师三"
c1.start()
c2.start()
c3.start()
p1.start()
p2.start()
p3.start()
p4.start()
p5.start() |
a00c9548740c336e0c19136f04e5aae09f92d4ce | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/78_16.py | 1,594 | 4.4375 | 4 | hashlib.sha3_224() in Python
With the help of **hashlib.sha3_224()** method, we can convert the normal
string in byte format is converted to an encrypted form. Passwords and
important files can be converted into hash to protect them with the help of
hashlib.sha3_224() method.
> **Syntax :** hashlib.sha3_224()
>
> **Return :** Return the hash code for the string.
**Example #1 :**
In this example we can see that by using hashlib.sha3_224() method, we are
able to encrypt the byte string or passwords to protect them by using this
method.
__
__
__
__
__
__
__
# import hashlib
import hashlib
# Using hashlib.sha3_224() method
gfg = hashlib.sha3_224()
gfg.update(b'GeeksForGeeks')
print(gfg.digest())
---
__
__
**Output :**
>
> b”\xa1\x155\xec\x93\xb1\xdcf)\x1c\xea\xf0\xf5\xe6\xdf\xc5I\x94’r{2\x04\xe8\xc9\xceY\xa8″
**Example #2 :**
__
__
__
__
__
__
__
# import hashlib
import hashlib
# Using hashlib.sha3_224() method
gfg = hashlib.sha3_224()
gfg.update(b'xyz@1234_GFG')
print(gfg.digest())
---
__
__
**Output :**
> b’:\xddo\xd7\xb9Y\xc9%\xd1\x9f\x06u”g\x89*{\xbd\x18\x07\xcdIC\xbc<UQ\xed'
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
9fe8246b7f12ea8f528b5713b83e733e1fbc1d13 | Jsings/Lab4 | /dbDisplay_door.py | 303 | 3.6875 | 4 | import sqlite3
dbconnect = sqlite3.connect("my.db");
dbconnect.row_factory = sqlite3.Row;
cursor = dbconnect.cursor();
cursor.execute('SELECT * FROM sensors where type = "door"');
for row in cursor:
#if row['type'] == 'door':
print(row['sensorID'],row['type'],row['zone']);
dbconnect.close();
|
b74dabe3bb45f58f1fef378b4286f22936e96c69 | Marcus893/algos-collection | /math/my_sqrt.py | 404 | 3.65625 | 4 | def mySqrt(x):
if x == 0 or x == 1:
return x
else:
start, end = 0, x
res = 0
while start <= end:
mid = (start + end) / 2
if mid * mid == x:
return mid
elif mid * mid < x:
start += 1
res = mid
else:
end -= 1
res = mid
return res
|
ef085bbfcddf06dc58c436df4ecc8d1743d2c644 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2905/60734/270037.py | 130 | 3.5 | 4 | import re
lst = re.findall(r'\d+',input())
res = 0
base = 0
for x in lst[::-1]:
res += int(x)*(2**base)
base+=1
print(res) |
34e20c31d62fa284807c029e81affb2da90ff51e | rynoschni/python-102 | /reverse.py | 297 | 3.953125 | 4 | nums = [2,3,4,5]
fruits = ["apple", "banana", "orange"]
print(nums)
nums.reverse()
print(nums)
print(fruits)
fruits.reverse()
print(fruits)
a_string = "This is a string"
a= len(a_string) - 1
b_string = ""
while a >= 0:
b_string = b_string + a_string[a]
a -= 1
print(b_string)
|
4d16c46a13e9bb9f88da024dea71896afd2b7178 | anuragmukherjee2001/Python_codes | /OOPs programming/Python oops/Access_specifier.py | 522 | 3.8125 | 4 | # Public Private and protected variables
class Employee:
num_of_leaves = 0
_protected = 1
__private = 200
def __init__(self, name, age, salary, role):
self.name = name
self.age = age
self.salary = salary
self.role = role
def print_details(self):
return f"The name is {self.name}, salary is {self.salary}, age is {self.age}, and the role is {self.role}"
anurag = Employee("Anurag", 1000, 21, "Programmer")
print(anurag._protected)
print(anurag._Employee__private)
|
727ad416c7f6f69a60568e0d22977e94e255ceb1 | brigitteunger/katas | /test_Kth_missing_positive_number.py | 882 | 3.734375 | 4 | import unittest
from typing import List
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
i = 0
j = 0
len_arr = len(arr)
while k != 0:
i += 1
if len_arr == j:
return arr[j-1] + k
if i != arr[j]:
k -= 1
else:
j += 1
return i
class TestKthMissing_number(unittest.TestCase):
def setUp(self):
self.sol = Solution()
def test_findKthPositive_1(self):
arr = [2, 3, 4, 7, 11]
k = 5
result = self.sol.findKthPositive(arr, k)
self.assertEqual(result, 9)
def test_findKthPositive_2(self):
arr = [1, 2, 3, 4]
k = 2
result = self.sol.findKthPositive(arr, k)
self.assertEqual(result, 6)
if __name__ == "__main__":
unittest.main()
|
53fbfe6d1fed7d58c94c7a994ba24cd157474776 | Neshametha/Lab-1-Python-Exercises | /Lab1Question3.py | 150 | 3.625 | 4 | '''Yamil Galo'''
'''Ketul Polara'''
'''Stuart Simmons'''
'''Natalie Whitehead'''
n = int(input("Input any number: "))
d = dict()
for n in range(1, n+1):
d[n] = n*n
print(d)
|
b84788d26544e117f45a5a99b0c3b073d1406f7f | afshinatashian/PreBootcamp | /ali.py | 340 | 3.6875 | 4 | def ali(statments):
statments.sort()
smallest_statment=""
for i in statments[0]:
smallest_statment +=i
smallest_statment +=" "
print("\n",smallest_statment)
n=int(input())
statments = []
for i in range(n):
statment=input()
my_list = statment.split()
statments.append(my_list)
ali(statments)
|
bf9d890180b7c2e33e39c1e70ce88f5668a6c26b | xiaozuo7/algorithm_python | /offer/LeftRotateString.py | 1,081 | 3.984375 | 4 | #!/usr/local/anaconda3/bin/python3
# -*- coding: utf-8 -*-
"""
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,
请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。
思路:
先旋转 0-n
再旋转 n-len(s)
再旋转 0-len(s)
@author: xiaozuo
"""
class Solution:
def LeftRotateString(self, s, n):
"""左旋转字符串"""
# write code here
if not s or n < 0:return s
s = list(s)
self.swap(s, 0, n-1) # 0 - n
self.swap(s, n, len(s)-1) # n - len(s)
self.swap(s, 0, len(s)-1) # 0 - len(s)
return ''.join(s)
def swap(self, s, l, r):
"""旋转函数"""
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
if __name__ == '__main__':
sol = Solution()
s = 'abcXYZdef'
print(sol.LeftRotateString(s=s, n=3)) |
356b14550841579aabf70e501ff2d80a76f30d12 | Jallgit/pythonHarjutus2 | /harjutused.py | 1,357 | 3.90625 | 4 | # Harjutus 1 - Leia vahemik
# Looge funktsioon, mis võtab sisendiks ühe arvu
# Funktsioon peab kontrollima, kas antud arv kuulub vahemikku 0 kuni 100 või 101 kuni 1000
# Kui kuulub vahemikku 0 kuni 100, siis tuleb printida tekst "Arv on vahemikus 0st 100ni".
# Kui kuulub vahemikku 101 kuni 1000, siis tuleb printida tekst "Arv on vahemikus 101st 1000ni".
# Harjutus 2 - prindi negatiivsed arvud
# Ette on antud arvude list
#arvud = [5, 9, 1, -2, 6, -15, -20]
# Looge funktsioon, mis käib tsükliga kõik arvud listis läbi ning iga arvu puhul kontrollib, kas arv on negatiivne.
# Kui arv on negatiivne, siis printige see välja
# Harjutus 3 - boonus
# Looge funktsioon, mis võtab sisendiks listi, mis koosneb 4st täis arvust.
# Funktsioon peab iga listi elemendi puhul printima uuele reale nii mitu $ sümbolit kui elemendi väärtus ütleb
# Näiteks listi puhul prinditakse järgnev tulemus
#$
#$$$
#$$$$
#$$$
sisend = [1, 3, 4, 3]
def h3 (sisend):
for arv in sisend:
print('$' * arv)
h3(sisend)
#print('E' * 7)
#H1.
def number (arv):
if arv > 0 and arv < 100:
print ("Arv on vahemikus 0st 100ni")
elif arv > 101 and arv < 1000:
print ("Arv on vahemikus 101st 1000ni")
number(5)
#H2.
arvud = [5, 9, 1, -2, 6, -15, -20]
for arv in arvud:
if arv < 0:
print(arv)
#H3
|
d95a009fc0dcf1e618d3d2e2bc3aceb428f05d8d | Ali-H-Vahid/mm4w2v | /scripts/remove_stopwords.py | 2,512 | 4.25 | 4 | """
Given a text file and a list of stop-words, this script writes the content of the text file after
removing stop-words. The scripts assumes that the tokens in the text file are separated by spaces.
"""
import sys
import argparse
def remove_stopwords(input_file, stopwords, lowercase=False, remove_punctuation=False):
for line in input_file:
line_without_stopwords = []
for word in line.split():
word_comparing = word.lower() if lowercase else word
if not word_comparing in stopwords:
if remove_punctuation:
if word.decode("utf-8").isalnum():
line_without_stopwords.append(word)
else:
line_without_stopwords.append(word)
yield ' '.join(line_without_stopwords)
def read_stopwords(input_file, lowercase=False):
stopwords = set()
for line in input_file:
word = line.split()[0]
if lowercase:
stopwords.add(word.lower())
else:
stopwords.add(word)
return stopwords
def main():
parser = argparse.ArgumentParser(description="Given a text file and a list of stop-words, this script writes the "
"content of the text file after removing stop-words.")
parser.add_argument("stopword_list", help="path of the file containing the list of stop-words, one per line")
parser.add_argument("input", nargs='?', help="path of the input file, default is standard input", default=None)
parser.add_argument("output", nargs='?', help="path of the output file, default is standard output", default=None)
parser.add_argument("-l", "--lowercase", help="lowercase both words and stopwords when comparing them",
action='store_true', default=False)
parser.add_argument("-p", "--remove_punctuation", help="also remove non alphanumeric words",
action='store_true', default=False)
args = parser.parse_args()
stopword_file = open(args.stopword_list, 'r')
input_file = sys.stdin if args.input is None else open(args.input, 'r')
output_file = sys.stdout if args.output is None else open(args.output, 'w')
stopwords = read_stopwords(stopword_file, args.lowercase)
for line in remove_stopwords(input_file, stopwords, args.lowercase, args.remove_punctuation):
output_file.write(line)
output_file.write('\n')
return 0
if __name__ == '__main__':
sys.exit(main())
|
4f1bf4ee9b06526310f6f8b425cbc21a198db42a | annasw/Project-Euler | /euler20.py | 181 | 3.5 | 4 | # again, python does not have a problem handling big numbers
# (and 100! is way smaller than 2**1000)
from math import factorial
print(sum([int(i) for i in str(factorial(100))]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.