blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
bedb2a2c70ec6fd13f34ff94a64e891bf4bc2011 | xuaijingwendy/Class-assignment-29 | /循环/while.py | 96 | 4 | 4 | count = 0
while(count<9):
print ('The count is:',count)
count=count+1
print("Good bye!") |
707e6fba10638bed204c624e0a36f8ced3361c52 | SmischenkoB/campus_2018_python | /Viktor_Miroshnychenko/2/armstrong_numbers.py | 631 | 4 | 4 | def is_amstrong_number(number):
"""
:param number: - number to check weather it is an amstrong number
:type number: - str or int
:return: - True if param1 is Amstrong number, False otherwise
:rtype: - bool
"""
if isinstance(number, int):
number = str(number)
power = len(number)
compare_val = 0
for digit in number:
digit = int(digit)
compare_val += digit ** power
number = int(number)
return number == compare_val
print(is_amstrong_number(9))
print(is_amstrong_number(10))
print(is_amstrong_number(153))
print(is_amstrong_number(1254))
|
54f6465964e4e96a7d5214571a6b087995f7df7c | gargshiva/Python-DataStructureAlgo | /search/RotatedArray.py | 1,364 | 4.15625 | 4 | # Search an element in sorted and rotated array
def find_element(arr, element):
end = len(arr) - 1
pivot_index = find_pivot_index(arr, 0, len(arr) - 1)
print("Pivot Index : {} ".format(pivot_index))
if arr[pivot_index] == element:
return pivot_index
elif arr[pivot_index + 1] <= element <= arr[end]:
return binary_search(arr, pivot_index + 1, end, element)
elif arr[0] <= element <= arr[pivot_index - 1]:
return binary_search(arr, 0, pivot_index - 1, element)
else:
return -1
def binary_search(arr, start, end, element):
mid = int((start + end) / 2)
if start > end:
return -1
elif arr[mid] == element:
return mid
elif arr[mid] > element:
return binary_search(arr, start, mid - 1, element)
else:
return binary_search(arr, mid + 1, end, element)
def find_pivot_index(arr, start, end):
mid = int((start + end) / 2)
if start > end:
return -1
elif arr[mid - 1] > arr[mid] < arr[mid + 1]:
return mid
elif arr[mid] < arr[end]:
return find_pivot_index(arr, start, mid - 1)
else:
return find_pivot_index(arr, mid + 1, end)
arr = [4, 5, 1, 2, 3]
print("Element found at Index : {}".format(find_element(arr, 3)))
arr = [3, 4, 5, 1, 2]
print("Element found at Index : {}".format(find_element(arr, 3)))
|
a8ce8ce0b486f7c7d7315ebbe69c6aa7d83bb1da | Anoopsmohan/Python-Recursion | /fact_tail.py | 89 | 3.796875 | 4 | def fact(f,n):
if n==1:
return f
else:
return fact(f*n,n-1)
a=fact(1,3)
print a
|
1fedad368df49d614f0dd93616a762794e071ce8 | TurcsanyAdam/Gitland | /if10.py | 371 | 4.03125 | 4 | A = int(input("Give length of A side: "))
B = int(input("Give length of B side: "))
C = int(input("Give length of C side: "))
if (A*A + B*B) == C*C:
print("Derékszögű a háromszög")
elif(A*A + C*C) == B*B:
print("Derékszögű a háromszög")
elif(B*B + C*C) == A*A:
print("Derékszögű a háromszög")
else:
print("Nem derékszögű a háromszög") |
98dc0711e54f8bab427585b0ca29fdbda326ae08 | jkcadee/A01166243_1510_labs | /Lab01/Valid and Invalid.py | 398 | 3.84375 | 4 | # 1. X = 1 is valid as you are just assigning an int value to a variable
# 2. X = Y is invali as Y does not have an assigned value
# 3. X = Y + 2 is invalid as Y does not have an assigned value
# 4. X + 1 = 3 is invalid as an operator cannot be on the variable side of an assignment
# 5. X + Y = Y + X is invalid as Y is not defined and an operator cannot be on the variable side of an assignment
|
4d32355a45ad4d23d1fcdacd2e6e76ab2f4aa38f | lucasjct/app-flask | /overview/aula4/views.py | 487 | 3.734375 | 4 | from flask import Flask, request
"""Extensão Flask"""
def init_app(app: Flask):
@app.route('/')
def index():
print(request.args)
return "Hello Codeshow"
@app.route('/contato')
def contato():
return "<form><input type='text'></input></form>"
def page_other(app: Flask):
@app.route('/lista')
def tabela():
return """<ul><li>Teste1</li>
<li>Teste2</li>
<li>Teste3</li></ul>""" |
f3ba86deeaf11d66c18813d381e74d3126905aa9 | ameeli/algorithms | /leetcode/range_sum_of_bst.py | 780 | 4.03125 | 4 | """
Given the root node of a binary search tree, return the sum of values of all
nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
Note:
The number of nodes in the tree is at most 10000.
The final answer is guaranteed to be less than 2^31.
"""
def find_range_sum_of_bst(root, l, r):
if not root:
return 0
if root.val < l:
return find_range_sum_of_bst(root.right)
elif root.val > r:
return find_range_sum_of_bst(root.left)
return root.val + find_range_sum_of_bst(
root.left) + find_range_sum_of_bst(root.right)
|
18da413dc6b5dfd2739d90f56474aa64d250a372 | jessicanina23/Jhessy | /Nina03.py | 167 | 4.0625 | 4 | # Calcular a área de uma circunferência
import math
raio = float(input("informe o raio: "))
area = math.pi * raio ** 2
print("Área do círculo", raio, "=", area)
|
6ba2ed11bb6c13d8677c76c45bb9a150f372100a | SI507-Waiver-Fall2018/si-507-waiver-assignment-f18-scarescrow | /part3.py | 1,810 | 3.75 | 4 | # these should be the only imports you need
import requests
from bs4 import BeautifulSoup
# My full name is Sagnik Sinha Roy
# My UMich uniqname is sagniksr
# write your code here
# usage should be python3 part3.py
URL = "https://www.michigandaily.com"
if __name__ == "__main__":
# First, use the HTTP GET method to get the HTML
# of the website
req = requests.get(URL)
html = req.text
req.close()
# Now convert it to a soup object
soup = BeautifulSoup(html, 'html.parser')
# Find the div of most read stories with
# a unique identifier
class_to_find = 'view-most-read'
most_read_div = soup.find('div', class_=class_to_find)
# Parse the div to get the text and links
# of the most read stories
most_read_list = most_read_div.find('ol').findAll('li')
most_read_stories = []
for listItem in most_read_list:
anchorTag = listItem.find('a')
storyObject = {
'link': anchorTag['href'],
'title': anchorTag.getText()
}
most_read_stories.append(storyObject)
# Iterate over the stories, and make an HTTP
# request for each link
class_to_find = 'byline'
for story in most_read_stories:
req = requests.get(URL + story['link'])
html = req.text
req.close()
soup = BeautifulSoup(html, 'html.parser')
# Now parse the html to get the name of the author
# print(story['link'])
try:
author_div = soup.find('div', class_=class_to_find)
author = author_div.find('a').getText()
story['author'] = author
except:
# Some articles under the news section do not have an author,
# so marking the author of those as Daily Staff Writer
story['author'] = 'Daily Staff Writer'
pass
# Finally, print result in the required format
print("Michigan Daily -- MOST READ")
for story in most_read_stories:
print(story['title'])
print(' by ' + story['author']) |
a4f9327fcbaeb8ab3a89f9624f244f51e5170728 | Hamiltonxx/pyalgorithms | /ds_tutorial/count_possible_paths.py | 187 | 3.5 | 4 |
def dfs(u,v,visited=[]):
visited.append(u)
for w in graph[u]:
if w==v:
return visited
elif w not in visited:
dfs(w,v,visited)
|
626bcc62f786c5cfb15559748a7cd7005d3e4a01 | Josh-Cruz/python-strings-and-list-prac | /PYthon_Dict_basics.py | 335 | 3.796875 | 4 | josh_C = {
"name": "Josh",
"age": 30,
"country": "Murica",
"fav_lan": "Python"
}
def print_info(dict):
print "My name is", dict["name"]
print "My age is", dict["age"]
print "My country of origin is", dict["country"]
print "My favorite language to code in is", dict["fav_lan"]
print(print_info(josh_C)) |
c55595f6e05e605302f2f111569d16f0d1f08eeb | w2kzx80/py_algs | /7/1.py | 1,441 | 3.953125 | 4 | # 1. Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, заданный случайными числами на
# промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы.
# Примечания:
# a. алгоритм сортировки должен быть в виде функции, которая принимает на вход массив данных,
# b. постарайтесь сделать алгоритм умнее, но помните, что у вас должна остаться сортировка пузырьком.
# Улучшенные версии сортировки, например, расчёской, шейкерная и другие в зачёт не идут.
import random
def mysort(array):
lastsorted = len(array)
for n in range(len(array) - 1):
chcount = 0
for i in range(lastsorted - 1):
if array[i] < array[i + 1]:
array[i], array[i + 1] = array[i + 1], array[i]
chcount += 1
lastsorted = i + 1
# print(f"Sorting {i} <=> {i+1}")
print(array)
if chcount == 0:
break
array = [random.randint(-100,100) for i in range(10)]
print(array)
print("="*50)
mysort(array)
print("="*50)
print(array)
|
5a1e6ef7f70370ee7372b8de5a1b00e64c5174c7 | deepakmanktalaomni/python | /check year.py | 821 | 3.96875 | 4 | y = int(input("Year: "))
m = int(input("Month: "))
d = int(input("Day: "))
if 0 <= y and 0 < m < 13 and 0 < d < 32: #Check whether date is under limit.
if m in (4,6,9,11):
if d > 30:
print("<Wrong>")
else:
print("<Correct>")
elif y % 4 == 0: # Every 4 year "Leap" year occures so checking...
if m == 2: # In "Leap" year February has 29 days
if d < 30:
print("<Correct>")
else:
print("<Wrong>")
elif m == 2: # But if it's not "Leap" year February will have 28 days
if d < 29:
print("<Correct>")
else:
print("<Wrong>")
elif y % 4 != 0 and m != 2: # Otherwise print "Correct"
print("<Correct>")
else:
print("<Wrong>") |
3e9200da78d1b19e12f750d505a0e26383da9abd | Diando-Re12/OOP-Python | /OOP-python/Try-Except/pengujian-error.py | 998 | 3.9375 | 4 | #try except adalah proses pengujian error pada sebuah program hal ini sangat bermanfaat untuk mengetahui segala kesalahan dan memberikan peringatan
#kondisi ketika benar
'''
x=30
try:
print(x)
except:
print("ERROR")
'''
#kondisi ketika salah
'''
try:
print(x)
except:
print("ERROR")
'''
#kondisi ketika salah lainnya
'''
try:
print(c)
except NameError:#ini akan dieksekusi
print("Tidak ada variabel c disini")
except:
print("Keluar")
'''
#finally/proses akhir
'''
try:#ini yg akan berjalan,tapi bisa juga dibuat salah untuk mengetahui exceptnya
file=open("G:\OOP-python\ikan.txt","r")
print(file.read())
except:
print("Tidak ada file ini")
finally:#proses ini akan dilakukan try&except diekseskusi
file.close()
'''
#raise Exception(membuat Except)
'''
nama=12
if not type(nama)is str:#jika nama tidak termasuk string,maka akan ada type Error
raise TypeError("Coba tuliskan itu dengan String")
''' |
f0a4f4733475075925dd9d7c2bd4c5547f5412bd | neelbhuva/Data-Mining | /HW4/wine.py | 1,053 | 3.515625 | 4 | import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
def plotHisto(df):
fig = plt.figure(figsize=(20,15)) #Creating a new figure with the mentioned figure size
cols = 4 # No of columns to display the charts
rows = 4 # No of rows to display the charts. These numbers are chosen as we have 16 attributes
# Alternatively, *rows = math.ceil(float(df.shape[1]) / cols)*
# can be used when there are indefinete number of attributes.
for i, column in enumerate(df.columns):
ax = fig.add_subplot(rows, cols, i+1) #Adds a subplot in the i+1 th position
ax.set_title(column)
if df.dtypes[column] == np.object: #For categorical attributes.
df[column].value_counts().plot(kind="bar", axes=ax)
else:
df[column].hist(axes=ax) #For conitnous attributes
plt.xticks(rotation="vertical")
# plt.subplots_adjust(hspace=0.7, wspace=0.2) # To adjust the plots and their labels
if __name__ == '__main__':
df = pd.read_csv("wine.csv")
plotHisto(df)
print(df)
|
8ee2a2458302eea90d63fce71e13dcf78d71d5d2 | TarPakawat/Python | /Bowling.py | 330 | 3.625 | 4 | Frame # = 1
d = 10
while Frame <= 10:
if d == 10:
d = int(input("Number of pins down: "))
s = 10
Frame # = Frame # + 1
elif d < 10:
e = 10-d
d = int(input("Number of pins down (0-%d)" % e))
if d = e:
s = 10
elif d != e:
s = 10 - e
print("Total score is %d" % s)
|
b647265accef90bafb57f008c8c52c431390bea8 | adityamhatre/DCC | /dcc #9/largest_sum_of_non_adjacent_numbers.py | 3,095 | 4.34375 | 4 | import unittest
"""Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0
or negative.
For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10,
since we pick 5 and 5.
Follow-up: Can you do this in O(N) time and constant space?
"""
def largest_sum_of_non_adjacent_numbers(arr):
"""
Calculates the largest possible sum of non-adjacent elements in the array.
ONLY TAKES int
How it works:
Start from end of the array. Now we have two options.
Option 1: Include that element for the sum
Option 2: Don't include that element in the sum
If we select option 1, that means the next element should be the one that is 2 places before it. Since we want
non-adjacent elements
If we select option 2, that means we can skip this element and select the element that is left to it.
Recurse down to the start of the array to get desired sum
:param arr: Input array
:return: Max sum possible using non-adjacent elements
"""
# Edge cases -->
if not arr:
return None
if arr.__contains__(None):
return None
for a in arr:
if type(a) is not int:
return None
if len(arr) == 0:
return 0
# <-- Edge cases
# Base case -->
if len(arr) < 3:
return max(arr)
# <-- Base case
# Include the last element in the sum, and recurse with skipping one element to left of it
including_last = arr[-1] + largest_sum_of_non_adjacent_numbers(arr[:-2])
# Exclude the last element in the sum, and recurse with one element to left of it
excluding_last = largest_sum_of_non_adjacent_numbers(arr[:-1])
# Get the maximum of the above two variables, this is our result
return max(including_last, excluding_last)
class Test(unittest.TestCase):
def test_given_case_1(self):
self.assertEqual(largest_sum_of_non_adjacent_numbers([2, 4, 6, 2, 5]), 13)
def test_given_case_2(self):
self.assertEqual(largest_sum_of_non_adjacent_numbers([5, 1, 1, 5]), 10)
def test_with_negative(self):
self.assertEqual(largest_sum_of_non_adjacent_numbers([5, 3, -1]), 5)
self.assertEqual(largest_sum_of_non_adjacent_numbers([5, 6, -1]), 6)
def test_with_negatives(self):
self.assertEqual(largest_sum_of_non_adjacent_numbers([-5, -3, -1]), -3)
def test_with_zeroes(self):
self.assertEqual(largest_sum_of_non_adjacent_numbers([0, 0, -1]), 0)
self.assertEqual(largest_sum_of_non_adjacent_numbers([0, 0, 1]), 1)
def test_with_None_elements(self):
self.assertEqual(largest_sum_of_non_adjacent_numbers([0, None, 1, 2]), None)
def test_with_None_array(self):
self.assertEqual(largest_sum_of_non_adjacent_numbers(None), None)
def test_with_invalid_elements(self):
self.assertEqual(largest_sum_of_non_adjacent_numbers([1, 2, 3.5]), None)
self.assertEqual(largest_sum_of_non_adjacent_numbers([1, 2, 3, 'a']), None)
if __name__ == '__main__':
unittest.main()
|
9973f705b4ab1413c8e22632c7914296b5f09496 | hmoshabbar/Make_Estimate_anout_Earth_land_using_python-_code | /mean.py | 4,797 | 3.890625 | 4 | print " Workout the quantity of earth for an embankment 150m long Wide at the top.Side slope is 2:1"
print "and depts at each 30m interval are 0.60,.1.2,1.4,1.6,1.4, and 1.6 m "
Station=int(input("Enter Your Station:"))
width=int(input("Enter Your Wide:"))
side=int(input("Enter Your Side:"))
depth1=float(input("Enter Your depth1:"))
depth2=float(input("Enter Your depth2:"))
depth3=float(input("Enter Your depth3:"))
depth4=float(input("Enter Your depth4:"))
depth5=float(input("Enter Your depth5:"))
depth6=float(input("Enter Your depth6:"))
interval=int(input("Enter Your Enterval:"))
#Solutuon:
# since 150 long and depth(differenence) in 30m then
print "....................................................."
Station1=30+Station
Station2=Station1+30
Station3=Station2+30
Station4=Station3+30
Station5=Station4+30
print "Starting station is=", Station
print "First Station is =",Station1
print "second Station is =",Station2
print "Third Station is =",Station3
print "Fourth Station is =",Station4
print "Fivth Station is =",Station5
print "......................................................"
# Given width is 10 means W=10.
#width=int(input("Enter Your Wide:"))
# since Depth is given D=[.60,1.2,1.4,1.6,1.4,1.6]
#depth1=float(input("Enter Your depth1:"))
#depth2=float(input("Enter Your depth2:"))
#depth3=float(input("Enter Your depth3:"))
#depth4=float(input("Enter Your depth4:"))
#depth5=float(input("Enter Your depth5:"))
#depth6=float(input("Enter Your depth6:"))
print "Depth 1 is=",depth1
print "Depth 2 is=",depth2
print "Depth 3 is=",depth3
print "Depth 4 is=",depth4
print "Depth 5 is=",depth5
print "Depth 6 is=",depth6
print "........................................................"
CenterArea1=width*depth1
CenterArea2=width*depth2
CenterArea3=width*depth3
CenterArea4=width*depth4
CenterArea5=width*depth5
CenterArea6=width*depth6
print "Center area WD1=", CenterArea1
print "Center area WD2=", CenterArea2
print "Center area WD3=", CenterArea3
print "Center area WD4=", CenterArea4
print "Center area WD5=", CenterArea5
print "Center area WD6=", CenterArea6
print "........................................................."
# since the given slove Side is 2:1 then Formula s*d*d means(2*depth)
#side=int(input("Enter Your Side:")) #2:1 means 2
Area_of_side1=side*depth1*depth1
Area_of_side2=side*depth2*depth2
Area_of_side3=side*depth3*depth3
Area_of_side4=side*depth4*depth4
Area_of_side5=side*depth5*depth5
Area_of_side6=side*depth6*depth6
print "Side of Area1 Sd^2=",Area_of_side1
print "Side of Area2 Sd^2=",Area_of_side2
print "Side of Area3 Sd^2=",Area_of_side3
print "Side of Area4 Sd^2=",Area_of_side4
print "Side of Area5 Sd^2=",Area_of_side5
print "Side of Area6 Sd^2=",Area_of_side6
print ".........................................................."
# Calculate for Total area...
total_area1=CenterArea1+Area_of_side1
total_area2=CenterArea2+Area_of_side2
total_area3=CenterArea3+Area_of_side3
total_area4=CenterArea4+Area_of_side4
total_area5=CenterArea5+Area_of_side5
total_area6=CenterArea6+Area_of_side6
print "Total Area A1=WD+Sd^2 is", total_area1
print "Total Area A2=WD+Sd^2 is",total_area2
print "Total Area A3=WD+Sd^2 is",total_area3
print "Total Area A4=WD+Sd^2 is",total_area4
print "Total Area A5=WD+Sd^2 is",total_area5
print "Total Area A6=WD+Sd^2 is",total_area6
print "............................................................"
# Calculate for Mean Area....
mean_area1=(total_area1+total_area2)/2
mean_area2=(total_area2+total_area3)/2
mean_area3=(total_area3+total_area4)/2
mean_area4=(total_area4+total_area5)/2
mean_area5=(total_area5+total_area6)/2
print "Mean area MA1=A1+A2/2 is",mean_area1
print "Mean area MA2=A1+A2/2 is",mean_area2
print "Mean area MA3=A1+A2/2 is",mean_area3
print "Mean area MA4=A1+A2/2 is",mean_area4
print "Mean area MA5=A1+A2/2 is",mean_area5
print "..........................................................."
# Since interval is 30 then
#interval=int(input("Enter Your Enterval:"))
Quantity1=interval*mean_area1
Quantity2=interval*mean_area2
Quantity3=interval*mean_area3
Quantity4=interval*mean_area4
Quantity5=interval*mean_area5
print "The Quantity Q1=interval*MA1 is", Quantity1
print "The Quantity Q2=interval*MA2 is",Quantity2
print "The Quantity Q3=interval*MA3 is",Quantity3
print "The Quantity Q4=interval*MA4 is",Quantity4
print "The Quantity Q5=interval*MA5 is",Quantity5
print "............................................................"
# Calculate Total Quantity...
Total_Quantity=Quantity1+Quantity2+Quantity3+Quantity4+Quantity5
print "Total Embankment Quantity Q=Q1+Q2+Q3+Q4+Q5 is",Total_Quantity,"m^3"
|
d56c0cea3d9aaf18e0876cb3efb7db860b2c3715 | jaredchin/Core-Python-Programming | /第七章/练习/7-3.py | 141 | 3.890625 | 4 | adict = {'a':1,'b':2,'c':3,'d':4,'e':5}
print(sorted(adict))
for key in sorted(adict):
print('key %s has value %s' % (key, adict[key]))
|
8c56579272069351508a2d05d4086edffc062283 | ralex1975/rapidpythonprogramming | /chapter7/list2.py | 149 | 3.734375 | 4 | """
list2.py
Chapter 7 Cool Features of Python
Author: William C. Gunnells
Rapid Python Programming
"""
output = [i for i in range(10) if i > 3]
print(output)
|
5e48c8eff3d887ea6eac04e02eb4d0792f405e61 | protea-ban/programmer_algorithm_interview | /CH2/2.6/stack2queue.py | 1,220 | 4.3125 | 4 | # 用两个栈来模拟队列操作
# 基本栈
class Stack():
def __init__(self):
self.items = []
def isEmpty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def top(self):
if not self.isEmpty():
return self.items[len(self.items)-1]
else:
return None
def pop(self):
if len(self.items) > 0:
return self.items.pop()
else:
print("栈已空")
return None
def push(self, item):
self.items.append(item)
class MyStack():
def __init__(self):
self.A = Stack()
self.B = Stack()
def push(self, data):
self.A.push(data)
def pop(self):
if self.B.isEmpty():
while not self.A.isEmpty():
self.B.push(self.A.top())
self.A.pop()
first = self.B.top()
self.B.pop()
return first
if __name__ == '__main__':
stack = MyStack()
stack.push(1)
stack.push(2)
stack.push(3)
print("队列的队首元素为:",stack.pop())
print("队列的队首元素为:",stack.pop())
print("队列的队首元素为:",stack.pop())
|
692bd543de0c74ef98ca5377bb4afad5750d58ad | imercadovazquez/lab14_bdd | /retirement.py | 6,192 | 3.96875 | 4 | """
REATTEMPT ASSIGNMENT
This module contains functions for calculating retirement age and date.
The private validation functions parse and validate correct input values.
The public calculation functions validate inputs and calculate the desired values.
Write unit tests using pytest for the following functions in this module:
* calculate_retirement_age
* calculate_retirement_date
The unit test must cover all equivalence classes and boundary conditions,
including invalid inputs.
Read the comments in this module for testing hints.
Warning:
This version of retirement.py is different from the one used by the original lab.
Please read it thoroughly and carefully!
Unlike the original assignment,
this reattempt assignment will not include testing for the DateTemp class.
"""
# ----------------------------------------------------------------------
# Validation Functions
#
# These functions validate input values.
# In Python, functions prefixed with an underscore ("_") are private.
# Typically, unit tests should not be written for private functions.
# Don't write tests for them.
# Instead, write input validation tests for the calculation functions.
# ----------------------------------------------------------------------
def _validate_age_month(month):
month = int(month)
if month < 0 or month > 11:
raise ValueError(f'Age month "{month}" must be between 0 and 11')
return month
def _validate_age_year(year):
year = int(year)
if year < 65 or year > 67:
raise ValueError(f'Age year "{year}" must be between 65 and 67')
return year
def _validate_birth_month(month):
month = int(month)
if month < 1 or month > 12:
raise ValueError(f'Birth month "{month}" must be between 1 and 12')
return month
def _validate_birth_year(year):
year = int(year)
if year < 1900:
raise ValueError(f'Birth year "{year}" must be no earlier than 1900')
elif year >= 2020:
raise ValueError(f'Birth year "{year}" must be earlier than 3000')
return year
# ----------------------------------------------------------------------
# Calculation Function: Retirement Age
#
# This function takes in a birth year and returns the retirement age.
# The retirement age is a (years, months) tuple.
#
# Notice the large number of if-else cases for birth years.
# Each one represents an equivalence class.
# Most conditions are single year values, but some represent ranges.
# There should be a test for each equivalence class and each boundary value.
# pytest.mark.parametrize can cover multiple inputs for the same test function.
#
# This function also validates inputs.
# Some inputs can be successfully parsed, but others will raise exceptions.
# There should be a test to cover each equivalence class of inputs, good and bad.
# pytest.raises makes testing exceptions easy.
# ----------------------------------------------------------------------
def calculate_retirement_age(birth_year):
birth_year = _validate_birth_year(birth_year)
if birth_year <= 1937:
return 65, 0
elif birth_year == 1938:
return 65, 2
elif birth_year == 1939:
return 65, 4
elif birth_year == 1940:
return 65, 6
elif birth_year == 1941:
return 65, 8
elif birth_year == 1942:
return 65, 10
elif 1943 <= birth_year <= 1954:
return 66, 0
elif birth_year == 1955:
return 66, 2
elif birth_year == 1956:
return 66, 4
elif birth_year == 1957:
return 66, 6
elif birth_year == 1958:
return 66, 8
elif birth_year == 1959:
return 66, 10
else:
return 67, 0
# ----------------------------------------------------------------------
# Calculation Function: Retirement Date
#
# This function takes in four values to calculate the retirement date.
# The retirement date is a (year, month) tuple.
#
# There isn't a large if-else table in this function.
# Instead, there is a mathematical calculation.
# Unit tests should cover all ways the calculation can happen.
# Hint: look at the "if" condition.
#
# This function also validates all inputs.
# Again, there should be a test to cover good and bad inputs.
# There will be many more input validation tests for this function.
# ----------------------------------------------------------------------
def calculate_retirement_date(birth_year, birth_month, age_years, age_months):
birth_year = _validate_birth_year(birth_year)
birth_month = _validate_birth_month(birth_month)
age_years = _validate_age_year(age_years)
age_months = _validate_age_month(age_months)
year = birth_year + age_years
month = birth_month + age_months
if month > 12:
year += 1
month -= 12
return year, month
# ----------------------------------------------------------------------
# Each test function should test one equivalence class.
# For example, don't do this:
#
# def test_thing():
# assert thing(1) == 1
# assert thing(2) == 2
# assert thing(3) == 3
#
# Instead, do this:
#
# def test_thing_1():
# assert thing(1) == 1
#
# def test_thing_2():
# assert thing(2) == 2
#
# def test_thing_3():
# assert thing(3) == 3
#
# Or, better yet, do this:
#
# @pytest.mark.parametrize("num", [1, 2, 3])
# def test_thing(num):
# assert thing(num) == num
#
# Also, use descriptive names for tests.
# For example, "test_calculate_retirement_age_when_birth_year_is_negative".
# If a test fails, the name should indicate what went wrong.
#
# Use helpful parameter names as well.
# Names like "num", "input", and "output" aren't very helpful.
# Name parameters after the values they represent.
#
# Even though there are only two functions to test,
# many tests must be written to successfully complete this assignment
# because the functions have several equivalence classes and boundary conditions.
# How many is "many"?
# The instructor's solution has a few dozen, mostly from pytest.mark.parametrize.
# Err on the side of thoroughness rather than skimpiness.
# ----------------------------------------------------------------------
|
263cfb3234309a92b07af84f16b0df57eb350433 | jillvp/Personal_Projects | /Star Wars Mad Libs Game/madlibs.py | 1,679 | 3.890625 | 4 | # A GALAXY APART: STAR WARS YOUR WAY AD-LIB
print("<<<<<<<<<<<<<<<<<<<<<<<<< Mad Libs - A Galaxy Apart >>>>>>>>>>>>>>>>>>>>>>>>>")
name = input("Tell me your name, and click enter. ")
adj1 = input("Tell me an adjective, and click enter. ")
verb1 = input("Tell me a verb, and click enter. ")
sillyword = input("Tell me a silly word, and click enter. ")
noun1 = input("Tell me a noun, and click enter. ")
noun2 = input("Tell me another noun (plural), and click enter. ")
verb2 = input("Tell me a verb (plural, ending in 'ed'), and click enter. ")
noun3 = input("Tell me a noun, and click enter. ")
noun4 = input("Tell me a noun, and click enter. ")
verb3 = input("Tell me a verb (plural, ending in 'ed'), and click enter. ")
adj2 = input("Tell me an adjective, and click enter. ")
print('\n\nDarth {0} looked at his master while his {1} cold breathing filled the room.\nHe was told to go to {2} everything on the planet of {3}.\nHe got in his {4} and to hyperspace.\nSoon before he reached the planet, he dropped out of hyperspace and was attacked by Rebel {5}'.format(name, adj1, verb1, sillyword, noun1, noun2))
print('He {0} them off and continued to the planet`s surface.\nHe landed and confronted more opposition, slicing it down with his {1}.\nHe used the {2} to choke another Rebel, then {3} him aside.\nHe finished off all life on the planet with a/an {4} laugh.'.format(verb2, noun3, noun4, verb3, adj2))
|
51ecc647f2c6c292f362031d6d4da1f2806bffa3 | akhilerm/Google-Foobar | /hall.py | 227 | 3.5625 | 4 | def answer(s):
salutes = 0
people = 0
for person in s:
if person == '-':
continue
elif person == '>':
people+=1
else:
salutes+=people
return salutes*2
|
de39263bfe2edf8523d682ae57229353988956ba | DarioCampagnaCoutinho/logica-programacao-python | /modulo01-introducao/exercicios/exercicio02.py | 146 | 4.15625 | 4 | fahrenheit = float(input('Digite a temperatura em Fahrenheit : '))
celsius = 5 * (fahrenheit - 32) / 9
print('Celsius = {:,3f}'.format(celsius)) |
f33e74e815f71661cd66bc5053117aa936650cf0 | Bralor/python-workshop | /materials/03_loops/kosik.py | 1,504 | 3.875 | 4 | #!/usr/bin/python3
""" Lekce #4 - Uvod do programovani, Nakupni kosik """
kosik = {}
ODDELOVAC = "=" * 40
POTRAVINY = {
"mleko": [30, 5],
"maso": [100, 1],
"banan": [30, 10],
"jogurt": [10, 5],
"chleb": [20, 5],
"jablko": [10, 10],
"pomeranc": [15, 10]
}
print(
"VITEJTE V NASEM VIRTUALNIM OBCHODE".center(40, " "),
end=f"\n{ODDELOVAC}\n"
)
TABULKA = POTRAVINY.copy()
while TABULKA:
radek_potravina = TABULKA.popitem()
print(f"POTRAVINA: {radek_potravina[0]},\tCENA: {radek_potravina[1][0]}")
else:
print(ODDELOVAC)
while (vyber_zbozi := input("VYBERTE ZBOZI: ")) != 'q':
if vyber_zbozi not in POTRAVINY:
print(f"{vyber_zbozi} NEMAME V NABIDCE!")
elif vyber_zbozi not in kosik and POTRAVINY[vyber_zbozi][1] > 0:
kosik[vyber_zbozi] = [POTRAVINY[vyber_zbozi][0], 1] # pridam ks
POTRAVINY[vyber_zbozi][1] = POTRAVINY[vyber_zbozi][1] - 1 # odeberu ks
elif vyber_zbozi in kosik and POTRAVINY[vyber_zbozi][1] > 0:
kosik[vyber_zbozi][1] = kosik[vyber_zbozi][1] + 1
POTRAVINY[vyber_zbozi][1] = POTRAVINY[vyber_zbozi][1] - 1
elif POTRAVINY[vyber_zbozi][1] == 0:
print(f"{vyber_zbozi.upper()} JIZ NENI SKLADEM!")
else:
print("UKONCUJI NAKUP..", ODDELOVAC, sep="\n")
total = 0
for potraviny, (cena, kus) in kosik.items():
print(f"POTRAVINA:{potraviny}\t\t{kus}x {cena}")
total = total + (cena*kus)
else:
print(ODDELOVAC, f"CELKOVA CENA NAKUPU: {total}", sep="\n")
|
3e56d735450ffcc007bd34fbb5bfe3f4ce690bb7 | Xzooan/Profit-and-loss-finder | /Profit and loss finder.py | 373 | 3.921875 | 4 |
sp=float(input("The selling price="))
print(sp)
cp=float(input("The cost price="))
print(cp)
if sp>cp:
profit=sp-cp
print("Profit",'=',profit,'rupees')
_profit=profit*100/cp
print("Profit %",'=',_profit)
else:
loss=cp-sp
print("Loss",'=',loss,'rupees')
_loss=loss*100/cp
print("Loss %",'=',_loss)
print("=========end=========")
|
c1194b1f3716bbec4b024f3c3f7868f0f46663c8 | skybrim/practice_leetcode_python | /offer/algorithm/left_rotate_string.py | 801 | 4 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@file: left_rotate_string.py
@author: wiley
@datetime: 2020/7/10 9:57 AM
左旋转字符串
字符串的坐旋转操作是把字符串前面的若干个字符转移到字符串的尾部。
请定义一个函数,实现字符串左旋转操作的功能。
举例:输入字符串 "abcdefg" 和数字 2,该函数将返回左旋转两位得到的结果 "cdefgab"
"""
def reverse_left_words(s, n):
"""
@param s: str
@param n: int
@return: str
"""
return s[n:] + s[:n]
def reverse_left_words_ii(s, n):
res = ""
for i in range(n, len(s)):
res += s[i]
for i in range(0, n):
res += s[i]
return res
if __name__ == '__main__':
result = reverse_left_words_ii("abcdeft", 2)
print(result)
|
d8f0788ab9863873ec8a4e2f726c14b19a09b2f6 | chenyan198804/myscript | /08day4/Virtuallife/Person.py | 381 | 3.59375 | 4 | #!/usr/bin/env python
#_*_coding:utf-8_*_
class Person(object):
def __init__(self,name,age,sexuality,work,salary,special):
self.name = name
self.age = age
self.sexuality = sexuality
self.work = work
self.salary = salary
self.special = special
def talk(self,word):
print("{0}:\"{1}\"".format(self.name,word)) |
1a7f97129c40da6128270dcfef3c3a00d98331a8 | jasonrbriggs/python-for-kids | /ch7/silly-age-joke.py | 243 | 3.734375 | 4 | import sys
def silly_age_joke():
print('How old are you?')
age = int(sys.stdin.readline())
if age >= 10 and age <= 13:
print('What is 13 + 49 + 84 + 155 + 97? A headache!')
else:
print('Huh?')
silly_age_joke() |
9da523e6173bf2b65f12e18e994f6b782ae64a67 | Dinosurr/nackademinlabb | /funcs/bubblesort2.py | 329 | 3.984375 | 4 | def bubblesort(myList):
for item in range(len(myList)):
for i in range(len(myList)-1):
if myList[i] > myList[i+1]:
myList[i], myList[i+1] = myList[i+1], myList[i]
numList = [1, 5, 6, 7, 8, 2, 3, 4, 5, 6, 1, 8,
9, 4, 243, 23, 12, 19, 54, 43]
bubblesort(numList)
print(numList) |
1f1da13ecc052004707b6fd4eb9c80e11c3813ac | omkar-javadwar/CodeWars | /katas/kyu_6/What_century_is_it?.py | 696 | 4.09375 | 4 | # https://www.codewars.com/kata/52fb87703c1351ebd200081f/train/python
'''
Instructions :
Return the inputted numerical year in century format. The input will always be a 4 digit string. So there is no need for year string validation.
Examples:
"1999" --> "20th"
"2011" --> "21st"
"2154" --> "22nd"
"2259" --> "23rd"
"1124" --> "12th"
"2000" --> "20th"
'''
import math
def what_century(year):
year = int(year)
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(math.floor(n/10)%10!=1)*(n%10<4)*n%10::4])
if year <= 100:
return '1st'
elif year % 100 == 0:
return ordinal(int(year/100))
else:
return ordinal(int(year/ 100) + 1)
|
2a79f5ddd1f8e2066759afe2081d87494014da94 | Melifire/CS120 | /Projects/Short 9/Part 1/TestCases/tree_generator.py | 2,142 | 4.65625 | 5 | #! /usr/bin/python3
"""Generates a snippet of code, which represents a randomly-generated binary
tree. Note that this is *NOT* a BST; the arrangement of nodes is random.
However, the values in the tree are unique.
This will never generate a tree that is empty; if you want to test that,
write a testcase by hand. Likewise, it will generate very small trees (1-3
nodes) only in *exceptional* circumstances. It's possible, but highly
unlikely.
Copy the output of this program into your own program, and then use 'root'
as the root of the tree that has been generated.
"""
import random
from tree_node import TreeNode
# generate a random set of values, which we will use to populate our tree. It
# needs to be random, but also have unique values. So we'll generate a random
# set (which might include duplicates), and then turn it into a set(), which
# removes duplicates, and then shuffle them.
vals_count = random.randint(5,32)
vals = [ random.randint(-50,100) for i in range(vals_count) ]
vals = set(vals)
vals = list(vals)
random.shuffle(vals)
# build the nodes. We're doing this exactly like building a BST, except that
# it's randomly choosing whether to go left or right.
def random_insert(root, val):
if root is None:
return TreeNode(val)
if random.randint(0,1) == 0:
root.left = random_insert(root.left, val)
else:
root.right = random_insert(root.right, val)
return root
root = None
for v in vals:
root = random_insert(root, v)
# just in case the user doesn't realize it, this import is important. But
# canny users won't need it...
print("from tree_node import TreeNode")
print()
# now, just print out the nodes that we've created. To make it pretty, we'll
# use a recursive function here, which uses .left.right chains to name the
# nodes.
def print_out_subtree(root, prefix):
print(f"{prefix} = TreeNode({root.val})")
if root. left is not None:
print_out_subtree(root.left, prefix+".left")
if root.right is not None:
print_out_subtree(root.right, prefix+".right")
print_out_subtree(root, "root")
print()
|
df0b2bcc3b11d7718707dd508ef06d3382c3ae86 | rookuu/AdventOfCode-2015 | /Day 5/Puzzle 1.py | 1,341 | 3.609375 | 4 | #!/usr/bin/env python
"""
Solution to Day 5 - Puzzle 1 of the Advent Of Code 2015 series of challenges.
--- Day 5: Doesn't He Have Intern-Elves For This? ---
Needs to apply sets of conditions to series of strings to determine whether they're valid or not.
-----------------------------------------------------
Author: Luke "rookuu" Roberts
"""
vowels = "aeiou"
badStrings = ["ab", "cd", "pq", "xy"]
noOfGoodStrings = 0
inputFile = open('input.txt')
dataFromFile = inputFile.read().splitlines()
def checkvowels (string):
counter = 0
for c in string:
for vowel in vowels:
if vowel == c:
counter += 1
if counter == 3:
return True
return False
def checkbadstrings (string):
for badstring in badStrings:
if string.find(badstring) != -1:
return False
return True
def checkdoubles (string):
for i in range(0,len(string)-1):
if string[i] == string[i+1]:
return True
return False
def checkconditions (string):
if checkvowels(string) and checkbadstrings(string) and checkdoubles(string):
return True
else:
return False
for lines in dataFromFile:
if checkconditions(lines):
noOfGoodStrings += 1
print "The number of strings that are deemed 'nice' are " + str(noOfGoodStrings)
|
f25d29fe23ca284be847e4cfdfae80a4e90ec6a8 | hhsue-zz/leetcode | /RotateArray/mine2.py | 748 | 3.578125 | 4 | #!/usr/bin/python
#[0,1,2,3,4,5,6]
#[4,5,6,0,1,2,3]
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {void} Do not return anything, modify nums in-place instead.
def rotate(self, nums, k):
mod = k % len(nums)
d = {} #{index:value}
for i in range(0,len(nums)):
if i < len(nums) - mod - 1:
d[nums[i+mod]] = i
if i in d:
nums[i+mod] = d[i]
else:
nums[i+mod] = nums[i]
else:
if i in d:
new_index = i + mod - len(nums)
nums[new_index] = d[i]
return nums
s = Solution()
print s.rotate([0,1,2,3,4,5,6], 3)
|
545289f41e7a6165308cbbf488c6d5d852d5b3ea | Drunk-Mozart/card | /DL_09_while sum.py | 329 | 3.734375 | 4 | i = 0
summary = 0
while 100 >= i:
summary += i
i += 1
print(summary, i)
i = 0
summary = 0
while 100 >= i:
summary += i
i += 2
if i == 2:
break
print(i)
print(summary, i)
i = 0
result = 0
while i <= 100:
i += 1
if i % 2 == 1:
continue
print(i)
result += i
print(result)
|
c74d086a397a11968b3a17e31dc6db6ec87efcad | emma-rose22/practice_problems | /test_scratch.py | 5,668 | 4 | 4 | '''
Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'.
Example
For s = "abacabad", the output should be
first_not_repeating_character(s) = 'c'.
There are 2 non-repeating characters in the string: 'c' and 'd'. Return c since it appears in the string first.
For s = "abacabaabacaba", the output should be
first_not_repeating_character(s) = '_'.
There are no characters in this string that do not repeat.
'''
def first_not_repeating_character(s):
#put each letter as a key in dict, value is times sighted
#get the keys that were sighted once
# if none return _
#get their index position in the OG string, and return the letter
#at the first index position
cache = {}
repeats = []
index_pos = []
#inserting all into cache
for letter in s:
if letter in cache:
cache[letter] += 1
else:
cache[letter] = 1
#getting all the values that appeared once
for key in cache:
if cache[key] == 1:
repeats.append(key)
#if repeats isn't empty
#get all their index positions in OG list
#and return the smallest one
if len(repeats) > 0:
for repeat in repeats:
index = s.index(repeat)
index_pos.append(index)
smallest = min(index_pos)
return s[smallest]
else:
return '_'
s = "abacabad"
#print(first_not_repeating_character(s))
'''
In a city-state of n people, there is a rumor going around that one of the n people is a spy for the neighboring city-state.
The spy, if it exists:
Does not trust anyone else.
Is trusted by everyone else (he's good at his job).
Works alone; there are no other spies in the city-state.
You are given a list of pairs, trust. Each trust[i] = [a, b] represents the fact that person a trusts person b.
If the spy exists and can be found, return their identifier. Otherwise, return -1.
Example 1:
Input: n = 2, trust = [[1, 2]]
Output: 2
Explanation: Person 1 trusts Person 2, but Person 2 does not trust Person 1, so Person 2 is the spy.
Example 2:
Input: n = 3, trust = [[1, 3], [2, 3]]
Output: 3
Explanation: Person 1 trusts Person 3, and Person 2 trusts Person 3, but Person 3 does not trust either Person 1 or Person 2. Thus, Person 3 is the spy.
Example 3:
Input: n = 3, trust = [[1, 3], [2, 3], [3, 1]]
Output: -1
Explanation: Person 1 trusts Person 3, Pers
'''
def uncover_spy(n, trust):
#two lists
# one with trusted people
# one with possible spies
# when we add trusted people to list (every 1st in pair)
# check if they are in possible spies
# if so, remove them
# to see if we add someone to the spies list
# check if they are already trusted
# if so dont add to spies
# else add
trusted = []
maybe_spies = []
for nest in trust:
#put all the trusters in trusted
trusted.append(nest[0])
if nest[0] in maybe_spies:
#if truster in spies, take them out
maybe_spies = list(filter(lambda x: x != nest[0], maybe_spies))
#if not trusted not in trusted list, add to spies
if nest[1] not in trusted:
maybe_spies.append(nest[1])
#if there is just one spy left
one_spies = list(set(maybe_spies))
#and they are trusted by n - 1 people
# (so they show up in the spies list n- 1 times)
everyone_trusts = len(maybe_spies)
#return them as the spy
if (len(one_spies) == 1) and everyone_trusts == (n-1):
return maybe_spies[0]
else:
return -1
n = 3
trust = [[1,2],
[2,3]]
#print(uncover_spy(n, trust))
'''
Write a function that receives as input the head node of a linked list and an integer k. Your function should remove the kth node from the end of the linked list and return the head node of the updated list.
For example, if we have the following linked list:
(20) -> (19) -> (18) -> (17) -> (16) -> (15) -> (14) -> (13) -> (12) -> (11) -> null
The head node would refer to the node (20). Let k = 4, so our function should remove the 4th node from the end of the linked list, the node (14).
After the function executes, the state of the linked list should be:
(20) -> (19) -> (18) -> (17) -> (16) -> (15) -> (13) -> (12) -> (11) -> null
If k is longer than the length of the linked list, the linked list should not be changed.
Can you implement a solution that performs a single pass through the linked list and doesn't use any extra space?
'''
def remove_kth_from_end(head, k):
#iterate through the list
# by the k iteration, start pointer incrementing from the head
# when we get to the end, pointer should be pointing at the given node
counter = 0
pointer = head
before_k = None
while pointer:
counter += 1
#if the counter is two past the node we want to delete
#start the before k at the heaad
if counter == k + 2:
before_k = head
#increment the position before the node we want to delete
if before_k:
before_k = before_k.next
#increment pointer used to move through list
pointer = pointer.next
#cant start pointer if k == len(list)
#but that means it is always the head that is deleted
if counter == k:
head = head.next
try:
before_k.next = before_k.next.next
except:
pass
return head
head = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11]
k = 4
print(remove_kth_from_end(head, k)) |
9f3e2d3e174e86a1258b44c2210140fa96f2aaac | vup999/test | /test2.py | 830 | 4.125 | 4 | # Numbers
# str()
# num1=28
# print (str(num1))
# print(str(num1) + ' days in FEB')
# print('------------------')
# int() & float()
# f_num='5'
# l_num='6'
#
# print (int(f_num) + float(l_num))
# print (int(f_num) + int(l_num))
# datetime
from datetime import datetime, timedelta
today=datetime.now()
print(today)
print(str(today))
print('day :' + str(today.day))
print('Month :' + str(today.month))
print('Year :' + str(today.year))
# section 2 timedelta#
delta_days= input('Input How many days before? > ')
date_before= today - timedelta(days=float(delta_days))
print( str(delta_days) + ' days before is :' + str(date_before))
# section 3 datetime.strptime
# birthday = input('When is your birthday (yyyy/mm/dd)?')
# birthday_date = datetime.strptime(birthday,'%Y%m%d')
# print('birthday =' + str(birthday_date))
|
f5e09e5a5bb643433eb3b2667dab357784da3764 | ikki2530/holberton-system_engineering-devops | /0x16-api_advanced/1-top_ten.py | 627 | 3.53125 | 4 | #!/usr/bin/python3
"""
queries the Reddit API and prints the titles of the first 10 hot posts
listed for a given subreddit.
"""
import requests
def top_ten(subreddit):
"""top ten subreddits titles"""
if subreddit:
try:
heads = {'User-agent': 'dagomez2530'}
url = "https://www.reddit.com/r/{}/hot.json".format(subreddit)
response = requests.get(url, headers=heads)
data_reddit = response.json()
i = 0
for i in range(10):
print(data_reddit['data']['children'][i]['data']['title'])
except:
print(None)
|
cc7605a35008024a7e9fd950660344ba733f4956 | mesrop1665/My_works | /index.py | 177 | 3.671875 | 4 | def square_digits(num):
r = ""
for i in range(len(str(num))):
i = str(num)[i]
r += str(int(i)*int(i))
return int(r)
square_digits(1222) |
e83973796de3bb19f60be9d5572f4c1b6fe91c94 | adichamoli/LeetCodeProblems | /013 - Insert Interval/Solution3.py | 657 | 3.53125 | 4 | '''156 / 156 test cases passed. Status: Accepted
Runtime: 68 ms Memory Usage: 17.5 MB'''
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
if not intervals:
return [newInterval]
intervals.append(newInterval)
intervals.sort()
res = []
res.append(intervals[0])
for start, end in intervals[1:]:
if start > res[-1][1]:
res.append([start, end])
elif end > res[-1][1]:
res[-1][1] = end
return res |
dead4328b7352e2b6899022301a27b1ed97beb1e | TorpidCoder/Python | /W3School/StringPractice/10.py | 186 | 3.828125 | 4 | word_1 = input("enter word 1 : ")
word_2 = input("enter word 2 : ")
word3 = word_1.replace(word_1[0] , word_2[0])
word4 = word_2.replace(word_2[0],word_1[0])
print(word3)
print(word4)
|
91a3327e2c6054571efd3d5957de8e28f4094d3f | kevapostol/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 326 | 3.65625 | 4 | #!/usr/bin/python3
'''
The 1-number_of_lines module
'''
def number_of_lines(filename=""):
'''A function that returns the number of lines of a text file'''
count = 0
with open(filename, encoding='UTF-8') as a_file:
'''Opens a file'''
for line in a_file:
count += 1
return count
|
aa1453f8b9e83bc1895880b001605278feeaf13c | cp1372/Project-Euler-Solutions | /problem 203.py | 798 | 3.609375 | 4 | import math
def primes(n):
""" Returns a list of primes < n """
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
def choose(n, r):
result = math.factorial(n) / ( math.factorial(r) * math.factorial(n-r) )
return result
squaresOfPrimes = [n*n for n in primes(50)]
def sqf(x):
for p in squaresOfPrimes:
if x % p == 0: return False
return True
uniqueNumbers = set()
for n in range(1,51):
for r in range(0,n+1):
uniqueNumbers.add( choose(n,r) )
squareFreeNumbers = []
for x in uniqueNumbers:
if sqf(x):
squareFreeNumbers.append(x)
print (sum(squareFreeNumbers), squareFreeNumbers) |
b91729900536a787a5b71f947a98891d7d61c45f | Jhonierk/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 1,602 | 4.15625 | 4 | #!/usr/bin/python3
"""defines island_perimeter module"""
def island_perimeter(grid):
"""Returns perimeter of island"""
perimeter = 0
for row in range(len(grid)):
# print(row) # 0, 1, 2, 3
for column in range(len(grid[row])):
# print(grid[row][column]) #actual values
if grid[row][column] == 1:
"""count top perimeter"""
if row == 0:
# print("TOP ROW")
perimeter += 1
elif row != 0 and grid[row - 1][column] != 1:
# print("TOP ISLAND")
perimeter += 1
"""left perimeter"""
if column == 0:
# print("BEGIN ROW")
perimeter += 1
elif column != 0 and grid[row][column - 1] != 1:
# print ("LEFT ISLAND")
perimeter += 1
"""right perimeter"""
if column == len(grid[row]) - 1:
# print("END ROW")
perimeter += 1
elif (column != len(grid[row]) - 1 and
grid[row][column + 1] != 1):
# print("RIGHT ISLAND")
perimeter += 1
"""bottom perimeter"""
if row == len(grid) - 1:
# print("LAST ROW")
perimeter += 1
elif row != len(grid) - 1 and grid[row + 1][column] != 1:
# print("BOTTOM ISLAND")
perimeter += 1
return perimeter
|
e25dbffe213cfa3b3affb2747f45ac5154431d8a | cristinarivera/python | /130.py | 1,023 | 3.71875 | 4 | print 'MAXIMO COMUN DIVISOR'
a = int(raw_input('ingrese primer nro: '))
b = int(raw_input('ingrese segundo nro: '))
c = int(raw_input('ingrese tercer nro: '))
mcd = 0
if c < a > b:
if b < c:
for i in range(1, b+1):
if a % i ==0 and b % i ==0 and c % i ==0:
mcd = i
print 'mcd:', mcd
elif c < b:
for i in range(1, c+1):
if a % i ==0 and b % i ==0 and c % i ==0:
mcd = i
print 'mcd:', mcd
if c < b > a:
if a < c:
for i in range(1, a+1):
if a % i ==0 and b % i ==0 and c % i ==0:
mcd = i
print 'mcd:', mcd
elif c < a:
for i in range(1, c+1):
if a % i ==0 and b % i ==0 and c % i ==0:
mcd = i
print 'mcd:', mcd
if b < c > a:
if a < b:
for i in range(1, a+1):
if a % i ==0 and b % i ==0 and c % i ==0:
mcd = i
print 'mcd:', mcd
elif b < a:
for i in range(1, b+1):
if a % i ==0 and b % i ==0 and c % i ==0:
mcd = i
print 'mcd:', mcd |
2c807876754d385787da7ad9036bc550dc6f807a | techyphob/python | /Leap Year/main (1).py | 544 | 4.0625 | 4 | def isYearLeap(year):
if year % 4 == 0:
if year % 100 == 0 and not year % 400 == 0: leap = False
else: leap = True
else: leap = False
return leap
def daysInMonth(year, month):
months30 = [4,6,9,11]
if month == 2:
if isYearLeap(year): return 29
else: return 28
elif month in months30: return 30
else: return 31
def dayOfYear(year, month, day):
days = 0
for m in range(1,month):
days += daysInMonth(year, m)
return days + day
print(dayOfYear(2000, 12, 31)) |
3e926e32c664603be1eb57cb868a90777fb1af3d | ji-eun-k/crawler | /7_example.py | 230 | 3.5 | 4 | f = open("예외처리연습.txt", "r", encoding="utf-8")
txt = f.readlines()
try:
n = int(input())
for i in range(n):
print(txt[i])
except IndexError:
print('모든 행이 출력완료 되었습니다') |
69e57f3485777a5f5c1fa605045aea3834a7940e | Piropoo/alura-jogos-python | /forca/forca_lib.py | 4,400 | 3.796875 | 4 | import random
from os import read, stat_result
# Definindo funções
def abertura():
print('\n' + '\033[34m=\033[m'*20, 'Forca', '\033[34m=\033[m'*20)
print('Bem vindo ao jogo da forca!\n')
def lendo_arquivo_palavras() -> list:
arquivo_palavras = open('palavras.txt', 'r', encoding='UTF-8')
palavras = arquivo_palavras.read().replace(',', '').strip().split()
arquivo_palavras.close
return palavras
def define_palavra_secreta(palavras: list) -> str:
palavra_secreta = palavras[random.randint(0, len(palavras))].upper()
acertadas = ['_' for letra in palavra_secreta]
return palavra_secreta, acertadas
def digita_chute() -> str:
chute = input('\nQual letra? ').strip().upper()
print('')
return chute
def validar_chute(chute: str, digitadas: list) -> str: # Valida se é um valor válido
while len(chute) > 1 or chute.isalpha() == False:
chute = input('Digite UMA LETRA: ')
print('')
if chute not in digitadas: # Valida se ja foi digitado
digitadas.append(chute)
else:
while chute in digitadas:
print('Você já digitou esta letra, tente novamente.')
chute = input('Tente de novo: ').upper()
print('')
return chute, digitadas
def coloca_letras(chute: str, palavra_secreta: str, acertadas: list):
index = 0
for letra in palavra_secreta:
if(chute == letra):
acertadas[index] = letra
index += 1
def desenho_forca(tentativas: int):
print(' _______ ')
print(' |/ | ')
if tentativas == 7:
print (' | ')
print (' | ')
print (' | ')
print (' | ')
if tentativas == 6:
print(" | (_) ")
print(" | ")
print(" | ")
print(" | ")
if tentativas == 5:
print(" | (_) ")
print(" | \ ")
print(" | ")
print(" | ")
if tentativas == 4:
print(" | (_) ")
print(" | \| ")
print(" | ")
print(" | ")
if tentativas == 3:
print(" | (_) ")
print(" | \|/ ")
print(" | ")
print(" | ")
if tentativas == 2:
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | ")
if tentativas == 1:
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / ")
if tentativas == 0:
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / \ ")
print(" | ")
print("_|___ ")
print()
def fim(acertou: bool, palavra_secreta: str):
if acertou:
print("\nParabéns, você ganhou!")
print(" ___________ ")
print(" '._==_==_=_.' ")
print(" .-\\: /-. ")
print(" | (|:. |) | ")
print(" '-|:. |-' ")
print(" \\::. / ")
print(" '::. .' ")
print(" ) ( ")
print(" _.' '._ ")
print(" '-------' ")
else:
print("\nPuxa, você foi enforcado!")
print(f"A palavra era {palavra_secreta.lower()}!")
print(" _______________ ")
print(" / \ ")
print(" / \ ")
print("// \/\ ")
print("\| XXXX XXXX | / ")
print(" | XXXX XXXX |/ ")
print(" | XXX XXX | ")
print(" | | ")
print(" \__ XXX __/ ")
print(" |\ XXX /| ")
print(" | | | | ")
print(" | I I I I I I I | ")
print(" | I I I I I I | ")
print(" \_ _/ ")
print(" \_ _/ ")
print(" \_______/ ")
print('\033[34m=\033[m'*20, 'Fim', '\033[34m=\033[m'*20, '\n') |
2b25fba87e4fd78db5fb6e7276db52a9237def03 | YuriiKhomych/ITEA-advanced | /Yurii_Khomych/1_functions/hw/comprehensions.py | 241 | 3.953125 | 4 | print({x for x in range(-9, 10)})
print({x: x ** 3 for x in range(5)})
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
list_using_comp = [var for var in input_list if var % 2 == 0]
print("Output List using list comprehensions:", list_using_comp) |
ccf6d5e41fe04d1779cdcae5d5a52a77b6e8f4ed | savorywatt/testing | /perceptron.py | 6,357 | 3.5625 | 4 | from random import random
from random import shuffle
MAX_EPOCHS = 10
class Perceptron(object):
def __init__(self, weight_keys):
self.weights = {weight_key: random()
for weight_key in weight_keys}
self.threshold = random()
self.learning_rate = random()
self.epochs = 0
self.count = 0
self.edges = {weight_key: 0.0 for weight_key in weight_keys}
def update_weights(self, features, error):
"""Update weights for the incoming features based on error"""
for key, value in self.weights.iteritems():
vector_value = features.get(key)
if vector_value:
correction = (self.learning_rate * error * float(vector_value))
self.weights[key] = correction
self.average()
def average(self):
for feature, count in self.edges.iteritems():
self.weights[feature] = (self.count * self.weights[feature] + count) / (count + 1)
self.count += 1
def score(self, features):
"""Based on passed in features find the dot product of any matching
features.
"""
response = 0.0
for key, value in self.weights.iteritems():
vector_value = features.get(key)
if vector_value:
response += vector_value * value
return response
def classify(self, features):
"""Classify using the score and threshold."""
score = self.score(features)
if score >= self.threshold:
return 1
return -1
def train(self, data):
"""Based on the data learn the features by adjusting weights when
the perceptron incorrectly classifies a peice of training data.
"""
epochs = 0
train_error = 0.1
learning = True
learned = 0
correct = 0
while learning:
epoch_correct = 0
for features in data:
response = self.classify(features)
expected = features.get('class')
error = float(expected - response)
if expected != response:
learned += 1
for feature in features:
if feature in self.edges.iterkeys():
self.edges[feature] += 1
self.update_weights(features, error)
train_error += abs(error)
else:
correct += 1
epoch_correct += 1
epochs += 1
if epochs >= MAX_EPOCHS or train_error == 0.0:
learning = False
self.epochs = epochs
def test(self, data):
"""Used to report and record statistics for how accurate the perceptron
was at classifying the new data set.
"""
total = len(data)
correct = 0
incorrect = 0
for datum in data:
response = self.classify(datum)
expected = datum.get('class')
if expected != response:
incorrect += 1
else:
correct += 1
print 'correct:', correct
self.accuracy = (float(correct) / float(total)) * 100
print 'accuracy: ', self.accuracy
print 'trained in %d epochs' % self.epochs
print 'threshold:', self.threshold
def generate_test_data(features=None, num=10):
""" assumes even amounts of data, divisible by 2
"""
if not features:
features = ['a', 'b', 'c']
desired_data = xrange(num)
data = []
cutoff = num / 2
variance = -0.5
target = 1
for i, desired in enumerate(desired_data):
if i > cutoff:
variance = 0.5
target = -1
datum = {feature: random() * 2 - 1 / 2 + variance
for feature in features}
datum['class'] = target
data.append(datum)
return data
def test_random(num):
features = ['a', 'b', 'c']
train_data = generate_test_data(features, num)
test_data = generate_test_data(features, int(num * 0.9))
test(features, train_data, test_data)
def test(features, train_data, test_data):
perceptron = Perceptron(features)
perceptron.train(train_data)
perceptron.test(test_data)
return perceptron
def parse_vote_file():
"""Read the csv file and turn it into weights and appropriate tags"""
file_name = 'house-votes-84.data.txt'
data = []
features = []
with open(file_name) as raw_data:
for line in raw_data:
values = line.split(',')
target = values[0]
classed = 1
if 'republican' in target:
classed = -1
values.remove(target)
datum = {'class': classed}
features = []
for i, value in enumerate(values):
features.append(i)
if '?' not in value:
if 'y' in value:
value = 1
if value != 1 and 'n' in value:
value = int(-1)
datum[i] = value
data.append(datum)
return data, features
def test_vote():
"""Test the vote data using multiple trials to try and find the 'best'
perceptron to test with."""
data, features = parse_vote_file()
shuffle(data)
offset = len(data) - int(len(data) * 0.9)
train_data = data[:len(data) - offset]
test_data = data[len(data) - offset:]
print 'training %d testing %d' % (len(train_data), len(test_data))
best = None
best_accuracy = 0.0
accuracies = []
for x in xrange(10):
train_test = train_data
shuffle(train_test)
trial = test(features, train_data, train_test)
best_accuracy = max(trial.accuracy, best_accuracy)
if trial.accuracy == best_accuracy:
best = trial
accuracies.append(trial.accuracy)
print '-----------------------------------------------------'
print 'final against real test data'
best.test(test_data)
# This is to look at overfitting and to eventually see if a highly accurate
# trained perceptron does the best on the tests
print 'accuracies:', accuracies
if __name__ == '__main__':
test_vote()
|
db9ce863e4b5ea19e7387936f01835df22910ef5 | SashoStoichkovArchive/HB_TASKS | /projects/week10/08_05_2019/BCC/business_card.py | 3,426 | 4.03125 | 4 | import sqlite3, sys, os, pprint
def print_menu():
c = str(input(">>> Enter command: "))
if c == 'help':
print(
"""
#############
###Options###
#############
1. `add` - insert new business card
2. `list` - list all business cards
3. `get` - display full information for a certain business card (`ID` is required)
4. `delete` - delete a certain business card (`ID` is required)
5. `help` - list all available options
6. `exit` - exit the program
"""
)
elif c == 'add':
os.system('cls' if os.name == 'nt' else 'clear')
add_business_card()
elif c == 'list':
os.system('cls' if os.name == 'nt' else 'clear')
list_business_cards()
elif c == 'get':
os.system('cls' if os.name == 'nt' else 'clear')
id = int(input("Enter id: "))
get_business_card(id)
elif c == 'delete':
os.system('cls' if os.name == 'nt' else 'clear')
id = int(input("Enter id: "))
delete_business_card(id)
elif c == 'exit':
os.system('cls' if os.name == 'nt' else 'clear')
print("Goodbye!")
sys.exit(0)
def create_user_table():
connection = sqlite3.connect('bcc.db')
cursor = connection.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS User
(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT, email TEXT, age INTEGER, phone TEXT, add_info TEXT);
"""
)
connection.commit()
connection.close()
def add_business_card():
connection = sqlite3.connect('bcc.db')
cursor = connection.cursor()
name = str(input("Enter full name: "))
email = str(input("Enter email: "))
age = int(input("Enter age: "))
phone = str(input("Enter phone: "))
add_info = str(input("Enter additional info (optional): "))
cursor.execute(
"""
INSERT INTO User (name, email, age, phone, add_info) VALUES(?, ?, ?, ?, ?);
""", (name, email, age, phone, add_info)
)
connection.commit()
connection.close()
def list_business_cards():
connection = sqlite3.connect('bcc.db')
cursor = connection.cursor()
cursor.execute(
"""
SELECT * FROM User;
"""
)
pprint.pprint(cursor.fetchall())
connection.commit()
connection.close()
def get_business_card(id):
connection = sqlite3.connect('bcc.db')
cursor = connection.cursor()
cursor.execute(
"""
SELECT * FROM User WHERE id=?;
""", (id,)
)
id, name, email, age, phone, add_info = cursor.fetchone()
print(
"""
Contact Information:
###############
Id: {id},
Full name: {name}
Email: {email}
Age: {age}
Phone: {phone}
Additional info: {add_info}
##############
""".format(id=id, name=name, email=email, age=age, phone=phone, add_info=add_info)
)
connection.commit()
connection.close()
def delete_business_card(id):
connection = sqlite3.connect('bcc.db')
cursor = connection.cursor()
print("Following contact is deleted successfully")
get_business_card(id)
cursor.execute(
"""
DELETE FROM User WHERE id=?;
""", (id,)
)
connection.commit()
connection.close()
if __name__ == "__main__":
print("Hello! This is your business card catalog. What would you like? (enter 'help' to list all available options)")
while True:
create_user_table()
print_menu()
|
bda474719a7aab99cd2dced41bb8771e14476ae5 | swaathe/py | /pdt.py | 146 | 3.671875 | 4 | total = 1
n=[int(n) for n in input("enter the elements with whitespaces:").split()]
for i in range(0, len(n)):
total *= n[i]
print (total) |
2c8b33aaa502030497341bb22e90d57dc814f93d | yongyaoli/pystudy | /sample/c13.py | 1,139 | 3.59375 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
'''
BIF 函数 filter
filter:接收一个函数和序列,把传入的函数依次作用于每个序列元素,根据返回值说True还是False决定是否保留该元素
BIF 函数 sorted
排序: sorted函数可以对list进行排序
返回函数: 函数作为返回值
匿名函数:
list(map(lambda x: x * x, [1, 2, 3, 4, 5]))
关键词lambda 表示匿名函数,冒号前的x 表示函数参数
匿名函数只能是一个表达式,不用return
'''
# 保留奇数
def is_odd(n):
'''
保留奇数
'''
return n % 2 ==1
l = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
print(type(l))
print(l)
# 删除空字符串
def not_empty(s):
return s and s.strip()
print(filter(not_empty,['A', '', 'B', 'C',None,'','0']))
print('---'*30)
print(sorted([1, 90, -12, 12,-23]))
print("---"*30)
def lazy_sum(*args):
def sum():
nx = 0
for n in args:
nx = nx +n
return nx
return sum
s = lazy_sum(1, 2, 3, 4, 5, 6)
print(s)
print(s())
print('---'*20)
v = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7]))
print(v)
|
a0ebbca376a7d0709406c2af53ff9768b7206509 | ericgarig/daily-coding-problem | /021-min-classrooms.py | 813 | 3.859375 | 4 | """
Daily Coding Problem - 2018-10-28.
Given an array of time intervals (start, end) for classroom lectures
(possibly overlapping), find the minimum number of rooms required.
For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
"""
def min_classrooms(interval_list):
"""Given a list of time intervals, return min number of rooms."""
interval_list.sort()
room_end_times = [0]
for start, end in interval_list:
for room in range(len(room_end_times)):
if room_end_times[room] <= start:
room_end_times[room] = end
break
else:
# unable to find a room, so we must add another
room_end_times.append(end)
return len(room_end_times)
print(min_classrooms([(30, 75), (0, 50), (60, 150)])) # 2
|
a42fed93c707d7473fb77c4fdcf811db24799241 | selvendiranj-zz/python-bchain | /transactions.py | 1,600 | 3.9375 | 4 | """
validate transactions and update balance(state) functions
"""
def updateState(txn, state):
"""
We will take the first k transactions from the transaction buffer, and turn them into a block
"""
# Inputs: txn, state: dictionaries keyed with account names,
# holding numeric values for transfer amount (txn) or account balance (state)
# Returns: Updated state, with additional users added to state if necessary
# NOTE: This does not not validate the transaction, just updates the state!
# If the transaction is valid, then update the state
# As dictionaries are mutable, let's avoid any confusion
# by creating a working copy of the data.
state = state.copy()
for key in txn:
if key in state.keys():
state[key] += txn[key] # Update balance for existing account
else:
state[key] = txn[key] # Add balance to new account
return state
def isValidTxn(txn, state):
"""
Before we put transactions into blocks, we need to define a method for checking
the validity of the transactions we've pulled into the block
"""
# Assume that the transaction is a dictionary keyed by account names
# Check that the sum of the deposits and withdrawals is 0
if sum(txn.values()) is not 0:
return False
# Check that the transaction does not cause an overdraft
for key in txn.keys():
if key in state.keys():
acct_balance = state[key]
else:
acct_balance = 0
if (acct_balance + txn[key]) < 0:
return False
return True
|
bdcd0a4b0fe6a8b20396666d6204bd4bccdd8fdc | itadh/python_scripts | /count_things2.py | 86 | 3.625 | 4 | #!/usr/bin/python3
satz = input('Bitte geben Sie einen Satz ein: ')
print(len(satz))
|
54a7374c2e3ee73e5bb9fde51bbd628aa68a6bff | ufp1000/Python | /Graphs/Bachelor_Graph.py | 365 | 3.5625 | 4 | #import bokeh for plotting graph
from bokeh.plotting import figure
from bokeh.io import output_file,show
import pandas
#prepare some test data
df=pandas.read_csv("bachelors.csv")
x=df["Year"]
y=df["Engineering"]
#prepare the output file
output_file("Line from Bachelors.html")
print(df)
#create a figure object
f=figure()
#create line plot
f.line(x,y)
show(f) |
759a0c8825caeeed2c61825efc9d3f59d8f17a99 | narhumo/Short-joke-bot | /main.py | 2,508 | 3.59375 | 4 | import time
import random
while True:
Q = input(">").rstrip().lower()
jokes = []
jokes.append(['What did the skeleton say when he got spooked?', 'He was chilled to the bone!'])
jokes.append(["Why do archeologists keep dinosuar bones on their car?", "Because they're fossil fuels!"])
jokes.append(["Why did the dog cross the road?", "To get to the barking lot!"])
jokes.append(["what did the bread think when the dragon attacked?", "'I'm toast"])
jokes.append(["A Englishman and a Scotsman walk into a bar.", "The Irishman says:'ay laddy, that has got to hurt.'"])
jokes.append(["You know all those graveyards? They're really popular nowadays.", "Cause everyones dying to get in!"])
jokes.append(["What is the duck knight called?", "Sir Quack-a-lot!"])
jokes.append(["Which type of donut is homer simpsons favorite?", "A doh!nut"])
jokes.append(["two scientests walked into a bar, one ordered H20, the other said 'I'll have H20 too!", "The second scientest died."])
jokes.append(["A chicken layed more eggs than usual, and what did the farmer say?", "Eggcellent."])
jokes.append(["A man ate chicken in front of a Emu.", "It was not emused."])
jokes.append(["Why were the FBI worried about the spaghetti?", "It looked like a impasta."])
jokes.append(["What do you call a cat destroying the house?", "A catastrophe! And hundreds of dollars in damages."])
oops = []
oops.append("My proccessers cannot compute that.")
oops.append("I'm afraid my language proccessers cannot tell what you said.")
oops.append("My logic calculators do not make sense of that.")
oops.append("Error, Error")
oops.append("Pardon me, I don't understand.")
oops.append("Huh? I can't seem to find a response.")
if Q == "Hello".lower() or Q == "Hi".lower():
print("Hi!")
elif Q == "What are you".lower() or Q == "Who are you".lower() or Q == "Who are you?".lower() or Q == "What are you?".lower():
print("I am Robby! Do you want to know what I can do?")
elif Q == "What can you do?".lower() or Q == "What can you do".lower():
print("I tell jokes! Would you like to hear one?")
#if Q == "Yes".lower():
# rnd_joke = random.choice(jokes)
# print(rnd_joke[0])
# time.sleep(3)
# print(rnd_joke[1])
#elif Q != "Yes".lower():
# pass
elif Q == "Tell me a joke".lower():
rnd_joke = random.choice(jokes)
print(rnd_joke[0])
time.sleep(3)
print(rnd_joke[1])
elif Q == "bye":
break
else :
print(random.choice(oops))
|
0f5d283dae3af23815d2404abb3bb8da1c93a8b6 | bhattaraijay05/prg | /area_of_circle.py | 422 | 4.40625 | 4 | # from math import pi
# radius_of_circle=int(input("Enter the area of the circle "))
# area_of_circle=pi*radius_of_circle**2
# print("The area of the circle with radius: %.2f"%area_of_circle)
from math import pi
radius_of_circle = int(input("Enter the area of the circle "))
area_of_circle = pi * radius_of_circle ** 2
try :
radius_of_circle < 0
# print("The area of the circle with radius: %.2f"%area_of_circle) |
14b93f99b82243e6e2344086e529e084bc1f9534 | nymous-experiments/python-memory-game-forma-git-2021 | /outro.py | 656 | 3.609375 | 4 | from tkinter import *
from tkinter.font import Font
def show_victory(old_root):
old_root.destroy()
victory_screen = Tk()
victory_screen.title("Règles")
victory_screen.geometry("+300+100")
victory_screen.resizable(0, 0)
victory_screen.bind("<Escape>", lambda event: exit())
victory_screen.bind("<Button-1>", lambda event: exit())
victory_screen.bind("<Return>", lambda event: exit())
font = Font(victory_screen, size=25)
text = Label(
text="BRAVO\nVOUS AVEZ GAGNÉ",
font=font,
width="32",
anchor="center",
bg="misty rose",
)
text.pack(side=TOP)
victory_screen.mainloop()
|
6c4d38f9bf65685d9bbae420787da7cd31cc45e2 | Bouananhich/Ebec-Paris-Saclay | /user_interface/package/API/queries.py | 1,949 | 3.5625 | 4 | """Queries used with API."""
def query_city(
rad: float,
latitude: float,
longitude: float,
) -> str:
"""Create an overpass query to find the nearest city from the point.
:param rad: Initial search radius.
:param latitude: Latitude of the point.
:param longitude: Longitude of the point.
return overpass_query : build the query to find the nearest city from your
point
"""
overpass_query = f"""[out:json][timeout:800];(node["place"="town"](around:{rad},{latitude},{longitude});node["place"="city"](around:{rad},{latitude},{longitude});node["place"="village"](around:{rad},{latitude},{longitude}););out body;>;out skel qt;"""
return overpass_query
def query_street(
rad: float,
latitude: float,
longitude: float,
) -> str:
"""Create an overpass query to find the nearest street from the point.
:param rad: Initial search radius.
:param latitude: Latitude of the point.
:param longitude: Longitude of the point.
return overpass_query : build the query to find the nearest street
from your point
"""
overpass_query = f"[out:json][timeout:800];way(around:{rad},{latitude},{longitude})[name];(._;>;);out;"
return overpass_query
def query_ways(
latitude: float,
longitude: float,
) -> str:
"""."""
overpass_query_get_ways = f"[out:json][timeout:800];way(around:2,{latitude},{longitude})[name];(._;>;);out;"
return overpass_query_get_ways
def query_nodes(
id_node: int,
) -> str:
"""Create the query to find a node defined by its id.
:param id_node: Integer that is a primary key for nodes.
return overpass_query_get_node : build the query to get the node associated
to the id
"""
overpass_query_get_node = f"[out:json][timeout:800];node({id_node});out;"
return overpass_query_get_node
__all__ = ["query_city", "query_street", "query_ways", "query_nodes"]
|
e856b1f96d08d75ebc73145f541f7f33908b7be1 | lucioeduardo/cc-ufal | /APC/Listas/06 - Recursão/q2.py | 408 | 3.921875 | 4 | """
Implemente uma função recursiva que, dados dois
números inteiros x e n, calcule o valor de x^n
"""
#O(n) - Solução óbvia
def exp(x, n):
if(n == 0):
return 1
return x*exp(x,n-1)
#O(log n) - Exponenciação rápida
def fast_exp(x, n):
if(n == 0):
return 1
if(n % 2):
return x*fast_exp(x*x,n//2)
return fast_exp(x*x,n//2)
print(exp(3,5), fast_exp(3,5))
|
5c49826b3547a26819a594531f242e84c6071741 | Boellis/ObjectDetection | /scripts/renameFile.py | 669 | 4.125 | 4 | import os
path = input("Enter the path or folder name: ") #This is the path relative to the directory this script is stored on (use / instead of \)
updatedFilename = input("Enter the updated name: ")
files = os.listdir(path)
print("Are sure you want to rename the following files?")
print(files)
awns = input("(y/n): ").lower()
if awns == "y" or awns == "yes" or awns == "yeah" or awns == "probably" or awns == "yup" or awns == "you bet":
i = 1
for file in files:
root, ext = os.path.splitext(file) #ext will get the file extension of the file
os.rename(os.path.join(path,file), os.path.join(path, updatedFilename+str(i)+ext))
i+=1
|
8c0ac6916ccb5209f031450a3c5ac51080f3071d | SarvagyaShastri/Algorithms | /Longest Increasing subsequence.py | 836 | 3.703125 | 4 | #LIS IN O(NLOGN)
def findIndex(sequence,value):
middle=0
beg=0
end=len(sequence)
while end-beg>1:
middle=beg+(end-beg)/2
if sequence[middle]>value:
end=middle
else:
beg=middle
return end
#
def find_lis(elements):
sequence=[]
sequence.append(elements[0])
for i in xrange(1,len(elements)):
if elements[i]>sequence[-1]:
sequence.append(elements[i])
elif elements[i]<sequence[0]:
sequence[0]=elements[i]
else:
index=findIndex(sequence,elements[i])
print index,"this is index","______________________________________________________"
sequence[index]=elements[i]
print len(sequence)
def main():
try:
elements=map(int, raw_input("Enter the elements").split())
except Exception:
print "Please enter integer values next time."
lis=[1]*len(elements)
find_lis(elements)
main() |
c2e8c30f998ffa148bc673ffacb926b49e890a83 | therealdavidbrown/Sprint-12062020---Dice-Simulator | /DB Sprint 12062020.py | 1,743 | 4.25 | 4 | import random
line = "_______________________________________________________________________________\n"
print("Welcome to\n \nDICE ROLL SIM 11\nThese go up to eleven.\n"+line)
print("This game is your one-size-fits-all for random number generationin games. You can generate random numbers for any polyhedral die, and it supports any number of dice.\nEven 11 eleven-sided dice"+line)
# Welcomes the user to the game. '11' and "these go up to eleven" is a gratuitous reference to This Is Spinal Tap, one of the greatest movies of all time
def roll(nDice, nSides): # function for rolling dice, takes the number of dice, and the number of sides of each die into account
for i in range(nDice):
print(random.randrange(0, nSides) + 1)
play_game = input('Are you ready to roll the dice? Enter Yes or No.').lower()
if play_game.lower()[0] == 'y':
game_on = True # variable for while loop, avoids the program from running forever and getting stuck in a loop
while game_on == True:
nDice = int(input('how many dice are there? Enter an integer.')) # asks the user the number of dice
nSides = int(input("how many sides does each die have?"))# asks the user for the number of sides for each die
roll(nDice, nSides)# rolls the dice
play_game = input('Do you wish to play again? Enter yes or no.')# asks the user each time they wish to roll the dice, this helps with each turn in the game
if play_game.lower()[0] == 'n': # checks if the user said no to rolling again
game_on = False # ends the while loop
else: print("Thanks for making DICE ROLL SIM 11 your dice simulator of choice. We look forward to seeing you again!") # while else loop that thanks the user for their... use... of the program
|
d8dd6f51ee707aa26fc0db0354fe390d92f21c48 | xeon2007/machine-learning | /justin-python-ml/homeworks/hw1.py | 3,083 | 3.71875 | 4 | import numpy as np
import random
from pprint import pprint
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, training_set=None, testing_set=None, weights=None):
# Default weights to [0, 0, 0]
if weights == None:
self.weights = [0., 0., 0.]
else:
self.weights = weights
self.training_set = training_set
self.testing_set = testing_set
# Points 1 and 2 used to draw line
# aka produces our target function!
self.point1 = (np.random.uniform(-1, 1), np.random.uniform(-1, 1))
self.point2 = (np.random.uniform(-1, 1), np.random.uniform(-1, 1))
# 1/-1 for above/below the line
def getTargetLabel(self, feature):
x1, y1 = self.point1
x2, y2 = self.point2
# Remember, x0 is the default 1
x0, feature_x, feature_y = feature
slope = (y2 - y1) / (x2 - x1)
return 1 if feature_y > (y1 + slope * (feature_x - x1)) else -1
def hypothesis(self, feature):
return np.sign(np.dot(feature, self.weights))
def train(self):
misclassified = []
iterations = 0
while True:
# Grab misclassified points
for feature in self.training_set:
target_y = self.getTargetLabel(feature)
predicted_y = self.hypothesis(feature)
if predicted_y != target_y:
misclassified += [(feature, target_y)]
# If there are misclassified points, keep trying
if misclassified:
iterations += 1
feature, target_y = random.choice(misclassified)
adjustment = np.dot(feature, target_y)
self.weights += adjustment
misclassified = []
else:
break
return iterations
def test(self):
num_wrong = 0.
for feature in self.testing_set:
target_y = self.getTargetLabel(feature)
predicted_y = self.hypothesis(feature)
if predicted_y != target_y:
num_wrong += 1
return num_wrong / len(self.testing_set)
def runPLA(data_size=10, num_iterations=1000):
training_set = [[1., np.random.uniform(-1, 1), np.random.uniform(-1, 1)]
for i in xrange(data_size)]
testing_set = [[1., np.random.uniform(-1, 1), np.random.uniform(-1, 1)]
for i in xrange(data_size)]
avg_iterations = 0
avg_disagreement = 0
plot_weights = []
for i in range(num_iterations):
pla = Perceptron(training_set=training_set, testing_set=testing_set)
avg_iterations += pla.train()
avg_disagreement += pla.test()
plot_weights.append(pla.weights)
avg_iterations = avg_iterations / num_iterations
avg_disagreement = avg_disagreement / num_iterations
return avg_iterations, avg_disagreement
if __name__ == "__main__":
print 'With data_size = 10,', runPLA(data_size=10)
# print 'With data_size = 100,', runPLA(data_size=100)
|
e039d4ef81bd553ec67eb5b516d7d986e5cfeced | lemonnader/LeetCode-Solution-Well-Formed | /greedy/Python/0435-non-overlapping-intervals(按起始点排序).py | 936 | 3.78125 | 4 | from typing import List
class Solution:
# 按照起点排序:选择结尾最早的,后面才有可能接上更多的区间
# 那么要删除的就是:与之前的区间有重叠的,并且结尾还比当前结尾长的
# 关键:如果两个区间有重叠,应该保留那个结尾短的
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
size = len(intervals)
if size <= 1:
return 0
intervals.sort(key=lambda x: x[0])
end = intervals[0][1]
res = 0
for i in range(1, size):
if intervals[i][0] < end:
res += 1
end = min(end, intervals[i][1])
else:
end = intervals[i][1]
return res
if __name__ == '__main__':
intervals = [[1, 2], [1, 2], [1, 2]]
solution = Solution()
result = solution.eraseOverlapIntervals(intervals)
print(result)
|
12758d56534c5864e6c69b2e82bfa2891b8a6983 | jackhscompbook/VeryBadGraphingCalculator | /calc.py | 3,322 | 3.546875 | 4 |
import math
class calc:
def __init__(self):
self.coordinates = {}
self.tmp_x = 0
self.tmp_y = 0
self.x_max = 10
self.x_min = 1
self.y_max = 10
self.y_min = 1
self.x_step = (self.x_max - self.x_min)/10
self.y_step = (self.y_max - self.y_min)/10
def drange(self, start, stop, step):
r_value = start
while r_value < stop:
yield r_value
r_value += step
def calc(self, function='x'):
y_Values = []
op_list = self.cut(function)
x_Values = [x for x in self.drange(self.x_min, self.x_max, self.x_step)]
for value[1] in x_Values:
self.find_value(value, op_list)
self.display()
def find_value(self, value, op_list, iteration=0):
# value should be an int
# op_list should be a list formatted like this:
# [<operation (str)>, <2nd operator (int)>, <optional 2nd layer op_list (list)>]
if not iteration:
self.tmp_x = value
iteration += 1
if op_list[ 0 ] == 'a':
value += op_list[ 1 ]
elif op_list[ 0 ] == 's':
value -= op_list[ 1 ]
elif op_list[ 0 ] == 'm':
value *= op_list[ 1 ]
elif op_list[ 0 ] == 'd':
value /= op_list[ 1 ]
elif op_list[ 0 ] == 'n':
pass
else:
print(f'incorrect mode: {op_list[0]} at op_list[0]')
try:
self.find_value(value, op_list[2], iteration=iteration)
except IndexError:
self.coordinates[int(self.tmp_x)] = int(value)
def cut(self, function):
# input: '10*x+3'
# output: ['m', 10, ['a', 3]]
# return op_list
if function == 'x':
op_list = ['n']
elif '*' in function:
cut = function.split('*')
if cut[0] != 'x':
op_list = ['m', int(cut[0]), self.cut(cut[1])]
else:
op_list = ['m', int(cut[1])]
elif '/' in function:
cut = function.split('/')
if cut[0] != 'x':
op_list = ['d', int(cut[0]), self.cut(cut[1])]
else:
op_list = ['d', int(cut[1])]
elif '+' in function:
cut = function.split('+')
if cut[0] != 'x':
op_list = ['a', int(cut[0]), self.cut(cut[1])]
else:
op_list = ['a', int(cut[1])]
elif '-' in function:
cut = function.split('-')
if cut[0] != 'x':
op_list = ['s', int(cut[0]), self.cut(cut[1])]
else:
op_list = ['s', int(cut[1])]
return op_list
def display(self):
graph = [
['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
['|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
['+','_','_','_','_','_','_','_','_','_','_']
]
print(self.coordinates)
for x in self.coordinates.keys():
if x > self.x_max or x < self.x_min:
continue
elif self.coordinates[x] > self.y_max or self.coordinates[x] < self.y_min:
continue
else:
print(x, self.coordinates[x])
graph[-(self.coordinates[x]+1)][x] = ':'
for row in graph:
for column in row:
print(column, end=' ')
print('')
c = calc()
c.calc('x') |
1a9e141a9dacb746293a0bddc7ad9b3a1947b8e9 | maxpipoka/cursofullstack | /03_Tercera_clase/ejercicio_04.py | 937 | 3.6875 | 4 | # Enunciado
# Dada una lista (lista1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]),
# iterarla y mostrar números divisibles por cinco, y si encuentra un
# número mayor que 150, detenga la iteración del bucle
import os
import sys
####################################################################################
#Funciones
def borrarPantalla(): #Funcion para limpiar pantalla detectando SO
if os.name == "posix":
os.system ("clear")
elif os.name == "ce" or os.name == "nt" or os.name == "dos":
os.system ("cls")
def iterarLista(lista1):
menorA150 = True
for i in lista1:
if i > 150:
break
if i%5 == 0:
print(f'{i} es divisible por 5.')
####################################################################################
# Codigo principal
borrarPantalla()
lista1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
iterarLista(lista1)
sys.exit() |
1436dd0ea54a70520ad6ab3885853ca0f4f792a6 | nagagopi19/Python-programms | /weekbyacceptinganumber.py | 437 | 4.21875 | 4 | """
To display day of the week by accepting a number.
Author: K Naga Gopi
Version: v1.0
Company: Google Inc
Project: abc1234
Code:34_45
"""
n = int(input('Enter a number(1-7): '))
if n==1:
print('Sunday')
elif n==2:
print('Monday')
elif n==3:
print('Tuesday')
elif n==4:
print('Wednesday')
elif n==5:
print('Thrusday')
elif n==6:
print('Friday')
elif n==7:
print('Saturday')
else:
print("Not a valid Number")
|
e7b5fe4016707db95e1cccaa5e78907ec9d41565 | sotiriskalogiros/python | /ασκηση 7.py | 270 | 3.796875 | 4 | from datetime import datetime
# Get a datetime object
now = datetime.now()
# General functions
print "Year: %d" % now.year
print "Month: %d" % now.month
print "Day: %d" % now.day
print "Weekday: %d" % now.weekday() # Day of week Monday = 0, Sunday = 6
|
b593a0038755848a41323b3e2379ca7aecb0fa0a | PaigeThePain/Fizz-Buzz | /fizz.py | 354 | 4.09375 | 4 | print("Welcome to Fizz Buzz\n")
number = int(input("Please enter a number to count up to."))
counter = 1
while counter <= number:
if counter % 3 == 0 and counter % 5 == 0:
print ("Fizz Buzz")
elif counter % 3 == 0:
print("Fizz")
elif counter % 5 == 0:
print("Buzz")
else:
print(counter)
counter += 1 |
dd1fef5a62e98becb9e859b5ad3edd626537a4c2 | AhmedEssamIsmail/Virtual-Whiteboard | /Board.py | 358 | 3.53125 | 4 | import cv2 as cv
import numpy as np
def draw(board, first_point, second_point, color, thickness, inwardDist):
dist = np.sqrt(pow((first_point[0] - second_point[0]), 2) + pow((first_point[1] - second_point[1]), 2))
if dist < inwardDist:
cv.line(board, first_point, second_point, color, thickness)
cv.imshow('Virtual Whiteboard', board)
|
cccca544fb364071e42ec8991e150a888160f48b | zhaolijian/suanfa | /huawei/6.py | 733 | 3.859375 | 4 | # 功能:输入一个正整数,按照从小到大的顺序输出它的所有质因子(重复的也要列举)(如180的质因子为2 2 3 3 5 )
# 最后一个数后面也要有空格
# 方法1
x = int(input())
flag = False
for i in range(2, x // 2 + 1):
while x % i == 0:
flag = True
print(i, end=' ')
x = x // i
if not flag:
print(x, end=' ')
# 方法2
x = int(input())
flag = False
for i in range(2, x + 1):
while x % i == 0:
flag = True
print(i, end=' ')
x = x // i
# 方法3
x = int(input())
p = 2
while True:
if x % p == 0:
print(p, end=' ')
x //= p
elif p * p > x:
print(x, end=' ')
break
else:
p += 1 |
3bf4a8ac01f61d7e33f97821ad524444e95ffba9 | hihumi/renote | /sub.py | 630 | 4 | 4 | #!/usr/bin/env python3
"""renote: re sub module
"""
import re
def my_sub(word):
"""renote: re sub function
"""
pattern = re.compile(r'p')
res = pattern.sub('P', word)
if res:
print('{}'.format(res))
print('OK')
else:
print('NG')
if __name__ == '__main__':
print('文字列を入力 終了するにはq, Qキー')
print('>>> ', end='')
while True:
enter_word = input()
if enter_word == 'q' or enter_word == 'Q':
print('終了')
break
elif enter_word:
my_sub(enter_word)
print('>>> ', end='')
|
2c5873651cd6b9d0e8762f1490b944be6056651a | dlevylambert/project2-pd6 | /Group7/utils.py | 3,211 | 3.515625 | 4 | import urllib2
import json
from operator import itemgetter
def utils(url):
return json.loads(urllib2.urlopen(url).read())
def currentYear(item,year,dInd):
"""
item: Event data
year: last 2 digits of year (i.e. "12" or "13")
dInd: index of the time criteria to parse through (i.e. 12 = 'StartEventTime') for an event)
returns true if event occurs in the same year as input
standardizes date format: MM/DD/YY
standardizes time format: 00:00 AM or 00:00 PM
"""
boolean = False
me=item[dInd]
if me[1:2]=="/" and (me[4:6]==year or me[5:7]==year):
if me[3:4]=="/":
if me[4:6]==year:
me=str(me[:2])+"0"+str(me[2:])
boolean = True
else:
if me[5:7]==year:
boolean = True
me="0"+str(me)
else:
if me[4:5]=="/" and me[5:7]==year:
me=str(me[:3])+"0"+str(me[3:])
boolean=True
elif me[6:8]==year:
boolean=True
me=str(me)
if boolean and me[10:11]==":":
me= me[:9]+"0"+me[9:]
item[dInd]=me
return boolean
def sortB(l,b):
"""
l: list to sort through
b: borough to look for
"""
boro=[]
for i in l:
if i[19]==b:
boro.append(i)
return boro
def sortT(l):
"""
returns the input, list, sorted by time
according to the start time of the event (index 12)
from most recent to least recent
"""
return sorted(l,key=itemgetter(12), reverse=True)
def getE():
url ="https://data.cityofnewyork.us/api/views/xenu-5qjw/rows.json"
events=[]
events2013=[]
for i in utils(url)['data']:
if currentYear(i,"12",12):
events.append(i) #every event that occured in 2012
elif currentYear(i,"13", 12):
events2013.append(i)
events=sortT(makeString(events))
events2013=sortT(makeString(events2013))
events = events2013+events
return events
def geteAfter(month,day,year,b):
events=getB(b)
after=[]
for i in events:
if i[12][6:8]>year:
after.append(i)
elif i[12][6:8]==year:
if i[12][0:2]>month:
after.append(i)
elif i[12][0:2]==month:
if i[12][3:5]>day:
after.append(i)
return after
def geteOn(month,day,year,b):
events=getB(b)
on=[]
for i in events:
if i[12][6:8]==year:
if i[12][0:2]==month:
if i[12][3:5]==day:
on.append(i)
return on
def geteBefore(month,day,year,b):
events=getB(b)
before=[]
for i in events:
if i[12][6:8]<year:
before.append(i)
elif i[12][6:8]==year:
if i[12][0:2]<month:
before.append(i)
elif i[12][0:2]==month:
if i[12][3:5]<day:
before.append(i)
return before
def makeString(l):
temp = l
for i in temp:
n=0
while n<len(i):
i[n]=str(i[n])
n=n+1
l = temp
return l
#print events
def getB(b):
events=getE()
return sortB(events,b)
#for i in getB("Manhattan"):
# print i[12]
|
598f30422edb5efa30431dc3f24fecfcbe42ae6a | kayartaya-vinod/2017_08_PHILIPS_PYTHON | /Examples/userexceptions.py | 588 | 3.625 | 4 | # this and every file with .py is known as a module
# A module may comprise: variables, functions, classes, or some executable code
# variables, functions and classes from this module can be used in other modules
class InvalidAgeException(Exception):
def __init__(self, message = "Invalid age. Must be a number between 1 and 120"):
self.__message = message
def __str__(self):
return self.__message
class InvalidNameException(Exception):
def __init__(self, message = "Invalid name. Must be a string"):
self.__message = message
def __str__(self):
return self.__message
|
b8c5a0d5c26d9749b8b2b0dc79b07068c63914f8 | swayamsudha/python-programs | /per_sq.py | 258 | 4.15625 | 4 | ##WAP TO CHECK A NUMBER IF A PERFECT SQUARE OR NOT
num=int(input("Enter the number: "))
root=(num**0.5)
#print("root =",root)
n=int(root+0)**2
#print("n=",n)
if n ==num:
print(num,"is a perfect square:")
else:
print(num,"is not a perfect square:")
|
7bfa4459f593f06921d1bf516d86b1ada8422c09 | korniloff75/TestPython | /21/__init__.py | 1,211 | 3.8125 | 4 | # koloda = range(6,11) * 10
koloda = [6,7,8,9,10,2,3,4,11] * 10
import random
random.shuffle(koloda)
print('Поиграем в очко?')
userCount = 0
bankCount = 0
while True:
choice = input('Будете брать карту? y/n\n')
if (choice == 'y') or (choice == 'н'):
current = koloda.pop()
bankStep = koloda.pop()
print('Вам попалась карта достоинством %d' %current)
userCount += current
bankCount += bankStep
print('У банкира %d очков' %bankCount)
if bankCount > 21:
print('Банкир проиграл, набрав %d очков' %bankCount)
break
if userCount > 21:
print('Извините, но вы проиграли, набрав %d очков' %userCount)
break
elif userCount == 21:
print('Поздравляю, вы набрали 21!')
break
else:
print('У вас %d очков.' %userCount)
elif choice == 'n':
print('У вас %d очков и вы закончили игру.' %userCount)
print('У банкира %d .' %bankCount)
if userCount > bankCount:
print('Вы победили.')
else:
print('Вы проиграли')
break
print('До новых встреч!')
|
22c78d3a5f29d31b38fe9bde2128ffbb6e58ab10 | ManMMD/Manyu | /homework_day_5/1.py | 454 | 3.6875 | 4 | class Rectangle:
def __init__(self,width=1,height=2):
self.width=width
self.height=height
print('Width:'+str(self.width))
print('Height:'+str(self.height))
def getArea(self):
print('Area:'+str(self.width*self.height))
def getPerimeter(self):
print('Perimeter:'+str(self.width*2+self.height*2))
m=Rectangle(4,40)
m.getArea()
m.getPerimeter()
n=Rectangle(3.5,35.7)
n.getArea()
n.getPerimeter()
|
c576dc419a8ce0b15b8e1de768c48f9ca0501274 | Sanjay-Nithish-KS/Text-Editor-using-PyQT | /FileDisplay.py | 1,407 | 3.515625 | 4 | """
FileDisplay Class
The Class FileDisplay is used to display the file content in the
text editor's text area.
The FileDisplay class can display both text files and image files.
Usage:
import FileDisplay
FileDisplay.FileDisplay(file_path,TextEditor object)
"""
import re
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import alertWindow
class FileDisplay:
def __init__(self,file_path,editor_window):
self.file_path = file_path
self.editor_window = editor_window
regex = "([^\\s]+(\\.(?i)(jpe?g|png|gif|bmp))$)"
p = re.compile(regex)
if re.search(p,file_path):
self.displayImageFile(file_path)
else:
self.displayTextFile(file_path)
def displayTextFile(self,file_path):
"""
displayTextFile displays text files in the text editor's
text area.
"""
try:
file_content = open(file_path).read()
self.editor_window.text_area.setPlainText(file_content)
except:
alertWindow.createAlert(alertWindow,'You have not chose any file to open')
def displayImageFile(self,file_path):
"""
displayTextFile displays Image files in the text editor's
text area.
"""
self.editor_window.text_area.setPlainText("")
document = self.editor_window.text_area.document()
cursor = QTextCursor(document)
position = cursor.position()
cursor.insertImage(file_path)
|
cda9c3f672cde4b3e3b92597656f43e7a0540fe4 | mmthatch12/Algo-rith | /lecture/fibonacci.py | 1,225 | 3.8125 | 4 | # fibonacci
# good practice is to do both of these inside another function
# don't really want cache to be global
# def fib(n):
# cache = {} #memorization
# def fibn(n):
# if n == 0:
# return 0
# elif n == 1:
# return 1
# if n not in cache:
# cache[n] = fibn(n-1) + fibn(n-2)
# return cache[n]
# return fibn(n)
# def otherway(n):
# if n == 0:
# return 0
# elif n == 1:
# return 1
# prevprev = 0
# prev = 1
# for _ in range(n-1):
# cur = prevprev + prev
# prevprev = prev
# prev = cur
# return cur
# print(otherway(450))
cache = {} #memorization
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
if n not in cache:
cache[n] = fib(n-1) + fib(n-2)
return cache[n]
print(fib(50))
# def orfib(n):
# if n==0:
# return 0
# elif n == 1:
# return 1
# return fib(n-1)+fib(n-2)
# def fib(n):
# if n == 0:
# return 0
# elif n == 1:
# return 1
# final = 0
# for i in range(0, n):
# final += (i-1) + (i-2)
# return final
# for i in range(40):
# print(fib(i)) |
270fe141ad3a3e5ba0edad692e7564eb92f9fa1b | bfridkis/CS325---Miscellaneous | /makingChange_RunningTimes_TimeAsFunctionOfnA.py | 1,491 | 3.546875 | 4 | #################################################################
## Program name: makingChange_RunningTimes_TimeAsAFunctionOfA.py
## Class name: CS325-400
## Author: Ben Fridkis
## Date: 4/19/2018
## Description: Program to time minimumChange for various sizes
## of array parameter "V" and various values for
## parameter "A".
#################################################################
import time
import random
def minimumChange(V, A):
singleCoin = False
C = []
for denomination in V:
if denomination == A:
C.append(1)
singleCoin = True
else:
C.append(0)
if singleCoin:
C.append(1)
return C
CA = [[0 for y in range(len(V) + 1)] for x in range(A + 1)]
for i in range(1, A + 1):
if i in V:
CA[i][V.index(i)] = 1
CA[i][len(V)] = 1 #The last array element holds the coin count
else:
minArray = []
for j in range(1, int(i/2) + 1):
currentArray = [x + y for x, y in zip(CA[i - j], CA[i - (i - j)])]
if j == 1:
minArray = currentArray
else:
if currentArray[len(V):] < minArray[len(V):]:
minArray = currentArray
for k in range(len(V) + 1):
CA[i][k] = minArray[k]
return CA[A]
for i in range(1, 11):
A = 750 * i
V = [1] + random.sample(range(2, A+1),i*10-1)
start_time = time.time()
minimumChange(V, A)
end_time = time.time()
run_time = end_time - start_time
print(str(A*len(V)) + ": " + str(run_time))
print("\n\n----Done----\n\n") |
1ac6379a53680454aef975f5f3354b2a490e1f9c | galigaribaldi/Proyecto_Coneyotl | /DB/cargainfo.py | 417 | 3.8125 | 4 | # -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect('baseConeyotl.db')
cursor = con.cursor()
carga = open("cargaCalifgrado.sql",'r') ##abrimos nuestro archivo en modo lectura
for i in carga:
print(i)
cursor.execute(i)
#linea = carga.readline()
#print(linea)
#cursor.execute('''INSERT INTO estudiante VALUES(10000, 'Dafne Cabrera Garibaldi', 'Su casa', 10, '4to primaria')''')
con.commit()
con.close()
carga.close() |
7999b7f181ce2fb6acc9eae46920e21c4a212d1a | spettigrew/cs2-fundamentals-practice | /mod2-Time_Space_Complexity/space_complexity.py | 1,054 | 4.5 | 4 | """
Use Big O notation to classify the space complexity of the function below.
Space complexity - anything additional the function is adding to memory.
"""
def fibonacci(n):
lst = [0, 1]
for i in range(2, n):
lst.append(lst[i-2] + lst[i-1])
return lst[n-1]
# appending is storing a value in the list. O(n)
"""
Use Big O notation to classify the space complexity of the function below.
"""
def fibonacci_two(n):
x, y, z = 0, 1, None
if n == 0:
return x
if n == 1:
return y
for i in range(2, n):
z = x + y
x, y = y, z
return z
# space complexity remains the same, because we're only returning the value of z. O(1)
# Time complexity is O(n) because the number of operations will increase as the list increases.
"""
Use Big O notation to classify the space complexity of the function below.
"""
def do_something(n):
lst = []
for i in range(n):
for j in range(n):
lst.append(i + j)
return lst
# append = O(n) |
a600fc4768e060c89540ac958144d0ce5e42db64 | jaishiva/SudokuSolver | /SudokuSolver.py | 4,253 | 4.03125 | 4 | # contains board and method to display board
class sudoku:
def __init__(self,board):
self.board = board
def __str__(self):
visual = ""
for i in range(0,9):
for j in range(0,9):
visual += str(self.board[i][j].value) + ' '
if ((j+1) == 3) or ((j+1) == 6):
visual += "| "
if ((i+1) == 3) or ((i+1) == 6):
visual += "\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _"
visual += '\n\n'
return visual
# cell is a block in the board, cell object has a value and position
class cell:
def __init__(self,value,i,j):
self.value = value
if self.value == '.':
self.possibilities ={1,2,3,4,5,6,7,8,9}
else:
self.possibilities = {}
self.row = i
self.column = j
def __str__(self):
return str(self.value)
# get and set all the possibilities a cell has storing the final list in the cell's possibility param
def get_possibility(cell,sudoku):
for c in sudoku.board[cell.row]:
if c != cell and c.value != '.':
cell.possibilities -= {c.value}
for c in range(9):
if c != cell.row and sudoku.board[c][cell.column] != '.':
cell.possibilities -= {sudoku.board[c][cell.column].value}
if cell.column < 3:
start_col = 0
elif cell.column < 6:
start_col = 3
else:
start_col = 6
if cell.row < 3:
start_row = 0
elif cell.row < 6:
start_row = 3
else:
start_row = 6
for r in range(start_row,start_row+3):
for c in range(start_col,start_col+3):
if sudoku.board[r][c] != cell and sudoku.board[r][c] != '.':
cell.possibilities -= {sudoku.board[r][c].value}
def back_tracking():
if not is_empty():
return True
empty_cell = is_empty()
for poss in empty_cell.possibilities:
empty_cell.value = empty_cell.possibilities.pop()
if check_for_validity(empty_cell,sudoku):
if back_tracking():
return True
empty_cell.possibilities.add(empty_cell.value)
empty_cell.value ='.'
return False
def check_for_validity(empty_cell,sudoku):
for c in sudoku.board[empty_cell.row]:
if c.column != empty_cell.column and c.value == empty_cell.value:
return False
for c in range(9):
if c != empty_cell.row and sudoku.board[c][empty_cell.column].value == empty_cell.value:
return False
if empty_cell.column < 3:
start_col = 0
elif empty_cell.column < 6:
start_col = 3
else:
start_col = 6
if empty_cell.row < 3:
start_row = 0
elif empty_cell.row < 6:
start_row = 3
else:
start_row = 6
for r in range(start_row,start_row+3):
for c in range(start_col,start_col+3):
if sudoku.board[r][c].value == empty_cell.value and sudoku.board[r][c] != empty_cell:
return False
return True
# init - initial setup of board
board = []
given_board = [5,3,'.','.',7,'.','.','.','.',6,'.','.',1,9,5,'.','.','.','.',9,8,'.','.','.','.',6,'.',8,'.','.','.',6,'.','.','.',3,4,'.','.',8,'.',3,'.','.',1,7,'.','.','.',2,'.','.','.',6,'.',6,'.','.','.','.',2,8,'.','.','.','.',4,1,9,'.','.',5,'.','.','.','.',8,'.','.',7,9]
counter =0
for i in range(9):
row = []
for j in range(9):
row.append(cell(given_board[counter],i,j))
counter += 1
board.append(row)
sudoku = sudoku(board)
print(sudoku)
# get all possible solutions and set the values where there is only one possibility
for i in range(9):
for j in range(9):
if sudoku.board[i][j].value == '.':
get_possibility(sudoku.board[i][j],sudoku)
print(sudoku.board[i][j].possibilities)
if len(sudoku.board[i][j].possibilities)==1:
sudoku.board[i][j].value = sudoku.board[i][j].possibilities.pop()
print(sudoku)
def is_empty():
for i in range(9):
for j in range(9):
if sudoku.board[i][j].value == '.':
return sudoku.board[i][j]
return False
back_tracking()
print(sudoku) |
847674385f9369f3afbd02665d64ebcbe3e40d42 | AmandaRH07/AulaEntra21_AmandaHass | /Prof01/Aula05/if_parte1/exercicio07.py | 327 | 4.125 | 4 | # Exercicio 7
# Faça um programa que peça 3 números inteiros e mostre o menor número.
n1 = int(input("Insira o n1: "))
n2 = int(input("Insira o n2: "))
n3 = int(input("Insira o n3: "))
if n1 < n2 and n1 < n3:
print("Menor: ", n1)
elif n2 < n1 and n2< n3:
print("Menor: ", n2)
else:
print("Menor: ", n3)
|
462b4ab492182830a0a1a8b9dc37c4eeeaefc06f | tsaitiieva/Python | /Lesson5.py | 1,983 | 3.828125 | 4 | import functools
x=[1, -2, 3, -50, 40, -90]
result = filter(lambda x: x>0, x)
# возвести все положительные элементы последовательности в квадрат
def positive_in_square(el):
if el>0:
return el**2
else:
return el
print(list(map(positive_in_square, x)))
# map принимает 2 параметра: func и *iterables.
# map makes an iterator that computes the function using arguments from each of the iterables.
def make_p(func):
functools.wraps(func)
def wrapper(*args):
result = '{0} {1} {2}'.format('<p>', func(*args), '</p>')
return result
return wrapper
def make_strong(func):
functools.wraps(func)
def wrapper(*args):
result = '{0} {1} {2}'.format('<strong>', func(*args), '</strong>')
return result
return wrapper
#декоратор инициалиируется один раз для каждой новой переданой ему функции. После того как он инициализирован вызывается только wrapper
def check_count(func):
functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
print(wrapper.calls)
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@check_count
@make_strong
@make_p
def create_text(text):
return text
# print(create_text('Hello world!'))
# print(create_text('Hello world!'))
# print(create_text('Hello world!'))
# Генераторы
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# for num in numbers:
# print(num)
[num for num in numbers]
[num for num in numbers if num>0]
divide_by_two = [str(num) for num in numbers if num%2==0]
for num in divide_by_two:
print(num)
#Генератор инициализирует по одному элементу, а не все элементы списка сразу
#Генератор может быть и dictionary {} |
41d0fed2dec6c4d9ab40c663e80105c7c7ba2278 | ravinaNG/python | /List/sa_re_ga_ma_pa_level.py | 6,075 | 3.6875 | 4 | sargam = ["sa", "re", "ga", "ma", "pa", "dh", "ni", "Sa"]
level = 0
while(level < len(sargam)):
rag = 0
while(rag < len(sargam)):
if (level == 0):
print (sargam[rag])
if (level == 1):
if (rag == 0):
print (sargam[0])
print (sargam[rag + 1])
rag = 1
else:
print (sargam[rag-1])
print (sargam[rag])
if (level == 2):
if (rag == 0):
print (sargam[0])
print (sargam[rag + 1])
print (sargam[rag + 2])
rag = 2
else:
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
if (level == 3):
if (rag == 0):
print (sargam[0])
print (sargam[1])
print (sargam[2])
print (sargam[3])
rag = 3
else:
print (sargam[rag - 3])
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
if (level == 4):
if (rag == 0):
print (sargam[0])
print (sargam[1])
print (sargam[2])
print (sargam[3])
rag = 4
else:
print (sargam[rag - 4])
print (sargam[rag - 3])
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
if (level == 5):
if (rag == 0):
print (sargam[0])
print (sargam[1])
print (sargam[2])
print (sargam[3])
print (sargam[4])
rag = 5
else:
print (sargam[rag - 4])
print (sargam[rag - 3])
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
sargam = ["sa", "re", "ga", "ma", "pa", "dh", "ni", "Sa"]
level = 0
while(level < len(sargam)):
rag = 0
while(rag < len(sargam)):
if (level == 0):
print (sargam[rag])
if (level == 1):
if (rag == 0):
print (sargam[0])
print (sargam[rag + 1])
rag = 1
else:
print (sargam[rag-1])
print (sargam[rag])
if (level == 2):
if (rag == 0):
print (sargam[0])
print (sargam[rag + 1])
print (sargam[rag + 2])
rag = 2
else:
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
if (level == 3):
if (rag == 0):
print (sargam[0])
print (sargam[1])
print (sargam[2])
print (sargam[3])
rag = 3
else:
print (sargam[rag - 3])
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
if (level == 4):
if (rag == 0):
print (sargam[0])
print (sargam[1])
print (sargam[2])
print (sargam[3])
rag = 4
else:
print (sargam[rag - 4])
print (sargam[rag - 3])
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
if (level == 5):
if (rag == 0):
print (sargam[0])
print (sargam[1])
print (sargam[2])
print (sargam[3])
print (sargam[4])
rag = 5
else:
print (sargam[rag - 4])
print (sargam[rag - 3])
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
sargam = ["sa", "re", "ga", "ma", "pa", "dh", "ni", "Sa"]
level = 0
while(level < len(sargam)):
rag = 0
while(rag < len(sargam)):
if (level == 0):
print (sargam[rag])
if (level == 1):
if (rag == 0):
print (sargam[0])
print (sargam[rag + 1])
rag = 1
else:
print (sargam[rag-1])
print (sargam[rag])
if (level == 2):
if (rag == 0):
print (sargam[0])
print (sargam[rag + 1])
print (sargam[rag + 2])
rag = 2
else:
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
if (level == 3):
if (rag == 0):
print (sargam[0])
print (sargam[1])
print (sargam[2])
print (sargam[3])
rag = 3
else:
print (sargam[rag - 3])
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
if (level == 4):
if (rag == 0):
print (sargam[0])
print (sargam[1])
print (sargam[2])
print (sargam[3])
rag = 4
else:
print (sargam[rag - 4])
print (sargam[rag - 3])
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
if (level == 5):
if (rag == 0):
print (sargam[0])
print (sargam[1])
print (sargam[2])
print (sargam[3])
print (sargam[4])
rag = 5
else:
print (sargam[rag - 4])
print (sargam[rag - 3])
print (sargam[rag - 2])
print (sargam[rag-1])
print (sargam[rag])
|
5e1027ac5d2187084410dbe73e5ee0de5e55e675 | kh4r00n/SoulCodeLP | /sclp007.py | 368 | 3.671875 | 4 | '''Crie um programa quea leia o salario e despesas de uma pessoa e inform a porcentagem que a despesa representa de seu salário'''
salario = float(input('Iforme seu salário: '))
despesa = float(input('Informe suas despesas: '))
porc = (despesa * 100) / salario
print(f'Sua despesas de {despesa:.2f} equivale a {porc}% do seu salário de R${salario:.2f}') |
6f64e46011c1bceff817c683d45abdbcf6a132e3 | Andrescorreaf/Cursopython | /Diccionarios/Ejercicio_diccionarios.py | 5,825 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# ---QUE SON LOS DICCIONARIOS EN PYTHON?.
# Son una estructura de datos que nos permite almacenar valores de diferente tipo
# (enteros, cadenas de textos, decimales) e incluso listas y otros diccionarios
#-----CARACTERISTICAS----------
# La principal característica de los diccionarios
# es que los datos se almacenan asociados a una clave
# de tal forma que se crea una asociación de tipo CLAVE:VALOR para cada elemento almacenado.
# Los elementos almacenados no están ordenados.
# El orden es indiferente a la hora de almacenar informacón en un diccionario.
#---SINTAXIS DE UN DICCIONARIO-----.
# -Nombre que le quieras dar a un diccionario. Ejemplo, midiccionario
# -y los lementos que van dentro estan encerrado bajo llave, va primero la CLAVE , luego : y el VALOR·
#----FUNCIOANAMIENTO----------
# Se declara la variable del diccionario.
# dentro de las llaves va primero la clave, la clave puede ser de cualquier tipo (texto, numerico, una tupla, listas, diccionario)
# luego va dos puentos el valor que puedes ser de diferente tipo,(texto, numerico, lista, tupla, diccionrio).
#----EJEMPLO------
midiccionario={"Alemania":"Berlin", "Francia":"Paris", "Reio unido":"Londres", "Espania":"Madrid"}
#---- PARA AGREGAR UN ELEMENTO A UN DICCIONARIO----
# ponemos el nombre del diccionario.
# luego en corchetes va la clave, cerramos corchetes y ponemos = y el valor.
midiccionario["Colombia"] = "manizales"
print(midiccionario)
# --------------CAMBIAR UN VALOR A UNA CLAVE----------------------
# Se hace el mismo proceso anterio, ya que lo que hace python es sobre escribir el valor asignado.
midiccionario["Colombia"]= "Bogota"
print(midiccionario)
# -------- COMO ELIMINAR UN ELEMENTO--------
# Para eliminar un elemento del diccionario utilizamos una funcion propira de python que es DEL.
# del es una funcion propia de pytho y nos sirve para eliminar un elemento del diccionario.
# la sintaxis sería: la funcion del, luego el nombre del dicionario luego dentro de corchetes la clave que se va eliminar
# NOTA: se eliminŕa la pareja completa.
# --------EJEMPLO------------------------------------------------
del midiccionario["Francia"] # <---- declaramos la linea de codigo que me elimiara la pareja del valor ingresaod en corchetes
print(midiccionario)
#----------------EJEMPLO DE UN DICCIONARIO CON VALORES DE TIPO NUMERICO ENTERO Y FLOTANTE-------------
midiccionario2={"Andres":31, "Ciudad":"manizales", "Anio de nacimieno":1987, "Dia":15, "mes":06, "estatura":1.7}
print(midiccionario2)
# -----GREGARLE VALORES A AUN DICCIONARIO MEDIANTE UNA TUPLA.
# la sistaxis seria.
# Se crea la tupl.
# luego se declara el nombre del diccionario, luego ponemos = y dentro de llaves ingresamos el nobre de la tupla, que es la
# qe va a ser la clave para los valores que se van a ingresar al diccioario, luego
# entre corchetes va la posicion de la tupla, luego dos puntos : y ya se pone el valor de la clave del diccionario.
#-------------EJEMPLO--------------------------
mitupla=("Capital de Caldas", "Capital de risaralda","Capital del Quindio")
midiccionario3={mitupla[0]:"Manizales", mitupla[1]:"Pereira", mitupla[2]:"Armenia"}
print(midiccionario3)
# ----------MOSTRAR EL VALOR DE LA CLAVE ASIGANADA AL DICCIONARIO DESDE UNA TUPLA.
# mostrar el valor de la clave asignada desde el u
print(midiccionario3["Capital del Quindio"]) #<--- de esta maera se accede al valor de un diccionario
# ----- COMO ALMACENAR UNA TUPLA EN UN DICCIONARIO JUTO CON OTROS VALORES------------
# La sintaxis es la siguientes.
# Declaramos el nombr del diccionario,
# ingresamos la clave y el valor, luego de ya tener los valores del diccionario.
# Podemos ingresar una clave y si queremso qe esa clave tenga vario valores, se hace lo siguiente; ponemos el valor que va a ser la clave
# luego ponemos dos puntos: luego en corchetes ingresamos lo valores que queremos que asignar a la clave.
# -------------EJEMPLO----------------
midiccionario4={"Liliana":23, "Dia de naimiento":24, "Ciudad y Departamento":("Manizales","Caldas")}
print(midiccionario4)
# ----- COMO ALMACENAR UN DICCIONARIO DENTRO DE OTRO DICCIONARIO------------
# Para almacenar un diccionario dentrod e otro diccionario se realiza la siguiente declaracion:
# 1--> Declaramos el nombre del primer diccionario, luego entre llaves se ponen las claves y valores normal de las llaves.
# 2--> Despues de tener el diccionario agregamos otro dentro de este de la siguiente manera; Ponemos el el valor que le vamos a dar
# al diccionario, luego DOS PUNTOS : , luego brimos llaves, y dentro de las llaves ponemos el valor y clave, luego de poner el VALOR:CLAVE, que necesites,
# cierras el diccionario, y luego continuas con el otro que inciaste.
# ------ EJEMPLO-------------------------------------------
midiccionario5={"Datos usuario 1":{"Liliana":23, "Dia de nacimiento":24}, "Ciudad y Departamento":("Manizales","Caldas"),"Datos":{"Nombres":("Andres Felipe","liliana Ocampo")}}
print(midiccionario5["Datos usuario 1"])
# ---------METODOS INTERESANTES QUE SE PUEDEN UTILIZAR CON UN DICCIONARIO----------------------
# Metodos com el KEYS, VALUEs, LENG.
# El metodo KEYS, nos devuelve las claves de un diccionario.
# El metodo VALUEs, que nos devuleve los valores, diccionario.
# El metodo LENG, que nos devuelve la longitud, de un diccionario.
# -------------EJEMPLO-------------------
midiccionario5={"Datos usuario 1":{"Liliana":23, "Dia de nacimiento":24}, "Ciudad y Departamento":("Manizales","Caldas"),"Datos":{"Nombres":("Andres Felipe","liliana Ocampo")}}
print(midiccionario5.keys()) # <---- Nos devuleve todas la claves del diccionario
print(midiccionario5.values()) # <---- Nos devuleve todos los valores de las claves del diccionario
print(len(midiccionario5)) # <---- Nos devuleve la longitud del diccionario. |
e32225853129fa962df89632f15c14cf151ea4c2 | LamaHamadeh/Customer-Behaviour | /CB.py | 3,988 | 3.8125 | 4 |
"""
Created on Fri Dec 16 13:01:27 2016
Author: Lama Hamadeh
Software: I use Spyder (Python 2.7) to write the following code
The aim: Analyse the data and look for the behavioural differences between investors and non-investors
The Question:
We have attached a small subset of data from our front end events database. Dataset focuses on behavioural activity before
user makes their first investment. Each of the lines is a distinct user's behaviour before making the first investment.
You will note that not everyone from this dataset made the first investment. What we would like you to do is to analyse
the data and look for the behavioural differences between investors and non-investors.
"""
#importing libraries
#-------------------
import pandas as pd #pandas
import numpy as np #numpy
import matplotlib.pyplot as plt #matplotlib
from matplotlib import style #style
style.use("ggplot") #look pretty
from sklearn import preprocessing
#reading the dataframe from .csv file
#-------------------------------------
Behaviour = pd.read_csv("user_to_1st_time_investor.csv")
#take a look at the dataset
#---------------------------
print (Behaviour.shape) #(263501, 16)
print (Behaviour.head(4))
print (Behaviour.describe())
#checking the types of the dataset features
#-----------------------------------------
print (Behaviour.dtypes)
# We need to change 'time_to_sign_up_from_first_visit_days' and 'first_visit_to_first_investment_days'
# to numeri values in order to be compatible with the other features when plotted.
Behaviour['first_visit_to_first_investment_days'] = pd.to_numeric(Behaviour['first_visit_to_first_investment_days'], errors='coerce')
print (Behaviour.dtypes)
#identify nans
#-------------
def num_missing(x):
return sum(x.isnull())
#Applying per column:
print ("Missing values per column:")
print (Behaviour.apply(num_missing, axis=0)) #251338 nans in the 'time to sign up from first visit days ' feature
#and 262142 nans in the 'first visit to first investment days' feature.
#fill nans with zero in the last column of the database
Behaviour[['first_visit_to_first_investment_days']] = Behaviour[['first_visit_to_first_investment_days']].fillna(value=0, inplace=True)
#inplace=True will make the changes permanent, without having to make a copy of the object.
#in the following we are going to analyse the behaviour of the customers, investors and non_investors
#taking in our consideration only the following features:
#Each dataset has 12 features:
#------------------------------
#distinct days visited website
#distinct_properties_viewed
#time on properties
#interactions on property page
#times marketplace filter used
#dashboard interactions
#time on howitworks
#time on faqs
#time on aboutus
#time on team
#time on homepage
#time on marketplace
#and that is because, the 'guid' feature is irrelevant to our study, and the last two features have
# a large number of nans.
#drop unnecessary features:
#--------------------------
columns = ['guid', 'time_to_sign_up_from_first_visit_days', 'first_visit_to_first_investment_days']
Behaviour.drop(columns, inplace=True, axis=1)
print(Behaviour.shape) #263501, 13
#Create a slice called non_investor that includes only the non_investors records
#--------------------------------------------------------------------------------
non_investor = Behaviour[(Behaviour.investor_status == 'non-investor')]
print(non_investor.shape)#262142, 13
#Create a slice called investor that includes only the investors records
#------------------------------------------------------------------------
investor = Behaviour[(Behaviour.investor_status == 'investor')]
print(investor.shape) #(1359, 13)
|
5c7f5df9fc98115e180380bb93bfbe95d6308824 | nowellclosser/dailycodingproblem | /2018-11-19-product-of-others.py | 1,034 | 4.21875 | 4 | # This problem was asked by Uber.
# Given an array of integers, return a new array such that each element at
# index i of the new array is the product of all the numbers in the original
# array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be
# [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would
# be [2, 3, 6].
# Follow-up: what if you can't use division?
def product_of_others(numbers):
product = numbers[0]
for number in numbers[1:]:
product *= number
return [product // number for number in numbers]
# Could build up intermediate products to not redo work.
def product_no_division(numbers):
result = []
for i in range(len(numbers)):
product = 1
for j in range(len(numbers)):
if not j == i:
product *= numbers[j]
result.append(product)
return result
if __name__ == '__main__':
print(product_of_others([1,2,3,4,5]))
print(product_no_division([1,2,3,4,5]))
|
3dd255b9299542032a379e29f2f514088908f9ce | nfarnan/cs001X_examples | /oo/TH/05_inheritance.py | 887 | 3.921875 | 4 | class Person:
def __init__(self, name, age=20):
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", self.age)
def __str__(self):
return self.name + "!"
def __repr__(self):
rv = "Person("
rv += self.name
rv += ", "
rv += str(self.age)
rv += ")"
return rv
def hadBirthday(self):
self.age += 1
def getAge(self):
return self.age
class Student(Person):
def __init__(self, name, age):
Person.__init__(self, name, age)
self.__classes = []
def addClass(self, new_class):
self.__classes.append(new_class)
def display(self):
Person.display(self)
print("Classes:", self.__classes)
def __repr__(self):
rv = "Student("
rv += self.name
rv += ", "
rv += str(self.age)
rv += ", "
rv += str(self.__classes)
rv += ")"
return rv
a = Student("Alice", 20)
print(repr(a))
a.display()
print(a)
|
bb5763bb59030646f04bf29c4036b74bc2ed16a4 | brianmr31/check-Py_basic | /2_while.py | 127 | 3.671875 | 4 | #!/usr/bin/env python
x = input('Masukan nilai Integer : ')
i = 0
while i < x :
print 'nilai ke ',i,' dengan x : ',x
i+=1
|
779cb5f01665b3dac9b85f14cb370160c1dcbe4f | jonasht/cursoIntesivoDePython | /exercisesDosCapitulos/06-dicionarios/6.10-numerosFavoritos.py | 251 | 3.796875 | 4 | pessoas = {
'ana': [1, 8, 4],
'pitona': [78, 5, 888],
'elen': [232, 7, 8, 6, 1, 2, 4]
}
for pessoa, i in pessoas.items():
print(f'\nos numeros favoritos de {pessoa} são:')
for n in pessoas[pessoa]:
print(f'{n}|', end='')
|
d1c270addb0ce48eaa4ca8e98ea7b5c01e922127 | MANA624/MiscRep | /Averager/Averager1.0/averager.pyw | 56,612 | 3.640625 | 4 | # Import TKinter
from tkinter import *
import tkinter.messagebox
from tkinter.filedialog import askopenfilename
import os
import shutil
# These are some variables used to determine if a window has been opened yet
root = Tk()
# I'm gonna write some code that involves checking for a text file, and reading a text file and saving the result
# as a global variable. The purpose of this is so that the user can rename their classes. Here goes
def check_names():
global class1, class2, class3, class4, class5, class6, class7
try:
math_text = open('math.txt', 'r')
class1 = math_text.read()
math_text.close()
except:
class1 = 'Math'
try:
comp_text = open('comp.txt', 'r')
class2 = comp_text.read()
comp_text.close()
except:
class2 = 'Comp. Sci.'
try:
phys_text = open('phys.txt', 'r')
class3 = phys_text.read()
phys_text.close()
except:
class3 = 'Physics'
try:
span_text = open('span.txt', 'r')
class4 = span_text.read()
span_text.close()
except:
class4 = 'Spanish'
try:
engl_text = open('engl.txt', 'r')
class5 = engl_text.read()
engl_text.close()
except:
class5 = 'English'
try:
hist_text = open('hist.txt', 'r')
class6 = hist_text.read()
hist_text.close()
except:
class6 = 'History'
try:
chem_text = open('chem.txt', 'r')
class7 = chem_text.read()
chem_text.close()
except:
class7 = 'Chemistry'
check_names()
# This is the function to open the scores for a class. active.txt gets changed to all 0's every time the window
# closes, but the user can choose to open a class, which sets active.txt to the value of the scores saved in the
# class chosen
def load_scores():
global scores1
try:
score_reader = open('active.txt', 'r')
scores1 = score_reader.read()
score_reader.close()
scores1 = scores1.split('\n')
except:
scores1 = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]
load_scores()
# This function saves the scores of the first class by retrieving all the values of the boxes and saving them in
# a scores1.txt text file
def save_scores1():
scores1 = str(test.prompt_Box_1_1.get()) + '\n' \
+ str(test.prompt_Box_1_2.get()) + '\n' + \
str(test.prompt_Box_2_1.get()) + '\n' + \
str(test.prompt_Box_2_2.get()) + '\n' + \
str(test.prompt_Box_3_1.get()) + '\n' + \
str(test.prompt_Box_3_2.get()) + '\n' + \
str(test.prompt_Box_4_1.get()) + '\n' + \
str(test.prompt_Box_4_2.get()) + '\n' + \
str(test.prompt_Box_5_1.get()) + '\n' + \
str(test.prompt_Box_5_2.get()) + '\n' + \
str(test.prompt_Box_6_1.get()) + '\n' + \
str(test.prompt_Box_6_2.get()) + '\n' + \
str(test.prompt_Box_7_1.get()) + '\n' + \
str(test.prompt_Box_7_2.get()) + '\n' + \
str(test.prompt_Box_8_1.get()) + '\n' + \
str(test.prompt_Box_8_2.get()) + '\n'
score_writer = open('scores1.txt', 'w')
score_writer.write(scores1)
score_writer.close()
def open_scores1():
global test, root
try:
temp_reader = open('scores1.txt', 'r')
temp = temp_reader.read()
temp_reader.close()
active_writer = open('active.txt', 'w')
active_writer.write(temp)
active_writer.close()
load_scores()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
except:
tkinter.messagebox.showinfo('Problem Loading Scores', "Scores for this class could not be found. Try saving some first")
# This function saves the scores of the first class by retrieving all the values of the boxes and saving them in
# a scores2.txt text file
def save_scores2():
scores1 = str(test.prompt_Box_1_1.get()) + '\n' \
+ str(test.prompt_Box_1_2.get()) + '\n' + \
str(test.prompt_Box_2_1.get()) + '\n' + \
str(test.prompt_Box_2_2.get()) + '\n' + \
str(test.prompt_Box_3_1.get()) + '\n' + \
str(test.prompt_Box_3_2.get()) + '\n' + \
str(test.prompt_Box_4_1.get()) + '\n' + \
str(test.prompt_Box_4_2.get()) + '\n' + \
str(test.prompt_Box_5_1.get()) + '\n' + \
str(test.prompt_Box_5_2.get()) + '\n' + \
str(test.prompt_Box_6_1.get()) + '\n' + \
str(test.prompt_Box_6_2.get()) + '\n' + \
str(test.prompt_Box_7_1.get()) + '\n' + \
str(test.prompt_Box_7_2.get()) + '\n' + \
str(test.prompt_Box_8_1.get()) + '\n' + \
str(test.prompt_Box_8_2.get()) + '\n'
score_writer = open('scores2.txt', 'w')
score_writer.write(scores1)
score_writer.close()
def open_scores2():
try:
global test, root
temp_reader = open('scores2.txt', 'r')
temp = temp_reader.read()
temp_reader.close()
active_writer = open('active.txt', 'w')
active_writer.write(temp)
active_writer.close()
load_scores()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
except:
tkinter.messagebox.showinfo('Problem Loading Scores', "Scores for this class could not be found. Try saving some first")
# This function saves the scores of the first class by retrieving all the values of the boxes and saving them in
# a scores3.txt text file
def save_scores3():
scores1 = str(test.prompt_Box_1_1.get()) + '\n' \
+ str(test.prompt_Box_1_2.get()) + '\n' + \
str(test.prompt_Box_2_1.get()) + '\n' + \
str(test.prompt_Box_2_2.get()) + '\n' + \
str(test.prompt_Box_3_1.get()) + '\n' + \
str(test.prompt_Box_3_2.get()) + '\n' + \
str(test.prompt_Box_4_1.get()) + '\n' + \
str(test.prompt_Box_4_2.get()) + '\n' + \
str(test.prompt_Box_5_1.get()) + '\n' + \
str(test.prompt_Box_5_2.get()) + '\n' + \
str(test.prompt_Box_6_1.get()) + '\n' + \
str(test.prompt_Box_6_2.get()) + '\n' + \
str(test.prompt_Box_7_1.get()) + '\n' + \
str(test.prompt_Box_7_2.get()) + '\n' + \
str(test.prompt_Box_8_1.get()) + '\n' + \
str(test.prompt_Box_8_2.get()) + '\n'
score_writer = open('scores3.txt', 'w')
score_writer.write(scores1)
score_writer.close()
def open_scores3():
try:
global test, root
temp_reader = open('scores3.txt', 'r')
temp = temp_reader.read()
temp_reader.close()
active_writer = open('active.txt', 'w')
active_writer.write(temp)
active_writer.close()
load_scores()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
except:
tkinter.messagebox.showinfo('Problem Loading Scores', "Scores for this class could not be found. Try saving some first")
# This function saves the scores of the fourth class by retrieving all the values of the boxes and saving them in
# a scores4.txt text file
def save_scores4():
scores1 = str(test.prompt_Box_1_1.get()) + '\n' \
+ str(test.prompt_Box_1_2.get()) + '\n' + \
str(test.prompt_Box_2_1.get()) + '\n' + \
str(test.prompt_Box_2_2.get()) + '\n' + \
str(test.prompt_Box_3_1.get()) + '\n' + \
str(test.prompt_Box_3_2.get()) + '\n' + \
str(test.prompt_Box_4_1.get()) + '\n' + \
str(test.prompt_Box_4_2.get()) + '\n' + \
str(test.prompt_Box_5_1.get()) + '\n' + \
str(test.prompt_Box_5_2.get()) + '\n' + \
str(test.prompt_Box_6_1.get()) + '\n' + \
str(test.prompt_Box_6_2.get()) + '\n' + \
str(test.prompt_Box_7_1.get()) + '\n' + \
str(test.prompt_Box_7_2.get()) + '\n' + \
str(test.prompt_Box_8_1.get()) + '\n' + \
str(test.prompt_Box_8_2.get()) + '\n'
score_writer = open('scores4.txt', 'w')
score_writer.write(scores1)
score_writer.close()
def open_scores4():
try:
global test, root
temp_reader = open('scores4.txt', 'r')
temp = temp_reader.read()
temp_reader.close()
active_writer = open('active.txt', 'w')
active_writer.write(temp)
active_writer.close()
load_scores()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
except:
tkinter.messagebox.showinfo('Problem Loading Scores', "Scores for this class could not be found. Try saving some first")
def save_scores5():
scores1 = str(test.prompt_Box_1_1.get()) + '\n' \
+ str(test.prompt_Box_1_2.get()) + '\n' + \
str(test.prompt_Box_2_1.get()) + '\n' + \
str(test.prompt_Box_2_2.get()) + '\n' + \
str(test.prompt_Box_3_1.get()) + '\n' + \
str(test.prompt_Box_3_2.get()) + '\n' + \
str(test.prompt_Box_4_1.get()) + '\n' + \
str(test.prompt_Box_4_2.get()) + '\n' + \
str(test.prompt_Box_5_1.get()) + '\n' + \
str(test.prompt_Box_5_2.get()) + '\n' + \
str(test.prompt_Box_6_1.get()) + '\n' + \
str(test.prompt_Box_6_2.get()) + '\n' + \
str(test.prompt_Box_7_1.get()) + '\n' + \
str(test.prompt_Box_7_2.get()) + '\n' + \
str(test.prompt_Box_8_1.get()) + '\n' + \
str(test.prompt_Box_8_2.get()) + '\n'
score_writer = open('scores5.txt', 'w')
score_writer.write(scores1)
score_writer.close()
def open_scores5():
try:
global test, root
temp_reader = open('scores5.txt', 'r')
temp = temp_reader.read()
temp_reader.close()
active_writer = open('active.txt', 'w')
active_writer.write(temp)
active_writer.close()
load_scores()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
except:
tkinter.messagebox.showinfo('Problem Loading Scores', "Scores for this class could not be found. Try saving some first")
def save_scores6():
scores1 = str(test.prompt_Box_1_1.get()) + '\n' \
+ str(test.prompt_Box_1_2.get()) + '\n' + \
str(test.prompt_Box_2_1.get()) + '\n' + \
str(test.prompt_Box_2_2.get()) + '\n' + \
str(test.prompt_Box_3_1.get()) + '\n' + \
str(test.prompt_Box_3_2.get()) + '\n' + \
str(test.prompt_Box_4_1.get()) + '\n' + \
str(test.prompt_Box_4_2.get()) + '\n' + \
str(test.prompt_Box_5_1.get()) + '\n' + \
str(test.prompt_Box_5_2.get()) + '\n' + \
str(test.prompt_Box_6_1.get()) + '\n' + \
str(test.prompt_Box_6_2.get()) + '\n' + \
str(test.prompt_Box_7_1.get()) + '\n' + \
str(test.prompt_Box_7_2.get()) + '\n' + \
str(test.prompt_Box_8_1.get()) + '\n' + \
str(test.prompt_Box_8_2.get()) + '\n'
score_writer = open('scores6.txt', 'w')
score_writer.write(scores1)
score_writer.close()
def open_scores6():
try:
global test, root
temp_reader = open('scores6.txt', 'r')
temp = temp_reader.read()
temp_reader.close()
active_writer = open('active.txt', 'w')
active_writer.write(temp)
active_writer.close()
load_scores()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
except:
tkinter.messagebox.showinfo('Problem Loading Scores', "Scores for this class could not be found. Try saving some first")
def save_scores7():
scores1 = str(test.prompt_Box_1_1.get()) + '\n' \
+ str(test.prompt_Box_1_2.get()) + '\n' + \
str(test.prompt_Box_2_1.get()) + '\n' + \
str(test.prompt_Box_2_2.get()) + '\n' + \
str(test.prompt_Box_3_1.get()) + '\n' + \
str(test.prompt_Box_3_2.get()) + '\n' + \
str(test.prompt_Box_4_1.get()) + '\n' + \
str(test.prompt_Box_4_2.get()) + '\n' + \
str(test.prompt_Box_5_1.get()) + '\n' + \
str(test.prompt_Box_5_2.get()) + '\n' + \
str(test.prompt_Box_6_1.get()) + '\n' + \
str(test.prompt_Box_6_2.get()) + '\n' + \
str(test.prompt_Box_7_1.get()) + '\n' + \
str(test.prompt_Box_7_2.get()) + '\n' + \
str(test.prompt_Box_8_1.get()) + '\n' + \
str(test.prompt_Box_8_2.get()) + '\n'
score_writer = open('scores7.txt', 'w')
score_writer.write(scores1)
score_writer.close()
def open_scores7():
try:
global test, root
temp_reader = open('scores7.txt', 'r')
temp = temp_reader.read()
temp_reader.close()
active_writer = open('active.txt', 'w')
active_writer.write(temp)
active_writer.close()
load_scores()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
except:
tkinter.messagebox.showinfo('Problem Loading Scores', "Scores for this class could not be found. Try saving some first")
def reset_scores():
global test, root
score_writer = open('active.txt', 'w')
score_writer.write('0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0')
score_writer.close()
load_scores()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
# These are the functions that open the syllabi for your courses feel free to rename them, but hopefully
# I'll make it so that's not necessary!
def open_math():
try:
os.startfile('math_syl.pdf')
except:
tkinter.messagebox.showinfo('Error opening file', 'No such file was found. Try saving your syllabus first')
def open_comp():
try:
os.startfile('comp_syl.pdf')
except:
tkinter.messagebox.showinfo('Error opening file', 'No such file was found. Try saving your syllabus first')
def open_phys():
try:
os.startfile('phys_syl.pdf')
except:
tkinter.messagebox.showinfo('Error opening file', 'No such file was found. Try saving your syllabus first')
def open_span():
try:
os.startfile('span_syl.pdf')
except:
tkinter.messagebox.showinfo('Error opening file', 'No such file was found. Try saving your syllabus first')
def open_engl():
try:
os.startfile('engl_syl.pdf')
except:
tkinter.messagebox.showinfo('Error opening file', 'No such file was found. Try saving your syllabus first')
def open_hist():
try:
os.startfile('hist_syl.pdf')
except:
tkinter.messagebox.showinfo('Error opening file', 'No such file was found. Try saving your syllabus first')
def open_chem():
try:
os.startfile('chem_syl.pdf')
except:
tkinter.messagebox.showinfo('Error opening file', 'No such file was found. Try saving your syllabus first')
# This function is the class that runs all the main frame repeatedly
class AverageClass:
def __init__(self, master):
global scores1
# I am giving the thing a title
self.master = master
self.master.title("Hand Caclulations Are So Last Century!")
self.master.maxsize(width=604, height=474)
self.frame = Frame(master)
self.frame.pack(fill=BOTH)
# Some things that were farther down, but I needed to be behind the background image
imag_label = Label(self.frame, text="")
imag_label.grid(row=11, column=0, columnspan=4, padx=275)
top_space = Label(self.frame, text='\n')
top_space.grid(row=0, column=0, columnspan=5)
bottom_space = Label(self.frame, text='\n')
bottom_space.grid(row=2, column=0)
# This is the code for the background image
self.photo = PhotoImage(file="bg_img.png")
self.img_label = Label(self.frame, image=self.photo)
self.img_label.grid(row=0, column=0, rowspan=13, columnspan=5)
# This is the label at the top
self.greet_label = Label(self.frame, text=" Welcome to the Average Grade Calculator! ", bd=15, highlightcolor="black")
self.greet_label.grid(row=1, column=0, columnspan=4)
# T hese are the top row of words of how to place the numbers
guide_label_1 = Label(self.frame, text="Catergory", bd=2)
guide_label_1.grid(row=3, column=0, sticky=E)
guide_label_2 = Label(self.frame, text="Percentage", bd=2)
guide_label_2.grid(row=3, column=1)
guide_label_2 = Label(self.frame, text="Weight (%)", bd=2)
guide_label_2.grid(row=3, column=2)
# This is the first row with entries
# The label for the first row
side_label_1 = Label(self.frame, text="Written Homework:")
side_label_1.grid(row=4, column=0, sticky=E)
# The input for the grades for the first row
self.prompt_Box_1_1 = Entry(self.frame, bd=2)
self.prompt_Box_1_1.grid(row=4, column=1)
self.prompt_Box_1_1.insert(0, scores1[0])
self.prompt_Box_1_1.bind("<Return>", self.retrieve_input)
self.color = self.prompt_Box_1_1.cget('bg')
# The input for the weight for the first row
self.prompt_Box_1_2 = Entry(self.frame, bd=2)
self.prompt_Box_1_2.grid(row=4, column=2)
self.prompt_Box_1_2.insert(0, scores1[1])
self.prompt_Box_1_2.bind("<Return>", self.retrieve_input)
self.var1 = IntVar()
c1 = Checkbutton(self.frame, text="Drop lowest grade:", variable=self.var1)
c1.grid(row=4, column=3, sticky=W)
# This is the second row with entries
side_label_2 = Label(self.frame, text="Online Homework:")
side_label_2.grid(row=5, column=0, sticky=E)
self.prompt_Box_2_1 = Entry(self.frame, bd=2)
self.prompt_Box_2_1.grid(row=5, column=1)
self.prompt_Box_2_1.insert(0, scores1[2])
self.prompt_Box_2_1.bind("<Return>", self.retrieve_input)
self.prompt_Box_2_2 = Entry(self.frame, bd=2)
self.prompt_Box_2_2.grid(row=5, column=2)
self.prompt_Box_2_2.insert(0, scores1[3])
self.prompt_Box_2_2.bind("<Return>", self.retrieve_input)
self.var2 = IntVar()
c1 = Checkbutton(self.frame, text="Drop lowest grade:", variable=self.var2)
c1.grid(row=5, column=3, sticky=W)
# The third row with entries
side_label_3 = Label(self.frame, text="Quizzes:")
side_label_3.grid(row=6, column=0, sticky=E)
self.prompt_Box_3_1 = Entry(self.frame, bd=2)
self.prompt_Box_3_1.grid(row=6, column=1)
self.prompt_Box_3_1.insert(0, scores1[4])
self.prompt_Box_3_1.bind("<Return>", self.retrieve_input)
self.prompt_Box_3_2 = Entry(self.frame, bd=2)
self.prompt_Box_3_2.grid(row=6, column=2)
self.prompt_Box_3_2.insert(0, scores1[5])
self.prompt_Box_3_2.bind("<Return>", self.retrieve_input)
self.var3 = IntVar()
c1 = Checkbutton(self.frame, text="Drop lowest grade:", variable=self.var3)
c1.grid(row=6, column=3, sticky=W)
# The fourth row with entries
side_label_4 = Label(self.frame, text="Test 1:")
side_label_4.grid(row=7, column=0, sticky=E)
self.prompt_Box_4_1 = Entry(self.frame, bd=2)
self.prompt_Box_4_1.grid(row=7, column=1)
self.prompt_Box_4_1.insert(0, scores1[6])
self.prompt_Box_4_1.bind("<Return>", self.retrieve_input)
self.prompt_Box_4_2 = Entry(self.frame, bd=2)
self.prompt_Box_4_2.grid(row=7, column=2)
self.prompt_Box_4_2.insert(0, scores1[7])
self.prompt_Box_4_2.bind("<Return>", self.retrieve_input)
# The fifth row with entries
side_label_5 = Label(self.frame, text="Test 2:")
side_label_5.grid(row=8, column=0, sticky=E)
self.prompt_Box_5_1 = Entry(self.frame, bd=2)
self.prompt_Box_5_1.grid(row=8, column=1)
self.prompt_Box_5_1.insert(0, scores1[8])
self.prompt_Box_5_1.bind("<Return>", self.retrieve_input)
self.prompt_Box_5_2 = Entry(self.frame, bd=2)
self.prompt_Box_5_2.grid(row=8, column=2)
self.prompt_Box_5_2.insert(0, scores1[9])
self.prompt_Box_5_2.bind("<Return>", self.retrieve_input)
# The sixth row with entries
side_label_6 = Label(self.frame, text="Test 3:")
side_label_6.grid(row=9, column=0, sticky=E)
self.prompt_Box_6_1 = Entry(self.frame, bd=2)
self.prompt_Box_6_1.grid(row=9, column=1)
self.prompt_Box_6_1.insert(0, scores1[10])
self.prompt_Box_6_1.bind("<Return>", self.retrieve_input)
self.prompt_Box_6_2 = Entry(self.frame, bd=2)
self.prompt_Box_6_2.grid(row=9, column=2)
self.prompt_Box_6_2.insert(0, scores1[11])
self.prompt_Box_6_2.bind("<Return>", self.retrieve_input)
# The seventh row with entries ... how many more do I have?
side_label_7 = Label(self.frame, text="THE FINAL...:")
side_label_7.grid(row=10, column=0, sticky=E)
self.prompt_Box_7_1 = Entry(self.frame, bd=2)
self.prompt_Box_7_1.grid(row=10, column=1)
self.prompt_Box_7_1.insert(0, scores1[12])
self.prompt_Box_7_1.bind("<Return>", self.retrieve_input)
self.prompt_Box_7_2 = Entry(self.frame, bd=2)
self.prompt_Box_7_2.grid(row=10, column=2)
self.prompt_Box_7_2.insert(0, scores1[13])
self.prompt_Box_7_2.bind("<Return>", self.retrieve_input)
# The eighth row with entries ... just some extra credit
side_label_8 = Label(self.frame, text="Extra Credit:")
side_label_8.grid(row=11, column=0, sticky=E)
self.prompt_Box_8_1 = Entry(self.frame, bd=2)
self.prompt_Box_8_1.grid(row=11, column=1, sticky=N)
self.prompt_Box_8_1.insert(0, scores1[14])
self.prompt_Box_8_1.bind("<Return>", self.retrieve_input)
self.prompt_Box_8_2 = Entry(self.frame, bd=2)
self.prompt_Box_8_2.grid(row=11, column=2, sticky=N)
self.prompt_Box_8_2.insert(0, scores1[15])
self.prompt_Box_8_2.bind("<Return>", self.retrieve_input)
# This is some code to have the cells expand as the screen expands. First the columns
Grid.columnconfigure(self.frame, 0, weight=2)
Grid.columnconfigure(self.frame, 1, weight=1)
Grid.columnconfigure(self.frame, 2, weight=1)
Grid.columnconfigure(self.frame, 3, weight=3)
# Then the rows. Not much is done here, but looking at the final product, I'm okay with that. It collapses well
Grid.rowconfigure(self.frame, 0, weight=7)
Grid.rowconfigure(self.frame, 1, weight=3)
Grid.rowconfigure(self.frame, 2, weight=7)
Grid.rowconfigure(self.frame, 3, weight=1)
Grid.rowconfigure(self.frame, 4, weight=1)
Grid.rowconfigure(self.frame, 5, weight=1)
Grid.rowconfigure(self.frame, 6, weight=1)
Grid.rowconfigure(self.frame, 7, weight=1)
Grid.rowconfigure(self.frame, 8, weight=1)
Grid.rowconfigure(self.frame, 9, weight=1)
Grid.rowconfigure(self.frame, 10, weight=1)
Grid.rowconfigure(self.frame, 11, weight=1)
Grid.rowconfigure(self.frame, 12, weight=0)
# This is the code for the buttons
self.submit_Button = Button(self.frame, text="Submit", command=self.retrieve_input, bd=4)
self.submit_Button.grid(row=12, column=2, columnspan=1, padx=0, pady=40)
self.submit_Button.bind("<button-1>")
self.reset_Button = Button(self.frame, text="Reset", command=reset_scores, bd=4)
self.reset_Button.grid(row=12, column=1, columnspan=1, padx=0, pady=40)
self.reset_Button.bind("<button-1>")
# This is a developing but of code that can do a lot of cool things. But it kinda makes me wanna cry...
menu = Menu(master)
root.config(menu=menu)
sub_menu = Menu(menu, tearoff=False)
menu.add_cascade(label='File', menu=sub_menu)
subsub_menu = Menu(sub_menu, tearoff=False)
sub_menu.add_cascade(label='Open Syllabus', menu=subsub_menu)
sub_save_menu = Menu(sub_menu, tearoff=False)
sub_menu.add_cascade(label='Save Syllabus', menu=sub_save_menu)
scores_load_menu = Menu(sub_menu, tearoff=False)
sub_menu.add_separator()
sub_menu.add_cascade(label='Load Scores', menu=scores_load_menu)
scores_save_menu = Menu(sub_menu, tearoff=False)
sub_menu.add_cascade(label='Save Scores', menu=scores_save_menu)
sub_menu.add_separator()
sub_save_menu.add_command(label=class1, command=set_math_path)
sub_save_menu.add_command(label=class2, command=set_comp_path)
sub_save_menu.add_command(label=class3, command=set_phys_path)
sub_save_menu.add_command(label=class4, command=set_span_path)
sub_save_menu.add_command(label=class5, command=set_engl_path)
sub_save_menu.add_command(label=class6, command=set_hist_path)
sub_save_menu.add_command(label=class7, command=set_chem_path)
subsub_menu.add_command(label=class1, command=open_math)
subsub_menu.add_command(label=class2, command=open_comp)
subsub_menu.add_command(label=class3, command=open_phys)
subsub_menu.add_command(label=class4, command=open_span)
subsub_menu.add_command(label=class5, command=open_engl)
subsub_menu.add_command(label=class6, command=open_hist)
subsub_menu.add_command(label=class7, command=open_chem)
scores_load_menu.add_command(label=class1, command=open_scores1)
scores_load_menu.add_command(label=class2, command=open_scores2)
scores_load_menu.add_command(label=class3, command=open_scores3)
scores_load_menu.add_command(label=class4, command=open_scores4)
scores_load_menu.add_command(label=class5, command=open_scores5)
scores_load_menu.add_command(label=class6, command=open_scores6)
scores_load_menu.add_command(label=class7, command=open_scores7)
scores_save_menu.add_command(label=class1, comman=save_scores1)
scores_save_menu.add_command(label=class2, comman=save_scores2)
scores_save_menu.add_command(label=class3, comman=save_scores3)
scores_save_menu.add_command(label=class4, comman=save_scores4)
scores_save_menu.add_command(label=class5, comman=save_scores5)
scores_save_menu.add_command(label=class6, comman=save_scores6)
scores_save_menu.add_command(label=class7, comman=save_scores7)
sub_menu.add_command(label='Quit', command=root.destroy)
customize_menu = Menu(menu, tearoff=False)
menu.add_cascade(label='Customize', menu=customize_menu)
naming = Menu(customize_menu, tearoff=False)
customize_menu.add_cascade(label='Rename Classes', menu=naming)
naming.add_command(label='Rename Class 1', command=prompt_math)
naming.add_command(label='Rename Class 2', command=prompt_comp)
naming.add_command(label='Rename Class 3', command=prompt_phys)
naming.add_command(label='Rename Class 4', command=prompt_span)
naming.add_command(label='Rename Class 5', command=prompt_engl)
naming.add_command(label='Rename Class 6', command=prompt_hist)
naming.add_command(label='Rename Class 7', command=prompt_chem)
help_menu = Menu(menu, tearoff=False)
menu.add_cascade(label='Help', menu=help_menu)
help_menu.add_command(label='Help', command=help_box)
help_menu.add_command(label='About', command=about_box)
# This function takes the inputs
def retrieve_input(self, *args):
if self.var1.get() == 0:
written = average(self.prompt_Box_1_1.get())
else:
written = drop_low_average(self.prompt_Box_1_1.get())
if written == 9480203402:
self.prompt_Box_1_1.config(bg='red')
else:
self.prompt_Box_1_1.config(bg=self.color)
written_w = average(self.prompt_Box_1_2.get())
written_f = written * (written_w / 100)
if written_w == 9480203402:
self.prompt_Box_1_2.config(bg='red')
else:
self.prompt_Box_1_2.config(bg=self.color)
if self.var2.get() == 0:
online = average(self.prompt_Box_2_1.get())
else:
online = drop_low_average(self.prompt_Box_2_1.get())
if online == 9480203402:
self.prompt_Box_2_1.config(bg='red')
else:
self.prompt_Box_2_1.config(bg=self.color)
online_w = average(self.prompt_Box_2_2.get())
online_f = online * (online_w / 100)
if online_w == 9480203402:
self.prompt_Box_2_2.config(bg='red')
else:
self.prompt_Box_2_2.config(bg=self.color)
if self.var2.get() == 0:
quizzes = average(self.prompt_Box_3_1.get())
else:
quizzes = drop_low_average(self.prompt_Box_3_1.get())
if quizzes == 9480203402:
self.prompt_Box_3_1.config(bg='red')
else:
self.prompt_Box_3_1.config(bg=self.color)
quizzes_w = average(self.prompt_Box_3_2.get())
quizzes_f = quizzes * (quizzes_w / 100)
if quizzes_w == 9480203402:
self.prompt_Box_3_2.config(bg='red')
else:
self.prompt_Box_3_2.config(bg=self.color)
test1 = average(self.prompt_Box_4_1.get())
if test1 == 9480203402:
self.prompt_Box_4_1.config(bg='red')
else:
self.prompt_Box_4_1.config(bg=self.color)
test1_w = average(self.prompt_Box_4_2.get())
test1_f = test1 * (test1_w / 100)
if test1_w == 9480203402:
self.prompt_Box_4_2.config(bg='red')
else:
self.prompt_Box_4_2.config(bg=self.color)
test2 = average(self.prompt_Box_5_1.get())
if test2 == 9480203402:
self.prompt_Box_5_1.config(bg='red')
else:
self.prompt_Box_5_1.config(bg=self.color)
test2_w = average(self.prompt_Box_5_2.get())
test2_f = test2 * (test2_w / 100)
if test2_w == 9480203402:
self.prompt_Box_5_2.config(bg='red')
else:
self.prompt_Box_5_2.config(bg=self.color)
test3 = average(self.prompt_Box_6_1.get())
if test3 == 9480203402:
self.prompt_Box_6_1.config(bg='red')
else:
self.prompt_Box_6_1.config(bg=self.color)
test3_w = average(self.prompt_Box_6_2.get())
test3_f = test3 * (test3_w / 100)
if test3_w == 9480203402:
self.prompt_Box_6_2.config(bg='red')
else:
self.prompt_Box_6_2.config(bg=self.color)
final = average(self.prompt_Box_7_1.get())
if final == 9480203402:
self.prompt_Box_7_1.config(bg='red')
else:
self.prompt_Box_7_1.config(bg=self.color)
final_w = average(self.prompt_Box_7_2.get())
final_f = final * (final_w / 100)
if final_w == 9480203402:
self.prompt_Box_7_2.config(bg='red')
else:
self.prompt_Box_7_2.config(bg=self.color)
extra_credit = average(self.prompt_Box_8_1.get())
if extra_credit == 9480203402:
self.prompt_Box_8_1.config(bg='red')
else:
self.prompt_Box_8_1.config(bg=self.color)
extra_credit_w = average(self.prompt_Box_8_2.get())
extra_credit_f = extra_credit * (extra_credit_w / 100)
if extra_credit_w == 9480203402:
self.prompt_Box_8_2.config(bg='red')
else:
self.prompt_Box_8_2.config(bg=self.color)
# The sum of the weights
final_weight = written_w + online_w + quizzes_w + test1_w + test2_w + test3_w + final_w
top_disp = ""
# This is a test vector. I want to make sure none of the inputs were bad
test_arr = [written, online, quizzes, test1, test2, test3, final, extra_credit, written_w,
online_w, quizzes_w, test1_w, test2_w, test3_w, final_w, extra_credit_w]
# A continuation of what I was doing. If a number were a string, it would get
# turned into that long, awful number
no_good = 0
for x in range(len(test_arr)):
if test_arr[x] == 9480203402:
no_good = 1
final_arr = 9480203402
break
# This is a test to make sure we're not dividing by 0
if final_weight == 0:
no_good = 1
final_arr = 9480203402
tkinter.messagebox.showinfo('You really screwed up this time', "Bro. Literally all your weights were 0")
if no_good == 0:
final_arr = written_f + online_f + quizzes_f + test1_f + test2_f + test3_f + final_f + extra_credit_f
scorer(final_arr, final_weight)
# The purpose of this function is to both make the conversion
# from string to float and average any lists of grades entered
def average(scores):
if scores[0] == '#':
scores = '0'
test1 = scores.split(',')
while True:
try:
for x in range(len(test1)):
test1[x] = float(test1[x])
break
except ValueError:
tkinter.messagebox.showinfo('You really screwed up this time', ' \"' + scores + "\" is not a valid input ")
test1 = [9480203402]
break
scores = test1
avg = sum(scores) / len(scores)
return avg
# This is the same function as the last, only it stores the
# lowest score as an unused variable and aveages the rest of them
def drop_low_average(scores):
if scores[0] == '#':
scores = '0'
test1 = scores.split(',')
while True:
try:
for x in range(len(test1)):
test1[x] = float(test1[x])
break
except ValueError:
tkinter.messagebox.showinfo('You really screwed up this time', ' \"' + str(scores) + "\" is not a valid input ")
test1 = [9480203402]
break
scores = test1
if len(scores) > 1:
scores.sort()
dummy, *scores = scores
avg = sum(scores) / len(scores)
return avg
# The purpose of this function is to take the final score and
# final weight and calculate our long-awaited average!
def scorer(final_arr, weight):
if final_arr == 9480203402:
weight = 100
avg = final_arr / (weight / 100)
grade(avg)
# This function just returns the grade for the class and calls the function to tell the user the result
def grade(avg):
if avg > 100:
mid_disp = "Dude, you're such a cheater. Or a liar. I'm not sure which"
elif avg >= 92.5:
mid_disp = "You got an A! :)"
elif avg >= 89.5:
mid_disp = "You got an A-!"
elif avg >= 86.5:
mid_disp = "You got a B+"
elif avg >= 82.5:
mid_disp = "You got a B"
elif avg >= 79.5:
mid_disp = "You got a B- :("
elif avg >= 76.5:
mid_disp = "You got a C+ :("
elif avg >= 72.5:
mid_disp = "You got a C :'("
elif avg >= 69.5:
mid_disp = "You got a C- :'("
elif avg >= 66.5:
mid_disp = "You got a D+ :'0"
elif avg >= 62.5:
mid_disp = "You got a D :'0"
elif avg >= 59.5:
mid_disp = "You got a D- :'0_"
else:
mid_disp = "You got an F\nJust go kill yourself"
if int(round(avg)) != 9480203402:
while TRUE:
try:
temp_root.destroy()
break
finally:
break
abre_ventana(avg, mid_disp)
# This actually opens the window in which the user sees the final grade result
def abre_ventana(middle, last):
global temp_root
temp_root = Tk()
label2 = Label(temp_root, text="\nYour average is currently: " + "{0:.2f}".format(middle) + "\n")
label2.pack(padx=19)
label3 = Label(temp_root, text=last + '\n')
label3.pack()
temp_root.iconbitmap('favicon.ico')
temp_root.title('Result')
# This opens the tkinter box with the help menu in it. It currently has four different options to explain the
# four different parts of the application. I had to make a bunch of global variables since you can't call
# a variable from inside a function, and it's hard to call a class from a menu button.
def help_box():
global var, label, gen_text, rnme_text, syl_text, grd_text
global help_root
while True:
try:
help_root.destroy()
break
finally:
break
help_root = Tk()
var = tkinter.StringVar(help_root)
# initial value
var.set('General')
choices = ['General', 'Renaming Classes', 'Opening Your Syllabus', 'Opening Saved Grades']
option = tkinter.OptionMenu(help_root, var, *choices)
option.grid(pady=20, sticky=S)
help_root.title('Socorro!')
gen_text ="Welcome to the Grade Averager!\n\n" \
"In the grade percentage, enter as many grades as you want in the\n" \
"same box separated by commas and they will be averaged. Then put the\n" \
"percentage of weight they have and enter it. Feel free to leave any boxes\n" \
"empty. If you don't want the program to read a box, enter # before the\n" \
"number(s). Even though you are probably a friend or family member if\nyou are reading this, please give suggestions and comments!"
rnme_text = "So, this is pretty straightforward, but I'll hold your hand and tell you how\n" \
"to do it anyways. Well, I won't hold your hand, but you get the idea.\n" \
"Unless you're a freshman engineering student like me, you probably aren't\n" \
"taking math, physics, computer science, blah, blah, blah. So just go to\n" \
"Customize > Rename Classes pick the class you want to rename. From there\n" \
"enter your class' name in the box and hit enter. Name it anything. I dare ya."
syl_text = "Because I, too, am a lazy college student, I know that you don't want\n" \
"to find your syllabus every time you need to calculate your grades!\n" \
"As a result, there is a built-in function that makes it so you only have\n" \
"to browse your computer once for that obsolete PDF. Just go to\n" \
"File > Save Syllabus and pick the class you want to save your syllabus for.\n" \
"Then next time you need that syllabus, just go to File > Open Syllabus and\n" \
"that syllabus will open in your default .pdf reader. Feel free to move\n" \
"or get rid of the syllabus. It is saved inside the program.\n" \
"*Please note that your syllabus must be in .pdf form*"
grd_text = "What's the use of a grade calculator that doesn't remember your grades, you ask?\n" \
"The answer is none. And if you have a grade calculator that can't even remember\n" \
"some stupid numbers, then you need to burn it with fire! Here, though, you just\n" \
"have to enter your grades, and when you're done go to File > Save Grades and pick\n" \
"the class that you just entered grades for. Then next time you want to update or\n" \
"view them, just go to File > Open Grades and they will magically appear, just like\n" \
"you left them!\n"
label = Label(help_root, text=gen_text)
label.grid(row=0, column=1, rowspan=2, padx=30, pady=30, sticky=N)
button = Button(help_root, text="Go!", command=update_label)
button.grid(row=1, padx=70, pady=20, sticky=N)
help_root.iconbitmap('favicon.ico')
help_root.mainloop()
def update_label():
global var, label, gen_text, rnme_text, syl_text, grd_text
if var.get() == 'General':
label.config(text=gen_text)
if var.get() == 'Renaming Classes':
label.config(text=rnme_text)
if var.get() == 'Opening Your Syllabus':
label.config(text=syl_text)
if var.get() == 'Opening Saved Grades':
label.config(text=grd_text)
# This opens the about box. Just makin' sure people get straight who made this epic program
def about_box():
global about
while True:
try:
about.destroy()
break
finally:
break
about = Tk()
about.title('We all cool here')
label = Label(about, text="This is a privately developed Python GUI Application\n"
"developed soley by Matthew Niemiec. Feel free to use\n"
"it as needed, just don't do anything stupid like showing\n"
"it to your friends and saying it's yours. That's just\n"
"rude. Special thanks to Adam Smith for critiques and\n"
"general guidance. You're the coolest, Adam!")
label.pack(side=TOP, padx=30, pady=30)
about.iconbitmap('favicon.ico')
about.mainloop()
# This essentially copies and pastes the user's choice of PDF file into the folder and renames
# renames it so that the program can consistently read it and open it.
def set_math_path():
fname = askopenfilename(filetypes=(("PDF files", "*.pdf;*.PDF"),
("All files", "*.*")))
try:
shutil.copyfile(fname, 'math_syl.pdf')
except:
pass
# Same thing as the above function, only with the second class, which happens to be Physics by default
def set_phys_path():
fname = askopenfilename(filetypes=(("PDF files", "*.pdf;*.PDF"),
("All files", "*.*")))
try:
shutil.copyfile(fname, 'phys_syl.pdf')
except:
pass
# Same thing as the above function, only with the third class, which happens to be Computer Science by default
def set_comp_path():
fname = askopenfilename(filetypes=(("PDF files", "*.pdf;*.PDF"),
("All files", "*.*")))
try:
shutil.copyfile(fname, 'comp_syl.pdf')
except:
pass
# Same thing as the above function, only with the fourth class, which happens to be Spanish by default
def set_span_path():
fname = askopenfilename(filetypes=(("PDF files", "*.pdf;*.PDF"),
("All files", "*.*")))
while TRUE:
try:
shutil.copyfile(fname, 'span_syl.pdf')
break
finally:
break
# Same thing as the above function, only with the fourth class, which happens to be Spanish by default
def set_engl_path():
fname = askopenfilename(filetypes=(("PDF files", "*.pdf;*.PDF"),
("All files", "*.*")))
while TRUE:
try:
shutil.copyfile(fname, 'engl_syl.pdf')
break
finally:
break
# Same thing as the above function, only with the fourth class, which happens to be Spanish by default
def set_hist_path():
fname = askopenfilename(filetypes=(("PDF files", "*.pdf;*.PDF"),
("All files", "*.*")))
while TRUE:
try:
shutil.copyfile(fname, 'hist_syl.pdf')
break
finally:
break
# Same thing as the above function, only with the fourth class, which happens to be Spanish by default
def set_chem_path():
fname = askopenfilename(filetypes=(("PDF files", "*.pdf;*.PDF"),
("All files", "*.*")))
while TRUE:
try:
shutil.copyfile(fname, 'chem_syl.pdf')
break
finally:
break
# This function first asks the user what they want to rename their first class to
def prompt_math():
global math_root
# This just makes sure that there isn't already the same box open
while TRUE:
try:
math_root.destroy()
break
finally:
break
# This code is for the actual box that the user inputs their name into
math_root = Tk()
math_root.title("Name Changer")
math_root.iconbitmap('favicon.ico')
label = Label(math_root, text=' What would you like to call your first class?')
label.grid(row=0, column=0, sticky=E, pady=25)
global entry
entry = Entry(math_root)
entry.grid(row=0, column=1, sticky=W, pady=25)
entry.bind("<Return>", submit_math)
space = Label(math_root, text=' ')
space.grid(row=0, column=2)
button = Button(math_root, text='Submit', command=submit_math)
button.grid(row=1, columnspan=3)
bottom_space = Label(math_root, text=' ')
bottom_space.grid(row=2, pady=1)
math_root.mainloop()
# Synonymous with the function above, it takes the string from the entry box, destroys the window, and restarts the
# program with the renamed classes
def submit_math(*args):
global class1, entry, root, test
class1 = entry.get()
if len(class1) > 18:
class1 = class1[0:16] + '...'
math_write = open('math.txt', 'w')
math_write.write(class1)
math_write.close()
math_root.destroy()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
# If you didn't notice, the next six functions are continuations of the last two, only with the remaining three classes
def prompt_comp():
global comp_root
while TRUE:
try:
comp_root.destroy()
break
finally:
break
comp_root = Tk()
comp_root.title("Name Changer")
comp_root.iconbitmap('favicon.ico')
label = Label(comp_root, text=' What would you like to call your second class?')
label.grid(row=0, column=0, sticky=E, pady=25)
global entry1
entry1 = Entry(comp_root)
entry1.grid(row=0, column=1, sticky=W, pady=25)
entry1.bind("<Return>", submit_comp)
space = Label(comp_root, text=' ')
space.grid(row=0, column=2)
button = Button(comp_root, text='Submit', command=submit_comp)
button.grid(row=1, columnspan=3)
bottom_space = Label(comp_root, text=' ')
bottom_space.grid(row=2, pady=1)
comp_root.mainloop()
# The second function for the second class
def submit_comp(*args):
global class2, entry1, root, test
class2 = entry1.get()
if len(class2) > 18:
class2 = class2[0:16] + '...'
comp_write = open('comp.txt', 'w')
comp_write.write(class2)
comp_write.close()
comp_root.destroy()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
# The first function for the third class
def prompt_phys():
global phys_root
while TRUE:
try:
phys_root.destroy()
break
finally:
break
phys_root = Tk()
phys_root.title("Name Changer")
phys_root.iconbitmap('favicon.ico')
label = Label(phys_root, text=' What would you like to call your third class?')
label.grid(row=0, column=0, sticky=E, pady=25)
global entry2
entry2 = Entry(phys_root)
entry2.grid(row=0, column=1, sticky=W, pady=25)
entry2.bind("<Return>", submit_phys)
space = Label(phys_root, text=' ')
space.grid(row=0, column=2)
button = Button(phys_root, text='Submit', command=submit_phys)
button.grid(row=1, columnspan=3)
bottom_space = Label(phys_root, text=' ')
bottom_space.grid(row=2, pady=1)
phys_root.mainloop()
# The second function for the third class
def submit_phys(*args):
global class3, entry2, root, test
class3 = entry2.get()
if len(class3) > 18:
class3 = class3[0:16] + '...'
phys_write = open('phys.txt', 'w')
phys_write.write(class3)
phys_write.close()
phys_root.destroy()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
# The first function for the fourth class
def prompt_span():
global span_root
while TRUE:
try:
span_root.destroy()
break
finally:
break
span_root = Tk()
span_root.title("Name Changer")
span_root.iconbitmap('favicon.ico')
label = Label(span_root, text=' What would you like to call your fourth class?')
label.grid(row=0, column=0, sticky=E, pady=25)
global entry3
entry3 = Entry(span_root)
entry3.grid(row=0, column=1, sticky=W, pady=25)
entry3.bind("<Return>", submit_span)
space = Label(span_root, text=' ')
space.grid(row=0, column=2)
button = Button(span_root, text='Submit', command=submit_span)
button.grid(row=1, columnspan=3)
bottom_space = Label(span_root, text=' ')
bottom_space.grid(row=2, pady=1)
span_root.mainloop()
# The first function for the fourth class
def submit_span(*args):
global class4, entry3, test, root
class4 = entry3.get()
if len(class4) > 18:
class4 = class4[0:16] + '...'
span_write = open('span.txt', 'w')
span_write.write(class4)
span_write.close()
span_root.destroy()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
# The first function for the fifth class
def prompt_engl():
global engl_root
while TRUE:
try:
engl_root.destroy()
break
finally:
break
engl_root = Tk()
engl_root.title("Name Changer")
engl_root.iconbitmap('favicon.ico')
label = Label(engl_root, text=' What would you like to call your fifth class?')
label.grid(row=0, column=0, sticky=E, pady=25)
global entry4
entry4 = Entry(engl_root)
entry4.grid(row=0, column=1, sticky=W, pady=25)
entry4.bind("<Return>", submit_engl)
space = Label(engl_root, text=' ')
space.grid(row=0, column=2)
button = Button(engl_root, text='Submit', command=submit_engl)
button.grid(row=1, columnspan=3)
bottom_space = Label(engl_root, text=' ')
bottom_space.grid(row=2, pady=1)
engl_root.mainloop()
# The second function for the fifth class
def submit_engl(*args):
global class5, entry4, test, root
class5 = entry4.get()
if len(class5) > 18:
class5 = class5[0:16] + '...'
engl_write = open('engl.txt', 'w')
engl_write.write(class5)
engl_write.close()
engl_root.destroy()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
# The first function for the sixth class
def prompt_hist():
global hist_root
while TRUE:
try:
hist_root.destroy()
break
finally:
break
hist_root = Tk()
hist_root.title("Name Changer")
hist_root.iconbitmap('favicon.ico')
label = Label(hist_root, text=' What would you like to call your fifth class?')
label.grid(row=0, column=0, sticky=E, pady=25)
global entry5
entry5 = Entry(hist_root)
entry5.grid(row=0, column=1, sticky=W, pady=25)
entry5.bind("<Return>", submit_hist)
space = Label(hist_root, text=' ')
space.grid(row=0, column=2)
button = Button(hist_root, text='Submit', command=submit_hist)
button.grid(row=1, columnspan=3)
bottom_space = Label(hist_root, text=' ')
bottom_space.grid(row=2, pady=1)
hist_root.mainloop()
# The second function for the fifth class
def submit_hist(*args):
global class6, entry5, test, root
class6 = entry5.get()
if len(class6) > 18:
class6 = class6[0:16] + '...'
hist_write = open('hist.txt', 'w')
hist_write.write(class6)
hist_write.close()
hist_root.destroy()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
# The first function for the seventh class
def prompt_chem():
global chem_root
while TRUE:
try:
chem_root.destroy()
break
finally:
break
chem_root = Tk()
chem_root.title("Name Changer")
chem_root.iconbitmap('favicon.ico')
label = Label(chem_root, text=' What would you like to call your fifth class?')
label.grid(row=0, column=0, sticky=E, pady=25)
global entry6
entry6 = Entry(chem_root)
entry6.grid(row=0, column=1, sticky=W, pady=25)
entry6.bind("<Return>", submit_chem)
space = Label(chem_root, text=' ')
space.grid(row=0, column=2)
button = Button(chem_root, text='Submit', command=submit_chem)
button.grid(row=1, columnspan=3)
bottom_space = Label(chem_root, text=' ')
bottom_space.grid(row=2, pady=1)
chem_root.mainloop()
# The second function for the seventh(!) class
def submit_chem(*args):
global class7, entry6, test, root
class7 = entry6.get()
if len(class7) > 18:
class7 = class7[0:16] + '...'
chem_write = open('chem.txt', 'w')
chem_write.write(class7)
chem_write.close()
chem_root.destroy()
dims = [root.winfo_x(), root.winfo_y(), root.winfo_height(), root.winfo_width()]
test.master.destroy()
root = Tk()
root.geometry('%dx%d+%d+%d' % (dims[3], dims[2], dims[0], dims[1]))
test = AverageClass(root)
root.iconbitmap('favicon.ico')
test = AverageClass(root)
root.iconbitmap('favicon.ico')
root.mainloop()
# This is just to reset the active scores so that next time the user opens the program, all 0's are displayed
score_writer = open('active.txt', 'w')
score_writer.write('0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0')
score_writer.close()
# What I still want to do:
# 1) Add/remove rows based on class
# 2) Have user choose extra credit
|
05985339a44c8762de7b54a5c087e385afac3e56 | GeertRoks/CSD2 | /CSD2a/AntwoordenExamples/03_randomTimeAntw.py | 1,455 | 3.703125 | 4 | import simpleaudio as sa
import time
import random
"""
An example project in which three wav files are played after eachother with a
break in between of a random duration.
Used durations are: 0.125, 0.25 and 0.5 seconds
------ HANDS-ON TIPS ------
- Alter the code:
Add a noteDurations list, with the numbers 0.25, 0.5, 1.0. These values stand
for a sixteenth, eighth and quarter note.
Add a bpm value to the project and calculate the corresponding timeIntervals
accordingly. Add these values to the timeIntervals list, instead of its
current values.
- Alter the code:
Write a function around the playback forloop, which takes two arguments:
- a list with samples
- a list with timeIntervals
Use this function.
"""
#load 3 audioFiles into a list
samples = [sa.WaveObject.from_wave_file("audioFiles/Pop.wav"),
sa.WaveObject.from_wave_file("audioFiles/Laser1.wav"),
sa.WaveObject.from_wave_file("audioFiles/Dog2.wav")]
bpm = 120
#create a list to hold the timeIntervals 0.25, 0.5, 1.0
timeIntervals = [0.25, 0.5, 1]
#play samples and wait in between (random duration)
for sample in samples:
#display the sample object
print(sample)
#play sample
sample.play()
#retrieve a random index value -> 0 till 2
randomIndex = random.randint(0, 2)
#dislay the selected timeInterval
print("waiting: " + str(timeIntervals[randomIndex]) + " seconds.")
#wait!
time.sleep(timeIntervals[randomIndex])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.