blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
11c57367b1f26d98d8ccab7ab1fc44fedfe7ca42 | IceMints/Python | /blackrock_ctf_07/Fishing.py | 1,503 | 4.25 | 4 | # Python3 Program to find
# best buying and selling days
# This function finds the buy sell
# schedule for maximum profit
def max_profit(price, fee):
profit = 0
n = len(price)
# Prices must be given for at least two days
if (n == 1):
return
# Traverse through given price array
i = 0
while (i < (n - 1)):
# Find Local Minima
# Note that the limit is (n-2) as we are
# comparing present element to the next element
while ((i < (n - 1)) and ((price[i + 1])<= price[i])):
i += 1
# If we reached the end, break
# as no further solution possible
if (i == n - 1):
break
# Store the index of minima
buy = i
buying = price[buy]
i += 1
# Find Local Maxima
# Note that the limit is (n-1) as we are
# comparing to previous element
while ((i < n) and (price[i] >= price[i - 1])):
i += 1
while (i < n) and (buying + fee >= price[i - 1]):
i += 1
# Store the index of maxima
sell = i - 1
selling = price[sell]
print("Buy on day: ",buy,"\t",
"Sell on day: ",sell)
print(buying, selling)
profit += (selling - fee - buying)
print(profit)
# sample test case
# Stock prices on consecutive days
price = [1, 3, 2, 8, 4, 9]
n = len(price)
# Fucntion call
max_profit(price, 2)
|
9e78c589ae150f49d8d743ffabe3acfa3b85674a | smallflyingpig/leetcode | /the_sward_to_offer/29.py | 1,046 | 3.546875 | 4 | """
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
input1: [[1,2],[3,4]]
output1: [1,2,4,3]
"""
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
H, W = len(matrix), len(matrix[0])
i,j = 0,0
rtn = []
while H>0 and W>0:
rtn += matrix[i][j:j+W-1]
j += W-1
rtn += [matrix[_i][j] for _i in range(i, i+H-1)]
i += H-1
if H==1 or W==1:
rtn.append(matrix[i][j])
break
rtn += matrix[i][j:j-(W-1):-1]
j -= W-1
rtn += [matrix[_i][j] for _i in range(i,i-(H-1),-1)]
i -= H-1
i += 1
j += 1
H -= 2
W -= 2
return rtn
|
8bbbe27826bc90773247fa63aa779423a92b00ad | smallflyingpig/leetcode | /the_sward_to_offer/41.2.py | 2,064 | 3.75 | 4 | # -*- coding:utf-8 -*-
"""
字符流中第一个不重复的字符
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
后台会用以下方式调用Insert 和 FirstAppearingOnce 函数
string caseout = "";
1.读入测试用例字符串casein
2.如果对应语言有Init()函数的话,执行Init() 函数
3.循环遍历字符串里的每一个字符ch {
Insert(ch);
caseout += FirstAppearingOnce()
}
2. 输出caseout,进行比较。
返回值描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
input1:
google
output1:
ggg#ll
"""
class Solution:
def __init__(self):
self.freq = [0 for _ in range(128)]
self.char_queue = []
self.first_char = None
# 返回对应char
def FirstAppearingOnce(self):
# write code here
if self.first_char is None:
return '#'
else:
return self.first_char
def Insert(self, char):
# write code here
char_int = ord(char)
if self.freq[char_int] == 0:
self.freq[char_int] = 1
self.char_queue.append(char)
if self.first_char is None:
self.first_char = char
else:
self.freq[char_int] += 1
if char == self.first_char:
# update queue
while len(self.char_queue)>0 and self.freq[ord(self.char_queue[0])]>1:
self.char_queue = self.char_queue[1:]
if len(self.char_queue)>0:
self.first_char = self.char_queue[0]
else:
self.first_char = None
if __name__=="__main__":
string = 'google'
rtn = ''
solution = Solution()
for c in string:
solution.Insert(c)
rtn += solution.FirstAppearingOnce()
print(rtn) |
5b8a511d1b41dbecda8f5349c3a3fba7ae96ced2 | smallflyingpig/leetcode | /the_sward_to_offer/41.1.py | 2,279 | 4 | 4 | # -*- coding:utf-8 -*-
"""
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
"""
import heapq
class MaxHeap:
def __init__(self):
self.data = []
def top(self):
return -self.data[0]
def push(self, val):
heapq.heappush(self.data, -val)
def pop(self):
return -heapq.heappop(self.data)
def __len__(self):
return len(self.data)
class MinHeap:
def __init__(self):
self.data = []
def top(self):
return self.data[0]
def push(self, val):
heapq.heappush(self.data, val)
def pop(self):
return heapq.heappop(self.data)
def __len__(self):
return len(self.data)
class Solution:
def __init__(self):
self.min_heap = MinHeap()
self.max_heap = MaxHeap()
def Insert(self, num):
# write code here
if len(self.max_heap)==0:
self.max_heap.push(num)
return
elif len(self.min_heap)==0:
self.min_heap.push(num)
return
else:
pass
top_left = self.max_heap.top()
top_right = self.min_heap.top()
if num>top_left:
self.min_heap.push(num)
if len(self.min_heap)>len(self.max_heap):
d = self.min_heap.pop()
self.max_heap.push(d)
else:
self.max_heap.push(num)
if len(self.max_heap)>len(self.min_heap)+1:
d = self.max_heap.pop()
self.min_heap.push(d)
def GetMedian(self):
# write code here
if len(self.max_heap)==len(self.min_heap):
return (self.max_heap.top()+self.min_heap.top())/2
else:
return self.max_heap.top()
if __name__=="__main__":
data = [1,3,8,7,9,2,4,5,6,0,10]
s = Solution()
for d in data:
s.Insert(d)
print(s.GetMedian())
|
5318a53949d7cf0e5c395602ac52d225b64f572d | GeoffBreemer/DLToolkit | /dltoolkit/preprocess/resize.py | 995 | 3.984375 | 4 | """Resize an image to a new height, width and interpolation method"""
import cv2
class ResizePreprocessor:
"""Resize an image to a new height, width and interpolation method
Attributes:
width: new width of the image
height: new height of the image
interp: resize interpolation method
"""
def __init__(self, width, height, interp=cv2.INTER_AREA):
"""
Initialise the class
:param width: desired image width
:param height: desired image height
:param interp: desired interpolation method
"""
self.width = width
self.height = height
self.interp = interp
def preprocess(self, image):
"""
Preprocess the image by resizing it to the new width and height using the chosen interpolation method
:param image: image data
:return: preprocessed image data
"""
return cv2.resize(image, (self.width, self.height), interpolation=self.interp)
|
fbf0437b8e91ebb09b1b51296170487289735c66 | GeoffBreemer/DLToolkit | /dltoolkit/preprocess/resizewithaspectratio.py | 1,581 | 3.890625 | 4 | """Resize an image while maintaining its aspect ratio, cropping the image if/when required
Code is based on the excellent book "Deep Learning for Computer Vision" by PyImageSearch available on:
https://www.pyimagesearch.com/deep-learning-computer-vision-python-book/
"""
import cv2
import imutils
class ResizeWithAspectRatioPreprocessor:
def __init__(self, width, height, inter=cv2.INTER_AREA):
"""
Initialise the class
:param width: desired image width
:param height: desired image height
:param inter: desired interpolation method
"""
self.width = width
self.height = height
self.inter = inter
def preprocess(self, image):
"""
Perform the resize operation
:param image: image data
:return: resized image data
"""
(height, width) = image.shape[:2]
crop_width = 0
crop_height = 0
# Determine whether to crop the height or width
if width < height:
image = imutils.resize(image, width=self.width, inter=self.inter)
crop_height = int((image.shape[0] - self.height)/2.0)
else:
image = imutils.resize(image, height=self.height, inter=self.inter)
crop_width = int((image.shape[1] - self.width)/2.0)
# Crop the image
(height, width) = image.shape[:2]
image = image[crop_height:height - crop_height, crop_width:width - crop_width]
# Finally resize
return cv2.resize(image, (self.width, self.height), interpolation=self.inter)
|
9da1e536d9a360a4ced7217b0b8a338a7d2b2b25 | DivyaraniPhondekar/TrainingAssignments- | /Python/Assign5/Image.py | 787 | 3.71875 | 4 | from PIL import Image
size = 100, 100
class main():
while(1):
x=input("Plase Enter operation no. you want to execute: 1. RESIZE THE IMAGE 2. THUMBNAIL OF IMAGE 3.EXIT \n")
if x == 1:
try:
im = Image.open('panda.jpg')
im = im.resize(size, Image.ANTIALIAS)
im.save('resize.jpg')
except IOError:
print "cannot resize for '%s'" % infile
elif x == 2:
try:
im = Image.open('panda.jpg')
im.thumbnail(size, Image.ANTIALIAS)
im.save('thumbnail.jpg')
except IOError:
print "cannot create thumbnail for '%s'" % infile
else:
exit(0)
if __name__ == '__main__':
main()
|
0a9583f1a597607cbb0d764815bbc0444507b8b4 | Zhen001/Big-Data-Management-and-Analysis | /HDFS & MapReduce/WDreducer1.py | 1,500 | 3.8125 | 4 | #!/usr/bin/env python
'''
The script is for reducing phase
'''
import sys
current_word = word = None
current_count = line_count = word_count = unique_word = 0
words = []
# input comes from STDIN
for line in sys.stdin:
line = line.strip()
# parse the input we got from WDmapper.py
key, val = line.split('\t', 1)
# if the input is a line, we count line; otherwise we count word
if key == '#Line#':
line_count += 1
continue
word, count = key, val
# total word number add 1
word_count += 1
# convert count (a tring) to int
try:
count = int(count)
except ValueError:
# if count was not a number, silently ignore the line
continue
# Hadoop sorts map output by key (here: word) before it is passed to the reducer
if current_word == word:
current_count += count
else:
# store the (word, count) pair in a list
if current_word:
unique_word += 1
words.append((current_word, current_count))
current_count = count
current_word = word
# output the total number of lines
print('There are ' + str(line_count) + ' lines in the text.\n')
# output the top 100 most frequently words
word_100 = sorted(words, key=lambda x: x[1], reverse=True)[:100]
print('The 100 most frequently used words are:\n')
for word, count in word_100:
print((word, count))
print('\n')
# output the total word count
print('There are ' + str(word_count) + ' words in the text.\n')
# output the number of unique words
print('There are ' + str(unique_word) + ' unique words in the text') |
dc9e8b7b79223b58c8f7c37728d86957306ed96e | JVuns/Driver-Log-Recorder---Final-Project | /New folder/New folder/Kvun/P04 NIM 02(2).py | 335 | 3.75 | 4 | input1 = int(input("Input N: "))
input2 = int(input("Input M: "))
matrix = []
input3 = str(input("Input string: "))
count = 0
for y in range(input1):
for i in range(input2):
a = []
a.append(input3[count::(input2)])
matrix.append(a)
count += 1
a = ""
for x in matrix:
for c in x:
a += c
print(a) |
251caa642fd81d10abb2f3e7f8eeee6439325ffd | JVuns/Driver-Log-Recorder---Final-Project | /New folder/New folder/Kvun/P04 NIM 02.py | 244 | 3.921875 | 4 | input1 = str(input("Input the initial integer: "))
count = 0
while len(input1) != 1:
result = 1
for i in input1:
count += 1
result *= int(i)
input1 = str(result)
print (f"After {count} process: {result}")
|
245ab5b35314ca645807899f74f23c23d067a88b | cdacsanket1595/exam1 | /gcd.py | 95 | 3.890625 | 4 | a=(input("Enter no 1:-"))
b=(input("Enter no 2:-"))
if a > b:
print(a)
else:
print(b)
|
ca852b7e34604400fef625312f0d1c033dca39b0 | frankverrill/Py | /Test/cust_service_bot.py | 4,893 | 3.90625 | 4 | """ cust = customer/
selected = every function where there is an option to select/
"""
def cust_service_bot(): # Automated web customer support
print(
"The DNS Cable Company's Service Portal.",
"Are you a new or existing customer?",
"\n [1] New",
"\n [2] Existing")
selected = input("Enter [1] or [2]: ")
if selected == "1":
print("new_cust()")
elif selected == "2":
existing_cust()
else:
print("Try again, select only: [1] or [2]")
cust_service_bot()
def new_cust(): # Select type of service for New Customer
print("How can we help?",
"\n[1] Sign up for service?",
"\n[2] Schedule home visit?",
"\n[3] Speak to live person?")
selected = input(
"Enter [1], [2] or [3]: ")
if selected == "1":
sign_up()
elif selected == "2":
home_visit("home visit")
elif selected == "3":
live_rep("sales")
else:
print("Try again, select only: [1], [2] or [3]")
new_cust()
def sign_up(): # New customer selects options to sign up for
print("Please select the package ",
"you are interested in signing up for:",
"\n[1] Bundle (Internet + Cable)",
"\n[2] Internet",
"\n[3] Cable")
selected = input("Enter [1], [2] or [3]: ")
if selected == "1":
print("You've selected the Bundle Package! ",
"Schedule a home visit and our technician ",
"will come out and set up your new service.")
home_visit("new install")
elif selected == "2":
print("You've selected the Internet Only Package! ",
"Schedule a home visit and our technician ",
"will come out and set up your new service.")
home_visit("new install")
elif selected == "3":
print("You've selected the Cable Only Package! ",
"Schedule a home visit and our technician ",
"will come out and set up your new service.")
home_visit("new install")
else:
print("Try again, select only: [1], [2] or [3]")
sign_up()
def existing_cust(): # Type of support for existing customer
print("What do you need help with?",
"\n[1] TV",
"\n[2] Internet",
"\n[3] Speak to a Live Person")
selected = input("Enter [1], [2] or [3]: ")
if selected == "1":
tv()
elif selected == "2":
internet()
elif selected == "3":
live_rep("sales")
else:
print("Try again, select only: [1], [2] or [3]")
existing_cust()
def tv(): # TV support
print("What is the issue?",
"\n [1] Can't access certain channels",
"\n [2] Picture is blurry",
"\n [3] Keep losing service",
"\n [4] Other issues")
selected = input("Enter [1], [2], [3] or [4]: ")
if selected == "1":
print("Please check the channel lists at DefinitelyNotSinister.com.:",
"\nIf the channel you cannot access is there,",
"\nplease contact a live representative.")
did_that_help("a blurry picture")
elif selected == "2":
print("Try adjusting the antenna above your television set.")
did_that_help("adjusting the antenna")
elif selected == "3":
print("Is it raining outside? If so, ",
"\nwait until it's not raining, then try again.")
did_that_help("the rain outside")
elif selected == "4":
live_rep("support")
else:
print("Try again, select only: [1], [2] or [3]")
tv()
def internet(): # Internet support
print("What is the issue?",
"\n[1] Can't connect to internet",
"\n[2] Very slow connection",
"\n[3] Can't access certain sites",
"\n[4] Other issues")
selected = input("Enter only: [1], [2], [3] or [4]: ")
if selected == "1":
print("Unplug your router, then plug it back in, "
"then give it a good whack, like the Fonz.")
did_that_help("can't connect to internet")
elif selected == "2":
print("Move to a different region or install a VPN. ",
"Some areas block certain sites")
did_that_help("very slow connection")
elif selected == "3":
print("Is it raining outside? If so, ",
"wait until it's not raining, then try again.")
did_that_help("can't access certain sites")
elif selected == "4":
live_rep("support")
else:
print("Try again, select only: [1], [2] or [3]")
internet()
def did_that_help(message): # Did that support answer help?
print(message)
def home_visit(purpose): # Book a home visit
print(purpose)
def live_rep(message): # Live person support
print(message)
cust_service_bot() # Function call to automated customer support
|
f938ced4e04b95f0d13048fcefe7c2e633edd2fc | bristy/HackYourself | /hackerearth/hacker_earth/college/practice/generate_prime.py | 603 | 3.65625 | 4 | # http://www.hackerearth.com/practice-contest-1-3/algorithm/generate-the-primes-2/
from sys import stdin
def getInt():
return map(int, stdin.readline().split())
# @param integer n
# list of primes below n
def sieve(n):
primes = list()
s = [True] * n
s[0] = s[1] = False
for i in xrange(2, n):
if s[i]:
j = i * i
while j < n:
s[j] = False
j += i
primes.append(i)
return (primes, s)
MAX = 10000000
primes, s = sieve(MAX)
t, = getInt()
for _ in xrange(t):
n = getInt() - 1
print primes[n]
|
a1514c507909bd3d00953f7a8c7dd09223779ead | VEGANATO/Organizing-Sales-Data-Code-Academy | /script.py | 651 | 4.53125 | 5 | # Len's Slice: I work at Len’s Slice, a new pizza joint in the neighborhood. I am going to use my knowledge of Python lists to organize some of the sales data.
print("Sales Data")
# To keep track of the kinds of pizzas sold, a list is created called toppings that holds different toppings.
toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"]
# A list called "prices" is created to track how much each pizza costs.
prices = [2, 6, 1, 3, 2, 7, 2]
len(toppings)
num_pizzas = len(toppings)
print("We sell " + str(num_pizzas) + " different kinds of pizza!")
pizzas = list(zip(prices, toppings))
print(pizzas)
|
f2c8fbab9bf7f8bc0e423d9a2b53896a95961b02 | AbhayF8/thinkpython.py | /1.py | 497 | 3.84375 | 4 | import turtle as t
def koch(t,n):
"""draws a koch curve with the given length n and t as turtle"""
if (n<3):
t.fd(n)
return n
else:
koch(t,n/3)
t.lt(60)
koch(t,n/3)
t.rt(120)
koch(t,n/3)
t.lt(60)
koch(t,n/3)
# to draw a snowflake with 3 parts
# for i in range(3):
# koch(t,180)
# t.rt(120)
def snowflake(t,n,a):
for i in range(a):
koch(t,n)
t.rt(360/a)
snowflake(t,180,8)
t.mainloop() |
f21b2b2f20b59d677d6f2fbbed23ea46bd0ad713 | pharick/python-coursera | /week7/15-synonims.py | 160 | 3.640625 | 4 | n = int(input())
words = dict()
for _ in range(n):
word1, word2 = input().split()
words[word1] = word2
words[word2] = word1
print(words[input()])
|
c3fa671896b191e6f884c9e46fbe7361b5326dac | pharick/python-coursera | /week3/2-sum-of-row.py | 105 | 3.625 | 4 | n = int(input())
sum = 0
for i in range(1, n + 1):
sum += 1 / (i**2)
print("{0:.6f}".format(sum))
|
c05f73e0239c2ae34f6f9807765cc18635fa359e | pharick/python-coursera | /week7/9-polyglots.py | 431 | 3.703125 | 4 | n = int(input())
all_students = set()
one_student = set()
for i in range(n):
m = int(input())
student_langs = set()
for j in range(m):
student_langs.add(input())
if i == 0:
all_students = student_langs
else:
all_students &= student_langs
one_student |= student_langs
print(len(all_students))
print(*all_students, sep="\n")
print(len(one_student))
print(*one_student, sep="\n")
|
d4d0831a7335cd636b06fa82f6eaf2bf6a02134d | pharick/python-coursera | /week2/45-max-near-equal.py | 276 | 3.578125 | 4 | n = int(input())
last = 0
if n != 0:
count = 1
else:
count = 0
max_count = count
while n != 0:
last = n
n = int(input())
if n == last:
count += 1
else:
count = 1
if count > max_count:
max_count = count
print(max_count)
|
fa097a4d517368a2cc341da7e94089ea82ec627e | pharick/python-coursera | /week4/14-gcd.py | 239 | 3.90625 | 4 | def gcd(a, b):
if a == 1 or b == 1:
return 1
if a == b:
return a
if a < b:
a, b = b, a
if a % b == 0:
return b
return gcd(b, a % b)
a = int(input())
b = int(input())
print(gcd(a, b))
|
23993e926a21e60e5527f7b11f2d8e718e44574d | pharick/python-coursera | /week2/14-even-odd.py | 228 | 3.796875 | 4 | a = int(input())
b = int(input())
c = int(input())
is_one_even = a % 2 == 0 or b % 2 == 0 or c % 2 == 0
is_one_odd = a % 2 == 1 or b % 2 == 1 or c % 2 == 1
if is_one_even and is_one_odd:
print("YES")
else:
print("NO")
|
7e2eb3ac9b86b13729fed53e427e0b5edab2b4ef | pharick/python-coursera | /week3/15-first-and-last.py | 179 | 3.65625 | 4 | string = input()
o1 = string.find("f")
o2 = string[::-1].find("f")
if o2 != -1:
o2 = len(string) - o2 - 1
if o2 == o1:
print(o1)
else:
print(o1, o2)
|
8a7d269f016f4d4511b3170780220892909b84e1 | pharick/python-coursera | /week7/7-guess-number.py | 288 | 3.71875 | 4 | n = int(input())
numbers = set(range(1, n + 1))
line = input()
while line != "HELP":
question = set(map(int, line.split()))
answer = input()
if answer == "YES":
numbers &= question
else:
numbers -= question
line = input()
print(*sorted(numbers))
|
f61e08ab356df988fdff02fd02f40935d059eabb | pharick/python-coursera | /week2/18-boxes.py | 1,473 | 3.5625 | 4 | a1 = int(input())
b1 = int(input())
c1 = int(input())
a2 = int(input())
b2 = int(input())
c2 = int(input())
case1 = (a1 == a2) and (b1 == b2) and (c1 == c2)
case2 = (a1 == b2) and (b1 == a2) and (c1 == c2)
case3 = (a1 == b2) and (b1 == c2) and (c1 == a2)
case4 = (a1 == a2) and (b1 == c2) and (c1 == b2)
case5 = (a1 == c2) and (b1 == a2) and (c1 == b2)
case6 = (a1 == c2) and (b1 == b2) and (c1 == a2)
if case1 or case2 or case3 or case4 or case5 or case6:
print("Boxes are equal")
else:
case1 = (a1 >= a2) and (b1 >= b2) and (c1 >= c2)
case2 = (a1 >= b2) and (b1 >= a2) and (c1 >= c2)
case3 = (a1 >= b2) and (b1 >= c2) and (c1 >= a2)
case4 = (a1 >= a2) and (b1 >= c2) and (c1 >= b2)
case5 = (a1 >= c2) and (b1 >= a2) and (c1 >= b2)
case6 = (a1 >= c2) and (b1 >= b2) and (c1 >= a2)
if case1 or case2 or case3 or case4 or case5 or case6:
print("The first box is larger than the second one")
else:
case1 = (a1 <= a2) and (b1 <= b2) and (c1 <= c2)
case2 = (a1 <= b2) and (b1 <= a2) and (c1 <= c2)
case3 = (a1 <= b2) and (b1 <= c2) and (c1 <= a2)
case4 = (a1 <= a2) and (b1 <= c2) and (c1 <= b2)
case5 = (a1 <= c2) and (b1 <= a2) and (c1 <= b2)
case6 = (a1 <= c2) and (b1 <= b2) and (c1 <= a2)
if case1 or case2 or case3 or case4 or case5 or case6:
print("The first box is smaller than the second one")
else:
print("Boxes are incomparable")
|
d46dd99e9bdbbabb35b9ea77ace0f6cc280ccc2a | pharick/python-coursera | /week2/7-chessboard.py | 357 | 3.8125 | 4 | x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
x_diff = x1 - x2
if x_diff < 0:
x_diff = x2 - x1
y_diff = y1 - y2
if y_diff < 0:
y_diff = y2 - y1
if x_diff % 2 == 0:
if y_diff % 2 == 0:
print("YES")
else:
print("NO")
else:
if y_diff % 2 == 0:
print("NO")
else:
print("YES")
|
dfd3b1f1adfba41eb01831fc03f550c4bb826f43 | pharick/python-coursera | /week7/12-phone-numbers.py | 458 | 3.9375 | 4 | def unify_number(number):
result = ""
for s in number:
if s != "(" and s != ")" and s != "-" and s != "+":
result += s
if len(result) == 7:
result = "8495" + result
elif result[0] == "7":
result = "8" + result[1:]
return result
new_number = unify_number(input())
for _ in range(3):
number = unify_number(input())
if number == new_number:
print("YES")
else:
print("NO")
|
03b4ce541905902ed5e04e0634319e05b91a805e | cohadar/learn-python-the-hard-way | /ex35.py | 1,550 | 3.84375 | 4 | import sys
def gold_room():
print "this room is full of gold, how much do you take?"
choice = raw_input('> ')
try:
how_much = int(choice)
except ValueError:
dead('learn to type a number')
if how_much < 50:
print "Nice, you are not greedy, you win"
sys.exit(0)
else:
dead("You greedy bastard")
def bear_room():
print "There is a bear here, he has lots of honey"
print "The fat bear is in front of another door, how will you move the bear?"
bear_moved = False
for _ in xrange(10000):
choice = raw_input('> ')
if choice == 'take honey':
dead('bear slaps your face off')
elif choice == 'taun bear' and not bear_moved:
print "bear has moved"
bear_moved = True
elif choice == 'taun bear' and bear_moved:\
dead('bear catches you, you get ucked')
elif choice == 'open door' and bear_moved:
gold_room()
else:
print "unknown choice, try: 'take honey', 'taun bear' or 'open door'"
def cthulhu_room():
print "You see the great evil Cthulhu"
print "You go insane"
print "Flee for your life or eat your own head?"
choice = raw_input('> ')
if 'flee' in choice:
start()
elif 'head' in choice:
dead("your head tastes good")
else:
cthulhu_room()
def dead(why):
print why, 'Good Job!'
sys.exit(0)
def start():
print "You are in a dark room"
print "There is a door to your right and left"
print "which one do you take"
choice = raw_input('> ')
if choice == 'left':
bear_room()
elif choice == 'right':
cthulhu_room()
else:
dead('wandering around you fell into a pit')
start()
|
3678c826c8c66c2acfa14d167753cd1905a5a048 | LokIIE/AdventOfCode2020 | /Day3/firstStar.py | 288 | 3.515625 | 4 | inputFile = open("input.txt", "r")
grid = []
currColumn = 0
countTrees = 0
for line in inputFile:
if line[currColumn] == "#":
countTrees += 1
currColumn += 3
if currColumn >= (len(line) - 1):
currColumn = currColumn % (len(line) - 1)
print(countTrees) |
0f71ebbafc60d8f6974949e63fccbfc22ac011b3 | asirvex/andela-interview | /password_checker.py | 1,305 | 4 | 4 | from string import ascii_uppercase, ascii_lowercase, digits
passwords = list(input("Enter comma separated passwords: ").split(","))
def min_length(password):
return len(password) >= 6
def max_length(password):
return len(password) <= 12
def has_lower(password):
lower_count = 0
for letter in password:
if letter in ascii_lowercase:
lower_count += 1
return lower_count > 0
def has_upper(password):
upper_count = 0
for letter in password:
if letter in ascii_uppercase:
upper_count += 1
return upper_count > 0
def has_digit(password):
digit_count = 0
for i in password:
if i in digits:
digit_count += 1
return digit_count > 0
def has_char(password):
char_count = 0
char_list = ["$", "#", "@"]
for i in password:
if i in char_list:
char_count += 1
return char_count > 0
def password_validate(passwords):
good_passwords = []
for password in passwords:
if min_length(password) and max_length(password) and has_char(password) and has_digit(password) and has_lower(password) and has_upper(password):
good_passwords.append(password)
return good_passwords
for password in password_validate(passwords):
print(password)
|
b23339a3e5ef9ad71ba9b7cbf064fe1f262ae40b | altruistically-minded/euler | /problem_003/problem009.py | 2,541 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
=================================================================
Sieve of Eratosthenes
=================================================================
Input: an integer n > 1
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding sqrt(n):
if A[i] is true:
for j = i2, i2+i, i2+2i, ..., not exceeding n :
A[j] := false
Output: all i such that A[i] is true.
"""
import time
from math import sqrt
class Point:
""" Point class represents and manipulates x,y coords. """
def __init__(self):
""" Create a new point at the origin """
self.x = 0
self.y = 0
def farey( n, asc=True ):
seq = []
"""Python function to print the nth Farey sequence, either ascending or descending."""
if asc:
a, b, c, d = 0, 1, 1 , n # (*)
else:
a, b, c, d = 1, 1, n-1 , n # (*)
while (asc and c <= n) or (not asc and a > 0):
k = int((n + b)/d)
a, b, c, d = c, d, k*c - a, k*d - b
p = Point()
p.x = a
p.y = b
seq.append(p)
return seq
def genTFtable(n):
l = [True]*(n+1)
for i in range(2, n+1):
if l[i]:
for x in range(i*2,n+1,i):
l[x] = False
return l
def genPrimes(n):
truthTable = genTFtable(n)
primes = []
for x in range(0, len(truthTable)):
if truthTable[x]:
primes.append(x)
return primes
#n = 20
tStart = time.time()
###########################################################################
n = 1000
f = farey(n)
possible = []
for i in f:
a = i.x
b = float(i.y)
print "%d, %d" % (a, b)
# Possible match
c = 0
c = sqrt(a**2 + b**2)
if (a + b + c) == 1000:
possible.append((a,b,c))
print '-'*20
print possible
###########################################################################
print "run time = " + str((time.time() - tStart))
def brute_force(n):
possible = []
for a in range(0,n):
for b in range(0,n):
c = sqrt(a**2 + b**2)
if (a+b+c) == 1000:
possible.append((a,b,c))
return possible
tStart = time.time()
###########################################################################
n = 1000
possible = brute_force(n)
print possible
###########################################################################
print "run time = " + str((time.time() - tStart))
|
d3315de4b268377b31cf00542f69fb9f8ea1190d | AlanSobenes/for_loop_basic1 | /for_loop_basic1.py | 576 | 3.609375 | 4 | # 1. Basic
for x in range(150):
print(x)
# 2. Multiples of Five
for x in range(5, 1000, 5):
print(x)
# 3. Counting the Dojo way
for x in range(1, 101):
if x % 10 == 0:
x = "Coding Dojo"
elif x % 5 == 0:
x = "Coding"
print(x)
# 4. Whoa. That sucker's Huge
sum = 0
for x in range(0, 500001):
if x % 2 == 1:
sum += x
print(sum)
# 5. Countdown by Fours
for x in range(2018,0,-4):
print(x)
# 6. Flexible Counter
lowNum = 2
highNum = 9
mult = 3
for x in range(lowNum, highNum + 1):
if x % mult == 0:
print(x) |
1a8262e906cafab214943997574fa2106db0abdf | HenryAcevedo/canvas-scripts | /scripts/get-course-comments.py | 1,651 | 3.53125 | 4 | #
# Henry Acevedo
#
# Purpose: Get Comments from assignments for a course
import csv
from canvasapi import Canvas
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
MYURL = config.get('instance', 'test')
MYTOKEN = config.get('auth', 'token')
canvas = Canvas(MYURL, MYTOKEN)
def main():
# Will begin by asking for a course id, can be found in URL of course
# Will then grab that course and get a list of assignments
num = int(input('Enter your course number: '))
course = canvas.get_course(num)
assignments = course.get_assignments()
# Create a .csv file to populate with our findings, write header
with open("SubComments.csv", "w", newline='') as myFile:
writer = csv.writer(myFile)
writer.writerow(['Assignment Name', 'Preview Submission', 'Submission Author', 'Comment', 'Comment Author'])
# Cycle through the assignments in the course
for assignment in assignments:
# get the submissions for the current assignment
submissions = assignment.get_submissions(include=['submission_comments', 'user'])
# For each submision
for sub in submissions:
# For each comment in current submission
for comment in sub.submission_comments:
# Print and write to .csv file
print(assignment.name, sub.preview_url, sub.user['name'], comment['comment'], comment['author_name'])
writer.writerow([assignment.name, sub.preview_url, sub.user['name'], comment['comment'], comment['author_name']])
if __name__ == "__main__":
main()
|
53aa99bf40211591483a7abce633ab307626820f | pveiga-abreu/design-patterns | /State/classes/desconto.py | 2,008 | 3.578125 | 4 | from abc import ABCMeta, abstractmethod
class Estado_Orcamento(object):
__metaclass__ = ABCMeta
@abstractmethod
def aplica_desconto(self, orcamento): pass
@abstractmethod
def aprova(self, orcamento): pass
@abstractmethod
def reprova(self, orcamento): pass
@abstractmethod
def finaliza(self, orcamento): pass
class Em_Aprovacao(Estado_Orcamento):
def aplica_desconto(self, orcamento):
orcamento.adiciona_desconto_extra(orcamento.valor*0.02)
def aprova(self, orcamento):
orcamento.estado_atual = Aprovado()
def reprova(self, orcamento):
orcamento.estado_atual = Reprovado()
def finaliza(self, orcamento):
raise Exception('Orçamentos em aprovação não podem ir para finalizado')
class Aprovado(Estado_Orcamento):
def aplica_desconto(self, orcamento):
orcamento.adiciona_desconto_extra(orcamento.valor*0.05)
def aprova(self, orcamento):
raise Exception('Orçamento já aprovado')
def reprova(self, orcamento):
raise Exception('Orçamento já aprovado')
def finaliza(self, orcamento):
orcamento.estado_atual = Finalizado()
class Reprovado(Estado_Orcamento):
def aplica_desconto(self, orcamento):
raise Exception('Orçamentos reprovados não recebem desconto extra!')
def aprova(self, orcamento):
raise Exception('Orçamento já reprovado')
def reprova(self, orcamento):
raise Exception('Orçamento já reprovado')
def finaliza(self, orcamento):
orcamento.estado_atual = Finalizado()
class Finalizado(Estado_Orcamento):
def aplica_desconto(self, orcamento):
raise Exception('Orçamentos finalizados não recebem desconto extra!')
def aprova(self, orcamento):
raise Exception('orçamento já finalizado')
def reprova(self, orcamento):
raise Exception('orçamento já finalizado')
def finaliza(self, orcamento):
raise Exception('orçamento já finalizado')
|
6d03e7955cb8adfb46904b66c2ba00bfab127d99 | sofieditmer/deep_learning | /src/lr-got.py | 12,832 | 3.796875 | 4 | #!/usr/bin/env python
"""
Info: This script creates a baseline logistic regression model and trains it on the dialogue of all Game of Thrones 8 seasons to predict which season a given line is from. This model can be used as a means of evaluating how a deep learning model performs.
Parameters:
(optional) input_file: str <name-of-input-file>, default = "game_of_thrones_script.csv"
(optional) chunk_size: int <size-of-chunks>, default = 10
(optional) test_size: float <size-of-test-data>, default = 0.25
(optional) main_output_filename: str <name-of-output-file>, default = "lr_classification_report.txt"
Usage:
$ python lr-got.py
Output:
- lr_classification_report.txt: classification report of the logistic regression classifier.
- lr_heatmap.png: normalized heatmap displaying an overview of the performance of the logistic regression classifier.
- lr_cross_validation_results.png: cross-validation results obtained by the logistic regression classifier.
"""
### DEPENDENCIES ###
# core libraries
import os
import sys
sys.path.append(os.path.join(".."))
# matplotlib
import matplotlib.pyplot as plt
# import utility functions
import utils.classifier_utils as clf # for classification
import utils.preprocessing_utils as preprocess # for preprocessing
# Machine learning tools
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import ShuffleSplit # cross-validation
from sklearn import metrics
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn import preprocessing
# argparse
import argparse
import warnings
warnings.filterwarnings('ignore')
### MAIN FUNCTION ###
def main():
### ARGPARSE ###
# Initialize ArgumentParser class
ap = argparse.ArgumentParser()
# Argument 1: Path to training data
ap.add_argument("-i", "--input_filename",
type = str,
required = False, # this argument is not required
help = "Path to the training data",
default = "game_of_thrones_script.csv")
# Argument 2: Test data size
ap.add_argument("-ts", "--test_size",
type = float,
required = False, # this argument is not required
help = "Define the size of the test dataset as a float value, e.g. 0.20",
default = 0.25) # default test size
# Argument 3: Size of chunks
ap.add_argument("-c", "--chunk_size",
type = int,
required = False, # this argument is not required
help = "Number of lines to chunk together",
default = 10) # default chunk size
# Argument 4: Name of output file
ap.add_argument("-o", "--main_output_filename",
type = str,
required = False, # this argument is not required
help = "Define the name of the main output file, i.e. the classification report",
default = "lr_classification_report.txt") # default name
# Parse arguments
args = vars(ap.parse_args())
# Save input parameters
input_file = os.path.join("..", "data", args["input_filename"])
test_size = args["test_size"]
chunk_size = args["chunk_size"]
output_filename = args["main_output_filename"]
# Create output directory
if not os.path.exists(os.path.join("..", "output")):
os.mkdir(os.path.join("..", "output"))
# User message
print("\n[INFO] Initializing the construction of the logistic regression classifier...")
# Load data
print(f"\n[INFO] Loading, preprocessing, and chunking '{input_file}'...")
preprocessed_data = preprocess.load_and_tokenize(input_file)
preprocessed_df = preprocess.chunk_data(preprocessed_data, chunk_size)
# Instantiate the logistic regression classifier class
lr = Logistic_regression(preprocessed_df)
# Create test-train split
print(f"\n[INFO] Creating train-test split with test size of {test_size}...")
X_train, X_test, y_train, y_test, sentences, labels = lr.create_train_test(test_size)
# Vectorize data
print("\n[INFO] Vectorizing training and validation data using a count vectorizer...")
vectorizer, X_train_feats, X_test_feats = lr.vectorize(X_train, X_test)
# Perform grid search
print("\n[INFO] Performing grid search to estimate the most optimal hyperparameters...")
best_params = lr.perform_gridsearch(X_train_feats, y_train)
# Train logistic regression classifier on training data
print("\n[INFO] Building logistic regression classifier and training it on the traning data...")
classifier = lr.train_lr_classifier(X_train_feats, y_train, best_params)
# Evaluate the logistic regression classifier
print("\n[INFO] Evaluating the logistic regression classifier on the validation data...")
classification_metrics = lr.evaluate_lr_classifier(classifier, X_test_feats, y_test, output_filename, best_params)
print(f"\n[INFO] Below are the classification metrics for the logistic regression classifier trained with the following hyperparameters: {best_params}. These metrics are also saved as '{output_filename} in 'output' directory. \n \n {classification_metrics}\n")
# Cross-validation
print("\n[INFO] Performing cross-validation...")
lr.cross_validate(sentences, vectorizer, labels, test_size)
# User message
print("\n[INFO] Done! You have now defined and trained a logistic regression classifier. The results can be found in the 'output' directory.\n")
### LOGISTIC REGRESSION ###
# Creating Logistic Regression class
class Logistic_regression:
# Intialize Logistic regression class
def __init__(self, preprocessed_df):
# Receive input
self.preprocessed_df = preprocessed_df
def create_train_test(self, test_size):
"""
This method creates X_train, X_test, y_train, and y_test based on the preprocesssed and chunked dialogue.
"""
# Extract seasons as labels
labels = self.preprocessed_df['Season'].values
# Create train data
sentences = self.preprocessed_df["Chunks"].values
# Create training and test split using sklearn
X_train, X_test, y_train, y_test = train_test_split(sentences,
labels,
test_size=test_size,
random_state=42)
return X_train, X_test, y_train, y_test, sentences, labels
def vectorize(self, X_train, X_test):
"""
This method vectorizes the training and test data using a CountVectorizer available in scikit-learn.
"""
# Intialize count vectorizer with default parameters
vectorizer = CountVectorizer()
# Fit vectorizer to training and test data
X_train_feats = vectorizer.fit_transform(X_train)
X_test_feats = vectorizer.transform(X_test)
# Normalize features
X_train_feats = preprocessing.normalize(X_train_feats, axis=0)
X_test_feats = preprocessing.normalize(X_test_feats, axis=0)
return vectorizer, X_train_feats, X_test_feats
def perform_gridsearch(self, X_train_feats, y_train):
"""
This method performs grid search, i.e. iterates over possible hyperparameters for the logistic regression model
in order to find the most optimal values.
The hyperparameters that I have chosen to iterate over are C (regularization strength/learning rate) and tolerance.
The smaller the regularization value, the stronger the regularization, and the longer the training time.
The tolerance value tells the optimization algorithm when to stop, which means that if the tolerance value is high
the algorithm stops before it converges. Hence, the tolerance value should not be too high, because this means that
the model might not converge.
"""
# Initialize pipeline consisting of the "classifier" which is made up of the logistic regression classification function
pipe = Pipeline([('classifier', LogisticRegression())])
# Set tunable parameters for grid search
C = [1.0, 0.1, 0.01] # regularization strengths
tol = [0.1, 0.01, 0.001] # tolerance values
# Create parameter grid (a Python dictionary) that contains the hyperparameters
parameters = dict(classifier__C = C,
classifier__tol = tol)
# Choose which metrics on which we want to optimize
scores = ['precision', 'recall', 'f1']
# For each of the metrics find the optimal hyperparameter values
for score in scores:
# Initialise Gridsearch with predefined parameters
clf = GridSearchCV(pipe,
parameters,
scoring= f"{score}_weighted",
cv=5) # using 10-fold cross-validation
# Fit grid search model to data
clf.fit(X_train_feats, y_train)
# Print the best paremeters to terminal
print(f"\n [INFO] Best parameters found on training data for '{score}' metric: \n {clf.best_params_} \n")
# Save best parameters
best_params = clf.best_params_
return best_params
def train_lr_classifier(self, X_train_feats, y_train, best_params):
"""
This method trains the logistic regression classifier on the training data with hyperparameters estimated by grid search.
"""
# Train the logistic regression classifier on the scaled data
classifier = LogisticRegression(random_state = 42,
max_iter = 10000,
C=best_params['classifier__C'], # taking the most optimal regularization strength as estimated by grid search
tol=best_params['classifier__tol'], # taking the best tolerance value estimated by grid search
multi_class='multinomial').fit(X_train_feats, y_train) # when using 'multinomial' the loss minimized is the multinomial loss fit across the entire probability distribution
return classifier
def evaluate_lr_classifier(self, classifier, X_test_feats, y_test, output_filename, best_params):
"""
This method evaluates the logistic regression classifier on the validation data.
"""
# Extract predictions
y_pred = classifier.predict(X_test_feats)
# Evaluate model
classification_metrics = metrics.classification_report(y_test, y_pred)
# Save in output directory
out_path = os.path.join("..", "output", output_filename)
with open(out_path, 'w', encoding='utf-8') as f:
f.write(f"Below are the classification metrics for the logistic regression classifier trained with the following hyperparameters: {best_params} \n \n{classification_metrics}")
# Plot results as a heatmap using utility function
clf.plot_cm(y_test, y_pred, normalized=True)
# Save heatmap to output directory
out_path_heatmap = os.path.join("..", "output", "lr_heatmap.png")
plt.savefig(out_path_heatmap)
return classification_metrics
def cross_validate(self, sentences, vectorizer, labels, test_size):
"""
This method performs cross-validation and saves results in output directory.
"""
# Vectorize the sentences
X_vect = vectorizer.fit_transform(sentences)
# Intialize cross-validation
title = "Learning Curves (Logistic Regression)"
cv = ShuffleSplit(n_splits=100, test_size=test_size, random_state=0)
# Run cross-validation
model = LogisticRegression(random_state=42, max_iter = 10000)
# Plot learning curves
clf.plot_learning_curve(model, title, X_vect, labels, cv=cv, n_jobs=4)
# save in output directory
out_path = os.path.join("..", "output", "lr_cross_validation_results.png")
plt.savefig(out_path)
# Define behaviour when called from command line
if __name__=="__main__":
main() |
f75bd1438134ff227c897c69d72b3d002aeb7998 | t3miLo/web-caesar | /vigenere.py | 1,703 | 4 | 4 | from helpers import alphabet_position, rotate_character
def vigenere_encrypt(text, key):
checker = 'abcdefghijklmnopqrstuvwxyz'
key_number = []
new_message = ''
for each_letter in list(key):
key_number.append(alphabet_position(each_letter.lower()))
key = 0
for each_char in list(text):
if each_char.lower() not in checker:
new_message += each_char.lower()
else:
new_message += rotate_character(each_char, key_number[key])
key += 1
if key == len(key_number):
key = 0
return new_message
def main():
from sys import argv, exit
message = input('Type a messsage to encrypt : ')
try:
if len(argv) >= 2:
key_word = argv[1]
if key_word.isalpha() is False:
key_word = input(
'''
Please use a key word that has no
numbers/spaces/special characters
the vigenere cypher :
''')
else:
key_word = input('What is your key word? ')
if key_word.isalpha() is False:
key_word = input(
'''
Please use a key word that has no
numbers/spaces/special characters
for the vigenere cypher :
''')
except ValueError:
print('Woops you did not use a word please try again!')
exit()
if len(key_word) <= 1:
key_word = input('Please use a word that is atleast 2 characters long :')
print(vigenere_encrypt(message, key_word))
if __name__ == '__main__':
main()
|
a82ebcde0450e32bd403f3f334e81976abec92b9 | brennomaia/CursoEmVideoPython | /ex007.py | 210 | 3.921875 | 4 | nota1 = float(input('Digite o valor da nota 1: '))
nota2 = float(input('Digite o balor da nota 2: '))
media = (nota1+nota2)/2
print('A média entre {} e {} é igual a: {:.1f}'.format((nota1), (nota2), (media))) |
a4b6a01b3a542cccebc03ecdc5b90bbb4c56b3e5 | brennomaia/CursoEmVideoPython | /ex049.py | 321 | 4.03125 | 4 | #Exercício Python 049: Refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.
# EXERCICIO COM BASE DA AULA 13
t = int(input('Digite o valor da tabuada: '))
for c in range(1, 11): ## Contar de 1 a 10
s = t * c
print('{} x {} = {}'.format(t, c, s)) |
4c4dcc03d10adde7510c0f9e1c252050b23cad92 | brennomaia/CursoEmVideoPython | /ex039.py | 724 | 4.15625 | 4 | from datetime import date
aNasc = int(input('Digite o ano de nascimento: '))
aAtual = date.today().year
idade = aAtual - aNasc
# Menores de idade
if idade < 18:
calc = 18-idade
print('Quem nasceu em {} tem {} anos em {}.\nAinda faltam {} anos para o alistamento militar!\nO alistamento será em {}.'.format(aNasc, idade, aAtual, calc, (aAtual+calc)))
# Maiores
elif idade > 18:
calc = idade-18
print('Quem nasceu em {} tem {} anos em {}\nDeveria ter se alistado há {} anos.\nO alismento foi no ano de {}.'.format(aNasc, idade, aAtual, calc, (aAtual-calc)))
# Iguais a 18 anos
elif idade == 18:
print('Quem nasceu em {} tem {} anos em {}.\nDeve se alistar IMEDIATAMENTE!'.format(aNasc, idade, aAtual)) |
ef9497e554f2959e53ee6cc4b1438806cfc9b619 | brennomaia/CursoEmVideoPython | /ex046.py | 462 | 3.953125 | 4 | ## Exercício Python 048: Faça um programa que calcule a soma entre todos os números que são múltiplos de três e que se encontram no intervalo de 1 até 500.
soma = 0 ### Acomulador de soma
cont = 0 #### acomulador de contagem
for c in range(1, 501, 2):
if c % 3 == 0:
cont += 1 ### Contagem de numero diviseis por 3
soma += c ### Soma de todos os valores diviseis por 3
print('A soma de todos os {} valores é {}'.format(cont, soma)) |
4b08e3c064c59408afaf5783e9a15d29e59426cc | brennomaia/CursoEmVideoPython | /ex014.py | 162 | 3.890625 | 4 | cel = float(input('Digite a temperatura em graus celsius:'))
convfah = ((cel*9/5)+32)
print('A conversão de {:.2f}°C é igual a {:.2f}°F'.format(cel, convfah)) |
c97f9a652604ecfda8fa6906940f66ef6ad7083f | RealDense/school | /fun/helloWorld.py | 200 | 3.671875 | 4 | import random
#name = raw_input("please type name: ")
#if(name =="Camille"):
# print ("Camille is the freakin best!")
#else:
# print ("hello World")
num1 = random.randint(1,10)
print(num1)
|
b0f9cb6596d4f841f133ba1ec06378f536569eb1 | RealDense/school | /6600_IntelligentSystems/hw1/logical_perceptrons.py | 4,290 | 3.59375 | 4 | #!/usr/bin/python
####################################################
# CS 5600/6600/7890: Assignment 1: Problems 1 & 2
# Riley Densley
# A01227345
#####################################################
import numpy as np
import math
class and_perceptron:
def __init__(self):
# your code here
self.w = [.5,.5]
self.b = -.5
pass
def output(self, x):
# your code here
y = 0
for i in range(len(x)):
y += (x[i]*self.w[i])
y += self.b
if(y > 0):
return 1
else:
return 0
pass
class or_perceptron:
def __init__(self):
# your code
self.w = [.5,.5]
self.b = 0
pass
def output(self, x):
# your code
y = 0
for i in range(len(x)):
y += (x[i]*self.w[i])
y += self.b
#print(y)
if(y > 0):
return 1
else:
return 0
pass
class not_perceptron:
def __init__(self):
# your code
self.w = [-1]
self.b = 1
pass
def output(self, x):
# your code
y = 0
for i in range(len(x)):
y += (x[i]*self.w[i])
y += self.b
if(y > 0):
return 1
else:
return 0
pass
class xor_perceptron:
def __init__(self):
# your code
self.w = [1,1]
self.b = 1
self.andp = and_perceptron()
self.orp = or_perceptron()
self.notp = not_perceptron()
pass
def output(self, x):
# your code
andResult = self.andp.output(x)
orResult = self.orp.output(x)
notResult = self.notp.output([andResult])
and2Result = self.andp.output([orResult,notResult])
return and2Result
#return self.andp.output([self.orp.output(x), self.notp.output([self.andp.output(x)])])
class xor_perceptron2:
def __init__(self):
# your code
self.w1 = [[-.5,-.5],[.5,.5]]
self.b1 = [1,0]
self.w2 = [.5,.5]
self.b2 = -.5
pass
def output(self, x):
# your code
step1 = [0,0]
y = 0
for j in range(len(step1)):
for i in range(len(x)):
step1[j] += (x[i]*self.w1[j][i])
step1[j] += self.b1[j]
step1[j] = math.ceil(step1[j])
for i in range(len(step1)):
y += (step1[i]*self.w2[i])
y += self.b2
#print(x, step1, y)
if(y > 0):
return [1]
else:
return [0]
pass
### ================ Unit Tests ====================
# let's define a few binary input arrays.
x00 = np.array([0, 0])
x01 = np.array([0, 1])
x10 = np.array([1, 0])
x11 = np.array([1, 1])
# let's test the and perceptron.
def unit_test_01():
andp = and_perceptron()
assert andp.output(x00) == 0
assert andp.output(x01) == 0
assert andp.output(x10) == 0
assert andp.output(x11) == 1
print ('all andp assertions passed...')
# let's test the or perceptron.
def unit_test_02():
orp = or_perceptron()
assert orp.output(x00) == 0
assert orp.output(x01) == 1
assert orp.output(x10) == 1
assert orp.output(x11) == 1
print ('all orp assertions passed...')
# let's test the not perceptron.
def unit_test_03():
notp = not_perceptron()
assert notp.output(np.array([0])) == 1
assert notp.output(np.array([1])) == 0
print ('all notp assertions passed...')
# let's test the 1st xor perceptron.
def unit_test_04():
xorp = xor_perceptron()
assert xorp.output(x00) == 0
assert xorp.output(x01) == 1
assert xorp.output(x10) == 1
assert xorp.output(x11) == 0
print ('all xorp assertions passed...')
# let's test the 2nd xor perceptron.
def unit_test_05():
xorp2 = xor_perceptron2()
# xorp2.output(x00)
# xorp2.output(x01)
# xorp2.output(x10)
# xorp2.output(x11)
assert xorp2.output(x00)[0] == 0
assert xorp2.output(x01)[0] == 1
assert xorp2.output(x10)[0] == 1
assert xorp2.output(x11)[0] == 0
print ('all xorp2 assertions passed...')
unit_test_01()
unit_test_02()
unit_test_03()
unit_test_04()
unit_test_05()
|
4e7a0bda2e931e40f9f012cb524c295f44beeca5 | ouril/python-Homework | /ykxb.py | 878 | 3.78125 | 4 | # функция считывает строку и решает уравнение заданного вида
exp = input("Введите уравнение в виде y = kx + b, где k и b - числа:\n")
x = float(input("Введите x:\n"))
k = ''
b = ''
kcount = 0
# цикл читает выражение и находит k и b
for i in exp:
# пропускаем у = , пробелы и +
if i == 'y' or i == '=' or i == ' ' or i == '+':
pass
# если мы нашли х то значит к найден, отмечаем это в kcount
elif i == 'x':
kcount += 1
else:
if kcount > 0:
b = str(b) + str(i)
else:
k = str(k) + str(i)
# если к не изменилось, то записать его как 1
if k == '':
k = 1
y = x * float(k) + float(b)
print(y) |
4f354744baf727b45cea6383918aa4cc0ac20c3e | danielmedinam03/Diplomado-Python2021 | /EjerciciosVarios/MenuFunciones.py | 10,437 | 3.8125 | 4 | i = 0
uLiquido = 0
volumenFinal=0
indice=0
def operacion(numero1, numero2, opcion):
if opcion == 1:
resultado = numero1+numero2
print("resultado: ", resultado)
elif opcion == 2:
resultado = numero1-numero2
print("resultado: ", resultado)
elif opcion == 3:
if numero2 == 0:
print("No se puede dividir en 0")
else:
resultado = numero1/numero2
print("resultado: ", resultado)
elif opcion == 4:
resultado = numero1*numero2
print("resultado: ", resultado)
def unidadDeMedidaVolumen(uLiquido,volumenFinal,opc):
volumenFinal=0
x=0
opc=int(opc)
uLiquido=int(uLiquido)
if opc == 1:
while x<1:
opcUnidadVolumen = int(input("""
1. Si desea convertir de Litros a Galones
2. Si desea convertir de Litros a Pintas
Opcion: """))
if opcUnidadVolumen >=1 and opcUnidadVolumen <=2:
if opcUnidadVolumen==1:
volumenFinal = uLiquido*2.6417
print(uLiquido, " litros equivalen a ", volumenFinal, " galones")
elif opcUnidadVolumen==2:
volumenFinal = uLiquido*2.11338
print(uLiquido, " litros equivalen a ", volumenFinal, " pintas")
else:
print()
x+=1
else:
print("ERROR!! Estas digitando una letra o un numero no correspondiente")
elif opc == 2:
while x<1:
opcUnidadVolumen = int(input("""
1. Si desea convertir de Galones a Litros
2. Si desea convertir de Galones a Pintas
Opcion: """))
if opcUnidadVolumen >=1 and opcUnidadVolumen <=2:
opcUnidadVolumen=int(opcUnidadVolumen)
if opcUnidadVolumen==1:
volumenFinal = 3.7854118*uLiquido
print(uLiquido, " galones equivalen a ", volumenFinal, " litros")
elif opcUnidadVolumen==2:
volumenFinal = uLiquido*8
print(uLiquido, " galones equivalen a ", volumenFinal, " pintas")
else:
print()
x+=1
else:
print("ERROR!! Digite un numero")
elif opc == 3:
while x<1:
opcUnidadVolumen = int(input("""
1. Si desea convertir de Pintas a Litros
2. Si desea convertir de Pintas a Galones
Opcion: """))
if opcUnidadVolumen >=1 and opcUnidadVolumen <=2:
if opcUnidadVolumen==1:
volumenFinal = 0.57*uLiquido
print(uLiquido, " pintas equivalen a ", volumenFinal, " litros")
elif opcUnidadVolumen==2:
volumenFinal = uLiquido*0.125
print(uLiquido, " pintas equivalen a ", volumenFinal, " galones")
else:
print()
x+=1
else:
print("ERROR!! Digite un numero")
def promedioSueldos(numPersonas,indice=0,acumuladorSueldo=0):
if numPersonas.isnumeric()==True:
numPersonas=int(numPersonas)
while indice<numPersonas:
sueldo=float(input("Ingrese sueldo: $"))
acumuladorSueldo+=sueldo
finalPromedio=acumuladorSueldo/numPersonas
indice+=1
print("Promedio de sueldos: $",finalPromedio)
else:
print("ERROR !!! Digite por favor un nuemero")
def unidadesDistancia(opcUnidadLongitud, longitud):
opcUnidadLongitud=int(opcUnidadLongitud)
longitud=int(longitud)
if opcUnidadLongitud ==1:
unidadFinal=longitud/100
print("Resultado: ",unidadFinal," metros")
elif opcUnidadLongitud==2:
unidadFinal=longitud/612371
print("Resultado: ",unidadFinal," Millas")
elif opcUnidadLongitud==3:
unidadFinal=longitud/100000
print("Resultado: ",unidadFinal," Kilometros")
elif opcUnidadLongitud==4:
unidadFinal=longitud*100
print("Resultado: ",unidadFinal," Centimetros")
elif opcUnidadLongitud==5:
unidadFinal=longitud/6213.71
print("Resultado: ",unidadFinal," Millas")
elif opcUnidadLongitud==6:
unidadFinal=longitud/1000
print("Resultado: ",unidadFinal," Kilometros")
elif opcUnidadLongitud==7:
unidadFinal=longitud*160934
print("Resultado: ",unidadFinal," centimetros")
elif opcUnidadLongitud==8:
unidadFinal=longitud*1609.34
print("Resultado: ",unidadFinal," metros")
elif opcUnidadLongitud==9:
unidadFinal=longitud*1.609
print("Resultado: ",unidadFinal," Kilometros")
elif opcUnidadLongitud==10:
unidadFinal=longitud*100000
print("Resultado: ",unidadFinal," Centimetros")
elif opcUnidadLongitud==11:
unidadFinal=longitud*1000
print("Resultado: ",unidadFinal," Metros")
elif opcUnidadLongitud==12:
unidadFinal=longitud/1.609
print("Resultado: ",unidadFinal," Millas")
"""
1cm = 0.01m
1cm = 0.00001km
1cm = 0.00000621371
1m = 100cm
1m = 0.001km
1m = 0.000621371 millas
1milla = 1.60934km
1milla = 1609.34m
1milla = 160934cm
1km = 0.621371 millas
1km = 1000m
1km = 100000cm
"""
#Menu de opciones
#While, para que se quede en el bucle hasta que el usuario digite una opción correcta
while i <=1:
opcMenu = (input("""Menú:
1. Calculadora
2. Unidad de medida Liquidos
3. Promedio Sueldos
4. Unidades de distancia
SI DESEAS SALIR DIGITA UN '*'
Opcion: """))
#Validacion que sea un numero
if opcMenu.isnumeric()==True:
#Convierte el numeor en un entero
opcMenu = int(opcMenu)
if opcMenu>=1 and opcMenu<=4 :
x=0
#Condicionales para realizar las diferentes opciones del menú
if opcMenu == 1:
while x <1:
numero1 = (input("Digite numero 1: "))
numero2 = (input("Digite numero 2: "))
opcion = (input("Si desea realizar una suma digite 1: \n" +
"Si desea realizar una resta digite 2: \n" +
"Si desea realizar una division digite 3: \n" +
"Si desea realizar una multiplicacion digite 4: \n" +
"Opcion: "))
#Validacion que sea un numero
if numero1.isnumeric() == True and numero2.isnumeric() == True and opcion.isnumeric() == True:
"""
numero1:int=numero1
numero2:int=numero2
opcion:int=opcion
"""
numero1=int(numero1)
numero2=int(numero2)
opcion=int(opcion)
if opcion>=1 and opcion<=4:
x+=1
operacion(numero1, numero2, opcion)
else:
print("ERROR !!! Estas digitando letras o un numero no correspondiente ")
#Condicion para realizar la unidad de Volumen
elif opcMenu == 2:
opc = (input("""Digite el numero segun corresponda:
Que unidad de medida desea convertir ?
1. Si desea convertir Litros
2. Si desea convertir Galones
3. Si desea convertir Pintas
Opción: """))
uLiquido = (
input("Volumen de liquido que desea convertir: "))
#Validacion que sea un numero
if opc.isnumeric()==True and uLiquido.isnumeric()==True:
unidadDeMedidaVolumen(uLiquido,volumenFinal,opc)
#Condicion para realizar el promedio de sueldos
elif opcMenu==3:
numPersonas=input("Ingrese el numero de personas: ")
if numPersonas.isnumeric()==True:
promedioSueldos(numPersonas)
#Condicion para realizar la conversion de medida del unidad de Longitud
elif opcMenu==4:
longitud=input("Longitud que desea convertir: ")
opcUnidadLongitud=(input("""
Digite el numero segun corresponda.
1. Si desea convertir de Centimetros a Metros
2. Si desea convertir de Centimetros a Millas
3. Si desea convertir de Centimetros a Kilometros
4. Si desea convertir de Metros a Centimetros
5. Si desea convertir de Metros a Millas
6. Si desea convertir de Metros a Kilometros
7. Si desea convertir de Millas a Centimetros
8. Si desea convertir de Millas a Metros
9. Si desea convertir de Millas a Kilometros
10. Si desea convertir de Kilometros a Centimetros
11. Si desea convertir de Kilometros a Metros
12. Si desea convertir de Kilometros a Millas
"""))
if longitud.isnumeric()==True and opcUnidadLongitud.isnumeric()==True:
unidadesDistancia(opcUnidadLongitud, longitud)
# Contador para salir del menú
i += 1
#Dar mensaje cuadno la opción no es correcta
else:
print("")
if opcMenu=="*":
break
|
fbe096ded2a9ff3e5aab6aea8cb0bda8b85ee4a9 | zitaxcy/pythoncoursera | /6.3.py | 123 | 3.625 | 4 | def CT(strings,characters)
count = 0
for character in strings:
if character = characters:
count = count + 1
return count |
15a7a744d88f9c4a79360b3fa80daeb92a8e3131 | 0xred/DeleteDuplicate | /SimpleDuplicate.py | 1,132 | 4 | 4 | import os
###########################################
# function to remove duplicate emails
def remove_duplicate():
# opens emails.txt in r mode as one long string and assigns to var
emails = open(iii, 'r').read()
# .split() removes excess whitespaces from str, return str as list
emails = emails.split()
# empty list to store non-duplicate e-mails
clean_list = []
# for loop to append non-duplicate emails to clean list
for email in emails:
if email not in clean_list:
clean_list.append(email)
return clean_list
# close emails.txt file
emails.close()
# assigns no_duplicate_emails.txt to variable below
os.system('cls' if os.name == 'nt' else 'clear')
iii = input(" || Enter Name Text File : ")
bbb = input(" || Save To : ")
no_duplicate_emails = open(bbb, 'w')
# function to convert clean_list 'list' elements in to strings
for email in remove_duplicate():
# .strip() method to remove commas
email = email.strip(',')
no_duplicate_emails.write(f"{email}\n")
# close no_duplicate_emails.txt file
no_duplicate_emails.close()
print(" || DONE ...!!")
quit()
|
a0aa4a59a44339f86763d469e59d695ff2d508e7 | raspoli/Self-Organized-Criticality-on-Spreading-of-Cooperative-Diseases | /Python Functions/network.py | 586 | 3.578125 | 4 | import networkx as nx
def make_adjmat_dict(List):
import numpy as np
AdjList = dict()
l1 = int(np.sqrt(len(List)))
j = 0
for neigh in (List):
neighbors = []
for i in List[neigh]:
neighbors.append(l1 * i[0] + i[1])
AdjList[j] = neighbors
j += 1
return AdjList
l = int(input('Enter lattice size\n'))
G = nx.grid_2d_graph(n=l,m=l,periodic=True)
L = nx.to_dict_of_lists(G)
AdjMat = make_adjmat_dict(L)
f = open("AdjList"+str(l)+"lattice.txt","w")
for v in AdjMat.values():
f.write(str(v)+"\n")
f.close()
|
f0e01d3a40149e29c69709346fb7ba673de0a4b5 | houpaul0817/AE401-2021s-paul | /test0925.py | 403 | 3.53125 | 4 | # from mcpi.minecraft import Minecraft
# import time
# mc = Minecraft.create()
# while 1+1==2:
# mc.setBlock(-236,77,238,46)
# time.sleep(0.1)
score = int(input("score: "))
if score >= 90:
print('Grade is: A')
elif score >= 80:
print('Grade is: B')
elif score >= 70:
print('Grade is: C')
elif score >= 60:
print('Grade is: D')
else:
print('Grade is: F')
|
7df64998ce5965ba3fabcbd54cedc6751ca413c8 | gustavovalverde/intro-programming-nano | /Python/Work Session 5/Loop 4.py | 2,343 | 4.46875 | 4 | # We now would like to summarize this data and make it more visually
# appealing.
# We want to go through count_list and print a table that shows
# the number and its corresponding count.
# The output should look like this neatly formatted table:
"""
number | occurrence
0 | 1
1 | 2
2 | 3
3 | 2
4 | 2
5 | 1
6 | 1
7 | 2
8 | 3
9 | 1
10 | 2
"""
# Here is our code we have written so far:
import random
# Create random list of integers using while loop --------------------
random_list = []
list_length = 20
while len(random_list) < list_length:
random_list.append(random.randint(0, 10))
# Aggregate the data -------------------------------------------------
count_list = [0] * 11
index = 0
while index < len(random_list):
number = random_list[index]
count_list[number] += 1
index += 1
# Write code here to summarize count_list and print a neatly formatted
# table that looks like this:
"""
number | occurrence
0 | 1
1 | 2
2 | 3
3 | 2
4 | 2
5 | 1
6 | 1
7 | 2
8 | 3
9 | 1
10 | 2
"""
print count_list
print sum(count_list)
# Hint: To print 10 blank spaces in a row, we can multiply a string
# by a number "n" to print this string n number of times:
print "number | ocurrence"
index = 0
while index <= 10:
if index < 10:
print " " * 5 + str(index) + " | " + str(count_list[index] * "*")
else:
print " " * 4 + str(index) + " | " + str(count_list[index] * "*")
index += 1
print ""
print "-----------------"
print "Another approach"
print "-----------------"
print ""
print "number | occurrence"
index = 0
num_len = len("number")
while index < len(count_list):
num_spaces = num_len - len(str(index))
print " " * num_spaces + str(index) + " | " + str(count_list[index])
index = index + 1
# BONUS!
# From your summarize code you just wrote, can you make the table even
# more visual by replacing the count with a string of asterisks that
# represent the count of a number. The table should look like:
"""
number | occurrence
0 | *
1 | **
2 | ***
3 | **
4 | **
5 | *
6 | *
7 | **
8 | ***
9 | *
10 | **
"""
# Congratulations! You just created a distribution table of a list
# of numbers! This is also known as a histogram
|
a9bed93ff1f778a466167b06cbc8afa902dabf9e | gustavovalverde/intro-programming-nano | /Python/Problem Solving/Calc_age_on_date.py | 2,173 | 4.21875 | 4 | # Given your birthday and the current date, calculate your age
# in days. Compensate for leap days. Assume that the birthday
# and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is
# 2 Jan 2012 you are 1 day old.
daysOfMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def isLeapYear(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 400 != 0:
return False
else:
return True
def isDateValid(y1, m1, d1, y2, m2, d2):
if y1 < y2:
return True
elif y1 == y2:
if m1 < m2:
return True
elif m1 == m2:
if d1 <= d2:
return True
else:
print "Please enter a valid initial date"
return False
else:
print "Please enter a valid initial date"
return False
def daysinYear(y1, y2):
days = 0
if y1 < y2:
for y in range(y1, y2):
if isLeapYear(y) is True:
days += 366
else:
days += 365
return days
def daysInMonth(m1, d1, m2, d2):
birthDate = sum(daysOfMonths[0: m1 - 1]) + d1
currentDate = sum(daysOfMonths[0: m2 - 1]) + d2
currentDays = currentDate - birthDate
return currentDays
def daysBetweenDates(y1, m1, d1, y2, m2, d2):
finalDays = daysinYear(y1, y2) + daysInMonth(m1, d1, m2, d2)
if ((isLeapYear(y1) is True) and (m1 >= 3)) or (
(isLeapYear(y2) is True) and (m2 >= 3)):
finalDays += 1
print "You are " + str(finalDays) + " days old"
return finalDays
def test():
test_cases = [((2012, 1, 1, 2012, 2, 28), 58),
((2012, 1, 1, 2012, 3, 1), 60),
((2011, 6, 30, 2012, 6, 30), 366),
((2011, 1, 1, 2012, 8, 8), 585),
((1900, 1, 1, 1999, 12, 31), 36523)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
print result
else:
print "Test case passed!"
test()
|
8dc56aa55548dc8396efee8198999e9cb2be735f | Isaac-Gathere/basic-calculator-python | /calc2.py | 3,321 | 3.65625 | 4 | from tkinter import*
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_Input.set(operator)
def ClrButton():
global operator
operator =""
text_Input.set("")
def equals():
global operator
total = str(eval(operator))
text_Input.set(total)
operator = ""
cal = Tk()
cal.title('SIMPLE CALCULATOR')
operator = ""
text_Input = StringVar()
# entry field
txtDisplay = Entry(cal,font = ("arial",20,"bold"),textvariable=text_Input, bd=30, insertwidth=4, bg="red",justify="right").grid(columnspan=4)
# row 1
btn7=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="7", bg='powder blue',command=lambda:btnClick(7)).grid(row=1,column=0)
btn8=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="8",bg='powder blue',command=lambda:btnClick(8)).grid(row=1,column=1)
btn9=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="9",bg='powder blue',command=lambda:btnClick(9)).grid(row=1,column=2)
btn_add=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="+",bg='powder blue',command=lambda:btnClick("+")).grid(row=1,column=3)
# row 2
btn4=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="4", bg='powder blue',command=lambda:btnClick(4)).grid(row=2,column=0)
btn5=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="5",bg='powder blue',command=lambda:btnClick(5)).grid(row=2,column=1)
btn6=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="6",bg='powder blue',command=lambda:btnClick(6)).grid(row=2,column=2)
btnsub=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="-",bg='powder blue',command=lambda:btnClick('-')).grid(row=2,column=3)
# row 3
btn1=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="1",bg='powder blue',command=lambda:btnClick(1)).grid(row=3,column=0)
btn2=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="2",bg='powder blue',command=lambda:btnClick(2)).grid(row=3,column=1)
btn3=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="3", bg='powder blue',command=lambda:btnClick(3)).grid(row=3,column=2)
btn_multiply=Button(cal,padx=16,pady=16,bd=8, fg='black'
,font=('arial',20,'bold'),text="*",bg='powder blue',command=lambda:btnClick("*")).grid(row=3,column=3)
#row 4
btn_zero=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="0", bg='powder blue',command=lambda:btnClick(0)).grid(row=4,column=0)
btn_clear=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="C",bg='powder blue',command=lambda:ClrButton()).grid(row=4,column=1)
btn_div=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="/",bg='powder blue',command=lambda:btnClick('/')).grid(row=4,column=2)
btn_equals=Button(cal,padx=16,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="=",bg='powder blue',command=lambda:equals()).grid(row=4,column=3)
# row 5
# press exit to quit
button_quit= Button(cal,padx=120,pady=16,bd=8, fg='black',font=('arial',20,'bold'),text="EXIT",bg='powder blue',command=cal.quit).grid(row=5,columnspan=4)
cal.mainloop()
|
b44302339187c200fa0fd172cfd3a21988353133 | jrvc/reSkilling | /nn_implementation/nn1.py | 3,829 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
FROM SCRATCH
Build a 3-layer neural network with 1 input layer, 1 hidden layer and 1 output layer.
The number of nodes in the input layer is 2; the dimensionality of our data.
The number of nodes in the output layer is 2; the number of classes we have.
The number of nodes in the hidden layer will vary.
MODELS:
1) tanh
FWD:
# INPUT layer activation values
a1 = X.copy()
# HIDDEN layer activation values
z2 = a1.dot(W1) + b1
a2 = np.tanh(z2)
# OUTPUT layer activation values
z3 = a2.dot(W2) + b2
a3 = softmax(z3) = np.exp(z3) / np.sum(exp_scores, axis=1, keepdims=True)
BackWD:
# output errors
delta3 = a3 - y
# hidden layer errors
delta2 = (delta3.dot( W2')) * (1 - tanh**2(z2)) = (delta3.dot( W2')) * (1 - a2.^2)
#derivatives
dW2 = a2' * delta3
db2 = delta3 # bias unit derivative wrt loss-func, hence change of 1
dW1 = a1' * delta2
db1 = delta2
2) sigmoid
FWD:
# INPUT layer activation values
a1 = X.copy()
# HIDDEN layer activation values
z2 = a1.dot(W1) + b1
a2 = utils_loc.sigmoid(z2)
# OUTPUT layer activation values
z3 = a2.dot(W2) + b2
a3 = utils_loc.sigmoid(z3)
@author: Raul Vazquez
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
import scipy.optimize as op
import os
os.chdir('C:\\Users\\Raul Vazquez\\Desktop\\reSkilling\\reSkilling\\nn_implementation')
import utils_loc
# Generate a dataset and plot it
np.random.seed(100)
X, y = datasets.make_moons(200, noise=0.25)
plt.scatter(X[:,0], X[:,1], s=40, c=y, cmap=plt.cm.Spectral)
m = len(X) # training set size
nn_input_dim = X.shape[1] # input layer dimensionality
nn_output_dim = 2 # output layer dimensionality
''' IMPORTANT PARAMETER: play with nn_hdim to see how the decision boundary changes'''
nn_hdim = 4 # hidden layer dmensionality (3 seems to be the optimal, 4 already overfitts the data)
# Gradient descent parameters
epsilon = 0.01 # learning rate for gradient descent
reg_lambda = 0.01 # regularization strength
# Initialize the parameters to random values. We need to learn these.
np.random.seed(10)
b1, W1, b2, W2 = utils_loc.random_init(nn_input_dim, nn_hdim, nn_output_dim)
cardW1 = nn_input_dim * nn_hdim
#cardW2 = nn_hdim * nn_output_dim
# generate an unrolled vector of parameters
initial_grad = np.append(np.append(b1, (W1).ravel()), np.append(b2, (W2).ravel() ) )
# minimize the desired function
'''
if 'jac' is a boolean and is True, 'fun' is assumed to return the gradient alog with the objective function.:
If False, the gradient will be estimated numerically
'''
def caller(x):
return utils_loc.nn_costFn_TanH(x, nn_input_dim, nn_hdim, nn_output_dim, X, y, reg_lambda)
result = op.minimize(fun = caller, x0 = initial_grad, jac = True)
# for fun one can choose nn_costFn_TanH OR nn_costFn_SIGMOID
result = op.minimize(fun = utils_loc.nn_costFn_TanH, x0 = initial_grad,
args = (nn_input_dim, nn_hdim, nn_output_dim, X, y, reg_lambda),
jac = True)
new_b1 = result.x[0:nn_hdim]
new_W1 = np.reshape( result.x[nn_hdim:(nn_hdim + cardW1)], (nn_input_dim, nn_hdim) )
new_b2 = result.x[(nn_hdim + cardW1):(nn_hdim + cardW1 + nn_output_dim)]
new_W2 = np.reshape( result.x[(nn_hdim + cardW1 + nn_output_dim):], (nn_hdim, nn_output_dim) )
utils_loc.plot_decision_boundary( (lambda x: utils_loc.predict(W1, b1, W2, b2, x)), X, y )
plt.title("Decision Boundary of initial Parameters")
utils_loc.plot_decision_boundary( (lambda x: utils_loc.predict(new_W1, new_b1, new_W2, new_b2, x) ), X,y)
plt.title("Decision Boundary for hidden layer size "+ str( nn_hdim))
|
1018f2da0c71c59aa9491bf5ab74ab734accb09d | adirickyk/course-python | /try_catch.py | 302 | 4.3125 | 4 | #create new exception
try:
Value = int(input("Type a number between 1 and 10 : "))
except ValueError:
print("You must type a number between 1 and 10")
else:
if(Value > 0) and (Value <= 10):
print("You typed value : ", Value)
else:
print("The value type is incorrect !")
|
9dda20b3902f6af459be06794b77330670b0fc4c | WalkingLight/Expert-System | /or_op.py | 2,657 | 3.6875 | 4 | import operator
import sys
class OrOp:
__data = []
__n = ['=', '<', '>']
__change = 1
def __init__(self, var_list):
for line in var_list:
if '|' in line or ('^' not in line and '+' not in line):
self.__data.append(line)
@staticmethod
def check_facts(char, facts):
for line in facts:
for c in line:
if c == char:
return True
return False
def operations(self, var_list, neg, facts):
equals = 0
num_t = 0
for char, value in sorted(neg.items(), key=operator.itemgetter(1)):
if neg[char] == 2:
equals = 1
if neg[char] == 0 or neg[char] == 3:
if var_list[char] is True:
num_t += 1
if neg[char] == 1 or neg[char] == 4:
if var_list[char] is False:
num_t += 1
if equals == 1 and num_t > 0:
if neg[char] == 3:
if self.check_facts(char, facts) is True:
if var_list[char] is False:
print "Error : Contradiction"
sys.exit(1)
var_list[char] = True
elif neg[char] == 4:
if self.check_facts(char, facts) is True:
if var_list[char] is True:
print "Error : Contradiction"
sys.exit(1)
var_list[char] = False
return var_list
def or_op(self, var_list, facts):
while self.__change == 1:
c = 0
for line in self.__data:
neg = {}
equals = 0
not_i = 0
for char in line:
if char == '=':
equals = 1
neg[char] = 2
if char == '!':
not_i = 1
if char.isalpha() and equals == 0:
if not_i == 0:
neg[char] = 0
elif not_i == 1:
neg[char] = 1
not_i = 0
if char.isalpha() and equals == 1:
if not_i == 0:
neg[char] = 3
elif not_i == 1:
neg[char] = 4
not_i = 0
var_list = self.operations(var_list, neg, facts)
if c == 0:
self.__change = 0
return var_list
|
17b0b49f8b26d7ddf8f5e7543df2b457494e985e | younga7/leap_year | /alex_young_hw2.py | 550 | 4.1875 | 4 | # CS362 HW2
# Alex Young
# 1/26/2021
# Run this file using python3 alex_young_hw2.py
# This program checks if a year is a leap year with error handling
c = 0
while c == 0:
try:
n = int (input('Enter year: '))
c = 1
except:
print ('Error, input is not valid, try again!')
if n % 4 == 0:
if n % 400 == 0:
print (n, 'is a leap year.')
else:
if n % 100 == 0:
print (n, 'is not a leap year.')
else:
print (n, 'is a leap year.')
else:
print (n, 'is not a leap year.') |
25a6b266cbcad69bc8428e4af1773d658e5b8e39 | arielmirra/python-sandbox | /src/sandbx.py | 2,037 | 3.953125 | 4 | # you will need to install matplotlib (pip install matplotlib)
import matplotlib.pyplot as plt
data = [['a', 1, 1], ['b', 3, 2]]
for item in data:
plt.plot(item, 'ro-')
plt.show()
from graph import Graph
def plot_graph(graph):
"""
graph has:
- Vertex list
- Edge list
"""
# [[0, 1], [1, 2]]
# 'a', 'b', 'c'
for i in range(0, len(graph.edges)):
pass
plt.show()
graph_demo = Graph()
graph_demo.add_vertex("Hay")
graph_demo.add_vertex("una")
graph_demo.add_vertex("serpiente")
graph_demo.add_vertex("en")
graph_demo.add_vertex("mi")
graph_demo.add_vertex("Bota")
graph_demo.add_edge(graph_demo.get_vertex_position("Hay"), graph_demo.get_vertex_position("una"))
graph_demo.add_edge(graph_demo.get_vertex_position("una"), graph_demo.get_vertex_position("serpiente"))
graph_demo.add_edge(graph_demo.get_vertex_position("serpiente"), graph_demo.get_vertex_position("en"))
graph_demo.add_edge(graph_demo.get_vertex_position("en"), graph_demo.get_vertex_position("mi"))
graph_demo.add_edge(graph_demo.get_vertex_position("mi"), graph_demo.get_vertex_position("Bota"))
plot_graph(graph_demo)
def get_adjacent(graph, index):
if graph.is_empty(): return []
for i in range(1, len(graph.vertexes)):
pass
# Especificar y escribir algoritmos para resolver los siguientes problemas.
# Considerar que el grafo es simple y puede tener lazos. Calcular O grande.
# a)Mostrar el grafo.
def show_graph(graph):
# beginner: prints, advanced: matplotlib B)
pass
# b)Retornar la cantidad de lazos de un grafo.
def tie_quantity(graph):
"""check for"""
for i in range(0, graph.size()):
pass
# c)Retornar un arreglo con los vértices que tienen lazos.
# d)Dado un vértice informar si es aislado.
# e)Calcular cuantos vértices son aislados.
# f)Retornar todos los vértices aislados.
# g)Dado un grafo debe retornar otro grafo sin lazos y sin vértices aislados.
# h)Calcular y mostrar la matriz de adyacencia.
# i)Calcular y mostrar la matriz de incidencia.
|
5a812ff48b2fa61605d10ebc0538feb11906d4c4 | burrizozo/aoc2020 | /day6.sln.py | 778 | 3.5625 | 4 | file1 = open('day6.input.txt', 'r')
lines = file1.readlines()
def part1():
ans = 0
questionset = set()
for line in lines:
if line != "\n":
for question in line.rstrip():
questionset.add(question)
else:
ans += len(questionset)
questionset = set()
ans += len(questionset)
print(ans)
def part2():
ans = 0
questionset = {}
headcount = 0
for line in lines:
if line != "\n":
headcount += 1
for question in line.rstrip():
if question not in questionset:
questionset[question] = 1
else:
questionset[question] += 1
else:
ans += sum(x == headcount for x in questionset.values())
questionset = {}
headcount = 0
ans += sum(x == headcount for x in questionset.values())
print(ans)
part2() |
7d4785c275e7b8786a52fa8ceb1673399da57ac4 | Patroon-tab/QOG | /Assistance_Files/Image_Resizing.py | 241 | 3.515625 | 4 | from PIL import Image, ImageTk
def resize(input,output,x,y):
img = Image.open(input)
img = img.resize((x, y))
img.save(output)
def main():
resize("pic.png", "pic2.png", 208, 183)
if __name__ == "__main__":
main()
|
8507c80a2044c46f0789317abad550d142deaa35 | toanqz/ktpm2013 | /triangle/test.py | 4,256 | 3.5625 | 4 | import unittest
import math
import triangle
class test(unittest.TestCase):
#test tam giac deu
def test_triangleDeu1(self):
self.assertEquals(triangle.detect_triangle(1.0, 1.0, 1.0), "Tam giac deu")
def test_triangleDeu2(self):
self.assertEquals(triangle.detect_triangle(2**32.0-1, 2**32.0-1, 2**32.0-1), "Tam giac deu")
def test_triangleDeu3(self):
self.assertEquals(triangle.detect_triangle(0.00000000001, 0.00000000001, 0.00000000001), "Tam giac deu")
#test tam giac vuong can
def test_triangleVuongCan(self):
self.assertEquals(triangle.detect_triangle(1.0, 1.0, math.sqrt(2.0)), "Tam giac vuong can")
def test_triangleVuongCan2(self):
self.assertEquals(triangle.detect_triangle(1.0, math.sqrt(2.0), 1.0), "Tam giac vuong can")
def test_triangleVuongCan3(self):
self.assertEquals(triangle.detect_triangle (math.sqrt(2.0), 1.0, 1.0), "Tam giac vuong can")
#test tam giac vuong
def test_triangleVuong(self):
self.assertEquals(triangle.detect_triangle(5.0, 3.0, 4.0), "Tam giac vuong")
def test_triangleVuong2(self):
self.assertEquals(triangle.detect_triangle(4.0, 5.0, 3.0), "Tam giac vuong")
def test_triangleVuong3(self):
self.assertEquals(triangle.detect_triangle(3.0, 4.0, 5.0), "Tam giac vuong")
def test_triangleVuong4(self):
self.assertEquals(triangle.detect_triangle(math.sqrt(2.0), math.sqrt(1.0), math.sqrt(3.0)), "Tam giac vuong")
#test tam giac can
def test_triangleCan(self):
self.assertEquals(triangle.detect_triangle(1.0, 3.0, 3.0), "Tam giac can")
def test_triangleCan2(self):
self.assertEquals(triangle.detect_triangle(3.0, 1.0, 3.0), "Tam giac can")
def test_triangleCan3(self):
self.assertEquals(triangle.detect_triangle(3.0, 3.0, 1.0), "Tam giac can")
def test_triangleCan4(self):
self.assertEquals(triangle.detect_triangle(2**31.0, 2**31.0, 0.0001), "Tam giac can")
def test_triangleCan5(self):
self.assertEquals(triangle.detect_triangle(2**32.0-1, 1.0, 2**32.0-1), "Tam giac can")
#test tam giac thuong
def test_triangleThuong(self):
self.assertEquals(triangle.detect_triangle(2.0, 4.0, 3.0), "Tam giac thuong")
def test_triangleThuong2(self):
self.assertEquals(triangle.detect_triangle(2**32.0-1, 4.0, 2**32.0-2), "Tam giac thuong")
def test_triangleThuong3(self):
self.assertEquals(triangle.detect_triangle(0.0001, 0.00012, 0.00011), "Tam giac thuong")
def test_triangleThuong4(self):
self.assertEquals(triangle.detect_triangle(2**32.0-1, 2**32.0-1.1, 2**32.0-2), "Tam giac thuong")
#test khong phai tam giac
def test_KhongPhaitriangle(self):
self.assertEquals(triangle.detect_triangle(1.0, 1.0, 3.0), "Khong thoa man tam giac")
def test_KhongPhaitriangle2(self):
self.assertEquals(triangle.detect_triangle(1.0, 3.0, 1.0), "Khong thoa man tam giac")
def test_KhongPhaitriangle3(self):
self.assertEquals(triangle.detect_triangle(3.0, 1.0, 1.0), "Khong thoa man tam giac")
def test_KhongPhaitriangle4(self):
self.assertEquals(triangle.detect_triangle(2**32.0-1, 1.0, 3.0), "Khong thoa man tam giac")
#test ngoai mien gia tri
def test_MienGiaTri(self):
self.assertEquals(triangle.detect_triangle(-1.0, 1.0, 1.0), "Khong thuoc mien gia tri")
def test_MienGiaTri2(self):
self.assertEquals(triangle.detect_triangle(-1.0, -1.0, -1.0), "Khong thuoc mien gia tri")
def test_MienGiaTri3(self):
self.assertEquals(triangle.detect_triangle(2**32.0, 1.0, -1.0), "Khong thuoc mien gia tri")
def test_MienGiaTri4(self):
self.assertEquals(triangle.detect_triangle(2**32.0, 2**32.0, 2**32.0), "Khong thuoc mien gia tri")
#test sai kieu gia tri dau vao Float
def test_KieuGiaTri(self):
self.assertEquals(triangle.detect_triangle('a', 'b', 'c'), "Kieu du lieu sai")
def test_KieuGiaTri2(self):
self.assertEquals(triangle.detect_triangle('a', 'b', 5), "Kieu du lieu sai")
def test_KieuGiaTri3(self):
self.assertEquals(triangle.detect_triangle(1.0, 'b', 'c'), "Kieu du lieu sai")
if __name__ == '__main__':
unittest.main()
|
e09986bf28f9a3da5e9156b14da0e624914afbd7 | yellingviv/practice_makes_perfect | /are_they_close.py | 840 | 3.71875 | 4 | # challenge: https://gist.github.com/seemaullal/eab0853325b70aa41d211cdf7259ddc9
def check_similarity(word1, word2):
"""check if word1 and word2 are only one character different"""
similar = False
counter = 0
range_len = 0
if len(word1) - len(word2) not in (-1, 1, 0):
return similar
elif len(word1) > len(word2):
range_len = len(word2)
counter += 1
elif len(word1) < len(word2):
range_len = len(word1)
counter += 1
elif len(word1) == len(word2):
range_len = len(word1)
for i in range(range_len):
if word1[i] != word2[i]:
if counter >= 1:
return similar
counter += 1
similar = True
return similar
# test cases I used:
# nifty, nifto
# nifty, nofto
# howdy, hellothere
# asks, ask
# asta, ask
|
e8368e5d17e8682b1f8d59ab9466995584747627 | castacu0/codewars_db | /15_7kyu_Jaden Casing Strings.py | 1,069 | 4.21875 | 4 | from string import capwords
"""
Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word. For simplicity, you'll have to capitalize each word, check out how contractions are expected to be in the example below.
Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.
Example:
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
def to_jaden_case(string):
# ...
"""
def to_jaden_case(string):
return print(" ".join(i.capitalize() for i in string.split()))
# split() makes a list. any whitespace is by default
# join makes a str again and takes an iterable
# Best practices
# from string import capwords
def to_jaden_case(string):
return string.capwords(string)
to_jaden_case("kou liu d'wf")
|
e8467f6d82e44b3c9d21456ec71255cbd64a3909 | JGracia98/python_game | /python_game.py | 5,505 | 4 | 4 | ## This is based off of Happy Death Day.
## You have to try and solve you're own death and find out who killed you.
## Goodluck
## Scene
from textwrap import dedent
from sys import exit
class Scene(object):
def enter(self):
exit(1)
class Bedroom(Scene):
def enter(self):
print(dedent("""
You wake up after being killed by someone who has been stalking your every move. It has happened time after time again, and now you're fed up with it. Now is the time to solve you're own murder and kill this son of a... You know what I meant to say. Make the right choices, don't get killed again or you will wake up again re-living everything over again. Have fun, goodluck, and HAPPY DEATH DAY!
*************************************************************
The last thing you remember was going home from a frat party and decided it was a WONDERFUL idea to walk through the very cloudy park. Someone with a baby-face mask stabs you in the chest a steak knife. You finally wake up scared for your safety. Only way to stop this loop is to find out who keeps killing you, and kill them. With this informaton at hand, what do you want to do?
1. Walk to the kitchen and grab the sharp knife from the sink for protection.
2. Go to the living room and call your friends.
"""))
insert = input(">> ")
if insert == '1':
print(dedent("""
Not a bad choice. Just hope you got some sick skills with that thing unless you're dunzo.
"""))
ParkScene.enter(self)
elif insert == '2':
print(dedent("""
I mean it's not a bad idea but, it wasn't the correct thing to do. You're power got cut off when you tried to call your friends. It's very dark and you can't see a thing. Footsteps start to come closer and closer. The maniac comes from behind you and slits your throat and you bleed to death.
"""))
return 'Bedroom'
else:
print(dedent("""
Not in choices!
"""))
return 'Bedroom'
class ParkScene(Scene):
def enter(self):
print(dedent("""
This should be familiar... I mean you did die here before so be careful.
***************************************************************
You go back to the park and take the same path you took the night you got murdered. As you get closer to the exact location to where you got stabbed, you see the baby-face mask on the floor near the trash bin and a trail of muddy footsteps towards the statue in the middle of the park.
1. Pick up the mask and follow the muddy trail
2. Leave the park and run home
3. Yell for help (for some reason.)
"""))
insert = input(">> ")
if insert == '1':
print(dedent("""
As you get closer to the Statue, you see some of the bushes moving. Is it a squirrel? Raccoon? Your Aunt Nancy? Nah, it was just a raccoon don't be scared. After realizing there is nothing else to worry about, you head over to the apartment building across the street in hope to find out anymore clues.
"""))
ApptBuilding.enter(self)
elif insert == '2':
print(dedent("""
As you get closer to the exit, the Maniac comes out from hiding behind a tree and trips you then suffocates you until you die.
"""))
return 'Bedroom'
elif insert == '3':
print(dedent("""
After yelling for 30 seconds the Maniac shoots you in the mouth with a silence pistol to shut you up.
"""))
return 'Bedroom'
else:
print(dedent("""
Not in Choices. Now start over.
"""))
return 'Bedroom'
class ApptBuilding(Scene):
def enter(self):
print(dedent("""
As you approach the apartment building, you see a note on the glass door. It says, "Building will be under construction from 02/11 - 02/23 from 9:00am-8:30pm." It's 02/13 today and the time is 5:00pm. You see the work vehicles in the area, but no construction noises coming from within the building? You decide to enter and see two apartment rooms slighly open, A3 & B2. The building has been evacuated due to the construction, why are people still in their rooms?
1. Go through B2
2. Go through A3
"""))
insert = input(">> ")
if insert == '2':
print(dedent("""
The tv is on, sink is on, and the shower is running. You start to head into the bathroom and see a trail of blood leading into it. You open the door and see the baby-face mask Maniac washing his bloody hands. You grab your steak knife and stab him in the neck. Once he bleeds to death you take off his mask, it was one of your friends from the frat party you went to.
"""))
Solved.enter(self)
elif insert == '1':
print(dedent("""
As you get closer to the door, you can see the room is really misty and hard to see through. YOu start to enter the room and trip over claymore mine and explode into pieces.
"""))
return 'Bedroom'
class Solved(object):
def enter(self):
print(dedent("""
You solved it congrats!
"""))
Bedroom.enter(Scene)
|
3e942eb151c8963b5a79e62b66c52ea98ae60fc0 | bayuwira/KNN-Classification-from-scratch | /KNeighborsClassifier.py | 1,117 | 3.5625 | 4 | import numpy as np
#compute the euclidean distance between two point of data'
def euclidean_distance(x1, x2):
return np.sqrt(np.sum((x1 - x2) ** 2))
class KNeighborsClassifier:
def __init__(self, num_neighbors=7):
self.num_neighbors = num_neighbors
def fit(self, X, y):
self.X_train = X
self.y_train = y
def predict(self, X):
y_pred = [self.compute_knn(x) for x in X]
return np.array(y_pred)
def compute_knn(self, x):
distances = [euclidean_distance(x, x_train) for x_train in self.X_train]
# Sort by distance and return indices of the first k neighbors
k_idx = np.argsort(distances)[: self.num_neighbors]
# Extract the labels of the k nearest neighbor training samples
k_neighbor_labels = [self.y_train[i] for i in k_idx]
# return the most common class label
temp = 0
what_max = 0
for data in k_neighbor_labels:
if (temp < k_neighbor_labels.count(data)):
temp = k_neighbor_labels.count(data)
what_max = data
return what_max |
bdcf5f38df876124dac89805f4ac6b695dca3d14 | jeffreyziegler/PythonClass-2015 | /Class3-ErrorTesting/ordinalTest.py | 851 | 3.765625 | 4 | import unittest
import lab3
class ordinalTest(unittest.TestCase):
def test_one(self): #run test to distinguish between 1st and 11th
self.assertEqual('11th',lab3.ordinal(11))
self.assertEqual('1st',lab3.ordinal(1))
def test_teens(self): #run test to check ordinals of teens
self.assertEqual('13th',lab3.ordinal(13))
self.assertEqual('18th',lab3.ordinal(18))
def test_largeNumber(self): #run test to check large numbers with multiple digits
self.assertEqual('2013th',lab3.ordinal(2013))
self.assertEqual('2001st',lab3.ordinal(2001))
def test_typeError(self): #check type errors
self.assertEqual("Enter an integer.",lab3.ordinal('b')) #test string
self.assertEqual("Enter an integer.",lab3.ordinal('12.7')) #test float
if __name__ == '__main__': #Add this if you want to run the test with this script.
unittest.main() |
eea36189021cd2a623499e0b66692b637ddc61db | jeffreyziegler/PythonClass-2015 | /Class6-SortSearch/hw4/JZhw4.py | 609 | 4.03125 | 4 | # insertion sort
def insertion_sort(item_list):
for i in range(1, len(item_list)):
k = item_list[i]
j = i - 1
while (j >= 0) and (item_list[j] > k):
item_list[j+1] = item_list[j]
j = j - 1
item_list[j+1] = k
return insertion_sort
# selection sort
def selection_sort(item_list):
for spot in range(len(item_list)-1,0,-1):
positionOfMax=0
for location in range(1, spot + 1):
if item_list[location] > item_list[positionOfMax]:
positionOfMax = location
temp = item_list[spot]
item_list[spot] = item_list[positionOfMax]
item_list[positionOfMax] = temp
return selection_sort |
9940f02410122ddc6d0a9394479576fa0fb1a4fb | marizmelo/udacity | /CS262/lesson3/mapdef.py | 267 | 4.125 | 4 | def mysquare(x): return x * x
print map( mysquare, [1, 2, 3, 4, 5])
print map( lambda(x): x * x, [1, 2, 3, 4, 5]) # this use of lambda is sometimes called anonymous function
print [len(x) for x in ["hello", "my", "friends"]]
print [x * x for x in [1, 2, 3, 4, 5]] |
c287b5f834c313060f4ad2004de99619a66b123a | marizmelo/udacity | /CS262/lesson3/small_words.py | 157 | 4.1875 | 4 | def small_words(words):
for word in words:
if len(word) <= 3:
yield word
print [w for w in small_words(["The", "quick", "brown", "fox"])]
|
37857877fae4554279f5fe54ba39cbacc9d8e7a7 | jatingandhi32/Analysis-and-Design-of-Algorithms | /ADA/topologicalSort.py | 762 | 3.828125 | 4 | import numpy as np
def topological(adj,indegree,n):
"""for i in range(n):
for j in range(n):
indegree[i] +=adj[j][i]"""
length =n
while length:
for i in range(n):
if indegree[i]==0:
print(i+1,end=" ")
indegree[i]=-1
for j in range(n):
if adj[i][j]==1:
indegree[j]=indegree[j]-1
length -=1
row = int(input("Enter the rows of graph\n"))
print("Enter the adjacency matrix\n")
dependency = list(map(int,input().split()))
dependency = np.array(dependency).reshape(len(dependency)//2,2)
indegree=[0]*row
adjacency =np.zeros((row,row))
row2 = len(dependency)
for i in dependency:
if i[1]==0:
pass
else:
indegree[i[0]-1] +=1
adjacency[i[1]-1][i[0]-1] = 1
print(dependency)
print()
topological(adjacency,indegree,row)
|
c02aeab828af37abdfbf341362fe2037ea58b382 | jatingandhi32/Analysis-and-Design-of-Algorithms | /ADA/Sudoku.py | 2,141 | 3.671875 | 4 | import numpy as np
def display(arr):
for i in range(9):
for j in range(9):
print (arr[i][j],end = " ")
print ()
def unassigned(arr,l):
for row in range(9):
for col in range(9):
if(arr[row][col]==0):
l[0]=row
l[1]=col
return True
return False
def used_row(arr,row,num):
for i in range(9):
if(arr[row][i] == num):
return True
return False
def used_col(arr,col,num):
for i in range(9):
if(arr[i][col] == num):
return True
return False
def used_box(arr,row,col,num):
for i in range(3):
for j in range(3):
if(arr[i+row][j+col] == num):
return True
return False
def isSafe(arr,row,col,num):
return not used_row(arr,row,num) and not used_col(arr,col,num) and not used_box(arr,row - row%3,col - col%3,num)
def sudoku(arr):
l=[0,0]
if(not unassigned(arr,l)):
return True
row=l[0]
col=l[1]
for num in range(1,10):
if(isSafe(arr,row,col,num)):
arr[row][col]=num
if(sudoku(arr)):
return True
arr[row][col] = 0
return False
n = 9
m = 9
print(n,m)
matrix = []
for i in range(0,m):
matrix.append([])
for j in range(0,n):
matrix[i].append(0)
matrix[i][j] = int(input())
print matrix
if(sudoku(matrix)):
display(matrix)
else:
print ("No solution exists")
"""
Output:
[[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]]
3 1 6 5 7 8 4 9 2
5 2 9 1 3 4 7 6 8
4 8 7 6 2 9 5 3 1
2 6 3 4 1 5 9 8 7
9 7 4 8 6 3 1 2 5
8 5 1 7 9 2 6 4 3
1 3 8 9 4 7 2 5 6
6 9 2 3 5 1 8 7 4
7 4 5 2 8 6 3 1 9
"""
|
1f2dbc00c9e3b42288863fa939ccccc913bff71a | sacrrie/reviewPractices | /6515/fixedPoint.py | 504 | 3.765625 | 4 | #find the item value equals to index in log n time
#first let's implement the binary search algo
#done
def fixedPoint(arr):
#index=list(range(len(arr)))
i=0
while len(arr)>1:
j=len(arr)//2
i+=j
if arr[j]==i:
return(True)
elif arr[j]<i:
arr=arr[j:]
#else arr[i]>target:
else:
arr=arr[:j]
i-=len(arr)
if arr[0]==i:
return(True)
return(False)
a=[-12,-3,1,3,9]
print(fixedPoint(a))
|
cde62f98c13afd6ad02a93f7e13e40980d9a54c7 | sacrrie/reviewPractices | /CC150/Python solutions/5-0.py | 1,272 | 4.0625 | 4 | #bit manipulation practice file
#a simple bit manipulation function
'''
import bitstring
print(int('111001', 2))
def repeated_arithmetic_right_shift(base,time):
answer=base
for i in range(time):
answer=base>>1
return(answer)
a=repeated_arithmetic_right_shift(-75,1)
print(a)
def repeated_logical_right_shift(base,time):
answer=bitstring.BitArray(int=base,length=32)
print(answer.int)
for i in range(time):
answer=answer >> 1
return(answer)
b=repeated_logical_right_shift(5,1)
print(b.int)
def get_bit(num, index):
left=num
right=1 << index
#code below won't work , the right most 1 would disappear
#right=1 >> index
return((left & right) != 0)
print(get_bit(4,2))
def set_bit(num,index):
left=num
right=1 << index
return(left | right)
print(set_bit(4,1))
def clear_bit(num,index):
left=num
right=~(1 << index)
return(left & right)
print(clear_bit(7,1))
'''
#clear bit from most significant to i index inclusively
def left_clear_bit(num,index):
left=num
right=(1 << index)-1
return(left & right)
print(left_clear_bit(7,1))
#the other way
def right_clear_bit(num,index):
left=num
right=(-1 << index+1)
return(left & right)
print(right_clear_bit(7,1))
|
75bda027beb93483617dd1068f2a2e44dcb7e49b | mingcgg/mars | /com/bak/mnist_1.0_softmax.py | 5,811 | 3.515625 | 4 | import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data as mnist_data
from matplotlib import pyplot as plt
from matplotlib import animation
mnist = mnist_data.read_data_sets("data", one_hot=True, reshape=False, validation_size=0)
#属于分类问题 全连接网络:每一个像素点(特征)都与标准值连接28*28*10
# 训练方式是,取一批数据整体训练全部的权值
#label
#step 1 create model
X = tf.placeholder(tf.float32, [None, 28, 28, 1]) # [样本数量, 长,宽,通道数]
Y_ = tf.placeholder(tf.float32,[None, 10]) # [样本数量, 分类种数类别数] 存放实际值,用于与预测值对比
XX = tf.reshape(X, [-1, 784]) # 模型形状转换 行,列[样本数量, 28*28=784列] 每一列的某一个表示一个像素点
#W = tf.Variable(tf.zeros([784, 10]))
# 尽量不要全0
W = tf.Variable(tf.zeros([784, 10]))#tf.ones([784, 10]) np.random.normal(size=(784, 10)).astype(np.float32)
b = tf.Variable(tf.zeros([10]))
#soft max 不会改变形状, 在最低维度上计算其总占比为100%的每个分量的占比 [[0.1, 0.1...0.7,0.001], [], []]
# 将所有像素点值与权值矩阵相乘,转换为概率输出,softmax:1、将总值为100%,2、突出数值相对较大的那个位置,这个之前写过代码进行验证的
Y = tf.nn.softmax(tf.matmul(XX, W) + b) #[-1, 748] * [784, 10] = [-1, 10]
cross_entropy = -tf.reduce_mean(Y_ * tf.log(Y)) * 1000
# https://zh.numberempire.com/graphingcalculator.php 图像
# 这是整个程序最为关键的一句 log自然对数函数(自然对数以常数e为底数的对数 e≈2.71828),x(0 - 1 此x(Y)处为softmax的计算结果0到1) -> y(0 到 负无穷) 每一张图片贡献自已单独的熵
# 与实际值Y_相乘, [0 0 0 1 0 0 ……]自己为1的位保留放大,最后得到一个整体的交叉熵
# 20181026 明
# 1、tf.log(Y) 计算后的结果的形状依然是 [-1, 10] log为此模型的激函数
# 2、tf.log(Y) 计算后的结果 为0 到 负无穷[[-0.01, -0.2, -0.4, -0.3...-0.06], [], []...[]]
# 3、Y_ * tf.log(Y) [None, 10] * [-1 , 10] = [-1, 10] 相乘为普通相乘,不是矩阵相关(这里特别注意一下) ,形状不变(写段代码验证一下)
# 4、每次相乘的时候,10个值中只有一个为1,其它位置都是0,即为1的位置为相乘后会保留下来,从log函数曲线上可以看来,如果概率分布值越大得到的y值就越小(交叉熵就小,就越靠近正确答案)
# 如果此位置的概率分布值很小,就会得到一个负的很大的y值(交叉熵就大,就越偏离了正确答案),下次权值就会往交叉熵小的方向调整(按照设置的学习率调整)
# 5、cross_entropy是一个损失函数数值(tf.reduce_mean 结果是一个值)
allweights = tf.reshape(W, [-1])
train_step = tf.train.GradientDescentOptimizer(0.005).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
def addToPlt(array, fig, idx):
array = np.array(array, dtype=float)
array = array.reshape(28, 28)
ax = fig.add_subplot(idx)
ax.imshow(array, cmap='jet') #, cmap="inferno" magma
fig = plt.figure()
for i in range(6000):
batch_x, batch_y = mnist.train.next_batch(100) # 每次取一批样本,用模型运算,反向传播,更新权值和偏置值 ,全连接网络 共7840个权值
sess.run(train_step, feed_dict={X:batch_x, Y_:batch_y})#
c = sess.run(cross_entropy, feed_dict={X:batch_x, Y_:batch_y})
#W_OUT = sess.run(W, feed_dict={X:batch_x, Y_:batch_y})
#allweights_value = sess.run(allweights, feed_dict={X:batch_x, Y_:batch_y})
if i % 2000 == 0:
BB = sess.run(b, feed_dict={X:batch_x, Y_:batch_y})
WW = sess.run(W, feed_dict={X:batch_x, Y_:batch_y})
print(WW.shape)
temp0 = [];
temp1 = [];
temp2 = [];
temp3 = [];
temp4 = [];
temp5 = [];
temp6 = [];
temp7 = [];
temp8 = [];
temp9 = [];
for k, v in enumerate(WW):
temp0.append(v[0]);
temp1.append(v[1]);
temp2.append(v[2]);
temp3.append(v[3]);
temp4.append(v[4]);
temp5.append(v[5]);
temp6.append(v[6]);
temp7.append(v[7]);
temp8.append(v[8]);
temp9.append(v[9]);
#print(temp) 参数349的意思是:将画布分割成3行4列,图像画在从左到右从上到下的第9块,如下图
addToPlt(temp0, fig, 251)
addToPlt(temp1, fig, 252)
addToPlt(temp2, fig, 253)
addToPlt(temp3, fig, 254)
addToPlt(temp4, fig, 255)
addToPlt(temp5, fig, 256)
addToPlt(temp6, fig, 257)
addToPlt(temp7, fig, 258)
addToPlt(temp8, fig, 259)
temp9 = np.array(temp9)
temp9 = temp9.reshape(28, 28)
ax = fig.add_subplot(2,5,10)
ax.imshow(temp9, cmap='jet') #, cmap="inferno" magma
#ax = fig.add_subplot(222)
#ax.imshow(temp2, cmap='jet') #, cmap="inferno" magma
#plt.colorbar()
plt.show()
accuracy_out = sess.run(accuracy, feed_dict={X:batch_x, Y_:batch_y})
print("cross entropy:", c)
print("test accuracy %g", accuracy_out)
saver.save(sess, "testdata/model.ckpt")
#for j in allweights_value:
# if(j != 0):
# print(i,j)
# |
3d6870ba3a835e3ca8426695bf5762d934341486 | Shmuelnaaman/NYC_Subway_Rainy_days | /fix_turnstile_data.py | 1,860 | 3.828125 | 4 | import csv
def fix_turnstile_data(filenames):
'''
Filenames is a list of MTA Subway turnstile text files.
There are numerous data points included in each row of the
a MTA Subway turnstile text file.
Here I write a function that will update each row in the text
file so there is only one entry per row. A few examples below:
A002,R051,02-00-00,05-28-11,00:00:00,REGULAR,003178521,001100739
A002,R051,02-00-00,05-28-11,04:00:00,REGULAR,003178541,001100746
A002,R051,02-00-00,05-28-11,08:00:00,REGULAR,003178559,001100775
The updated data is than writen in to a different text file in the format of
"updated_" + filename.
For example:
1) if you read in a text file called "turnstile_110521.txt"
2) you should write the updated data to "updated_turnstile_110521.txt"
The order of the fields preserved.
Sample input file:
https://www.dropbox.com/s/mpin5zv4hgrx244/turnstile_110528.txt
Sample updated file:
https://www.dropbox.com/s/074xbgio4c39b7h/solution_turnstile_110528.txt
To run this function type
fix_turnstile_data({'turnstile_110528.txt'})
'''
for name in filenames:
print name
with open(name, 'rb') as f:
reader = csv.reader(f)
for row in reader:
header = row[0:3]
rowclipped = row[len(header):]
totallist = []
with open("updated_" + name, 'ab') as fp:
writer = csv.writer(fp)
x = 0
for i in range (len(rowclipped)/5):
totallist = header + rowclipped[x:(x+5)]
writer .writerow(totallist)
x = x+5
|
3f672028ddf03e5d74d21b000c8476a9df8f5c94 | cameronp98/python-brainfuck | /brainfuck/program.py | 2,515 | 3.96875 | 4 | """
Model the state of a brainfuck program and
act upon it using brainfuck operations.
"""
class ExecutionError(Exception):
"""
An error during program execution.
"""
pass
class Program:
"""Represents the execution state of a brainfuck program."""
def __init__(self, num_cells):
"""
Create a new program with a given number of cells
"""
self.cells = [0] * num_cells
self.pointer = 0
@property
def cell(self):
return self.cells[self.pointer]
@cell.setter
def cell(self, value):
self.cells[self.pointer] = value
def modify_pointer(self, amount):
"""
Change the pointer by `amount` and wrap around the
program's cell count.
"""
self.pointer = (self.pointer + amount) % len(self.cells)
def execute_one(self, op):
"""
Execute a given operation
"""
if isinstance(op, list):
# If the cell at the pointer is non-zero, execute the
# operations inside the loop.
# If the cell at the pointer is still non-zero, repeat.
while self.cell != 0:
self.execute_many(op)
if self.cell == 0:
break
elif op == "+":
# increment the cell at the pointer
self.cell += 1
elif op == "-":
# decrement the cell at the pointer
self.cell -= 1
elif op == ">":
# move the pointer one cell to the right
self.modify_pointer(+1)
elif op == "<":
# move the pointer one cell to the left
self.modify_pointer(-1)
elif op == ".":
# output the cell at the pointer
print(self.cell)
elif op == ",":
# input the cell at the pointer as either a number,
# or a single character
value = input(f"Input for cell {self.pointer}: ")
if value.isnumeric():
self.cell = int(value)
elif len(value) == 1:
self.cell = ord(value)
else:
raise ExecutionError(
"Input must be a number or a single character")
else:
ExecutionError(f"Unknown operation: {op}")
def execute_many(self, ops):
"""
Execute a sequence of operations.
"""
for op in ops:
self.execute_one(op)
|
89a7a9009cea475f97fbe0daf1c5eb350aa4b014 | guoxiaowhu/lenstronomy | /lenstronomy/LensModel/Profiles/hernquist.py | 6,787 | 3.53125 | 4 | import numpy as np
class Hernquist(object):
"""
class to compute the Hernquist 1990 model
"""
_diff = 0.00000001
_s = 0.00001
param_names = ['sigma0', 'Rs', 'center_x', 'center_y']
lower_limit_default = {'sigma0': 0, 'Rs': 0, 'center_x': -100, 'center_y': -100}
upper_limit_default = {'sigma0': 100, 'Rs': 100, 'center_x': 100, 'center_y': 100}
def density(self, r, rho0, Rs):
"""
computes the density
:param x:
:param y:
:param rho0:
:param a:
:param s:
:return:
"""
rho = rho0 / (r/Rs * (1 + (r/Rs))**3)
return rho
def density_2d(self, x, y, rho0, Rs, center_x=0, center_y=0):
"""
projected density
:param x:
:param y:
:param rho0:
:param a:
:param s:
:param center_x:
:param center_y:
:return:
"""
x_ = x - center_x
y_ = y - center_y
r = np.sqrt(x_**2 + y_**2)
X = r/Rs
sigma0 = self.rho2sigma(rho0, Rs)
if isinstance(X, int) or isinstance(X, float):
if X == 1:
X = 1.000001
else:
X[X == 1] = 1.000001
sigma = sigma0 / (X**2-1)**2 * (-3 + (2+X**2)*self._F(X))
return sigma
def _F(self, X):
"""
function 48 in https://arxiv.org/pdf/astro-ph/0102341.pdf
:param X: r/rs
:return:
"""
c = self._s
if isinstance(X, int) or isinstance(X, float):
X = max(X, c)
if X < 1 and X > 0:
a = 1. / np.sqrt(1 - X ** 2) * np.arctanh(np.sqrt(1 - X**2))
elif X == 1:
a = 1.
elif X > 1:
a = 1. / np.sqrt(X ** 2 - 1) * np.arctan(np.sqrt(X**2 - 1))
else: # X == 0:
a = 1. / np.sqrt(1 - c ** 2) * np.arctanh(np.sqrt((1 - c ** 2)))
else:
a = np.empty_like(X)
X[X < c] = c
x = X[X < 1]
a[X < 1] = 1 / np.sqrt(1 - x ** 2) * np.arctanh(np.sqrt((1 - x**2)))
x = X[X == 1]
a[X == 1] = 1.
x = X[X > 1]
a[X > 1] = 1 / np.sqrt(x ** 2 - 1) * np.arctan(np.sqrt(x**2 - 1))
# a[X>y] = 0
return a
def mass_3d(self, r, rho0, Rs):
"""
mass enclosed a 3d sphere or radius r
:param r:
:param a:
:param s:
:return:
"""
mass_3d = 2*np.pi*Rs**3*rho0 * r**2/(r + Rs)**2
return mass_3d
def mass_3d_lens(self, r, sigma0, Rs):
"""
mass enclosed a 3d sphere or radius r for lens parameterisation
:param sigma0:
:param Rs:
:return:
"""
rho0 = self.sigma2rho(sigma0, Rs)
return self.mass_3d(r, rho0, Rs)
def mass_2d(self, r, rho0, Rs):
"""
mass enclosed projected 2d sphere of radius r
:param r:
:param rho0:
:param a:
:param s:
:return:
"""
sigma0 = self.rho2sigma(rho0, Rs)
return self.mass_2d_lens(r, sigma0, Rs)
def mass_2d_lens(self, r, sigma0, Rs):
"""
mass enclosed projected 2d sphere of radius r
:param r:
:param rho0:
:param a:
:param s:
:return:
"""
X = r/Rs
alpha_r = 2*sigma0 * Rs * X * (1-self._F(X)) / (X**2-1)
mass_2d = alpha_r * r * np.pi
return mass_2d
def mass_tot(self, rho0, Rs):
"""
total mass within the profile
:param rho0:
:param a:
:param s:
:return:
"""
m_tot = 2*np.pi*rho0*Rs**3
return m_tot
def grav_pot(self, x, y, rho0, Rs, center_x=0, center_y=0):
"""
gravitational potential (modulo 4 pi G and rho0 in appropriate units)
:param x:
:param y:
:param rho0:
:param a:
:param s:
:param center_x:
:param center_y:
:return:
"""
x_ = x - center_x
y_ = y - center_y
r = np.sqrt(x_**2 + y_**2)
M = self.mass_tot(rho0, Rs)
pot = M / (r + Rs)
return pot
def function(self, x, y, sigma0, Rs, center_x=0, center_y=0):
"""
lensing potential
:param x:
:param y:
:param sigma0: sigma0/sigma_crit
:param a:
:param s:
:param center_x:
:param center_y:
:return:
"""
x_ = x - center_x
y_ = y - center_y
r = np.sqrt(x_**2 + y_**2)
if isinstance(r, int) or isinstance(r, float):
r = max(self._s, r)
else:
r[r < self._s] = self._s
X = r / Rs
f_ = sigma0 * Rs ** 2 * (np.log(X ** 2 / 4.) + 2 * self._F(X))
return f_
def derivatives(self, x, y, sigma0, Rs, center_x=0, center_y=0):
"""
:param x:
:param y:
:param sigma0: sigma0/sigma_crit
:param a:
:param s:
:param center_x:
:param center_y:
:return:
"""
x_ = x - center_x
y_ = y - center_y
r = np.sqrt(x_**2 + y_**2)
if isinstance(r, int) or isinstance(r, float):
r = max(self._s, r)
else:
r[r < self._s] = self._s
X = r/Rs
alpha_r = 2 * sigma0 * Rs * X * (1 - self._F(X)) / (X ** 2 - 1)
f_x = alpha_r * x_/r
f_y = alpha_r * y_/r
return f_x, f_y
def hessian(self, x, y, sigma0, Rs, center_x=0, center_y=0):
"""
:param x:
:param y:
:param sigma0: sigma0/sigma_crit
:param a:
:param s:
:param center_x:
:param center_y:
:return:
"""
alpha_ra, alpha_dec = self.derivatives(x, y, sigma0, Rs, center_x, center_y)
diff = self._diff
alpha_ra_dx, alpha_dec_dx = self.derivatives(x + diff, y, sigma0, Rs, center_x, center_y)
alpha_ra_dy, alpha_dec_dy = self.derivatives(x, y + diff, sigma0, Rs, center_x, center_y)
f_xx = (alpha_ra_dx - alpha_ra)/diff
f_xy = (alpha_ra_dy - alpha_ra)/diff
#f_yx = (alpha_dec_dx - alpha_dec)/diff
f_yy = (alpha_dec_dy - alpha_dec)/diff
return f_xx, f_yy, f_xy
def rho2sigma(self, rho0, Rs):
"""
converts 3d density into 2d projected density parameter
:param rho0:
:param a:
:param s:
:return:
"""
return rho0 * Rs
def sigma2rho(self, sigma0, Rs):
"""
converts projected density parameter (in units of deflection) into 3d density parameter
:param sigma0:
:param Rs:
:return:
"""
return sigma0 / Rs |
328d4465fe96b12b3d8d70be1898d8e97763d312 | SumireSakamoto/python-tutorial | /uranai.py | 858 | 3.625 | 4 | import random
def number_input(message):
result = input(message)
if(result.isdigit()):
result = int(result)
return result
else:
return 0
def judgement(omikuji):
rand = random.randint(1,9)
if (omikuji == rand):
print('大吉ですね')
elif(omikuji > rand):
print('中吉ですね')
elif(omikuji < rand):
print('凶ですね...')
while(True):
omikuji = number_input('1~9で好きな数字を入力してください。\n\n')
if((omikuji !=0) and (omikuji > 0) and (omikuji < 10)):
print('あなたの好きな数字は' + str(omikuji) + 'ですね!\n\n')
print('それではその数字からあなたの命運を占いましょう\n\n')
judgement(omikuji)
break
else:
print('1~9の数字を入力してください。\n\n')
|
9743e67ea9188f1012825f5f6b6be4fb74ba7313 | DenVanvan/maze-BFS_alg | /maze_class.py | 3,251 | 3.71875 | 4 |
import os
from time import sleep
from collections import deque
class Maze:
# transforms .txt to list of lists
def __init__(self, file_path):
with open(file_path, 'r') as file:
self.content_initial = file.read().split('\n')
self.content_processed = [item for item in self.content_initial]
self.content_processed = [[fig for fig in item] for item in self.content_processed]
# calculates the shortest path out of total path
def find_path(self, path_dict, point, start_point, path):
path = [point]
while point != start_point:
point = path_dict[point]
path.append(point)
return path
# defines if the point is not outside the maze
def not_Valid(self, point):
if point[0]<0 or point[0] > len(self.content_processed):
return True
elif point[1]<0 or point[1]>len(self.content_processed[0]):
return True
else:
return False
# defines if the point will not hit the wall
def wall(self, point):
if self.content_processed[point[0]][point[1]] == '0':
return True
else:
return False
# main function: calculates the shortest path from I to Exit
def calculate(self):
visited = []
Queue = deque()
start_point = Maze.starting_point(self,'I')
Queue.appendleft(start_point)
path_dict = dict()
final_path = []
while Queue:
cur_point = Queue.popleft()
# moving the grid
next_points = [(cur_point[0]-1, cur_point[1]), (cur_point[0]+1, cur_point[1]),
(cur_point[0], cur_point[1]+1), (cur_point[0], cur_point[1]-1)]
# checking possible points
for point in next_points:
if Maze.not_Valid(self, point):
continue
elif Maze.wall(self, point):
continue
elif point in visited:
continue
elif self.content_processed[point[0]][point[1]] == 'E':
path_dict[point] = cur_point
print('Solution found: ')
return Maze.find_path(self, path_dict,point, start_point, final_path)
# adding point to queue if valid, not wall, not visited and not exit
else:
Queue.append(point)
path_dict[point] = cur_point
visited.append(cur_point)
# returns tuple: coordinates for the starting point
def starting_point(self, starting_point_str):
for i , row in enumerate(self.content_processed):
if starting_point_str in row:
path = (i,row.index(starting_point_str))
return path
# draws the output txt file
def draw_maze(self, path):
content_copy = self.content_processed[:]
for item in path[1:-1]:
content_copy[item[0]][item[1]] = '@'
with open('Maze_out.txt', 'w') as file:
for row in content_copy:
for item in row:
file.write(item)
file.write('\n')
|
3710e775d29c95539cc626d2e47089372815ed56 | naga1992/python_projects | /inheritence.py | 895 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 10 18:46:05 2018
@author: DS00331004
"""
class Parent():
def __init__(self,last_name,eye_color):
print("Calling Parent Class Constructor")
self.last_name=last_name
self.eye_color=eye_color
def show_info(self):
print("last name-"+self.last_name)
print("eye color-"+self.eye_color)
class Child(Parent):
def __init__(self,last_name,eye_color,number_of_toys):
print("Calling Child class Constructor")
Parent.__init__(self,last_name,eye_color)
self.number_of_toys=number_of_toys
def show_info(self):
print("last name-"+self.last_name)
print("eye color-"+self.eye_color)
print("no of toys"+str(self.number_of_toys))
suresh_jr=Child("donda","blue",12)
print(suresh_jr.show_info()) |
41b7bb5d872aee8f2458e1a9d5245f9a0d3d5eab | netstat-antp/netscripts | /test.py | 110 | 3.71875 | 4 | print "hello world!"
print "printing something else!"
for i in range (10):
print "Test number" + str(i)
|
d1a11902d5e502f95373da7a202e95409e576f44 | inwk6312winter2019/openbookfinal-sararasheed123 | /task1Asubtask1.py | 631 | 3.578125 | 4 | fin1 = open("Book1.txt",'r')
fin2 = open("Book2.txt",'r')
fin3 = open("Book3.txt",'r')
for line in fin1:
word1 = line.strip()
print(word1)
for line in fin2:
word2 = line.strip()
print(word2)
for line in fin3:
word3 = line.strip()
print(word3)
for item1 in word1:
if len(item1) == 50:
print(item1)
break
else:
print(item1)
for item2 in word2:
if len(item2) == 50:
print(item2)
break
else:
print(item2)
for item3 in word3:
if len(item3) == 50:
print(item3)
break
else:
print(item3)
|
b45c396e6b80a33845f27583f96a22f385f7250d | jmishra01/Google_foobar_Challenge | /5/5_1 Expanding Nebula.py | 5,858 | 3.515625 | 4 | # Expanding Nebula
# ================
# You've escaped Commander Lambda's exploding space station along with numerous escape pods full of bunnies. But - oh no! -
# one of the escape pods has flown into a nearby nebula, causing you to lose track of it. You start monitoring the nebula,
# but unfortunately, just a moment too late to find where the pod went. However, you do find that the gas of the steadily
# expanding nebula follows a simple pattern, meaning that you should be able to determine the previous state of the gas and
# narrow down where you might find the pod.
# From the scans of the nebula, you have found that it is very flat and distributed in distinct patches, so you can model
# it as a 2D grid. You find that the current existence of gas in a cell of the grid is determined exactly by its 4 nearby cells,
# specifically, (1) that cell, (2) the cell below it, (3) the cell to the right of it, and (4) the cell below and to the right of it.
# If, in the current state, exactly 1 of those 4 cells in the 2x2 block has gas, then it will also have gas in the next state.
# Otherwise, the cell will be empty in the next state.
# For example, let's say the previous state of the grid (p) was:
# .O..
# ..O.
# ...O
# O...
# To see how this grid will change to become the current grid (c) over the next time step, consider the 2x2 blocks of cells around
# each cell. Of the 2x2 block of [p[0][0], p[0][1], p[1][0], p[1][1]], only p[0][1] has gas in it, which means this 2x2 block would
# become cell c[0][0] with gas in the next time step:
# .O -> O
# ..
# Likewise, in the next 2x2 block to the right consisting of [p[0][1], p[0][2], p[1][1], p[1][2]], two of the containing cells have
# gas, so in the next state of the grid, c[0][1] will NOT have gas:
# O. -> .
# .O
# Following this pattern to its conclusion, from the previous state p, the current state of the grid c will be:
# O.O
# .O.
# O.O
# Note that the resulting output will have 1 fewer row and column, since the bottom and rightmost cells do not have a cell below and to
# the right of them, respectively.
# Write a function answer(g) where g is an array of array of bools saying whether there is gas in each cell (the current scan of the nebula),
# and return an int with the number of possible previous states that could have resulted in that grid after 1 time step. For instance,
# if the function were given the current state c above, it would deduce that the possible previous states were p (given above) as well as
# its horizontal and vertical reflections, and would return 4. The width of the grid will be between 3 and 50 inclusive, and the height of
# the grid will be between 3 and 9 inclusive. The answer will always be less than one billion (10^9).
# Languages
# =========
# To provide a Python solution, edit solution.py
# To provide a Java solution, edit solution.java
# Test cases
# ==========
# Inputs:
# (boolean) g = [[True, False, True],
# [False, True, False],
# [True, False, True]]
# Output:
# (int) 4
# Inputs:
# (boolean) g = [[True, False, True, False, False, True, True, True],
# [True, False, True, False, False, False, True, False],
# [True, True, True, False, False, False, True, False],
# [True, False, True, False, False, False, True, False],
# [True, False, True, False, False, True, True, True]]
# Output:
# (int) 254
# Inputs:
# (boolean) g = [[True, True, False, True, False, True, False, True, True, False],
# [True, True, False, False, False, False, True, True, True, False],
# [True, True, False, False, False, False, False, False, False, True],
# [False, True, False, False, False, False, True, True, False, False]]
# Output:
# (int) 11567
# Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder.
from collections import defaultdict
def gen_function(x, y, z):
z = ~(2**z)
a = x & z
b = y & z
c = x >> 1
d = y >> 1
return (a&~b&~c&~d) | (~a&b&~c&~d) | (~a&~b&c&~d) | (~a&~b&~c&d)
def matrix(n, nums):
dict_map = defaultdict(set)
nums = set(nums)
rn = 2**(n+1)
for i in range(rn):
for j in range(rn):
generation = gen_function(i,j,n)
if generation in nums:
dict_map[(generation, i)].add(j)
return dict_map
def answer(g):
g = list(zip(*g))
ncols = len(g[0])
nums = [sum([2**i if col else 0 for i, col in enumerate(row)]) for row in g]
matrix_map = matrix(ncols, nums)
pre_image = {i: 1 for i in range(2**(ncols+1))}
for row in nums:
next_row = defaultdict(int)
for c1 in pre_image:
for c2 in matrix_map[(row, c1)]:
next_row[c2] += pre_image[c1]
pre_image = next_row
return sum(pre_image.values())
g = [[True, False, True], [False, True, False], [True, False, True]]
assert answer(g) == 4
g = [[True, False, True, False, False, True, True, True],
[True, False, True, False, False, False, True, False],
[True, True, True, False, False, False, True, False],
[True, False, True, False, False, False, True, False],
[True, False, True, False, False, True, True, True]]
assert answer(g) == 254
g = [[True, True, False, True, False, True, False, True, True, False],
[True, True, False, False, False, False, True, True, True, False],
[True, True, False, False, False, False, False, False, False, True],
[False, True, False, False, False, False, True, True, False, False]]
assert answer(g) == 11567 |
d5d2ac28e6e566984101db96010427dc702f18f5 | jmishra01/Google_foobar_Challenge | /3/3_5 Find_the_Access_Codes.py | 2,567 | 3.8125 | 4 | # Find the Access Codes
# =====================
# In order to destroy Commander Lambda's LAMBCHOP doomsday device, you'll need access to it. But the only door leading to the LAMBCHOP chamber is secured
# with a unique lock system whose number of passcodes changes daily. Commander Lambda gets a report every day that includes the locks' access codes, but
# only she knows how to figure out which of several lists contains the access codes. You need to find a way to determine which list contains the access
# codes once you're ready to go in.
# Fortunately, now that you're Commander Lambda's personal assistant, she's confided to you that she made all the access codes "lucky triples" in order to
# help her better find them in the lists. A "lucky triple" is a tuple (x, y, z) where x divides y and y divides z, such as (1, 2, 4). With that information,
# you can figure out which list contains the number of access codes that matches the number of locks on the door when you're ready to go in (for example,
# if there's 5 passcodes, you'd need to find a list with 5 "lucky triple" access codes).
# Write a function answer(l) that takes a list of positive integers l and counts the number of "lucky triples" of (li, lj, lk) where the list indices meet
# the requirement i < j < k. The length of l is between 2 and 2000 inclusive. The elements of l are between 1 and 999999 inclusive. The answer fits within
# a signed 32-bit integer. Some of the lists are purposely generated without any access codes to throw off spies, so if no triples are found, return 0.
# For example, [1, 2, 3, 4, 5, 6] has the triples: [1, 2, 4], [1, 2, 6], [1, 3, 6], making the answer 3 total.
# Languages
# =========
# To provide a Python solution, edit solution.py
# To provide a Java solution, edit solution.java
# Test cases
# ==========
# Inputs:
# (int list) l = [1, 1, 1]
# Output:
# (int) 1
# Inputs:
# (int list) l = [1, 2, 3, 4, 5, 6]
# Output:
# (int) 3
# Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your
# solution passes the test cases, it will be removed from your home folder.
def answer(l):
res = 0
i = 0
n_l = len(l) - 2
while i < n_l:
first = l[i]
j = i + 1
while j < n_l + 1:
if l[j]%first == 0:
res += sum([1 for k in l[j+1:] if k%l[j]==0])
j+=1
i+=1
return res
assert answer([1,2,3,4,5,6])==3
assert answer([1,1,1])==1
assert answer([1,2,3,5,7,11])==0
|
6e59bbbea25aca648e640db7e36bcde89272d4a4 | ArielGz08/unaj-2021-s2-unidad3-com16 | /reuso_codigo_fuente.py | 1,266 | 3.859375 | 4 | # Vamos a ver como a través del uso de funciones podemos evitar tener código fuente repetido
# Código fuente aportado por Walter Grachot (tiene unos 34 sentencias originalmente)
def carga_producto_y_calcula_subtotal():
producto= input("Ingrese nombre del producto comprado: ")
valor= float(input("Ingrese su valor: "))
cantidad= int(input("Ingrese la cantidad: "))
total= (valor*cantidad)
producto = (producto, valor, cantidad)
print(total)
print()
return total, producto
def imprimir_subtotales(producto):
print("Compró " + str(producto[1][2]) + " " + str(producto[1][0]) + " a un Precio Unitario de $" + str(producto[1][1]) + " por un total de " + str(producto[0]))
print("Bienvenido al Supermercado Don Erne")
print("-" * 80)
dato_producto1 = carga_producto_y_calcula_subtotal()
dato_producto2 = carga_producto_y_calcula_subtotal()
dato_producto3 = carga_producto_y_calcula_subtotal()
dato_producto4 = carga_producto_y_calcula_subtotal()
imprimir_subtotales(dato_producto1)
imprimir_subtotales(dato_producto2)
imprimir_subtotales(dato_producto3)
imprimir_subtotales(dato_producto4)
total_general = dato_producto1[0] + dato_producto2[0] + dato_producto3[0] +dato_producto4[0]
print ("Ha gastado en total " + str(total_general))
|
6ba4b5dedebb3eeca01e63654515cfbd086881aa | xiaojieluo/yygame | /game/calculator.py | 7,110 | 4.34375 | 4 | #!/usr/bin/env python
# coding=utf-8
# copy from http://blog.chriscabin.com/coding-life/python/python-in-real-world/1101.html
# Thanks
class Stack(object):
"""
The structure of a Stack.
The user don't have to know the definition.
"""
def __init__(self):
self.__container = list()
def __is_empty(self):
"""
Test if the stack is empty or not
:return: True or False
"""
return len(self.__container) == 0
def push(self, element):
"""
Add a new element to the stack
:param element: the element you want to add
:return: None
"""
self.__container.append(element)
def top(self):
"""
Get the top element of the stack
:return: top element
"""
if self.__is_empty():
return None
return self.__container[-1]
def pop(self):
"""
Remove the top element of the stack
:return: None or the top element of the stack
"""
return None if self.__is_empty() else self.__container.pop()
def clear(self):
"""
We'll make an empty stack
:return: self
"""
self.__container.clear()
return self
class Calculator(object):
"""
A simple calculator, just for fun
"""
def __init__(self):
self.__exp = ''
def __validate(self):
"""
We have to make sure the expression is legal.
1. We only accept the `()` to specify the priority of a sub-expression. Notes: `[ {` and `] }` will be
replaced by `(` and `)` respectively.
2. Valid characters should be `+`, `-`, `*`, `/`, `(`, `)` and numbers(int, float)
- Invalid expression examples, but we can only handle the 4th case. The implementation will
be much more sophisticated if we want to handle all the possible cases.:
1. `a+b-+c`
2. `a+b+-`
3. `a+(b+c`
4. `a+(+b-)`
5. etc
:return: True or False
"""
if not isinstance(self.__exp, str):
print('Error: {}: expression should be a string'.format(self.__exp))
return False
# Save the non-space expression
val_exp = ''
s = Stack()
for x in self.__exp:
# We should ignore the space characters
if x == ' ':
continue
if self.__is_bracket(x) or self.__is_digit(x) or self.__is_operators(x) \
or x == '.':
if x == '(':
s.push(x)
elif x == ')':
s.pop()
val_exp += x
else:
print('Error: {}: invalid character: {}'.format(self.__exp, x))
return False
if s.top():
print('Error: {}: missing ")", please check your expression'.format(self.__exp))
return False
self.__exp = val_exp
return True
def __convert2postfix_exp(self):
"""
Convert the infix expression to a postfix expression
:return: the converted expression
"""
# highest priority: ()
# middle: * /
# lowest: + -
converted_exp = ''
stk = Stack()
for x in self.__exp:
if self.__is_digit(x) or x == '.':
converted_exp += x
elif self.__is_operators(x):
converted_exp += ' '
tp = stk.top()
if tp:
if tp == '(':
stk.push(x)
continue
x_pri = self.__get_priority(x)
tp_pri = self.__get_priority(tp)
if x_pri > tp_pri:
stk.push(x)
elif x_pri == tp_pri:
converted_exp += stk.pop() + ' '
stk.push(x)
else:
while stk.top():
if self.__get_priority(stk.top()) != x_pri:
converted_exp += stk.pop() + ' '
else:
break
stk.push(x)
else:
stk.push(x)
elif self.__is_bracket(x):
converted_exp += ' '
if x == '(':
stk.push(x)
else:
while stk.top() and stk.top() != '(':
converted_exp += stk.pop() + ' '
stk.pop()
# pop all the operators
while stk.top():
converted_exp += ' ' + stk.pop() + ' '
return converted_exp
def __get_result(self, operand_2, operand_1, operator):
if operator == '+':
return operand_1 + operand_2
elif operator == '-':
return operand_1 - operand_2
elif operator == '*':
return operand_1 * operand_2
elif operator == '/':
if operand_2 != 0:
return operand_1 / operand_2
else:
print('Error: {}: divisor cannot be zero'.format(self.__exp))
return None
def __calc_postfix_exp(self, exp):
"""
Get the result from a converted postfix expression
e.g. 6 5 2 3 + 8 * + 3 + *
:return: result
"""
assert isinstance(exp, str)
stk = Stack()
exp_split = exp.strip().split()
for x in exp_split:
if self.__is_operators(x):
# pop two top numbers in the stack
r = self.__get_result(stk.pop(), stk.pop(), x)
if r is None:
return None
else:
stk.push(r)
else:
# push the converted number to the stack
stk.push(float(x))
return stk.pop()
def __calc(self):
"""
Try to get the result of the expression
:return: None or result
"""
# Validate
if self.__validate():
# Convert, then run the algorithm to get the result
return self.__calc_postfix_exp(self.__convert2postfix_exp())
else:
return None
def get_result(self, expression):
"""
Get the result of an expression
Suppose we have got a valid expression
:return: None or result
"""
self.__exp = expression.strip()
return self.__calc()
"""
Utilities
"""
@staticmethod
def __is_operators(x):
return x in ['+', '-', '*', '/']
@staticmethod
def __is_bracket(x):
return x in ['(', ')']
@staticmethod
def __is_digit(x):
return x.isdigit()
@staticmethod
def __get_priority(op):
if op in ['+', '-']:
return 0
elif op in ['*', '/']:
return 1
# usage
c = Calculator()
print('result: {:f}'.format(c.get_result('8+10/2')))
print(int(c.get_result('8+10')))
# output:
result: 0.666000
|
aee33d9d32071f96b20643094deb1c6fc6158768 | EwertonLuan/Curso_em_video | /56_cadastro_de_pessoas.py | 881 | 3.703125 | 4 | ida = 0 # idade dos dois somados
h_velho = 0 # idade do homem mais velho
h_vn = '' # Nome do homem mais velho
m_20 = 0 # mulheres com 20 anos
for i in range(1, 5):
nome = str(input('Digite o nome {}ª pessoa: '.format(i)))
idade = int(input('Dite idade {}ª pessoa: '.format(i)))
ida += idade
sexo = str(input('Qual o sexo da {}ªpessoa (H/M): '.format(i))).upper().strip()
if sexo == 'H' and i == 1:
h_velho = idade
h_vn = nome
elif idade > h_velho:
h_velho = idade
h_vn = nome
if sexo == 'M' and idade < 20:
m_20 += 1
media = ida / 4
print('Media de idade entre homens e mulheres é de {}'.format(media))
print('O homem mais velho é o {} com {} anos de idade'.format(h_vn, h_velho))
print('{} mulheres com menos de 20 anos'.format(m_20))
|
c966acf1bedce7a5d9ff29d21a4e9db069c70141 | EwertonLuan/Curso_em_video | /41_categoria_atleta.py | 714 | 3.8125 | 4 | from datetime import date
print('\033[1;32m##\033[m' * 20+'\nPrograma para ver a categoria dos atletas\n'+'\033[1;32m##\033[m'*20)
ida = date.today().year - int(input('Qual a idade do atleta: '))
if ida <= 9:
print('Atleta esta com {} anos, sua categoria é \033[1;33mMIRIM\033[m'.format(ida))
elif ida <= 14:
print('Atleta esta com {} anos, sua categoria é \033[1;34mINFANTIL\033[m'.format(ida))
elif ida <= 19:
print('Atleta esta com {} anos, sua categoria é \033[1;35mJUNIOR\033[m'.format(ida))
elif ida <= 20:
print('Atleta esta com {} anos, sua categoria é \033[1;36mSENIOR\033[m'.format(ida))
else:
print('Atleta esta com {} anos, sua categoria é \033[1;31mMASTER\033[m'.format(ida)) |
0fa3b0ba1cc789068b001406df17eba6a53c8628 | changzhai/project_euler | /project_euler/src/pe23.py | 1,726 | 4.0625 | 4 | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
instructions = """
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
"""
import utils
def is_abundant(n):
if sum(utils.factors(n)) - n > n:
return True
else:
return False
abundant = []
total = 0
for x in range(1,28123+1):
not_abundant = True
if is_abundant(x):
abundant.append(x)
print(str(x) + ' is abundant')
for n in [n for n in abundant if x/n>=2]:
if (x - n) in abundant:
not_abundant = False
break
if not_abundant:
total += x
print(str(x) + ', total = ' + str(total))
else:
print(str(x) + 'is the sum of abundants')
print(total) |
a0c074a2bca1cb02d862c7f5ce267ee28785adc4 | kbethany/LPTHW | /ex19_drill.py | 754 | 3.53125 | 4 | #create new function, cheese_and_crackers, which has two variables
def pets(cat_count, dog_count):
#the function has four things inside it contains, 4 print statements
print "You have %d cat!" % cat_count
print "You have %d dog!" % dog_count
print "Man, those are hungry pets!"
print "Give them a boost!\n"
print "We can just give the function numbers directly:"
#prints the functino where 20 and 30 map to first and second variables
pets(1, 1)
print "OR, we can use variables from our script:"
amount_of_cat = 1
amount_of_dog = 5
pets(amount_of_cat, amount_of_dog)
print "We can even do math inside, too:"
pets(10 + 20, 5 + 6)
print "And we can combine the two, variables and math:"
pets(amount_of_cat + 100, amount_of_dog + 1000)
|
feb27cb841884e8a2460cbe7cc645bb2ba7ae2fb | kbethany/LPTHW | /ex15.py | 912 | 3.765625 | 4 | #sys is a package, argv says to import only the vars listed
#when you call up the program (ex15.py filename), where argv is any
#module i want retrieved from that package.
from sys import argv
#argv is the arguments vector which contains the arguments passed
#to the program.
script, filename = argv
#opens the filnemae listed above
txt = open(filename)
#prints the name of the file as defined above
print " Here's your file %r:" % filename
#prints everything inside the text file
print txt.read() #calls a function on txt named 'read'
print "Type the filename again:"
#prompts the user to input the filename again (see print command above)
#and sets what she enters to file_again
file_again = raw_input("> ")
#function that opens the text of file_again and sets the whole text
#as txt_again
txt_again = open(file_again)
#function that prints everything in txt_again without modification
print txt_again.read()
|
a9d1ca7beb482a72282d801a27858350ff365c7a | migeller/thinkful | /pip_001/fizz_buzz/fizz_buzz.py | 642 | 3.828125 | 4 | #!/usr/bin/env python
import sys
def modulo(x, y):
""" Determines if we can divide x from y evenly. """
return x % y == 0
def stepper(limit = 100):
""" Steps through from 1 to limit and prints out a fizzbuzz sequence. """
print "Our Upper Limit is %d! Let's go!" % limit
for n in xrange(1, limit + 1):
if modulo(n, 3):
print "fizz",
if modulo(n, 5):
print "\b-buzz"
else:
print "\b"
elif modulo(n, 5):
print "buzz"
else:
print n
if __name__ == '__main__':
try:
i = sys.argv[1]
except IndexError:
stepper()
else:
try:
limit = int(i)
except ValueError:
stepper()
else:
stepper(limit)
|
3b78e75671e8048fe45e4dfa2319d6cbc7d3bfe1 | YoZe24/lingi2364-projects | /project1/src/apriori_prefix_vdb.py | 3,406 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def apriori(filepath, minFrequency, verbose=True):
"""Runs the apriori algorithm on the specified file with the given minimum frequency.
This version has:
- intelligent candidate generation using prefixes (implemented using lists);
- frequency computation using union of singleton database projections,
with break if minsup cannot be reached;
- no additional anti-monotonicity pruning."""
ngen = 0
nsupp = 0
nfreq = 0
# read data; this is heavily inspired from the provided template
transactions_set = list()
lines = filter(None, open(filepath, "r").read().splitlines())
app = transactions_set.append
items = 0
for line in lines:
transaction = list(map(int, line.rstrip().split(" ")))
items = max(items, transaction[-1]) # transactions are sorted, find number of items
app(set(transaction))
trans = len(transactions_set) # number of transactions
member = [set() for i in range(items+1)]
for t in range(len(transactions_set)):
for i in transactions_set[t]:
member[i].add(t) # store the transactions t in which item i appears
minSupport = trans * minFrequency
if not minSupport == int(minSupport):
minSupport = int(minSupport) + 1
def frequency(itemset):
"""Returns the frequency of the given itemset for the current list of transactions"""
# compute the intersection of all member[i] where i in itemset
# this intersection contains all the transactions covered by itemset
s = member[itemset[0]]
if len(itemset) > 1:
for i in itemset[1:]:
s = s & member[i]
if len(s) < minSupport:
return 0
return len(s)/trans
F = [] # frequent sets
for i in range(items):
nsupp += 1
ngen += 1
freq = frequency([i + 1])
if freq >= minFrequency:
F += [[i+1]]
if verbose:
nfreq += 1
print("%s (%g)" % ([i+1], freq)) # print frequent singleton sets
while F != []:
# list of subsets of items of size level
l = F[:] # deep copy the list
F = []
cnt = 1
for l1 in l[:-1]:
l11 = l1[:-1] # take prefix
for l2 in l[cnt:]:
if l11 == l2[:-1]: # if the sets share a common prefix
newl = l1 + [l2[-1]] # new candidate based on sets sharing prefixes
freq = frequency(newl)
nsupp += 1
ngen += 1
if freq >= minFrequency:
F += [newl]
if verbose:
nfreq += 1
print("%s (%g)" % (newl, freq)) # print frequent sets
else: # prefix will never be the same again, we can skip
break
cnt += 1
if verbose:
print(ngen)
print(nsupp)
print(nfreq)
if __name__ == "__main__":
"""
ti = 0
for i in range(10):
s = time.perf_counter()
apriori("../statement/Datasets/accidents.dat", 0.9, verbose=False)
ti += time.perf_counter() - s
print(ti/10)
"""
apriori('../statement/Datasets/chess.dat', 0.99, verbose=True) |
a6f2c1f7a0acbdf5f1685ebd3456be49aeb01aed | peter0703257153/School-project | /school_directory.py | 3,555 | 3.78125 | 4 | __author__ = 'pedro'
class School_directory(object):
def __init__(self):
self.schools = []
def add(self, school_name):
self.schools.append(school_name)
def find(self, name):
for school in self.schools:
if school.school_name == name:
return school
def get_school(self):
return self.schools
class School(object):
def __init__(self, school_name):
self.streams = []
self.school_name = school_name
def add(self, stream):
self.streams.append(stream)
def find(self, stream_name):
for stream in self.streams:
if stream.name == stream_name:
return stream
def __repr__(self):
return self.school_name
school_directory = School_directory()
class Stream(object):
def __init__(self, name):
self.name = name
self.students = []
self.teachers = []
def add_student(self, student):
self.students.append(student)
def add_teacher(self, teacher):
self.teachers.append(teacher)
def find_student(self, student_name):
for student in self.students:
if student.name == student_name:
return student.name
def find_teacher(self, teacher_name):
for teacher in self.teachers:
if teacher.name == teacher_name:
return teacher.name
def get_students(self):
return self.students
class Student(object):
def __init__(self, name, age, parent_name):
self.name = name
self.age = age
self.parent_name = parent_name
def __repr__(self):
return self.name
class Teacher(object):
def __init__(self, name):
self.name = name
def register_student():
stream_name = raw_input("Enter the stream")
school = raw_input("Enter name of the school")
name = raw_input("Enter student name")
age = raw_input("Enter age")
parent = raw_input("Enter parent name")
school_name = school_directory.find(school)
student = Student(name, age, parent)
stream = school_name.find(stream_name)
stream.add_student(student)
school_name = school_directory.find(school)
stream = school_name.find(stream_name)
print stream.get_students()
showmenue()
def register_teacher():
name = raw_input("Enter teacher name")
teacher = Teacher(name)
stream = Stream()
stream.add_teacher(teacher)
showmenue()
def register_stream():
school = raw_input("Enter name of the school")
stream_name = raw_input("Enter stream name")
stream = Stream(stream_name)
school_name = school_directory.find(school)
school_name.add(stream)
showmenue()
def register_school():
school_name = raw_input("Enter school name")
school = School(school_name)
school_directory.add(school)
print school_directory.get_school()
showmenue()
def showmenue():
print "1 - Enter stream"
print "2 - Enter student"
print "3 - Enter teacher"
print "4 - Enter school name"
print "5 - Find school"
print "6 - Find teacher"
print "7 - Find student"
menue = int(raw_input("Choose any number"))
if menue == 2:
register_student()
elif menue == 3:
register_teacher()
elif menue == 1:
register_stream()
elif menue == 4:
register_school()
showmenue() |
381d4fa43d359440ffc3198333987812e06308c7 | aishwariya-7/apple | /main.py | 324 | 3.703125 | 4 | '''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
Str ="I LOVE BEEZ LAB";
count =0;
for(i in range(0.len(Str))):
if(Str[i]!=' '):
count=count+1;
print(Str(count)); |
ff73cf14435050af2da53a669de66c9aa5de32aa | bruyneron/python_ds | /algo/bubble_sort.py | 625 | 3.859375 | 4 | # TC - O(n^2)
def ascending_sort(a):
n = len(a)
for i in range(0, n):
for j in range(0, n-1-i):
# (n-1)-i => n-1 becuase we are doing a[j] & a[j+1]. We don't want to go over the limit of j and get index out of range error.
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
def descending_sort(a):
n = len(a)
for i in range(0, n):
for j in range(0, n-1-i):
if a[j] < a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
if __name__ == '__main__':
arr = [23, 43, 541, 12, 1, 12, 323]
print(arr)
descending_sort(arr)
print(arr) |
83dfa83903466ca2eca35f96a9351f76d7dc9adb | bruyneron/python_ds | /ds/queue.py | 4,221 | 3.78125 | 4 | '''
1) List
enqueue() | q.append()
dequeue() | q.pop(0) 1st element is 0
size() | len(q)
is_empty() | len(q)==0
2) SLL/DLL
(Have to use DLL. Reason: With SLL deletion takes O(n), Queue is supposed to take O(1) for deletion) <--- This is dumb
why??
SLL with head and tail.
Insertion @ tail (No deletion @ tail) -> O(1)
Deletion @ head (No insertion @ head) -> O(1)
1 -> 2 -> 3 ->
| |
head Tail
------------------------------------------------------------------------------------
FIFO - QUEUE
Insertion | O(1)
Deletion | O(1)
Access/Search | O(n)
'''
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class Queue:
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
# if (self.head is self.tail) doesn't work for identifying empty queue
# Reason: If queue has only one element, then head and tail pint to the same element
return self.head is None and self.tail is None
def enqueue(self, data):
'''
2 cases:
1) Empty queue
2) Non empty queue
'''
if self.is_empty():
self.head = self.tail = Node(data, None)
return
self.tail.next = Node(data, None)
self.tail = self.tail.next
def dequeue(self):
'''
3 cases:
1) Empty queue
2) Non-empty queue with more than 1 elements
3) Non-empty queue with exactly 1 element
'''
if self.is_empty():
raise Exception('Queue is empty. Can\'t dequeue')
dequeued_element = self.head.data # Don't return node itself. If node is returned returned node can be used to traverse the Queue
self.head = self.head.next
# In case of a Queue 'q' with one element
# 1 --> None
# /\
# head tail
#
# After: q.dequeue()
#
# 1 --> None
# | |
# tail head
#
# Tail would still be pointing to an element. Hence queue won't be empty. So tail should be reset
# For queue to be empty condition is: (self.head is None) and (self.tail is None)
#
if self.head is None:
self.tail = None
return dequeued_element
def size(self):
if self.is_empty():
return 0
itr = self.head
length = 0
while itr:
length += 1
itr = itr.next
return length
def reverse(self):
if self.is_empty():
return
# Reverse links (Reversing linked list)
prev = None
curr = self.head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
# Reverse head and tail markers
temp = self.head
self.head = self.tail
self.tail = temp
def print(self):
if self.is_empty():
print('Queue is empty')
return
itr = self.head
qstr = ''
while itr:
qstr += str(itr.data) + '-->'
itr = itr.next
print(qstr)
if __name__ == '__main__':
q = Queue()
q.print()
print(q.head, q.tail)
q.enqueue(1)
q.print()
print(q.head.data, q.tail.data)
q.enqueue(2)
q.print()
print(q.head.data, q.tail.data)
q.enqueue(3)
q.print()
print('Size', q.size())
print(q.head.data, q.tail.data)
print(q.dequeue())
q.print()
print(q.head.data, q.tail.data)
print(q.dequeue())
q.print()
print(q.head.data, q.tail.data)
print(q.dequeue())
q.print()
print(q.head, q.tail)
print('Size', q.size())
#q.dequeue()
print('For fun\n==========')
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.print()
print(f'head = {q.head.data}, tail = {q.tail.data}')
q.reverse()
q.print()
print(f'head = {q.head.data}, tail = {q.tail.data}')
q.enqueue(0)
q.print()
q.dequeue()
q.print()
|
751fab2eb3a2da8e335dff8b2ae2da160df1872f | lx881219/webley-puzzle | /webley.py | 3,392 | 3.78125 | 4 | import csv
import sys
import pathlib
class Solution:
def __init__(self):
self.result = []
self.target_price = None
self.menu = []
def handle_file_error(self):
print('Please provide a valid csv file in the following format. (python webley.py example.csv)')
print("""
Target price, $14.55
mixed fruit,$2.15
french fries,$2.75
side salad,$3.35
hot wings,$3.45
mozzarella sticks,$4.20
sampler plate,$5.80
""")
def get_price(self, raw_price):
"""
convert raw price to float
:param raw_price: raw price in string format
:return: price in float format
"""
try:
price = float(raw_price.split('$')[-1])
except ValueError:
print("Invalid price")
sys.exit()
return price
def parse_csv(self, csv_file):
"""
parse the csv file
:param csv_file: csv file name
:return: True when file is successfully parsed
"""
current_dir = pathlib.Path.cwd()
file = pathlib.Path(current_dir, csv_file)
if file.exists():
with open(file, mode='r') as f:
csv_reader = csv.reader(f)
first_row = next(csv_reader, None)
if not first_row:
self.handle_file_error()
return False
if 'Target price' in first_row:
self.target_price = self.get_price(first_row[1])
for row in csv_reader:
if row:
menu_item, menu_price = row[0], self.get_price(row[1])
self.menu.append((menu_item, menu_price))
# sort the menu by price for fast lookup
self.menu.sort(key=lambda x: x[1])
return True
self.handle_file_error()
return False
def find_combination(self, target, index, current):
"""
a recursive function to find the right combination
:param target: the target price
:param index: current index
:param current: current combination
:return:
"""
if target == 0.0:
# hard copy the current combination
self.result = list(current)
return True
for i in range(index, len(self.menu)):
if target < self.menu[i][1]:
break
current.append(i)
found = self.find_combination(target-self.menu[i][1], i, current)
if found:
return True
else:
current.pop()
def solution(self):
args = sys.argv
if len(args) < 2:
self.handle_file_error()
else:
parse_result = self.parse_csv(str(args[1]))
if parse_result:
self.find_combination(self.target_price, 0, [])
if self.result:
print("We can order the following dishes given the target price $%f:" % self.target_price)
for i in self.result:
print(self.menu[i][0], ''.join(['$', str(self.menu[i][1])]))
else:
print("There is no combination of dishes that is equal to the target price")
s = Solution()
s.solution()
|
96265a429106573491aed434cec6d734534eea5a | backcover7/Algorithm | /15. 3Sum.py | 3,174 | 3.515625 | 4 | import bisect
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
if len(nums)<3: return res
length = len(nums)
listsort = sorted(nums)
for start in range(length-2):
if listsort[start] > 0: break
if start > 0 and listsort[start] == listsort[start-1]: continue
point = start + 1
end = length - 1
while point<end:
total = listsort[start] + listsort[point] + listsort[end]
if total < 0:
point += 1
elif total > 0:
end -= 1
else:
res.append([listsort[start], listsort[point], listsort[end]])
while point < end and listsort[point] == listsort[point+1]:
point += 1
while point< end and listsort[end] == listsort[end-1]:
end -= 1
point += 1
end -= 1
return res
def threeSum_180ms(self, nums):
ans = []
numcounts = self.count(nums) # get set(nums) and their counts
nums = sorted(numcounts) # same as set(nums)
for i, num in enumerate(nums):
'''
We consider two scenarios:
When there are duplicate nums in a solution
When all values in a solution are unique
at which point, we perform twosum for each negative num
'''
if numcounts[num] >= 2: # there are 2 scenarios for 2 duplicate vals
if num == 0: # zeros
if numcounts[num] >= 3:
ans.append([0, 0, 0])
else: # and non-zeros
if (-2 * num) in nums:
ans.append([num, num, -2 * num])
if num < 0:
ans = self.twosum(ans, nums, numcounts, num, i)
return ans
def twosum(self, ans, nums, numcounts, num, i):
"""Find two numbers a, b such that a + b + num = 0 (a + b = -num)"""
twosum = -num # find 2 nums that sum up to this positive num
left = bisect.bisect_left(nums, (twosum - nums[-1]), i + 1) # minval
right = bisect.bisect_right(nums, (twosum // 2), left) # maxval
for num2 in nums[left:right]: # we do this knowing the list is sorted
num3 = twosum - num2
if num3 in numcounts and num3 != num2:
ans.append([num, num2, num3])
return ans
def count(self, nums):
"""Organize nums by `{num: occurence_count}`"""
count = {}
for num in nums:
if num in count:
count[num] += 1
else:
count[num] = 1
return count
s = Solution()
s.threeSum_180ms([-1, 0, 1, 2, -1, -4])
# Given array nums = [-1, 0, 1, 2, -1, -4],
#
# A solution set is:
# [
# [-1, 0, 1],
# [-1, -1, 2]
# ] |
d4eec8ca65674a001474dcd2574fcbfea7d9df70 | backcover7/Algorithm | /70. Climbing Stairs.py | 1,148 | 3.59375 | 4 | class Solution(object):
def climbStairs_recurse(self, n):
"""
:type n: int
:rtype: int
"""
# recurse but time limit exceeded
# Time complexity: O(2^n)
if n <= 1: return 1
return self.climbStairs_recurse(n-1) + self.climbStairs_recurse(n-2)
# recurse with memory: Top-to-Down, main problem first
# def __init__(self):
# self.mem = {0:1, 1:1}
def climbStairs_recurse_with_memory(self, n):
if n not in self.mem:
self.mem[n] = self.climbStairs_recurse_with_memory(n - 1) + self.climbStairs_recurse_with_memory(n - 2)
return self.mem[n]
def climbStairs_dp_with_onearray(self, n):
# Down-to-Top, subproblem first
# space complexity: O(n)
dp = [1] * (n+1)
for i in xrange(2, n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
def climbStairs(self, n):
# one param, space complexity: O(1)
dp1, dp2 = 1, 1
for x in xrange(2, n+1):
dp2, dp1 = dp1+dp2, dp2
return dp2
S = Solution()
print S.climbStairs(36) |
65da66866a817543e61627a73d2eed4cc2e6abb2 | backcover7/Algorithm | /513. Find Bottom Left Tree Value.py | 714 | 3.9375 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return
max_depth = 0
queue = [(root, 1)]
while queue:
curr, level = queue.pop(0)
if curr:
if level > max_depth:
max_depth = level
ans = curr.val
queue.append((curr.left, level+1))
queue.append((curr.right, level+1))
return ans |
ac51f8eefc234d49caf3a6a2eaee68f88f018e38 | backcover7/Algorithm | /29. Divide Two Integers.py | 862 | 3.640625 | 4 | class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
# https://www.youtube.com/watch?v=htX69j1jf5U
sig = (dividend < 0) == (divisor < 0)
a, b, res = abs(dividend), abs(divisor), 0
while a >= b:
x = 0 # 2^x # b*2^0; b*2^1; b*2^2
while a >= b << (x + 1): x += 1
res += 1 << x
a -= b << x
'''
3*2^0=3, 10>3, x=0
3*2^1=6, 10>6, x=1
3*2^2=12, 10<12, x=2 [NO]
res = 1<<x = 2^1 = 2
10-3*2^1=10-6=4
4->res=2+{1}=3 #This is the answer
'''
return min(res if sig else -res, 2147483647)
a = 10
b = 3
S = Solution()
print S.divide(a, b) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.