blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
69905e825f7034ef8afd488fa900db50098408ea | gapc87/EjerciciosPython | /fundamentos/operadores_aritmeticos.py | 263 | 3.9375 | 4 | a = 3
b = 2
suma = a + b
print('suma', suma)
resta = a - b
print('resta', resta)
multi = a * b
print('multiplicacion', multi)
division = a/b
print('division', division)
modulo = a % b
print('residuo', modulo)
exponente = a ** b
print('exponente', exponente)
|
0d843c4ef440e3a9a3b816c41e8eea7788492421 | Redhead80/files.sorted | /main.py | 697 | 3.59375 | 4 | def sorted_union_files(files: list, result_path: str) -> None:
temp_dict = {sum(1 for _ in open(one_file, encoding="UTF-8")): one_file for one_file in files}
with open(result_path, "w") as file_write:
file_write.write("")
with open(result_path, "a") as file_write:
for key in sorted(temp_dict.keys()):
file_write.write(temp_dict[key] + "\n")
file_write.write(str(key) + "\n")
file_write.writelines(line for line in open(temp_dict[key], "r", encoding="UTF-8"))
file_write.write("\n")
def main():
files = ["1.txt", "2.txt", "3.txt"]
sorted_union_files(files, "new file.txt")
if __name__ == "__main__":
main()
|
5cb61169d5312ae1d2db4e8b9424950df5e6a44f | soonler/Python000-class01 | /Week_02/G20200389010209/week02_0209_ex.py | 2,061 | 4.125 | 4 | #父类:1、变量初始化;2、打印支付信息的方法
class Customer(object):
def __init__(self, name,total_goods, total_money):
self.name = name
self.total_money = total_money
self.total_goods = total_goods
def print_tips(self,name,total_money):
print(f"亲爱的顾客{self.name},您需要支付{self.total_money:.2f}元")
#子类普通会员:结算方式的方法
class Customer_Normal(Customer):
def __init__(self, name,total_goods, total_money):
super().__init__(self, name,total_goods, total_money)
def payup(self):
if self.total_money < 200:
super().print_tips(self.name,self.total_money)
else:
self.total_money = self.total_money * 0.9
super().print_tips(self.name,self.total_money)
#子类VIP会员:结算方式的方法
class Customer_VIP(Customer):
def __init__(self, name, total_goods, total_money):
self.name = name
self.total_money = total_money
self.total_goods = total_goods
def payup(self):
if self.total_money < 200 and self.total_goods < 10 :
super().print_tips(self.name,self.total_money)
elif self.total_money < 200.0 and self.total_goods >= 10.0 :
self.total_money = self.total_money * 0.85
super().print_tips(self.name,self.total_money)
else:
self.total_money = self.total_money * 0.8
super().print_tips(self.name,self.total_money)
#根据不同的会员调用不同的类
class Factory:
def getPerson(self, name, level,total_goods, total_money):
if level == 'Normal':
customer = Customer_Normal(name, total_goods, total_money)
return customer.payup()
elif level == 'VIP':
customer = Customer_VIP(name, total_goods, total_money)
return customer.payup()
else:
print("请输入正确的会员等级!")
if __name__ == '__main__':
factory = Factory()
person = factory.getPerson("Adam", "VIP",20,19) |
b6b893d3dc6a4364eb38b1a24e68759d672331e4 | chapsan2001/ITMO.Labs | /PythonLabs/Lab3/lab_03_05.py | 729 | 3.921875 | 4 | '''
Операции cо словарями
'''
d2 = {'a':1, 'b':2, 'c':3, 'bag':4}
d5 = d2.copy() # создание копии словаря
print("Dict d5 copying d2 = ", d5)
# получение значения по ключу
print("Get dict value by key d5['bag']: ", d5["bag"])
print("Get dict value by key d5.get('bag'): ",d5.get('bag'))
print("Get dict keys d5.keys(): ", d5.keys()) #список ключей
print("Get dict values d5.values(): ", d5.values()) #список значений
print("\n")
myInfo = {'surname':'Chapkey', 'name':'Alexander', 'middlename': 'Urievich1', 'day':29, 'mouth':3,'year':2001, 'university':'ITMO'}
for i in myInfo.keys():
print('MyInfo[',i,'] = ', myInfo[i])
|
e3a94c1d185811bc82b8397acec050aae3cb8190 | pyxin/python_test001 | /part_one/py001.py | 1,834 | 3.78125 | 4 | # 一摞有序的纸牌 __getitem__ 和 __len___
# import sys
# sys.path.extend(['/Users/pan/Codes-01/PY/python_test001'])
import collections
import doctest
Card = collections.namedtuple('Card', ['rank', 'suit'])
"""
>>> beer_card = Card(7,'ssss')
>>> beer_card
Card(rank=7, suit='ssss')
"""
class FrenchDeck:
"""
定义一个纸牌类
>>> FrenchDeck.ranks
['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
>>> FrenchDeck.suit
['spades', 'diamonds', 'clubs', 'hearts']
>>> deck = FrenchDeck()
>>> deck[0]
Card(rank='2', suit='spades')
>>> deck[:3]
[Card(rank='2', suit='spades'), Card(rank='3', suit='spades'), Card(rank='4', suit='spades')]
>>> deck[12::13]
[Card(rank='A', suit='spades'), Card(rank='A', suit='diamonds'), Card(rank='A', suit='clubs'), Card(rank='A', suit='hearts')]
>>> for i in deck[:4]: # doctest: +ELLIPSIS
... print(i)
...
Card(rank='2', suit='spades')
Card(rank='3', suit='spades')
Card(rank='4', suit='spades')
Card(rank='5', suit='spades')
>>> for i in reversed(deck[:4]): # doctest: +ELLIPSIS
... print(i)
...
Card(rank='5', suit='spades')
Card(rank='4', suit='spades')
Card(rank='3', suit='spades')
Card(rank='2', suit='spades')
"""
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suit = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suit for rank in self.ranks] # 全排列
def __len__(self):
return len(self._cards)
def __getitem__(self, item):
return self._cards[item]
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
def spades_high(card):
rank_value = FrenchDeck.ranks.index(card.rank)
return rank_value * len(suit_values) + suit_values[card.suit]
if __name__ == '__main__':
doctest.testmod(verbose=True)
|
90dbb8b39f5875d3fd2d9f7340bb0071337280d9 | cmhuang0328/hackerrank-python | /basic-data-types/4-find-the-second-largest-number.py | 537 | 4.0625 | 4 | #! /usr/bin/env python3
'''
You are given n numbers. Store them in a list and find the second largest number.
Input Format
The first line contains n. The second line contains an array A[] of n integers each separated by a space.
Constraints
2 <= n <= 10
-100 <= A[i] <= 100
Output Format
Print the value of the second largest number.
'''
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
# use sorted to sort the list with [-2] to find the second largest
print (sorted(list(set(arr)))[-2])
|
aa51818ff92b4b1a75986c08c647ffc5b2cfb1ad | chris-sooseok/food_prediction_machine | /2_IDA.PY | 7,926 | 3.875 | 4 | import pandas as pd
import csv
import numpy as np
import string
import math
import re
# count max number of items to fill headers
def count_max(filename):
f = open(filename, 'r')
lines = csv.reader(f)
max = 0
for line in lines:
if (max < len(line)):
max = len(line)
return max
# create headers using count_max function
def create_header(filename):
new_file = "./cse487_project1/data/recipe/2_recipe_with_header.csv"
# count max len of items
len = count_max(filename)
with open(filename, 'r', encoding='utf-8-sig') as f_out, \
open(new_file, 'w', newline="", encoding='utf-8-sig') as f_in:
writer = csv.writer(f_in)
header = ["title"]
# create a header list filled with number of items
for idx in range(len - 1):
header.append("item{}".format(idx + 1))
# write header
writer.writerow(header)
# copy paste rows of data into new file
for line in csv.reader(f_out):
writer.writerow(line)
create_header("./cse487_project1/data/recipe/1_recipe.csv")
# we have proper header now, but we need to fill blanks of each row if corresponding items are empty
def fill_blank(filename):
new_file = "./cse487_project1/data/recipe/3_recipe_with_comma.csv"
# max number of items
cnt = count_max(filename)
with open(filename, 'r') as reader,\
open(new_file, 'w', newline="") as writer:
lines = csv.reader(reader, delimiter = ",")
header = next(lines)
writer = csv.writer(writer)
writer.writerow(header)
for line in lines:
if(len(line) < cnt):
freq = cnt - len(line)
while(freq != 0):
line.append('$')
freq -= 1
writer.writerow(line)
#12
#fill_blank("./cse487_project1/data/recipe/2_recipe_with_header.csv")
# 3
def remove_front_space(text):
answer = ""
for n in range(len(text)):
if(text[n] == ' ' and text[n+1] == ' '):
count = n + 1
while(text[count] == ' '):
count += 1
answer = text[count:len(text)]
if(answer == ""):
answer = text
if(answer[0] == "(" and answer[len(answer)-1] == ")"):
answer = '$'
return answer
def remove_back_space(text):
answer = ""
if(text == 0):
answer=0
else:
for n in range(len(text)):
if(text[n] == ' ' and text[n + 1] == '('):
answer = text[0:n]
break
if(text[n] == ','):
answer = text[0:n]
break
if(answer == ""):
answer = text
return answer
# remove unwanted space for items
def remove_space(filename):
new_file = "./cse487_project1/data/recipe/4_recipe_with_no_space.csv"
data = pd.read_csv(filename)
header = data.columns.values
header_with_no_title = np.delete(header,0)
for header in header_with_no_title:
for idx in range(len(data[header])):
data[header][idx] = remove_back_space(remove_front_space(data[header][idx]))
data.to_csv(new_file, index = False)
#remove_space("./cse487_project1/data/recipe/3_recipe_with_comma.csv")
# remove duplicated items for each row
def duplicate(filename):
df = pd.read_csv(filename)
height = df.shape[0]
width = df.shape[1]
fields = []
for i in range(width-1):
fields.append("item{}".format(i+1))
for row in range(height):
items = set()
for field in fields:
if(df[field][row] != '$' and df[field][row] != "half-and-half"):
items.add(df[field][row])
items_len = len(items)
inc_to_items_len = 0
for field, item in zip(fields, items):
df[field][row] = item
for field in fields:
if(inc_to_items_len < items_len):
inc_to_items_len += 1
else:
df[field][row] = '$'
df.to_csv("./cse487_project1/data/recipe/5_recipe_no_duplicate.csv", index=False)
#duplicate( "./cse487_project1/data/recipe/4_recipe_with_no_space.csv")
def helper_non_char(text):
# remove quotation
if not ',' in text:
text = text.replace('"',"")
# remove parenthesis
text = re.sub(r" ?\([^)]+\)", "", text)
# remove common unwanted symbol
text = text.replace('-'," ").replace('!',"").replace('.'," ")
# remove unwanted whitesapce
text = text.strip()
text = re.sub(' +', ' ', text)
return text
def remove_non_char(filename):
new_file = "./cse487_project1/data/recipe/6_recipe_without_nonchar.csv"
data = pd.read_csv(filename)
for idx in range(len(data["title"])):
data["title"][idx] = helper_non_char(data["title"][idx])
data.to_csv(new_file, index = False)
#remove_non_char("./cse487_project1/data/recipe/5_recipe_no_duplicate.csv")
# 5
def sorting(filename):
df = pd.read_csv(filename)
df.sort_values('title', inplace=True)
height = df.shape[0]
width = df.shape[1]
fields = []
for i in range(width-1):
fields.append("item{}".format(i+1))
for row in range(height):
dict_holder = {}
for key in list(string.ascii_lowercase):
dict_holder[key] = []
for field in fields:
if(key == df[field][row][0]):
dict_holder[key].append(df[field][row])
items = []
for li in dict_holder.values():
if(len(li) != 0):
for item in li:
items.append(item)
for field, item in zip(fields, items):
df[field][row] = item
df.to_csv("./cse487_project1/data/recipe/final_recipe.csv", index=False)
#sorting("./cse487_project1/data/recipe/6_recipe_without_nonchar.csv")
# 6
# -------------------------------------------------recipe done ------------------------------------------------
def filter_value(text):
number = ""
for let in text:
if(let.isdigit()):
number = number + let
return number
def only_value(filename):
new_file = "./cse487_project1/data/nutrition/2_nutrition_only_num.csv"
data = pd.read_csv(filename)
header = data.columns.values
header_with_no_title = np.delete(header,0)
for header in header_with_no_title:
for idx in range(len(data[header])):
data[header][idx] = filter_value(data[header][idx])
data.to_csv(new_file, index=False)
#only_value("./cse487_project1/data/nutrition/1_nutrition.csv")
#7
def filter_no_cal(filename):
df = pd.read_csv(filename)
df = df[df.calories != 0]
df.to_csv("./cse487_project1/data/nutrition/3_nutrition_all_food.csv", index=False)
filter_no_cal("./cse487_project1/data/nutrition/2_nutrition_only_num.csv")
def remove_non_char_ntr(filename):
new_file = "./cse487_project1/data/nutrition/4_nutrition_without_nonchar.csv"
data = pd.read_csv(filename)
for idx in range(len(data["title"])):
data["title"][idx] = helper_non_char(data["title"][idx])
data.to_csv(new_file, index = False)
remove_non_char_ntr("./cse487_project1/data/nutrition/3_nutrition_all_food.csv")
def sort_ntr(filename):
df = pd.read_csv(filename)
df.sort_values('title', inplace=True)
df.to_csv("./cse487_project1/data/nutrition/final_nutrition.csv", index=False)
sort_ntr("./cse487_project1/data/nutrition/4_nutrition_without_nonchar.csv")
#
#def read_recipe(filename):
#
# df = pd.read_csv(filename)
#
# print(df)
#read_recipe("6_recipe_ordered.csv") |
e17ed949e1ddb2d9097495b233191d839981dd9c | curiousTauseef/Algorithms_and_solutions | /Codility/6_NumberOfDistinctIntersections.py | 4,161 | 3.625 | 4 | '''
We draw N discs on a plane. The discs are numbered from 0 to N − 1. An array A of N non-negative integers, specifying the radiuses of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J].
We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs have at least one common point (assuming that the discs contain their borders).
The figure below shows discs drawn for N = 6 and A as follows:
A[0] = 1
A[1] = 5
A[2] = 2
A[3] = 1
A[4] = 4
A[5] = 0
There are eleven (unordered) pairs of discs that intersect, namely:
discs 1 and 4 intersect, and both intersect with all the other discs;
disc 2 also intersects with discs 0 and 3.
Write a function:
def solution(A)
that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000.
Given array A shown above, the function should return 11, as explained above.
Assume that:
N is an integer within the range [0..100,000];
each element of array A is an integer within the range [0..2,147,483,647].
Complexity:
expected worst-case time complexity is O(N*log(N));
expected worst-case space complexity is O(N) (not counting the storage required for input arguments).
'''
def solution(A):
# Pre-process and find start and end of discs.
N = len(A)
if N == 0:
return 0
start = [0]*N
end = [0]*N
for i in range(0,N):
# Crop if disc goes blow 0 or above N
start[i] = max(0, i - A[i])
end[i] = min(N, i + A[i] )
# Sort by start
start, end = zip(*sorted(zip(start, end)))
end = list(end)
start = list(start)
# Count how many discs ended before the new one starts (new_start <= old_ends)
count = 0
aux_end = [] # add or discard
for i in range(0,N):
# Find values of end of discs that are higher than the start.
# If not, remove from the list, they will never intersect again.
j=0
while j <= len(aux_end)-1:
#print('i=' + str(i) + ' j=' + str(j) + ' count=' + str(count) + ' start[i]=' + str(start[i]) + ' aux_end=' + str(aux_end))
if aux_end[j] >= start[i]:
count += 1
j += 1
else:
aux_end.pop(j)
# Add end of i
aux_end.append(end[i])
if count > 10000000:
return -1
# END
return count
# count += len([x for x in end[0:i] if x >= start[i]])
A = [3,1,1,1,0]
solution(A) # 7
A = [1,5,2,1,4,0]
solution(A) # 11
A = []
solution(A)
'''
def solution(A):
A2 = sorted(enumerate(A), key=lambda x: x[1],reverse=True)
N = len(A2)
count = 0
elint_save = []
for i in range(0,N):
# elements that intersect. Careful not to get out of range
if (A2[i][0] - A2[i][1]) < 0: # Below 0
if (A2[i][0] + A2[i][1]) > N:
elint = list(range(0,N))
else:
elint = list(range(0, A2[i][0] + A2[i][1]))
else: # above 0
if (A2[i][0] + A2[i][1]) > N:
elint = list(range(A2[i][0] - A2[i][1],N))
else:
elint = list(range(A2[i][0] - A2[i][1], A2[i][0] + A2[i][1]))
elint_save += elint
# check how many elements have been shown previusly to the left
prev = [ A2_el[0] for A2_el in A2[0:i]]
prev.append(A2[i][0])
prev_found = [k not in prev for k in elint]
# Add counter
count += sum(prev_found)
# count by summing
print('iter: ' + str(i) + ' count: ' + str(count) + ' elint: ' + str(elint) + ' ' + str(prev_found))
# Check max counter
if count > 10000000:
return -1
return count
A = [1,5,2,1,4,0]
solution(A)
A = [1,1,1]
solution(A) # should be 3 its 2. FUCK
def solution(A):
A2 = sorted(enumerate(A), key=lambda x: x[1], reverse=True)
N = len(A2)
count = 0
for i in range(0, N):
# closing of the disc
end_i = A2[i][0] + A2[i][1]
if (A2[i][0] + A2[i][1]) > (N-1):
end_i = (N-1)
# for the remaining of the disks above, count if they intersect
low_i = 0
for j in range(A2[i][0], end_i):
low_i += int(A2[j][0] - A2[j][1] <= end_i)
count += low_i
# count by summing
print('iter: ' + str(i) + ' count: ' + str(count) + ' low_i: ' + str(low_i) )
# Check max counter
if count > 10000000:
return -1
return count
'''
|
f61c59ad1db01a892a9f5317a8c28ca66e55b09c | strawwj/pythontest | /pythoncase/udpserver_test.py | 336 | 3.578125 | 4 | #udp没有客户端服务端之分
import socket
MYHOST = '127.0.0.1'
OTHERHOST = '127.0.0.1'
PORT = 60008
with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as s:
s.bind((MYHOST,PORT))
s.sendto(b'hello i am wj',(OTHERHOST,60008))
data,addr = s.recvfrom(1024)
print('data:',data)
print('addr:',addr)
s.close()
|
ca5ba9239b148fd7c5cee98d963d0490fe8db8ff | saurav1066/python-assignment | /8.py | 343 | 4.21875 | 4 | """
Write a Python program to remove the nth index character from a nonempty string.
"""
inp = input("Enter a string:")
remove_index = int(input("Enter the index you want to remove:"))
if len(inp) < remove_index:
print("Sorry the string is shorter than you think.. ")
else:
inp = inp[0:remove_index]+inp[remove_index+1:]
print(inp)
|
8d92533a7f31c1c88a1b3b0f7b9690503f2a6d9a | anna-s-dotcom/python01-python08 | /Tag04/dozent_queue.py | 691 | 3.859375 | 4 | import queue
print('start fifo')
fifoq = queue.Queue()
fifoq.put(5)
fifoq.put('A')
fifoq.put(True)
fifoq.put([1, 5])
while not fifoq.empty():
print(fifoq.get())
print()
print('end fifo')
print()
print('start lifo')
lifoq = queue.LifoQueue()
lifoq.put(5)
lifoq.put('A')
lifoq.put(True)
lifoq.put([1, 5])
while not lifoq.empty():
print(lifoq.get())
print()
print('end lifo')
print()
print('start prio')
prioq = queue.PriorityQueue()
prioq.put((1, 'XX'))
prioq.put((5, 'A'))
prioq.put((3, True))
prioq.put((2, [1, 5]))
prioq.put((1, 'B'))
while not prioq.empty():
print(prioq.get())
print()
print('end prio')
print()
|
687699ceb423770daf2d49f0522fa3bd836d4ede | Rvh88/category-production-computational-modelling-1 | /framework/evaluation/tabulation.py | 1,627 | 3.8125 | 4 | """
===========================
Tabulation and working with pandas.DataFrames.
===========================
Dr. Cai Wingfield
---------------------------
Embodied Cognition Lab
Department of Psychology
University of Lancaster
c.wingfield@lancaster.ac.uk
caiwingfield.net
---------------------------
2019
---------------------------
"""
from pandas import pivot_table, DataFrame
def save_tabulation(data: DataFrame, values, rows, cols, path: str):
"""
Saves a tabulated form of the DataFrame data, where rows are values of `rows`, columns are values of `cols`, and
values are values of `values`.
:param data:
:param values:
:param rows:
:param cols:
:param path:
:return:
"""
# pivot
p = pivot_table(data=data, index=rows, columns=cols, values=values,
# there should be only one value for each group, but we need to use "first" because the
# default is "mean", which doesn't work with the "-"s we used to replace nans.
aggfunc="first")
_tabulation_to_csv(p, path)
def _tabulation_to_csv(table, csv_path):
"""
Saves a simple DataFrame.pivot_table to a csv, including columns names.
Thanks to https://stackoverflow.com/a/55360229/2883198
"""
# If there are nested indices, it just works
if len(table.index.names) > 1:
table.to_csv(csv_path)
# Otherwise we have to break off the header to give it space to label the column names
else:
csv_df: DataFrame = DataFrame(columns=table.columns, index=[table.index.name]).append(table)
csv_df.to_csv(csv_path, index_label=table.columns.name)
|
5dc289b609bba64c11f23ee23e2afda4e8f92196 | ccojocea/PythonVSC | /CollectionsModule/namedtuple.py | 236 | 3.734375 | 4 | from collections import namedtuple
Dog = namedtuple('Dog', 'age breed name')
sam = Dog(age=2, breed='Lab', name='Sammy')
print(sam)
Cat = namedtuple('Cat', 'fur claws name')
c = Cat(fur='Fuzzy', claws=False, name='Kitty')
print(c[1]) |
d4850ae7c9bd3ac512a5fbfffc6bed3b428fbd01 | spartanick666/practice_python | /exercise11.py | 345 | 4.09375 | 4 |
def get_number():
return int(input("Please enter a number: "))
#combine functions
def not_prime():
if number % i == 0:
print("This is not prime number")
def is_prime():
if number % i != 0:
print("This is a prime number")
number = get_number()
for i in range(2, number + 1):
not_prime()
is_prime()
break
|
3cfac8470683e13a2e149feb58afd36ec8b7f423 | eduardofmarcos/Python | /11 - aluguel_de_carros.py | 210 | 3.71875 | 4 | km = float(input('Digite a kmmetragem rodada: '))
dias = int(input('Digite a quantidade de dias: '))
total = (km * 0.15) + (dias * 60)
print('O total a pagar pelo aluguel será de R$: {:.2f}'.format(total))
|
ce8909fd77eef131d4fcd8ace05fe1c8eeeb2c6b | tramvn1996/datastructure | /strings/mnemonics_phone.py | 849 | 3.953125 | 4 | #generate a corresponding characters sequence
#based on a string of digits
MAPPING = ('0','1','ABC','DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ')
def mnemonics_phone(phone_number):
def phone_mnemonics_helper(digit):
if digit == len(phone_number):
mnemonics.append(''.join(partial_mnemonic))
else:
for c in MAPPING[int(phone_number[digit])]:
#print(partial_mnemonic,mnemonics)
partial_mnemonic[digit]=c
phone_mnemonics_helper(digit+1) #recursion
#add two elements together then add to the final result
#print(digit,c, partial_mnemonic[0],partial_mnemonic)
#print('break')
mnemonics, partial_mnemonic=[],[0]*len(phone_number)
phone_mnemonics_helper(0)
return mnemonics
print(mnemonics_phone('23'))
|
8c6fa26db94b73d1d58d6efd52fd9014278d7ae6 | devjayantmalik/PythonTutorials | /src/tutorial_5.py | 7,084 | 4.59375 | 5 | # ==================================================
# ==================================================
# Functions
# ==================================================
# ==================================================
# ===============================================
# Write a function to add two numbers
def add_numbers(num1, num2):
return num1 + num2
sum = add_numbers(5, 3)
print("5 + 3 =", sum)
# ===============================================
# Example to demonstrate that variable created
# inside function is available only inside function
def assign_name():
name = "Vikash"
print("name inside function:", name)
# create a global variable
name = "Jayant Malik"
# Use assign name to change the variable
assign_name()
# print the name
print("name outside function:", name)
# ========================================================
# Create a global variable 'name'
# create a function change_name(name) and
# assign name="Tom" inside function
# pass the global variable inside change_name()
# print value of name outside the function
# Defining a function change_name()
def change_name(name):
name = "Tom"
# Creating a global variable
name = "Jayant Malik"
# Call the change_name() function
change_name(name)
# Print the value of name
print("Value of name is:", name)
# ==========================================================
# Change value of global variable by
# returning some value from function
# Define a function
def change_name(name):
return name
# Create a global variable 'name'
name = "Jayant Malik"
# Print initial value of name
print("Initial Name:", name)
# Call change_name() function and assign value to name
name = change_name("Donald Trump")
# Print name on the screen
print("Changed Name:", name)
# ===========================================================
# Change the global variable using global keyword
# Create a function change_name()
def change_name():
global global_name
global_name = "Peter"
# Declare a global variable and print its initial value
global_name = "Arvind"
print("Using global initial name:", global_name)
# Call change_name function
change_name()
# Print changed value of global_name
print("using global changed name:", global_name)
# =================================================
# Example to demonstrate that a function
# without a return value returns None
# Declare a function
def say_hello():
print("Hello inside say_hello()")
result = say_hello()
print("Result from say_hello():", result)
# ====================================================
# Write a program to solve for x
# Sample output:
# Enter Equation: x + 4 = 9
# Result: x = 5
# Rules:
# First input will always be x and
# we need to only perform addition
# function will receive a single string and then split it into parts
# Create a function to solve for x
def solve_x(eqn):
# Intial equation: x + val1 = val2
# For soln Equation becomes: x = val2 - val1
# Split the string into words
x, plus, val1, equals, val2 = eqn.split(" ")
# Solve for x
return int(val2) - int(val1)
# Ask the user for equation and split it into parts
eqn = input("Enter Equation: ")
# Call the solve_x function and store the result
soln = solve_x(eqn)
# Print value of x
print("Result: x =", soln)
# ==================================================
# Create a function that returns multiple values at same time
# Also receive and store the values in result1, result2 variables
# Tips:
# Create a program to return addition and subtraction
# of two numbers at the same time.
# Declaring a multi_vals function with two arguments.
def multi_vals(num1, num2):
return (num1 + num2), (num1 - num2)
# Receiving result from multi_vals function
addition, subtraction = multi_vals(5, 4)
# Print the results on screen
print("addition 5 + 4:", addition)
print("subtraction 5 - 4:", subtraction)
# ================================================
# Write a function that returns list of prime numbers
# A prime number is only divisible by 1 and itself
# 5 is a prime, because it is divisible only by 1 and 5
# 6 is not a prime, because it is divisible by 1, 2, 3, 6
# Rules:
# Create a seperate function to check if a no is prime
# Create a seperate function to return a list of prime nos
# Creating a function to check if a no is prime
def is_prime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
# Creating a function to get a list of prime nos
def get_primes(upto):
# list of prime nos
listPrimes = [1]
# a loop to generate no from 1 to upto
for i in range(2, upto):
if is_prime(i) == True:
listPrimes.append(i)
# return listPrimes back
return listPrimes
# Ask the user for max no upto which he wants a list to be generated
upto = int(input("Enter upto: "))
# Receive list of primes and store it in a variable
primes = get_primes(upto)
# print primes on screen
for prime in primes:
print(prime, end=", ")
print("\b\b")
# =======================================================
# Create a function to receive unknown no of arguments
# Use splat operator (*)
# Create a function to sum n numbers
def sum_all(*args):
# Create a variable to store sum
sum = 0
# cycling through each argument passed
for num in args:
sum += num
# Return the final sum
return sum
# Assigning sum to variable
result = sum_all(1,2,3,4,5,6)
# Print the sum on the screen
print("Result:", result)
# ==============================================
# Write a program to calculate area of different shapes:
# Ignore case in which input is provided by user.
# Sample output:
# Enter shape: rectangle
# Area of Rectange is :
# Import math module
import math
def rectangle_area():
# Ask the user for length and breadth
length = float(input("Enter length: "))
breadth = float(input("Enter breadth: "))
# Calculate the area
area = length * breadth
# Print the area on screen
print("Area of rectangle: {} x {} = {}".format(length, breadth, area))
def square_area():
# Ask for side
side = float(input("Enter side: "))
# Calculate the area
area = math.pow(side, 2)
# Print the area on screen
print("Area of square: {} x {} = {}".format(side, side, area))
def circle_area():
# Ask for radius
radius = int(input("Enter radius: "))
# Calculate the area
area = math.pi * math.pow(radius, 2)
# Print the result on screen
print("Area of circle: {:.6f} x {} x {}".format(math.pi, radius, radius))
def get_area(shape):
# Convert shape to lower case
shape = shape.lower()
# Check for shapes
if shape == "rectangle":
rectangle_area()
elif shape == "square":
square_area()
elif shape == "circle":
circle_area()
else:
print("Invalid shape entered.")
def main():
# Ask the user for type of shape
shape = input("Enter shape (rectangle, square, circle): ")
# Call get_area() function
get_area(shape)
main()
|
11541508eda910012ca16ac3e2f6fcf1c0c16074 | sitnet1102/project2_bank_system | /dataType.py | 9,782 | 3.71875 | 4 |
'''
데이터 타입과 관련된 메소드들은 기획서를 기반으로 합니다.
'''
class dataTypeBase :
''' 데이터 타입 추상 클래스입니다. '''
@classmethod
def dataConfirm(cls, data) :
#데이터 문법 확인 매소드
pass
@classmethod
def dataToBasicType(cls, data) :
#기본형 변환 메소드
#if self.dataConfirm(data) :
return data.strip(' ') # 양쪽 공백 지우기
@classmethod
def dataCompare(cls, A, B) :
A = cls.dataToBasicType(A)
B = cls.dataToBasicType(B)
if A == B :
return True
else :
return False
class DateData(dataTypeBase) :
@classmethod
def dataConfirm(cls, data) :
if len(data) == 6 :
for i in range(len(data)) :
if ord('0') <= ord(data[i]) <= ord('9') :
pass
else :
return False
year = int(data[:2])
month = int(data[2:4])
day = int(data[4:])
if 40 <= year <= 50 :
return False
if 1 <= month <= 12 :
pass
else :
return False
if 1 <= day <= 31 :
pass
else :
return False
elif len(data) == 8 :
if ord(data[2]) == ord('-') or ord(data[2]) == ord('/') or ord(data[2]) == ord('.') :
for i in range(len(data)) :
if i == 2 or i == 5 :
if ord(data[2]) == ord(data[5]) :
pass
else :
return False
else :
if ord('0') <= ord(data[i]) <= ord('9') :
pass
else :
return False
year = int(data[:2])
month = int(data[3:5])
day = int(data[6:])
if 40 <= year <= 50 :
return False
if 1 <= month <= 12 :
pass
else :
return False
if 1 <= day <= 31 :
pass
else :
return False
else :
for i in range(len(data)) :
if ord('0') <= ord(data[i]) <= ord('9') :
pass
else :
return False
year = int(data[:4])
month = int(data[4:6])
day = int(data[6:])
if 1900 <= year <= 2100 :
# 구간 변경??? 1950 <= year <= 2040
pass
else :
return False
if 1 <= month <= 12 :
pass
else :
return False
if 1 <= day <= 31 :
pass
else :
return False
elif len(data) == 10 :
if ord(data[4]) == ord('-') or ord(data[4]) == ord('/') or ord(data[4]) == ord('.') :
for i in range(len(data)) :
if i == 4 or i == 7 :
if ord(data[4]) == ord(data[7]) :
pass
else :
return False
else :
if ord('0') <= ord(data[i]) <= ord('9') :
pass
else :
return False
year = int(data[:4])
month = int(data[5:7])
day = int(data[8:])
if 1900 <= year <= 2100 :
# 구간 변경??? 1950 <= year <= 2040
pass
else :
return False
if 1 <= month <= 12 :
pass
else :
return False
if 1 <= day <= 31 :
pass
else :
return False
else :
return False
return True
@classmethod
def dataToBasicType(cls, data) :
result = ""
if cls.dataConfirm(data) :
if len(data) == 6 :
tmp = ""
if int(data[:2]) < 40 :
tmp = "20"
elif int(data[:2]) > 50 :
tmp = "19"
result = tmp + data
elif len(data) == 8 :
if ord(data[2]) == ord('-') or ord(data[2]) == ord('/') or ord(data[2]) == ord('.') :
tmp = ""
if int(data[:2]) < 40 :
tmp = "20"
elif int(data[:2]) > 50 :
tmp = "19"
result = tmp + data[:2] + data[3:5] + data[6:]
else :
result = data
elif len(data) == 10 :
result = data[:4] + data[5:7] + data[8:]
return result
class BankAccountData(dataTypeBase) :
@classmethod
def dataConfirm(cls, data) :
if len(data) == 16 :
if ord(data[4]) == ord('-') or ord(data[2]) == ord(' ') or ord(data[2]) == ord('.') :
for i in range(len(data)) :
if i == 4 or i == 8 :
if ord(data[4]) == ord(data[8]) :
pass
else :
return False
else :
if ord('0') <= ord(data[i]) <= ord('9') :
pass
else :
return False
elif len(data) == 14 :
for i in range(len(data)) :
if ord('0') <= ord(data[i]) <= ord('9') :
pass
else :
return False
else :
return False
return True
@classmethod
def dataToBasicType(cls, data) :
result = ""
if cls.dataConfirm(data) :
if len(data) == 14 :
result = data
elif len(data) == 16 :
if ord(data[4]) == ord('-') or ord(data[4]) == ord(' ') or ord(data[4]) == ord('.') :
result = data[:4] + data[5:8] + data[9:]
return result
class PasswordData(dataTypeBase) :
@classmethod
def dataConfirm(cls, data) :
check = True
num = 0
sEng = 0
bEng = 0
sChar = 0
otherChar = 0
if len(data) < 10 or len(data) > 20 :
return False
for i in range(len(data)) :
if ord('0') <= ord(data[i]) <= ord('9') :
num = num + 1
elif ord('a') <= ord(data[i]) <= ord('z') :
sEng = sEng + 1
elif ord('A') <= ord(data[i]) <= ord('Z') :
bEng = bEng + 1
elif ord(data[i]) == ord('!') or ord(data[i]) == ord('@') or ord(data[i]) == ord('#') or ord(data[i]) == ord('$') or ord(data[i]) == ord('%') or ord(data[i]) == ord('^') or ord(data[i]) == ord('&') or ord(data[i]) == ord('*') or ord(data[i]) == ord('(') or ord(data[i]) == ord(')') :
sChar = sChar + 1
else :
otherChar = otherChar + 1
'''
print(num)
print(sEng)
print(bEng)
print(sChar)
'''
if num == 0 or sEng == 0 or bEng == 0 or sChar == 0 :
check = False
if otherChar == 0 :
pass
else :
check = False
return check
class NameData(dataTypeBase) :
@classmethod
def dataConfirm(cls, data) :
check = True
if len(data) <= 1 or len(data) > 10 :
check = False
for i in range(1, len(data)) :
if data[i] == " " :
check = False
if ord('가') <= ord(data[i]) <= ord('힣') :
pass
else :
check = False
return check
class TimeData(dataTypeBase) :
@classmethod
def dataConfirm(cls, data) :
if len(data) == 8 :
for i in range(len(data)) :
if i == 2 or i == 5 :
if ord(data[i]) == ord(':') :
pass
else :
return False
else :
if ord('0') <= ord(data[i]) <= ord('9') :
pass
else :
return False
h = int(data[:2])
min = int(data[3:5])
sec = int(data[6:-1])
if 0 <= h <= 23 :
pass
else :
return False
if 0 <= min <= 59 :
pass
else :
return False
if 0 <= sec <= 59 :
pass
else :
return False
else :
return False
return True
@classmethod
def dataToBasicType(cls, data) :
result = ""
if cls.dataConfirm(data) :
return data[:2] + data[3:5] + data[6:]
else :
return result
class PriceData(dataTypeBase) :
@classmethod
def dataConfirm(cls, data) :
intdata = int(data)
if intdata >= 0 and intdata < 1000000000000000 :
if data == 0 :
return True
else :
if ord(data[0]) == ord('0'):
return False
else :
return True
else :
return False |
73966187535e1aa60fbd701724e652053d15d2a8 | ZhangYet/vanguard | /myrtle/date0313/peek_index_in_a_mountain_array.py | 760 | 3.703125 | 4 | # https://leetcode.com/problems/peak-index-in-a-mountain-array/
from typing import List
def same_direction(nums: List[int], up: bool) -> bool:
if len(nums) == 1:
return True
if up:
return all([nums[i] < nums[i+1] for i in range(len(nums) - 1)])
return all([nums[i] > nums[i+1] for i in range(len(nums) - 1)])
class Solution:
def peakIndexInMountainArray(self, A: List[int]) -> int:
if len(A) < 3:
return -1
peek = max(A)
peek_index = A.index(peek)
if A[peek_index+1] == peek:
return -1
if not same_direction(A[:peek_index], True):
return -1
if not same_direction(A[peek_index+1:], False):
return -1
return peek_index
|
3d98d33b8f2a1a637b2e02385d478f2540f2433f | luotong1995/ML_python | /Perceptron/Perceptron.py | 2,622 | 3.578125 | 4 | import numpy as np
from matplotlib import pyplot as plt
class Perceptron(object):
def __init__(self, input_num, activator):
'''
:param input_num: 感知器数据的输入维度
:param activator: 激活函数
'''
self.input_num = input_num
self.activator = activator
# 权重初始化
self.weights = [0.0 for _ in range(input_num)]
# 偏置项初始化
self.bias = 0.0
alph = 0.01
def costFunction(X, y, theta, b):
return y * (X.dot(theta) + b)
def train(X, y, theta, b):
while True:
# i = random.randint(0,len(y)-1)
for i in range(len(y)):
result = y[i][0] * ((np.dot(X[i:i + 1], theta)) + b)
if result <= 0:
temp = np.reshape(X[i:i + 1], (theta.shape[0], 1))
theta += y[i][0] * temp * alph
b += y[i][0] * alph
cost = costFunction(X, y, theta, b)
# print(cost)
if (cost > 0).all():
break
return theta, b
def plotData(X, y, b, theta):
plt.xlabel('x1')
plt.ylabel('x2')
m = len(y)
for i in range(m):
if int(y[i][0]) == 1:
plt.scatter(X[i][0], X[i][1], marker='x', color='red')
else:
plt.scatter(X[i][0], X[i][1], marker='x', color='blue')
print('theta', theta[0][0], theta[1][0])
xl = np.arange(0, 10, 0.001)
yl = -1 / theta[1][0] * (b + theta[0][0] * xl)
plt.plot(xl, yl, color='black', linewidth='1')
plt.show()
def plotData2(X, y):
plt.xlabel('x1')
plt.ylabel('x2')
m = len(y)
for i in range(m):
if int(y[i][0]) == 1:
plt.scatter(X[i][0], X[i][1], marker='x', color='red')
else:
plt.scatter(X[i][0], X[i][1], marker='x', color='blue')
plt.show()
def f(x):
'''
感知器使用的激活函数就是一个sign符号函数
:param x:
:return:
'''
return 1 if x > 0 else -1
def pre(X, theta, b):
y_ = X.dot(theta) + b
return f(y_)
if __name__ == '__main__':
# for i in range(10):
# X_train = [i for i in range(200)]
# rand_index = np.random.choice(200, size=20)
# print (rand_index)
# batch_x = X_train[rand_index]
# batch_ys = y_train[rand_index,:]
X = [[3, 3], [4, 3], [1, 1], [3, 2], [3, 4], [2, 3]]
y = [[1], [1], [-1], [1], [-1], [-1]]
X = np.array(X, float)
y = np.array(y, float)
# plotData2(X,y)
theta = np.zeros((X.shape[1], 1))
b = 0
theta, b = train(X, y, theta, b)
plotData(X, y, b, theta)
print(pre(np.array([[2, 2]]), theta, b))
|
a29adc30c35a4103613e00b057ae862d370fbc52 | theshdb/Brute-Force-Linear-Regression | /main.py | 1,944 | 3.765625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class Linear_Regression:
def __init__(self, file_path):
self.train_data = pd.read_csv(file_path)
self.train_x = self.train_data.pop("house age")
self.train_y = self.train_data.pop("house price of unit area")
def Slope_and_Intercept(self):
#Slope
m = sum(float(x - self.train_x.mean() * (y - self.train_y.mean())) for x, y in zip(self.train_x[0:], self.train_y[0:]))/sum(float(x - self.train_x.mean()**2) for x in self.train_x[0:])
#Intercept
b = float(self.train_y.mean() - m * self.train_x.mean())
return m, b
def Drawing_Graph(self, predictions, user_x, user_y):
plt.xlabel('House Age')
plt.ylabel('Cost per unit area in $')
# plotting points as a scatter plot
plt.scatter(self.train_x, self.train_y, color= "blue", marker= ".")
#best fit line
plt.plot(self.train_x, predictions, color = "red")
#predictions
plt.scatter(user_x, user_y, color = "red")
plt.annotate("$"+ str(round(user_y, 2)) , xy=(user_x, user_y), xytext=(4, 10), fontsize=12,
arrowprops=dict(facecolor='green', shrink=0.05))
plt.show()
if __name__ == "__main__":
#Creating Linear Regression Model
file_path = "Replace this with file path"
model = Linear_Regression(file_path)
#Generating slope and y inercept
linear_variables = model.Slope_and_Intercept()
#generating best fit line
predictions = [linear_variables[0]*x + linear_variables[1] for x in model.train_x]
#taking user input for predictions
user_x = float(input("Enter house age : "))
#displaying o/p through graph
model.Drawing_Graph(predictions , user_x, linear_variables[0]*user_x+linear_variables[1]) |
40375ea1239b01730a42c908636248db4c48ace9 | xuefengCrown/Files_01_xuef | /all_xuef/程序员练级+Never/Fun_Projects/Interpreter/draw_animation.py | 685 | 4.0625 | 4 | import turtle
screen = turtle.Screen() # create a new screen
screen.setup(500,500) # 500 x 500 window
don = turtle.Turtle() # create a new [ninja] turtle
don.speed(0) # make it move faster
def draw_square() : # a function that draws one square
for side in range(4) :
don.forward(100)
don.left(90)
don.penup() # go off-screen on the left
don.goto(-350, 0)
don.pendown()
while True : # now do this repeatedly, to animate :
don.clear() # - clear all the turtle's previous drawings
draw_square() # - draw a square
don.forward(10) # - move forward a bit
|
242eb9402addb6e8bd7aa887dd497757e1c76e1a | midah18/Pyramid | /draw.py | 4,335 | 4.25 | 4 | def get_shape():
"""
certain names of shapes are valid
if user input is the right shape break from this function
if user input is the wrong shape, keep asking till the correct one is given
"""
valid = ['square', 'triangle', 'pyramid', 'proper square', 'rectangle', "paralellogram"]
while True:
shape = input("Shape?: ").lower()
if shape in valid:
break
else:
continue
return shape
def get_height():
"""
user input asks for a number
function checks if it is a number/int
function also checks is it in the range of 0(inclusive) and 81(exclusive)
if they are not met, it will continue asking
"""
while True:
height = input("Height?: ")
if height.isnumeric() and height:
height = int(height)
if height in range(0, 81):
break
return height
def draw_pyramid(height, outline):
space = height - 1
stars = 1
if outline is True:
#i = 0
j = 1
height -= 2
h = height #actually the height
print(" "*(height+1)+ "*")
while 0 < (height):
print(" " * (height) + "*" + " " * j + "*")
j += 2 #space counter
height -= 1 #controls the 'x'
if height == 0:
print("*" * (h * 2 + 3))
else:
for x in range(0, height):
print(" " * space + "*" * stars)
space = space - 1
stars = stars + 2
def draw_triangle(height, outline):
if outline is True:
print("*")
print("**")
i = 3
j = 1
while i < height:
print("*" + (" " * j) + "*")
i += 1
j += 1
print("*" * height, end= '')
print()
else:
for x in range(0, height):
for y in range(0, x + 1):
print("*", end = '')
print()
def draw_square(height, outline):
if outline is True:
print("*" * height)
for i in range (height-2):
print('*' + ' ' * (height - 2) + "*")
print("*" * height)
else:
for i in range (height):
print('*'*height)
def draw_rectangle(height, outline):
if outline is True:
i = 0
print("*" * height)
while i < (height - 2):
print("*" + " " * (height - 2) + "*")
i += 1
print("*" * height)
else:
for row in range(0, height):
print("*" * height)
def draw_paralellogram(height, outline):
if outline is True:
print(" " * (height - 1) + "*" * height)
for row in range(0, height-2):
print(" " * (int(height) - row - 2) + "*" + " "* (int(height)-2) + '*')
print("*" * height)
else:
for row in range(0, height):
print(" " * (height - row - 1) + "*" * height)
def draw_proper_square(height, outline):
if outline is True:
print("* " * height)
for i in range (height-2):
print('* ' + ' ' * (height - 2) + "* ")
print("* " * height)
else:
for i in range (height):
print('* '*height)
def draw(shape, height, outline):
"""
compares the user input shape name to a particular name
if the name is equal to the given shape name, it goes to that specific function
"""
if shape == 'pyramid':
draw_pyramid(height, outline)
elif shape == 'square':
draw_square(height, outline)
elif shape == 'triangle':
draw_triangle(height, outline)
elif shape == 'rectangle':
draw_rectangle(height, outline)
elif shape == 'proper square':
draw_proper_square(height, outline)
elif shape == "paralellogram":
draw_paralellogram(height, outline)
def get_outline():
"""
user input is asked whether it should an outline or not
y returns true ... an outline
n returns false ... a full shape
"""
outline = input("Outline only? (Y/N)").lower()
if outline == "y":
return True
else:
return False
if __name__ == "__main__":
shape_param = get_shape()
height_param = get_height()
outline_param = get_outline()
draw (shape_param, height_param, outline_param)
|
2b2cde4e5e7c5d20b45d98c5710b69bd9064c9dd | jcfischer/suncontrol | /python/objects.py | 7,947 | 3.59375 | 4 | """Classes to define world objects"""
import random
import math_utils
import color_utils
class Object:
pos = (0, 0, 0)
vec = (0, 0, 0)
color = (0, 0, 0)
size = 0.0
max_size = 0.1
alive = True
def __init__(self, pos=(0, 0, 0), vec=(0, 0, 0), color=(0, 0, 0), size=0.1, ttl=10):
self.pos = pos
self.vec = vec
self.color = color
self.max_size = size
self.size = 0.1
self.ttl = ttl
self.alive = True
def move(self, dt):
if self.alive:
if self.size < self.max_size:
self.size += 0.1 * dt
self.pos = math_utils.add_vec(self.pos, self.vec, dt)
self.ttl -= dt
if self.ttl < 1:
r, g, b = self.color
r -= 0.1 * dt
g -= 0.1 * dt
b -= 0.1 * dt
self.color = (r, g, b)
self.alive = self.ttl > 0
def draw(self, coord):
"""returns an rgb tuple to add to the current coordinates color"""
color = self.color
distance = math_utils.dist(coord, self.pos)
(r, g, b) = (0.0, 0.0, 0.0)
if distance < self.size + 0.1:
dot = (1 / (distance + 0.0001)) # + (time.time()*twinkle_speed % 1)
# dot = abs(dot * 2 - 1)
dot = color_utils.remap(dot, 0, 10, 0.1, 1.1)
dot = color_utils.clamp(dot, -0.5, 1.1)
# dot **=2
dot = color_utils.clamp(dot, 0.2, 1)
r = color[0] * dot
g = color[1] * dot
b = color[2] * dot
new_color = (r, g, b)
return new_color
def init_random(self, boundary):
self.random_vec()
self.random_pos(boundary)
self.random_color()
self.random_size()
self.random_ttl()
def random_pos(self, boundary):
"""set the position to a random point within the boundary"""
min_bound, max_bound = boundary
x = random.uniform(min_bound[0], max_bound[0])
y = random.uniform(min_bound[1], max_bound[1])
z = random.uniform(min_bound[2], max_bound[2])
self.pos = (x, y, z)
def random_vec(self):
"""set a random movement vector"""
dx = random.uniform(-0.4, 0.4)
dy = random.uniform(-0.4, 0.4)
dz = random.uniform(-0.4, 0.4)
self.vec = (dx, dy, dz)
def random_color(self):
self.color = (random.random(), random.random(), random.random())
def random_size(self):
self.size = random.uniform(0.1, 0.5)
def random_ttl(self):
self.ttl = random.uniform(3, 20)
class Ball(Object):
"""a ball"""
class Color(Object):
"""a solid color that fades in and out over its ttl"""
def move(self, dt):
if self.alive:
self.ttl -= dt
if self.ttl < 1:
r, g, b = self.color
r -= 0.1 * dt
g -= 0.1 * dt
b -= 0.1 * dt
self.color = (r, g, b)
self.alive = self.ttl > 0
def draw(self, coord):
return self.color
def random_color(self):
self.color = (random.random()/2.0, random.random()/2.0, random.random()/2.0)
print(self.color)
class Grower(Object):
"""a ball that grows and fades as it gets too big"""
growing = True
def random_vec(self):
self.vec = (0, 0, 0)
def move(self, dt):
if self.alive:
if self.growing:
if self.size < self.max_size:
self.size += 0.3 * dt
else:
self.growing = False
else:
if self.size > 0.05:
self.size -= 0.3 * dt
else:
self.growing = True
self.ttl -= dt
if self.ttl < 1:
r, g, b = self.color
r -= 0.1 * dt
g -= 0.1 * dt
b -= 0.1 * dt
self.color = (r, g, b)
self.alive = self.ttl > 0
class Ring(Grower):
"""a ring that expands"""
speed = 0.8
def random_size(self):
self.max_size = random.uniform(0.4, 1)
self.size = 0.05
def move(self, dt):
if self.alive:
self.size += self.speed * dt
self.speed -= dt / 5
self.ttl -= dt
if self.ttl < 1:
r, g, b = self.color
r -= 0.1 * dt
g -= 0.1 * dt
b -= 0.1 * dt
self.color = (r, g, b)
self.alive = self.ttl > 0
def draw(self, coord):
"""returns an rgb tuple to add to the current coordinates color"""
color = self.color
distance = math_utils.dist(coord, self.pos)
(r, g, b) = (0.0, 0.0, 0.0)
if (distance > self.size - 0.07) and (distance < self.size + 0.07):
dot = 0.8
# # dot = abs(dot * 2 - 1)
# dot = color_utils.remap(dot, 0, 10, 0.1, 1.1)
# dot = color_utils.clamp(dot, -0.5, 1.1)
# # dot **=2
# dot = color_utils.clamp(dot, 0.2, 1)
r = color[0] * dot
g = color[1] * dot
b = color[2] * dot
new_color = (r, g, b)
return new_color
class Glider(Object):
"""a line in direction of the vector and size"""
p2 = (0, 0, 0)
direction = "x"
def random_vec(self):
"""set a random movement vector in one of the cardinal axis"""
self.direction = random.choice(["x", "y", "z"])
dx, dy, dz = 0.0, 0.0, 0.0
if self.direction == "x":
dx = random.uniform(-0.4, 0.4) * 3
if self.direction == "y":
dy = random.uniform(-0.4, 0.4) * 3
if self.direction == "z":
dz = random.uniform(-0.4, 0.4) * 3
self.vec = (dx, dy, dz)
def random_pos(self, boundary):
"""set the position to a random point at the boundary"""
min_bound, max_bound = boundary
x, y, z = 0.0, 0.0, 0.0
if self.direction == "x":
if self.vec[0] < 0:
x = max_bound[0]
else:
x = min_bound[0]
y = random.uniform(min_bound[1], max_bound[1])
z = random.uniform(min_bound[2], max_bound[2])
if self.direction == "y":
if self.vec[1] < 0:
y = max_bound[1]
else:
y = min_bound[1]
x = random.uniform(min_bound[0], max_bound[0])
z = random.uniform(min_bound[2], max_bound[2])
if self.direction == "z":
if self.vec[2] < 0:
z = max_bound[2]
else:
z = min_bound[2]
x = random.uniform(min_bound[0], max_bound[0])
y = random.uniform(min_bound[1], max_bound[1])
self.pos = (x, y, z)
def move(self, dt):
Object.move(self, dt)
self.p2 = math_utils.add_vec(self.pos, self.vec, -self.size)
def draw(self, coord):
"""returns an rgb tuple to add to the current coordinates color"""
color = self.color
(r, g, b) = (0, 0, 0)
dist_line = math_utils.dist_line_point(self.pos, self.p2, coord)
# only compute further if we are very close to the line already
if dist_line < 0.08:
distance = math_utils.dist_line_seg_point(self.pos, self.p2, coord)
if distance < self.size:
dot = (1 / (distance + 0.0001)) # + (time.time()*twinkle_speed % 1)
# dot = abs(dot * 2 - 1)
dot = color_utils.remap(dot, 0, 10, 0.1, 1.1)
dot = color_utils.clamp(dot, -0.5, 1.1)
# dot **=2
dot = color_utils.clamp(dot, 0.2, 1)
r = color[0] * dot
g = color[1] * dot
b = color[2] * dot
new_color = (r, g, b)
return new_color
|
2129040f84883d0879b8a9eebe595faf67cf6fdd | oman36/self-learning | /tutorial/4.More-Control-Flow-Tools/4.7.More-on-Defining-Functions/4.7.0.Function-properies.py | 779 | 3.640625 | 4 | def parent_func():
variable = 'Value'
other_var = 'Val2'
if other_var == 'Val1':
variable = 'Other value'
def nested_func(a, b, third_val=2):
return variable == a or third_val == b
return nested_func
func = parent_func()
print(repr(func.__name__))
# 'nested_func'
print(repr(func.__qualname__))
# 'parent_func.<locals>.nested_func'
print(repr(func.__module__))
# '__main__'
print(repr(func.__defaults__))
# (2,)
print(repr(func.__kwdefaults__))
# None
# None
print(len(func.__closure__))
# 1
print(repr(func.__closure__[0].cell_contents))
# 'Value'
print(func.__code__.co_cellvars)
# ()
print(func.__code__.co_freevars)
# ('variable',)
print(parent_func.__code__.co_cellvars)
# ('variable',)
print(parent_func.__code__.co_freevars)
# ()
|
004b87e4355a65e91d266c983198d238ca5de714 | UltraPythonCoder/PythonStuff | /FibbonacciSequence.py | 205 | 3.875 | 4 | i = int(input("How Many Numbers? "))
a = 1
b = 1
counter = 2
print("1")
print("1")
while counter < i:
if counter != 2:
a = c
c = a + b
print(c)
b = a
counter += 1
|
21a4cbab427b832ddef6ab324a9bdcd624c4da3e | Suhailhassanbhat/algorithm | /linear_regression.py | 1,471 | 3.921875 | 4 | import pandas as pd
import numpy as no
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
ca_api_data = pd.read_csv('apib12tx.csv')
print(ca_api_data.columns)
#make a histogram
grade12 = plt.figure(1)
ca_api_data['API12B'].hist()
# histogram of meals, which is pct of students
meals=plt.figure(2)
ca_api_data['MEALS'].hist()
ca_api_data.plot(kind="scatter", x='MEALS', y='API12B')
#set up basic regression analysis
x=ca_api_data[['MEALS']].values
y=ca_api_data[['API12B']].values
my_regression =LinearRegression()
my_regression.fit(x,y)
#make a scatter plot in blue and plot line in red
plt.scatter(x,y, color='blue')
#draw regression line in red
plt.plot(x, my_regression.predict(x), color='red', linewidth='1')
#what is the slope?
print(my_regression.coef_)
#what is the intercept(i.e. MEALS = 0)
print(my_regression.intercept_)
#what is the expected score for a school with 80 percent lower income students?
print(my_regression.predict([[80]]))
outperforming_schools = ca_api_data[(ca_api_data['MEALS']>=80)& (ca_api_data['API12B']>=900)]
print(outperforming_schools[['SNAME', 'MEALS', 'API12B']])
#get set up for statsmodels
X_stats = ca_api_data[['MEALS']].values
Y_stats = ca_api_data[['API12B']].values
X_stats=sm.add_constant(X_stats)
#create and print the model
my_model = sm.OLS(Y_stats, X_stats).fit()
my_predictions = my_model.predict(X_stats)
print(my_model.summary())
plt.show() |
74dac41e1a4a00b697cd38bdde409b56cdc220c7 | kaijie0102/H2-computing | /Assignments/Assignment 6.py | 2,417 | 4.09375 | 4 | #Qn 1
'''
class Pet:
def __init__(self,name,animal_type,age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
def set_name(self,name):
self.__name = name
def set_animal_type(self,animal_type):
self.__animal_type = animal_type
def set_age(self,age):
self.__age = age
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get_age(self):
return self.__age
def main():
name = input('Enter name: ')
Type = input('Enter animal type: ')
age = input('Enter age: ')
obj = Pet(name,Type,age)
print(obj.get_name(), 'is a', obj.get_animal_type(), 'and is', obj.get_age(),'years old.')
main()
'''
#Qn 2
'''
class Car:
def __init__(self,model,make,speed=0):
self.__year_model = model
self.__make = make
self.__speed = speed
def accelerate(self):
self.__speed += 5
def brake(self):
self.__speed -= 5
def get_speed(self):
return self.__speed
def main():
car = Car('Tesla','makeyourrmother')
for x in range(5):
car.accelerate()
print(car.get_speed())
for x in range(5):
car.brake()
print(car.get_speed())
main()
'''
#Qn 3
'''
class Data:
def __init__(self,name,address,age,number):
self.__name = name
self.__address = address
self.__age = age
self.__number = number
def set_name(self,name):
self.__name = name
def set_address(self,address):
self.__address = address
def set_age(self,age):
self.__age = age
def set_number(self,age):
self.__number = number
def get_name(self):
return self.__name
def get_address(self):
return self.__address
def get_age(self):
return self.__age
def get_number(self):
return self.__number
def main():
A = Data('Wei Hong','hci',99,12345678)
B = Data('Rosie','trashbin',999,912831)
C = Data('Yu peng','near taylor',1,1233445)
main()
'''
#Qn 4
'''
class RetailItem:
def __init__(self,item,units,price):
self.__item = item
self.__units = units
self.__price = price
def main():
Item1 = RetailItem('Jacket',12,59.95)
Item2 = RetailItem('Designer Jeans',40,34.95)
Item3 = RetailItem('Shirt',20,24.95)
main()
''' |
2e3c50f04fbe1fb7d3c8cab47d73e1d38db44dad | caw024/Myline | /draw.py | 1,213 | 4.0625 | 4 | from display import *
#eq of line is Ax+By+C=0
def draw_line( x0, y0, x1, y1, screen, color):
A = y1 - y0 #change in y
B = x0 - x1 #negative change in x
x = x0
y = y0
if B==0:
while y <= y1:
plot(screen,color,x,y)
y+=1
else:
m = -1.0*A/B #slope #octant 1
if ((1 > m) & (m >= 0)):
d = 2*A + B
while x <= x1:
plot(screen,color,x,y)
if d>0: #above line
y+=1
d+= 2*B
x+=1
d+=2*A #octant 2
elif m >= 1:
d = 2*B + A
while y<= y1:
plot(screen, color,x,y)
if d<0:
x+=1
d+=2*A
y+=1
d+=2*B
#octant 8 - not done
elif ((-1 < m) & (m < 0)):
d = 2*A-B
while x <= x1:
plot(screen,color,x,y)
if d<=0:
y-=1
d-=2*B
x+=1
d+=2*A #octant 7 - not done
else:
d = A - 2*B
while y >= y1:
plot(screen, color,x,y)
if d>0:
x+=1
d+=2*A
y-=1
d-=2*B
pass
|
ff53374b1d460fbc87e07b2ca7134073c61c6592 | helllo-ai/Project | /class1.py | 595 | 3.65625 | 4 | import csv
with open("project.csv",newline="")as f:
reader=csv.reader(f)
file_data=list(reader)
file_data.pop(0)
total_marks=0
total_entries=len(file_data)
for marks in file_data:
total_marks+=float(marks[1])
mean=total_marks/total_entries
print("Mean (Average) is -> "+str(mean))
import pandas as pd
import plotly.express as px
df=pd.read_csv("project.csv")
fig=px.scatter(df,x="Student Number",y="Marks")
fig.update_layout(shapes=[
dict(
type='line',
y0=mean,y1=mean,
x0=0,x1=total_entries
)
])
fig.update_yaxes(rangemode="tozero")
fig.show()
|
57943939f85a6a5537a75fb898afe1a75deb781f | decross1/hackerrank_30_days_of_code | /Day 13 of 30 Days.py | 734 | 4.15625 | 4 | ## Hackerrank: Day 13 of 30 Days of Code
from abc import ABCMeta, abstractmethod
class Book:
__metaclass__ = ABCMeta
def __init__(self, title, author):
self.title = title
self.author = author
@abstractmethod
def display():
pass
# Write MyBook class
class MyBook(Book):
def __init__(self, title, author, price):
Book.__init__(self, title, author)
self.price = str(price)
def display(self):
print("Title: " + self.title)
print("Author: " + self.author)
print("Price: " + self.price)
title = 'The Alchemist'
author = 'Paulo Coelho'
price = 248
new_novel = MyBook(title, author, price)
new_novel.display() |
06a2f274279e4245a663f434d4b75209bb7743c1 | Darshini-V-M/python-programming | /beginner level 1/print in words.py | 314 | 3.828125 | 4 | x=int(raw_input())
if(x==1):
print('One')
elif(x==2):
print('Two')
elif(x==3):
print('Three')
elif(x==4):
print('Four')
elif(x==5):
print('Five')
elif(x==6):
print('Six')
elif(x==7):
print('Seven')
elif(x==8):
print('Eight')
elif(x==9):
print('Nine')
elif(x==10):
print('Ten')
else:
print('invalid')
|
31c502d3bca2cd57d2bd0bb56c6ed3dd26ee3470 | Anirudh-Muthukumar/Python-Code | /Print all Root to Leaf paths of a Binary Tree.py | 1,055 | 3.78125 | 4 | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def rootToLeafPath(root):
res = []
q = [(root, [root.val])]
while q:
node, path = q.pop(0)
if not node.left and not node.right: # leaf node
res += path,
if node.left: # node has one child
q += (node.left, path + [node.left.val]),
if node.right: # node has one child
q += (node.right, path + [node.right.val]),
print("Single child nodes: ", res)
if __name__ == '__main__':
node8 = Node(8)
node5 = Node(5)
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node6 = Node(6)
node7 = Node(7)
node10 = Node(10)
node9 = Node(9)
node12 = Node(12)
node0 = Node(0)
root = node0
root.left = node1; root.right = node2;
node1.left = node3; node1.right = node4;
node2.left = node5; node5.right = node7;
node3.right = node6; node6.right = node8;
rootToLeafPath(root) |
e56d6b12b654bb05a417e63b5cb4db8e66346b93 | Empirio991/testing | /step3.py | 2,528 | 3.828125 | 4 | """Fizz Buzz game with a twist to it."""
import argparse
import json
class FizzBuzzGame:
"""FizzBuzz game class."""
def __init__(self, rules):
"""init method for the class."""
self.rulesDivisible = rules["divisible"]
self.rulesEndsWith = rules["ends"]
def buzzer(self, n: int) -> list:
"""Function generates FizzBuzz."""
output = []
for i in range(1, n+1):
answer_string = ""
for key in self.rulesDivisible.keys():
if i % int(key) == 0:
answer_string += self.rulesDivisible[key]
for key in self.rulesEndsWith.keys():
if (i - int(key)) % 10 == 0:
answer_string += self.rulesEndsWith[key]
if not answer_string:
answer_string = str(i)
output.append(answer_string)
return output
def output(self, outputList, outputType: str) -> None:
"""Prints the output using the desired method."""
outputTypeDict = {
"console": "console",
"file": "file",
"email": "email"
}
if outputType in outputTypeDict:
for ele in outputList:
print("{}: {}".format(outputTypeDict[outputType], ele))
else:
print("Output type is not defined, hence printing to console")
for ele in outputList:
print("{}: {}".format("console", ele))
def main():
""" Main method for the script."""
parser = argparse.ArgumentParser(description="get some input from users")
parser.add_argument('range', type=int, default=100, const=100, nargs='?',
help="enter the number to run the fizzbuzz game until")
parser.add_argument(
'--output', type=str, help="enter the type of output you desire the fizzbuzz to go into")
parser.add_argument(
'--rules', type=str, help="a json file that contians the rules for modified fizzbuzz game")
args = parser.parse_args()
fb = FizzBuzzGame(json.loads(args.rules))
result = fb.buzzer(args.range)
fb.output(result, args.output)
if __name__ == "__main__":
print("Hello, welcome to a Fizz Buzz game")
main()
"""
# sample input to console
#
# python3 step3.py 15 --rules '{
# "divisible":{
# "3": "Fizz",
# "5": "Buzz"
# },
# "ends":{
# "3": "Foo",
# "5": "Bar"
# }
# }'
given more time I will expand the database of the rules/output types
"""
|
cc308c8ceb9f299814d4fd0d1ef8d97007bba75f | DebashishSarkarDurjoy/SDES | /sdes.py | 8,517 | 3.859375 | 4 |
# S-DES functions in the form of list
IP = [2, 6, 3, 1, 4, 8, 5 , 7]
IPinverse = [4, 1, 3, 5, 7, 2, 8, 6]
P10 = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
P8 = [6, 3, 7, 4, 8, 5, 10, 9]
E_P = [4, 1, 2, 3, 2, 3, 4, 1]
P4 = [2, 4, 3, 1]
# the S0 table as 2d list
S0 = [
[1, 0, 3, 2],
[3, 2, 1, 0],
[0, 2, 1, 3],
[3, 1, 3, 2]
]
# the S1 table as 2d list
S1 = [
[0, 1, 2, 3],
[2, 0, 1, 3],
[3, 0, 1, 0],
[2, 1, 0, 3]
]
# a dictionary to map the permutation name to the permutation list
permutations = {
"P10" : P10,
"P8" : P8,
"P4" : P4,
"E_P" : E_P,
"IP" : IP,
"IP-1" : IPinverse
}
#convert a decimal number into binary number and print it
def decimalToBinaryRecurse(n, binArray):
if(n > 1):
# divide with integral result
# (discard remainder)
decimalToBinaryRecurse(n//2, binArray)
binArray.append(n%2)
# print(n%2, end=' ')
#this is the helper function for the recurse function
#takes decimal base number as input
#returns a list containing the equivalent binary number
def decimalToBinary(n, digits):
binArray = [] #declaring the list here to pass it to the recurse function
decimalToBinaryRecurse(n, binArray) #call the actual conversion function
if (digits > len(binArray)):
for i in range(0, digits - len(binArray)):
binArray.append(0)
if (binArray[0] == 1):
temp = binArray.pop(0)
binArray.append(temp)
return binArray
#split input string of binary numbers into a list of binary numbers
#takes in a ' ' separated string
#returns a list
def stringToList(input):
theList = input.split() #split based on space
return theList
#takes in a list of string and a permutation name and applies it on
#the list of string and returns the result as a list
def applyP(charList, permutationName):
result = []
for index in permutations[permutationName]: #uses the values from the dictionary
result.append(charList[index - 1])
return result
#performs the binary left shift by popping the first element and
#inserting it at the end
#calling it n times will perform left-shift-n
#returns the result as a list
def leftShift(arr):
leftHalf = arr[: 5] #takes only the left side 5 digits
rightHalf = arr[5: ] #takes only the right side 5 digits
temp = leftHalf.pop(0) #removes the first element, stores it in temp
leftHalf.append(temp) #inserts the temp at the end
temp = rightHalf.pop(0) #removes the first element, stores it in temp
rightHalf.append(temp) #inserts the temp at the end
return leftHalf + rightHalf
def powerOf2(power):
result = 1
for i in range(power):
result = 2 * result
return int(result)
#performs binary XOR operation
#returns a list
def XOR(arr1, arr2):
result = []
for i in range(len(arr1)):
if arr1[i] != arr2[i]: #if two digits are different, it appends 1
result.append(1)
else:
result.append(0) #otherwise appends 0
return result
#converts list containing binary numbers into its decimal base equivalent
def binToDec(arr):
result = 0
for i in range(len(arr)): #loops over the lenght of arr
if arr[i] == 1:
#this is basically this: result = result + 2 ^ position of 1 in arr
result = result + powerOf2(len(arr) - i - 1)
return int(result)
#takes a row and col integer and returns a value from the corresponding
#row and col in the 2d list S0
def valToS0(row, col):
return S0[row][col]
#takes a row and col integer and returns a value from the corresponding
#row and col in the 2d list S1
def valToS1(row, col):
return S1[row][col]
#the function that uses K1
#takes in an array, Key1 and a boolean value
def fk1(arr, K1, decryption = False):
#takes the left-portion of arr and applies E/P
rightEP = applyP(arr[4: ], "E_P")
#then performs XOR on the returned value
rightEP = XOR(rightEP, K1)
r1 = []
c1 = []
#gets the row and col to fetch data from S0
r1.append(rightEP[0])
r1.append(rightEP[3])
c1.append(rightEP[1])
c1.append(rightEP[2])
#gets the row and col to fetch data from S1
r2 = []
c2 = []
r2.append(rightEP[4])
r2.append(rightEP[7])
c2.append(rightEP[5])
c2.append(rightEP[6])
#gets binary equivalent of the left part
leftPart = decimalToBinary(valToS0(binToDec(r1), binToDec(c1)), 2)
#gets binary equivalent of the right part
rightPart = decimalToBinary(valToS1(binToDec(r2), binToDec(c2)), 2)
temp = leftPart + rightPart
temp = applyP(temp, "P4") #applies P4 on the result
temp = XOR(temp, arr[: 4]) #applies XOR on temp and righ-portion of arr
temp = temp + arr[4: ] #concatenates left-portion of arr with temp
if decryption == True:
#if decrypting then apply IP-1 and return the result
tempIPinverse = applyP(temp, "IP-1")
return tempIPinverse
#otherwise perform switch and return the result
switched = arr[4:] + temp
return switched
#the function that uses K2
#takes in an array, Key2 and a boolean value
def fk2(arr, K2, decryption = False):
#takes the left-portion of arr and applies E/P
rightEP = applyP(arr[4: ], "E_P")
#then performs XOR on the returned value
rightEP = XOR(rightEP, K2)
r1 = []
c1 = []
#gets the row and col to fetch data from S0
r1.append(rightEP[0])
r1.append(rightEP[3])
c1.append(rightEP[1])
c1.append(rightEP[2])
r2 = []
c2 = []
#gets the row and col to fetch data from S1
r2.append(rightEP[4])
r2.append(rightEP[7])
c2.append(rightEP[5])
c2.append(rightEP[6])
#gets binary equivalent of the left part
leftPart = decimalToBinary(valToS0(binToDec(r1), binToDec(c1)), 2)
#gets binary equivalent of the right part
rightPart = decimalToBinary(valToS1(binToDec(r2), binToDec(c2)), 2)
temp = leftPart + rightPart
temp = applyP(temp, "P4") #applies P4 on the result
temp = XOR(temp, arr[: 4]) #applies XOR on temp and righ-portion of arr
if decryption == True:
#if decrypting then perform switch and return the result
switched = arr[4:] + temp
return switched
#otherwise perform concatenation with the left-portion of arr
temp = temp + arr[4:]
temp = applyP(temp, "IP-1") #apply IP-1 on temp and return temp
return temp
def decrypt():
#get use input for Ciphertext
inputTEXT = input("Enter Ciphertext: ")
inputArr = []
for c in inputTEXT:
inputArr.append(int(c))
#get use input for Key
inputKEY = input("Enter K: ")
inputKey = []
for c in inputKEY:
inputKey.append(int(c))
print("K1: ", end="")
# applies P10 on inputKey, then left-shift then P8
K1 = applyP(leftShift(applyP(inputKey, "P10")), "P8")
print(K1)
print("K2: ", end="")
# applies P10 on inputKey,
# then left-shift 3x
# then applies P8
K2 = applyP((leftShift(leftShift(leftShift(applyP(inputKey, "P10"))))), "P8")
print(K2)
result = applyP(inputArr, "IP") # applies IP on inputArr
result = fk2(result, K2, decryption = True)
result = fk1(result, K1, decryption = True)
print("Plaintext: ", end="")
print(result)
# print(stringToList("A B C D E F G H I J"))
# print(applyP(stringToList("A B C D E F G H I J"), "IP"))
def encrypt():
#get use input for Plaintext
inputTEXT = input("Enter Plaintext: ")
inputArr = []
for c in inputTEXT:
inputArr.append(int(c))
#get user input for Key
inputKEY = input("Enter Key: ")
inputKey = []
for c in inputKEY:
inputKey.append(int(c))
inputIP = applyP(inputArr, "IP") # applies IP on inputArr
print("K1: ", end="")
# applies P10 on inputKey, then left-shift then P8
K1 = applyP(leftShift(applyP(inputKey, "P10")), "P8")
print(K1)
print("K2: ", end="")
# applies P10 on inputKey,
# then left-shift 3x
# then applies P8
K2 = applyP((leftShift(leftShift(leftShift(applyP(inputKey, "P10"))))), "P8")
print(K2)
result = fk1(inputIP, K1)
result = fk2(result, K2)
print("Ciphertext: ", end="")
print(result)
# this function shows the menu and expects a user input
# calls the appropriate function based on the user input
def showMenu():
print("1. Encrypt.")
print("2. Decrypt.")
option = input(">> ")
return int(option)
option = showMenu()
if option == 1:
encrypt()
else:
decrypt()
|
a1f1e528df2218b1551941e39254d5d0af99e24c | Dimple16/Winsound | /sound.py | 1,748 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 10 06:31:27 2018
@author: DEV
"""
import winsound
#The winsound module provides access to the basic sound-playing machinery provided by Windows platforms. It includes functions and several constants
print("Binary Representation of sound")
print("Enter the duration of each note (in ms)?")
print("e.g. 200")
rate = int(input(">"))
print("Enter a 4-bit binary note")
print("Or more than one note separated by spaces")
"""
print("Notes:")
print("0000 = no sound")
print("0001 = Low C")
print("0010 = D")
print("0011 = E")
print("0100 = F")
print("0101 = G")
print("0110 = A")
print("0111 = B")
print("1000 = High C")
print("0101 0101 0101 0010 0011 0011 0010 0000 0111 0111 0110 0110 0101")
"""
soundBinary = input(">")
print("e.g: ")
for note in soundBinary.split():
if note == "A": #rest
freq = 392
elif note == "B": #low c
freq = 220
elif note == "C": #d
freq = 38
elif note == "D": #e
freq = 124
elif note == "E": #f
freq = 74
elif note == "F": #g
freq = 784
elif note == "G": #a
freq = 165
elif note == "H": #b90
freq = 62
elif note == "I": #high c
freq =110
elif note == "J":
freq= 1000
winsound.Beep(freq, rate)
#Beep the PC’s speaker. The frequency parameter specifies frequency, in hertz, of the sound, and must be in the range 37 through 32,767. The duration parameter specifies the number of milliseconds the sound should last. If the system is not able to beep the speaker, RuntimeError is raised. |
5152133f8e590f6552471a7f5796d7bdc697d8cf | ukarthikvarma/DataAnalysisProjects | /sea-level-predictor/sea_level_predictor.py | 1,591 | 3.515625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import linregress
def draw_plot():
# Read data from file
df = pd.read_csv('epa-sea-level.csv')
new_year = []
for i in range(2014,2050):
new_year.append(i)
i = i+1
empty_array = np.empty((36,4))
empty_array[:] = np.NaN
new_array = np.column_stack((new_year,empty_array))
new_df = pd.DataFrame(data=np.concatenate((df.values,new_array)),columns=df.columns)
# Create scatter plot
fig , ax = plt.subplots(figsize=(17,10))
ax.scatter(x=df['Year'],y=df['CSIRO Adjusted Sea Level'],label='Original Data')
# Create first line of best fit
x = df['Year'].values
y = df['CSIRO Adjusted Sea Level'].values
slope , intercept, r_value, p_value, std_err = linregress(x,y)
ax.plot(new_df['Year'],intercept+slope*(new_df['Year']),'r',label='Best Fit Line to 2050')
# Create second line of best fit
df_2000 = df[df['Year'] >= 2000]
new_x = df_2000['Year'].values
new_y = df_2000['CSIRO Adjusted Sea Level'].values
new_2000df = new_df[new_df['Year'] >= 2000]
slope , intercept, r_value, p_value, std_err = linregress(new_x,new_y)
ax.plot(new_2000df['Year'],intercept+slope*(new_2000df['Year']),'g',label='Best Fit line from 2000')
# Add labels and title
ax.set_xlabel('Year')
ax.set_ylabel('Sea Level (inches)')
ax.set_title('Rise in Sea Level')
ax.legend()
# Save plot and return data for testing (DO NOT MODIFY)
plt.savefig('sea_level_plot.png')
return plt.gca() |
c91d7a0cb0631bd0fb7da78c41adf651719739d9 | chlomcneill/advent-of-code-2018 | /Python/Day 2/Day2Part1.py | 852 | 3.78125 | 4 | import string
def letter_repeats_exactly_2_times(n):
alphabet = list(string.ascii_lowercase)
repeats = []
for letter in alphabet:
if n.count(letter) == 2:
repeats.append(letter)
return repeats
def letter_repeats_exactly_3_times(n):
alphabet = list(string.ascii_lowercase)
repeats = []
for letter in alphabet:
if n.count(letter) == 3:
repeats.append(letter)
return repeats
f = open("/Users/mcneillc/Documents/advent-of-code-2018/Day 2/Day2input.txt","r")
IDs = f.readlines()
f.close()
IDs = [ID.strip('\n') for ID in IDs]
double = 0
triple = 0
for ID in IDs:
if letter_repeats_exactly_2_times(ID) != None:
double += 1
for ID in IDs:
if letter_repeats_exactly_3_times(ID) != None:
triple += 1
checksum = double * triple
print(checksum) |
abee39af450089a4901a1237b1ba9fb0b746bb9e | joshuap233/algorithms | /tree/binary_search_tree.py | 3,138 | 4.1875 | 4 | from typing import Optional
"""
最麻烦的删除操作:
需要删除的节点为 A
1. A 为树叶,直接删除
2. A 只有一个儿子, 儿子代替父节点即可
3. A 有两个儿子, 找到 A 右子树中最小的节点删除, 然后代替 A
测试(偷懒用 leetcode 测试):
查找: leetcode T700
插入: leetcode T701
删除: leetcode T450
验证: leetocde T98
"""
class Node:
# 可以添加一个 key 字段, 这里仅使用 val 来查找
def __init__(
self, val: int,
left: Optional['Node'] = None,
right: Optional['Node'] = None
):
self.val: int = val
self.left: Optional['Node'] = left
self.right: Optional['Node'] = right
class BSTree:
def __init__(self):
self.root: Optional[Node] = None
def insert(self, val: int) -> None:
def Insert(node: Optional[Node]) -> Node:
if not node:
return Node(val)
if val > node.val:
node.right = Insert(node.right)
else:
node.left = Insert(node.left)
return node
self.root = Insert(self.root)
def delete(self, val: int) -> None:
def findMin(node: Node) -> int:
while node.left:
node = node.left
return node.val
def Delete(node: Optional[Node], target: int) -> Optional[Node]:
if not node:
return node
if target > node.val:
node.right = Delete(node.right, target)
elif target < node.val:
node.left = Delete(node.left, target)
else:
if not (node.left and node.right):
return node.left or node.right
node.val = findMin(node.right)
node.right = Delete(node.right, node.val)
return node
self.root = Delete(self.root, val)
return self.root
def find(self, val: int) -> Node:
def Find(node: Optional[Node]) -> Optional[Node]:
if not node:
return None
if node.val == val:
return node
return Find(node.left) \
if val < node.val else Find(node.right)
return Find(self.root)
def valid(self):
# 验证是否为二叉搜索树
prev = float('-inf')
def Valid(node: Node) -> bool:
if not node:
return True
nonlocal prev
if Valid(node.left):
if node.val < prev:
return False
prev = node.val
return Valid(node.right)
return False
return Valid(self.root)
def __bool__(self) -> bool:
return self.root is not None
if __name__ == '__main__':
from plot import print_tree
from random import randint
tree = BSTree()
for i in range(10):
new = randint(0, 20)
while tree.find(new):
new = randint(0, 20)
tree.insert(new)
assert tree.valid()
print_tree(tree.root)
|
22a003978a9e99bf292e67b0835e901aeea02578 | GeraJuarez/code-analysis-python | /lab2/test_myPowerList.py | 2,527 | 4.09375 | 4 | import unittest
from MyPowerList import MyPowerList as MPL
class TestingMyPowerList(unittest.TestCase):
"""MyPowerList unit tests.
"""
def test_add_item_count(self):
"""Test number of additions corresponds to the list size.
"""
mpl = MPL()
mpl.add_item(1)
expected = 1
result = len(mpl.power_list)
self.assertEqual(expected, result,
f'Result: {result}, expectd: {expected}')
mpl.add_item(2)
mpl.add_item(20)
expected = 3
result = len(mpl.power_list)
self.assertEqual(expected, result,
f'Result: {result}, expectd: {expected}')
def test_add_item_exists(self):
"""Test consistency of the list when adding the first element.
"""
mpl = MPL()
mpl.add_item([])
expected = []
result = mpl.power_list[0]
self.assertEqual(expected, result,
f'Result: {result}, expectd: {expected}')
def test_remove_item(self):
"""Test consistency of the list after removing an element.
"""
mpl = MPL()
mpl.add_item(1)
mpl.add_item('string')
mpl.add_item([1])
mpl.remove_item_at(0)
expected = 'string'
result = mpl.power_list[0]
self.assertEqual(expected, result,
f'Result: {result}, expectd: {expected}')
def test_remove_item_bounds(self):
"""Test IndexError when removing an item.
"""
mpl = MPL()
mpl.add_item(1)
self.assertRaises(IndexError, mpl.remove_item_at, 1)
def test_read_from_file(self):
"""Test data from file is saved correctly into the list
"""
mpl = MPL()
mpl.read_from_txt_file('sample.txt')
expected = '1'
result = mpl.power_list[0]
self.assertEqual(expected, result,
f'Result: {result}, expectd: {expected}')
def test_read_from_file_error1(self):
"""Test IOError when reading non-txt files.
"""
mpl = MPL()
mpl.add_item(1)
self.assertRaises(IOError, mpl.read_from_txt_file, 'sample.csv')
def test_read_from_file_error2(self):
"""Test IOError when reading non-existent files
"""
mpl = MPL()
mpl.add_item(1)
self.assertRaises(IOError, mpl.read_from_txt_file, 'sample2.txt')
if __name__ == "__main__": # pragma: no cover
unittest.main()
|
c24446d278e7fbe80357a66660a188ae2a5af11a | daniel-bray/skillshare-py-chattybot | /Problems/The first digit of a two-digit number/task.py | 70 | 3.609375 | 4 | # put your python code here
num = int(input(""))
print(int(num / 10))
|
8f1f1b6c59c52e2b38478dad546a6f2393d10548 | greenfox-velox/danielliptak | /week4/day3/9.py | 603 | 4.21875 | 4 | # create a 300x300 canvas.
# create a square drawing function that takes 1 parameter:
# the square size
# and draws a square of that size to the center of the canvas.
# draw 3 squares with that function.
from tkinter import *
root = Tk()
width = 300
height = 300
canvas = Canvas(root, width=width, height=height)
canvas.pack()
def draw_line(x):
startx = (width/2) - (x/2)
starty = (height/2) - (x/2)
endx = (width/2) + (x/2)
endy = (height/2) + (x/2)
return canvas.create_rectangle(startx, starty, endx, endy, fill='lime green')
draw_line(100)
draw_line(50)
draw_line(20)
root.mainloop()
|
bf1f22643f12cfeeb3e389f7c96a104b5d5aff89 | nunes-moyses/Projetos-Python | /Projetos Python/pythonexercicios/des010.py | 166 | 3.640625 | 4 | p = float(input('Qual o preço do produto?'))
pd = p - (p * 0.05)
print('O produto que custava {}, na promoção com desconto de 5% vai custar {:.2f}'.format(p, pd))
|
e17f56117b544d5bba1e98c326f5587b2a283905 | Jasmine-2002/Python | /xxx.py | 348 | 3.71875 | 4 | import re
def is_palindrome_1(tmp_str):
for i in range(len(tmp_str)):
if tmp_str[i] != tmp_str[-(i+1)]:
return False
return True
x=input().lower()
r='[’!"#$%&\'()*+,-./:;<=>?@[ \\]^_`{|}~\n。!,]+'
a=re.sub(r,'',x)
b=list(a.replace(" ",''))
n=is_palindrome_1(b)
if n==True:
print('yes')
else:
print('no') |
d16a53c256191673da688a32f34bc12cf7c2be40 | Muhodari/python-complete-crash-Course | /E.word_Replacement_exercise/wordReplacement.py | 236 | 4.21875 | 4 | sentence = input('Enter the sentence:')
wordToReplace = input('Enter word to replace: ')
replaceWordWith = input("Enter the word to replace with: ")
finalSentence = sentence.replace(wordToReplace, replaceWordWith)
print(finalSentence)
|
1c0df7b32b402e67a7df801a9279c05f9a67daea | vineel2014/Pythonfiles | /python_exercises/20project_ideas/emailsender.py | 1,055 | 3.859375 | 4 | import smtplib
from tkinter import *
import tkinter.messagebox as mbox
def sent():
to =e1.get()
gmail_user = 'Enter your gmail username'
gmail_pwd = 'Enter your gmail password'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:from vineel python program\n'
mbox.showinfo('INFORMATION',header)
msg = header + '\n This is python mail sending program from python \n\n'
smtpserver.sendmail(gmail_user, to, msg)
mbox.showinfo('Yes','Mail sent Sucessfully')
smtpserver.close()
def quit():
master.destroy()
master = Tk()
Label(master, bg="lime",text="Email id").grid(row=0)
e1 = Entry(master)
e1.grid(row=0, column=1)
master["bg"] = "green"
Button(master, text='send',bg="lime", command=sent).grid(row=3, column=0, sticky=W, pady=4)
Button(master, text='Quit',bg="lime", command=quit).grid(row=3, column=3, sticky=W, pady=4)
mainloop()
|
e567fb8130105586704047a59821f5366110b3dc | xeladock/Python_wb | /Black Box(Smoke)/scratches/3.1.1.py | 211 | 3.84375 | 4 | def f(x):
if x<=-2:
print(1-((x+2)**2))
return ''
elif -2<x<=2:
print(-x/2)
return ''
elif 2<x:
print(1+((x-2)**2))
return''
x=int(input())
print(f(x)) |
eb4a8eb6f061a5bab38d0ece4aa000ae1ce08b36 | sheelabhadra/LeetCode-Python | /324_Wiggle_Sort_II.py | 755 | 4.09375 | 4 | #Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
#Example:
#(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].
#(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2].
## SOLUTION: Sort the array in descending order. Divide it into 2 halves. Insert the lower half in
# odd indices and the upper half in the even indices. Time: O(nlogn), Space: O(1)
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort()
half = len(nums[::2])
nums[::2], nums[1::2] = nums[:half][::-1], nums[half:][::-1]
|
553fdf08c6102c6c016e8464f6ebce3e26a2b96a | robj137/advent_of_code | /2016/day01.py | 1,448 | 3.796875 | 4 | import datetime as dt
from collections import defaultdict
class Traveler:
def __init__(self):
self.position = 0 + 0j
self.direction = 0 + 1j
self.visited = {}
self.visited_twice = []
def get_position(self):
return self.position
def get_distance(self, val):
return abs(int(val.real)) + abs(int(val.imag))
def get_current_distance(self):
return self.get_distance(self.position)
def travel(self, instruction):
if instruction[0] == 'L':
self.direction *= 1j
else:
self.direction *= -1j
distance = int(instruction[1:])
for x in range(distance):
self.position += self.direction
if self.position not in self.visited:
self.visited[self.position] = 0
else:
self.visited_twice.append(self.position)
def main():
with open('inputs/day1.txt') as f:
x = f.read()
directions = [y.strip().strip('\n') for y in x.split(',')]
traveler = Traveler()
for d in directions:
traveler.travel(d)
pos = traveler.get_position()
print('Part a: Easter Bunny HQ is {} blocks away'.format(traveler.get_current_distance()))
print('Part b: on second thought, Easter Bunny HQ is really {} blocks away'.format(traveler.get_distance(traveler.visited_twice[0])))
if __name__ == '__main__':
begin = dt.datetime.now()
main()
diff_time = dt.datetime.now() - begin
print('That took {:.3f} seconds'.format(diff_time.seconds + 1e-6*diff_time.microseconds))
|
72dc14e0441e6888d728eb9822c5d94becd03f03 | Austin-Long/CS5 | /hw1pr2.py | 1,692 | 3.828125 | 4 |
# CS5 Gold, Lab1 part 2
# Filename: hw1pr2.py
# Name:
# Problem description: First few functions!
def dbl(x):
"""Result: dbl returns twice its argument
Argument x: a number (int or float)
Spam is great, and dbl("spam") is better!
"""
return 2*x
def tpl(x):
"""Return value: tpl returns thrice its argument
Argument x: a number (int or float)
"""
return 3*x
def sq(x):
"""Return value: sq returns the square of its Argument
argument x: a number (int or float)
"""
return x*x
def interp(low, hi, fraction):
"""Return value: the floating-point value that is fraction of the way between low and hi.
Argument: three numbers, low, hi, fraction
"""
return low + ((hi-low)*fraction)
def checkends(s):
"""Return value: True if first character in s is the same as last character
Argument s: a string s
"""
return s[0] == s[len(s)-1]
def flipside(s):
"""Return value: a string whose first half is s's second half and whose second half is s's second half.
Argument s: a string s
"""
round = len(s)//2
return s[round:len(s)] + s[0:round]
def convertFromSeconds(s):
"""Return value: a list of four nonnegative
integers that represents that number of seconds in a more conventional unit of time:
Number of days, number of hours, number of minutes, number of seconds.
Argument s: a nonnegative integer number of seconds s
"""
days = s // (24*60*60) # Number of days
s = s % (24*60*60) # The leftover
hours = s // (60*60)
s = s % (60*60)
minutes = s // 60
seconds = s % 60
return [days, hours, minutes, seconds]
|
e55a9dac4da160dc2456cd097eb6923aded8e9a8 | jjasonkal/Codewars | /kata/kata_solved/calculator/CalculatorTests.py | 1,557 | 3.640625 | 4 | import unittest
from kata_solved.calculator.Calculator import Calculator
class MyTestCase(unittest.TestCase):
def test_add(self):
test_data = [
('1.1 + 2.2 + 3.3', 6.6),
('2 + 3', 5),
('2 + 2 + 2 + 2', 8)]
for test_input, test_output in test_data:
self.assertEqual(Calculator().evaluate(test_input), test_output)
def test_minus(self):
test_data = [
('2 - 3 - 4', -5),
('2 - 3', -1),
('2 - 2 - 2 - 2', -4)]
for test_input, test_output in test_data:
self.assertEqual(Calculator().evaluate(test_input), test_output)
def test_mul(self):
test_data = [
('2 * 3 * 4', 24),
('2 * 2', 4),
('2 * 2 * 2 * 2', 16)]
for test_input, test_output in test_data:
self.assertEqual(Calculator().evaluate(test_input), test_output)
def test_div(self):
test_data = [
('2 / 4', 0.5),
('2 / 2', 1),
('2 / 2 / 2 / 2', 0.25)]
for test_input, test_output in test_data:
self.assertEqual(Calculator().evaluate(test_input), test_output)
def test_complex(self):
test_data = [
('2 + 3 * 4 / 3 - 6', 0),
('10 * 5 / 2', 25),
('1 / 2 * 4 + 2', 4),
('1 + 1 / 2 * 4 + 2 * 5', 13)]
for test_input, test_output in test_data:
self.assertEqual(Calculator().evaluate(test_input), test_output)
if __name__ == '__main__':
unittest.main()
|
2b87c24be4f7384458af7bab356fcc4f34112dfa | Daniyal963/LAB-05 | /Program 1.py | 273 | 3.59375 | 4 | print("Daniyal Ali - 18B-096-CS(A)")
print("Program 1")
count = 0
f = eval(input("Please enter your final loop where u want to end the loop"))
while (count<7):
print("The value of Count",count)
count = count+1
print("I am using while loop", count, "time")
|
b2aa907950c2fe53e676d6f6b71d9099f9656fe0 | BradenRowlands/CP1404Practicals | /Prac04/Lottery.py | 269 | 3.734375 | 4 | import random
thelist = []
amountOfPicks = input("Please enter the amount of picks you would like")
for i in range (int(amountOfPicks)):
for number in range(6):
number = random.randint(1,45)
thelist.append(number)
print(thelist)
thelist = [] |
e2402b603f4e217ad83e6a3ecb82af98e8679f86 | rao003/StartProgramming | /PYTHON/einstieg_in_python/Beispiele/spiel_oop.py | 1,524 | 3.671875 | 4 | import random
# Klasse "Spiel"
class Spiel:
def __init__(self):
# Start des Spiels
random.seed()
self.richtig = 0
# Anzahl bestimmen
self.anzahl = -1
while self.anzahl<0 or self.anzahl>10:
try:
print("Wieviele Aufgaben (1 bis 10):")
self.anzahl = int(input())
except:
continue
def spielen(self):
# Spielablauf
for i in range(1,self.anzahl+1):
a = Aufgabe(i, self.anzahl)
print(a)
self.richtig += a.beantworten()
def __str__(self):
# Ergebnis
return "Richtig: " + str(self.richtig) \
+ " von " + str(self.anzahl)
# Klasse "Aufgabe"
class Aufgabe:
# Aufgabe initialisieren
def __init__(self, i, anzahl):
self.nr = i
self.gesamt = anzahl
# Aufgabe stellen
def __str__(self):
a = random.randint(10,30)
b = random.randint(10,30)
self.ergebnis = a + b
return "Aufgabe " + str(self.nr) \
+ " von " + str(self.gesamt) + " : " \
+ str(a) + " + " + str(b)
# Aufgabe beantworten
def beantworten(self):
try:
if self.ergebnis == int(input()):
print(self.nr, ": *** Richtig ***")
return 1
else:
raise
except:
print(self.nr, ": *** Falsch ***")
return 0
# Hauptprogramm
s = Spiel()
s.spielen()
print(s)
|
c4c46ee7d884cf30ddbcd1d71e4d6342c58fcf6b | Reebs296/Okanagan-Engineering-Competition-2021-Team-EngiCoders | /main.py | 8,772 | 3.859375 | 4 | import random
#import gui library
import tkinter as tk
#create tile class that is either a stone or a bomb
class Tile:
#initialize the tile
def __init__(self, x, y, bomb):
self.x = x
self.y = y
self.bomb = bomb
self.bombnum = 0
self.revealed = False
self.flagged = False
#create board class that holds array of tiles
class Board:
#initialize the board with x and y size and number of bombs
def __init__(self, x, y, bombs):
self.x = x
self.y = y
self.bombs = bombs
self.tiles = []
#add Tile objects to the tiles array and randomly place bombs until the number of bombs is reached
def add_tiles(self):
for i in range(self.x):
for j in range(self.y):
self.tiles.append(Tile(i, j, False))
for i in range(self.bombs):
rand_x = random.randint(0, self.x - 1)
rand_y = random.randint(0, self.y - 1)
self.tiles[rand_x + rand_y * self.x].bomb = True
#is valid checks if the tile is within the bounds of the board
def is_valid(self, x, y):
if x < 0 or x >= self.x:
return False
if y < 0 or y >= self.y:
return False
return True
#count the number of bombs adjacent to the tile
def count_adjacent_bombs(self, x, y):
count = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
if self.is_valid(x + i, y + j):
if self.tiles[(x + i) + (y + j) * self.x].bomb == True:
count += 1
return count
#loop through the tiles array and count the number of bombs adjacent to each tile
def count_bombs(self):
for i in range(self.x):
for j in range(self.y):
if self.tiles[i + j * self.x].bomb == False:
#set bomnum equal to the amount of bombs around the tile
self.tiles[i + j * self.x].bombnum = self.count_adjacent_bombs(i, j)
else:
self.tiles[i + j * self.x].bombnum = -1
def clicked_tile(self, x, y):
#if the tile is a bomb, game over
if self.tiles[x + y * self.x].bomb == True:
return False
#if the tile is not a bomb, reveal the tile
else:
self.tiles[x + y * self.x].revealed = True
#if the tile is not a bomb and has no adjacent bombs, reveal all adjacent tiles
if self.tiles[x + y * self.x].bombnum == 0:
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
if self.is_valid(x + i, y + j):
if self.tiles[(x + i) + (y + j) * self.x].revealed == False:
self.clicked_tile(x + i, y + j)
return True
def print_board(self):
for i in range(self.x):
for j in range(self.y):
if self.tiles[i + j * self.x].revealed == False:
print("[ ]", end = "")
#if the tile is a bomb and is revealed, print a bomb
elif self.tiles[i + j * self.x].bomb == True and self.tiles[i + j * self.x].revealed == True:
print("[B]", end = "")
#if the tile is flagged, print a flag
elif self.tiles[i + j * self.x].flagged == True:
print("[F]", end = "")
else:
print("[" + str(self.tiles[i + j * self.x].bombnum) + "]", end = "")
print("")
print("")
#check if the game is over
#if all unrevealed tiles are bombs, you win
def check_win(self):
count = 0
for i in range(self.x):
for j in range(self.y):
if self.tiles[i + j * self.x].revealed == False:
count += 1
if count == self.bombs:
return True
else:
return False
#create board object
board = Board(10, 10, 10)
#difficulty buttons clicked function based on the bomb and size of the board
def difficulty_clicked(x, y, bombs, popup):
board.x = x
board.y = y
board.bombs = bombs
board.add_tiles()
board.count_bombs()
board.print_board()
popup.destroy()
def flag_tile(x, y):
board.tiles[x + y * board.x].flagged = True
def clicked_tile(x, y, button):
#if the tile is not revealed and not flagged, reveal the tile
if board.tiles[x + y * board.x].revealed == False and board.tiles[x + y * board.x].flagged == False:
#if the tile is a bomb, game over
if board.tiles[x + y * board.x].bomb == True:
board.tiles[x + y * board.x].revealed = True
board.print_board()
print("Game over")
#popup window to show game over
popup = tk.Tk()
popup.title("Game Over")
popup.geometry("200x100")
#create label to show game over
label = tk.Label(popup, text = "Game Over")
label.pack()
#create button to restart the game
button = tk.Button(popup, text = "Exit", command = lambda: exit())
button.pack()
popup.mainloop()
return False
#if the tile is not a bomb, reveal the tile
else:
board.tiles[x + y * board.x].revealed = True
#if the tile is not a bomb and has no adjacent bombs, reveal all adjacent tiles and set the button to the number of adjacent bombs
if board.tiles[x + y * board.x].bombnum == 0:
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
if board.is_valid(x + i, y + j):
if board.tiles[(x + i) + (y + j) * board.x].revealed == False:
clicked_tile(x + i, y + j, button)
board.print_board()
return True
#create main function
def main():
while True:
#create a popup window with a difficulty button for each difficulty
popup = tk.Tk()
popup.title("Difficulty")
popup.geometry("200x200")
#create a button for each difficulty
easy_button = tk.Button(popup, text = "Easy", command = lambda: difficulty_clicked(9, 9, 10, popup))
medium_button = tk.Button(popup, text = "Medium", command = lambda: difficulty_clicked(16, 16, 40, popup))
hard_button = tk.Button(popup, text = "Hard", command = lambda: difficulty_clicked(16, 30, 99, popup))
#add the buttons to the popup window
easy_button.pack()
medium_button.pack()
hard_button.pack()
#show the popup window
popup.mainloop()
#destroy the popup window
#create a game window
game_window = tk.Tk()
#set the game window title to Minesweeper
game_window.title("Minesweeper")
#set the game window size to 500x500
game_window.geometry("500x500")
#create a grid of buttons based on the board size
for i in range(board.x):
for j in range(board.y):
#create a button for each tile that you can right click on to flag the tile and left click to reveal the tile
button = tk.Button(game_window, text = "", command = lambda x = i, y = j: clicked_tile(x, y, button))
button.bind("<Button-1>", lambda event, x = i, y = j: clicked_tile(x, y, button))
button.bind("<Button-3>", lambda event, x = i, y = j: flag_tile(x, y, button))
#flag the tile by right clicking on it
button.grid(row = i, column = j)
#if all unreavealed tiles are bombs, you win
if board.check_win() == True:
print("You win")
#popup window to show you win
popup = tk.Tk()
popup.title("You Win")
popup.geometry("200x100")
#create label to show you win
label = tk.Label(popup, text = "You Win")
label.pack()
#create button to restart the game
button = tk.Button(popup, text = "Exit", command = lambda: exit())
button.pack()
popup.mainloop()
#destroy the popup window
popup.destroy()
#destroy the game window
game_window.destroy()
#restart the game
main()
game_window.mainloop()
if __name__ == "__main__":
main()
|
2e60e1dd6c2b93324c5d0fc7da2d6d4c0e76af1c | steffenschumacher/TimeString | /TimeString/__init__.py | 3,494 | 3.703125 | 4 | import re
import datetime
class TimeString(object):
string_time_re = re.compile(r'(((?P<years>\d+)y)|((?P<weeks>\d+)w)|((?P<days>\d+)d)|((?P<hours>\d+)h)){1,2}')
@staticmethod
def convert(value):
"""
Converts either timestring (1y2w etc) to timedelta, or timedelta(or hours as int) to timestring
:param value:
:return:
"""
if isinstance(value, str):
return TimeString._to_time_delta(value)
elif isinstance(value, datetime.timedelta):
return TimeString._to_time_string(value)
elif isinstance(value, int):
return TimeString._to_time_string(value)
else:
raise ValueError('cannot convert {}, as it is an unsupported type'.format(value))
@staticmethod
def to_hours(value):
"""
Converts timedelta or timestring to hours
:param value: either timedelta or string - eg. 1y34w
:return: number of hours
:rtype: int
"""
if isinstance(value, str):
value = TimeString._to_time_delta(value)
if isinstance(value, datetime.timedelta):
return value.days*24+value.seconds/3600
raise ValueError('The value {} was of an unexpected type?'.format(value))
@staticmethod
def _to_time_delta(item):
"""
Parse a time string - eg. 1w2d
:param item:
:return:
"""
string_time_match = TimeString.string_time_re.match(item)
delta_parts = None
if string_time_match:
delta_parts = {x: int(v) for x, v in string_time_match.groupdict().items() if v}
return datetime.timedelta(**delta_parts)
@staticmethod
def _to_time_string(item):
"""
:param item: timedelta or int (hours)
:type item: datetime.timedelta | int
:return: str
"""
hours = item
if isinstance(item, datetime.timedelta):
hours = TimeString.to_hours(item)
val = ''
years = int(hours/8760)
weeks = int(hours/168)
days = int(hours/24)
if (years) > 0:
val = '{}y'.format(years)
remainder_days = int(hours%8760/24)
if remainder_days == 0:
pass # do nothing further
elif remainder_days%7 == 0:
val += '{}w'.format(int(remainder_days/7))
else:
val += '{}d'.format(remainder_days)
elif (weeks) > 0:
val = '{}w'.format(weeks)
remainder = (hours % 168)
if remainder == 0:
pass # do nothing further
elif remainder % 24 == 0:
val += '{}d'.format(int(remainder/24))
else:
val += '{}h'.format(remainder)
elif (days) > 0:
val = '{}d'.format(days)
remainder = (hours % 24)
if remainder > 0:
val += '{}h'.format(remainder)
else:
val += '{}h'.format(hours)
return val
@staticmethod
def to_hours(value):
"""
:param value: either timedelta or string - eg. 1y34w
:return: number of hours
:rtype: int
"""
if isinstance(value, str):
value = TimeString._to_time_delta(value)
if isinstance(value, datetime.timedelta):
return value.days*24+value.seconds/3600
raise ValueError('The value {} was of an unexpected type?'.format(value)) |
05bd09f9b249289d16a6ae401638d791ae851498 | mohan277/backend_repo | /clean_code/clean_code_submissions/clean_code_assignment_001/truck.py | 1,600 | 3.6875 | 4 | from car import Car
class Truck(Car):
HORN_SOUND = 'Honk Honk'
def __init__(
self, color=None, max_speed=None, acceleration=None,
tyre_friction=None, max_cargo_weight=None):
super().__init__(color, max_speed, acceleration, tyre_friction)
self._max_cargo_weight = max_cargo_weight
self._cargo = 0
@property
def max_cargo_weight(self):
return self._max_cargo_weight
@property
def may_cargo(self):
return self._cargo
@property
def cargo_weight(self):
return self._cargo_weight
def load(self, cargo_weight):
if self._current_speed <= 0:
self._cargo_weight = cargo_weight
if self._cargo_weight <= 0:
raise ValueError(f'Invalid value for cargo_weight')
else:
if self._cargo + self._cargo_weight <= self._max_cargo_weight:
self._cargo += self._cargo_weight
else:
print('Cannot load cargo more than max limit: {}'.format(
self._max_cargo_weight))
else:
print('Cannot load cargo during motion')
def unload(self, cargo_weight):
if self._current_speed <= 0:
self._cargo_weight = cargo_weight
if self._cargo_weight <= 0:
raise ValueError(f'Invalid value for cargo_weight')
else:
if self._cargo - self._cargo_weight >= 0:
self._cargo -= self._cargo_weight
else:
print('Cannot unload cargo during motion')
|
518e9e256174b4e6ec2f3637364c3977562b2b20 | anas-yousef/Connect-Four | /game.py | 7,767 | 4.21875 | 4 | class Game:
PLAYER_ONE = 0
PLAYER_TWO = 1
DRAW = 2
ROWS = 6
COLUMNS = 7
CHECK_FACTOR = 3
'''
I assigned it to be equal to 3 because in the functions where I check if there is a winner,
I use the number 3 constantly
'''
def __init__(self):
'''
Initializes the class Game. It has all the algorithms to run the game without the design,
such as finding the next legal move, check if there is a winner or not...
'''
self.winner_dict = [] # Holds the coordinates of the winning player
self.counter = 0
self.coord_table = {}
for index_row in range(self.ROWS):
for index_col in range(self.COLUMNS):
coord = index_row, index_col
self.coord_table[coord] = None
def column_is_full(self, column):
'''
:param column: Takes in column from the board
:return: Returns False if the column is still not full, else it raises an exception if it is
'''
if self.coord_table[(0, column)] == None:
return False
else:
raise Exception('Illegal move\n')
return True
def Index_last_none(self, column):
'''
:param column: Takes in column from the board
:return: Returns the coordinates of the legal assignment
'''
rows = self.ROWS - 1
while rows >= 0:
if self.coord_table[(rows, column)] == None:
return (rows, column)
rows -= 1
def make_move(self, column):
'''
:param column: Takes in column from the board
:return: Returns the player that did the move with the coordinates of the assignment(legal move)
'''
check = True
while check:
try:
if not self.column_is_full(column):
coord_place = self.Index_last_none(column)
if self.counter % 2 == 0:
self.coord_table[coord_place] = self.PLAYER_ONE
self.counter += 1
return self.PLAYER_ONE, coord_place
else:
self.coord_table[coord_place] = self.PLAYER_TWO
self.counter += 1
return self.PLAYER_TWO, coord_place
except:
('Illegal move. Insert again\n')
return False
self.counter += 1
def get_pre_player(self):
'''
:return: Returns the player that played in the last round
'''
if self.counter % 2 == 0:
return self.PLAYER_TWO
if self.counter % 2 == 1:
return self.PLAYER_ONE
def check_if_full(self):
'''
:return: Returns True if the board is full, else False
'''
for column in range(self.COLUMNS):
if self.coord_table[(0, column)] == None:
return False
return True
def check_horizontal(self, row, col):
'''
:param row: Takes a row from the board
:param col: Takes a column from the board
:return: Returns True if the player one horizontally, else False
'''
if self.coord_table[(row, col)] == None:
return False
if col in range(self.CHECK_FACTOR + 1, self.COLUMNS): # Not in the range to win horizontally
return False
color_player = self.coord_table[(row, col)] # Disk of the current player
column = col
while column <= col + self.CHECK_FACTOR:
self.winner_dict.append((row, column)) # We use this list so we can change the winner's disks
if self.coord_table[(row, column)] != color_player and color_player != None:
self.winner_dict = []
return False
column += 1
return True
def check_parallel(self, row, col):
'''
:param row: Row from the board
:param col: Column from the board
:return: Returns True if the player one in a parallel way
'''
if self.coord_table[(row, col)] == None:
return False
if row >= self.ROWS - self.CHECK_FACTOR: # Not in the range to win in that way
return False
color_player = self.coord_table[(row, col)] # Disk of the current player
rows = row
while rows <= row + self.CHECK_FACTOR:
self.winner_dict.append((rows, col)) # We use this list so we can change the winner's disks
if self.coord_table[(rows, col)] != color_player and color_player != None:
self.winner_dict = []
return False
rows += 1
return True
def check_diagonal(self, row, col):
'''
:param row: Row from the board
:param col: Column from the board
:return: Returns True if the player one diagonally
'''
if self.coord_table[(row, col)] == None:
return False
if row in range(0, self.ROWS) and col in range(self.CHECK_FACTOR + 1, self.COLUMNS): # Not in the right range
return False
color_player = self.coord_table[(row, col)]
rows = row
columns = col
'''
Here there is two ways to win diagonally, either in the range (0,3) - (0,4), or
(3,6) - (0,4)
'''
if row in range(0, self.CHECK_FACTOR) and col in range(0, self.CHECK_FACTOR + 1): # In the right range
while rows <= row + self.CHECK_FACTOR and columns <= col + self.CHECK_FACTOR:
self.winner_dict.append((rows, columns)) # We use this list so we can change the winner's disks
if self.coord_table[(rows, columns)] != color_player and color_player != None:
self.winner_dict = []
return False
rows += 1;
columns += 1
if row in range(self.CHECK_FACTOR, self.ROWS) and col in range(0, self.CHECK_FACTOR + 1): # In the right range
while rows >= row - self.CHECK_FACTOR and columns <= col + self.CHECK_FACTOR:
self.winner_dict.append((rows, columns)) # We use this list so we can change the winner's disks
if self.coord_table[(rows, columns)] != color_player and color_player != None:
self.winner_dict = []
return False
rows -= 1;
columns += 1
return True
def get_winner(self):
'''
:return: Returns the winning player, else returns DRAW
'''
for row in range(self.ROWS):
for column in range(self.COLUMNS):
if self.check_horizontal(row, column):
player = (self.get_current_player() + 1) % 2
return player
if self.check_parallel(row, column):
player = (self.get_current_player() + 1) % 2
return player
if self.check_diagonal(row, column):
player = (self.get_current_player() + 1) % 2
return player
if not self.check_if_full():
return self.DRAW
def get_player_at(self, row, col):
'''
:param row: Row from the board
:param col: Column form the board
:return: Returns the player that is found in the place (row, col)
'''
return self.coord_table[(row, col)]
def get_current_player(self):
'''
:return: Returns the player that is holding the current turn
'''
if self.counter % 2 == 0:
return self.PLAYER_ONE
if self.counter % 2 == 1:
return self.PLAYER_TWO
|
256a6aa582c669a79b39ccdcb8369eeb6ce7c03e | sonichuang/My-py-file | /保存属性值文件.py | 1,384 | 3.6875 | 4 | import time #通过小甲鱼的代码使用time.ctime()方法显示时间更方便
import pickle #储存二进制文件
import os #使用remove方法删除文件
class Mydes:
def __init__(self, value = None, name = None):
self.value = value
self.name = name
self.path = 'C:\\Users\\vulcanten\\desktop\\%s.txt' % self.name #不同的属性保存在不同的文件里面
def __get__(self, instance, owner):
with open(self.path, 'ab') as f:
pickle.dump('Variable <%s> has been read at Beijing Time <%s>, %s = %s\n' % (self.name, time.ctime(), self.name, str(self.value)), f) #注意self.value不能用%d格式化需要转换成字符串形式,否则传入的值是不同类型时就会出现报错
return self.value
def __set__(self, instance, value):
self.value = value
with open(self.path, 'ab') as f:
pickle.dump('Variable <%s> has been set at Beijing Time <%s>, %s = %s\n' % (self.name, time.ctime(), self.name, str(self.value)), f)
def __delete__(self, instance):
with open(self.path, 'ab') as f:
pickle.dump('Variable <%s> has been deleted at Beijing Time <%s>\n' % (self.name, time.ctime()), f)
os.remove(self.path) #删除属性的时候就删除了属性文件
del self.value
class T:
x = Mydes(10, 'x')
y = Mydes(8.8, 'y')
|
de3310357d59a9c4fcfaf0604424a02f1fb60530 | rlipscomb99/LIS4930 | /unittest.py | 781 | 3.78125 | 4 | import itertools
import unittest
def iteration(name):
count = 0
lista = []
for i in itertools.cycle(name):
if count > 10:
break
else:
lista.append(i)
count += 1
return lista
class testIteration(unittest.TestCase):
def testIterationsuccess(self):
actual = iteration(name = "Potatoes")
expected = ['T','O','M','A','T', 'O','E','S','T']
self.assertEqual(actual,expected,)
if __name__ == '__main__':
unittest.main()
def repeat(number,times):
nums = list(itertools.repeat(number,times))
return nums
class testIteration(unittest.TestCase):
def testIterationsuccess(self):
actual = repeat(number = 3, repeat = 2)
expected = [3, 3]
self.assertEqual(actual,expected)
if __name__ == '__main__':
unittest.main()
|
e20242a5341b231666de17d5e13979fa415dee65 | ComiteMexicanoDeInformatica/OMI-Archive | /2019/OMIPS-2019-pistas/tests/test-validator.py | 1,741 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import collections
import libkarel
from kareltest import *
class Test(KarelTest):
def test(self):
world = self.world
#Karel inicia en la casilla (1,1) viendo al norte.
self.assertEqual(1, world.y)
self.assertEqual(1, world.x)
self.assertEqual(world.direccion, 'NORTE')
#Karel no tiene zumbadores en la mochila
self.assertEqual(world.mochila, 0)
#Las únicas paredes en el mundo son las que lo delimitan.
self.assertTightWorldSize()
self.assertNoInnerWalls()
# Sólo se evalúa la posición final de Karel
self.assertEqual(world.despliega, ['POSICION'])
#Hay al menos un zumbador por fila, y exactamente uno en la primera fila, cada monton con a lo mas N zumbadores
for i in range(1, world.h):
montones = 0
for j in range(1, world.w + 1):
if (j, i) in world.lista_zumbadores:
montones += 1
self.assertTrue(world.zumbadores(j, i)<= world.h)
self.assertTrue(montones >= 1)
if i == 1:
self.assertEqual(1, montones)
# Las pistas son validas
pista = 1
for i in range(1, world.w + 1):
if (i, 1) in world.lista_zumbadores:
pista = world.zumbadores(i, 1)
break
pistas = 1;
for i in range(2, world.h):
pista = world.zumbadores(pista, i)
if pista > 0:
pistas += 1
else:
break
# hay menos pistas reales que el alto del mundo
self.assertTrue(pistas < world.h)
Test().run()
|
c08a47b1f3684bfcdb09fbc1eb02131605a137b0 | flaviogf/courses | /geral/livro_data_science_do_zero/chapter5/example01.py | 869 | 3.625 | 4 | from collections import Counter
import matplotlib.pyplot as plt
num_friends = [100, 49, 41, 40, 25, 100, 49]
friends_count = Counter(num_friends)
xs = range(101)
ys = [friends_count[x] for x in xs]
plt.bar(xs, ys)
plt.axis([0, 101, 0, 25])
plt.title('Histograma de Contagem de Familiares')
plt.xlabel('# de familiares')
plt.ylabel('# de pessoas')
def mean(x): return sum(x) / len(x)
def median(x):
size = len(x)
sorted_x = sorted(x)
midpoint = size // 2
return sorted_x[midpoint] if size % 2 == 1 else (sorted_x[midpoint - 1] + sorted_x[midpoint]) / 2
def quartile(num_quartile, x):
sorted_x = sorted(x)
return sorted_x[int(num_quartile * len(sorted_x))]
def mode(x):
c = Counter(x)
import pdb
pdb.set_trace()
return [x for x, y in c.items() if y == max(c.values())]
if __name__ == '__main__':
plt.show()
|
1335af13201a15c3a8c3f9ac35140abf6b8eb46a | garibaldiviolin/knapsack-solutions | /naive_recursion.py | 838 | 4 | 4 | """
A naive recursive implementation of 0-1 Knapsack Problem
Returns the maximum value that can be put in a knapsack of
capacity W
Reference: https://www.geeksforgeeks.org/python-program-for-dynamic-programming-set-10-0-1-knapsack-problem/
"""
def naive_recursion_knapsack(W, wt, val, n):
# Base Case
if n == 0 or W == 0:
return 0
# If weight of the nth item is more than Knapsack of capacity
# W, then this item cannot be included in the optimal solution
if (wt[n - 1] > W):
return naive_recursion_knapsack(W, wt, val, n - 1)
# return the maximum of two cases:
# (1) nth item included
# (2) not included
else:
return max(
val[n - 1] + naive_recursion_knapsack(W - wt[n - 1], wt, val, n - 1),
naive_recursion_knapsack(W, wt, val, n - 1)
)
|
834c27e43d5ec459dd2735eabf2773e497d91223 | rafaelgustavofurlan/basicprogramming | /Programas em Python/04 - Vetores/Script5.py | 600 | 3.828125 | 4 | # Faça um programa que carregue um vetor com dez numeros inteiros.
# Calcule e mostre os numeros superiores a 50 e suas respectivas
# posicoes. Mostrar mensagem se não existir nenhum numero nesta
# condição.
vetor = []
tem_maior_50 = False
#entradas
for n in range(0, 10):
num = int(input("Informe {0} valor para o vetor: ".format(n+1)))
vetor.append(num)
for n in vetor:
if n > 50:
print("O número {0} está na posição {1} do vetor.".format(n, vetor.index(n)))
tem_maior_50 = True
if tem_maior_50 == False:
print("Não existe nenhum número maior que 50")
|
6f4e4e07aee1258e2a8b1c2cbfba4c5a51951896 | miaopei/MachineLearning | /LeetCode/github_leetcode/Python/reverse-nodes-in-k-group.py | 1,888 | 4 | 4 | # Time: O(n)
# Space: O(1)
#
# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
#
# If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
#
# You may not alter the values in the nodes, only nodes itself may be changed.
#
# Only constant memory is allowed.
#
# For example,
# Given this linked list: 1->2->3->4->5
#
# For k = 2, you should return: 2->1->4->3->5
#
# For k = 3, you should return: 3->2->1->4->5
#
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
class Solution:
# @param head, a ListNode
# @param k, an integer
# @return a ListNode
def reverseKGroup(self, head, k):
dummy = ListNode(-1)
dummy.next = head
cur, cur_dummy = head, dummy
length = 0
while cur:
next_cur = cur.next
length = (length + 1) % k
if length == 0:
next_dummy = cur_dummy.next
self.reverse(cur_dummy, cur.next)
cur_dummy = next_dummy
cur = next_cur
return dummy.next
def reverse(self, begin, end):
first = begin.next
cur = first.next
while cur != end:
first.next = cur.next
cur.next = begin.next
begin.next = cur
cur = first.next
if __name__ == "__main__":
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
print Solution().reverseKGroup(head, 2) |
5d5c2db91704e472ba501bd13cb65338e848c4f1 | PuffyShoggoth/Competitive | /CCC/CCC '09 J2 - Old Fishin' Hole.py | 412 | 3.640625 | 4 | trout=int(input())
pike=int(input())
pickerel=int(input())
lake=int(input())
combos=0
for a in range(0, lake+1):
for b in range(0, lake+1):
for c in range(0, lake+1):
if a+b+c==0: continue
if a*trout+b*pike+c*pickerel<=lake:
print(a,'Brown Trout,', b, 'Northern Pike,', c, 'Yellow Pickerel')
combos=combos+1
print('Number of ways to catch fish:', combos) |
f7141e5e76d2cfc5ff5d406bf03134155c1937a2 | tomboy-64/pje | /py/prob0196.py | 1,974 | 3.53125 | 4 | import math
import gmpy2
LINE_NO = [ 8, 9, 10000, 5678027, 7208785]
primes = [ 2 ]
def isPrime(x):
if x > primes[ len(primes)-1 ]:
nextPrimes(x)
if x in primes:
return True
else:
return False
def nextPrimes(x):
global primes
outerDone = False
# sys.stdout.write(".")
# sys.stdout.flush()
while not outerDone:
innerDone = False
i = primes[ len(primes)-1 ]
while not innerDone:
i += 1
maxTest = int( math.sqrt(i) )
for j in primes:
if i % j == 0:
break
if maxTest <= j:
innerDone = True
primes += [ i ]
#print("DEBUG 1:", primes)
break
if primes[ len(primes)-1 ] >= x:
outerDone = True
def has_neighbours( length, testor, first, second, previous ):
results = []
for i in range(testor - length, testor - length + 3):
if i in first and (not i in previous):
results += [[1, i]]
for i in range(testor + length - 1, testor + length + 2):
if i in second and (not i in previous):
results += [[2, i]]
return results
for i in LINE_NO:
searchprimes = []
targets = []
for j in range(i-2, i+3):
searchprimes += [[]]
for k in range(sum(range(j)) + 1, sum(range(j)) + 1 + j):
if gmpy2.is_prime( k ):
searchprimes[len(searchprimes)-1] += [ k ]
# print( str(i) + ":", searchprimes )
for j in searchprimes[2]:
# print(has_neighbours( i, j, searchprimes[1], primes[3], [ j ] ))
for chk_neighbours in has_neighbours( i, j, searchprimes[1], searchprimes[3], [ j ] ):
if chk_neighbours[0] == 1:
chk_neighbours = has_neighbours( i-1, chk_neighbours[1], searchprimes[0], searchprimes[2], [j, chk_neighbours[1]] )
elif chk_neighbours[0] == 2:
chk_neighbours = has_neighbours( i+1, chk_neighbours[1], searchprimes[2], searchprimes[4], [j, chk_neighbours[1]] )
if len(chk_neighbours) > 0:
targets += [ j ]
break
# print( str(i) + ":", targets )
print( str(i) + " (sum):", sum(targets) )
# print(searchprimes[2][0] - searchprimes[2][len(searchprimes[2])-1])
|
8e5685361270f69df82e32753ca7a53c8561b3cd | yenchihliao/ankiSupport | /OperationDecorator.py | 558 | 3.5625 | 4 | from Operation import Operation
class Loop2X(Operation):
def __init__(self, op):
self.operation = op
self.helpMsg = "Looping, X to exit, and ? to get help\n" + self.operation.helpMsg
self.prefix = "decorator"
def do(self):
while(True):
arg = input(self.operation.prefix).split(', ')
if arg[0] == 'X':
break
elif arg[0] == '?':
printHelp()
else:
self.operation.do(arg)
def printHelp(self):
print(self.helpMsg)
|
50587ced395a200f03f33407da4ac5c218df10ec | hudefeng719/uband-python-s1 | /homeworks/A13191/checkin10/day16-homework2.py | 393 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import time
import calendar
print time.localtime()
print time.time()
localtime = time.localtime(time.time())
print "本地时间为:", localtime
localtime = time.asctime( time.localtime(time.time()) )
print "本地时间为:", localtime
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print '\n'
cal=calendar.month(2017,7)
print cal |
ecc9bd5abded97db30d2b69b35acf272d3695be4 | mabatko/python-chess | /chessboard.py | 9,359 | 3.578125 | 4 | class Chessboard:
board = [[] * 8 for i in range(8)]
pieces = []
turns = 0
lastMove = {"pieceName": '', "type": '', "color": '', "origX": -1, "origY": -1, "futureX": -1, "futureY": -1}
x_axis = [' 0 ',' 1 ',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ']
def __init__(self):
from square import Square
for i in range(8):
for j in range(8):
if (i+j)%2:
self.board[i].append(Square("White", i, j))
else:
self.board[i].append(Square("Black", i, j))
def printBoard(self):
for i in range(8):
if not i % 2:
print(' ', '░░░░░░░▓▓▓▓▓▓▓' * 4)
print(7-i, end=' ')
for j in range(8):
print(self.board[7-i][j].printSquare(), end='')
print('')
print(' ', '░░░░░░░▓▓▓▓▓▓▓' * 4)
else:
print(' ', '▓▓▓▓▓▓▓░░░░░░░' * 4)
print(7-i, end=' ')
for j in range(8):
print(self.board[7-i][j].printSquare(), end='')
print('')
print(' ', '▓▓▓▓▓▓▓░░░░░░░' * 4)
print(' ', ''.join(self.x_axis))
def createPiece(self, piece):
self.pieces.append(piece)
def deactivatePiece(self, x_pos, y_pos):
piece_name = self.board[y_pos][x_pos].pieceOn
pieceToDeactivate = self.returnPieceByName(piece_name)
pieceToDeactivate.isActive = False
pieceToDeactivate.initialMoveNotDone = False
print("Piece {} was removed from [{},{}]".format(piece_name,x_pos,y_pos))
def addPiece(self, piece):
if piece.isActive:
self.board[piece.y_position][piece.x_position].pieceOn = piece.name
def removePiece(self, piece):
self.board[piece.y_position][piece.x_position].pieceOn = ' - '
def returnPieceByName(self, piece_name):
for pieces in self.pieces:
if pieces.name == piece_name:
return pieces
def isPieceActive(self, name):
pieceNotFound = True
for pieces in self.pieces:
if pieces.name == name:
pieceNotFound = False
if not pieces.isActive:
print("Piece {} is not active".format(name))
return False
if pieceNotFound:
print("Piece with name {} doesn't exist".format(name))
return False
return True
def movePiece(self, piece_name, future_x_pos, future_y_pos):
pieceToMove = self.returnPieceByName(piece_name)
if pieceToMove.isMoveLegal(future_x_pos, future_y_pos, self):
# is this move En Passant?
if pieceToMove.type == "Pawn" and self.returnEnPassantSquare() == [future_x_pos, future_y_pos]:
self.deactivatePiece(self.lastMove["futureX"], self.lastMove["futureY"])
self.removePiece(self.returnPieceByName(self.lastMove["pieceName"]))
# is this move castling?
if pieceToMove.type == "King" and abs(pieceToMove.x_position-future_x_pos) == 2:
if pieceToMove.color == "White":
if future_x_pos == 6:
rook = self.returnPieceByName("WR2")
else:
rook = self.returnPieceByName("WR1")
else:
if future_x_pos == 6:
rook = self.returnPieceByName("BR2")
else:
rook = self.returnPieceByName("BR1")
self.removePiece(rook)
if future_x_pos == 6:
rook.x_position = 5
else:
rook.x_position = 3
rook.initialMoveNotDone = False
self.addPiece(rook)
self.lastMove["pieceName"] = pieceToMove.name
self.lastMove["type"] = pieceToMove.type
self.lastMove["color"] = pieceToMove.color
self.lastMove["origX"] = pieceToMove.x_position
self.lastMove["origY"] = pieceToMove.y_position
self.lastMove["futureX"] = future_x_pos
self.lastMove["futureY"] = future_y_pos
self.removePiece(pieceToMove)
if not self.isFieldEmpty(future_x_pos, future_y_pos):
self.deactivatePiece(future_x_pos, future_y_pos)
pieceToMove.x_position = int(future_x_pos)
pieceToMove.y_position = int(future_y_pos)
pieceToMove.initialMoveNotDone = False
self.addPiece(pieceToMove)
#pawn promotion
if pieceToMove.type == "Pawn" and ((pieceToMove.color == "White" and pieceToMove.y_position == 7) or (pieceToMove.color == "Black" and pieceToMove.y_position == 0)):
self.promotion(pieceToMove)
return True
else:
print('The move is not legal')
return False
def isFieldValid(self, x_position, y_position):
if x_position < 0 or x_position > 7 or y_position < 0 or y_position > 7:
return False
else:
return True
def isFieldEmpty(self, x_position, y_position):
if self.board[y_position][x_position].pieceOn == ' - ':
return True
else:
return False
def isEnemyOnTheField(self, x_position, y_position, myColor):
import re
if myColor == 'White':
if re.search("^B.*", self.board[y_position][x_position].pieceOn):
return True
else:
return False
else:
if re.search("^W.*", self.board[y_position][x_position].pieceOn):
return True
else:
return False
def canAttack(self, attackersName, victimsName):
attacker = self.returnPieceByName(attackersName)
victim = self.returnPieceByName(victimsName)
victimsPosition = [victim.x_position, victim.y_position]
attackersReach = attacker.returnValidFields(self)
if victimsPosition in attackersReach:
return True
else:
return False
def isFieldSafe(self, xPos, yPos, myColor):
fieldInQuestion = [xPos, yPos]
for piece in self.pieces:
if piece.color != myColor and piece.isActive:
if piece.type == "Pawn":
validFields = piece.returnPossibleTargetFields(self)
else:
validFields = piece.returnValidFields(self)
if fieldInQuestion in validFields:
return False
return True
def countPieceByType(self, typeName, color):
num = 0
for piece in self.pieces:
if piece.type == typeName and piece.color == color:
num += 1
return num
def promotion(self, pawnToPromote):
from piece import Rook, Bishop, Queen, Knight
print("Pawn {} on [{},{}] is going to be promoted".format(pawnToPromote.name, pawnToPromote.x_position, pawnToPromote.y_position))
if pawnToPromote.color == "White":
while True:
pieceType = input("Choose which type it will become: Queen, Knight, Rook, Bishop: ").upper()
if pieceType in ["QUEEN", "KNIGHT", "ROOK", "BISHOP"]:
break
else:
print("Incorrect type")
else:
pieceType = "QUEEN"
if pieceType == "ROOK":
numOfPieces = self.countPieceByType("Rook", pawnToPromote.color)
if pawnToPromote.color == "White":
piece = Rook("Rook", "WR"+str(numOfPieces+1), pawnToPromote.color, pawnToPromote.x_position, pawnToPromote.y_position, self, False, True)
else:
piece = Rook("Rook", "BR"+str(numOfPieces+1), pawnToPromote.color, pawnToPromote.x_position, pawnToPromote.y_position, self, False, True)
if pieceType == "QUEEN":
numOfPieces = self.countPieceByType("Queen", pawnToPromote.color)
if pawnToPromote.color == "White":
piece = Queen("Queen", "WQ"+str(numOfPieces+1), pawnToPromote.color, pawnToPromote.x_position, pawnToPromote.y_position, self, False, True)
else:
piece = Queen("Queen", "BQ"+str(numOfPieces+1), pawnToPromote.color, pawnToPromote.x_position, pawnToPromote.y_position, self, False, True)
if pieceType == "BISHOP":
numOfPieces = self.countPieceByType("Bishop", pawnToPromote.color)
if pawnToPromote.color == "White":
piece = Bishop("Bishop", "WB"+str(numOfPieces+1), pawnToPromote.color, pawnToPromote.x_position, pawnToPromote.y_position, self, False, True)
else:
piece = Bishop("Bishop", "BB"+str(numOfPieces+1), pawnToPromote.color, pawnToPromote.x_position, pawnToPromote.y_position, self, False, True)
if pieceType == "KNIGHT":
numOfPieces = self.countPieceByType("Knight", pawnToPromote.color)
if pawnToPromote.color == "White":
piece = Knight("Knight", "WK"+str(numOfPieces+1), pawnToPromote.color, pawnToPromote.x_position, pawnToPromote.y_position, self, False, True)
else:
piece = Knight("Knight", "BK"+str(numOfPieces+1), pawnToPromote.color, pawnToPromote.x_position, pawnToPromote.y_position, self, False, True)
self.addPiece(piece)
pawnToPromote.isActive = False
def returnEnPassantSquare(self):
if self.lastMove["type"] == "Pawn" and abs(self.lastMove["origY"] - self.lastMove["futureY"]) == 2:
return [self.lastMove["origX"],(self.lastMove["origY"] + self.lastMove["futureY"])/2]
else:
return []
def isGameFinished(self):
if not self.isPieceActive('WKK'):
print("White king is dead. Black won!")
return True
if not self.isPieceActive('BKK'):
print("Black king is dead. White won!")
return True
return False
|
196fd2cb6ddd86992c51a92fd2fc945d15e3df07 | naveen673/pythonprogramming | /cit_CyberSecurity/assessments/assessment_3/task_2.py | 731 | 4.40625 | 4 | '''
Task 2
# Write a python program to find the factors of a given number.
# The factors of a number are those, which are divisible by the number itself and 1.
# For example, the factors of 15 are 1, 3, 5.
# Please follow the below steps to complete this task:
# Define a function which will take the number as parameter and perform the task.
# Use for loops and if expression to perform the factorization.
# Python Program to find the factors of a number
# This function computes the factor of the argument passed
'''
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
num = int(input("Enter the number to find it's factors: "))
print_factors(num) |
4bb2ebe022c3a89549f5b856b0b508e40f754dc3 | 409085596/TallerHC | /Clases/Programas/Tarea07/Ejercicio01S.py | 569 | 3.65625 | 4 | # -*- coding: utf-8 -*-
from Ejercicio01 import determinaIgualdad
interruptor = True
while interruptor == True:
a, b= raw_input("\nDame dos listas para determinar si son iguales.\nTienen que estar separadas por un espacio, pero sin dejar espacios entre sus elementos:\n").split()
a=a.replace("[",""); a=a.replace("]",""); b=b.replace("[",""); b=b.replace("]","")
a=a.split(",") ; b=b.split(",")
print (determinaIgualdad(a,b))
interruptor = bool(raw_input("Si desea repetir el proceso ingrese cualquier caracter, de lo contrario presione enter: "))
|
be8d555f37b45cea50577e8614689e3fa71173d5 | Ritesh007/tutorial | /python/class_syntax.py | 296 | 3.90625 | 4 | #!/usr/bin/python
#########################
# python script 17
########################
#defining a class
class Class_name():
def function1(self):
name = lambda a: a+5
print(name(10))
#creating a object
class_object = Class_name()
#calling a def in class
class_object.function1()
|
e2ff29bda99bf4d72e43268dc3b3019a94faf962 | Marcfeitosa/listadeexercicios | /ex034.py | 565 | 3.9375 | 4 | print("""Desafio 34
Faça um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento.
Para salários superiores a R$ 1.200,00 calcule um aumento de 10%.
Para salários inferiores ou iguais, o aumento é de 15%""")
sal = float(input('Qual é o seu salário? '))
if sal > 1200.00:
print('Parabéns, ganhou um aumento de 15%, o seu novo salário é de {}{}{}.'.format('\033[31m', sal*1.15, '\033[m'))
else:
print('Parabéns, ganhou um aumento de 10%, o seu novo salário é de {}.'.format('\033[7;30m', sal*1.10, '\033[m')) |
ba69c6856d2bdbcec5d4189fe8c363f025a9e3dd | micaswyers/Advent | /Advent2015/15/day15.py | 3,708 | 3.53125 | 4 | # Part 1
from collections import defaultdict
def parse_input(file_name):
"""Returns a dict mapping properties to ingredients & stats
ex) {
'capacity': {'sprinkles': 5, 'peanutbutter': -1, 'frosting': 0, 'sugar': -1},
}
"""
with open(file_name) as f:
properties = defaultdict(lambda: {})
for line in f:
name_stats = line.split(":")
ingredient = name_stats[0].lower()
props = name_stats[1].split(',')
prop_amounts = [x.strip() for x in props]
for prop_amount in prop_amounts:
property_and_amount = prop_amount.split()
prop = property_and_amount[0]
amount = int(property_and_amount[1])
properties[prop][ingredient] = amount
return properties
def optimize_cookie_points(properties):
"""Returns the highest possible cookie score
Args:
properties: dict mapping property to ingredient & multiplier
Returns:
int of highest score
"""
all_scores = []
properties.pop('calories')
for num1 in range(101):
for num2 in range(101-num1):
for num3 in range(101-num1-num2):
num4 = (100 - num1 - num2 - num3)
totals = []
for prop, ingredient_amount in properties.iteritems():
total_prop_score = sum([
num1 * ingredient_amount['sprinkles'],
num2 * ingredient_amount['peanutbutter'],
num3 * ingredient_amount['frosting'],
num4 * ingredient_amount['sugar'],
])
if total_prop_score < 0:
total_prop_score = 0
totals.append(total_prop_score)
total_cookie_score = reduce(lambda x, y: x*y, totals)
all_scores.append(total_cookie_score)
return max(all_scores)
# Part 2
def optimize_for_calories(properties):
"""Return max possible score given constraint of 500cals"""
calories_dict = properties.pop('calories')
all_scores = []
for num1 in range(101):
for num2 in range(101-num1):
for num3 in range(101-num1-num2):
num4 = (100 - num1 - num2 - num3)
total_calories = sum([
num1 * calories_dict['sprinkles'],
num2 * calories_dict['peanutbutter'],
num3 * calories_dict['frosting'],
num4 * calories_dict['sugar'],
])
if total_calories == 500:
totals = []
for prop, ingredient_amount in properties.iteritems():
total_prop_score = sum([
num1 * ingredient_amount['sprinkles'],
num2 * ingredient_amount['peanutbutter'],
num3 * ingredient_amount['frosting'],
num4 * ingredient_amount['sugar'],
])
if total_prop_score < 0:
total_prop_score = 0
totals.append(total_prop_score)
total_cookie_score = reduce(lambda x, y: x*y, totals)
all_scores.append(total_cookie_score)
return max(all_scores)
|
0dc8aef8626037514ae6b195a1f9b89fbd1105b7 | dean-joshua/CSE-210-02pp | /Hilo/game/dealer.py | 1,643 | 3.984375 | 4 | import random
class Dealer:
def __init__(self):
'''A constructor method for the Dealer class.'''
self.current_card = 0
self.next_card = 0
self.h_or_l = ""
def draw_card(self):
'''A draw card method that pulls a new card'''
list_of_cards = [1,2,3,4,5,6,7,8,9,10,11, 12, 13]
return random.choice(list_of_cards)
def get_current_card(self):
'''A current card method that. The dealer draws a current card'''
self.current_card = self.draw_card()
def get_next_card(self):
'''A next card method. The dealer draws the next card'''
self.next_card = self.draw_card()
def get_h_or_l(self):
'''Asks the user for their guess as h or l.'''
guessing = True
while guessing:
try:
self.h_or_l = input("Higher or Lower? [h/l]: ")
if self.h_or_l.lower() == 'h' or self.h_or_l.lower() == 'l':
guessing = False
else:
print("Needs to be h or l.")
except ValueError:
print("Needs to be a string or int")
assert self.h_or_l in ["h","l"], "Should be h or l"
def get_points(self):
'''Add points to local points value depending on guess. (to be added to director points)'''
if self.next_card > self.current_card:
if self.h_or_l == "h":
return 100
else:
return 75
elif self.current_card > self.next_card:
if self.h_or_l == "l":
return 100
else:
return 75
|
4b26bdc9c7cb8cc35f6656dcc421ddd51fae6930 | KingOfRaccoon/2 | /12.py | 205 | 4.125 | 4 | string = '3' * 95
while '333' in string or '999' in string:
if '999' in string:
string = string.replace('999', '3', 1)
else:
string = string.replace('333', '9', 1)
print(string) |
779908de67851ba3e9a52f80acd0053a335a6f8c | xuedong/hacker-rank | /Interview Preparation Kits/Interview Preparation Kit/Dynamic Programming/Max Array Sum/max_array_sum.py | 774 | 3.53125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maxSubsetSum function below.
def maxSubsetSum(arr):
n = len(arr)
if n == 1:
return arr[0]
elif n == 2:
return max(arr[0], arr[1])
else:
max_sum1 = max(arr[0], arr[1])
max_sum2 = arr[0]
max_sum = max(arr[0], arr[1])
for i in range(2, n):
max_sum = max(arr[i], max(max_sum2+arr[i], max_sum1))
max_sum2 = max_sum1
max_sum1 = max_sum
return max_sum
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = list(map(int, input().rstrip().split()))
res = maxSubsetSum(arr)
fptr.write(str(res) + '\n')
fptr.close()
|
87c3cb7cbdb7042826cb5e75712f27b31710bb24 | QAlexBall/Python_Module | /cookbook/meta_programing/exercise_1.py | 1,141 | 3.5625 | 4 | """
exercise 1
"""
import time
import logging
from functools import wraps
def timethis(func):
"""
Decorator that reports the execution time.
"""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end - start)
return result
return wrapper
@timethis
def countdown(num):
"""
Counts down
"""
while num > 0:
num -= 1
def logged(level, name=None, message=None):
"""
logged
"""
def decorate(func):
logname = name if name else func.__module__
print(logname)
log = logging.getLogger(logname)
logmsg = message if message else func.__name__
@wraps(func)
def wrapper(*args, **kwargs):
log.log(level, logmsg)
return func(*args, **kwargs)
return wrapper
return decorate
@logged(logging.DEBUG)
def add(x, y):
return x + y
@logged(logging.CRITICAL, 'example')
def spam():
print('Spam!')
print(add(1, 2))
spam()
countdown(100)
countdown(1000)
countdown(10000000)
|
e2d99b7f412e5ce63d6cfe8c78ca110100358cad | brianchiang-tw/leetcode | /No_0653_Two Sum IV - Input is a BST/by_preorder_and_set.py | 2,145 | 3.828125 | 4 | '''
Description:
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
num_set = set()
def helper( node: TreeNode, k: int)->bool:
nonlocal num_set
if not node:
return False
if node.val in num_set:
return True
num_set.add( k - node.val )
return helper( node.left, k) or helper( node.right, k )
# --------------------------------------------------------------
return helper( root, k) if root else False
# n : the number of nodes in binary search tree
## Time Complexity: O( n )
#
# The overhead in time is the cost of DFS traversal, which is of O( n )
## Space Complexity: O( n )
#
# The overhead in space is the storage for set, num_set, which is of O( n )
def test_bench():
## Test_case_#1
root_1 = TreeNode(5)
root_1.left = TreeNode(3)
root_1.right = TreeNode(6)
root_1.left.left = TreeNode(2)
root_1.left.right = TreeNode(4)
root_1.right.right = TreeNode(7)
# expected output:
'''
True
'''
print( Solution().findTarget(root = root_1, k = 9) )
## Test_case_#2
root_1 = TreeNode(5)
root_1.left = TreeNode(3)
root_1.right = TreeNode(6)
root_1.left.left = TreeNode(2)
root_1.left.right = TreeNode(4)
root_1.right.right = TreeNode(7)
# expected output:
'''
False
'''
print( Solution().findTarget(root = root_1, k = 28) )
if __name__ == '__main__':
test_bench()
|
a0714e8bda11809c931d81867ef9e8f1f172d58b | Mahantesh1729/python | /Activity_11.py | 359 | 3.875 | 4 | def main():
print("Enter the first number")
a = input_number()
print("Enter the second number")
b = input_number()
summation = add(a, b)
display(a, b, summation)
def input_number():
return int(input())
def add(a, b):
return a + b
def display(a, b, summation):
print(f"{a} + {b} = {summation}")
main()
|
ee179a8a2c6b18a01ed1c7b68517ddb16725e3be | zhaochuanshen/leetcode | /Remove_Duplicates_from_Sorted_List.py | 629 | 3.75 | 4 | '''
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
p = head
while p:
q = p.next
while q and p.val == q.val:
p.next = q.next
q = q.next
p = q
return head
|
e7c9ff96bfd41f28f35486d8635a44bbcdb47126 | benilak/Everything | /CS241_Miscellaneous/scratch_2.py | 2,743 | 4.28125 | 4 | '''class Time:
def __init__(self, hours = 0, minutes = 0, seconds = 0):
self._hours = hours
self._minutes = minutes
self._seconds = seconds
def get_hours(self):
return self._hours
def set_hours(self, hours):
if hours < 0:
self._hours = 0
elif hours > 23:
self._hours = 23
else:
self._hours = hours
def get_minutes(self):
return self._minutes
def set_minutes(self, minutes):
if minutes < 0:
self._minutes = 0
elif minutes > 59:
self._minutes = 59
else:
self._minutes = minutes
def get_seconds(self):
return self._seconds
def set_seconds(self, seconds):
if seconds < 0:
self._seconds = 0
elif seconds > 59:
self._seconds = 59
else:
self._seconds = seconds
def main1():
time = Time()
hours = int(input("Please enter hours: "))
minutes = int(input("Please enter minutes: "))
seconds = int(input("Please enter seconds: "))
time.set_hours(hours)
print(time.get_hours())
time.set_minutes(minutes)
print(time.get_minutes())
time.set_seconds(seconds)
print(time.get_seconds())
if __name__ == "__main__":
main()
'''
class Time:
def __init__(self, hours = 0, minutes = 0, seconds = 0):
self.__hours = 0
self.__minutes = 0
self.__seconds = 0
def get_hours(self):
return self.__hours
def set_hours(self, hours):
if hours < 0:
self.__hours = 0
elif hours > 23:
self.__hours = 23
else:
self.__hours = hours
hours = property(get_hours, set_hours)
def get_minutes(self):
return self.__minutes
def set_minutes(self, minutes):
if minutes < 0:
self.__minutes = 0
elif minutes > 59:
self.__minutes = 59
else:
self.__minutes = minutes
minutes = property(get_minutes, set_minutes)
def get_seconds(self):
return self.__seconds
def set_seconds(self, seconds):
if seconds < 0:
self.__seconds = 0
elif seconds > 59:
self.__seconds = 59
else:
self.__seconds = seconds
seconds = property(get_seconds, set_seconds)
def main():
time = Time()
hours = int(input("Please enter hours: "))
minutes = int(input("Please enter minutes: "))
seconds = int(input("Please enter seconds: "))
time.hours = hours
print(time.hours)
time.minutes = minutes
print(time.minutes)
time.seconds = seconds
print(time.seconds)
if __name__ == "__main__":
main()
|
82b224451dba360530b8859a82896acba87cffde | RSanchez98/python | /UMDC/01/05.py | 257 | 3.8125 | 4 | #Escribir un programa que imprima todos los números pares entre dos números que
#se le pidan al usuario
primero = int(input("Primer nuermo "))
ultimo = int(input("Ultimo numero "))
primero += primero % 2
for i in range(primero, ultimo+1, 2):
print(i) |
1aaf8dc33fe75a183f1c0c6956c2705c2ea55342 | luckyanand235/Coursera_Algorithmic_Toolbox | /week2/stress_test/fib_last_digit_st.py | 672 | 4.0625 | 4 | # Uses python3
import numpy as np
import math
def fibonacci(n):
phi1 = (1 + math.sqrt(5)) / 2
#phi2 = (1 - math.sqrt(5)) / 2
return round(pow(phi1, n) / math.sqrt(5)) % 10
def get_fibonacci_last_digit_optimized(n):
if n <= 1:
return n
previous = 0
current = 1
temp = 0
for _ in range(1, n):
temp = current + previous
temp = temp%10
current, previous = temp, current
return temp
if __name__ == '__main__':
while True:
n = np.random.randint(0, 100)
a = fibonacci(n)%10
b = get_fibonacci_last_digit_optimized(n)
if a != b:
break
print("a = ", a, " b = ", b, "OK!!!")
print("For n = ",n, " fibonacci value digits a , b", a, b)
|
44e8477cc08cefc16db0f67823974cb13da82c6a | deepgupta11101/vsa2018 | /proj02_02.py | 1,086 | 4.5625 | 5 | # Name:
# Date:
# proj02_02: Fibonaci Sequence
"""
Asks a user how many Fibonacci numbers to generate and generates them. The Fibonacci
sequence is a sequence of numbers where the next number in the sequence is the sum of the
previous two numbers in the sequence. The sequence looks like this:
1, 1, 2, 3, 5, 8, 13...
"""
want = int(raw_input("How many numbers do you want in your Fibonacci sequence? "))
previousNumber=0
currentNumber=1
for i in range (want) :
nextNumber = previousNumber + currentNumber
print currentNumber
previousNumber=currentNumber
currentNumber=nextNumber
# powers of 2 extension
want=int(raw_input("How many powers of 2 would you like to see? "))
count =0
while count<want:
print 2**count
count+=1
# divisor extension
divisor=2
num=int(raw_input("What integer would you like all of the divisors for?"))
if num<1:
print "Invalid range: please try again."
elif num==2:
print "1"
print "2"
else :
print 1
while divisor<num :
if num%divisor==0:
print divisor
divisor+=1
print num
|
62658823a27f622e7af6b254fdcd37fa09cb7f3a | manuck/myAlgo | /baekjoon/1717_집합의 표현.py | 511 | 3.53125 | 4 | import sys
sys.stdin = open('1717_input.txt')
input = sys.stdin.readline
def find(num):
if p[num] != num:
p[num] = find(p[num])
return p[num]
def union(a, b):
A = find(a)
B = find(b)
if A != B:
p[B] = A
n, m = map(int, input().split())
p = [i for i in range(n + 1)]
for _ in range(m):
state, a, b = map(int, input().split())
if state:
if find(a) == find(b):
print("YES")
else:
print("NO")
else:
union(a, b) |
9c73b002b1f9da826887bedcfe2e0e838b4c6c14 | sudoheader/TAOD | /quadratic_equation_solver_app.py | 1,230 | 4.34375 | 4 | #!/usr/bin/env python3
import cmath
print("Welcome to the Quadratic Equation Solver App.\n")
print("A quadratic equation is of the form ax^2 + bx + c = 0")
print("Your solutions can be real or complex numbers.")
print("A complex number has two parts: a + bj")
print("Where a is the real portion and bj is the imaginary portion.\n")
equations = int(input("How many equations would you like to solve today: "))
# for loop for number of equations
for i in range(equations):
print("\nSolving equation #" + str(i + 1))
print("-"*63 + "\n")
a = float(input("Please enter your value of a (coefficient of x^2): "))
b = float(input("Please enter your value of b (coefficient of x): "))
c = float(input("Please enter your value of c (coefficient): "))
print("\nThe solutions to " + str(a) + "x^2 + " + str(b) + "x + " + str(c) + " = 0 are:")
# using quadratic formula
# x = (-b +/- sqrt(b^2 - 4ac)) / (2a)
sqrt_dis = cmath.sqrt(b**2 - 4 * a * c) # square root of discriminant
x1 = (-b + sqrt_dis) / (2 * a)
x2 = (-b - sqrt_dis) / (2 * a)
# cmath allows us to output with complex numbers
print("\n\tx1 = " + str(x1))
print("\tx2 = " + str(x2))
print("\nThank you for using the Quadratic Equation Solver App. Goodbye.")
|
a1a96efd4c12a837f3c12ade32434ed5e3af077c | mr-zhouzhouzhou/LeetCodePython | /剑指 offer/数组/二维数组中的查找.py | 880 | 3.5625 | 4 | """
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,
每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,
判断数组中是否含有该整数。
"""
"""
思路: 从左下角开始遍历,往上走是变小,往右走是变大
"""
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
row = len(array)
col = len(array[0])
m = row - 1
n = 0
while m >= 0 and n < col:
if array[m][n] > target:
m -= 1
elif array[m][n] < target:
n += 1
else:
return True
return False
target = 9
array = [[1,2,3,4,5],
[4,5,6,7,8],
[5,6,7,9,10]]
|
f5999b13fd8ba2e6f943763b5df71ca7d67a618a | zhanghong7096/CCC-Solutions | /2011/Senior/S1.py | 540 | 3.59375 | 4 | # CCC 2011 Senior 1: English or French
# written by C. Robart
# March 2011
# straight forward file handling with
# simple character counting in strings
file = open("s1.5.in", 'r')
lines = file.readlines(100000)
countS = 0
countT =0
for line in lines:
for i in range(0, len(line)):
if line[i] == "s" or line[i] == "S":
countS = countS + 1
elif line[i] == "t" or line[i] == "T":
countT = countT + 1
if countT > countS:
print "English"
else:
print "French"
file.close()
|
57b370549e16d998e36020293c055d1c8667184f | yinkz1990/100daysofcode | /classifier.py | 575 | 4.125 | 4 | age = int(input('Enter your age ='))
categories =['Child','Adolescence','Adult',' Senior Adult']
adult = ['Early','Middle','Late']
if age >= 0 and age <= 12:
print('You are a',categories[0])
elif age >= 13 and age <=18:
print('You are an' ,categories[1])
elif age >=19 and age <=59:
print('You are an' ,categories[2])
if age >=19 and age <=25:
print(adult[0] , 'adulthood')
elif age >=26 and age <= 35:
print(adult[1], 'adulthood')
else:
print(adult[2], 'adulthood')
elif age >=60:
print('You are a' ,categories[3]) |
34cad6a8b172637c2d2bcf43708fb78472843bd3 | Sibyl233/LeetCode | /src/LC/480.py | 1,218 | 3.71875 | 4 | from typing import List
import bisect
"""解法1:暴力法
- 时间复杂度:O(nklogk)
- 空间复杂度:O(k)
"""
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
n = len(nums)
res = []
for i in range(n-k+1):
tmp = nums[i:i+k]
tmp.sort()
res.append((tmp[k//2] + tmp[(k - 1)//2]) / 2) # 计算中位数奇偶两种情况可以合并
return res
"""解法2:双指针+二分插入
- 时间复杂度:O(nk)
- 空间复杂度:
"""
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
tmp, res = [], []
left = 0
for right in range(len(nums)):
bisect.insort_left(tmp, nums[right])
if len(tmp) > k:
tmp.pop(bisect.bisect_left(tmp, nums[left]))
left += 1
if len(tmp) == k:
res.append((tmp[k//2] + tmp[(k - 1)//2]) / 2)
return res
"""解法:堆
- 时间复杂度:
- 空间复杂度:
"""
if __name__ == "__main__":
nums = [1,3,-1,-3,5,3,6,7]
k = 3
print(Solution().medianSlidingWindow(nums, k)) # [1, -1, -1, 3, 5, 6] |
323d705f64528385fad9fd7a232c852efec01deb | Aprilya/bioinformatics | /RNA.py | 435 | 3.75 | 4 | # rosaling.info RNA task from bioinformatics stronghold
# transcribing coding DNA into RNA from sequence given in a sequence.txt
sequence = open('sequence.txt').read()
sequence_length = len(sequence)
RNA = ""
for i in range(sequence_length):
if sequence[i] == "T":
RNA += "U"
else:
RNA += sequence[i]
# print(sequence) #for comparision
# print(RNA)
result_file = open('RNA_results.txt', 'w+').write(RNA)
|
b241cb750b7ef59dd7fb2b4edcc5def54a03c1f9 | MannazX/mannaz | /Python/Exercise 6 - 4.7.py | 752 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 24 10:45:27 2018
@author: magge
"""
print("Add to inputs")
i1 = eval(input("input 1: "))
i2 = eval(input("input 2: "))
t = i1 + i2
print("Sum = {0}, type {1}".format(t, type(t)))
#With integers:
#input 1: 23
#input 2: 34
#Sum = 57, type <class 'int'>
#Now with list:
#input 1: [3.2, 4.1, 5.0, 5.9, 6.8, 7.7]
#input 2: [8.6, 9.5, 10.4, 11.3, 12.2, 13.1]
#Sum = [3.2, 4.1, 5.0, 5.9, 6.8, 7.7, 8.6, 9.5, 10.4, 11.3, 12.2, 13.1],
#type <class 'list'>
#Now with tuples:
#input 1: (2, 4, 5)
#input 2: (3, 5, 6)
#Sum = (2, 4, 5, 3, 5, 6)
print("This is a string")
i1 = eval(input("this is a string 1: "))
i2 = eval(input("this is a string 2: "))
r = i1 + i2
print("Sum = {0}, type {1}".format(r, type(r))) |
672a2156b394907b55f43dd6acfdb89a67b0cc07 | eosband/QuantRL | /envs.py | 4,154 | 3.765625 | 4 | from functions import *
class TradingEnv():
"""
Represents the trading environment used in our model.
Handles low-level data scraping, retrieval, and calculation
Adjustable parameters:
get_reward(params): the reward function of a certain action
get_state(params): the state that the model is currently in
"""
def __init__(self, train_data, window_size):
'''
Creates a trading environment from data train_data with window size window_size
:param train_data: data to be trained on, e.g. daily closing prices
:param window_size: size of the window on which we examine stock trends
'''
# List of all daily closing prices
self.data = train_data
# List of Simple Moving Averages from the window
self.sma_data = getSMAFromVec(train_data, window_size)
# Size of recent closing price list
self.window_size = window_size
# Keeps track of buying prices
self.inventory = []
# Keeps track of how much spent
self.max_spent = 0
self.current_out = 0 # currently held assets
self.buys = []
self.sells = []
self.total_profit = 0
def get_reward(self, selling_price, time_sold, bought_price, time_bought):
"""
Gets the reward of the given action
:param selling_price: price sold
:param time_sold: time sold
:param bought_price: buying price
:param time_bought: time bought
:return:
"""
delta_t = time_sold - time_bought
profit = selling_price - bought_price
return max(profit, .0001)
# reward = max(profit, .0001) // (np.log(delta_t) + 1)
# return reward
def get_weighted_diff(self, v1, v2):
return (abs(v2 - v1)) / v1
def get_state(self, t):
'''
Our state representation.
:param t: time
:return: n-day state representation ending at time t with sma indicator at end
'''
n = self.window_size + 1
d = t - n + 1
block = self.data[d:t + 1] if d >= 0 else -d * [self.data[0]] + self.data[0:t + 1] # pad with t0
res = []
for i in range(n - 1):
res.append(sigmoid(block[i + 1] - block[i]))
# add sigmoid of price and sma
# res.append(sigmoid(self.get_weighted_diff(self.data[t], self.sma_data[t])))
res = np.array([res])
return res
def reset_holdings(self):
"""
Resets the inventory and amount bought
"""
self.inventory = []
self.current_out = 0
self.max_spent = 0
self.buys = []
self.sells = []
self.total_profit = 0
def buy(self, t):
"""
Buys stock at time t
:param t: time to buy
"""
price = self.data[t]
self.inventory.append((price, t))
self.current_out += price
self.max_spent = max(self.max_spent, self.current_out)
self.buys.append(t)
def sell(self, t):
"""
Sells the oldest stock in portfolio
:param t: time at which to sell
:return: reward and profit from selling
"""
if len(self.inventory) < 1:
return 0, 0
bought_price, time_bought = self.inventory.pop(0)
selling_price = self.data[t]
reward = self.get_reward(selling_price, t, bought_price, time_bought)
profit = selling_price - bought_price
self.total_profit += profit
self.current_out -= selling_price
self.sells.append(t)
return reward, profit
def value_held(self, t):
"""
Returns the total value of the portfolio at time t
:param t: time
"""
return len(self.inventory) * self.data[t]
def net_profit(self, t):
"""
Returns the total profit of the environment, which represents
the net profit made on each transaction plus the value of all
current assets at time t
:param t: current time (so as to determine market price of stock)
"""
return self.total_profit + self.value_held(t)
|
26e1b8c7891e74fdc5abd386d619d5fe1f3033e2 | Devinwon/master | /craw/RE-matchMAXMIN.py | 195 | 3.796875 | 4 | import re
# 贪婪匹配(默认) 非贪婪匹配
# 增加?获得最小匹配
rel=re.match(r'PY.*N','PYANBNCNDN')
rel2=re.match(r'PY.*?N','PYANBNCNDN')
print(rel.group(0))
print(rel2.group(0))
|
25d47223b5c4eede49d710105b9c5e577638d977 | dymfangxing/leetcodelintcode | /leetcode_py/jiuzhang_py_Ladders/9chapter_10_Dynamic_Programming/116_Jump_Game.py | 1,183 | 3.59375 | 4 | #coding=utf-8
#1)array中每个元素表示在这一步最大能跳多少步,而非一定要这么多步
#2)可以超过最后那个数
#3) reach means it reachs the last index
"""
reach是为了记录每个点最远能到达的位置,取当前值与i+A[i]的较大值,
这样,即使reach不再变大,但i+A[i]依然能帮助走完整个array
"""
class Solution:
"""
@param A: A list of integers
@return: A boolean
"""
def canJump(self, A):
# write your code here
if not A:
return False
length, reach = len(A), 0
for i in range(length):
if i > reach or reach >= length -1:
break
reach = max(reach, i + A[i])
return reach >= length - 1
def canJump_mythought(self, A):
if not A:
return False
length, start = len(A), 0
while start < length:
start += A[start]
if start >= length:
return True
return False
if __name__ == '__main__':
solu = Solution()
nums = [2,3,1,1,4]
result = Solution().canJump(nums)
print("final result is: ", result) |
9d7a98618a962ec84ab577573e518a74a10db3c3 | arkanmgerges/cafm.identity | /src/domain_model/country/CityRepository.py | 1,094 | 3.765625 | 4 | """
@author: Mohammad S. moso<moso@develoop.run>
"""
from abc import ABC, abstractmethod
from typing import List
from src.domain_model.country.City import City
class CityRepository(ABC):
@abstractmethod
def cities(
self, resultFrom: int = 0, resultSize: int = 100, order: List[dict] = None
) -> dict:
"""Get list of cities
Args:
resultFrom (int): The start offset of the result item
resultSize (int): The size of the items in the result
order (List[dict]): A list of order e.g. [{'orderBy': 'name', 'direction': 'asc'}, {'orderBy': 'age', 'direction': 'desc'}]
Returns:
dict: A dict that has {"items": [], "totalItemCount": 0}
"""
@abstractmethod
def cityById(self, id: str) -> City:
"""Get city by id
Args:
id (str): The id of the city
Returns:
User: user object
:raises:
`CountryDoesNotExistException <src.domain_model.resource.exception.CountryDoesNotExistException>` Raise an exception if the city does not exist
"""
|
bc2229d2578f385b18d65df6ff2a8d58fd9a1277 | Alejandro-Paredes/EECS337---NLP-Project-2 | /conversions.py | 3,722 | 3.5625 | 4 | def convertTeaspoonToCup(teaspoon):
cup = round(teaspoon*0.021, 2)
return cup
def convertCupToTeaspoon(cup):
teaspoon = round(cup/0.021, 2)
return teaspoon
def convertTeaspoonToTablespoon(teaspoon):
tablesoon = round(teaspoon/3, 2)
return tablespoon
def convertTablespoonToTeaspoon(tablespoon):
teaspoon = round(tablespoon*3, 2)
return teaspoon
def convertTeaspoonToOz(teaspoon):
oz = round(teaspoon*0.167, 2)
return oz
def convertOztoTeaspoon(oz):
teaspoon = round(oz/0.167, 2)
return teaspoon
def convertTeaspoonToMl(teaspoon):
ml = round(teaspoon*5, 2)
return ml
def convertMltoTeaspoon(ml):
teaspoon = round(ml/5, 2)
return teaspoon
def convertTablespoonToOz(tablespoon):
oz = round(tablespoon*0.5, 2)
return oz
def convertOzToTablespoon(oz):
tablespoon = round(oz*2, 2)
return tablespoon
def convertTablespoonToGram(tablespoon):
gram = round(tablespoon*14, 2)
return gram
def convertGramToTablespoon(gram):
tablespoon = round(gram/14, 2)
return tablespoon
def convertTablespoonToMl(tablespoon):
ml = round(tablespoon*14.786, 2)
return ml
def convertMlToTablepoon(ml):
tablespoon = round(ml/14.786, 2)
return tablespoon
def convertTablespoonToCup(tablespoon):
cup = round(tablespoon*0.0625, 2)
return cup
def convertCupToTablespoon(cup):
tablespoon = round(cup/0.0625, 2)
return tablespoon
def convertTablespoonToLb(tablespoon):
lb = round(
return lb
def convertLbToTablespoon(lb):
tablespoon = round(
return tablespoon
def convertTablespoonToCup(tablespoon):
cup = round(
return cup
def convertCupToTablespoon(cup):
tablespoon = round(
return tablespoon
def convertTablespoonToPint(tablespoon):
pint = round(tablespoon*0.031, 2)
return pint
def convertCupToOz(cup):
oz = round(cup*8.0, 2)
return oz
def convertOzToCup(oz):
cup = round(oz/8.0, 2)
return cup
def convertCupToGallon(cup):
gallon = round(cup*0.0625, 2)
return gallon
def convertGallonToCup(gallon):
cup = round(gallon/0.0625, 2)
return cup
def convertCupToLiter(cup):
l = round(cup*0.25, 2)
return l
def convertLiterToCup(l):
cup = round(l*4, 2)
return cup
def convertCupToPint(cup):
pint = round(cup*0.5, 2)
return pint
def convertPintToCup(pint):
cup = round(pint*2, 2)
return cup
def convertCuptoQt(cup):
qt = round(cup*0.25, 2)
return qt
def convertQtToCup(qt):
cup = round(qt*4, 2)
return cup
def convertOzToLiter(oz):
liter = round(oz*0.03, 2)
return liter
def convertLiterToOz(liter):
oz = round(liter/0.03, 2)
return oz
def convertOzToQt(oz):
qt = round(oz*0.031, 2)
return qt
def convertQtToOz(qt):
oz = round(qt/0.031, 2)
return oz
def convertOzToPint(oz):
pint = round(oz/16, 2)
return pint
def convert PintToOz(pint):
oz = round(pint*16, 2)
return oz
def convertGallonToLiter(gallon):
liter = round(gallon*3.785, 2)
return liter
def convertLiterToGallon(liter):
gallon = round(liter/3.785, 2)
return gallong
def convertGallonToOz(gallon):
oz = round(gallon*128, 2)
return oz
def convertOzToGallon(oz):
gallon = round(oz/128, 2)
return gallon
def convertGallonToPint(gallon):
pint = round(gallon*8, 2)
return pint
def convertPintToGallon(pint):
gallon = round(pint/8, 2)
return gallon
def convertGallonToQt(gallon):
qt = round(gallon*4, 2)
def convertQtToGallon(qt):
gallon = round(qt/4, 2)
return gallon
def convertOzToLb(oz):
lb = round(oz/16, 2)
return lb
def convertLbToOz(lb):
oz = round(lb*16, 2)
retun oz
def convertOzToKg(oz):
kg = round(oz/35.272, 2)
return kg
def convertKgToOz(kg):
oz = round(kg*35.273, 2)
retun oz
def convertLbToKg(lb):
kg = round(lb*0.4375, 2)
return kg
def convertKgTolb(kg):
lb = round(kg/0.4375, 2)
return lb |
fc96135c8b4f6c999956aca666e5a55ccf71e3a9 | mroswell/python-snippets | /download-census-shapefiles.py | 1,862 | 3.515625 | 4 | '''
Download selected census shapefiles, unzip them in directories named by state abbreviation
fips.csv looks like this:
statename,code,twoletter
Alabama,1,AL
Alaska,2,AK
Arizona,4,AZ
Arkansas,5,AR
'''
import urllib
import csv
import sys
import os
fips_csv = csv.DictReader(open('fips-.csv', 'rU'), dialect='excel')
for row in fips_csv:
stateabbrev = row['twoletter']
# statename = row['statename'].upper().replace(' ','_')
statecode = row['code'].zfill(2)
filename_congress = 'tl_rd13_' + statecode + '_cd113.zip'
filename_upper = 'tl_rd13_' + statecode + '_sldu.zip'
filename_lower = 'tl_rd13_' + statecode + '_sldl.zip'
url_congress = 'http://www2.census.gov/geo/tiger/TIGERrd13_st/' + statecode + '/' + filename_congress
url_upper = 'http://www2.census.gov/geo/tiger/TIGERrd13_st/' + statecode + '/' + filename_upper
url_lower = 'http://www2.census.gov/geo/tiger/TIGERrd13_st/' + statecode + '/' + filename_lower
if not os.path.exists(stateabbrev):
os.makedirs(stateabbrev)
print 'getting ' + url_congress + ' ('+stateabbrev+')'
try:
urllib.urlretrieve(url_congress, stateabbrev + '/' +filename_congress)
urllib.urlretrieve(url_upper, stateabbrev + '/' +filename_upper)
urllib.urlretrieve(url_lower, stateabbrev + '/' +filename_lower)
os.chdir('/home/action/maps/'+stateabbrev)
os.system('unzip ' + filename_congress)
os.system('unzip ' + filename_upper)
os.system('unzip ' + filename_lower)
os.chdir('/home/action/maps/')
# os.system('rm ' + filename_congress)
except:
print "Unexpected error:", sys.exc_info()[0]
sys.exc_clear()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.