blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
4082d4cc3a18ac4915f8fb340efa7e35bd5ae96b | blackhen/Python | /luck.py | 273 | 3.8125 | 4 | '''Hello'''
def lucky_sum():
'''lucky'''
num1 = input()
num2 = input()
num3 = input()
if num1 == 13:
print 0
elif num2 == 13:
print num1
elif num3 == 13:
print num1+num2
else:
print num1+num2+num3
lucky_sum()
|
8222ca77df35cfae33a806eb24af88d63d76e941 | blackhen/Python | /Lab_Missing.py | 377 | 3.8125 | 4 | '''Lab_Missing'''
def missing(number_digit):
'''fide number missing'''
list_number = []
for i in range(number_digit):
number_input = input()
if number_input != 0:
list_number.append(number_input)
else:
break
for i in range(1, number_digit+1):
if i not in list_number:
print i
missing(input())
|
7ca5df8c654fb1dfa25abf8c539198544896ebbb | blackhen/Python | /100time.py | 565 | 3.515625 | 4 | '''time'''
def time(loop, zzz):
'''time'''
if zzz == loop:
print loop
else:
print zzz
time(loop, zzz+1)
print zzz
def time2(loop, zzz):
'''time'''
if zzz == loop:
print loop
else:
print zzz
time2(loop, zzz-1)
print zzz
def cheak():
'''check'''
loop_2 = input()
if loop_2 <= 50000 and loop_2 > 0:
time(loop_2, 1)
elif loop_2 >= -50000 and loop_2 < 0:
time2(loop_2, 1)
elif loop_2 == 0:
print 1
print 0
print 1
cheak()
|
1faaaa552dc1a6ecab0b2a6654edbf2fe9e3d0ac | blackhen/Python | /Lab_Bigram.py | 414 | 3.828125 | 4 | '''Lab_Bigram'''
def bigram(string):
'''bigram'''
dict_1 = {}
for i in range(len(string)-2):
word = string[i:i+2]#'iiiiii'
number = 0
for k in range(len(string)-1):
if word == string[k:k+2]:
number += 1
dict_1[number] = dict_1.get(number, word)
max_key = max(dict_1.keys())
print dict_1[max_key]
print max_key
bigram(raw_input())
|
5c752c7d1dc6cd6a3cf303cb36686d156578027c | blackhen/Python | /ceacar.py | 427 | 3.71875 | 4 | '''ceasar'''
def cea(num, word):
'''ceacar'''
ans = ""
big = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
small = big.lower()
for i in range(len(word)):
if word[i].isupper():
ans = ans+big[(big.find(word[i])+num)%len(big)]
elif word[i].islower():
ans = ans+small[(small.find(word[i])+num)%len(big)]
else:
ans = ans+word[i]
print ans
cea(input(), raw_input())
|
9927e65afa9914267124e4180ab9bbe4d59eb3c7 | blackhen/Python | /Lab_Olympic.py | 588 | 3.890625 | 4 | '''Lab_Olympic '''
def olympic(dic, count):
'''sort score of the country'''
for _ in range(input()):
num = raw_input().split()
num2 = num[1]+num[2]+num[3]
if num2 not in dic:
dic[num2] = dic.get(num2, [num[0]])
else:
dic[num2].append(num[0])
sor = sorted(dic, reverse=1)
for i in sor:
ans = i[0]+' '+i[1]+' '+i[2]+' '+str(int(i[0])+int(i[1])+int(i[2]))
dic[i].sort()
print dic[i]
for k in dic[i]:
print str(count)+' '+k+' '+ans
count += len(dic[i])
olympic({}, 1)
|
efafefaf8ae85276969c917ddc5bcad4e331b5e4 | blackhen/Python | /gdc.py | 508 | 3.671875 | 4 | '''GDC'''
def gdc(num1, num2):
while num1 % 6 == 0 and num2 % 6 == 0:
num1 = num1/6
num2 = num2/6
while num1 % 5 == 0 and num2 % 5 == 0:
num1 = num1/5
num2 = num2/5
while num1 % 4 == 0 and num2 % 4 == 0:
num1 = num1/4
num2 = num2/4
while num1 % 3 == 0 and num2 % 3 == 0:
num1 = num1/3
num2 = num2/3
while num1 % 2 == 0 and num2 % 2 == 0:
num1 = num1/2
num2 = num2/2
print num1*num2
gdc(input(), input())
|
926eb5e5cfdb387a52d28f11732719dfa924ffd1 | blackhen/Python | /deeplen.py | 246 | 3.546875 | 4 | '''deeplen'''
def deeplen(zzz):
'''if list[] >= 2:'''
num = 0
xxx = map(str, zzz)
for i in xxx:
if len(i) >= 2:
num = num + len(i.split())
else:
num = num + 1
print num
deeplen(input())
|
200461bfce6d1434eb71e2711cd449f7c01cb29c | CozyGwen/MY-FIZZBUZZ-IIIII | /gah.py | 760 | 3.671875 | 4 | x = 0
f = "Fizz"
b = "Buzz"
q = "Fizz Buzz"
def unless():
o = 1
o = o + 1
y = 15
y = y + 15
if o % 3 == 0:
print(end='\r', flush=True)
if o % 5 == 0:
print(end='\r', flush=True)
if o == y:
print(end='\r', flush=True)
else:
'\n'
while x <= 99:
if x % 3 == 0 and x != 0 and x % 15 != 0:
'\r, flush=True'
print(f)
if x % 5 == 0 and x != 0 and x % 15 != 0:
'\r, flush=True'
print(b)
if x % 15 == 0 and x != 0:
'\r, flush=True'
print(q)
else:
'\n'
x = x + 1
if x % 3 == 0:
continue
if x % 5 == 0:
continue
if x % 15 == 0:
continue
print(x)
|
71671911d60303d0304d672fcc7872bec5e4992d | ovanov/cosSim | /cosSim/parseClass.py | 2,795 | 3.5625 | 4 | """
This class uses static methods to operate with the other helper classes to get a corpus or parse / crawl a directory or file.
The filename(s) is sent to the processor class which takes care of parsing the files.
Lastly the similarity class is called, that vectorizes the text and calculates the similarity using numpy
@Author: ovanov
@date: 03.08.21
"""
import os
from typing import List, Dict
from .text_preprocessor import Preprocess
from .similarity import Similarity
class Parser():
@staticmethod
def parse_dir(path_to_dir: str, base_file: Dict, lang: str) -> List:
"""
This function parses the dir and returns a list of similarites. It calls the function "getSimilarity"
"""
list_of_sims = []
for file in os.listdir(path_to_dir):
if file.endswith(".txt"):
file = os.path.join(path_to_dir, file)
file_to_compare = Preprocess.preprocess(file, lang)
cossim = Similarity.get_sim(base_file, file_to_compare) * 100
list_of_sims.append(round(cossim,6))
return list_of_sims
@staticmethod
def parse_file(path_to_file: str, base_file: Dict, lang:str) -> List:
"""
This function parses the file and returns a list of similarites. It calls the function "get_sim"
"""
list_of_sims = []
file_to_compare = Preprocess.preprocess(path_to_file, lang)
cossim = Similarity.get_sim(base_file, file_to_compare) * 100
list_of_sims.append(round(cossim,6))
return list_of_sims
def get_corpus(base: str, lang: str) -> Dict:
"""
This function takes the base value (default == false) as well as the lang (default == 'de)
and determines by taking both values into account, which corpus should be used.
If base is 'False' and no language is specified, the standard basefile for german is used.
If the language is 'en', the standard english corpus is used.
If a basefile is specified, of course the language flag does not matter and the basefile is
passed to the "process_base()" function.
"""
dir = os.path.dirname(__file__) # get relative path to corpora
standard_german_corpus = os.path.join(dir, 'corpora', 'german.txt')
standard_english_corpus = os.path.join(dir, 'corpora', 'english.txt')
if lang == 'de':
if base == False:
return Preprocess.preprocess(standard_german_corpus, lang)
else:
return Preprocess.preprocess(base, lang)
elif lang == 'en':
if base == False:
return Preprocess.preprocess(standard_english_corpus, lang)
else:
return Preprocess.preprocess(base, lang)
|
3c531a1e68224261ddc3dc15474aabd4236e958c | kushaan20/Project-111 | /z-score.py | 2,171 | 3.71875 | 4 | import plotly.figure_factory as ff
import plotly.graph_objects as go
import statistics
import random
import pandas as pd
import csv
df = pd.read_csv("medium_data.csv")
data = df['reading_time'].tolist()
def random_set_of_mean(counter):
data_set = []
for i in range(0,counter):
random_index = random.randint(0,len(data)-1)
value = data[random_index]
data_set.append(value)
mean = statistics.mean(data_set)
return mean
mean_list = []
for i in range(0,100):
set_of_means = random_set_of_mean(30)
mean_list.append(set_of_means)
def show_fig(mean_list):
df = mean_list
fig = ff.create_distplot([df],['temp'], show_hist = False)
fig.show()
st_deviation = statistics.stdev(mean_list)
mean = statistics.mean(mean_list)
print("The Standard Deviation of the random numbers is:", st_deviation)
print("The Mean of the random numbers is:", mean)
first_stdev_start,first_stdev_end = mean-st_deviation, mean+st_deviation
second_stdev_start,second_stdev_end = mean-(2*st_deviation), mean+(2*st_deviation)
third_stdev_start,third_stdev_end = mean-(3*st_deviation), mean+(3*st_deviation)
#Finding the Mean of the students who gave extra time to Maths Lab
df = pd.read_csv("medium_data.csv")
data = df["reading_time"].tolist()
mean1 = statistics.mean(data)
print("The Mean of Sample is:", mean1)
fig = ff.create_distplot([mean_list],['Students Marks'], show_hist = False)
fig.add_trace(go.Scatter(x = [mean,mean], y = [0,0.17],mode = "lines", name = "Mean"))
fig.add_trace(go.Scatter(x = [mean1,mean1], y = [0,0.17],mode = "lines", name = "Mean of Students who had Fun Maths Sheets"))
fig.add_trace(go.Scatter(x = [first_stdev_end,first_stdev_end], y = [0,0.17],mode = "lines", name = "The First Standard Deviation"))
fig.add_trace(go.Scatter(x = [second_stdev_end,second_stdev_end], y = [0,0.17],mode = "lines", name = "The Second Standard Deviation"))
fig.add_trace(go.Scatter(x = [third_stdev_end,third_stdev_end], y = [0,0.17],mode = "lines", name = "The Third Standard Deviation"))
fig.show()
#If Z is greater than 3, it has a good impact
z_score1 = (mean-mean1)/st_deviation
print('Z Score of Sample 1:', z_score1) |
347a1acc1db3bae869270ff4ff223540b1600709 | shrivastava12/MachineLearning | /Part 4 - Clustering/Section 24 - K-Means Clustering/K_Means/kmeans_clusster.py | 1,521 | 3.625 | 4 | # Kmeans Clustering
# Importing the libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Importing the datasets
dataset = pd.read_csv('Mall_Customers.csv')
dataset.head()
X = dataset.iloc[:,[3,4]].values
# using the elbow method to find the optimal number of clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
Kmeans = KMeans(n_clusters = i,init = 'k-means++',max_iter = 300,n_init = 10,random_state = 0)
Kmeans.fit(X)
wcss.append(Kmeans.inertia_)
plt.plot(range(1,11),wcss)
plt.title('The Elbow Method')
plt.xlabel('Nuber of clusters')
plt.ylabel('wcss')
plt.show()
# Applyig k-means to the mall dataset
Kmeans = KMeans(n_clusters = 5,init = 'k-means++',max_iter = 300,n_init = 10,random_state = 0)
y_kmeans = Kmeans.fit_predict(X)
# Visualising the clusters
plt.scatter(X[y_kmeans == 0,0],X[y_kmeans == 0,1],s = 100,c = 'red',label = 'Carefull')
plt.scatter(X[y_kmeans == 1,0],X[y_kmeans == 1,1],s = 100,c = 'blue',label = 'Standard')
plt.scatter(X[y_kmeans == 2,0],X[y_kmeans == 2,1],s = 100,c = 'green',label = 'Target')
plt.scatter(X[y_kmeans == 3,0],X[y_kmeans == 3,1],s = 100,c = 'cyan',label = 'careless')
plt.scatter(X[y_kmeans == 4,0],X[y_kmeans == 4,1],s = 100,c = 'magenta',label = 'sensible')
plt.scatter(Kmeans.cluster_centers_[:,0],Kmeans.cluster_centers_[:,1], s = 300,c = 'yellow',label = 'centroids')
plt.title('Clusters of clients')
plt.xlabel('Annual income(k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show() |
eae729ca9e377af2c030152c7fb61400cbf49ab3 | eddir/Assembler | /Code.py | 2,871 | 3.78125 | 4 | """Транслирует мнемоники языка ассемблераHack в бинарные коды
"""
def dest(mnemonic: str):
"""Возвращает бинарный код мнемоники dest.
:param mnemonic: мнемоника dest, которую необходимо преобразовать в бинарное представление команды
:return: string
"""
instructions = {
'null': "000",
'M': "001",
'D': "010",
'MD': "011",
'A': "100",
'AM': "101",
'AD': "110",
'AMD': "111"
}
return instructions[mnemonic] if mnemonic in instructions else instructions['null']
def comp(mnemonic: str):
"""Возвращает бинарный код мнемоники comp.
:param mnemonic: мнемоника comp, которую необходимо преобразовать в бинарное представление команды
:return: string
"""
instructions_0 = {
'0': "101010",
'1': "111111",
'-1': "111010",
'D': "001100",
'A': "110000",
'!D': "110001",
'!A': "110001",
'-D': "001111",
'-A': "110011",
'D+1': "011111",
'A+1': "110111",
'D-1': "001110",
'A-1': "110010",
'D+A': "000010",
'D-A': "010011",
'A-D': "000111",
'D&A': "000000",
'D|A': "010101",
}
instructions_1 = {
'M': instructions_0['A'],
'!M': instructions_0['!A'],
'-M': instructions_0['-A'],
'M+1': instructions_0['A+1'],
'M-1': instructions_0['A-1'],
'D+M': instructions_0['D+A'],
'D-M': instructions_0['D-A'],
'M-D': instructions_0['A-D'],
'D&M': instructions_0['D&A'],
'D|M': instructions_0['D|A'],
}
# Согласно определнию a бит зависит от c битов
# Сам a бит определяет будет ли использоваться M Илм A
if mnemonic in instructions_0:
return '0' + instructions_0[mnemonic]
if mnemonic in instructions_1:
return '1' + instructions_1[mnemonic]
raise ValueError('Invalid mnemonic %s' % mnemonic)
def jump(mnemonic: str):
"""Возвращает бинарный код мнемоники jump.
:param mnemonic: мнемоника jump, которую необходимо преобразовать в бинарное представление команды
:return: string
"""
instructions = {
'null': "000",
'JGT': "001",
'JEQ': "010",
'JGE': "011",
'JLT': "100",
'JNE': "101",
'JLE': "110",
'JMP': "111"
}
return instructions[mnemonic] if mnemonic in instructions else instructions['null']
|
521f7092961eafb8ec49952366a9457e6549341f | HackerajOfficial/PythonExamples | /exercise1.py | 348 | 4.3125 | 4 | '''Given the following list of strings:
names = ['alice', 'bertrand', 'charlene']
produce the following lists: (1) a list of all upper case names; (2) a list of
capitalized (first letter upper case);'''
names = ['alice', 'bertrand', 'charlene']
upNames =[x.upper() for x in names]
print(upNames)
cNames = [x.title() for x in names]
print(cNames) |
bf4b0f1b742501d986080b3fb43afb7f68155778 | HackerajOfficial/PythonExamples | /classInheritance.py | 254 | 3.6875 | 4 | #Class Inheritance
class Person():
def __init__(self,name,age):
self.name=name
self.age=age
def out(self):
print("Name:" +self.name + " Age:" +self.age)
class child(Person):
pass
kid=child("Sumi","9")
kid.out()
|
2a85c44544a22bac0f15b800f208ce82abb701e1 | HackerajOfficial/PythonExamples | /FetchWebDetails.py | 144 | 3.53125 | 4 | import sys
import urllib2
url=raw_input("Enter Website:") #http://google.com
url.rstrip()
header=urllib2.urlopen(url).info()
print(str(header)) |
12568504b91ed1a6576637ebc8ef97f6d771c0f0 | HackerajOfficial/PythonExamples | /pop.py | 167 | 3.90625 | 4 | '''The pop method on a list returns the "rightmost"
item from a list and removes
that item from the list:'''
a = ['11','aaa','15','26',]
b = a.pop()
print(b)
print(a) |
1e0ac370459914f2a8741324768dbe26723b1f18 | alanwuuu/python_project_linear_regression | /Linear_Regression_Reggie.py | 5,855 | 4.375 | 4 | #Creator: Alan Wu
#Contact Info: alanwu379@gmail.com
#Senior studying Mathematics at CUNY Baruch
#Project: Linear Regression
# info:
#Reggie is a mad scientist who has been hired by the local fast food joint to build their newest ball pit in the play area.
#He is working on researching the bounciness of different balls so as to optimize the pit.
#He is running an experiment to bounce different sizes of bouncy balls, and then fitting lines to the data points he records.
#He has heard of linear regression, but needs your help to implement a version of linear regression in Python.
# Note:
#Linear Regression is when you have a group of points on a graph, and you find a line that approximately resembles that group of points.
#A good Linear Regression algorithm minimizes the _error_, or the distance from each point to the line.
#A line with the least error is the line that fits the data the best. We call this a line of best fit.
#-----------------------
#lets start with creating a function for finding y in a linear equation
#where m is the slope of the line and b is the y-intercept of the line
def linear_function(m, b, x):
y = m*x + b
return y
#lets test out our function to see if the output matches with our calculation bu hand (Remove the # below and both should return True)
#print(linear_function(1, 0, 7) == 7)
#print(linear_function(5, 10, 3) == 25)
#-----------------------
#so the Scientist Reggie wants to try out different m values and b values for linear_function to see which line produces the least error
#so to calculate the error between a point and a line
#We will create the function called: calculate_error(m,b,point)
#Where m is the slope, b is the y-intercept, and the point that contains a pair of x and y
#The function should return the distance between the line and the point
def calculate_error(m,b,point):
x, y = point #once we have point, we will seperate the list into two distinct variables, x and y
y_1 = linear_function(m,b,x) #using the linear function to generate y-value of the line
distance = abs(y-y_1) #using the distance to measure the difference between y and y_1
return distance
#the point (3, 3) should be 1 unit away from the line y = x - 1:
#remove the # to test out the result
#print(calculate_error(1, -1, (3, 3)))
#----------------------
#Reggie's datasets are sets of points
#where x represents the size of the bouncy ball (in cm) and y represents the distance that it bounced (in m)
#for example: (1,2) represents a 1 cm bouncy ball bounced 2 meters
datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)]
#So when we are given a set of data, we have no idea what the m and b we should use for our linear function
#We will start by finding out the total error for the dataset when we just input any m and b
#We will create a function called calculate_all_error with 3 arugements: m,b,datapoints
def calculate_all_error(m,b,datapoints):
total_error = 0 #we havent start the calculation yet, so there is no total error so far
for point in datapoints: #at each iteration, point will be the most left element/point in the datapoints list
point_error = calculate_error(m,b,point) #store the error for each point into point error
total_error += point_error #adding errors for each point/element in the datapoint/list
return total_error #Note: return should be outside of the for loop, since you want the total error after the loop iterates through the whole list
#code testing#
#every point in this dataset is 1 unit away from y = x - 1
#so the total error should be 4:
#remove # to test code. NOTE: in this testing, datapoints is reassigned a dataset
#datapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)]
#print(calculate_all_error(1, -1, datapoints))
#----------------------
#so now we have all the tools we need to find out the best m and best b for our linear regression model that will minimizes the total error of our dataset
#so lets set boundaries for our m and b (this could change depending on our data set, but for now, we will use the following boundries)
#let m be between -10 and 10 with as increment of 0.1
#let b be between -20 and 20 with as increment of 0.1
possible_ms = [m * 0.1 for m in range(-100, 101)]
possible_bs = [b * 0.1 for b in range(-200, 201)]
smallest_error = float('inf') #Used infinity because any error from the dataset will be smallet
#So the first error found will be the smallest at the moment
#We are dealing with decimals, so converted the type to float
best_m = 0
best_b = 0 #just giving them a value, which will be replaced
for m in possible_ms: #nested for loop for iterating through each m and b
for b in possible_bs:
error = calculate_all_error(m,b,datapoints) #calculating the total error for dataset with given m and b
if error < smallest_error:
best_m = round(m,2)
best_b = round(b,2)
smallest_error = error
smallest_error = round(smallest_error,2)
#print("Our linear function should have m as {} and b as {}. Which will give us a minimal error of {}.".format(best_m,best_b,smallest_error))
#There you have it, a linear regression model for Reggie
#Now, Reggie wants to predict the bounce height of a ball that is 6 cm
#lets test out our hard work!!
#remove # to see result
#print("The ball will bounce this high {}m!".format(linear_function(best_m,best_b,6)))
|
fd9c99441cba0d403b6b880db4444f95874eeb0c | micriver/leetcode-solutions | /1684.py | 2,376 | 4.3125 | 4 | """
You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed.
Return the number of consistent strings in the array words.
Example 1:
Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
Output: 2
Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.
Example 2:
Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
Output: 7
Explanation: All strings are consistent.
Example 3:
Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
Output: 4
Explanation: Strings "cc", "acd", "ac", and "d" are consistent.
Constraints:
1 <= words.length <= 104
1 <= allowed.length <= 26
1 <= words[i].length <= 10
The characters in allowed are distinct.
words[i] and allowed contain only lowercase English letters.
Count the number of strings where the allowed characters are consistent
if words[i][j] DOES NOT EQUAL ab[i] * n then do not increase the count to return
"""
allowed = "ab"
words = ["ad", "bd", "aaab", "baa", "badab"]
# Output: 2
def countConsistentStrings(allowed, words):
# count = 0
# loop through words
# for i in range(len(words)):
# for j in range(len(words[i])):
# print(words[i][j])
# for i in range(len(words)):
# for j in range(len(words[i])):
# # for x in range(len(allowed)):
# x = 0
# while x in range(len(allowed)):
# if words[i][j] == allowed[x]:
# x += 1
# if j == len(words[i]) - 1:
# count += 1
# else:
# i += 1
# return count
count = 0
allowed = set(allowed)
for word in words:
for letter in word:
if letter not in allowed:
count += 1
break
# return the number of consistent strings
return len(words) - count
# couldn't figure out a solution so decided to go with: https://leetcode.com/problems/count-the-number-of-consistent-strings/discuss/971323/Python-3-solution-100-faster-than-any-other-codes
# what is set(): https://www.geeksforgeeks.org/python-set-method/
# countConsistentStrings(allowed, words)
print(countConsistentStrings(allowed, words)) |
aab785831638f7e29f6ca68343eff9c5cdc29c0e | micriver/leetcode-solutions | /1470_Shuffle_Array.py | 983 | 4.375 | 4 | """
Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
"""
# What is happening? Using the given integer (n) as a separator creating two arrays, you must reshuffle the given array and return a new array with the paired indexes
from typing import List
# nums = [2, 5, 1, 3, 4, 7]
# n = 3
# Output: [2,3,5,4,1,7]
nums = [1, 2, 3, 4, 4, 3, 2, 1]
n = 4
# Output: [1, 4, 2, 3, 3, 2, 4, 1]
def shuffle(nums: List[int], n: int) -> List[int]:
result = []
for i in range(n):
result.append(nums[i])
result.append(nums[i + n])
return result
print(shuffle(nums, n)) |
997b9c7df5170f1a26fa421af330508897866f59 | KbDinesh87/Python-Tutorial | /hello.py | 858 | 3.90625 | 4 | print("Hello Python")
x = 23.6
if x == 1:
# indented four spaces
print("x is 1.")
else:
print("x is NOT 1.")
floatv = float(55)
print "my float value is", floatv
intv = float(55.26)
print "my integer value is", intv
round2 = round(55.2352356,2)
print "my rounded value is", round2
amount = 1000
balance = 10
print("my salary is %s but now in my account %s" % (amount, balance))
print("my salary is {} but now in my account {}".format(amount, balance))
concatString = "my salary is {} but now in my account {}".format(amount, balance)
print (concatString)
a,b,c = 6,4,"Three"
print "a is {} and b is {} and c is {}".format(a,b,c)
if isinstance(x,float) :
print "X is float"
if isinstance(x,float) and x ==23.6 :
print "X is float and value is 23.6"
if isinstance(x,float) and x ==23.6 :
print "X is float and value is %f " % x |
191756085fa94750a2432ca24db949aa08b0c59e | LongNguyen0024/Ciphers | /rowTransposition.py | 2,022 | 3.953125 | 4 | def encrypt(key, plaintext):
key = key.replace(" ", "")
plaintext = plaintext.replace(" ", "")
# For extra letters to add to table
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# Initialize empty dictionary
table = {}
rows = (len(plaintext)//len(key))+1
cols = len(key)
# Populate empty dictionary with keys ordered by number of columns
for i in range(1, cols+1):
table[i]=[]
incrementBy = 0
for i in range(1, cols+1):
if(incrementBy>=len(plaintext)):
incrementBy=0
incrementBy+=i-1
for j in range(rows):
if(incrementBy>=len(plaintext)):
table[i].append(alphabet.pop())
else:
table[i].append(plaintext[incrementBy])
incrementBy+=cols
finalResult = ''
for i in key:
for j in range(rows):
finalResult+=table[int(i)][j]
return finalResult
print(encrypt("3 4 2 1 5 6 7", "attack postponed until two am"))
def decrypt(ciphertext, key):
key = key.replace(" ", "")
ciphertext = ciphertext.replace(" ", "")
# Initialize empty dictionary
table = {}
rows = len(ciphertext)//len(key)
cols = len(key)
k = 0
# Populate empty dictionary with columns as the key
for i in key:
table[i]=[]
for j in range(len(ciphertext)):
if(j>=rows):
break
else:
table[i].append(ciphertext[k])
k+=1
new_table = {}
# Rearrange columns in order
for i in range(1, len(key)+1):
new_table[str(i)]=table[str(i)]
plaintext = ''
# Piece the plaintext together by the new table
for i in range(0, rows):
for j in range(1, cols+1):
plaintext+=new_table[str(j)][i]
return plaintext
print(decrypt("ttnaaptmtsuoaodwcoizknlypetx", "3421567")) |
fd8a18476da2f6ad0ca93ca4ec1ab7144a8d122c | TrendingTechnology/deduplipy | /deduplipy/blocking/blocking_rules.py | 2,710 | 3.53125 | 4 | import re
def whole_field(x):
x_trimmed = x.strip()
if len(x_trimmed):
return x_trimmed
else:
return None
def first_word(x):
x_trimmed = x.strip()
if len(x_trimmed):
return x_trimmed.split()[0]
else:
return None
def first_two_words(x):
x_trimmed = x.strip()
if len(x_trimmed):
return " ".join(x_trimmed.split()[:2])
else:
return None
def first_three_letters(x):
x_trimmed = x.strip()
if len(x_trimmed):
return x_trimmed[:3]
else:
return None
def first_four_letters(x):
x_trimmed = x.strip()
if len(x_trimmed):
return x_trimmed[:4]
else:
return None
def first_five_letters(x):
x_trimmed = x.strip()
if len(x_trimmed):
return x_trimmed[:5]
else:
return None
def first_three_letters_no_space(x):
x = x.replace(' ', '')
if len(x):
return x[:3]
else:
return None
def first_four_letters_no_space(x):
x = x.replace(' ', '')
if len(x):
return x[:4]
else:
return None
def first_five_letters_no_space(x):
x = x.replace(' ', '')
if len(x):
return x[:5]
else:
return None
def sorted_integers(x):
digits = re.compile(r'\d+').findall
numeric_list = digits(x)
numeric_list = sorted([int(n) for n in numeric_list])
string_list = [str(n) for n in numeric_list]
if len(string_list):
return " ".join(string_list)
else:
return None
def first_integer(x):
digits = re.compile(r'\d+').findall
numeric_list = digits(x)
if len(numeric_list):
return numeric_list[0]
else:
return None
def last_integer(x):
digits = re.compile(r'\d+').findall
numeric_list = digits(x)
if len(numeric_list):
return numeric_list[-1]
else:
return None
def largest_integer(x):
digits = re.compile(r'\d+').findall
numeric_list = digits(x)
numeric_list = sorted([int(n) for n in numeric_list])
if len(numeric_list):
return str(numeric_list[-1])
else:
return None
def three_letter_abbreviation(x):
letters = re.compile((r'[a-zA-Z]+')).findall
word_list = letters(x)
if len(word_list) >= 3:
abbreviation = "".join(w[0] for w in word_list[:3])
return abbreviation
else:
return None
all_rules = [whole_field, first_word, first_two_words, first_three_letters, first_four_letters, first_five_letters,
first_three_letters_no_space, first_four_letters_no_space, first_five_letters_no_space, sorted_integers,
first_integer, last_integer, largest_integer, three_letter_abbreviation]
|
f0a446dd94d7f02abf085078591ed370d94c53b1 | DawidMiroyan/RL_Lab | /lab_session6/1.bandits/bandit.py | 4,621 | 3.6875 | 4 | """
Module containing the k-armed bandit problem
Complete the code wherever TODO is written.
Do not forget the documentation for every class and method!
We expect all classes to follow the Bandit abstract object formalism.
"""
# -*- coding: utf-8 -*-
import numpy as np
class Bandit(object):
"""
Abstract concept of a Bandit, i.e. Slot Machine, the Agent can pull.
A Bandit is a distribution over reals.
The pull() method samples from the distribution to give out a reward.
"""
def __init__(self, **kwargs):
"""
Empty for our simple one-armed bandits, without hyperparameters.
Parameters
----------
**kwargs: dictionary
Ignored additional inputs.
"""
pass
def reset(self):
"""
Reinitializes the distribution.
"""
pass
def pull(self) -> float:
"""
Returns a sample from the distribution.
"""
raise NotImplementedError("Calling method pull() in Abstract class Bandit")
class Mixture_Bandit_NonStat(Bandit):
""" A Mixture_Bandit_NonStat is a 2-component Gaussian Mixture
reward distribution (sum of two Gaussians with weights w and 1-w in [O,1]).
The two means are selected according to N(0,1) as before.
The two weights of the gaussian mixture are selected uniformly.
The Gaussian mixture is non-stationary: the means AND WEIGHTS move every
time-step by an increment epsilon~N(m=0,std=0.01)"""
# TODO: Implement this class inheriting the Bandit above.
def __init__(self, **kwargs):
"""
Parameters
----------
**kwargs: dictionary
Ignored additional inputs.
"""
self.mean1 = 0.0 # Mean 1
self.mean2 = 0.0 # Mean 2
self.weight1 = 1.0 # Weight 1
self.weight2 = 0.0 # Weight 2
self.reset()
def reset(self):
"""
Reinitializes the distribution.
"""
self.mean1 = np.random.normal(0, 1)
self.mean2 = np.random.normal(0, 1)
self.weight1 = np.random.uniform()
self.weight2 = 1.0 - self.weight1
def pull(self) -> float:
"""
Returns a sample from the distribution.
"""
return np.random.normal(self.mean1, 1) * self.weight1 + \
np.random.normal(self.mean2, 1) * self.weight2
def update_mean(self):
self.mean1 += np.random.normal(0, 0.01)
self.mean2 += np.random.normal(0, 0.01)
self.weight1 += np.random.normal(0, 0.01)
self.weight2 = 1.0 - self.weight1
class KBandit_NonStat:
""" Set of K Mixture_Bandit_NonStat Bandits.
The Bandits are non stationary, i.e. every pull changes all the
distributions.
This k-armed Bandit has:
* an __init__ method to initialize k
* a reset() method to reset all Bandits
* a pull(lever) method to pull one of the Bandits; + non stationarity
"""
def __init__(self, k, **config):
"""
Instantiates the k-armed bandit, with a number of arms, and initializes
the set of bandits to new gaussian bandits in a bandits list.
The reset() method is supposedly called from outside.
Parameters
----------
k: positive int
Number of arms of the problem.
"""
self.k = k
self.best_action = 0
self.bandits = [Mixture_Bandit_NonStat() for _ in range(self.k)]
def reset(self):
""" Resets each of the k bandits """
for bandit in self.bandits:
bandit.reset()
self.best_action = np.argmax([bandit.mean1 * bandit.weight1 + bandit.mean2 * bandit.weight2 for bandit in self.bandits]) # printing purposes
def pull(self, action: int) -> float:
"""
Pulls the lever from Bandit #action. Returns the reward.
Parameters
----------
action: positive int < k
Lever to pull.
Returns
-------
reward : float
Reward for pulling this lever.
"""
r = self.bandits[action].pull()
self.update_means()
return r
def update_means(self):
""" Updates the mean for each of the Bandits"""
for bandit in self.bandits:
bandit.update_mean()
self.best_action = np.argmax([bandit.mean1 * bandit.weight1 + bandit.mean2 * bandit.weight2 for bandit in self.bandits])
def is_best_action(self, action: int) -> int:
"""
Checks if pulling from Bandit using #action is the best action.
"""
return int(action == self.best_action)
|
93c0bc6d46032081c7cd621ace401fa4935c66aa | BennettB123/Python-Maze-Generator | /mazeGenerator.py | 9,009 | 3.640625 | 4 | import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
import random
import statistics
import time
# Character encodings for various assets
WALL = u'\N{FULL BLOCK}'
PLAYER = u'\N{WHITE SMILING FACE}'
# Function to setup the screen
def setup():
strscr = curses.initscr()
strscr.keypad(True)
curses.noecho()
curses.cbreak()
curses.curs_set(0)
# Setting up colors
curses.start_color()
curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK) # Wall color
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) # Player color
return strscr
# Function to de-setup the screen so the console can return to normal
def end_window(strscr):
curses.nocbreak()
curses.echo()
strscr.keypad(False)
curses.endwin()
class Maze:
# Sets up the maze data-structure and generates a random maze
def __init__(self, rows, cols, screen):
self.rows = rows
self.cols = cols
# Need to check if rows and cols are good sizes for the maze
if (rows - 2) % 2 == 0:
self.rows -= 1
if (cols - 2) % 2 == 0:
self.cols -= 1
# Placing the starting location about halfway down the first column
self.start_col = 1
self.start_row = 1
#self.start_row = int(self.rows/2)
#if self.start_row % 2 == 0: # Make sure its not in a place a wall is going to be
#self.start_row -= 1
self.player_col = self.start_col
self.player_row = self.start_row
self.goal_col = self.cols - 2
self.goal_row = self.rows - 2
self.screen = screen
# Creating maze and filling it will spaces
self.maze = [[' ' for i in range(self.cols)] for j in range(self.rows)]
# Helper function for generate_maze
# Finds a random neighbor of (cur_row, cur_col) that is un-visited
def random_neighbor(self, cur_row, cur_col, visited):
# TODO: FIX THIS! IT DOES NOT LOOK CLEAN AT ALL
while True:
dir = random.randint(1, 4)
if dir == 1: # Try to go up
if cur_row - 2 >= 1:
if (cur_row - 2, cur_col) not in visited:
return cur_row - 2, cur_col
elif dir == 2: # Try to go right
if cur_col + 2 < self.cols:
if (cur_row, cur_col + 2) not in visited:
return cur_row, cur_col + 2
elif dir == 3: # Try to go down
if cur_row + 2 < self.rows:
if (cur_row + 2, cur_col) not in visited:
return cur_row + 2, cur_col
elif dir == 4: # Try to go left
if cur_col - 2 >= 1:
if (cur_row, cur_col - 2) not in visited:
return cur_row, cur_col - 2
# Helper function for generate_maze
# Checks if there are any unvisited neighbors of (cur_row, cur_col)
# Returns True if there is, False otherwise
def neighbor_exists(self, cur_row, cur_col, visited):
# TODO: FIX THIS! IT DOES NOT LOOK CLEAN AT ALL
# Try to go up
if cur_row - 2 >= 1:
if (cur_row - 2, cur_col) not in visited:
return True
# Try to go right
if cur_col + 2 < self.cols:
if (cur_row, cur_col + 2) not in visited:
return True
# Try to go down
if cur_row + 2 < self.rows:
if (cur_row + 2, cur_col) not in visited:
return True
# Try to go left
if cur_col - 2 >= 1:
if (cur_row, cur_col - 2) not in visited:
return True
return False
# Uses a depth-first search method to generate the maze
# See https://en.wikipedia.org/wiki/Maze_generation_algorithm
# This is a simple algorithm to implement, but does not produce complex mazes.
# TODO: IMPLEMENT MORE MAZE GENERATION ALGORITHMS TO GET MORE COMPLEX MAZES
def generate_maze(self):
# Adding in every wall to begin the maze generation algorithm
for i in range(len(self.maze)):
for j in range(len(self.maze[0])):
if i%2 == 0 or j%2 == 0:
self.maze[i][j] = WALL
# Borders of maze
if i == 0 or i == self.rows-1 or j == 0 or j == self.cols-1:
self.maze[i][j] = WALL
visited = {(self.start_row, self.start_col)} # set representing cells that have been visited so we don't loop
stack = [(self.start_row, self.start_col)] # stack of visited cells to make back-tracking easier
cur_row = self.start_row
cur_col = self.start_col
while len(stack) != 0:
# If an un-visited neighbor exists, pick one, remove the wall to it, and continue
if self.neighbor_exists(cur_row, cur_col, visited):
new_row, new_col = self.random_neighbor(cur_row, cur_col, visited)
self.maze[statistics.mean((new_row, cur_row))][statistics.mean((new_col, cur_col))] = ' ' # Removing wall
cur_row = new_row
cur_col = new_col
visited.add((cur_row, cur_col))
stack.append((cur_row, cur_col))
# If there are no un-visited neighbors, pop the stack until one is found
else:
while not self.neighbor_exists(cur_row, cur_col, visited):
if len(stack) != 0:
cur = stack.pop()
cur_row = cur[0]
cur_col = cur[1]
else:
break
# Removing all walls from starting block, to make maze appear more difficult
# Upper wall
if self.start_row - 2 >= 1:
self.maze[self.start_row - 1][self.start_col] = ' '
# Right wall
if self.start_col + 2 < self.cols:
self.maze[self.start_row][self.start_col + 1] = ' '
# Lower wall
if self.start_row + 2 < self.rows:
self.maze[self.start_row + 1][self.start_col] = ' '
# Left wall
if self.start_col - 2 >= 1:
self.maze[self.start_row][self.start_col - 1] = ' '
def print_maze(self):
# Displaying the maze to the screen
row = col = 0
for s in self.maze:
col = 0
for ss in s:
# in a try/catch because addch() wont let you draw in bottom right cell without raising an exception
try:
self.screen.addch(row, col, ss)
except curses.error as e:
pass
col += 1
row += 1
# Adding in the start and goal cells
self.screen.addch(self.start_row, self.start_col, 'S')
self.screen.addch(self.goal_row, self.goal_col, 'G')
# Adding in the player
self.screen.addch(self.player_row, self.player_col, PLAYER)
self.screen.refresh()
# Functions to move player
# Each one moves the player then checks if the player is in a wall
# If in a wall, move back
def move_player_left(self):
self.player_col -= 1
if self.maze[self.player_row][self.player_col] == WALL:
self.player_col += 1
def move_player_right(self):
self.player_col += 1
if self.maze[self.player_row][self.player_col] == WALL:
self.player_col -= 1
def move_player_up(self):
self.player_row -= 1
if self.maze[self.player_row][self.player_col] == WALL:
self.player_row += 1
def move_player_down(self):
self.player_row += 1
if self.maze[self.player_row][self.player_col] == WALL:
self.player_row -= 1
def win(self):
if (self.player_col, self.player_row) == (self.goal_col, self.goal_row):
return True
else:
return False
def main(stdscr):
strscr = setup()
m = Maze(int(curses.LINES), int(curses.COLS), strscr)
m.generate_maze()
while True:
strscr.erase()
m.print_maze()
event = strscr.getch()
key = key if event == -1 else event
if key in [KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, 'p']:
if key == KEY_LEFT:
m.move_player_left()
elif key == KEY_RIGHT:
m.move_player_right()
elif key == KEY_UP:
m.move_player_up()
elif key == KEY_DOWN:
m.move_player_down()
if m.win():
# strscr.erase()
# m.print_maze()
# time.sleep(0.5)
# strscr.erase()
# strscr.addstr(0, 0, "CONGRATULATIONS!\nPress any button to continue", curses.A_BLINK)
# time.sleep(1)
# strscr.getch()
exit()
end_window(strscr)
curses.wrapper(main)
|
bb007eb48ba89f03af3227b33d30108ba7b98373 | mdsiegel/unit4 | /rectangle.py | 177 | 3.640625 | 4 | #Matthew Siegel
#10/16/17
#rectanlge.py - finding rectangles
def rectangle(len,wid):
print('There area is',len*wid)
print('The perimenter is',len*2 + wid*2)
rectangle(3,4) |
74903ca44e197f6a2d98dde1104c59171c8248aa | mdsiegel/unit4 | /bubbles.py | 781 | 3.5625 | 4 | #Matthew Siegel
#10/25/17
#bubbles.py - making bubbles!!!!!
from ggame import *
from random import randint
red = Color(0xFF0000,1)
green = Color(0x00FF00,1)
blue = Color(0x0000FF,1)
black = Color(0x000000,1)
blackOutline = LineStyle(1,black) #pixels,color
def bubble(event):
randnum = randint(1,4)
if randnum == 1:
circle = CircleAsset(randint(20,100), blackOutline, red)
elif randnum == 2:
circle = CircleAsset(randint(20,100), blackOutline, blue)
elif randnum == 3:
circle = CircleAsset(randint(20,100), blackOutline, green)
elif randnum == 4:
circle = CircleAsset(randint(20,100), blackOutline, black)
Sprite(circle,(randint(20,1000),randint(20,600)))
App().listenMouseEvent('click', bubble)
App().run()
|
430ffa1c594df821a2d0b8bec36d884a5469ccbb | agalotaibi/Rock-Paper-Scissor-Game | /RPS.py | 3,445 | 3.515625 | 4 | import random
mv = ['rock', 'paper', 'scissors']
s_moves = ['r', 'p', 's']
def beats(one, two):
return ((one == 'scissors' and two == 'paper') or
(one == 'rock' and two == 'scissors') or
(one == 'paper' and two == 'rock'))
def c_hum_inp(s_moves):
if s_moves == 'p':
return 'paper'
elif s_moves == 'r':
return 'rock'
else:
return 'scissors'
class Player:
def __init__(self):
self.score = 0
def move(self):
return 'rock'
def learn(self, my_move, thir_move):
self.my_move = my_move
self.other_move = thir_move
class RandomPlyer(Player):
def move(self):
return random.choice(mv)
class HumanPlyer(Player):
def move(self):
hum_inp = input(
'chose (p) for paper'
'or (r) for rock'
'or (s) for scissors'
'or (q) for quit')
if hum_inp in s_moves:
return c_hum_inp(hum_inp)
elif hum_inp == 'q':
return 'q'
else:
print ('un correct letter')
return self.move()
class ReflectPlayer(Player):
def __init__(self):
super().__init__()
self.other_move = random.choice(mv)
def move(self):
return self.other_move
class CyclePlayer(Player):
def __init__(self):
super().__init__()
self.other_move = random.choice(mv)
def move(self):
if self.other_move == 'rock':
return 'paper'
elif self.other_move == 'paper':
return 'scissors'
else:
return 'rock'
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def play_round(self):
move1 = self.p1.move()
move2 = self.p2.move()
if (move1 == 'q') or (move2 == 'q'):
return 'exit'
print(f'Player1: {move1} Player2: {move2}')
if beats(move1, move2):
self.p1.score = self.p1.score+1
print('player1 won')
elif beats(move2, move1):
self.p2.score = self.p2.score+1
print ('player2 won')
else:
print('Equle')
print (f'Score: (Player1: {self.p1.score},' +
f'Player2: {self.p2.score})')
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
def player_game(self):
print ('Game start')
for round in range(3):
print(f'Round {round+1}:')
round_v = self.play_round()
if round_v == 'exit':
print('the end')
break
print ('Final Score')
print(f'Player1 :{self.p1.score}, + Player 2: {self.p2.score}')
if self.p1.score > self.p2.score:
print('Player1 won')
elif self.p1.score < self.p2.score:
print('Player2 won')
else:
print('They are Equles')
print('Game Over')
def select_comp_mode():
comp_mode = input('chose: random, reflect, cycle as game mode')
if comp_mode == 'random':
return Game(HumanPlyer(), RandomPlyer())
elif comp_mode == 'reflect':
return Game(HumanPlyer(), ReflectPlayer())
elif comp_mode == 'cycle':
return Game(HumanPlyer(), CyclePlayer())
else:
print('indvalid')
return select_comp_mode
if __name__ == '__main__':
game = select_comp_mode()
game.player_game()
|
e7f39b31e71e9ece4f4de8e3d391b27814fb4e26 | Si-ja/Unit-Testing-Python | /Checker/ToolsUpdate.py | 1,799 | 3.828125 | 4 | class Functions:
@staticmethod
def binary(a, b) -> list:
"""
Check whether values in respect to their positions
match per two arrays.
Parameters
----------
a : list or an array (numpy)
First list/array holding variable.
b : list or an array (numpy)
Second list/array holding variable.
Returns
-------
list
A list of True or False boolean values is returned
on whether values in both of the arreas match or
not per two different arrays.
"""
import numpy as np
if(isinstance(a, np.ndarray) or isinstance(b, np.ndarray)):
if a.ndim > 1 or b.ndim > 1:
raise ValueError("This method only processes 1 dimensional arrays")
else:
if any(isinstance(i, list) for i in a) or any(isinstance(i, list) for i in b):
raise ValueError("This method only processes 1 dimensional lists")
answer = []
if a == [] and b == []:
return [True]
try:
if a.size == 0 and b.size == 0:
return [True]
except:
pass
zipper = zip(a, b)
for data in tuple(zipper):
if data[0] == data[1]:
answer.append(True)
else:
answer.append(False)
if len(answer) != (len(a) + len(b)) / 2:
max_len = 0
if len(a) > max_len:
max_len = len(a)
if len(b) > max_len:
max_len = len(b)
for idx in range(max_len + 1):
if idx <= len(answer):
continue
else:
answer.append(False)
return answer |
e3669d643eda2fdbc7e6e38b26aa5300e288d40b | firelab/goes-fire | /mythreads.py | 1,547 | 3.78125 | 4 | import queue
import threading
class ThreadManager(object) :
"""Creates and manages threads and queues for bidirectional
communications with the worker."""
def __init__(self, worker, collector=None, num_threads=4, killsig=None) :
self.worker = worker
self.collector = collector
self.killsig = killsig
self.num_threads = num_threads
self.threads = []
self.work = queue.Queue()
self.product = queue.Queue()
self.collected_products = []
def start(self) :
for i in range(self.num_threads):
t = threading.Thread(target=self.worker)
t.start()
self.threads.append(t)
@property
def empty(self) :
"""true if both work and product queues are empty."""
return self.work.empty() and self.product.empty()
def reset_products(self) :
self.collected_products = []
def collect(self) :
"""collects results from the product queue until
both queues are empty."""
while not self.empty :
if self.collector is not None :
self.collector(self.product.get())
else :
self.collected_products.append(self.product.get())
def kill(self, block=True) :
"""sends the "killsig" object to all the threads"""
for i in range(self.num_threads) :
self.work.put(self.killsig)
if block :
for t in self.threads :
t.join()
|
26b569a159c98d69b9bdadbb2c8e498bacc41edf | sumibhatta/iwbootcamp-2 | /Data-Types/26.py | 348 | 4.3125 | 4 | #Write a Python program to insert a given string at the beginning
#of all items in a list.
#Sample list : [1,2,3,4], string : emp
#Expected output : ['emp1', 'emp2', 'emp3', 'emp4']
def addString(lis, str):
newList = []
for item in lis:
newList.append(str+"{}".format(item))
return newList
print(addString([1,2,3,4], 'emp'))
|
d740522b95d886aeef403569b0a299760a45b78b | sumibhatta/iwbootcamp-2 | /Data-Types/30.py | 515 | 4 | 4 | #Write a Python script to check whether a given key already exists
#in a dictionary.
def checkDuplicate(dict, key):
if key in dict:
print("Oh! the there is duplicate key")
else:
print("No duplicate :) ")
# def checkDuplicate(dict, key):
# li =[]
# li = dict.keys()
# li.append(key)
# if(len(li) != len(set(li))):
# print("Oh! the there is duplicate key")
# else:
# print("No duplicate :) ")
checkDuplicate({1: 10, 2: 20, 3: 30, 4: 40, 7: 50, 6: 60},5) |
47b4e0234552f6811a1f6d30d7a3c5424bc80362 | sumibhatta/iwbootcamp-2 | /Functions/13.py | 118 | 3.90625 | 4 | #Write a Python program to sort a list of tuples using Lambda.
hi = lambda tup: sorted(tup)
print(hi((2,3,1,4,5)))
|
3151f1dd3c21b3603d8c616b643cdfb3f25d79a3 | sumibhatta/iwbootcamp-2 | /Data-Types/12.py | 218 | 4.21875 | 4 | #Write a Python script that takes input from the user and
# displays that input back in upper and lower cases.
string = "Hello Friends"
upper = string.upper()
lower = string.lower()
print(string)
print(upper)
print(lower) |
f97d8fa2d1303999ae58af1ead1d8553fcc08dcf | sumibhatta/iwbootcamp-2 | /Data-Types/31.py | 172 | 4.4375 | 4 | #Write a Python program to iterate over dictionaries using for loops.
myd = {1: 10, 2: 20, 3: 30, 4: 40, 7: 50, 6: 60}
for key, value in myd.items():
print(key,value) |
595b55d7e6466d3bf99558d30947c34747658ff5 | sumibhatta/iwbootcamp-2 | /Data-Types/9.py | 223 | 3.96875 | 4 | #Write a Python program yo change the given string
# to a new string where the first and last chars have been exchanged.
def firsLas(string):
return string[-1:]+string[1:-1]+string[0:1]
pr = firsLas("Sumi")
print(pr) |
4714d27ba2e270f63757e3c36e9b5f1fa17e3b8a | sumibhatta/iwbootcamp-2 | /Data-Types/42.py | 119 | 3.828125 | 4 | #Write a Python program to convert a list to a tuple.
lis = [10, 20, 30, 40, 50, 60, 70]
tup = tuple(lis)
print(tup) |
4968e2a134c4a2620a9437e2589ef8899e362737 | sumibhatta/iwbootcamp-2 | /Data-Types/29.py | 324 | 3.765625 | 4 | #Write a Python script to concatenate following dictionaries
#to create a new one.
#Sample Dictionary :
#dic1={1:10, 2:20}
#dic2={3:30, 4:40}
#dic3={5:50,6:60}
#Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic1.update(dic2)
dic1.update(dic3)
print(dic1) |
9e8af25f5f6d921219dbf3b71368729e89ae1e6f | Jamaliela/A-Bug-s-Life | /A04 - Jamalie - Alfaroz.py | 7,637 | 4.21875 | 4 | ######################################################################
# Author: Ela Jamali, Emely Alfaro Zavala
# Username: jamalie, Alfaroe
#
# Purpose: Learn the impact a bug can have in the real world.
# Explore life path numbers.
# Practice creating your own fruitful functions.
# Learn to use modulus to capture remainders.
#
######################################################################
# Acknowledgements: Aaron Christon (TA hours) and Eureka (the moment Ela had when she figured out the first function)
######################################################################
import turtle
def day_of_birth():
"""
this function first checks if the input is a master number (11,22,33) and returns it. if not a master number, it adds the integers of the day of birth and returns them.
:param: None
:return: sum of integers of the day of birth or master number (11, 22 or 33)
"""
day = (int(input("What is the day of your birthday?"))) # asks the user to input their day of birth
if day % 11 == 0 and day <= 33: # checks if input is a master number by dividing it by 11 and checking if it is less than 33
return day # if the conditions are met, the master number is return (11,22,33)
else:
n = day % 10 # defining variable n and using modulus to get the second value to sum
m = day // 10 # defining variable m and using floor division to get to get the first value to sum
return m + n # adding the two variables
def month_of_birth():
"""
this function first checks if the input is a master number (11,22,33) and returns it. if not a master number, it adds the integers of the month of birth and returns them.
:param: None
:return: sum of integers of the month of birth or master number (11, 22 or 33)
"""
month = (int(input("What is the month of your birthday?"))) # asks the user to input their month of birth
if month % 11 == 0 and month <= 33: # checks if input is a master number by dividing it by 11 and checking if it is less than 33
return month # if the conditions are met, the master number is return (11,22,33)
else:
n = month % 10 # defining variable n and using modulus to get the second value to sum
m = month // 10 # defining variable m and using floor division to get to get the first value
return m + n # adding the two variables
def year_of_birth():
"""
this function gets the year if the sum of the digits of the year is a master number (11,22,33) it keeps it and returns it. if not a master number, it adds the integers of the year of birth and returns them.
:param: None
:return: sum of integers of the year of birth or master number (11, 22 or 33)
"""
year = (int(input("What is the year of your birthday?"))) # asks the user to input their year of birth
if year % 11 == 0 and year <= 33: # checks if input is a master number by dividing it by 11 and checking if it is less than 33
return year # if the conditions are met, the master number is return (11,22,33)
else:
f1 = year // 1000 # using floor division by 1000 to get first integer for year
f2 = year % 1000 # reducing the year to hundreds so we can get second digit
s1 = f2 // 100 # using floor division by 100 to get second integer for year
s2 = f2 % 100 # reducing the year to tents so we can get third digit
t1 = s2 // 10 # using floor division by 10 to get third integer for year
t2 = s2 % 10 # reducing the year to tents so we can get remainder (fourth digit)
suma = f1 + s1 + t1 + t2 # adding all the variables previously found so we get the total for year
if suma >= 10 and suma % 11 != 0: # we calculate here if our value is equal or less than ten and aif the remainder of dividing it by 11 is not zero
return suma % 10 + suma // 10 # if the conditions are met, we take the reminder of suma/10 and add it to the floor division of that number and 10
else:
return suma # if the final value does not meet the conditions, it is returned as it is.
def life_path_number():
"""
function that first calls all the functions and then adds all their values found to get the final life path number
:param: None
:return: sum of the three values found
"""
day1 = day_of_birth() # assigning the day_of_birth function to a variable to get its value
month1 = month_of_birth() # assigning the month_of_birth function to a variable to get its value
year1 = year_of_birth() # assigning the year_of_birth function to a variable to get its value
number = day1 + month1 + year1 # adding the three values together to get the life path number
if number >= 10 and number % 11 != 0: # if the number found is equal or more than 10 and its reminder is other than zero then
return number % 10 + number // 10 # the reminder of dividing the number by then and the one of doing floor division by ten is added.
else:
return number # if those conditions are not met, the total amount (number) is returned.
def final(tortuga):
"""
This function will display the life path number using turtle
:param: tortuga = a turtle object
:return: None
"""
numero = life_path_number() # we adding a value to the variable numero which will call the life_path_number
tortuga.write("Congratulations. Your life path number is " + str(numero), move=False, align="center", font=("Arial", 23, "italic"))
# the turtle will write the statement based on the life path number in a specific font and position
def main():
"""
main function where other functions are executed to find the life path number
:param: None
:return: None
"""
tortuga = turtle.Turtle() # creating a turtle object
tortuga.shape("blank") # hiding the turtle object in the middle of the screen.
tortuga.pencolor("black") # changing the pen color to black so the turtle writes in that color
wn = turtle.Screen() # setting up the background for our turtle object
wn.bgpic("backg.gif") # inserting an image in the background
wn.bgcolor("purple") # setting the color of the background
final(tortuga) # calling our final function that runs the other functions to compute life path number
wn.exitonclick() # indicates that the screen will exit when we click it
main()
|
63f14fdae94a896ef64d6553f889ca4a47e15321 | dagss/oomatrix | /oomatrix/symbolic.py | 13,377 | 3.734375 | 4 | """
Symbolic tree...
Hashing/equality: Leaf nodes compares by object identity, the rest compares
by contents.
By using the factory functions (add, multiply, conjugate_transpose,
inverse, etc.), one ensures that the tree is in a canonical shape,
meaning it has a certain number of "obvious" expression simplifications which
only requires looking at the symbolic structure. Some code expects
trees to be in this canonical state. (TODO: Move all such
simplification from constructors to factories)
- No nested multiplies or adds; A * B * C, not (A * B) * C
- No nested transposes or inverses; A.h.h and A.i.i is simplified
- Never A.h.i, but instead A.i.h
- (A * B).h -> B.h * A.h, (A + B).h -> A.h + B.h. This makes the
"no nested multiplies or adds rules" stronger
"""
from functools import total_ordering
from .cost_value import FLOP, INVOCATION
from .utils import argsort, invert_permutation
from . import kind, cost_value, metadata
from hashlib import sha256
import numpy as np
def _flatten_children(cls, children):
""" Used by add and multiply to avoid nesting arithmetic nodes
of the same type.
"""
flattened_children = []
for child in children:
if type(child) is cls:
flattened_children.extend(child.children)
else:
flattened_children.append(child)
return flattened_children
# Factory functions
def add(children):
children = _flatten_children(AddNode, children)
return AddNode(children)
def sorted_add(children):
children = _flatten_children(AddNode, children)
children.sort()
if len(children) == 0:
raise ValueError('children list is empty')
if len(children) == 1:
return children[0]
else:
return AddNode(children)
def multiply(children):
children = _flatten_children(MultiplyNode, children)
if len(children) == 0:
raise ValueError('children list is empty')
if len(children) == 1:
return children[0]
else:
return MultiplyNode(children)
def conjugate_transpose(expr):
if isinstance(expr, ConjugateTransposeNode):
# a.h.h -> a
return expr.child
elif (isinstance(expr, InverseNode) and
isinstance(expr.child, ConjugateTransposeNode)):
# a.h.i.h -> a.i
return InverseNode(expr.child.child)
elif isinstance(expr, MultiplyNode):
transposed_children = [conjugate_transpose(x)
for x in expr.children]
return multiply(transposed_children[::-1])
elif isinstance(expr, AddNode):
transposed_children = [conjugate_transpose(x)
for x in expr.children]
return add(transposed_children)
else:
return ConjugateTransposeNode(expr)
def inverse(expr):
if isinstance(expr, InverseNode):
# a.i.i -> a.i
return expr.child
elif isinstance(expr, ConjugateTransposeNode):
if isinstance(expr.child, InverseNode):
# a.i.h.i -> a.h
return ConjugateTransposeNode(expr.child.child)
else:
# a.h.i -> a.i.h
return ConjugateTransposeNode(InverseNode(expr.child))
else:
return InverseNode(expr)
class TODO:
name = 'TODO'
class PatternMismatchError(ValueError):
pass
@total_ordering
class ExpressionNode(object):
name = None
kind = None
_hash = None
task_dependencies = frozenset()
def get_type(self):
return TODO
def can_distribute(self):
"""
Can one use the distributive law on this node? Overriden
by AddNode and ConjugateTransposeNode
"""
return False
def distribute_right(self, other):
raise NotImplementedError()
def distribute_left(self, other):
raise NotImplementedError()
def dump(self):
from .formatter import BasicExpressionFormatter
return BasicExpressionFormatter({}).format(self)
def as_tuple(self):
"""Returns the tuple-serialization of the tree
"""
return ((self.symbol,) +
tuple(child.as_tuple() for child in self.children))
def __hash__(self):
if self._hash is None:
self._hash = hash(self.as_tuple())
return self._hash
def __eq__(self, other):
if type(self) is not type(other):
return False
return self.as_tuple() == other.as_tuple()
def __lt__(self, other):
return self.as_tuple() < other.as_tuple()
def __ne__(self, other):
return not self == other
def __repr__(self):
return '\n'.join(self._repr(indent=''))
def _attr_repr(self):
return ''
def _repr(self, indent):
lines = [indent + '<%s: %s' % (type(self).__name__, self._attr_repr())]
for child in self.children:
lines.extend(child._repr(indent + ' '))
lines[-1] += '>'
return lines
class ArithmeticNode(ExpressionNode):
def __init__(self, children):
self.children = children
# Following is correct both for multiplication and addition...
self.nrows= self.children[0].nrows
self.ncols = self.children[-1].ncols
self.dtype = self.children[0].dtype # TODO combine better
self.universe = self.children[0].universe
if all(hasattr(child, 'leaf_count') for child in children):
self.leaf_count = sum(child.leaf_count for child in children)
class AddNode(ArithmeticNode):
symbol = '+'
def accept_visitor(self, visitor, *args, **kw):
return visitor.visit_add(*args, **kw)
def can_distribute(self):
return True
def distribute_right(self, other):
return add([multiply([term, other])
for term in self.children])
def distribute_left(self, other):
return add([multiply([other, term])
for term in self.children])
class MultiplyNode(ArithmeticNode):
symbol = '*'
def accept_visitor(self, visitor, *args, **kw):
return visitor.visit_multiply(*args, **kw)
class SingleChildNode(ExpressionNode):
pass
class ConjugateTransposeNode(SingleChildNode):
"""
Note that
``ConjugateTransposeNode(ConjugateTransposeNode(x)) is x``,
so that one does NOT always have
``type(ConjugateTransposeNode(x)) is ConjugateTransposeNode``.
"""
symbol = 'h'
def __init__(self, child):
self.child = child
self.children = [child]
self.ncols, self.nrows = child.nrows, child.ncols
self.universe = child.universe
self.dtype = child.dtype
self.kind = child.kind
def accept_visitor(self, visitor, *args, **kw):
return visitor.visit_conjugate_transpose(*args, **kw)
def can_distribute(self):
# Since (A + B).h = A.h + B.h:
return self.child.can_distribute()
def distribute_right(self, other):
if not isinstance(self.child, AddNode):
raise AssertionError()
terms = self.child.children
return add(
[multiply([term.conjugate_transpose(), other])
for term in terms])
def distribute_left(self, other):
if not isinstance(self.child, AddNode):
raise AssertionError()
terms = self.child.children
return add(
[multiply([other, term.conjugate_transpose()])
for term in terms])
def conjugate_transpose(self):
return self.child
def compute(self):
return ConjugateTransposeNode(LeafNode(None, self.child.compute()))
class InverseNode(SingleChildNode):
symbol = 'i'
def __init__(self, child):
self.child = child
self.children = [child]
self.nrows, self.ncols = child.nrows, child.ncols
self.universe = child.universe
self.dtype = child.dtype
#self.cost = child.cost
def accept_visitor(self, visitor, *args, **kw):
return visitor.visit_inverse(*args, **kw)
class BracketNode(ExpressionNode):
symbol = 'b'
def __init__(self, child, allowed_kinds=None):
self.child = child
self.children = [child]
self.allowed_kinds = allowed_kinds
self.nrows, self.ncols = child.nrows, child.ncols
self.universe = child.universe
self.dtype = child.dtype
#self.cost = child.cost
def accept_visitor(self, visitor, *args, **kw):
return visitor.visit_bracket(*args, **kw)
def call_func(self, func, pattern):
raise NotImplementedError()
class BlockedNode(ExpressionNode):
def __init__(self, blocks, nrows, ncols):
# blocks should be a list of (node, selector, selector)
nrows = 0
ncols = 0
for node, row_selector, col_selector in blocks:
pass # just assert shape
first_node = blocks[0][0]
self.blocks = blocks
self.nrows = nrows
self.ncols = ncols
self.universe = first_node.universe
self.dtype = first_node.dtype
self.cost = None
class BaseComputable(ExpressionNode):
# TODO: REMOVE
children = ()
class Promise(BaseComputable):
def __init__(self, task):
metadata = task.metadata
self.metadata = task.metadata
self.nrows = metadata.nrows
self.ncols = metadata.ncols
self.kind = metadata.kind
self.universe = self.kind.universe
self.dtype = metadata.dtype
self.task = task
def accept_visitor(self, visitor, *args, **kw):
return visitor.visit_leaf(*args, **kw)
def __hash__(self):
return id(self)
class DecompositionNode(ExpressionNode):
"""
Represents a promise to perform a matrix decomposition.
"""
def __init__(self, child, decomposition):
self.symbol = 'decomposition:%s' % decomposition.name
self.child = child
self.children = [child]
self.decomposition = decomposition
self.nrows, self.ncols = child.nrows, child.ncols
self.universe = child.universe
self.dtype = child.dtype
self.kind = child.kind
def accept_visitor(self, visitor, *args, **kw):
return visitor.visit_decomposition(*args, **kw)
for x, val in [
(BaseComputable, 1000),
(DecompositionNode, 1000),
(BracketNode, 1000),
(InverseNode, 40),
(ConjugateTransposeNode, 40),
(MultiplyNode, 30),
(AddNode, 20)]:
x.precedence = val
#
# An uncompiled tree contains LeafNode
#
class LeafNode(BaseComputable):
cost = 0 * FLOP
def __init__(self, name, matrix_impl):
from .kind import MatrixImpl
if not isinstance(matrix_impl,MatrixImpl):
raise TypeError('not isinstance(matrix_impl, MatrixImpl)')
self.name = name
self.matrix_impl = matrix_impl
self.kind = type(matrix_impl)
self.universe = self.kind.universe
self.nrows = matrix_impl.nrows
self.ncols = matrix_impl.ncols
self.dtype = matrix_impl.dtype
def compute(self):
return self.matrix_impl
def get_type(self):
return type(self.matrix_impl)
def accept_visitor(self, visitor, *args, **kw):
return visitor.visit_leaf(*args, **kw)
def as_tuple(self):
return (self,)
def __hash__(self):
return id(self)
def __lt__(self, other):
return id(self) < id(other)
def __eq__(self, other):
return self is other
def __ne__(self, other):
return self is not other
def _attr_repr(self):
return self.name
#
# A compiled tree contains MatrixMetadataLeaf and TaskLeaf
#
class MatrixMetadataLeaf(ExpressionNode):
# Expression node for matrix metadata in a tree
kind = universe = ncols = nrows = dtype = None # TODO remove these from symbolic tree
precedence = 1000 # TODO
leaf_count = 1
leaf_index = -1
def __init__(self, metadata):
self.metadata = metadata
def set_leaf_index(self, leaf_index):
self.leaf_index = leaf_index
self.argument_index_set = frozenset([leaf_index])
def accept_visitor(self, visitor, *args, **kw):
return visitor.visit_metadata_leaf(*args, **kw)
def as_tuple(self):
# Important: should sort by kind first
return self.metadata.as_tuple() + (self.leaf_index,)
def _repr(self, indent):
return [indent + '<arg:%s, %r>' % (self.leaf_index, self.metadata)]
class TaskLeaf(ExpressionNode):
kind = universe = ncols = nrows = dtype = None # TODO remove these from symbolic tree
children = ()
precedence = 1000
def __init__(self, task, argument_index_set):
self.task = task
self.metadata = task.metadata
self.dependencies = task.dependencies
self.argument_index_set = argument_index_set
def as_tuple(self):
# ##TaskLeaf essentially compares by the its output and its dependencies,
# ##not how the computation is performed.
return self.metadata.as_tuple() + ('task', self.argument_index_set)
def accept_visitor(self, visitor, *args, **kw):
return visitor.visit_task_leaf(*args, **kw)
def _repr(self, indent):
return [indent + '<TaskLeaf %r %r>' % (
self.metadata,
sorted(list(self.argument_index_set)))]
def as_task(self):
return self.task
|
1a4cd38c80329b1f322a2097ee28174011e2fa14 | dagss/oomatrix | /oomatrix/heap.py | 552 | 4.03125 | 4 | import heapq
class Heap(object):
"""
Wraps heapq to provide a heap. The sorting is done by provided cost
and then insertion order; the values are never compared.
"""
def __init__(self):
self.heap = []
self.order = 0
def push(self, cost, value):
x = (cost, self.order, value)
self.order += 1
heapq.heappush(self.heap, x)
def pop(self):
cost, order, value = heapq.heappop(self.heap)
return cost, value
def __len__(self):
return len(self.heap)
|
e8e33e330ba94a130439ce22cae53b450e3d3a42 | vid2408/Day5 | /python_clouser2.py | 241 | 4.09375 | 4 | def nth_power(exponent):
def pow_of(base):
return pow(base,exponent)
return pow_of
square = nth_power(2)
print(square(2))
print(square(3))
print(square(4))
print(square(5))
cube = nth_power(3)
print(cube(2))
print(cube(3)) |
a4b2234ea23fb4c2dab818eb9e26d55c3c5d8324 | amyfranz/python_practice | /mostRepetition.py | 344 | 4.0625 | 4 | string = "this is a some words and it is my test"
def highest_value(string):
string = string.replace(" ", "").lower()
dict = {}
for item in range(len(string)):
dict[string[item]] = dict.get(string[item], 0) + 1
x = sorted(dict, key=(lambda key: dict[key]), reverse=True)
return x[0]
print(highest_value(string))
|
b797fe31c35ba7e71bd3f4001dc7dc980851804a | owenbrown/python_stack | /linked_list.py | 2,432 | 3.78125 | 4 | import unittest
class Node(object):
def __init__(self, val):
self.value = val
self.next = None
class SList(object):
def __init__(self):
self.head = None
def add_to_front(self, val):
new_node = Node(val)
current_head = self.head
new_node.next = current_head
self.head = new_node
return self
def print_values(self):
runner = self.head
while runner is None:
print(runner.value)
def add_to_back(self, val):
new_node = Node(val)
runner = self.head
while runner.next is not None:
runner = runner.next
runner.next = new_node
def remove_from_front(self):
self.head = self.head.next
def __eq__(self, other: 'SList'):
self_runner = self.head
other_runner = other.head
while True:
if self_runner is None and other_runner is None:
return True
if self_runner is None or other_runner is None:
return False
if self_runner.value != other_runner.value:
return False
self_runner = self_runner.next
other_runner = other_runner.next
def __iter__(self):
self.__start_node = self.head
self.__next_node = self.head
return self
def __next__(self):
if self.__next_node is None:
raise StopIteration
return_node = self.__next_node
self.__next_node = self.__next_node.next
return return_node
def remove_value(self, value):
runner = self.head
while runner:
if runner is None:
raise IndexError("value not in Slist")
if runner.value == value:
self.head = self.head.next
return
runner = runner.next
class TestSlist(unittest.TestCase):
def setUp(self):
self.a = SList()
self.b = SList()
for c in list("abcdefg"):
self.a.add_to_front(c)
self.b.add_to_front(c)
def test_equality(self):
self.assertTrue(self.a == self.b)
def test_not_equal(self):
self.a.remove_from_front()
self.assertFalse(self.a == self.b)
def test_iteration(self):
collect = list()
for n in self.a:
collect.append(n.value)
self.assertEqual(list("gfedcba"), collect) |
f51585ec6e8cd68dabd29429ef8d0ba2eb340d50 | avidalh/udacity-fsnd-p2 | /tournament.py | 7,737 | 3.5625 | 4 | #!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
# used to generate pairs
from itertools import combinations
# used to random assigning 'bye'
from random import choice
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
def deleteMatches(tid=0):
"""Remove all the match records from the database."""
db = connect()
c = db.cursor()
c.execute("SELECT * FROM delete_matches_by_tid(%s)", (tid,))
db.commit()
db.close()
def deletePlayers(tid=0):
"""Remove all the player records from the database."""
db = connect()
c = db.cursor()
c.execute("DELETE FROM players")
db.commit()
c.execute("DELETE FROM tournaments WHERE tid = %s", (tid,))
db.commit()
db.close()
def countPlayers():
"""Returns the number of players currently registered."""
db = connect()
c = db.cursor()
c.execute("SELECT COUNT(pid) FROM players")
count = c.fetchone()
db.close()
return count[0];
def registerPlayer(name, tid=0, tname="tournament_0"):
"""Adds a player to the tournament database.
The database assigns a unique serial id number for the player. (This
should be handled by your SQL database schema, not in your Python code.)
Args:
name: the player's full name (need not be unique).
tid: tournament tid
tname: tournament name
Extra: the function has 'tid' and 'tname' as new parameters with default
values allowing be used as anterior version and provide support for
more than one tournaments at same time.
"""
db = connect()
c = db.cursor()
c.execute("SELECT * FROM register_player(%s,%s,%s)", (name, tid, tname,))
db.commit()
db.close()
def playerStandings(tid=0, giveme_bye=0):
"""Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place, or a player
tid for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches):
id: the player's unique id (assigned by the database)
name: the player's full name (as registered)
wins: the number of matches the player has won
matches: the number of matches the player has played
Extras:
- the function has 'tid' as a new parameter with a default value = 0.
this option allows the function be used as anterior version and provide
support for more than one tournaments at same time.
- the function has 'giveme_bye' as a new parameter to support odd players
"""
db = connect()
c = db.cursor()
if not giveme_bye:
c.execute("SELECT pid, name, wins, matches \
FROM standings WHERE tid=%s", (tid,))
else:
c.execute("SELECT pid, name, bye \
FROM standings where tid =%s",(tid,))
standings = c.fetchall()
db.close()
return standings;
def reportMatch(winner, loser, draw=0):
"""Records the outcome of a single match between two players.
Args:
winner: the id number of the player who won
loser: the id number of the player who lost
draw: in tid matches draw=1 and the winner field in database is updated
to value 0.
Extra: the function has 'draw' as a new parameter with a default value = 0.
this option allows the function be used as anterior version and provide
support for tid matches.
"""
query = '''
SELECT * FROM report_match(%s,%s,%s);
'''
db = connect()
c = db.cursor()
if not draw:
c.execute(query, (winner, loser, winner,))
else:
c.execute(query, (winner, loser, 0,))
db.commit()
db.close()
def not_in(pair_to_test, pairs, debug_level):
"""
checks if pair_to _test is into pairs array.
Returns:
True if not in
False if in
"""
if debug_level>1:
print ' pair_to_test: ', pair_to_test
if debug_level>1:
print ' pairs: ', pairs
for player in pair_to_test:
for pair in pairs:
if player in pair:
return False
return True
def swissPairings(debug_level=0, tid=0):
"""Returns a list of pairs of players for the next round of a match.
Assuming that there are an even number of players registered, each player
appears exactly once in the pairings. Each player is paired with another
player with an equal or nearly-equal win record, that is, a player adjacent
to him or her in the standings.
Returns:
A list of tuples, each of which contains (id1, name1, id2, name2)
id1: the first player's unique id
name1: the first player's name
id2: the second player's unique id
name2: the second player's name
Extra:
- the function has 'tid' as a new parameter with a default value = 0.
this option allows the function be used as anterior version and provide
support for more than one tournaments at same time.
- just for debugging parameter 'debug_level' has been added with a
default value of 0 for compatibility with udacity tests file.
"""
# in first instance read the list of players sorted by rank descending, in
# order to acomplish with the swiss system (pairing players with the same
# or almost same rank) Uses 'giveme_bye' to know who has a bye or not to
# support even or odd number of players
players = playerStandings(tid, giveme_bye=1)
# check the number of players for even or odd
# if odd: take a random player (with no bye) and assign him/her a "bye" flag
# and a "free win" and then pop it from the list of candidates to pair
if len(players) % 2:
if debug_level>1:
print ' odd players'
while True:
player = choice(players)
if player[2] == 0:
if debug_level>1:
print ' found player with bye = 0, poping it from the list'
players.pop(players.index(player))
db = connect()
c = db.cursor()
c.execute("UPDATE players SET bye = 1 \
WHERE pid = %s", (player[0],))
db.commit()
db.close()
break
else:
if debug_level>1:
print ' even players'
# generates all the possible combinations (pairs)
groups = combinations(players,2)
# this piece of code is the core of the pairing system, it takes the
# combinations and check if any player in the combination have been
# used in other precedents pair.
# will be inserted into the pairs list and matches table.
pairs = []
for group in groups:
pair_to_test = (group[0][0], group[0][1], group[1][0], group[1][1])
if debug_level>1:
print ' pair_to_test: ', pair_to_test
print ' pairs: ', pairs
if (not_in(pair_to_test, pairs, debug_level)):
if debug_level>1:
print ' pair_to_test NOT IN pairs, inserting into ----------> DB!'
pairs.append((group[0][0], group[0][1], group[1][0], group[1][1]))
db = connect()
c = db.cursor()
c.execute("INSERT INTO matches(pid1,pid2) \
VALUES(%s,%s)", (group[0][0], group[1][0],))
db.commit()
db.close()
else:
if debug_level>1:
print ' pair_to_test has one player IN pairs, no insertion'
return pairs
|
efa5491f8219eecca5a44b00984aed3174e6a0d4 | shootk/git_vc | /python_practice/challenge7.py | 983 | 3.671875 | 4 | #charenge7
"""
#1
movie = ["ウォーキング・デッド","アントラージュ",
"ザ・ソプラノズ","ヴァンパイア・ダイアリーズ"]
for show in movie:
print(show)
#2
for i in range(25,51):
print(i)
#3
movie = ["ウォーキング・デッド","アントラージュ",
"ザ・ソプラノズ","ヴァンパイア・ダイアリーズ"]
for i,show in enumerate(movie):
print(i,":",show)
#4
right = (7,10,11,21)
while True:
num = input("Input num/if you quit input q:")
if(num == "q"):
break;
else:
try:
if(int(num) in right):
print("Right!")
else:
print("Fuck off")
except ValueError:
print("Input nunber")
print("See you")
#5
n1 = [8,19,148,4]
n2 = [9,1,33,83]
result = []
for i in n1:
for j in n2:
result.append(str(i)+"*"+str(j)+":"+str(i*j))
print(result)
"""
|
4dbb730d7301e9915567b9ffaa2fa118c1237ed4 | svveet123/testxx | /demo1.py | 1,698 | 3.6875 | 4 | '''
为了代码复用
# def 固定
# sum:方法名
# g,h 在调用方法时要传的数据
# return 返回值
def sum(g,h,i):
he = g+h+i
return he
a = 1
b = 2
c = 3
s1 = sum(a,b,c)
s2 = sum(b,c,c)
print(s1)
print(s2)
'''
'''
def test1():
print("用户")
print(123)
print(2.333)
print([1,2,3])
print((23,43,21))
test1()
'''
'''
参数的数据类型可以是任何形式的
def test2(l):
print(l)
test2(1)
test2(2.333)
test2("姓名")
test2([1,2.3,4])
test2({"username":"hu","key":"value"})
'''
'''
def test3(l):
return(l)
a = test3(1)
b = test3("用户")
c = test3([1,2.3,4,5])
d = test3({"用户":"金泰亨","age":"25"})
print(a)
print(b)
print(c)
print(d)
'''
#from dbtools import chaxun
# # 模拟管理员登录,输入账号和密码,查询输入的账号和密码,如果数据库中有该账号密码,则能查询到结果;
# # 如果账号密码不正确,则查询结果为空
# username = input("请输入账号:")
# password = input("请输入密码:")
# sql = 'select * from t_admin where username="{}" and password="{}"'.format(username,password)
# res = chaxun(sql)
# if len(res) != 0:
# print("管理员登录成功")
# else:
# print("管理员登录失败")
#---------------------------------注册-------------------------------------
from dbtools import commit
username = input("请输入账号:")
password = input("请输入密码:")
sql = 'INSERT into t_admin values(NULL, "{}", "{}", NULL, NULL, "管理员2", "好好学习啊", "headimg.jpg", NULL, "女", 0, NULL, NULL, NULL)'.format(username,password)
res = commit(sql)
if res ==True:
print("账号注册成功")
else:
print("账号注册失败")
|
1b8baef05584e1d74546ef90b45d618d9cda1e77 | serignefalloufall/Python_Repository | /exercice21.py | 636 | 3.734375 | 4 | print("-------------------- ********** --------------------")
print("User1 veillez saisir un nombre que user2 doit essaier de le trouver :")
nbr_user1 = int(input())
print("User2 devine le nombre que user1 a saisie:")
nbr_user2 = int(input())
score = 100
while(nbr_user1 != nbr_user2):
if(nbr_user1 > nbr_user2):
print("----- ohhhh plus grand diminue un peut rek -----")
score = score - 1
else:
print("----- ohhhhh plus petit augmente un peut -----")
score = score - 1
print("Saisir un autre nombre:")
nbr_user2 = int(input())
print("Bravoooo votre score est : ",score) |
9e49f16585cbf976e9bacb79fa5a52fe38d5c1bb | serignefalloufall/Python_Repository | /exercice15_b.py | 187 | 3.8125 | 4 | print("Saisir un nombre")
nombre = int(input())
som = 0
for i in range(1, nombre + 1): # de 1 à nombre +1 exclu --> de 1 à nombre inclus
som += i
moy = som / nombre
print(moy) |
424aa2c13cd4092ec799168ceea99cc5d2ff9be9 | dilanmorar/monsters_inc_oop_basics | /Spooky_Workshops_class.py | 772 | 3.609375 | 4 | from Student_Monsters_class import *
class Spooky_Workshops():
def __init__(self, subject, staff, location, student_list):
self.scary_subject = subject
self.staff = staff
self.list_students = student_list
self.location = location
def add_students(self, student):
student_name = self
student_name.list_students.append(student)
# workshop1 = Spooky_Workshops('scary', 'none', 'front', [])
# print(workshop1.list_students)
# workshop1.add_students('Dave')
# print(workshop1.list_students)
# lists student monsters
# Scare_Workshop = Spooky_Workshops('paranoia', 'ghost', 'front', '2 years', students)
# print('Should print list of students on the course "paranoia": ')
# print(Scare_Workshop.list_student_monsters) |
0ffe93f65e3470129a4d22f9fb32552f02e0b83e | ANJI1196/Assignment3 | /USE CASE4.py | 439 | 4 | 4 | #MENU APP:
while True:
print("MY TO DO APP")
print("==============")
print("1. Add Task")
print("2. View All Tasks")
print("0. To Exit")
option=int(input("Choose Option:"))
if option==1:
n1=input("Enter Task Name:")
print("Task added")
elif option==2:
n1=input("Enter Task Name:")
print("Task added")
elif option==0:
print("Bye")
break
|
6d03285682d26e44fa55d69d14a947fa9261dd6a | srininara/pykidz | /sessions/session-8-modular_programming/code/return.py | 635 | 3.75 | 4 | def age_commenter(age):
if age < 0:
print("Mr Unborn")
return
if age <= 12:
print("Whizzo Kiddo")
return
if age < 20:
print("Super Teen")
return
if age < 30:
print("Vibrant Youth")
return
print("Oldie Moldie")
def simple_interest(principal, rate, term):
if !type(principal) == int or !type(principal) == float:
print("Error: Principal has to be a number")
return
if !type(rate) == int or !type(rate) == float:
print("Error: Rate has to be a number")
return
# Do
age_commenter(28)
age_commenter(32)
age_commenter(6) |
e36282ae463014cb228241b4b6ff7dbfb48e3a65 | srininara/pykidz | /sessions/session-7-loops/code/while_path_change.py | 271 | 3.921875 | 4 | fruits = ['apple', 'apricot', 'banana', 'chickoo', 'fig', 'guava', 'mango', 'orange']
while fruits:
fruit = fruits.pop()
if fruit == 'chickoo':
print(fruit, "! Yuck... I will skip this one")
continue
print("I love", fruit)
print("I am done!") |
091eb10c7f430a46e145614f3da84eafe77ec083 | dachen123/algorithm_training_homework | /week5/LRUCache.py | 1,950 | 3.875 | 4 | #146.LRU缓存机制
class doubleLinkNode:
def __init__(self,key,val):
self.val = val
self.key = key
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.cache = {}
self.head = doubleLinkNode(-1,-1)
self.tail = doubleLinkNode(-1,-1)
self.head.next = self.tail
self.tail.prev = self.head
self.capacity = capacity
self.counter = 0
def del_node(self,node):
node.prev.next = node.next
node.next.prev = node.prev
return node
def add_node_to_head(self,node):
node.next = self.head.next
self.head.next.prev = node
node.prev = self.head
self.head.next = node
def move_node_to_head(self,node):
node = self.del_node(node)
self.add_node_to_head(node)
def get(self, key: int) -> int:
if key in self.cache:
node = self.cache[key]
self.move_node_to_head(node)
return node.val
return -1
def put(self, key: int, value: int) -> None:
if key not in self.cache:
node = doubleLinkNode(key,value)
self.cache[key] = node
self.add_node_to_head(node)
if self.counter >= self.capacity:
node = self.del_node(self.tail.prev)
self.cache.pop(node.key)
else:
self.counter += 1
else:
node = self.cache[key]
node.val = value
self.move_node_to_head(node)
lRUCache = LRUCache(2)
lRUCache.put(1, 1)
lRUCache.put(2, 2)
print(lRUCache.get(1))
lRUCache.put(3, 3)
print(lRUCache.get(2))
lRUCache.put(4, 4)
print(lRUCache.get(1))
print(lRUCache.get(3))
print(lRUCache.get(4))
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value) |
72004f108fca8cb388ab8e9c12b99b1e6bd79d46 | dachen123/algorithm_training_homework | /week3/minPathSum.py | 1,466 | 3.78125 | 4 | #最小路径和
#空间复杂度为n^2
class Solution1:
def minPathSum(self, grid) -> int:
m = len(grid)
n = len(grid[0])
dp = [[0]*(n) for i in range(m)] #dp[i][j]表示从(0,0)到(i,j)的最小路径
dp[0][0] = grid[0][0]
for i in range(1,m):
dp[i][0] = dp[i-1][0] + grid[i][0]
for j in range(1,n):
dp[0][j] = dp[0][j-1] + grid[0][j]
for i in range(1,m):
for j in range(1,n):
dp[i][j] = min(dp[i][j-1],dp[i-1][j]) + grid[i][j]
return dp[m-1][n-1]
#空间复杂度优化
class Solution2:
def minPathSum(self, grid) -> int:
m = len(grid)
n = len(grid[0])
dp = [0] * n
dp[0] = grid[0][0]
for j in range(1,n):
dp[j] = dp[j-1] + grid[0][j]
for i in range(1,m):
for j in range(n):
if j==0:
dp[j] += grid[i][0]
else:
dp[j] = min(dp[j],dp[j-1]) + grid[i][j]
return dp[n-1]
import unittest
class testSolution(unittest.TestCase):
def test_solution1(self):
s = Solution1()
self.assertEqual(s.minPathSum([[1,3,1],[1,5,1],[4,2,1]]),7)
def test_solution2(self):
s = Solution2()
self.assertEqual(s.minPathSum([[1,3,1],[1,5,1],[4,2,1]]),7)
if __name__ == '__main__':
unittest.main()
|
e98c4539c86315543c57669adee72077ad0e0381 | dachen123/algorithm_training_homework | /week5/reverseStr.py | 1,232 | 3.703125 | 4 | #541.反转字符串II
#我的解法:直接模拟,比较考验下标指针的移动
class Solution1:
def reverseStr(self, s: str, k: int) -> str:
if k <= 1:return s
i = 0
s = list(s)
while i+2*k-1 < len(s):
for j in range(k//2):
s[i+j],s[i+k-1-j] = s[i+k-1-j],s[i+j]
i += 2*k
if i + k - 1 < len(s): #剩余字符大于等于k小于2k的情况
for j in range(k//2):
s[i+j],s[i+k-1-j] = s[i+k-1-j],s[i+j]
else: #剩余字符小于k的情况
j = len(s)-1
while i < j:
s[i],s[j] = s[j],s[i]
i += 1 #不要忘记指针移动
j -= 1
return ''.join(s)
#官方解法:比较简洁牛逼
class Solution:
def reverseStr(self, s: str, k: int) -> str:
if k <= 1:return s
s = list(s)
for i in range(0,len(s),2*k):
s[i:i+k] = reversed(s[i:i+k])
return ''.join(s)
import unittest
class testSolution(unittest.TestCase):
def test_solution1(self):
s = Solution1()
self.assertEqual(s.reverseStr("abcdefg",2),"bacdfeg")
if __name__ == '__main__':
unittest.main() |
0edaf402a1fe2275d181fae2dc040f6ad669c3a3 | dachen123/algorithm_training_homework | /week4/minMutation.py | 996 | 3.65625 | 4 | #题目:最小基因变化
#双向bfs解法,参考单词接龙题目即可
class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
bank = set(bank)
if end not in bank:
return -1
front = {start}
back = {end}
step = 0
while front:
next_front = set()
for seq in front:
for i in range(len(seq)):
for new_c in ['A','C','G','T']:
if seq[i] != new_c:
new_seq = seq[:i] + new_c + seq[i+1:]
if new_seq in back:
return step + 1
if new_seq in bank:
next_front.add(new_seq)
bank.remove(new_seq)
step += 1
front = next_front
if len(front) > len(back):
front,back = back,front
return -1
|
96df21ca9673790184335bdd4b0ee9a353e76aef | dachen123/algorithm_training_homework | /week3/coinChange.py | 1,282 | 3.703125 | 4 | #题目:322.零钱兑换
#傻递归,超时
class Solution:
def coinSelect(self,coins,path,amount,res):
if amount==0:
res['num'] = min(res['num'],len(path))
for c in coins:
if amount - c >=0:
self.coinSelect(coins,path+[c],amount-c,res)
def coinChange(self, coins: List[int], amount: int) -> int:
res = {'num':float('inf')}
self.coinSelect(coins,[],amount,res)
return -1 if res['num']==float('inf') else res['num']
#常规动态规划
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [float('inf')] * (amount+1)
dp[0] = 0
for i in range(1,amount+1):
for coin in coins:
if coin <= i:
dp[i] = min(dp[i],dp[i-coin]+1)
return dp[amount] if dp[amount]!=float('inf') else -1
#tricky动态规划
#巧妙的地方:1.i从coin开始遍历,保证i-coin >=0
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [float('inf')] * (amount+1)
dp[0] = 0
for coin in coins:
for i in range(coin,amount+1):
dp[i] = min(dp[i],dp[i-coin]+1)
return dp[amount] if dp[amount]!=float('inf') else -1
|
aa5cdbd2c62421ab8a68d3112e4703ff70504bff | KenFin/sarcasm | /sarcasm.py | 1,715 | 4.25 | 4 | while True:
mainSentence = input("Enter your sentence here: ").lower() # making everything lowercase
letters = ""
isCapital = 0 # Re-initializing variables to reset the sarcastic creator
for letter in mainSentence:
if letter == " ": # If there's a space in the sentence, add it back into the final sentence
letters += " "
elif isCapital == 0: # If it's not a space run it through the magic sentence converter
compare = """1234567890-=[]\;',./`""" # List of all the special characters in a special order
compare2 = """!@#$%^&*()_+{}|:"<>?~""" # List of all the shifted special characters in the same order
count = 0 # Counting to retain which space the special character is in
if letter in compare:
for i in compare:
count += 1 # Keeping track of what space the special character is in
if letter == i:
letter = compare2[count-1] # Changes the letter
break
elif letter in compare2: # Checks to see if the special character is a shifted one
for i in compare2:
count += 1 # Keeps track of the space
if letter == i:
letter = compare[count-1] # Changes the letter
break
letters += letter.capitalize() # Adds the letter and if it isn't a special character it capitalizes it
isCapital += 1 # Allows it to alternate between capitalizing and not
elif isCapital == 1: # If the last letter was changed just add this letter normally
letters += letter # Adds letter to the sentence
isCapital -= 1 # Allows next letter to be changed
print(f"Here is your sarcastic sentence: {letters}")
input("Press enter to continue.")
|
dff13d9fdfaf28f16cd203929bbdbb4b80503aea | Markers/algorithm-problem-solving | /ARCTIC/free-lunch_ARCTIC.py | 1,606 | 3.6875 | 4 | import sys
import collections
# Visit all vetex using BFS
def decision(stations, power):
n = len(stations)
q = collections.deque()
visited = [False] * n
q.append(0)
visited[0] = True
while q:
here = q.pop()
for there in xrange(n):
if not visited[there]:
dist = (stations[here][0]-stations[there][0])**2 + (stations[here][1]-stations[there][1])**2
if dist <= power:
visited[there] = True
q.append(there)
return all(visited)
def solve(stations):
n = len(stations)
dist_list = set()
# Calculate all distances
for i in xrange(n):
for j in xrange(n):
if i == j:
continue
dist = (stations[i][0]-stations[j][0])**2 + (stations[i][1]-stations[j][1])**2
dist_list.add(dist)
# Sort distances
dist_list = sorted(dist_list)
low = 0
high = len(dist_list) -1
# Search a range of correct answer
while high - low > 3:
mid = int(round(low+high)/2)
if decision(stations, dist_list[mid]):
high = mid
else:
low = mid
# Search correct answer in range
for i in xrange(low, high+1):
if decision(stations, dist_list[i]):
return round(dist_list[i]**(0.5),2)
if __name__ == "__main__":
rl = lambda : sys.stdin.readline()
for _ in xrange(int(rl())):
stations = []
for _ in xrange(int(rl())):
stations.append(map(float, rl().split()))
print "{:.2f}".format(solve(stations))
|
daea3ff04e6c81bdeb3e6c6eb57dd9dbd42eb118 | Gr3atJes/pythonweek2 | /test/test_article.py | 538 | 3.609375 | 4 | import unittest
from app.models import Article
class TestArticle(unittest.TestCase):
"""
Test class to test the behaviour of the movie class
"""
self.new_article = Article("Bob","Random Title", "Short","random.com","random.jpg","12/12/12","None")
def test_instance(self):
"""
Tests if instance of the Article class
"""
self.assertTrue(isinstance(self.new_article,Article))
def test_init(self):
"""
Tests for proper instantiation
"""
self.assertEqual(self.new_article.author,"Bob")
|
f44e6b5789ee7c3d75a1891cb4df186016ff8d1a | tgm1314-sschwarz/csv | /csv_uebung.py | 2,240 | 4.34375 | 4 | import csv
class CSVTest:
"""
Class that can be used to read, append and write csv files.
"""
@staticmethod
def open_file(name, like):
"""
Method for opening a csv file
"""
return open(name, like)
@staticmethod
def get_dialect(file):
"""
Method that sniffs out the dialect of a give csv file
:param file: file you want to know the dialect off
"""
d = csv.Sniffer().sniff(file.read(1024))
file.seek(0)
return d
@staticmethod
def reg_dialect(name, delimiter):
"""
Method that can be used to register a new dialect for yourself
:param name: the name of the dialect you want to register
:param delimiter: the delimiter you want to set for the dialect
"""
csv.register_dialect(name, delimiter=delimiter)
@staticmethod
def read_file(file, dialect):
"""
Method that can be used to read a csv file
:param file: the file you want to read
:param dialect: the dialect that is used in the file
"""
return csv.reader(file, dialect)
@staticmethod
def append_files(reader1, reader2):
"""
Method that can be used to append two csv files together so it can be put into a third one
:param reader1: input from the first file
:param reader2: input from the second file
"""
out = []
for row in reader1:
out.append(row)
for row in reader2:
out.append(row)
return out
@staticmethod
def write_file(file, dialect, output):
"""
Method that can be used for writing a new csv file
:param file: name of the file you want to write
:param dialect: the dialect the file you want to write has
:param output: what the file you want to write contains
"""
writer = csv.writer(file, dialect=dialect)
for i in output:
writer.writerow(i)
@staticmethod
def close_file(file):
"""
Method that is used for closing the csv files once you are finished
:param file: the file you want to close
"""
file.close()
|
e41c38694d82e9abdb33e7d1642c7cdc66368d26 | karelbondan/Programming_Exercises_2 | /1.py | 341 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 08:29:52 2020
@author: karel
"""
feet,inch = eval(input("Enter your height (in feet, followed by inch separated by a comma):", ))
print("Feet:", feet)
print("Inches:", inch)
float(feet)
inch=inch/12
feet+=inch
board = feet*30.48*88/100
print("Suggested board length:", board) |
f0df0c613720e02d3e55628722e11c8b4c83088b | chihuanbin/Gaia_Cluster_Search | /cluster_hdbscan.py | 7,814 | 3.78125 | 4 | """Clusters Gaia DR2 data into groups with open cluster characteristics"""
import hdbscan
import numpy as np
import pandas as pd
import warnings
from cluster_plot import cluster_plot
warnings.filterwarnings("ignore")
# This selects which output cluster data the program will write to a csv file
# for subsequent analysis. The star cluster of interest is commonly "0", but
# it can sometimes be a variety of numbers depending on the number of clusters
# in the field.
CLUSTER_EXTRACT_NUM = 0
# This flag determines whether or not to add a colormap representing each
# star's cluster membership probability to the final cluster plots, and whether
# or not to plot the cluster spatial field in a separate 3D plot. Enter 1
# for color map without 3D plot, 2 for color map with 3D plot, and 0 (or
# anything that isn't 1 or 2) for neither. Plotting probabilities and 3D plots in
# is recommended, but when probability and/or 3D visualization aren't critical and simpler
# easier to read figures are desired, consider not adding the information.
PLOT_MEMBERSHIP_PROB = 2
# CLUSTER_NAME identifies the input file (usually using some type of
# shorthand) and output cluster file names. FIELD_RADIUS is the input
# GAIA DR2 search radius (in degrees), and is part of the input csv filename.
CLUSTER_NAME = "n2422.n2423"
FIELD_RADIUS = 2
MIN_SAMPLE = 98
def gaia_dr2_read_setup():
""" Read the input csv file (from GaiaSearch.py) into a dataframe. Return the
calculated distance and further important parameters and drop stars that are
missing these parameters. """
clusterfull = pd.read_csv(CLUSTER_NAME+"gaiafield"+str(FIELD_RADIUS)+".csv", delimiter=",")
# A second dataframe is created that only contains the parameters that will
# be used to base the HDBSCAN clustering on and for analyzing the results, and this command
# also allows the user to make further parallax error ratio cuts beyond the standard < 3; lastly,
# stars that are missing a parameter are dropped.
clusterfull["parallax_ratio"] = clusterfull["parallax"] / clusterfull["parallax_error"]
fieldparfull = clusterfull.loc[clusterfull["parallax_ratio"] > 5, ["ra", "dec", "pmra",\
"pmdec", "parallax", "phot_g_mean_mag", "bp_rp"]]
fieldpar = fieldparfull.dropna().copy()
# A new distance (pc) column is created in the dataframe based on the observed
# parallax. A 0.03 zeropoint correction is applied.
fieldpar['distance'] = 1/((fieldpar['parallax']+0.03)*0.001)
return fieldpar
def ra_wrapper(ra_dataframe):
""" The input RA are checked to see if they wrap around RA=0,360 and are
corrected. In either case, the RA is also transformed to a uniform scale
and added to the main dataframe and returned. Note that this program may
have some difficulty around the poles, but there are no clusters to analyze
in those regions."""
ramax = max(ra_dataframe["ra"])
ramin = min(ra_dataframe["ra"])
wrap_check = 0
ra_dataframe["rawrapped"] = ra_dataframe["ra"]
# If the maximum and minimum RA are more than 200 degrees apart, it is safe to
# assume that this is because they span RA=0,360. In this case, the minimum
# of the large values (~355 deg) and the maximum of the small value (~5 deg)
# must be calculated/corrected and then applied to properly scale and tie
# together the RA.
if ramax - ramin > 200:
wrap_check = 1
ramax = ra_dataframe.loc[ra_dataframe["ra"] < 200, ["ra"]].max().at["ra"]
ramin = ra_dataframe.loc[ra_dataframe["ra"] > 200, ["ra"]].min().at["ra"]
if ramin < (360 - ramax):
ramax += 360
ra_dataframe.loc[ra_dataframe['rawrapped'] >= 0, 'rawrapped'] = \
ra_dataframe['rawrapped']+360
else:
ramin -= 360
ra_dataframe.loc[ra_dataframe['rawrapped'] > 180, 'rawrapped'] = \
ra_dataframe['rawrapped']-360
racen = (ramin + ramax)/2
ra_dataframe["ratransform"] = ra_dataframe["ra"] - racen
if wrap_check == 1:
ra_dataframe.loc[ra_dataframe['ratransform'] > 180, 'ratransform'] = \
ra_dataframe['ratransform']-360
ra_dataframe.loc[ra_dataframe['ratransform'] < -180, 'ratransform'] = \
ra_dataframe['ratransform']+360
return ra_dataframe
def parameter_scaler(fieldparscaled, fieldpar):
""" Apply appropriate scales to normalize the parameters or place them in a
uniform space. The most appropriate scaling can be cluster dependent. Most
notably with increasing distance, the cluster distance and PM variations of
true members increase due to increased errors. I recommend scaling these so
that the output unscaled IQRs of the cluster members for each parameter are
roughly equal by adjusting what fieldpar['distance'] is divided by and what
fieldpar['pmra'] and ['pmdec'] are multiplied by. """
fieldparscaled['parallax'] = fieldpar['distance']/5
fieldparscaled['ratransform'] = fieldparscaled['ratransform']* \
np.cos(fieldpar["dec"]*3.14159/180)
fieldparscaled['ra'] = fieldparscaled['ratransform']*3.14159/180* \
fieldpar['distance']
fieldparscaled['dec'] = fieldpar['dec']*3.14159/180*fieldpar['distance']
fieldparscaled['pmra'] = fieldpar['pmra']*35
fieldparscaled['pmdec'] = fieldpar['pmdec']*35
return fieldparscaled
def clustering_algorithm(fieldparscaled, fieldpar):
""" The scaled parameters are applied to the hdbscan function. A minimum cluster
and sample size are set. 64 is typically an appropriate min_samples for a
5-dimensional hdbscan, but I recommend looking at potential differences in
output when this parameter is varied by up to a factor of 2 (if not more).
Especially adjust min_samples if a clear cluster in PM space is missed in
the output. A smaller min_samples increases noise but helps differentiate
from the field the clusters with proper motions comparable to the field.
Note that we can also use G magnitude and BP-RP color to increase clustering
accuracy. They are commented out in this input list, but they can help to
create a cleaner cluster main sequence, BUT at the expense of removing many
cluster giants/subdwarfs/white dwarfs. """
clustering = hdbscan.HDBSCAN(min_cluster_size=50, min_samples=MIN_SAMPLE, cluster_selection_method="leaf").\
fit(fieldparscaled[["ra", "dec", "pmra", "pmdec", "parallax"]])
# ,"phot_g_mean_mag","bp_rp"]])
# The cluster selection and probability results, plus transformed RA, are
# added as new columns to the original dataframe.
clusterselection = clustering.labels_
clusterprobabilities = clustering.probabilities_
fieldpar["clusternum"] = clusterselection.tolist()
fieldpar["clusterprob"] = clusterprobabilities.tolist()
fieldpar["ratransform"] = fieldparscaled["ratransform"]
fieldpar["rawrapped"] = fieldparscaled["rawrapped"]
# The stars absolute G (based on Gaia parallax) is calculated and the selected
# CLUSTER_EXTRACT_NUM cluster is output to a csv file.
fieldpar["M_G"] = fieldpar["phot_g_mean_mag"] - \
np.log10(fieldpar["distance"]/10)*5
fieldpar[fieldpar["clusternum"] == CLUSTER_EXTRACT_NUM]. \
to_csv(CLUSTER_NAME+"clustering.csv")
return fieldpar
def main():
""" Main program series, which calls data and clustering functions and then plots
them """
fieldpar = gaia_dr2_read_setup()
fieldparscaled = fieldpar.copy()
fieldparscaled = ra_wrapper(fieldparscaled)
fieldparscaled = parameter_scaler(fieldparscaled, fieldpar)
fieldpar = clustering_algorithm(fieldparscaled, fieldpar)
# Plots the output clustered data. See clusterplot.py for details.
cluster_plot(fieldpar, PLOT_MEMBERSHIP_PROB)
main()
|
5f69620a7ce1c8a4b3a7cb32abe697fa4ef522da | danhagg/python_bits | /CrashCourseInPython/kafah.py | 261 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 27 16:22:26 2017
@author: danielhaggerty
"""
answer = "Kafah tells lies"
question = input("Does Kafah prefer Dan or crappy Persian TV: ")
if 'Dan':
print(answer)
else:
print(answer) |
fe731fd040a7288811f1486979ffaf69245fff29 | danhagg/python_bits | /CrashCourseInPython/while_loops.py | 153 | 4.1875 | 4 | # while loops, the += operator == "current iterator + 1"
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
|
00e6c625791d1dba687996916e173461dd76f72e | Zihad07/Coding_for_Job_Interview | /Array_01/03_is_one_array_rotaion_of_another.py | 1,482 | 3.671875 | 4 |
# for BIG O(n)
def is_Rotation_my_method(A,B):
len_A = len(A)
result = {}
for i in range(len_A):
if A[i] not in result:
result[A[i]] = 1
else:
result[A[i]] += 1
if B[i] not in result:
result [B[i]] = 1
else:
result [B[i]] += 1
# if the diction all item value of sum = len_A*2
# return true
# else return false
myresult = 0
for key in result.keys():
myresult += result[key]
if myresult == (len_A * 2) and len_A == len(result):
return True
else:
return False
# --------------------------------------------------------------
# The Best Solution
def isRotaion(A,B):
len_A = len(A)
len_B = len(B)
if len_A != len_B:
return False
key = A[0]
key_index = -1
for i in range(len_B):
if key == B[i]:
key_index = i
break
if key_index == -1:
return False
for i in range(len_A):
j = (key_index + i) % len_A
if A[i] != B[j]:
return False
# other wise
return True # the one array is rotation other array
# Testing my method
if __name__ == '__main__':
A = [1,2,3,4,5,6,7]
B = [4,5,6,7,1,2,3]
print(is_Rotation_my_method(A,B))
print(isRotaion(A,B))
A = [1,2,3,4,5,6,7]
B = [4,8,9,7,1,2,3]
print(is_Rotation_my_method(A,B))
print(isRotaion(A,B))
|
c285779a11d17b02bda0bb45204f304db05cb12d | Fadzayi-commits/Python_Programming_Assignment_9 | /Disarium_btwn.py | 536 | 3.875 | 4 | def calculateLength(n):
length = 0;
while (n != 0):
length = length + 1;
n = n // 10;
return length;
def sumOfDigits(num):
rem = sum = 0;
len = calculateLength(num);
while (num > 0):
rem = num % 10;
sum = sum + (rem ** len);
num = num // 10;
len = len - 1;
return sum;
result = 0;
print("Disarium numbers between 1 and 100 are");
for i in range(1, 101):
result = sumOfDigits(i);
if (result == i):
print(i), |
a5059ea989573a23128d9f9eb670827e09f72bea | teazzy1/Python-Basics | /Conversion Program.py | 275 | 4 | 4 | print("Program running.....")
x= int(input("type a number in the box ")) #Defines input function
def conversion (unit): #Declare the functions
mililiters = unit * 29.57353 # Set the parameters
return mililiters
print(conversion(x)) #substitute 'x' for any number
|
a6a11c4a34f95565baee0f8dbb5885134106f72f | accubits/AI-ML_Marian_Sessions | /advertisement_app/predict.py | 714 | 3.796875 | 4 | import numpy as np
import pandas as pd
# Data Visualisation
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
advertising = pd.DataFrame(pd.read_csv("Data/simple_lr_application/advertising.csv"))
X = advertising['TV'].values
y = advertising['Sales'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
regressor = LinearRegression()
regressor.fit(X_train.reshape(-1, 1), y_train.reshape(-1, 1))
def predict_out(val):
val = np.array(int(val))
req_inp = np.array(val.reshape(-1, 1))
output = regressor.predict(req_inp)
return output |
c1249eca315f652960a09c2b903c93121c8a19c4 | saiso12/ds_algo | /study/OOP/Employee.py | 452 | 4.21875 | 4 | '''
There are two ways to assign values to properties of a class.
Assign values when defining the class.
Assign values in the main code.
'''
class Employee:
#defining initializer
def __init__(self, ID=None, salary=None, department=None):
self.ID = ID
self.salary = salary
self.department = department
def tax(self):
return self.salary * 0.2
def salaryPerDay(self):
return self.salary / 30
|
97e0ec7c4c0f59ba57726ee9dce2fa51440e0afe | saiso12/ds_algo | /study/recursion/sum_of_digits.py | 298 | 3.75 | 4 | #Sum of digits
# 10 = 1
# 120 = 122 % 10 => 12,2 => 12/10 => 1,2,2
def sumofDigits(n):
assert n >= 0 and int(n) == n, 'n must be positive and a whole number'
if n == 0:
return 0
else:
return int(n%10) + sumofDigits(int(n//10))
print(sumofDigits(1111111111111111111)) |
ac4e5c7b2a3b4e8f6c73e1ebe586a0aa921615e4 | boblespatates/Regex_tuto | /regex_2.py | 1,399 | 3.9375 | 4 | import re
#https://github.com/CoreyMSchafer/code_snippets/tree/master/Python-Regular-Expressions
text_to_search = '''
azertyuiop
azertyuio
azertyuHZZHZHA
abc
'''
sentence = 'Start a sentence and then bring it to an end'
# Allow to separate the patterns into a variable
# And make it easier to reuse that variable to perform
# Multiple searches
# Here we try to find urls (and 3 groups can be seen
pattern = re.compile(r'https?://(www\.)?(\w+)(\.w+)')
matches = pattern.finditer(text_to_search)
# Substitute with groupe 2 and 3
subbed_urls = pattern.sub(r'\2\3',urls)
# input : https://www.google.com
# output : google.com
# pattern.findall list all the find elements
# pattern.match return the begining match same as finditer
# pattern.search return the first match find but in the whole text
# re.compile(r'start', re.IGNORECASE) eventhought the pattern is in lower case
# It will search also the upper cases
with open('data.txt', 'r', encoding='utf-8') as f:
contents = f.read()
matches = pattern.finditer(contents)
for match in matches:
print(match)
# return ex : <_sre.SRE_Match object; span=(37, 40), match='abc'>
# so contains all the matches
# span is the begining and end index of the match
# print(text_to_search[37:40])
print(match.group(0))
# the match
print(match.group(1))
# only the group 1
# if there isn't it is set as none
|
c3fa48aaa5e4c241218c25d5b70c2e89a4f9142d | NguyenQuyPhuc20173302/thuctaptuan2 | /Sort_the_Lists1.py | 714 | 3.890625 | 4 | list1 = [1, 4, 7]
list2 = [1, 3, 4]
list3 = [2, 6]
count1 = 0
count2 = 0
count3 = 0
total_len = len(list1) + len(list2) + len(list3)
ls = []
# hàm này từ 2 dành sách rồi chuyển thành 1 danh sách đã được sắp xếp
def Sort_two_list(a1, a2):
a = []
dem1 = 0
dem2 = 0
while 1:
if dem1 == len(a1):
a.extend(a2[dem2:])
return a
if dem2 == len(a2):
a.extend(a1[dem1:])
return a
if a1[dem1] < a2[dem2]:
a.append(a1[dem1])
dem1 += 1
else:
a.append(a2[dem2])
dem2 += 1
list1 = Sort_two_list(list1, list2)
list1 = Sort_two_list(list1, list3)
print(list1)
|
135ab7dcac0c4aff3b8c628965d2bf6e3d3bde07 | sirbrave21/Python | /TaşKağıtMakas.py | 567 | 4.09375 | 4 | import random
print("1-Taş")
print("2-Kağıt")
print("3-Makas")
kullanıcı = int(input("1 ile 3 arası bir sayı seçiniz : "))
pc = random.randrange(3)+1
print("Bilgisayarın seçimi : ",random.randrange(3)+1)
if (kullanıcı == 1 and pc == 2) or (kullanıcı == 2 and pc == 3) or (kullanıcı == 3 and pc == 1):
print("Kaybettiniz")
elif (kullanıcı == 1 and pc == 3) or (kullanıcı == 2 and pc == 1) or (kullanıcı == 3 and pc == 2):
print("Kazandınız")
elif kullanıcı == pc:
print("Berabere")
else:
print("Geçersiz Girdi") |
3355e006e673b9be9917c552b0532a9e132e6122 | doonguk/algorithm | /20200406/90.py | 176 | 3.59375 | 4 | def solution(s):
stack = list()
for v in s:
if stack and stack[-1] == v:
stack.pop()
else:
stack.append(v)
return not(stack) |
579bb05dbb04a51bde52a643c0b0bcb3a247ff41 | doonguk/algorithm | /20200303/22.py | 747 | 3.578125 | 4 | import sys
sys.stdin = open("input22.txt", "rt")
n, target = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
start = 0
end = n-1
while start <= end:
mid = (start + end) // 2
if a[mid] == target:
print(mid+1)
break
elif a[mid] > target:
end = mid - 1
else:
start = mid + 1
# 방법2
# start = 0
#
# def binarySearch(start, end, target, data):
# if start > end:
# return None
# mid = (start + end) // 2
# if target == data[mid]:
# return mid + 1
# elif target > data[mid]:
# start = mid + 1
# else:
# end = mid-1
# return binarySearch(start, end, target, data)
#
#
# print(binarySearch(start, n-1, target, sorted(a))) |
cafc89d0019f391457ac72a2d98acd4cfce049c4 | nashit-mashkoor/Coding-Work-First-Phase- | /practice-pandas/.ipynb_checkpoints/CAPM MODEL-checkpoint.py | 1,192 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 9 21:08:49 2018
@author: MMOHTASHIM
"""
import pandas as pd
import matplotlib.pyplot as plt
import quandl
from statistics import mean
import numpy as np
from IPython import get_ipython
api_key="fwwt3dyY_pF8LyZqpNsa"
def get_data_company(company_name):
df=quandl.get("EURONEXT/"+str(company_name),authtoken=api_key)
df=pd.DataFrame(df["Last"])
df.rename(columns={"Last":"Price"},inplace=True)
df_2=df.resample("M").mean()
return df_2
def get_data_euronext():
df_2=pd.read_csv("EuroNext 100 Historical Data.csv")
df_2=df_2.loc[0:6, :]
df_2=pd.DataFrame(df_2[["Date","Price"]])
return df_2
def calculate_beta(company_name):
df=get_data_euronext()
df_2=get_data_company(company_name)
xs=np.array((df["Price"]))
ys=np.array(df_2["Price"])
m = (((mean(xs)*mean(ys)) - mean(xs*ys)) /
((mean(xs)*mean(xs)) - mean(xs*xs)))
b = mean(ys) - m*mean(xs)
get_ipython().run_line_magic('matplotlib', 'qt')
print("Your Beta is"+ str(m))
regression_line = [(m*x)+b for x in xs]
plt.scatter(xs,ys,color='#003F72')
plt.plot(xs, regression_line)
plt.show()
return m, b
|
bdb79ff3274d007e9fdf9c5d3fdbc237f4ce1392 | nashit-mashkoor/Coding-Work-First-Phase- | /sentdex machine learning projects/Regression part 10 and Part 11.py | 1,179 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 3 14:15:33 2019
@author: MMOHTASHIM
"""
#Linear Regression Model from scratch:
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("fivethirtyeight")
xs=np.array([1,2,3,4,5,6],dtype=np.float64)
ys=np.array([5,4,6,5,6,7],dtype=np.float64)
def best_fit_slope_and_intercept(xs,ys):
m=((mean(xs)*mean(ys)) - (mean(xs*ys)))/((mean(xs)**2)-mean(xs**2))
b=mean(ys)-m*mean(xs)
return m,b
m,b=best_fit_slope_and_intercept(xs,ys)
print(m,b)
def squared_error(ys_orgin,ys_line):
return sum((ys_line-ys_orgin)**2)
def coefficent_of_determination(ys_orgin,ys_line):
y_mean_line=[mean(ys_orgin) for y in ys_orgin]
square_error_regr=squared_error(ys_orgin,ys_line)
square_error_regr_y_mean=squared_error(ys_orgin,y_mean_line)
return 1-(square_error_regr)/(square_error_regr_y_mean)
regression_line=[(m*x)+b for x in xs]
r_square=coefficent_of_determination(ys,regression_line)
print(r_square)
predict_x=8
predict_y=(m*predict_x)+b
print(regression_line)
plt.scatter(xs,ys)
plt.scatter(predict_x,predict_y,color="g")
plt.plot(regression_line) |
800b8ea97a00f569ec7182a3084808cab5b97b41 | EarlHikky/CursaTetra | /ct_cell.py | 1,782 | 3.71875 | 4 | import curses as crs
"""
Gets the character value (as an int) of a cell in the board;
As blocks take up two curses-coordinate spaces,
a cell is defined as such, and its identifying
symbol will be in the righthand space;
In theory, the cell will either be empty (". "),
have an old block (two ACS_BLOCK chars),
or have an active block (two ACS_CKBOARD chars)
"""
def getCellValue(y, x, board):
return board.inch(y, 2 * x)
"""
Sets the character values of a cell in the board
"""
def setCellValue(y, x, val, board):
values = { \
"EMPTY": '. ', \
"ACTIVE": (crs.ACS_CKBOARD, crs.ACS_CKBOARD) \
}
colors = { \
"ACTIVE-C": 3, \
"ACTIVE-S": 2, \
"ACTIVE-Z": 1, \
"ACTIVE-L": 7, \
"ACTIVE-R": 4, \
"ACTIVE-I": 6, \
"ACTIVE-T": 5 \
}
if val == "EMPTY":
v = val
else:
v = "ACTIVE"
i = 2 * x - 1
for c in values[v]:
if v != "ACTIVE":
board.addch(y, i, c)
else:
board.addch(y, i, c, crs.color_pair(colors[val]))
i += 1
# String that contains the ghost piece characters
ghostChars = "[]"
"""
Returns True if the indicated cell is empty
"""
def isCellEmpty(y, x, board):
return y < 1 or getCellValue(y, x, board) in (ord(' '), ord(ghostChars[1]))
"""
Returns True if the indicated cell is a valid board space
"""
def isCellInBounds(y, x):
return y < 21 and x > 0 and x < 11
"""
Return a list of y-addresses that are full of blocks
"""
def getFullLines(board):
fullLines = []
for y in range(20, 0, -1):
full = True
for x in range(1, 11):
if isCellEmpty(y, x, board):
full = False
break
if full:
fullLines.append(y)
return fullLines
"""
Returns True if the indicated line has no blocks in it
"""
def isLineEmpty(y, board):
for x in range(1, 11):
if isCellEmpty(y, x, board):
continue
else:
return False
return True
|
8889124922ceecc18ee9ece4af6246f6ec9b4dcb | radiolariia/Python | /Labs/lab_5_HRYNEVYCH.py | 505 | 4 | 4 | print('lab5\nSofiia Hrynevych \nІПЗ-11 \nVariant 3')
def binomial_coefficient(n, k):
if n < k:
return (print('It`s impossible to calculate a factorial value of negative number!'))
if k == 0 or k == n:
return 1
else:
return binomial_coefficient(n - 1, k - 1) + binomial_coefficient(n - 1, k)
while True:
n = int(input(' n = '))
if n > 0:
break
else:
print(' n must be a natural number!')
k = int(input(' k = '))
print('Value of C(%d,%d) is (%s)' % (n , k , binomial_coefficient(n , k)))
|
21353b0049094df9e13a6a152f1ad84d15e6f91c | radiolariia/Python | /Labs/lab_2_HRYNEVYCH.py | 521 | 3.828125 | 4 | import math
print('Lab 2 \nSofiia Hrynevych \nIПЗ-11 \nTASK 1')
def s():
print('\n')
s()
while True:
a = float(input('Основа рівнобедренного трикутника = '))
b = float(input('Бічна сторона трикутника = '))
if (a > 0 and b > 0) and ((2 * b) > a):
break
s()
print('It`s an impossible triangle! \nTry again!')
area = round((a/2)*math.sqrt((b**2)-((a**2)/4)))
s()
print(area)
s()
if area % 2 == 0:
print(area/2)
else:
print('Не можу ділити на 2!')
|
9c7474fb68c1c9edf9855ed4d5c5f7a1234c181f | radiolariia/Python | /Labs/lab_1-2_HRYNEVYCH.py | 1,041 | 3.71875 | 4 | import math
print('Lab 2 \nSofiia Hrynevych \nIПЗ-11 \nVariant 3\n \nTASK 1')
def s():
print('\n')
s()
r = float(input('R = '))
length = (2*math.pi)*r
area = math.pi*(r**2)
s()
print('Length of the circle: {0:5.3f} \nArea of the circle: {1:5.3f}'.format(length,area))
s()
print('TASK2')
s()
d2 = float(input('D ='))
area2 = math.pi*((d2/2)**2)
s()
print('Area of the circle: {0:5.3f}'.format(area2))
s()
print('TASK3')
s()
length3 = float(input('Length = '))
r3 = length3/(2*math.pi)
s()
print('Radius: {0:5.3f}'.format(r3))
s()
print('TASK4')
s()
area4 = float(input('Area of the circle = '))
d4 = math.sqrt((area4/math.pi))*2
print('Diameter: {0:5.3f}'.format(d4))
s()
print('TASK5')
s()
catA = float(input('Cathetus A = '))
catB = float(input('Cathetus B = '))
hyp = math.hypot(catA, catB)
print('Hypotenuse: {0:5.3f}'.format(hyp) )
s()
print('TASK6')
s()
catB6 = float(input('Cathetus B = '))
hyp6 = float(input('Hypotenuse = '))
catA6 = math.sqrt((math.pow(hyp6,2) - math.pow(catB6,2)))
print('Cathetus A = {0:5.3f}'.format(catA6))
|
a5f0ce5dbb96b3360d565604bc12ac97d92a9e70 | bibiacoutinho/Python-Para-Zumbis | /Lista 5_bibiacoutinho.py | 3,149 | 3.734375 | 4 | ##Questão A
x = 2
y = 5
if y > 8:
y = y * 2
else:
x = x * 2
print (x + y)
##Questão B
lista = []
for i in range(9):
if i != 3:
for j in range (6):
print (f'oi')
lista.append(j)
print (len(lista))
##Questão C
lista = []
listafinal = []
for n in range (1068,3628,2): ##percorre de 2 em 2, a partir do primeiro numero
lista.append(n)
for n in lista:
if n%7==0:
listafinal.append(n)
print (len(listafinal))
##Questão D
def contem2(numero):
numero = str(numero) ##precisa transformar o 'numero' pois é a variavel a ser percorrida
for n in numero:
if n in '2':
return True
return False
def naocontem7(numero):
numero = str(numero)
for n in numero:
if n in '7':
return False #pra função, pode trocar as ordens de true e false
return True
lista = []
listafinal=[]
for n in range(18644,33088):
lista.append(n)
for numero in lista:
if contem2(numero) and naocontem7(numero):
listafinal.append(numero)
print(len(listafinal))
##Questão E
telefones = '''213752 216732 221063 221545 225583 229133 230648 233222
236043 237330 239636 240138 242123 246224 249183 252936
254711 257200 257607 261424 263814 266794 268649 273050
275001 277606 278997 283331 287104 287953 289137 291591
292559 292946 295180 295566 297529 300400 304707 306931
310638 313595 318449 319021 322082 323796 326266 326880
327249 329914 334392 334575 336723 336734 338808 343269
346040 350113 353631 357154 361633 361891 364889 365746
365749 366426 369156 369444 369689 372896 374983 375223
379163 380712 385640 386777 388599 389450 390178 392943
394742 395921 398644 398832 401149 402219 405364 408088
412901 417683 422267 424767 426613 430474 433910 435054
440052 444630 447852 449116 453865 457631 461750 462985
463328 466458 469601 473108 476773 477956 481991 482422
486195 488359 489209 489388 491928 496569 496964 497901
500877 502386 502715 507617 512526 512827 513796 518232
521455 524277 528496 529345 531231 531766 535067 535183
536593 537360 539055 540582 543708 547492 550779 551595
556493 558807 559102 562050 564962 569677 570945 575447
579937 580112 580680 582458 583012 585395 586244 587393
590483 593112 593894 594293 597525 598184 600455 600953
601523 605761 608618 609198 610141 610536 612636 615233
618314 622752 626345 626632 628889 629457 629643 633673
637656 641136 644176 644973 647617 652218 657143 659902
662224 666265 668010 672480 672695 676868 677125 678315'''.split()
def consecutivoigual(n):
for a in range(5):
if n[a]==n[a+1]:
return True
return False
def primeiroultimoigual(n):
if n[0]==n[5]:
return True
return False
def somadigitosigualpar(n):
soma = 0
for a in range(6):
soma+=int(n[a])
if soma%2==0:
return True
return False
c=0
for n in telefones:
n = list(n)
if not consecutivoigual(n):
if somadigitosigualpar(n):
if not primeiroultimoigual(n):
c+=1
print(c)
|
e83c1927d506cdbe6817d2f9571cd0a548bb5c41 | MarcoVillegasCampos/Dojo-Pets | /Ninja/Ninja.py | 650 | 3.59375 | 4 |
from Pet import Pet
class Ninja:
def __init__(self, first_name, last_name, treats, pet_food, pet):
self.first_name=first_name
self.last_name= last_name
self.treats=treats
self.pet_food=pet_food
self.pet=pet
def walk(self):
self.pet.play()
return self
def feed(self):
if len(self.pet_food)>0:
food= self.pet_food.pop()
print(f"Feeding{self.pet.name}{food}")
self.pet.eat()
else:
print("Oh no!!! You need more pet food")
return self
def bathe(self):
self.pet.noise()
|
00b72fd38c0c9d04f1f952ca6dd2ad7db0766217 | spiderbeg/100 | /answer/ex98.py | 292 | 3.796875 | 4 | # coding:utf8
import math
def FindHim():
for x in range(10):
for y in range(10):
if x != y:
result = x * 1100 + y * 11
test = math.sqrt(result)
if test.is_integer():
return result
print (FindHim()) |
cbf294b5deb0aa61a3dcce122eac4770522a4de9 | spiderbeg/100 | /answer/ex39.py | 152 | 3.703125 | 4 | # coding:utf8
num = input('请输入字符: ')
if num.isdigit():
print('您输入的是数字:%s'%num)
else:
print('您输入的不是数字') |
6f29cb3b97b356d5fe8b3104a305a0e4c4b22337 | spiderbeg/100 | /answer/ex48.py | 486 | 3.8125 | 4 | # coding:utf8
# 定义一个函数
def mcd(x, y):
"""该函数返回两个数的最大公约数"""
# 获取最小值
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
mc = i
return mc
# 用户输入两个数字
num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))
print( num1,"和", num2,"的最大公约数为", mcd(num1, num2)) |
b048fe3ff7a7d09967f564da005c5b7d150ac699 | pombreda/mpython-to-dalvik-compiler | /ex6.py | 221 | 4 | 4 | num1 = raw_input("Digite o primeiro número: ")
num2 = raw_input("Digite o segundo número: ")
if num1 > num2:
print("O primeiro número é maior que o segundo")
else
print("O segundo número é maior que o primeiro")
|
7af186adfb6bbc16b72a792fac137a13e4d9206c | pombreda/mpython-to-dalvik-compiler | /ex5.py | 149 | 3.546875 | 4 | print("=-=-=-=-=- Tabela de conversão: Celsius -> Fahrenheit -=-=-=-=-=")
cel = raw_input("Digite a temperatura em Celsius: ")
far = (9*cel+160)/5
|
0d6a3e36bf67579802704014fcec59c8c6745fa1 | gnduka17/My-Code-Samples | /ITP115_project_Nduka_Gloria/MenuItem.py | 1,048 | 3.640625 | 4 | #this class represents a single menu item on the menu
class MenuItem(object):
def __init__(self, nameparam, typeparam, priceparam, descripparam):
self.name = nameparam
self.type = typeparam
self.price = priceparam
self.description = descripparam
#the getter functions for name, type, price, and description
def getName(self):
return self.name
def getType(self):
return self.type
def getPrice(self):
return self.price
def getDescription(self):
return self.description
# the setter functions for name, type, price, and description
def setName(self, newName):
self.name=newName
def setType(self, newType):
self.type=newType
def setPrice(self, newPrice):
self.price=newPrice
def setDescription(self, newDescrip):
self.description=newDescrip
#return message with all the attributes
def __str__(self):
return self.name + " (" + self.type + "): " + str(self.price) + "\n\t" + self.description
|
87d3c0a689334c7072d0301528a4d011d1716c8b | yourboirusty/advanced_python_seminar | /02_Iterators/modifiers.py | 964 | 3.9375 | 4 | def isEven(x):
if x % 2 == 0:
return True
return False
def isUpper(x):
return x.isupper()
def square(x):
return x**2
def grade(x):
if x >= 95:
return "5.5"
elif x >= 80:
return "5"
elif x >= 70:
return "4"
elif x >= 65:
return "3"
elif x >= 50:
return "2.5"
return "2"
def main():
nums = (1, 8, 12, 54, 199, 24566, 9, 35)
chars = "yoUCaNTJuSTdoIT"
grades = (5, 30, 68, 50, 100, 87, 76)
# TODO Filter out odd numbers from nums
evens = list(filter(isEven, nums))
print(evens)
# TODO Filter out lowercase from chars
upeper = list(filter(isUpper, chars))
print(upeper)
# TODO Square all the nums
squares = list(map(square, nums))
print(squares)
# TODO Sort and grade
grades = sorted(grades)
print(grades)
real_grades = list(map(grade, grades))
print(real_grades)
if __name__ == "__main__":
main() |
a93d96372ed9207bf03fba2c71edae9c93025c08 | valdimirbarrosti/sistemaescolarharvard | /cadastro.py | 49,783 | 3.578125 | 4 |
## funcao para cadastrar professor no banco de dados ##
def cadastrarProf(nomeProf,discProf,userProf,senhaProf):
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
sqlInserir = "INSERT INTO professor VALUES ('{}','{}','{}','{}')".format(nomeProf,discProf,userProf,senhaProf) #variavel que recebe o comando SQL para ser manipulado pelo metodo execute abaixo
interagir.execute(sqlInserir)
conectar.commit()
'''
Assume-se que cada lista alunoDados conterá 5 elementos:
elemento nº 1: NOME DO ALUNO
elemento nº 2: LISTA DE NOTAS DE PORTUGUES
elemento nº 3: LISTA DE NOTAS DE MATEMÁTICA
elemento nº 4: LISTA DE NOTAS DE GEOGRAFIA
elemento nº 5: LISTA DE NOTAS DE HISTÓRIA
Assume-se que a lista anoTurma conterá as listas alunoDados sendo adicionadas
em cada loop e no final será salva no seu respectivo anoTurma.txt.
'''
### funcões que vão salvar as notas dos alunos no banco de dados SQLlite3 do sistema ###
def cadastrarNotasAlunosPrimeiroAnoA():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
sqlSelecionarDisciplina ="SELECT disciplina FROM professor WHERE usuario='alex.barradas'"
for row in interagir.execute(sqlSelecionarDisciplina):
discProf = str(row[0])
print(discProf)
interagir.execute("SELECT nomealuno FROM primeiroanoa ORDER BY nomealuno")
if discProf == 'portugues':
print('Cadastre suas notas referentes a disciplina de português:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Prt = float(input("1ª nota de Português: "))
n2Prt = float(input("2ª nota de Português: "))
n3Prt = float(input("3ª nota de Português: "))
n4Prt = float(input("4ª nota de Português: "))
mediaPrt = (n1Prt+n2Prt+n3Prt+n4Prt)/4
if mediaPrt>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1prt={}, nota2prt={}, nota3prt={}, nota4prt={}, mediaprt={}, situacaoprt='{}' WHERE nomealuno='{}'".format(n1Prt,n2Prt,n3Prt,n4Prt, mediaPrt, situacaoDisc, nomeAluno[0], ))
conectar.commit()
if discProf == 'matematica':
print('Cadastre suas notas referentes a disciplina de matemática:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Mtm = float(input("1ª nota de Matemática: "))
n2Mtm = float(input("2ª nota de Matemática: "))
n3Mtm = float(input("3ª nota de Matemática: "))
n4Mtm = float(input("4ª nota de Matemática: "))
mediaMtm = (n1Mtm+n2Mtm+n3Mtm+n4Mtm)/4
if mediaMtm>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1mtm={}, nota2mtm={}, nota3mtm={}, nota4mtm={}, mediamtm={}, situacaomtm='{}' WHERE nomealuno='{}'".format(n1Mtm,n2Mtm,n3Mtm,n4Mtm, mediaMtm, situacaoDisc, nomeAluno[0]))
if discProf == 'geografia':
print('Cadastre suas notas referentes a disciplina de geografia:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Geo = float(input("1ª nota de Geografia: "))
n2Geo = float(input("2ª nota de Geografia: "))
n3Geo = float(input("3ª nota de Geografia: "))
n4Geo = float(input("4ª nota de Geografia: "))
mediaGeo = (n1Geo+n2Geo+n3Geo+n4Geo)/4
if mediaGeo>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1geo={}, nota2geo={}, nota3geo={}, nota4geo={}, mediageo={}, situacaogeo='{}' WHERE nomealuno='{}'".format(n1Geo,n2Geo,n3Geo,n4Geo, mediaGeo, situacaoDisc, nomeAluno[0]))
if discProf == 'historia':
print('Cadastre suas notas referentes a disciplina de história:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Hst = float(input("1ª nota de História: "))
n2Hst = float(input("2ª nota de História: "))
n3Hst = float(input("3ª nota de História: "))
n4Hst = float(input("4ª nota de História: "))
mediaHst = (n1Hst+n2Hst+n3Hst+n4Hst)/4
if mediaHst>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1hst={}, nota2hst={}, nota3hst={}, nota4hst={}, mediahst={}, situacaohst WHERE nomealuno='{}'".format(n1Hst,n2Hst,n3Hst,n4Hst, mediaHst, situacaoDisc, nomeAluno[0]))
conectar.commit()
print('As notas foram cadastradas com sucesso!')
print("Retornando ao menu anterior...")
def cadastrarNotasAlunosPrimeiroAnoB():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
sqlSelecionarDisciplina ="SELECT disciplina FROM professor WHERE usuario='alex.barradas'"
for row in interagir.execute(sqlSelecionarDisciplina):
discProf = str(row[0])
print(discProf)
interagir.execute("SELECT nomealuno FROM primeiroanob ORDER BY nomealuno")
if discProf == 'portugues':
print('Cadastre suas notas referentes a disciplina de português:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Prt = float(input("1ª nota de Português: "))
n2Prt = float(input("2ª nota de Português: "))
n3Prt = float(input("3ª nota de Português: "))
n4Prt = float(input("4ª nota de Português: "))
mediaPrt = (n1Prt+n2Prt+n3Prt+n4Prt)/4
if mediaPrt>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanob SET nota1prt={}, nota2prt={}, nota3prt={}, nota4prt={}, mediaprt={}, situacaoprt='{}' WHERE nomealuno='{}'".format(n1Prt,n2Prt,n3Prt,n4Prt, mediaPrt, situacaoDisc, nomeAluno[0], ))
conectar.commit()
if discProf == 'matematica':
print('Cadastre suas notas referentes a disciplina de matemática:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Mtm = float(input("1ª nota de Matemática: "))
n2Mtm = float(input("2ª nota de Matemática: "))
n3Mtm = float(input("3ª nota de Matemática: "))
n4Mtm = float(input("4ª nota de Matemática: "))
mediaMtm = (n1Mtm+n2Mtm+n3Mtm+n4Mtm)/4
if mediaMtm>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanob SET nota1mtm={}, nota2mtm={}, nota3mtm={}, nota4mtm={}, mediamtm={}, situacaomtm='{}' WHERE nomealuno='{}'".format(n1Mtm,n2Mtm,n3Mtm,n4Mtm, mediaMtm, situacaoDisc, nomeAluno[0]))
if discProf == 'geografia':
print('Cadastre suas notas referentes a disciplina de geografia:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Geo = float(input("1ª nota de Geografia: "))
n2Geo = float(input("2ª nota de Geografia: "))
n3Geo = float(input("3ª nota de Geografia: "))
n4Geo = float(input("4ª nota de Geografia: "))
mediaGeo = (n1Geo+n2Geo+n3Geo+n4Geo)/4
if mediaGeo>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanob SET nota1geo={}, nota2geo={}, nota3geo={}, nota4geo={}, mediageo={}, situacaogeo='{}' WHERE nomealuno='{}'".format(n1Geo,n2Geo,n3Geo,n4Geo, mediaGeo, situacaoDisc, nomeAluno[0]))
if discProf == 'historia':
print('Cadastre suas notas referentes a disciplina de história:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Hst = float(input("1ª nota de História: "))
n2Hst = float(input("2ª nota de História: "))
n3Hst = float(input("3ª nota de História: "))
n4Hst = float(input("4ª nota de História: "))
mediaHst = (n1Hst+n2Hst+n3Hst+n4Hst)/4
if mediaHst>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanob SET nota1hst={}, nota2hst={}, nota3hst={}, nota4hst={}, mediahst={}, situacaohst WHERE nomealuno='{}'".format(n1Hst,n2Hst,n3Hst,n4Hst, mediaHst, situacaoDisc, nomeAluno[0]))
conectar.commit()
print('As notas foram cadastradas com sucesso!')
print("Retornando ao menu anterior...")
def cadastrarNotasAlunosPrimeiroAnoC():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
sqlSelecionarDisciplina ="SELECT disciplina FROM professor WHERE usuario='alex.barradas'"
for row in interagir.execute(sqlSelecionarDisciplina):
discProf = str(row[0])
print(discProf)
interagir.execute("SELECT nomealuno FROM primeiroanoc ORDER BY nomealuno")
if discProf == 'portugues':
print('Cadastre suas notas referentes a disciplina de português:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Prt = float(input("1ª nota de Português: "))
n2Prt = float(input("2ª nota de Português: "))
n3Prt = float(input("3ª nota de Português: "))
n4Prt = float(input("4ª nota de Português: "))
mediaPrt = (n1Prt+n2Prt+n3Prt+n4Prt)/4
if mediaPrt>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoc SET nota1prt={}, nota2prt={}, nota3prt={}, nota4prt={}, mediaprt={}, situacaoprt='{}' WHERE nomealuno='{}'".format(n1Prt,n2Prt,n3Prt,n4Prt, mediaPrt, situacaoDisc, nomeAluno[0], ))
conectar.commit()
if discProf == 'matematica':
print('Cadastre suas notas referentes a disciplina de matemática:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Mtm = float(input("1ª nota de Matemática: "))
n2Mtm = float(input("2ª nota de Matemática: "))
n3Mtm = float(input("3ª nota de Matemática: "))
n4Mtm = float(input("4ª nota de Matemática: "))
mediaMtm = (n1Mtm+n2Mtm+n3Mtm+n4Mtm)/4
if mediaMtm>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoc SET nota1mtm={}, nota2mtm={}, nota3mtm={}, nota4mtm={}, mediamtm={}, situacaomtm='{}' WHERE nomealuno='{}'".format(n1Mtm,n2Mtm,n3Mtm,n4Mtm, mediaMtm, situacaoDisc, nomeAluno[0]))
if discProf == 'geografia':
print('Cadastre suas notas referentes a disciplina de geografia:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Geo = float(input("1ª nota de Geografia: "))
n2Geo = float(input("2ª nota de Geografia: "))
n3Geo = float(input("3ª nota de Geografia: "))
n4Geo = float(input("4ª nota de Geografia: "))
mediaGeo = (n1Geo+n2Geo+n3Geo+n4Geo)/4
if mediaGeo>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoc SET nota1geo={}, nota2geo={}, nota3geo={}, nota4geo={}, mediageo={}, situacaogeo='{}' WHERE nomealuno='{}'".format(n1Geo,n2Geo,n3Geo,n4Geo, mediaGeo, situacaoDisc, nomeAluno[0]))
if discProf == 'historia':
print('Cadastre suas notas referentes a disciplina de história:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Hst = float(input("1ª nota de História: "))
n2Hst = float(input("2ª nota de História: "))
n3Hst = float(input("3ª nota de História: "))
n4Hst = float(input("4ª nota de História: "))
mediaHst = (n1Hst+n2Hst+n3Hst+n4Hst)/4
if mediaHst>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoc SET nota1hst={}, nota2hst={}, nota3hst={}, nota4hst={}, mediahst={}, situacaohst WHERE nomealuno='{}'".format(n1Hst,n2Hst,n3Hst,n4Hst, mediaHst, situacaoDisc, nomeAluno[0]))
conectar.commit()
print('As notas foram cadastradas com sucesso!')
print("Retornando ao menu anterior...")
def cadastrarNotasAlunosSegundoAnoA():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
sqlSelecionarDisciplina ="SELECT disciplina FROM professor WHERE usuario='alex.barradas'"
for row in interagir.execute(sqlSelecionarDisciplina):
discProf = str(row[0])
print(discProf)
interagir.execute("SELECT nomealuno FROM segundoanoa ORDER BY nomealuno")
if discProf == 'portugues':
print('Cadastre suas notas referentes a disciplina de português:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Prt = float(input("1ª nota de Português: "))
n2Prt = float(input("2ª nota de Português: "))
n3Prt = float(input("3ª nota de Português: "))
n4Prt = float(input("4ª nota de Português: "))
mediaPrt = (n1Prt+n2Prt+n3Prt+n4Prt)/4
if mediaPrt>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE segundoanoa SET nota1prt={}, nota2prt={}, nota3prt={}, nota4prt={}, mediaprt={}, situacaoprt='{}' WHERE nomealuno='{}'".format(n1Prt,n2Prt,n3Prt,n4Prt, mediaPrt, situacaoDisc, nomeAluno[0], ))
conectar.commit()
if discProf == 'matematica':
print('Cadastre suas notas referentes a disciplina de matemática:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Mtm = float(input("1ª nota de Matemática: "))
n2Mtm = float(input("2ª nota de Matemática: "))
n3Mtm = float(input("3ª nota de Matemática: "))
n4Mtm = float(input("4ª nota de Matemática: "))
mediaMtm = (n1Mtm+n2Mtm+n3Mtm+n4Mtm)/4
if mediaMtm>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE segundoanoa SET nota1mtm={}, nota2mtm={}, nota3mtm={}, nota4mtm={}, mediamtm={}, situacaomtm='{}' WHERE nomealuno='{}'".format(n1Mtm,n2Mtm,n3Mtm,n4Mtm, mediaMtm, situacaoDisc, nomeAluno[0]))
if discProf == 'geografia':
print('Cadastre suas notas referentes a disciplina de geografia:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Geo = float(input("1ª nota de Geografia: "))
n2Geo = float(input("2ª nota de Geografia: "))
n3Geo = float(input("3ª nota de Geografia: "))
n4Geo = float(input("4ª nota de Geografia: "))
mediaGeo = (n1Geo+n2Geo+n3Geo+n4Geo)/4
if mediaGeo>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE segundoanoa SET nota1geo={}, nota2geo={}, nota3geo={}, nota4geo={}, mediageo={}, situacaogeo='{}' WHERE nomealuno='{}'".format(n1Geo,n2Geo,n3Geo,n4Geo, mediaGeo, situacaoDisc, nomeAluno[0]))
if discProf == 'historia':
print('Cadastre suas notas referentes a disciplina de história:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Hst = float(input("1ª nota de História: "))
n2Hst = float(input("2ª nota de História: "))
n3Hst = float(input("3ª nota de História: "))
n4Hst = float(input("4ª nota de História: "))
mediaHst = (n1Hst+n2Hst+n3Hst+n4Hst)/4
if mediaHst>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE segundoanoa SET nota1hst={}, nota2hst={}, nota3hst={}, nota4hst={}, mediahst={}, situacaohst WHERE nomealuno='{}'".format(n1Hst,n2Hst,n3Hst,n4Hst, mediaHst, situacaoDisc, nomeAluno[0]))
conectar.commit()
print('As notas foram cadastradas com sucesso!')
print("Retornando ao menu anterior...")
def cadastrarNotasAlunosPrimeiroAnoA():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
sqlSelecionarDisciplina ="SELECT disciplina FROM professor WHERE usuario='alex.barradas'"
for row in interagir.execute(sqlSelecionarDisciplina):
discProf = str(row[0])
print(discProf)
interagir.execute("SELECT nomealuno FROM primeiroanoa ORDER BY nomealuno")
if discProf == 'portugues':
print('Cadastre suas notas referentes a disciplina de português:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Prt = float(input("1ª nota de Português: "))
n2Prt = float(input("2ª nota de Português: "))
n3Prt = float(input("3ª nota de Português: "))
n4Prt = float(input("4ª nota de Português: "))
mediaPrt = (n1Prt+n2Prt+n3Prt+n4Prt)/4
if mediaPrt>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1prt={}, nota2prt={}, nota3prt={}, nota4prt={}, mediaprt={}, situacaoprt='{}' WHERE nomealuno='{}'".format(n1Prt,n2Prt,n3Prt,n4Prt, mediaPrt, situacaoDisc, nomeAluno[0], ))
conectar.commit()
if discProf == 'matematica':
print('Cadastre suas notas referentes a disciplina de matemática:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Mtm = float(input("1ª nota de Matemática: "))
n2Mtm = float(input("2ª nota de Matemática: "))
n3Mtm = float(input("3ª nota de Matemática: "))
n4Mtm = float(input("4ª nota de Matemática: "))
mediaMtm = (n1Mtm+n2Mtm+n3Mtm+n4Mtm)/4
if mediaMtm>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1mtm={}, nota2mtm={}, nota3mtm={}, nota4mtm={}, mediamtm={}, situacaomtm='{}' WHERE nomealuno='{}'".format(n1Mtm,n2Mtm,n3Mtm,n4Mtm, mediaMtm, situacaoDisc, nomeAluno[0]))
if discProf == 'geografia':
print('Cadastre suas notas referentes a disciplina de geografia:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Geo = float(input("1ª nota de Geografia: "))
n2Geo = float(input("2ª nota de Geografia: "))
n3Geo = float(input("3ª nota de Geografia: "))
n4Geo = float(input("4ª nota de Geografia: "))
mediaGeo = (n1Geo+n2Geo+n3Geo+n4Geo)/4
if mediaGeo>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1geo={}, nota2geo={}, nota3geo={}, nota4geo={}, mediageo={}, situacaogeo='{}' WHERE nomealuno='{}'".format(n1Geo,n2Geo,n3Geo,n4Geo, mediaGeo, situacaoDisc, nomeAluno[0]))
if discProf == 'historia':
print('Cadastre suas notas referentes a disciplina de história:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Hst = float(input("1ª nota de História: "))
n2Hst = float(input("2ª nota de História: "))
n3Hst = float(input("3ª nota de História: "))
n4Hst = float(input("4ª nota de História: "))
mediaHst = (n1Hst+n2Hst+n3Hst+n4Hst)/4
if mediaHst>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1hst={}, nota2hst={}, nota3hst={}, nota4hst={}, mediahst={}, situacaohst WHERE nomealuno='{}'".format(n1Hst,n2Hst,n3Hst,n4Hst, mediaHst, situacaoDisc, nomeAluno[0]))
conectar.commit()
print('As notas foram cadastradas com sucesso!')
print("Retornando ao menu anterior...")
def cadastrarNotasAlunosSegundoAnoB():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
sqlSelecionarDisciplina ="SELECT disciplina FROM professor WHERE usuario='alex.barradas'"
for row in interagir.execute(sqlSelecionarDisciplina):
discProf = str(row[0])
print(discProf)
interagir.execute("SELECT nomealuno FROM segundoanob ORDER BY nomealuno")
if discProf == 'portugues':
print('Cadastre suas notas referentes a disciplina de português:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Prt = float(input("1ª nota de Português: "))
n2Prt = float(input("2ª nota de Português: "))
n3Prt = float(input("3ª nota de Português: "))
n4Prt = float(input("4ª nota de Português: "))
mediaPrt = (n1Prt+n2Prt+n3Prt+n4Prt)/4
if mediaPrt>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE segundoanob SET nota1prt={}, nota2prt={}, nota3prt={}, nota4prt={}, mediaprt={}, situacaoprt='{}' WHERE nomealuno='{}'".format(n1Prt,n2Prt,n3Prt,n4Prt, mediaPrt, situacaoDisc, nomeAluno[0], ))
conectar.commit()
if discProf == 'matematica':
print('Cadastre suas notas referentes a disciplina de matemática:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Mtm = float(input("1ª nota de Matemática: "))
n2Mtm = float(input("2ª nota de Matemática: "))
n3Mtm = float(input("3ª nota de Matemática: "))
n4Mtm = float(input("4ª nota de Matemática: "))
mediaMtm = (n1Mtm+n2Mtm+n3Mtm+n4Mtm)/4
if mediaMtm>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE segundoanob SET nota1mtm={}, nota2mtm={}, nota3mtm={}, nota4mtm={}, mediamtm={}, situacaomtm='{}' WHERE nomealuno='{}'".format(n1Mtm,n2Mtm,n3Mtm,n4Mtm, mediaMtm, situacaoDisc, nomeAluno[0]))
if discProf == 'geografia':
print('Cadastre suas notas referentes a disciplina de geografia:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Geo = float(input("1ª nota de Geografia: "))
n2Geo = float(input("2ª nota de Geografia: "))
n3Geo = float(input("3ª nota de Geografia: "))
n4Geo = float(input("4ª nota de Geografia: "))
mediaGeo = (n1Geo+n2Geo+n3Geo+n4Geo)/4
if mediaGeo>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE segundoanob SET nota1geo={}, nota2geo={}, nota3geo={}, nota4geo={}, mediageo={}, situacaogeo='{}' WHERE nomealuno='{}'".format(n1Geo,n2Geo,n3Geo,n4Geo, mediaGeo, situacaoDisc, nomeAluno[0]))
if discProf == 'historia':
print('Cadastre suas notas referentes a disciplina de história:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Hst = float(input("1ª nota de História: "))
n2Hst = float(input("2ª nota de História: "))
n3Hst = float(input("3ª nota de História: "))
n4Hst = float(input("4ª nota de História: "))
mediaHst = (n1Hst+n2Hst+n3Hst+n4Hst)/4
if mediaHst>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE segundoanob SET nota1hst={}, nota2hst={}, nota3hst={}, nota4hst={}, mediahst={}, situacaohst WHERE nomealuno='{}'".format(n1Hst,n2Hst,n3Hst,n4Hst, mediaHst, situacaoDisc, nomeAluno[0]))
conectar.commit()
print('As notas foram cadastradas com sucesso!')
print("Retornando ao menu anterior...")
def cadastrarNotasAlunosPrimeiroAnoA():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
sqlSelecionarDisciplina ="SELECT disciplina FROM professor WHERE usuario='alex.barradas'"
for row in interagir.execute(sqlSelecionarDisciplina):
discProf = str(row[0])
print(discProf)
interagir.execute("SELECT nomealuno FROM primeiroanoa ORDER BY nomealuno")
if discProf == 'portugues':
print('Cadastre suas notas referentes a disciplina de português:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Prt = float(input("1ª nota de Português: "))
n2Prt = float(input("2ª nota de Português: "))
n3Prt = float(input("3ª nota de Português: "))
n4Prt = float(input("4ª nota de Português: "))
mediaPrt = (n1Prt+n2Prt+n3Prt+n4Prt)/4
if mediaPrt>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1prt={}, nota2prt={}, nota3prt={}, nota4prt={}, mediaprt={}, situacaoprt='{}' WHERE nomealuno='{}'".format(n1Prt,n2Prt,n3Prt,n4Prt, mediaPrt, situacaoDisc, nomeAluno[0], ))
conectar.commit()
if discProf == 'matematica':
print('Cadastre suas notas referentes a disciplina de matemática:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Mtm = float(input("1ª nota de Matemática: "))
n2Mtm = float(input("2ª nota de Matemática: "))
n3Mtm = float(input("3ª nota de Matemática: "))
n4Mtm = float(input("4ª nota de Matemática: "))
mediaMtm = (n1Mtm+n2Mtm+n3Mtm+n4Mtm)/4
if mediaMtm>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1mtm={}, nota2mtm={}, nota3mtm={}, nota4mtm={}, mediamtm={}, situacaomtm='{}' WHERE nomealuno='{}'".format(n1Mtm,n2Mtm,n3Mtm,n4Mtm, mediaMtm, situacaoDisc, nomeAluno[0]))
if discProf == 'geografia':
print('Cadastre suas notas referentes a disciplina de geografia:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Geo = float(input("1ª nota de Geografia: "))
n2Geo = float(input("2ª nota de Geografia: "))
n3Geo = float(input("3ª nota de Geografia: "))
n4Geo = float(input("4ª nota de Geografia: "))
mediaGeo = (n1Geo+n2Geo+n3Geo+n4Geo)/4
if mediaGeo>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1geo={}, nota2geo={}, nota3geo={}, nota4geo={}, mediageo={}, situacaogeo='{}' WHERE nomealuno='{}'".format(n1Geo,n2Geo,n3Geo,n4Geo, mediaGeo, situacaoDisc, nomeAluno[0]))
if discProf == 'historia':
print('Cadastre suas notas referentes a disciplina de história:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Hst = float(input("1ª nota de História: "))
n2Hst = float(input("2ª nota de História: "))
n3Hst = float(input("3ª nota de História: "))
n4Hst = float(input("4ª nota de História: "))
mediaHst = (n1Hst+n2Hst+n3Hst+n4Hst)/4
if mediaHst>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE primeiroanoa SET nota1hst={}, nota2hst={}, nota3hst={}, nota4hst={}, mediahst={}, situacaohst WHERE nomealuno='{}'".format(n1Hst,n2Hst,n3Hst,n4Hst, mediaHst, situacaoDisc, nomeAluno[0]))
conectar.commit()
print('As notas foram cadastradas com sucesso!')
print("Retornando ao menu anterior...")
def cadastrarNotasAlunosTerceiroAnoA():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
sqlSelecionarDisciplina ="SELECT disciplina FROM professor WHERE usuario='alex.barradas'"
for row in interagir.execute(sqlSelecionarDisciplina):
discProf = str(row[0])
print(discProf)
interagir.execute("SELECT nomealuno FROM terceiroanoa ORDER BY nomealuno")
if discProf == 'portugues':
print('Cadastre suas notas referentes a disciplina de português:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Prt = float(input("1ª nota de Português: "))
n2Prt = float(input("2ª nota de Português: "))
n3Prt = float(input("3ª nota de Português: "))
n4Prt = float(input("4ª nota de Português: "))
mediaPrt = (n1Prt+n2Prt+n3Prt+n4Prt)/4
if mediaPrt>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanoa SET nota1prt={}, nota2prt={}, nota3prt={}, nota4prt={}, mediaprt={}, situacaoprt='{}' WHERE nomealuno='{}'".format(n1Prt,n2Prt,n3Prt,n4Prt, mediaPrt, situacaoDisc, nomeAluno[0], ))
conectar.commit()
if discProf == 'matematica':
print('Cadastre suas notas referentes a disciplina de matemática:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Mtm = float(input("1ª nota de Matemática: "))
n2Mtm = float(input("2ª nota de Matemática: "))
n3Mtm = float(input("3ª nota de Matemática: "))
n4Mtm = float(input("4ª nota de Matemática: "))
mediaMtm = (n1Mtm+n2Mtm+n3Mtm+n4Mtm)/4
if mediaMtm>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanoa SET nota1mtm={}, nota2mtm={}, nota3mtm={}, nota4mtm={}, mediamtm={}, situacaomtm='{}' WHERE nomealuno='{}'".format(n1Mtm,n2Mtm,n3Mtm,n4Mtm, mediaMtm, situacaoDisc, nomeAluno[0]))
if discProf == 'geografia':
print('Cadastre suas notas referentes a disciplina de geografia:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Geo = float(input("1ª nota de Geografia: "))
n2Geo = float(input("2ª nota de Geografia: "))
n3Geo = float(input("3ª nota de Geografia: "))
n4Geo = float(input("4ª nota de Geografia: "))
mediaGeo = (n1Geo+n2Geo+n3Geo+n4Geo)/4
if mediaGeo>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanoa SET nota1geo={}, nota2geo={}, nota3geo={}, nota4geo={}, mediageo={}, situacaogeo='{}' WHERE nomealuno='{}'".format(n1Geo,n2Geo,n3Geo,n4Geo, mediaGeo, situacaoDisc, nomeAluno[0]))
if discProf == 'historia':
print('Cadastre suas notas referentes a disciplina de história:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Hst = float(input("1ª nota de História: "))
n2Hst = float(input("2ª nota de História: "))
n3Hst = float(input("3ª nota de História: "))
n4Hst = float(input("4ª nota de História: "))
mediaHst = (n1Hst+n2Hst+n3Hst+n4Hst)/4
if mediaHst>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanoa SET nota1hst={}, nota2hst={}, nota3hst={}, nota4hst={}, mediahst={}, situacaohst WHERE nomealuno='{}'".format(n1Hst,n2Hst,n3Hst,n4Hst, mediaHst, situacaoDisc, nomeAluno[0]))
conectar.commit()
print('As notas foram cadastradas com sucesso!')
print("Retornando ao menu anterior...")
def cadastrarNotasAlunosTerceiroAnoB():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
sqlSelecionarDisciplina ="SELECT disciplina FROM professor WHERE usuario='alex.barradas'"
for row in interagir.execute(sqlSelecionarDisciplina):
discProf = str(row[0])
print(discProf)
interagir.execute("SELECT nomealuno FROM terceiroanob ORDER BY nomealuno")
if discProf == 'portugues':
print('Cadastre suas notas referentes a disciplina de português:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Prt = float(input("1ª nota de Português: "))
n2Prt = float(input("2ª nota de Português: "))
n3Prt = float(input("3ª nota de Português: "))
n4Prt = float(input("4ª nota de Português: "))
mediaPrt = (n1Prt+n2Prt+n3Prt+n4Prt)/4
if mediaPrt>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanob SET nota1prt={}, nota2prt={}, nota3prt={}, nota4prt={}, mediaprt={}, situacaoprt='{}' WHERE nomealuno='{}'".format(n1Prt,n2Prt,n3Prt,n4Prt, mediaPrt, situacaoDisc, nomeAluno[0], ))
conectar.commit()
if discProf == 'matematica':
print('Cadastre suas notas referentes a disciplina de matemática:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Mtm = float(input("1ª nota de Matemática: "))
n2Mtm = float(input("2ª nota de Matemática: "))
n3Mtm = float(input("3ª nota de Matemática: "))
n4Mtm = float(input("4ª nota de Matemática: "))
mediaMtm = (n1Mtm+n2Mtm+n3Mtm+n4Mtm)/4
if mediaMtm>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanob SET nota1mtm={}, nota2mtm={}, nota3mtm={}, nota4mtm={}, mediamtm={}, situacaomtm='{}' WHERE nomealuno='{}'".format(n1Mtm,n2Mtm,n3Mtm,n4Mtm, mediaMtm, situacaoDisc, nomeAluno[0]))
if discProf == 'geografia':
print('Cadastre suas notas referentes a disciplina de geografia:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Geo = float(input("1ª nota de Geografia: "))
n2Geo = float(input("2ª nota de Geografia: "))
n3Geo = float(input("3ª nota de Geografia: "))
n4Geo = float(input("4ª nota de Geografia: "))
mediaGeo = (n1Geo+n2Geo+n3Geo+n4Geo)/4
if mediaGeo>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanob SET nota1geo={}, nota2geo={}, nota3geo={}, nota4geo={}, mediageo={}, situacaogeo='{}' WHERE nomealuno='{}'".format(n1Geo,n2Geo,n3Geo,n4Geo, mediaGeo, situacaoDisc, nomeAluno[0]))
if discProf == 'historia':
print('Cadastre suas notas referentes a disciplina de história:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Hst = float(input("1ª nota de História: "))
n2Hst = float(input("2ª nota de História: "))
n3Hst = float(input("3ª nota de História: "))
n4Hst = float(input("4ª nota de História: "))
mediaHst = (n1Hst+n2Hst+n3Hst+n4Hst)/4
if mediaHst>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanob SET nota1hst={}, nota2hst={}, nota3hst={}, nota4hst={}, mediahst={}, situacaohst WHERE nomealuno='{}'".format(n1Hst,n2Hst,n3Hst,n4Hst, mediaHst, situacaoDisc, nomeAluno[0]))
conectar.commit()
print('As notas foram cadastradas com sucesso!')
print("Retornando ao menu anterior...")
def cadastrarNotasAlunosTerceiroAnoC():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
sqlSelecionarDisciplina ="SELECT disciplina FROM professor WHERE usuario='alex.barradas'"
for row in interagir.execute(sqlSelecionarDisciplina):
discProf = str(row[0])
print(discProf)
interagir.execute("SELECT nomealuno FROM terceiroanoc ORDER BY nomealuno")
if discProf == 'portugues':
print('Cadastre suas notas referentes a disciplina de português:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Prt = float(input("1ª nota de Português: "))
n2Prt = float(input("2ª nota de Português: "))
n3Prt = float(input("3ª nota de Português: "))
n4Prt = float(input("4ª nota de Português: "))
mediaPrt = (n1Prt+n2Prt+n3Prt+n4Prt)/4
if mediaPrt>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanoc SET nota1prt={}, nota2prt={}, nota3prt={}, nota4prt={}, mediaprt={}, situacaoprt='{}' WHERE nomealuno='{}'".format(n1Prt,n2Prt,n3Prt,n4Prt, mediaPrt, situacaoDisc, nomeAluno[0], ))
conectar.commit()
if discProf == 'matematica':
print('Cadastre suas notas referentes a disciplina de matemática:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Mtm = float(input("1ª nota de Matemática: "))
n2Mtm = float(input("2ª nota de Matemática: "))
n3Mtm = float(input("3ª nota de Matemática: "))
n4Mtm = float(input("4ª nota de Matemática: "))
mediaMtm = (n1Mtm+n2Mtm+n3Mtm+n4Mtm)/4
if mediaMtm>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanoc SET nota1mtm={}, nota2mtm={}, nota3mtm={}, nota4mtm={}, mediamtm={}, situacaomtm='{}' WHERE nomealuno='{}'".format(n1Mtm,n2Mtm,n3Mtm,n4Mtm, mediaMtm, situacaoDisc, nomeAluno[0]))
if discProf == 'geografia':
print('Cadastre suas notas referentes a disciplina de geografia:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Geo = float(input("1ª nota de Geografia: "))
n2Geo = float(input("2ª nota de Geografia: "))
n3Geo = float(input("3ª nota de Geografia: "))
n4Geo = float(input("4ª nota de Geografia: "))
mediaGeo = (n1Geo+n2Geo+n3Geo+n4Geo)/4
if mediaGeo>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanoc SET nota1geo={}, nota2geo={}, nota3geo={}, nota4geo={}, mediageo={}, situacaogeo='{}' WHERE nomealuno='{}'".format(n1Geo,n2Geo,n3Geo,n4Geo, mediaGeo, situacaoDisc, nomeAluno[0]))
if discProf == 'historia':
print('Cadastre suas notas referentes a disciplina de história:')
for nomeAluno in interagir.fetchall():
print("Aluno: {}".format(nomeAluno[0]))
n1Hst = float(input("1ª nota de História: "))
n2Hst = float(input("2ª nota de História: "))
n3Hst = float(input("3ª nota de História: "))
n4Hst = float(input("4ª nota de História: "))
mediaHst = (n1Hst+n2Hst+n3Hst+n4Hst)/4
if mediaHst>=7:
situacaoDisc = 'APROVADO'
else:
situacaoDisc = 'REPROVADO'
interagir.execute("UPDATE terceiroanoc SET nota1hst={}, nota2hst={}, nota3hst={}, nota4hst={}, mediahst={}, situacaohst WHERE nomealuno='{}'".format(n1Hst,n2Hst,n3Hst,n4Hst, mediaHst, situacaoDisc, nomeAluno[0]))
conectar.commit()
print('As notas foram cadastradas com sucesso!')
print("Retornando ao menu anterior...")
### funções que vão salvar os nomes dos alunos(tarefa do coordenador) no banco de dados SQLlite3 do sistema ###
def cadastrarPrimeiroAnoA():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
quantidadeAlunos = int(input('Informe quantidade de alunos a serem cadastrados na turma: '))
turma = 'primeiro ano turma A'
for contador in range(0,quantidadeAlunos):
nomeAluno = input("Informe o nome completo do aluno(a): ")
sqlCadastroNomeAluno = "INSERT INTO primeiroanoa(nomealuno) VALUES ('{}')".format(nomeAluno)
interagir.execute(sqlCadastroNomeAluno)
print("Aluno(a) {} cadastrado com sucesso no {}!".format(nomeAluno,turma))
print("Os alunos foram cadastrados com sucesso! \nlista de alunos cadastrados no {}".format(turma))
conectar.commit()
import coordenadorPedagogico
coordenadorPedagogico.menuCoordenador()
def cadastrarPrimeiroAnoB():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
quantidadeAlunos = int(input('Informe quantidade de alunos presentes na turma: '))
turma = 'primeiro ano turma B'
for contador in range(0,quantidadeAlunos):
nomeAluno = input("nome do aluno: ")
sqlCadastroNomeAluno = "INSERT INTO primeiroanob(nomealuno) VALUES ('{}')".format(nomeAluno)
interagir.execute(sqlCadastroNomeAluno)
print("Aluno(a) {} cadastrado com sucesso no {}!".format(nomeAluno,turma))
print("Os alunos foram cadastrados com sucesso! \nlista de alunos cadastrados no {}".format(turma))
conectar.commit()
import coordenadorPedagogico
coordenadorPedagogico.menuCoordenador()
def cadastrarPrimeiroAnoC():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
quantidadeAlunos = int(input('Informe quantidade de alunos presentes na turma: '))
turma = 'primeiro ano turma C'
for contador in range(0,quantidadeAlunos):
nomeAluno = input("nome do aluno: ")
sqlCadastroNomeAluno = "INSERT INTO primeiroanoc(nomealuno) VALUES ('{}')".format(nomeAluno)
interagir.execute(sqlCadastroNomeAluno)
print("Aluno(a) {} cadastrado com sucesso no {}!".format(nomeAluno,turma))
print("Os alunos foram cadastrados com sucesso! \nlista de alunos cadastrados no {}".format(turma))
conectar.commit()
import coordenadorPedagogico
coordenadorPedagogico.menuCoordenador()
def cadastrarSegundoAnoA():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
quantidadeAlunos = int(input('Informe quantidade de alunos presentes na turma: '))
turma = 'segundo ano turma A'
for contador in range(0,quantidadeAlunos):
nomeAluno = input("nome do aluno: ")
sqlCadastroNomeAluno = "INSERT INTO segundoanoa(nomealuno) VALUES ('{}')".format(nomeAluno)
interagir.execute(sqlCadastroNomeAluno)
print("Aluno(a) {} cadastrado com sucesso no {}!".format(nomeAluno,turma))
print("Os alunos foram cadastrados com sucesso! \nlista de alunos cadastrados no {}".format(turma))
conectar.commit()
import coordenadorPedagogico
coordenadorPedagogico.menuCoordenador()
def cadastrarSegundoAnoB():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
quantidadeAlunos = int(input('Informe quantidade de alunos presentes na turma: '))
turma = 'segundo ano turma B'
for contador in range(0,quantidadeAlunos):
nomeAluno = input("nome do aluno: ")
sqlCadastroNomeAluno = "INSERT INTO segundoanob(nomealuno) VALUES ('{}')".format(nomeAluno)
interagir.execute(sqlCadastroNomeAluno)
print("Aluno(a) {} cadastrado com sucesso no {}!".format(nomeAluno,turma))
conectar.commit()
import coordenadorPedagogico
coordenadorPedagogico.menuCoordenador()
def cadastrarSegundoAnoC():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
quantidadeAlunos = int(input('Informe quantidade de alunos presentes na turma: '))
turma = 'segundo ano turma C'
for contador in range(0,quantidadeAlunos):
nomeAluno = input("nome do aluno: ")
sqlCadastroNomeAluno = "INSERT INTO segundoanoc(nomealuno) VALUES ('{}')".format(nomeAluno)
interagir.execute(sqlCadastroNomeAluno)
print("Aluno(a) {} cadastrado com sucesso no {}!".format(nomeAluno,turma))
conectar.commit()
import coordenadorPedagogico
coordenadorPedagogico.menuCoordenador()
def cadastrarTerceiroAnoA():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
quantidadeAlunos = int(input('Informe quantidade de alunos presentes na turma: '))
turma = 'terceiro ano turma A'
for contador in range(0,quantidadeAlunos):
nomeAluno = input("nome do aluno: ")
sqlCadastroNomeAluno = "INSERT INTO terceiroanoa(nomealuno) VALUES ('{}')".format(nomeAluno)
interagir.execute(sqlCadastroNomeAluno)
print("Aluno(a) {} cadastrado com sucesso no {}!".format(nomeAluno,turma))
conectar.commit()
import coordenadorPedagogico
coordenadorPedagogico.menuCoordenador()
def cadastrarTerceiroAnoB():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
quantidadeAlunos = int(input('Informe quantidade de alunos presentes na turma: '))
turma = 'terceiro ano turma B'
for contador in range(0,quantidadeAlunos):
nomeAluno = input("nome do aluno: ")
sqlCadastroNomeAluno = "INSERT INTO terceiroanob(nomealuno) VALUES ('{}')".format(nomeAluno)
interagir.execute(sqlCadastroNomeAluno)
print("Aluno(a) {} cadastrado com sucesso no {}!".format(nomeAluno,turma))
conectar.commit()
import coordenadorPedagogico
coordenadorPedagogico.menuCoordenador()
def cadastrarTerceiroAnoC():
import sqlite3
conectar = sqlite3.connect("bancodeDados.db")
interagir = conectar.cursor()
quantidadeAlunos = int(input('Informe quantidade de alunos presentes na turma: '))
turma = 'terceiro ano turma C'
for contador in range(0,quantidadeAlunos):
nomeAluno = input("nome do aluno: ")
sqlCadastroNomeAluno = "INSERT INTO terceiroanoc(nomealuno) VALUES ('{}')".format(nomeAluno)
interagir.execute(sqlCadastroNomeAluno)
print("Aluno(a) {} cadastrado com sucesso no {}!".format(nomeAluno,turma))
conectar.commit()
import coordenadorPedagogico
coordenadorPedagogico.menuCoordenador()
|
649775ab8379b634ce41de17027514c2de97ae6d | spen0t/Honap-Nap | /honapos_vegleges.py | 662 | 3.6875 | 4 | honapok= ["Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"]
napok=[31,29,31,30,31,30,31,31,30,31,30,31]
h=input("Hónap: ")
n=input("Nap: ")
def szamHiba():
try:
int(n)
return True
except ValueError:
return False
def napHiba():
nap=int(n)
index=honapok.index(h)
napmax=napok[index]
if nap>=napmax and nap<0:
return False
if szamHiba()==False:
print("Hiba")
elif h not in honapok:
print("Hiba")
elif napHiba()==False:
print("Hiba")
else:
print("{} {}.".format(h,n))
|
01fcaaf1d2c6c6f9c785e619296e247dbaab938f | sthomen/pyselcall | /pyselcall/tones/square.py | 538 | 3.578125 | 4 | from math import floor
from .tone import Tone
class Square(Tone):
"""
This class continually produces a 50% duty cycle square wave centered in
the cycle (meaning it starts at halfway through the low cycle and then
shifts to high for 50% of the cycle and then back down to 0 at 75%.
"""
def __iter__(self):
switch = (self.rate / self.frequency) / 2
value = 0
x = switch / 2
while True:
if floor(x % switch) == 0:
value = self.high if value == self.low else self.low
x += 1
yield value
|
718ca423c56962b1cff82428ccd57e9b4dfece98 | FarukOmerB/Problem-Solving | /patika/patika_python_project.py | 687 | 3.90625 | 4 | # Ömer Faruk BAYSAL -- Patika Python Project
#%% Part 1
def flatten(inp):
"""
Recursive flatten function
"""
out=[]
for i in inp:
if type(i)==list:
[out.append(j) for j in flatten(i)]
else:
out.append(i)
return out;
inp= [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
print("Output of Part 1:",flatten(inp))
#%% Part 2
def listReverser(l):
"""
Recursive list reversing function
"""
if type(l)!=list:
return None
l.reverse()
for i in l:
listReverser(i)
inp=[[1, 2], [3, 4], [5, 6, 7]]
listReverser(inp)
print("Output of Part 2:",inp)
# %%
|
50e51ae174b51f47736e94d3c33d29921573894e | hellothisisnathan/Brain-Efficiency | /monte carlo/starter monte carlo.py | 1,041 | 3.75 | 4 | import numpy as np
import math
import random
from matplotlib import pyplot as plt
from IPython.display import clear_output
x = np.linspace(0, 100, 2000)
y = (1/7)*np.sqrt(2500+np.power(x,2))+(1/2)*np.sqrt(2500+np.power((100-x),2))
def get_rand_num(min_val, max_val):
range = max_val - min_val
choice = random.uniform(0,1)
return min_val + range * choice
def f_of_x(x):
"""
This is the main function we want to integrate over.
Args:
- x (float) : input to function; must be in radians
Return:
- output of function f(x) (float)
"""
return (1/7)*np.sqrt(2500+np.power(x,2))+(1/2)*np.sqrt(2500+np.power((100-x),2))
def crude_monte_carlo(num_samples=5000):
lower_bound = 0
upper_bound = 100
min = np.inf
s = 0
for i in range(num_samples):
x = get_rand_num(lower_bound, upper_bound)
f = f_of_x(x)
if min > f:
min = f
s = x
return min, s
f,s = crude_monte_carlo(10000)
print(s, f)
plt.plot(x, y)
plt.plot(s,f, 'ro')
plt.show() |
a251923e6e161f12d54d117338cafb68a2b24961 | whhxz/leetcode | /python3/0435_non-overlapping-intervals.py | 445 | 3.5 | 4 | from typing import List
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
if not intervals:
return 0
intervals.sort(key=lambda x: (x[1], x[0]))
before = intervals[0]
res = 0
for i in range(1, len(intervals)):
if intervals[i][0] < before[1]:
res += 1
else:
before = intervals[i]
return res
|
157f5e9d58d469789db3ed60dfebec534cf5da61 | YaroslavBulgakov/study | /beetroot_dz/linked_list.py | 5,964 | 4.03125 | 4 | class Stack():
def __init__(self):
self.list=[]
def push(self,data):
self.list.append(data)
def pop(self):
return self.list.pop()
def get(self):
return self.list
mystack=Stack()
mystack.push('Data1')
mystack.push('Data2')
print(mystack.pop())
print(mystack.get())
class ListNode:
def __init__(self,data=None,next=None):
self.data=data
self.next=next
class LinkedList:
def __init__(self):
#Голова или корень - это последний узел ну пока просто ее нет точнее начало слева
self.head = None
self.size=0
#Проверим есть ли какие-то данные в определнной коробке
def push(self,data):
#Вот тут происходит следующие когда мы первый раз вставляем то естественно это будет голова и данные
#Как бы хеад у нас постоянно затирается и в нем вроде бы всегда 1 элемент, но во втором значении содержиться как бы элемент который был до этого
#ну на самом деле просто указатель на него то есть как бы пришла новая коробка и мы предудущую засунули во второе отделение, потом еще пришла и мы вторую коробку содержащую первую засунули
#в третью
#Поместили первый например он никуда не ссылкается Data1-->None
#потом когда помещаем сторой self.head помещается в его свойство next
self.head=ListNode(data,next=self.head)
self.size+=1
def __repr__(self):
#Помним что во втором значении некст
next_node=self.head
res=''
#Вот этот алгоритм применим для много
while next_node:
#Каждый раз вынимаем другой объект
res+=str(next_node.data)+'-->'
next_node=next_node.next
return res
def delete(self,value):
this_node=self.head
prev_node=None
#Листаем
while this_node:
#Типа нашли нужный элемент
if this_node.data==value:
#Если предыдущая нода не пуста то нам нужно
if prev_node is not None:
prev_node.next=this_node.next
#Если же он пустой то значит это начальный
else:
self.head=this_node.next
self.size-=1
return True
#В конце уикла присваиваем предудущей ноде текущую а текущей следующую если не нашли
else:
prev_node=this_node
this_node=this_node.next
return False
def contains(self,value):
#В принипе также листаем если хотим найти что нибудь
this_node=self.head
#Так в принципе понятно мы листаем
while this_node:
if this_node.data==value:
return True
this_node=this_node.next
return False
class Double_Node:
def __init__(self,data,prev=None,next=None):
self.data=data
self.prev=prev
self.next=next
class DoubleLinkedList:
def __init__(self):
self.head=None
def push(self,data):
#Итак поместили первый элемент Data1 у него в нект поле будет Ноне
#помещаем Data2 у него в некст уже будет объект Data1
#помещем Data3 у него в поле некст будет обїект Data2 а у Data2-->Data1
#Поулчается нектс-ноде идет на уменьшение т.е 4 prev--->3-->2 next а 4 это будет прев
new=Double_Node(data,next=self.head)
#Если элемент первый то соответсвенно предыдущего у него нет а следующий будет None
'''
if self.head is None:
new.prev=None
if self.head:
self.head.prev=new
self.head=new
'''
if self.head:
self.head.prev = new
self.head = new
def __repr__(self):
prev=self.head
st=''
while prev:
st+=str(prev.data)+'<--'+str(prev.next.data)+'-->'
prev=prev.prev
return st
def print_list(self):
next_node = self.head
res = ''
# Вот этот алгоритм применим для много
while next_node:
# Каждый раз вынимаем другой объект
res += str(next_node.data) + '-->'
next_node = next_node.next
return res
#Нам не жуно создавать специально объекты этого класса они создаются в методе add класса LinkedList
mylist=LinkedList()
mylist.push('Data1')
mylist.push('Data2')
mylist.push('Data3')
mylist.push('Data4')
print(mylist)
print(mylist.contains('Data1'))
print(mylist.contains('Data5'))
mylist.delete('Data2')
print(mylist)
print('---------Double Linked List----------')
mylist2=DoubleLinkedList()
mylist2.push('Double1')
mylist2.push('Double2')
mylist2.push('Double3')
mylist2.push('Double4')
print(mylist2)
print(mylist2.print_list()) |
8d0b9fcc6273c721e40b81a35c3c04e63180adb4 | YaroslavBulgakov/study | /beetroot_dz/linked_list2.py | 4,011 | 3.859375 | 4 | class Stack():
def __init__(self):
self.list=[]
def push(self,data):
self.list.append(data)
def pop(self):
return self.list.pop()
def get(self):
return self.list
mystack=Stack()
mystack.push('Data1')
mystack.push('Data2')
print(mystack.pop())
print(mystack.get())
class ListNode:
def __init__(self,data=None,next=None):
self.data=data
self.next=next
class LinkedList:
def __init__(self):
self.head = None
self.size=0
def push(self,data):
self.head=ListNode(data,next=self.head)
self.size+=1
def __repr__(self):
next_node=self.head
res=''
while next_node:
res+=str(next_node.data)+'-->'
next_node=next_node.next
return res
def delete(self,value):
this_node=self.head
prev_node=None
while this_node:
if this_node.data==value:
if prev_node is not None:
prev_node.next=this_node.next
else:
self.head=this_node.next
self.size-=1
return True
else:
prev_node=this_node
this_node=this_node.next
return False
def contains(self,value):
this_node=self.head
while this_node:
if this_node.data==value:
return True
this_node=this_node.next
return False
class Double_Node:
def __init__(self,data,prev=None,next=None):
self.data=data
self.prev=prev
self.next=next
class DoubleLinkedList:
def __init__(self):
self.head=None
def push(self,data):
new=Double_Node(data,next=self.head)
'''
if self.head is None:
new.prev=None
if self.head:
self.head.prev=new
self.head=new
'''
if self.head:
self.head.prev = new
self.head = new
def __repr__(self):
this_node=self.head
st=''
while this_node:
if this_node.prev and this_node.next:
st+='<--'+str(this_node.data)+'-->'
elif this_node.next:
st+=str(this_node.data)+'-->'
elif this_node.prev:
st += '<--' + str(this_node.data)
else:
st+=str(this_node.data)
this_node=this_node.next
return st
def delete(self,value):
this_node=self.head
next_node=None
prev_node=None
while this_node:
if this_node.data==value:
if this_node.prev:
this_node.prev.next=this_node.next
if this_node.next:
this_node.next.prev=this_node.prev
return True
this_node=this_node.next
return False
def contains(self,value):
this_node=self.head
while this_node:
if this_node.data==value:
return True
this_node=this_node.next
return False
def print_one_linked_list(self):
next_node = self.head
res = ''
while next_node:
res += str(next_node.data) + '-->'
next_node = next_node.next
return res
print('------------Linked list--------------')
mylist=LinkedList()
mylist.push('Data1')
mylist.push('Data2')
mylist.push('Data3')
mylist.push('Data4')
print(mylist)
print(mylist.contains('Data1'))
print(mylist.contains('Data5'))
mylist.delete('Data2')
print(mylist)
print('---------Double Linked List----------')
mylist2=DoubleLinkedList()
for i in range(1,8):
mylist2.push('Double{0}'.format(i))
print(mylist2)
print('List contains Double3? ',mylist2.contains('Double3'))
print('List contains Test? ',mylist2.contains('Test'))
#print(mylist2.print_list())
print('Delete Double3',mylist2.delete('Double3'))
print(mylist2)
print('Delete Double1',mylist2.delete('Double1'))
print(mylist2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.