blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
887d7d7c1863ebf6939a008884b137af0063f2f8 | W17839213903/git111 | /python/lianxi.py | 5,529 | 3.6875 | 4 | #list(列表) srt(字符串) float(浮点数) tuple(元组) dict(字典) int(整数) bool(布尔值)
#none(空值) set(集合)
#第一个内置函数type(变量名) 产看数据类型
# a=89
# print(type(a))
# a='wuldss'
# print(type(a))
# a=input('<<<<')
# b=a.split()
# b.sort()
# print(b)
# a=input('<<<<')
# b=a.split()
# b.sort()
# a1=int(b[0])
# a2=int(b[1])
# a3=int(b[2])
# if a1+a2>a3:
# if a1**2+a2**2==a3**2:
# print('直角三角形')
# elif a1**2+a2**2<a3**2:
# print('钝角三角形')
# elif a1**2+a2**2>a3**2:
# print('锐角三角形')
# else:
# print('不能组成三角形')
# a={12,345,123,23,34,'ewrw',213,'reaafs'}
# # a.add(5798)
# b=a.pop()
# a.remove(123)
# # print(b)
# print(a)
# a = 12
# for i in range(2,a,3):
# print(i)
#!/usr/bin/env prthon
# a=0
# for i in range(2,101):
# for j in range(2,i):
# if i % j==0 :
# break
# else:
# a=a+i
# print(a)
# def quchong(*arge):
# b=[]
# for i in arge:
# if i not in b:
# b.append(i)
# print(b)
#
# quchong(9,2,9,0,4,5,3,4,7,8,9,0,4,3,1,5,2)
# a=123
# def aaa():
# global a
# a=999
# print(a)
# return a
# print(a)
# aaa()
# print(a)
# def aaa():
# a=0
# for i in range(2,100):
# for j in range(2,i):
# if i % j == 0:
# break
# else:
# a=a+i
# return a
#
# print(aaa())
# print(aaa()+1)
# aa = lambda x,y:x+y
# bb = lambda x,y:x-y
# cc = lambda x,y:x*y
# dd = lambda x,y:x//y
# a=input('>>>')
# if '+' in a:
# a=a.split('+')
# print(aa(int(a[0]),int(a[1])))
# if '-' in a:
# a = a.split('-')
# print(bb(int(a[0]),int(a[1])))
# if '*' in a:
# a = a.split('*')
# print(cc(int(a[0]),int(a[1])))
# if '//' in a:
# a = a.split('//')
# print(dd(int(a[0]),int(a[1])))
# a=[]
# for i in range(10):
# if i > 5:
# a.append(i)
# b=[(x-2) for x in range(10) if x > 5]
# print(a)
# print(b)
#
# a=(31,214,5,23,5213)
# print(min(a))
# a=100
# print(int(0b1010))
# for i in range(1,1000):
# a=0
# for j in range(1,i):
# if i%j==0:
# a=a+j
# if a==i:
# print(i)
# 选择法排序
# a=input('>>>>')
# b=a.split()
# c=len(b)
# for i in range(0,c):
# for j in range(i+1,c):
# if int(b[i])>int(b[j]):
# b[i],b[j]=b[j],b[i]
# print(b[0::])
# print(b[0::])
#冒泡排序
# a=input('>>>>')
# b=a.split()
# c=len(b)
# for i in range(0,c):
# for j in range(i+1):
# if int(b[i])>int(b[j]):
# b[i],b[j]=b[j],b[i]
# # print(b)
# print(b[::-1])
# 1000以内一个数的因数之和加起来等于本身的
# for i in range(1,1000):
# a=0
# for j in range(1,i):
# if i%j==0:
# a+=j
# if i==a :
# print(i)
# a=[23,12,43,25,1,29]
# b=a.copy()
# b.sort()
# c=b.index(b[0])
# d=b.index(b[-1])
# a[c],a[0]=a[0],a[c]
# a[d],a[-1]=a[-1],a[d]
# print(a)
#
#打印第一大和第二大的数
# a=[5000,3,51000,51000,51000,5000]
# a.sort()
# d=a.count(a[-1])
# f=a.count(a[-d-1])
# for i in range(0,d):
# print(a[-1])
# for i in range(0,f):
# print(a[-d-1])
#向左移动一位,不改变列表结构
# a=[1,5,6,3,8,2]
# b=len(a)
# for i in range(b-1):
# a[i],a[i-1]=a[i-1],a[i]
# print(a)
# a=[21,23,12,14]
# b=len(a)
# for i in range(b):
# for j in range()
# import random
# a=random.randrange(1,21)
# while True:
# b=int(input('<<<'))
# if b==a:
# print('ok')
# break
# elif b>a:
# print('大了')
# elif b<a:
# print('小了')
# for i in range(1,1001):
# a=0
# for j in range(1,i):
# if i%j==0:
# a=a+j
# if a==i:
# print(i)
# a=input('>>>>')
# b=len(a)//2
# for i in range(b):
# if a[i] != a[-i-1]:
# print('no')
# break
# else:
# print('yes')
# a=[1,2,3,4,5]
# b=len(a)
# for i in range(b-1):
# a[i],a[i-1]=a[i-1],a[i]
# print(a)
# a=input('>>>')
# b=a.split()
# c=[]
# for i in b:
# for j in b:
# for h in b:
# if (i != j) and (i != h) and (j != h):
# print(i,j,h)
# c.append(int(i)*100+int(j)*10+int(h))
# print(c)
# a=[1,2,3,7,8,9]
# b=int(input('>>>'))
# a.append(b)
# c=len(a)
# for i in range(0,c):
# for j in range(i+1):
# if int(a[i])>int(a[j]):
# a[i],a[j]=a[j],a[i]
# print(a[::-1])
# while True:
# a=input('>>>>')
# if a=='exit':
# break
# b=a.split()
# c=len(b)
# for i,j in enumerate(b):
# b[i]=int(j)
# print(sum(b)/c)
# for h in b:
# if h < sum(b)/c:
# print(w)
# a=input('>>>')
# b=a.split()
# c=b.index(max(b))
# d=b.index(min(b))
# b[c],b[-1]=b[-1],b[c]
# b[d],b[0]=b[0],b[d]
# print(b)
# a=input('请输入一组数字')
# f=a.split(',')
# for i,j in enumerate(f):
# f[i]=int(j)
# b=f.index(max(f))
# c=f.index(min(f))
# f[c],f[0]=f[0],f[c]
# f[b],f[-1]=f[-1],f[b]
# print(f)
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# def triangles():
# L = [1]
# while True:
# yield L
# L = [sum(i) for i in zip([0]+L, L+[0])]
#
import requests
class Qiushi(object):
def qingqiu(self):
url = 'http://www.qiushibaike.com/text/page/1'
qingqiu1 = requests.get(url=url)
html = qingqiu1.content.decode('utf-8')
return html
def guolv(self):
pass
qiushi = Qiushi()
qiushi.qingqiu() |
6bafb17cbaa6a88d397a9dd4b1276d556f01a17c | W17839213903/git111 | /python/gwc.py | 1,340 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding:utf -* -*-
a=int(input('请输入总资产'))
goods = [
{'name': '电脑', 'price': 1999},
{'name': '鼠标', 'price': 10},
{'name': '游艇', 'price': 20},
{'name': '美女', 'price': 998}
]
for i,j in enumerate(goods):
print(i+1,j['name'],j['price'])
print('已进入购物车,按exit退出购物车')
# while True:
# gouwuche = []
# bh=input('请输入商品编号,按exit退出购物车')
# if bh=='exit':
# break
# else:
# gouwuche.append(goods[int(bh)-1]['name'])
# def goumia():
# zongjia = 0
# b=input('请输入商品名称')
# for i in b:
# for i in goods:
# if i == j['name']:
# zongjia+=j['price']
# if a < zongjia:
# print('你的余额不足,充值还是删除购物车商品')
# a=input('请输入充值或者删除')
# if a == '充值':
# pass
#
# for i in ygjg:
# p+=i
# print('你要买的商品总价{}'.format(p))
# while True:
# if all < p:
# print('余额不足,请充值')
# cz = int(input('你要充值多钱'))
# alll = alll + cz + all
# if all < p and alll < p:
# print()
# elif alll >= p:
# print('商品已购买,谢谢惠顾')
# break |
00416619ea6ea655e17b97004be54dd70b890faa | swarnim321/ms | /dataStructures_Algorithms/longest_common_Prefix.py | 525 | 3.765625 | 4 | def commonPrefix(strs):
lcp=""
if (len(strs)==0):
return lcp
minLen = len(strs[0])
for i in range(len(strs)):
minLen = min(len(strs[i]), minLen)
strng= strs[0]
for i in range(minLen):
for j in range(1,len(strs)) :
print(strs[j][i])
if strng[i]!=strs[j][i]:
return lcp
lcp = lcp + strng[i]
arr = ["geeksforgeeks", "geeks",
"geek", "geezer"]
x = commonPrefix(arr)
print(x) |
84956569572fc36cd921466ffc0c4c422e5668c3 | swarnim321/ms | /dataStructures_Algorithms/search.py | 404 | 3.9375 | 4 |
lst=[]
size = int(input("enter the size of the array"))
#j=size-1
for i in range(size):
val = int(input("enter the elements in the array on by one"))
lst.append(val)
x=int(input("enter the elements to be searched"))
for i in range(0,size):
if i==size-1:
print("No")
elif x==lst[i]:
print("Yes")
break
#time complexity O(nlogn) |
e7dbe559e2c6f96e669e93aac9f6d610da5d27b9 | swarnim321/ms | /dataStructures_Algorithms/substring.py | 756 | 3.734375 | 4 | def check(strng,substrng):
count=0
j=0
for i in range(len(strng)):
if j==len(substrng):
print("true")
exit(1)
elif strng[i]==substrng[j]:
count+=1
j+=1
print(count)
else:
j=0
print("False")
def check2(strng,substr):
j=0
for i in range(len(strng)):
if strng[i]==substr[j]:
j+=1
if j==len(substr):
print("true")
print("i ", i)
exit(1)
else:
j=0
print("false")
print("i ", i)
strng=str(input("enter a string"))
substr=str(input("enter the substring"))
check2(strng,substr)
|
6e87b011e0c5d271b6773eed9243e7095838e01f | swarnim321/ms | /dataStructures_Algorithms/vowels.py | 404 | 3.625 | 4 | import heapq
vowels=['a','e','i','o','u']
strng=str(input("enter the string"))
dic={}
max_heap=[]
heapq.heapify(max_heap)
for i in range(len(strng)):
if strng[i] in dic:
dic[strng[i]]+=1
else:
dic[strng[i]]=1
for key,value in dic.items():
heapq.heappush(max_heap,[-value,key])
x=heapq.heappop(max_heap)
print("the vowel and the maximum count is " ,x[1],-x[0]) |
ba71dc4cd012e6e35c6c3ed46d6212f0f82f06fb | swarnim321/ms | /dataStructures_Algorithms/merge_sorted_linked_list.py | 507 | 3.78125 | 4 | def mergeLists(head1, head2):
main = temp = node()
if head1 is None:
return head2
if head2 is None:
return head1
while head1 is not None or head2 is not None:
if head1.data <head2.data:
current = head1.data
head1 =head1.next
if head2.data < head1.data:
current = head2.data
head2=head2.next
temp.next = current
temp = temp.next
return if __name__ == '__main__':
[[][] ] |
b7283ba7e0fb5d90bc1abf8113b6cb799e9f0d4a | swarnim321/ms | /dataStructures_Algorithms/reverse.py | 244 | 3.796875 | 4 | size=int(input("enter the size of the array"))
print("enter the elements of the array")
lst = list(map(int,input().split(" ")))
for i in range(size//2):
temp= lst[i]
lst[i]= lst[size-i-1]
lst[size - i - 1]=temp
print(lst)
|
dcf4456d331bfd6c3aa560503a4c288c60c4b277 | swarnim321/ms | /dataStructures_Algorithms/anti_diagonal.py | 1,314 | 3.953125 | 4 | def anti_diagonal(mat):
m=len(mat)
n=len(mat[0])
for col in range(m):
startcol=col
startrow=0
while startcol>=0 and startrow<m:
print(mat[startrow][startcol], end=" ")
startrow+=1
startcol-=1
print()
for i in range(1,n):
startrow=i
startcol=n-1
while startrow<n and startcol>=0:
print(mat[startrow][startcol], end=" ")
startrow += 1
startcol -= 1
print()
def diagonal(mat):
m = len(mat)
n = len(mat[0])
for i in range(m,0,-1):
startrow=0
startcol=i
while startrow>=0 and startcol<n:
#print("index ", startrow,startcol)
print(mat[startrow][startcol], end=" ")
startrow += 1
startcol += 1
print()
m = len(mat)
n = len(mat[0])
for i in range(n):
startrow = i
startcol =0
while startrow< n and startcol<n:
print(mat[startrow][startcol], end=" ")
startrow+=1
startcol+=1
print()
mat=[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
anti_diagonal(mat)
print(" ")
diagonal(mat) |
4f9e9241ebdd4405e5794463f1af684c6a6502cf | iamdarshan7/Python-Practice | /formatting.py | 1,296 | 3.890625 | 4 | # person = {'name': 'Jenn', 'age': 23}
# sentence = 'My name is {} and I am {} years old.'.format(person['name'], person['age'])
# print(sentence)
tag = 'h1'
text = 'This is a headline'
sentence = '<{0}><{1}></{0}>'.format(tag, text)
print(sentence)
# class Person():
# def __init_(self, name, age):
# self.name = name
# self.age = age
# p1 = Person('Jack', '33')
# sentence = 'My name is {0.name} and I am {0.age} years old.'.format(p1)
# print(sentence)
first_name = 'Corney'
last_name = 'Schafer'
# sentence = 'My name is {} {}'.format(first_name, last_name)
# print(sentence)
# sentence = f'My name is {first_name.upper()} {last_name}'
# print(sentence)
# person = {'name': 'Jenn', 'age': 23}
# # sentence = 'My name is {} and I am {} years old'.format(person['name'], person['age'])
# sentence = f"My name is {person['name']} and I am {person['age']} years old."
# print(sentence)
# calculation = f'4 times 11 is equal to {4*11}'
# print(calculation)
# for n in range(1, 11):
# sentence = f'The value is {n:02}'
# print(sentence)
# pi = 3.14159265
# sentence = f'Pi is equal to {pi:.4f}'
# print(sentence)
from datetime import datetime
birthday = datetime(1990, 1, 1)
sentence = f'Jenn has a birthday on {birthday:%B %d, %Y}'
print(sentence) |
22b96428465ba2920dda4a9519b7845c900811d2 | iamdarshan7/Python-Practice | /special.py | 974 | 3.8125 | 4 | class Employee:
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
def __repr__(self):
return "Employee ('{}', '{}', {})".format(self.first, self.last, self.pay)
def __str__(self):
return '{} - {}'.format(self.fullname(), self.email)
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'Thapa', 60000)
# print(emp_1)
print('test'.__len__())
# // both way is ok
# // 1st way
# print(repr(emp_1))
# print(str(emp_1))
# // 2nd way
# print(emp_1.__rep__())
# print(emp_1.__str__())
# // Finish Here
# // Other special dunder methods
# print(int.__add__(1, 2)) // prints 3
# print(str.__add__('a', 'b')) // prints ab |
1debc549e8b99c3d09c91e837ae03551d4dd4a6d | sunm22/final-project-SI206 | /population_data.py | 6,010 | 3.734375 | 4 | import requests
import sqlite3
import json
import os
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
#
# Name: Mingxuan Sun
# Who did you work with: Tiara Amadia
#
def setUpDatabase(db_name):
'''This function takes in the name of the database, makes a connection to server
using nane given, and returns cur and conn as the cursor and connection variable
to allow database access.'''
path = os.path.dirname(os.path.abspath(__file__))
conn = sqlite3.connect(path+'/'+db_name)
cur = conn.cursor()
return cur, conn
def pop_table(cur, conn, pop_dict, date, count):
'''This function takes in the cursor and connection variables to database, state, year and number of US Population for that state. It creates a table in the database if it doesn’t exist and inserts the state, date and number of population. Returns nothing'''
cur.execute('CREATE TABLE IF NOT EXISTS Population ("id" INTEGER PRIMARY KEY, "state" TEXT, "population" INTEGER)')
# Inserting 50 states at a time into Population Database
for x in pop_dict:
cur.execute('INSERT INTO Population (id, state, population) VALUES (?, ?, ?)', (count, x + ":" + str(date), pop_dict[x]))
count += 1
conn.commit()
def percent_changes(cur, conn):
'''This function takes in cursor and connection variables. It grabs the population and states from the database, seeds out the 2020 and 2010 population, append the state name into a labels list and its population numbers to the population list. Calculate percentage changes and write the calculations onto a txt file. Returns nothing.'''
labels2020 = []
pop2020 = []
# Grabbing Populations and States from the Database
cursor = cur.execute("SELECT state, population FROM Population")
for row in cursor:
if row[0].split(":")[1] == "2020":
labels2020.append(row[0].split(":")[0])
num = row[1]
num = int(num.replace(',', ''))
pop2020.append(num)
labels2010 = []
pop2010 = []
cursor = cur.execute("SELECT state, population FROM Population")
for row in cursor:
if row[0].split(":")[1] == "2010":
labels2010.append(row[0].split(":")[0])
num = row[1]
num = int(num.replace(',', ''))
pop2010.append(num)
f = open("pop_calculations.txt", "w+")
for x in range(len(labels2010)):
f.write(labels2010[x] + " has had a " + str(pop2020[x]/pop2010[x]) + " change in population\n")
f.close()
def pop_table_length(cur, conn):
'''This function calculates the number of rows in the CovidData table to help with extracting
25 lines at a time. Returns the number of rows in the table as an int.'''
cur.execute('CREATE TABLE IF NOT EXISTS Population ("id" INTEGER PRIMARY KEY, "state" TEXT, "population" INTEGER)')
cur.execute('SELECT MAX(id) FROM Population')
data = cur.fetchone()
num = data[0]
return num
############################################################
def get_pop_2020(soup):
'''This function takes in a soup request called in the main() and finds the table retaining population numbers through class tag. Then it finds the rows of the table and iterates through the rows to scrape state names and population numbers. It appends the state and population number into a dictionary where state is key and population number is value. It removes District of Columbia to get 50 states. Returns dictionary containing state name and 2020 population numbers.'''
table = soup.find('table',{'class':'wikitable sortable'})
body = table.find('tbody')
all_rows = body.find_all('tr')
key_pop_2020_dict = {}
for row in all_rows[2:53]:
row_cells = row.find_all('td')
key = row_cells[2].text.strip()
value = row_cells[3].text.strip()
key_pop_2020_dict[key] = value
key_pop_2020_dict.pop('District of Columbia')
return key_pop_2020_dict
def get_pop_2010(soup):
'''This function takes in a soup request called in the main() and finds the table retaining population numbers through class tag. Then it finds the rows of the table and iterates through the rows to scrape state names and population numbers. It appends the state and population number into a dictionary where state is key and population number is value. It removes District of Columbia to get 50 states. Returns dictionary containing state name and 2010 population numbers.'''
table = soup.find('table',{'class':'wikitable sortable'})
body = table.find('tbody')
all_rows = body.find_all('tr')
key_pop_2010_dict = {}
for row in all_rows[2:53]:
row_cells = row.find_all('td')
key = row_cells[2].text.strip()
value = row_cells[4].text.strip()
key_pop_2010_dict[key] = value
key_pop_2010_dict.pop('District of Columbia')
return key_pop_2010_dict
def main():
soup = BeautifulSoup(requests.get('https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States_by_population').text, 'html.parser')
pop_2020 = get_pop_2020(soup)
pop_2020_firsthalf = dict(list(pop_2020.items())[:25])
pop_2020_secondhalf = dict(list(pop_2020.items())[25:])
pop_2010 = get_pop_2010(soup)
pop_2010_firsthalf = dict(list(pop_2010.items())[:25])
pop_2010_secondhalf = dict(list(pop_2010.items())[25:])
cur, conn = setUpDatabase("finalProject.db")
num = pop_table_length(cur, conn)
if num == None:
pop_table(cur, conn, pop_2010_firsthalf, "2010", 1)
return
elif type(num) == int:
if num <= 25:
pop_table(cur, conn, pop_2010_secondhalf, "2010", 26)
return
if num <= 50:
pop_table(cur, conn, pop_2020_firsthalf, "2020", 51)
return
if num <= 75:
pop_table(cur, conn, pop_2020_secondhalf, "2020", 76)
percent_changes(cur, conn)
if __name__ == "__main__":
main()
|
0cb59c4b644410eb0e48ff890e844b55bd2221e8 | nss-day-cohort-18/bank-teller | /bank.py | 736 | 3.875 | 4 | import locale
class BankAccount():
def __init__(self):
self.balance = 0
self.account = None
def add_money(self, amount):
"""Add money to a bank account
Arguments:
amount - A numerical value by which the bank account's balance will increase
"""
self.balance += float(amount)
def withdraw_money(self, amount):
"""Withdraw money to a bank account
Arguments:
amount - A numerical value by which the bank account's balance will decrease
"""
pass
self.balance -= float(amount)
def show_balance(self):
"""Show formatted balance
Arguments:
None
"""
locale.setlocale( locale.LC_ALL, '' )
return locale.currency(self.balance, grouping=True)
|
9f9e207b57d42ed716c9d1acfb00c10de98c014f | LizBaker/Data-Structures | /binary_search_tree/binary_search_tree.py | 916 | 3.6875 | 4 | class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value > self.value:
if self.right is None:
self.right = [value]
else:
self.right.append(value)
elif value < self.value:
if self.left is None:
self.left = [value]
else:
self.left.append(value)
def contains(self, target):
if target == self.value:
return True
elif target > self.value:
for value in self.right:
if value == target:
return True
return False
elif target < self.value:
for value in self.left:
if value == target:
return True
return False
else: return False
def get_max(self):
if self.right is None:
return self.value
else:
self.right.sort()
return self.right[len(self.right)-1]
|
744631ed71bbb2e308a85b42baca861a5f5f0b02 | Samana19/Employeemgmt | /Management.py | 13,040 | 3.875 | 4 | from tkinter import *
import tkinter.ttk as ttk
import tkinter.messagebox as tkMessageBox
import sqlite3
# function to define database
def database():
""" database function is used to create table with specifies number of columns"""
global conn, cursor
# creating student database
conn = sqlite3.connect("employee.db")
cursor = conn.cursor()
# creating STUD_REGISTRATION table
cursor.execute(
"CREATE TABLE IF NOT EXISTS STUD_REGISTRATION (STU_ID text, STU_NAME text, STU_EMAIL text,STU_DOB text,STU_GENDER text, STU_CONTACT int, STU_ADDRESS text)")
def displayform():
root = Tk()
root.title("Employee Registration System")
root.geometry("1350x700+90+0")
root.iconbitmap('worker.ico')
title_name = Label(root, text="Employee Registration System", bd=10, relief=GROOVE,
font=("Helvetica", 20, "bold"), bg="coral", fg="black")
title_name.pack(side=TOP, fill=X)
global tree
global SEARCH
global id_no, name, email, dob, gender, contact, address
# All entry variables
SEARCH = StringVar()
id_no = StringVar()
name = StringVar()
email = StringVar()
dob = StringVar()
gender = StringVar()
contact = StringVar()
address = StringVar()
# First frame for user to enter data
upload1 = Frame(root, bd=4, relief=RIDGE, bg="light salmon")
upload1.place(x=20, y=100, height=580, width=450)
frame1_title = Label(upload1, text="Employee Data Upload", font=("Helvetica", 18, "bold"), fg="black",
bg="light salmon")
frame1_title.grid(row=0, columnspan=2, pady=20)
id_label = Label(upload1, text=" I.D.", font=("Helvetica", 15, "bold"), fg="black", bg="light salmon")
id_label.grid(row=1, column=0, padx=20, pady=10, sticky="w")
id_entry = Entry(upload1, textvariable=id_no, font=("Helvetica", 13, "bold"), bd=5, relief=SUNKEN)
id_entry.grid(row=1, column=1, padx=20, pady=10, sticky="w")
name_label = Label(upload1, text=" Name", font=("Helvetica", 15, "bold"), fg="black", bg="light salmon")
name_label.grid(row=2, column=0, padx=20, pady=10, sticky="w")
name_entry = Entry(upload1, textvariable=name, font=("Helvetica", 13, "bold"), bd=5, relief=SUNKEN)
name_entry.grid(row=2, column=1, padx=20, pady=10, sticky="w")
email_label = Label(upload1, text="Email", font=("Helvetica", 15, "bold"), fg="black", bg="light salmon")
email_label.grid(row=3, column=0, padx=20, pady=10, sticky="w")
email_entry = Entry(upload1, textvariable=email, font=("Helvetica", 13, "bold"), bd=5, relief=SUNKEN)
email_entry.grid(row=3, column=1, padx=20, pady=10, sticky="w")
dob_label = Label(upload1, text="D.O.B", font=("Helvetica", 15, "bold"), fg="black", bg="light salmon")
dob_label.grid(row=4, column=0, padx=20, pady=10, sticky="w")
dob_entry = Entry(upload1, textvariable=dob, font=("Helvetica", 13, "bold"), bd=5, relief=SUNKEN)
dob_entry.grid(row=4, column=1, padx=20, pady=10, sticky="w")
gender_label = Label(upload1, text="Gender", font=("Helvetica", 15, "bold"), fg="black", bg="light salmon")
gender_label.grid(row=5, column=0, padx=20, pady=10, sticky="w")
gender_drop = ttk.Combobox(upload1, textvariable=gender, font=("Helvetica", 11, "bold"), state="readonly")
gender_drop['values'] = ("male", "female", "other", "prefer not to say")
gender_drop.grid(row=5, column=1, padx=20, pady=10)
contact_label = Label(upload1, text="Contact No.", font=("Helvetica", 15, "bold"), fg="black", bg="light salmon")
contact_label.grid(row=6, column=0, padx=20, pady=10, sticky="w")
contact_entry = Entry(upload1, textvariable=contact, font=("Helvetica", 13, "bold"), bd=5, relief=SUNKEN)
contact_entry.grid(row=6, column=1, padx=20, pady=10, sticky="w")
address_label = Label(upload1, text="Address", font=("Helvetica", 15, "bold"), fg="black", bg="light salmon")
address_label.grid(row=7, column=0, padx=20, pady=10, sticky="w")
address_txt = Entry(upload1, textvariable=address, font=("Helvetica", 13, "bold"), bd=5, relief=SUNKEN)
address_txt.grid(row=7, column=1, padx=20, pady=10, sticky="w")
# Button Frame
button_frame = Frame(upload1, bd=4, relief=RIDGE, bg="light salmon")
button_frame.place(x=15, y=500, width=410)
add_btn = Button(button_frame, text="Add", width=10, pady=5, command=register)
add_btn.grid(row=0, column=0, padx=10, pady=10)
update_btn = Button(button_frame, text="Update", width=10, pady=5, command=Update)
update_btn.grid(row=0, column=1, padx=10, pady=10)
delete_btn = Button(button_frame, text="Delete", width=10, pady=5, command=Delete)
delete_btn.grid(row=0, column=2, padx=10, pady=10)
clear_btn = Button(button_frame, text="Clear", width=10, pady=5, command=Reset)
clear_btn.grid(row=0, column=3, padx=10, pady=10)
# Second frame for user details
details2 = Frame(root, bd=4, relief=RIDGE, bg="light salmon")
details2.place(x=500, y=100, height=580, width=830)
search_label = Label(details2, text="Search By", font=("Helvetica", 15, "bold"), fg="black", bg="light salmon")
search_label.grid(row=0, column=0, padx=20, pady=10, sticky="w")
def Search():
if search_drop.get() == 'ID':
search_ids()
if search_drop.get() == 'Name':
search_name()
if search_drop.get() == 'Contact':
search_contact()
def search_contact():
conn = sqlite3.connect("employee.db")
cursor = conn.cursor()
# creating STUD_REGISTRATION table
cursor.execute('''SELECT * FROM STUD_REGISTRATION''')
all = cursor.fetchall()
data2 = []
for id in all:
if search_entry.get() == str(id[5]):
# clear current data
tree.delete(*tree.get_children())
for data in id:
data2.append(data)
tree.insert('', 'end', values=tuple(data2))
tree.bind("<Double-1>", OnDoubleClick)
cursor.close()
conn.close()
def search_name():
conn = sqlite3.connect("employee.db")
cursor = conn.cursor()
# creating STUD_REGISTRATION table
cursor.execute('''SELECT * FROM STUD_REGISTRATION''')
all = cursor.fetchall()
data2 = []
for id in all:
if search_entry.get() == id[1]:
# clear current data
tree.delete(*tree.get_children())
for data in id:
data2.append(data)
tree.insert('', 'end', values=tuple(data2))
tree.bind("<Double-1>", OnDoubleClick)
cursor.close()
conn.close()
def search_ids():
conn = sqlite3.connect("employee.db")
cursor = conn.cursor()
# creating STUD_REGISTRATION table
cursor.execute('''SELECT * FROM STUD_REGISTRATION''')
all = cursor.fetchall()
data2 = []
for id in all:
if search_entry.get() == id[0]:
# clear current data
tree.delete(*tree.get_children())
for data in id:
data2.append(data)
tree.insert('', 'end', values=tuple(data2))
tree.bind("<Double-1>", OnDoubleClick)
cursor.close()
conn.close()
search_drop = ttk.Combobox(details2, font=("Helvetica", 11, "bold"), state="readonly")
search_drop['values'] = ("ID", "Name", "Contact")
search_drop.grid(row=0, column=1, padx=20, pady=10)
search_drop.current(0)
search_entry = Entry(details2, font=("Helvetica", 13, "bold"), bd=5, relief=SUNKEN)
search_entry.grid(row=0, column=2, padx=20, pady=10, sticky="w")
search_btn = Button(details2, text="Search", width=10, pady=5, command=Search)
search_btn.grid(row=0, column=4, padx=10, pady=10)
show_all_btn = Button(details2, text="Show All", width=10, pady=5, command=DisplayData)
show_all_btn.grid(row=0, column=5, padx=10, pady=10)
# Table Frame
table_frame = Frame(details2, bd=4, relief=RIDGE, bg="light salmon")
table_frame.place(x=10, y=70, height=490, width=800)
scroll_x = Scrollbar(table_frame, orient=HORIZONTAL)
scroll_y = Scrollbar(table_frame, orient=VERTICAL)
tree = ttk.Treeview(table_frame,
columns=("i.d.", "name", "email", "d.o.b", "gender", "contact", "address"),
xscrollcommand=scroll_x.set, yscrollcommand=scroll_y.set)
scroll_x.pack(side=BOTTOM, fill=X)
scroll_y.pack(side=RIGHT, fill=Y)
scroll_x.config(command=tree.xview)
scroll_y.config(command=tree.yview)
tree.heading("i.d.", text="ID")
tree.heading("name", text="Name")
tree.heading("email", text="Email")
tree.heading("d.o.b", text="D.O.B")
tree.heading("gender", text="Gender")
tree.heading("contact", text="Contact No")
tree.heading("address", text="Address")
tree["show"] = "headings"
tree.pack(fill=BOTH, expand=1)
DisplayData()
# function to update data into database
def Update():
""" Update function is used to edit and save user's information in the database """
database()
# getting form data
name1 = name.get()
con1 = contact.get()
email1 = email.get()
id1 = id_no.get()
dob1 = dob.get()
gender1 = gender.get()
address1 = address.get()
# applying empty validation
if name1 == '' or con1 == '' or email1 == '' or id1 == '' or dob1 == '' or gender1 == "" or address1 == "":
tkMessageBox.showinfo("Warning", "fill the empty field!!!")
else:
# getting selected data
curItem = tree.focus()
contents = (tree.item(curItem))
selecteditem = contents['values']
# update query
conn.execute(
f'UPDATE STUD_REGISTRATION SET STU_ID=?,STU_NAME=?,STU_EMAIL=?,STU_DOB =?,STU_GENDER = ?, STU_CONTACT=?, STU_ADDRESS=? WHERE STU_ID = ?',
(id1, name1, email1, dob1, gender1, con1, address1, selecteditem[0]))
conn.commit()
tkMessageBox.showinfo("Message", "Updated successfully")
# reset form
Reset()
# refresh table data
DisplayData()
conn.close()
def register():
database()
# getting form data
name1 = name.get()
con1 = contact.get()
email1 = email.get()
id1 = id_no.get()
dob1 = dob.get()
gender1 = gender.get()
address1 = address.get()
# applying empty validation
if name1 == '' or con1 == '' or email1 == '' or id1 == '' or dob1 == '' or gender1 == "" or address1 == "":
tkMessageBox.showinfo("Warning", "fill the empty field!!!")
else:
conn.execute(f'''INSERT INTO STUD_REGISTRATION VALUES (:a,:b,:c,:d,:e,:f,:g)''',
{"a": id1, "b": name1, "c": email1, "d": dob1, "e": gender1, "f": con1, "g": address1})
conn.commit()
tkMessageBox.showinfo("Message", "Stored successfully")
# refresh table data
DisplayData()
conn.close()
def Reset():
# clear current data from table
tree.delete(*tree.get_children())
# refresh table data
DisplayData()
# clear search text
SEARCH.set("")
name.set("")
contact.set("")
email.set("")
id_no.set("")
dob.set("")
gender.set("")
address.set("")
def Delete():
# open database
database()
if not tree.selection():
tkMessageBox.showwarning("Warning", "Select data to delete")
else:
result = tkMessageBox.askquestion('Confirm', 'Are you sure you want to delete this record?',
icon="warning")
if result == 'yes':
curItem = tree.focus()
contents = (tree.item(curItem))
selecteditem = contents['values']
tree.delete(curItem)
cursor = conn.execute("DELETE FROM STUD_REGISTRATION WHERE STU_ID = %d" % selecteditem[0])
conn.commit()
cursor.close()
conn.close()
# defining function to access data from SQLite database
def DisplayData():
# open database
database()
# clear current data
tree.delete(*tree.get_children())
# select query
cursor = conn.execute("SELECT * FROM STUD_REGISTRATION")
# fetch all data from database
fetch = cursor.fetchall()
# loop for displaying all data in GUI
for data in fetch:
tree.insert('', 'end', values=(data))
tree.bind("<Double-1>", OnDoubleClick)
cursor.close()
conn.close()
def OnDoubleClick(self):
# getting focused item from treeview
curItem = tree.focus()
contents = (tree.item(curItem))
selecteditem = contents['values']
# set values in the fields
id_no.set(selecteditem[0])
name.set(selecteditem[1])
email.set(selecteditem[2])
dob.set(selecteditem[3])
gender.set(selecteditem[4])
contact.set(selecteditem[5])
address.set(selecteditem[6])
# calling function
displayform()
if __name__ == '__main__':
# Running Application
mainloop() |
9f03da334a6ca63a3835f6a9082d5fa7543dace5 | svn2github/pyquante | /PyQuante/Util.py | 1,031 | 3.9375 | 4 | def parseline(line,format):
"""
Return the line split and with particular formats applied.
Format characters:
x Skip this record
s Convert the record to a string
f Convert the record to a float
d Convert the record to an int
i Convert the record to an int
Examples:
>>> parseline('H 0.0 0.0 0.0','sfff')
'H', 0.0, 0.0, 0.0
>>> parseline('H 0.0 0.0 0.0','xfff')
0.0, 0.0, 0.0
"""
xlat = {'x':None,'s':str,'f':float,'d':int,'i':int}
result = []
words = line.split()
if len(words) < len(format): return None
for i in xrange(len(format)):
f = format[i]
trans = xlat.get(f)
if trans: result.append(trans(words[i]))
if len(result) == 0: return None
if len(result) == 1: return result[0]
return result
def cleansym(s):
"""This function strips off the garbage (everything after and including
the first non-letter) in an element name."""
import re
return re.split('[^a-zA-Z]',s)[0]
|
d3d9a97c2707e954968d6cf037373c8b38a70f53 | robertrbeckett/Tic-Tac-Toe | /tic-tac-toe.py | 4,311 | 4.25 | 4 | #Text-Based Tic Tac Toe (Computer Makes Moves Randomly)
#Using https://repl.it/languages/python3
#Author: Robert Beckett
from random import randint
#This function prints the board. (View section)
def PrintBoard():
print(a1, a2, a3)
print(b1, b2, b3)
print(c1, c2, c3)
print("\n")
#This function checks whether either x or o has 3 in a row for a given set of 3 variables. (Model Section)
def WinTest(wtone, wttwo, wtthree):
if wtone == " X " and wttwo == " X " and wtthree == " X ":
PrintBoard()
print("You win!")
quit()
if wtone == " O " and wttwo == " O " and wtthree == " O ":
PrintBoard()
print("Computer Wins!")
quit()
#This function uses WinTest to check every possible win on the board. (Model Section)
def HasSomeoneWon():
WinTest(a1, a2, a3)
WinTest(b1, b2, b3)
WinTest(c1, c2, c3)
WinTest(a1, b1, c1)
WinTest(a2, b2, c2)
WinTest(a3, b3, c3)
WinTest(a1, b2, c3)
WinTest(a3, b2, c1)
if a1 != " - " and a2 != " - " and a3 != " - " and b1 != " - " and b2 != " - " and b3 != " - " and c1 != " - " and c2 != " - " and c3 != " - ":
print("Cat's Game!")
PrintBoard()
quit()
def ValidateAndPlay(turn, XorO): #Check if the cell is empty. If so play and return "False". Otherwise, return, "True." (Model Section)
global a1, a2, a3, b1, b2, b3, c1, c2, c3
if turn == str('a1') and a1 == " - ": #validate that cell is empty
a1 = XorO
return False
elif turn == str('a2') and a2 == " - ":
a2 = XorO
return False
elif turn == str('a3') and a3 == " - ":
a3 = XorO
return False
elif turn == str('b1') and b1 == " - ":
b1 = XorO
return False
elif turn == str('b2') and b2 == " - ":
b2 = XorO
return False
elif turn == str('b3') and b3 == " - ":
b3 = XorO
return False
elif turn == str('c1') and c1 == " - ":
c1 = XorO
return False
elif turn == str('c2') and c2 == " - ":
c2 = XorO
return False
elif turn == str('c3') and c3 == " - ":
c3 = XorO
return False
else:
return True
def HumanTurn(): #input a cell from player (Control Section)
playing = True
while playing == True:
global a1, a2, a3, b1, b2, b3, c1, c2, c3
print ('Please enter an unoccupied space using these codes:')
print ("\n")
print ('a1, a2, a3')
print ('b1, b2, b3')
print ('c1, c2, c3')
turn = input()
if ValidateAndPlay(turn, " X ") == False:
playing = False
#This function has a while loop that generates a random number between 1 and 9, checks if the corresponding spot on the board is empty, then plays if the spots available. If it's not available, it generates another random number and tries again. (Model Section)
def ComputerTurn():
playing = True
while playing == True:
global a1, a2, a3, b1, b2, b3, c1, c2, c3
randturn = randint(1,9)
if randturn == 1 and ValidateAndPlay("a1", " O ") == False:
playing = False
elif randturn == 2 and ValidateAndPlay("a2", " O ") == False:
playing = False
elif randturn == 3 and ValidateAndPlay("a3", " O ") == False:
playing = False
elif randturn == 4 and ValidateAndPlay("b1", " O ") == False:
playing = False
elif randturn == 5 and ValidateAndPlay("b2", " O ") == False:
playing = False
elif randturn == 6 and ValidateAndPlay("b3", " O ") == False:
playing = False
elif randturn == 7 and ValidateAndPlay("c1", " O ") == False:
playing = False
elif randturn == 8 and ValidateAndPlay("c2", " O ") == False:
playing = False
elif randturn == 9 and ValidateAndPlay("c3", " O ") == False:
playing = False
#This introduces variables used to see if someone has won.
#This sets up the variables for the board at the beginng of a game.
def gameinit():
global a1, a2, a3, b1, b2, b3, c1, c2, c3
a1 = " - "
a2 = " - "
a3 = " - "
b1 = " - "
b2 = " - "
b3 = " - "
c1 = " - "
c2 = " - "
c3 = " - "
def main():
gameinit()
print("Welcome to Tic Tac Toe!")
#In this section, it randomly chooses the first player.
#The computer also always assigns O's to the computer and X's to the human.
#Eventually it'll be nice and ask if the user wants to go first
#or play X's or O's.
#pick 1 or 2. This is the start number.
i = randint(1,2)
while i < 15:
PrintBoard()
#Even numbers = user goes.
if i % 2 == 0: #
HumanTurn()
HasSomeoneWon()
#Otherwise= computer goes.
else:
ComputerTurn()
HasSomeoneWon()
i += 1
main()
|
540aae5486f38c2c8a3954ac15e72f4c64b1d9ad | klaudiar/Lab_02 | /Server.py | 1,306 | 3.75 | 4 | from rock_paper_scissors import *
class Server:
my_choice = 0
def __init__(self, address, port):
self.server(address, port)
def server(self, address, port):
connection = runSocket(address, port)
answer = 0
while answer == 0:
while True:
try:
self.choice = int(connection.recv(1024)) # data size - 1024
break
except ValueError:
text = 'You must write a number'
print(text)
connection.send(text)
text, answer = yourChoice(self.choice)
connection.send(text)
my_choice, text = serverChoice()
connection.send(text)
if self.choice-1 == my_choice or (self.choice == 1 and my_choice == 3):
print("Client won")
text = '!! WINNER !!'
elif self.choice+1 == my_choice or (self.choice == 3 and my_choice == 1):
print("Server won")
text = 'LOOSER'
elif self.choice == my_choice:
print("Remis")
text = 'Remis'
connection.send(text)
connection.close()
if __name__ == "__main__":
host = 'localhost'
port = 50001
data_size = 1024
server = Server(host, port)
|
138922bf805c35255037d86640adc1e8a8dfbf2c | ingoGuzman/SoftArq2020 | /Tutorial_4_PyTest_TDD/fizzbuzz/fizz.py | 232 | 3.53125 | 4 | from checker import has_3
from checker import has_5
def buzz(n):
a=False
for i in range (1,n+1):
a=""
if i%3==0 or has_3(i):
a+="Fizz"
if i%5==0 or has_5(i):
a+="Buzz"
if a=="":
a=i
print(a)
return a
buzz(150)
|
d3d2936f7426bffb68c80b60457f075a8320d215 | emasters603/coding-challenges | /wonders_challenge.py | 576 | 3.796875 | 4 | Cards = ['w/b/s/o', 'w', 's/b', 's'] #for testing can make it raw input
make = "WWSS" #this is the final answer I am seeing if the cards can make
def sort(cards, make):
for i in cards:
i.split("/")
cards.sort() #sorting so it'll hit faster
need = list(make)
need.sort()
while len(need) > 0: #loop until each one has been verified
for i in cards:
if not [n for n in need]: #if one is impossible whole thing fails
print("nope")
else:
need.remove(n) #progress
print("it works!") #if none left to check then it works
sort(Cards, make) |
a016e66d51b7afc886f9784b23185622e23f3ad6 | coertquinton/population_subset | /subset.py | 1,626 | 3.5625 | 4 | import itertools
import datetime
import time
class SubsetCalculator(object):
def get_subset(self, my_list, target_number):
for i in range(1, len(my_list)+1):
total_tupple = itertools.combinations(my_list, i)
subset_tupple = self.test_sublist(total_tupple, target_number, i)
if (subset_tupple):
return subset_tupple
return None
def test_sublist(self, total_tupple, sub_number, i):
print("starting on tupple length %s at %s" % (i, str(datetime.datetime.now())))
for sub_list in total_tupple:
x = 0
precise_list = []
for number in sub_list:
precise_list.append(number)
x = x + number
if x > sub_number:
break
if x == sub_number:
return precise_list
calculator = SubsetCalculator()
my_list = [18897109, 12828837, 9661105, 6371773, 5965343, 5926800, 5582170, 5564635, 5268860, 4552402, 4335391, 4296250, 4224851, 4192887, 3439809, 3279933, 3095213, 2812896, 2783243, 2710489, 2543482, 2356285, 2226009, 2149127, 2142508, 2134411]
total = sum(my_list)
print('Total of all numbers together is {}.'.format(total))
target_number = 101000000
subset = calculator.get_subset(my_list, target_number)
if subset:
print('The subset which gives {} is {}.'.format(target_number, subset))
print('The sum of the subset is {}'.format(sum(subset)))
else:
print('No subset of {} gives {}.'.format(subset, target_number))
|
fb9656e7a916af86eeef3f4ea02d676d0b2bd899 | yungvldai-practice-2020/cv-stream-viewer | /image_processors.py | 246 | 3.515625 | 4 | import cv2 as cv
def scale(image, w, h):
scale_x = w / 320
scale_y = h / 240
width = int(image.shape[1] * scale_x)
height = int(image.shape[0] * scale_y)
return cv.resize(image, (width, height), interpolation=cv.INTER_AREA)
|
77a7141ae39c329f2e4398647c7e3b0c9954ceed | EraSilv/day2 | /def/tipacalcdef.py | 1,006 | 3.546875 | 4 | # def calc(a,b,suf):
# if suf == '*':
# print( a * b )
# elif suf == '/':
# print(a / b)
# elif suf == '+':
# print(a + b)
# elif suf == '-':
# print(a - b)
# elif suf == '%':
# print(a % b)
# n1 = int(input('NO.1: '))
# n2 = int(input('NO.2: '))
# s = input('TACKS: ')
# calc(n1,n2,s)
#-----------------------------factorial---------------------
# a = int(input('SASAn: '))
# def factorial(x):
# pr=1
# for i in range(2,x+1):
# pr = pr*i
# return pr
# # for i in range (1,a):
# # print('ANS:',i,':' ,factorial(i))
# print('ANS:',factorial(a))
#------------------asdf----------------------------------------
# def progress(num):
# geo = 1
# for i in range(1, num + 1):
# geo = geo * i
# print(geo)
# g = int(
# input('Сан бериниз 1: ')
# )
# g2 = int(
# input('Сан бериниз 2: ')
# )
# progress(g)
# progress(g2)
---------------------------------------------------------------------
|
093dd2b4103c3af5814e06047983dfa877f89e12 | EraSilv/day2 | /Practiceself/day15.py | 2,053 | 3.578125 | 4 | # username = 'ERA'
# print('NAMe: {0}'.format(username))
# print('AGE: {0} yo {1} {2}'.format(24,'Era','Yrysbaev'))
#-----------------------------------------------------------------------------
# num1 = 26
# num2 = 65
# print('{0} + {1} = {2}'.format(num1,num2,num1+num2*2))
#------------------------------------------------------------------------------------
# message = 'how is ur {} ?'.format('bitch')
# print(message)
#------------------------------------------------------------------------------
# bl = input('Say smth dear... : ')
# print('U said ..... {}, i got u '.format(bl))
#--------------------------------------------------------------------------------
# starwars = 1941
# endwars = 1945
# war = '2nd world war started in {} and finished in {}'.format(starwars,endwars)
# print(war)
#------------------------------------------------------------------------------------
# cats = ['panther','lion', 'tiger']
# message = ' {0} ,{1} and {2} are come from cats.'.format(cats[1], cats[0],cats[2])
# print(message)
#----------------------------------------------------------------------------------------
# asia = ['KG', 'Chine','Uzb','Tjk','KZ']
# msg = ' {0},\n {1},\n {2},\n {3}\n {4} are located in Central Asia.'.format(asia[0], asia[1],asia[2],asia[3],asia[4])
# print(msg)
#------------------------------------------------------------------------------
a = ' --FAKE-- '
lorem = '''Lorem Ipsum is simply dummy text {0} of the printing {0} and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled {0} it to make a type specimen book.
It has survived not only five centuries, but also {0} the leap into electronic typesetting, remaining essentially unchanged.
It was {0} popularised in the 1960s with the release of Letraset sheets {0} containing {0} Lorem Ipsum passages,
and more recently with desktop publishing software {0} like Aldus PageMaker including versions of Lorem Ipsum.'''.format(a)
print(lorem) |
e42ee3e2ecd1a0fb40359c837fa60cb53644b865 | EraSilv/day2 | /cw/cww.py | 713 | 3.765625 | 4 | # products = {
# 'утюг': 3500,
# 'телевизов': 24000,
# 'стиральная_машина': 30000,
# 'фен': 5500
# }
# a = products['утюг'] + products['телевизов'] + products['стиральная_машина']+products['фен']
# print(a)
# s = a * 0.85
# print('u need only: ',s, 'dollars')
#---------------------------------------------------------------------------------
# a = input('Введите число: ')
# g = int(a[0])
# b = int(a[1])
# c = int(a[2])
# print("Сумма цифр числа:", g + b + c)
#-------------------------------------------------------------
# a = input("Введите число: ")
# b = a[::-1]
# print(b)
|
c228953849e21432db65957399e9f2b155d60ec7 | EraSilv/day2 | /day5_6_7/Transfermoney.py | 1,140 | 3.84375 | 4 |
print('online shipping from AliEx')
print('way to pay for airpods')
way = (input('PAYMENT: ')).lower()
balance = 6000 #balance
acer = 3500 # costs
if way == 'mastercard':
print('sorry... MS is not maintainig!')
elif way == 'elcard':
print('sorry...Ed is not maintaing!')
elif way == 'visa' or way == 'paypal':
print('')
print('Download....')
card_no = input('Card no.: ')
if len(card_no) > 6 or len(card_no) < 6:
print('Card no. is incorrect...')
quit()
summ = int(input('Amount of money???: '))
if acer > summ:
print('U cant pay less then the costs of the good! ')
else:
print('download...')
print('')
a = 'With check'
b = 'Not'
input('with check or not?:' )
if a == a or b == b:
print('')
print('Download...')
else :
print('Error! ')
print('')
s = float(summ - acer)
print('u have', s ,'on ur card')
print('Successfully paid! Thnks for using our goods! ')
|
68097abbf240ee911dfd9cf5d8b1cc60dedb6bf8 | EraSilv/day2 | /day5_6_7/practice.py | 2,677 | 4.3125 | 4 | # calculation_to_seconds = 24 * 60 * 60
calculation_to_hours = 24
# print(calculation_to_seconds)
name_of_unit = "hours"
#VERSION 1:
# print(f"20 days are {20 * 24 * 60 * 60} seconds")
# print(f"35 days are {35 * 24 * 60 * 60} seconds")
# print(f"50 days are {50 * 24 * 60 * 60} seconds")
# print(f"110 days are {110 * 24 * 60 * 60} seconds")
#VERSION2:
# print(f"20 days are {20 * calculation_to_seconds} {name_of_unit}")
# print(f"35 days are {35 * calculation_to_seconds} {name_of_unit}")
# print(f"50 days are {50 * calculation_to_seconds} {name_of_unit}")
# print(f"110 days are {110 * calculation_to_seconds} {name_of_unit}")
#VERSION3:
# print(f"30 days are {30 * calculation_to_seconds} {name_of_unit}")
# print(f"90 days are {90 * calculation_to_seconds} {name_of_unit}")
# print(f"180 days are {180 * calculation_to_seconds} {name_of_unit}")
# print(f"365 days are {365 * calculation_to_seconds} {name_of_unit}")
######-------------------------------------------------------------------------------------------------------------------------
def days_to_units(num_of_days): #----------- line 52------ exchanged--------
# print(num_of_days > 0) #for true false
# if num_of_days > 0:
# print(f"{num_of_days} days are {num_of_days * calculation_to_hours} {name_of_unit}")
return(f"{num_of_days} days are {num_of_days * calculation_to_hours} {name_of_unit}")
# elif num_of_days == 0:
# return('u entered a 0, please enter a valid positive number!')
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# days_to_units(31 , 'Awesome!')
# days_to_units(35 , 'Looks Good!')
# days_to_units(13)
# days_to_units(90)
# days_to_units(365)
# user_input = input('Hey user, enter a number of days and i will convert it to hours!:\n')
# if user_input.isdigit():
# user_input_number = int(user_input)
# calculated_value = days_to_units(user_input_number)
# print(calculated_value)
# else:
# print('Ur input is not a valid number. Dont ruin my programm!')
# ---------------------------------------------------------------------------------
def validate_and_execute():
if user_input.isdigit():
user_input_number = int(user_input)
if user_input_number > 0:
calculated_value = days_to_units(user_input_number)
print(calculated_value)
elif num_of_days == 0:
print('u entered a 0, please enter a valid positive number!')
else:
print('Ur input is not a valid number. Dont ruin my programm!')
user_input = input('Hey user, enter a number of days and i will convert it to hours!:\n')
validate_and_execute()
|
4e8737d284c7cf01dea8dd82917e1fc787216219 | EraSilv/day2 | /day5_6_7/day7.py | 879 | 4.125 | 4 | # password = (input('Enter ur password:'))
# if len(password) >= 8 and 8 > 0:
# print('Correct! ')
# print('Next----->:')
# else:
# print('Password must be more than 8!:')
# print('Try again!')
# print('Create a new account ')
# login = input('login:')
# email = input('Your e-mail:')
# print('Choose correct password.')
# password = (input('Enter ur password:'))
# if len(password) >= 8 and 8 > 0:
# print('Correct! ')
# print('Next----->:')
# else:
# print('Password must be more than 8!:')
# print('Try again!')
# print('-----------------ENTER-------------------')
# log = input('login or e-mail: ')
# pas = input('password: ')
# if login==log and password==pas:
# print(' Entrance is successfully competed! ')
# else:
# print('password or login is incorrect! ')
# print('Try after a few minutes! ')
|
dce3ca1360dd31c7888f2dd98b256f39eab1ca15 | taylorbenwright/AdventOfCode2019 | /lib/day01.py | 820 | 3.5625 | 4 |
from math import floor
import helpers
@helpers.timer
def solve_01():
masses = [int(line) for line in open("../inputs/day01.txt", "r").read().splitlines()]
fuel_needs = [(floor(mass / 3) - 2) for mass in masses]
return fuel_needs
@helpers.timer
def solve_02():
masses = [int(line) for line in open("../inputs/day01.txt", "r").read().splitlines()]
total_fuel_needed = 0
for mass in masses:
needs_fuel = True
fuel_needs = mass
while needs_fuel:
fuel_needs = (floor(fuel_needs / 3) - 2)
if fuel_needs <= 0:
needs_fuel = False
else:
total_fuel_needed += fuel_needs
return total_fuel_needed
print("Day01 Part01 Solve: {}".format(sum(solve_01())))
print("Day01 Part02 Solve: {}".format(solve_02()))
|
167176ab607d2bc30b88eeb558ce5d71d278347c | ericlarslee/Algorithm_Intro | /Problem_Set/year.py | 1,505 | 3.96875 | 4 | from months import Month
def year_function():
temp_year = Year()
year = tuple(temp_year.month_list)
entry = int(input('which number month are you looking for a holiday in?')) - 1
if year[entry].holidays is not None:
print(f'{year[entry].name} has {year[entry].holiday_name} on {year[entry].holidays}')
else:
print('this month does not have holidays')
class Year:
def __init__(self):
self.month_list = []
self.make_month_list()
def make_month_list(self):
self.month_list.append(Month("January", 1, 31, None, None))
self.month_list.append(Month("February", 2, 28, None, None))
self.month_list.append(Month("March", 3, 31, 14, "Pi Day"))
self.month_list.append(Month("April", 4, 30, None, None))
self.month_list.append(Month("May", 5, 31, None, None))
self.month_list.append(Month("June", 6, 30, None, None))
self.month_list.append(Month("July", 7, 31, None, None))
self.month_list.append(Month("August", 8, 31, None, None))
self.month_list.append(Month("September", 9, 30, None, None))
self.month_list.append(Month("October", 10, 31, None, None))
self.month_list.append(Month("November", 11, 30, None, None))
self.month_list.append(Month("December", 12, 31, None, None))
def find_holiday(self, entry):
search = entry
while True:
print(f'{self.month_list[search].name} has {self.month_list[search].holiday_name}')
|
8d6281cc7b07d7ac5894b3f82495af97a9424dd3 | RaduAlbastroiu/Python-Projects | /Home Projects/Homework number 1.py | 7,551 | 4 | 4 | #
# mainFile.py
#
# Created by Radu Gabriel Albastroiu
#
def matrixRead():
# input reading
print(" Add another matrix, after the last row of the matrix enter an empty row")
matrix = []
while True:
aline = input()
if not len(aline):
break
matrix.append(aline.split())
# print matrix
print("\n Matrix is: ")
for i in matrix:
print(i)
n = len(matrix)
m = len(matrix[0])
# print dimensions
print("\n Matrix dimensions are : ")
print(" - Lines : " + str(n))
print(" - Columns : " + str(m))
return matrix
# add two matrices
def addmatrix(matrixA, matrixB):
#nA mB nB mB represent matrices dimensions
nA = len(matrixA)
mA = len(matrixA[0])
nB = len(matrixB)
mB = len(matrixB[0])
#only if the two matrices have the same dimensions
if nA != nB or mA != mB:
print("\n Matrix with different dimensions can not be added")
else:
#create matrix C
matrixC = []
for i in range(nA):
aline = []
for j in range(mA):
#every element of C is the concatenation between two elements, from A and B
aline.append(matrixA[i][j] + matrixB[i][j])
matrixC.append(aline)
# print matrix
print("\n Matrix resulted is: ")
for i in matrixC:
print(i)
# search in matrix the string
def searchmatrixforstring(matrix, strn):
listi = []
listj = []
i = 0
# i and j represent line and column
for line in matrix:
i += 1
j = 0
# search every line of the matrix element by element
for element in line:
j += 1
if element == strn:
listi.append(i)
listj.append(j)
# if the string wasn't found
if len(listi) == 0:
print("\n String not found")
# if the string was found print all the aparitions
else:
print("\n String found in " + str(len(listi)) + " places \n")
for i in range(len(listi)):
print(" #" + str(i) + " line: " + str(listi[i]) + " and column: " + str(listj[i]))
# given the line and column matrices and line lenght this function creates the string for position i and j in the result matrix
def multiplylines(matrixA, matrixB, i, j, mA):
# "b"-"a" is not supported so i couldn't transform from "bb" to 11
# instead i chosed to implement the next rule "ax" * "bb" = "ax" + "bb" = "axbb"
# example : a b + a b = aabc abbd
# c d c d cadc cbdd
alist = []
for k in range(mA):
alist.append(matrixA[i][k] + matrixB[k][j])
final = ""
for ele in alist:
final += ele
return final
# this function multiply the matrices using function multiplylines
def multiplymatrix(matrixA, matrixB):
#nA mB nB mB represent matrices dimensions
nA = len(matrixA)
mA = len(matrixA[0])
nB = len(matrixB)
mB = len(matrixB[0])
if nA != mB or mA != nB:
print("\n Matrix with different dimensions can not be multiplied")
else:
#for every position in final matrix we call multiplylines()
matrixC = []
for i in range(nA):
alist = []
for j in range(mA):
alist.append(multiplylines(matrixA, matrixB, i, j, mA))
matrixC.append(alist)
# print matrix
print("\n Matrix resulted is: ")
for i in matrixC:
print(i)
# compares two matrices
def comparematrix(matrixA, matrixB):
#nA mB nB mB represent matrices dimensions
nA = len(matrixA)
mA = len(matrixA[0])
nB = len(matrixB)
mB = len(matrixB[0])
if mA != mB:
print("\n Matrix with different dimensions can not be compared")
else:
semn = 0
# compares element by elemnt
# break at first difference
for i in range(nA):
for j in range(mA):
if matrixA[i][j] < matrixB[i][j]:
semn = 1
break
elif matrixA[i][j] > matrixB[i][j]:
semn = 2
break
elif matrixA[i][j] == matrixB[i][j]:
semn = 3
# semn represents the result after comparison
if semn == 1:
print("\n Second matrix is in lexicographical order after the First one ")
elif semn == 2:
print("\n First matrix is in lexicographical order after the Second one ")
else:
print("\n The matrices are identical")
# main
listofmatrices = []
# while for the options menu
while True:
op = int(input("\n Chose your option: \n 1. Add new matrix \n 2. Add two matrices \n 3. Search string in a matrix \n 4. Multiply matrices \n 5. Compare matrices \n 6. Stop \n Your option : "))
# add new matrix option
if op == 1:
matrix = matrixRead()
listofmatrices.append(matrix)
print(" There are " + str(len(listofmatrices)) + " matrices in the program")
# add two matrices option
elif op == 2:
if len(listofmatrices) < 2:
print(" Add another matrix in the program")
else:
print("\n Which matrices you want to add? ")
first = int(input(" Index of the first matrix : "))
second = int(input(" Index of the second matrix : "))
if first >= len(listofmatrices) or second >= len(listofmatrices):
print(" The index is not found in the list of matrices! ")
else:
addmatrix(listofmatrices[first], listofmatrices[second])
# search string in a matrix option
elif op == 3:
strng = input(" String to be searched: ")
nr = int(input(" Index of the matrix in which it will be seached: "))
if nr >= len(listofmatrices):
print(" The index is not found in the list of matrices! ")
else:
searchmatrixforstring(listofmatrices[nr], strng)
# multiply matrices option
elif op == 4:
if len(listofmatrices) < 2:
print(" Add another matrix in the program")
else:
print("\n Which matrices you want to multiply? ")
first = int(input(" Index of the FIRST matrix : "))
second = int(input(" Index of the SECOND matrix : "))
if first >= len(listofmatrices) or second >= len(listofmatrices):
print(" The index is not found in the list of matrices! ")
else:
multiplymatrix(listofmatrices[first], listofmatrices[second])
# compare matrices option
elif op == 5:
if len(listofmatrices) < 2:
print(" Add another matrix in the program")
else:
print("\n Which matrices you want to compare? ")
first = int(input(" Index of the FIRST matrix : "))
second = int(input(" Index of the SECOND matrix : "))
if first >= len(listofmatrices) or second >= len(listofmatrices):
print(" The index is not found in the list of matrices! ")
else:
comparematrix(listofmatrices[first], listofmatrices[second])
# break while loop
else:
break
|
2bb0afcd6465edcffe436a298ff3a3abf36246d5 | RaduAlbastroiu/Python-Projects | /Home Project4/RaduAlbastroiu.py | 690 | 4.03125 | 4 | # Homework2 Radu Albastroiu
# Homework number: 2
from Bank import Bank
# bank init, there could be more banks but for ease will use just one
ING = Bank()
comand = 1
while comand > 0:
# command for bank :
# - new account
# - login
# - delete account
comand = int(input("For creating a new account enter 1, for log in enter 2, for delete an account enter 3, for stop enter 0: "))
if comand == 1:
ING.newAccount()
if comand == 2:
accountNr = input("Enter your account Number: ")
accountPin = input("Enter your account Pin: ")
ING.login(accountNr, accountPin)
if comand == 3:
ING.delAccount() |
08a01f3a3fa969e0e40ef89d06b788995d441612 | Sean7419/sort-visualizer | /SortAlgoVis/visualizer.py | 3,989 | 3.65625 | 4 | from tkinter import *
from tkinter import ttk
import random
from sortAlgos import bubble_sort, merge_sort
# Global Variables
data = []
# Functions
def display_data(data, color_list):
"""
This function will clear the old data from canvas and display the new data
data is normalized to allow bars to be sized relative to one another
:param data: list that contains the generated data
:param color_list: list of colors. green indicates the data point being checked
:return: None
"""
data_canvas.delete("all")
canvas_width = 600
canvas_height = 380
# Calculate the width of the bars
bar_width = canvas_width / (len(data) + 1)
# Offset and Spacing will space out each bar from border and one another
offset = 30
spacing = 10
# Must normalize the data so bars are sized relative to one another
normalized_data = [i/max(data) for i in data]
for i, ht in enumerate(normalized_data):
x0 = i * bar_width + offset + spacing
y0 = canvas_height - ht * 340 # Multiplied by 340 to allow 40 pixels above the largest bar
x1 = (i+1) * bar_width + offset
y1 = canvas_height
data_canvas.create_rectangle(x0, y0, x1, y1, fill=color_list[i])
data_canvas.create_text(x0 + 2, y0, anchor=SW, text=str(data[i]))
root.update()
def generate():
"""
This function is called to generate a random set of data
The function gets the values put in by the user scales/sliders
:return: None
"""
global data
data = []
# Generate a random data set
for _ in range(usr_size.get()):
data.append(random.randrange(usr_min.get(), usr_max.get()+1))
display_data(data, ['red' for x in range(len(data))])
# Setup of root window
root = Tk()
root.title("Sorting Visualizer")
root.maxsize(900, 600)
root.config(bg="black")
def start_sort():
"""
Function determines which sort to use, then calls the function
:return: None
"""
global data
if algo_box.get() == "Bubble Sort":
bubble_sort(data, display_data, speed_scale.get())
elif algo_box.get() == "Merge Sort":
merge_sort(data, display_data, speed_scale.get())
#######
# UI
#######
# Setup Frame for UI
UI_frame = Frame(root, width=600, height=200, bg="grey")
UI_frame.grid(row=0, column=0, padx=10, pady=5)
user_algo = StringVar() # StringVar for saving the sort algo to use
# Label amd Combobox to use dropdown menu selector for algorithm
algo_selection = Label(UI_frame, text="Select Algorithm: ", bg="grey")
algo_selection.grid(row=0, column=0, padx=5, pady=5, sticky=W)
algo_box = ttk.Combobox(UI_frame, textvariable=user_algo, width="10", values=["Bubble Sort", "Merge Sort"])
algo_box.grid(row=0, column=1, padx=5, pady=5)
algo_box.current(0)
# Speed Scale
speed_scale = Scale(UI_frame, from_=0.1, to=2.0, length=200, digits=2, resolution=0.2, orient=HORIZONTAL,
label="Speed")
speed_scale.grid(row=1, column=0, padx=5, pady=5)
# Size Scale
usr_size = Scale(UI_frame, from_=3, to=30, resolution=1, length=150, orient=HORIZONTAL, label="Size of Data")
usr_size.grid(row=1, column=1, padx=5, pady=5, sticky=W)
# Min Value Scale
usr_min = Scale(UI_frame, from_=1, to=30, resolution=1, length=150, orient=HORIZONTAL, label="Min Value")
usr_min.grid(row=1, column=2, padx=5, pady=5, sticky=W)
# Max Value Scale
usr_max = Scale(UI_frame, from_=1, to=30, resolution=1, length=150, orient=HORIZONTAL, label="Max Value")
usr_max.grid(row=1, column=3, padx=5, pady=5, sticky=W)
# Generate Button
gen_button = Button(UI_frame, text="Generate", command=generate, bg='white')
gen_button.grid(row=2, column=0, padx=5, pady=5)
# Start Button
start = Button(UI_frame, text="Start", command=start_sort)
start.grid(row=2, column=1, padx=5, pady=5)
########
# CANVAS
########
# Setup canvas for displaying data
data_canvas = Canvas(root, width=600, height=380, bg="white")
data_canvas.grid(row=1, column=0, padx=10, pady=5)
root.mainloop()
|
736fe753e179f2650d038206df41cd0671b48e77 | Naitik-Gandhi/Best-Enlist | /Day2.py | 1,560 | 4.03125 | 4 | Python 3.9.5
>>> print("30 days 30 hour challenge")
30 days 30 hour challenge
>>> print('30 days 30 hour challenge')
30 days 30 hour challenge
>>> Hours = "thirty" print(Hours)
SyntaxError: invalid syntax
>>> Hours = "thirty"
>>> print(Hours)
thirty
>>> Days = "Thirty days"
>>> print(Days[0])
T
>>> print(Days[4])
t
>>> Challenge = "I will win"
>>> print(Challenge[7:10])
win
>>> print(len(Challenge))
10
>>> print(Challenge.lower())
i will win
>>> a = "30 Days"
>>> b = "30 hours"
>>> c = a + b
>>> print(c)
30 Days30 hours
>>> c = a + ' ' + b
>>> print(c)
30 Days 30 hours
>>> text = "Thirty days and Thirty hours"
>>> x = text.casefold()
>>> print(x)
thirty days and thirty hours
>>> x = 'DON’T TROUBLE TROUBLE UNTIL TROUBLE TROUBLES YOU.'
>>> print(x)
DON’T TROUBLE TROUBLE UNTIL TROUBLE TROUBLES YOU.
>>> a = x.casefold()
>>> print(a)
don’t trouble trouble until trouble troubles you.
>>> txt = "DON’T TROUBLE TROUBLE UNTIL TROUBLE TROUBLES YOU."
>>> a = txt.isalpha()
>>> print(a)
False
>>> a = txt.isalnum()
>>> print(a)
False
>>> a = txt.capitalize()
>>> print(a)
Don’t trouble trouble until trouble troubles you.
>>> a = txt.casefold()
>>> print(a)
don’t trouble trouble until trouble troubles you.
>>> a = txt.find('t')
>>> print(a)
-1
>>> a = txt.find('a')
>>> print(a)
-1
>>> a = txt.find('T')
>>> print(a)
4
>>> txt = ('TutorialDay2')
>>> a = txt.isalnum()
>>> print(a)
True
>>> a = txt.isalpha()
>>> print(a)
False
|
76f09844a2ee8abc1ebb5d7be2432a9f7b568a93 | Aayushi-Mittal/Udayan-Coding-BootCamp | /session3/Programs-s3.py | 648 | 4.3125 | 4 | """
a = int(input("Enter your value of a: ") )
b = int(input("Enter your value of b: ") )
print("Adding a and b")
print(a+b)
print("Subtract a and b")
print(a-b)
print("Multiply a and b")
print(a*b)
print("Divide a and b")
print(a/b)
print("Remainder left after dividing a and b")
print(a%b)
# Program 2
name=input("Enter your name")
print("Hello "+name)
# Program 3
c = int(input("Enter your value of c: ") )
print(c%10)
"""
# Program 4
signal=input("Enter the color of the signal : ")
if(signal=="red") :
print("STOP!")
elif(signal=="yellow") :
print("WAIT!")
elif(signal=="green") :
print("GO!")
else :
print("invalid choice")
|
3253b6843f4edd1047c567edc5a1d1973ead4b00 | watson1227/Python-Beginner-Tutorials-YouTube- | /Funtions In Python.py | 567 | 4.21875 | 4 | # Functions In Python
# Like in mathematics, where a function takes an argument and produces a result, it
# does so in Python as well
# The general form of a Python function is:
# def function_name(arguments):
# {lines telling the function what to do to produce the result}
# return result
# lets consider producing a function that returns x^2 + y^2
def squared(x, y):
result = x**2 + y**2
return result
print(squared(10, 2))
# A new function
def born (country):
return print("I am from " + country)
born("greensboro") |
0081a9128b1bb5a3c0821900d8fdcd043c4d03bc | HAMZA-420/Word-Search-Game | /WORD SEARCH GAME.py | 20,990 | 4.1875 | 4 | def game():
import random
#A subroutine to replace all "-" (empty characters) with a random letter
def randomFill(wordsearch):
LETTERS="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for row in range(0,12):
for col in range(0,12):
if wordsearch[row][col]=="-":
randomLetter = random.choice(LETTERS)
wordsearch[row][col]=randomLetter
#A subroutine to output the wordsearch on screen
def displayWordsearch(wordsearch):
print(" _________________________")
print("| |")
for row in range(0,12):
line="| "
for col in range(0,12):
line = line + wordsearch[row][col] + " "
line = line + "|"
print(line)
print("|_________________________|")
#A subroutine to add a word to the wordsearch at a random position
def addWord(word,wordsearch):
row=random.randint(0,11)
col=0
for i in range(0,len(word)):
wordsearch[row][col+i]=word[i]
# ----Randomly decide where the word will start
# ----Decide if the word will be added horizontally, vertically or diagonally
# ----Check that the word will fit in (within the 12 by 12 grid)
# ----Check that the word will not overlap with existing letters/words in the wordsearch
#Create an empty 12 by 12 wordsearch (list of lists)
wordsearch = []
for row in range(0,12):
wordsearch.append([])
for col in range(0,12):
wordsearch[row].append("-")
print("\nWELCOME TO WORD SEARCH GAME!")
print("\n1. Easy\n2. Medium\n3. Hard")
mode = eval(input("\nPlease select game mode\nSr No: "))
if mode==1:
#Adding words to our wordsearch
addWord("PYTHON",wordsearch)
addWord("ALGORITHM",wordsearch)
addWord("CODING",wordsearch)
addWord("PROGRAM",wordsearch)
addWord("HELLO",wordsearch)
#All unused spaces in the wordsearch will be replaced with a random letter
randomFill(wordsearch)
#Display the fully competed wordseach on screen
displayWordsearch(wordsearch)
print("\nYou have three Chances:\n")
print("Game will Starts in 5 Seconds: ")
count = 0
while count<=3:
if count == 1:
import winsound
import sys
import time
timeLoop = True
# Variables to keep track and display
Sec = 0
# Begin Process
while timeLoop:
while Sec!=5:
Sec += 1
sys.stdout.write(str(Sec) + "'s, ")
frequency = 300 # Set Frequency To 300 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
time.sleep(1)
if Sec==5:
print("\n\nLets Start Now!")
first_chance= input("\nEnter your word: ")
if first_chance == "PYTHON" or first_chance =="ALGORITHM" or first_chance =="CODING" or first_chance =="PROGRAM" :
print("You Won first Chance, HURRAH!")
else:
print("You lost your 1st chance")
break
break
if count == 2:
randomFill(wordsearch)
displayWordsearch(wordsearch)
print("\n2nd Chance")
print("\nPlease Enter any Word other than 1st Input")
print("\nGame will starts after 3 seconds")
import winsound
import sys
import time
timeLoop = True
# Variables to keep track and display
Sec = 0
# Begin Process
while timeLoop:
while Sec!=3:
Sec += 1
sys.stdout.write(str(Sec) + "'s, ")
frequency = 300 # Set Frequency To 300 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
time.sleep(1)
if Sec==3:
print("\n\nLets Start Now!")
second_chance = input("\nEnter your word: ")
if second_chance==first_chance:
print("\nYou've already entered this word\n find another one")
second_chance = input("\nEnter your word: ")
if second_chance == "PYTHON" or second_chance =="ALGORITHM" or second_chance =="CODING" or second_chance =="PROGRAM":
print("You Won 2nd Chance, HURRAH!")
else:
print("You lost your 2nd chance")
break
break
if count == 3:
randomFill(wordsearch)
displayWordsearch(wordsearch)
print("\n3rd Chance")
print("\nPlease Enter any Word other than 1st and 2nd Input")
print("\nGame will starts after 3 seconds")
import winsound
import sys
import time
timeLoop = True
# Variables to keep track and display
Sec = 0
# Begin Process
while timeLoop:
while Sec!=3:
Sec += 1
sys.stdout.write(str(Sec) + "'s, ")
frequency = 300 # Set Frequency To 300 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
time.sleep(1)
if Sec==3:
print("\n\nLets start Now!")
Third_chance = input("\nEnter your word: ")
if Third_chance==first_chance or Third_chance==second_chance:
print("\nYou've already entered this word\n find another one")
Third_chance = input("\nEnter your word: ")
if Third_chance == "PYTHON" or Third_chance =="ALGORITHM" or Third_chance =="CODING" or Third_chance =="PROGRAM":
print("You Won 3rd Chance, HURRAH!")
else:
print("You lost your 3rd chance")
def player_choice(): #Ask Player whether he wants to restart game or exit
print("\nWhats you like!")
print("1.Restart\n2.Exit")
Ask_Player = eval(input("Enter Here: "))
if Ask_Player == 1:
game()
elif Ask_Player ==2:
print("\nThank You for Being Here\n Good Bye")
sys.exit()
else:
print("Please select from given options")
player_choice()
player_choice()
break
break
count+=1
if mode==2:
addWord("ALGORITHM",wordsearch)
addWord("PROGRAM",wordsearch)
addWord("CODING",wordsearch)
addWord("MICROSOFT",wordsearch)
randomFill(wordsearch)
displayWordsearch(wordsearch)
print("\nYou have three Chances:\n")
print("Game will Starts in 5 Seconds: ")
count = 0
while count<=3:
if count == 1:
import winsound
import sys
import time
timeLoop = True
# Variables to keep track and display
Sec = 0
# Begin Process
while timeLoop:
while Sec!=5:
Sec += 1
sys.stdout.write(str(Sec) + "'s, ")
frequency = 300 # Set Frequency To 300 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
time.sleep(1)
if Sec==5:
print("\n\nLets Start Now!")
first_chance= input("\nEnter your word: ")
if first_chance =="ALGORITHM" or first_chance =="CODING" or first_chance =="PROGRAM" :
print("You Won first Chance, HURRAH!")
else:
print("You lost your 1st chance")
break
break
if count == 2:
randomFill(wordsearch)
displayWordsearch(wordsearch)
print("\n2nd Chance")
print("\nPlease Enter any Word other than 1st Input")
print("\nGame will starts after 3 seconds")
import winsound
import sys
import time
timeLoop = True
# Variables to keep track and display
Sec = 0
# Begin Process
while timeLoop:
while Sec!=3:
Sec += 1
sys.stdout.write(str(Sec) + "'s, ")
frequency = 300 # Set Frequency To 300 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
time.sleep(1)
if Sec==3:
print("\n\nLets Start Now!")
second_chance = input("\nEnter your word: ")
if second_chance==first_chance:
print("\nYou've already entered this word\n find another one")
second_chance = input("\nEnter your word: ")
if second_chance =="ALGORITHM" or second_chance =="CODING" or second_chance =="PROGRAM" :
print("You Won 2nd Chance, HURRAH!")
else:
print("You lost your 2nd chance")
break
break
if count ==3:
randomFill(wordsearch)
displayWordsearch(wordsearch)
print("\n3rd Chance")
print("\nPlease Enter any Word other than 1st and 2nd Input")
print("\nGame will starts after 3 seconds")
import winsound
import sys
import time
timeLoop = True
# Variables to keep track and display
Sec = 0
# Begin Process
while timeLoop:
while Sec!=3:
Sec += 1
sys.stdout.write(str(Sec) + "'s, ")
frequency = 300 # Set Frequency To 300 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
time.sleep(1)
if Sec==3:
print("\n\nLets start Now!")
Third_chance = input("\nEnter your word: ")
if Third_chance==first_chance or Third_chance==second_chance:
print("\nYou've already entered this word\n find another one")
Third_chance = input("\nEnter your word: ")
if Third_chance == "ALGORITHM" or Third_chance == "CODING" or Third_chance == "PROGRAM":
print("You Won 3rd Chance, HURRAH!")
else:
print("You lost your 3rd chance")
def player_choice(): #Ask Player whether he wants to restart game or exit
print("\nWhats you like!")
print("1.Restart\n2.Exit")
Ask_Player = eval(input("Enter Here: "))
if Ask_Player == 1:
game()
elif Ask_Player ==2:
print("\nThank You for Being Here\n Good Bye")
sys.exit()
else:
print("Please select from given options")
player_choice()
player_choice()
break
break
count+=1
if mode==3:
addWord("PROGRAM",wordsearch)
addWord("CODING",wordsearch)
addWord("JAVA",wordsearch)
randomFill(wordsearch)
displayWordsearch(wordsearch)
print("\nYou have three Chances:\n")
print("Game will Starts in 5 Seconds: ")
count = 0
while count<=3:
if count == 1:
import winsound
import sys
import time
timeLoop = True
# Variables to keep track and display
Sec = 0
# Begin Process
while timeLoop:
while Sec!=5:
Sec += 1
sys.stdout.write(str(Sec) + "'s, ")
frequency = 300 # Set Frequency To 300 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
time.sleep(1)
if Sec==5:
print("\n\nLets Start Now!")
first_chance= input("\nEnter your word: ")
if first_chance =="CODING" or first_chance =="PROGRAM" or first_chance == "JAVA":
print("You Won first Chance, HURRAH!")
else:
print("You lost your 1st chance")
break
break
if count == 2:
randomFill(wordsearch)
displayWordsearch(wordsearch)
print("\n2nd Chance")
print("\nPlease Enter any Word other than 1st Input")
print("\nGame will starts after 3 seconds")
import winsound
import sys
import time
timeLoop = True
# Variables to keep track and display
Sec = 0
# Begin Process
while timeLoop:
while Sec!=3:
Sec += 1
sys.stdout.write(str(Sec) + "'s, ")
frequency = 300 # Set Frequency To 300 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
time.sleep(1)
if Sec==3:
print("\n\nLets Start Now!")
second_chance = input("\nEnter your word: ")
if second_chance==first_chance:
print("\nYou've already entered this word\n find another one")
second_chance = input("\nEnter your word: ")
if second_chance =="CODING" or second_chance =="PROGRAM" or second_chance == "JAVA":
print("You Won 2nd Chance, HURRAH!")
else:
print("You lost your 2nd chance")
break
break
if count ==3:
randomFill(wordsearch)
displayWordsearch(wordsearch)
print("\n3rd Chance")
print("\nPlease Enter any Word other than 1st and 2nd Input")
print("\nGame will starts after 3 seconds")
import winsound
import sys
import time
timeLoop = True
# Variables to keep track and display
Sec = 0
# Begin Process
while timeLoop:
while Sec!=3:
Sec += 1
sys.stdout.write(str(Sec) + "'s, ")
frequency = 300 # Set Frequency To 300 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
time.sleep(1)
if Sec==3:
print("\n\nLets start Now!")
Third_chance = input("\nEnter your word: ")
if Third_chance==first_chance or Third_chance==second_chance:
print("\nYou've already entered this word\n find another one")
Third_chance = input("\nEnter your word: ")
if Third_chance == "CODING" or Third_chance == "PROGRAM" or Third_chance == "JAVA":
print("You Won 3rd Chance, HURRAH!")
else:
print("You lost your 3rd chance")
def player_choice(): #Ask Player whether he wants to restart game or exit
print("\nWhats you like!")
print("1.Restart\n2.Exit")
Ask_Player = eval(input("Enter Here: "))
if Ask_Player == 1:
game()
elif Ask_Player ==2:
print("\nThank You for Being Here\n Good Bye")
sys.exit()
else:
print("Please select from given options")
player_choice()
player_choice()
break
break
count+=1
else:
print("\nWrong input\nPlease Enter given Sr No")
game()
game()
|
8b742963ccb231788702ea9f266bbbcf9ae9100d | Amina-Yassin/Steve | /Attempt5.py | 155 | 3.828125 | 4 | print ("N1", '\t', "N2", '\t', "N1 * N2",)
print ("-----", '\t', "-----", '\t', "-------")
for x in range (5,21):
print (x, '\t', x, '\t', x*x)
|
6efa2595801663a5a27dbdf37c3a3d8c5423b8c6 | reyandoneil/BelajarPython | /tipedata_dictionary.py | 474 | 3.90625 | 4 | mahasiswa1 = {"NIM":106,
"Nama":"Anang Nugraha",
"Prodi":"Teknik Informatika",
"Status Mahasiswa":"Aktif"}
mahasiswa2 = {"NIM":104,
"Nama":"Aerosh Nugraha",
"Prodi":"Sistem Informasi",
"Status Mahasiswa":"Aktif"}
print(mahasiswa1["Nama"])
print(mahasiswa1.keys())
print(mahasiswa1.values())
print(mahasiswa1.items())
print(100*"=")
list_mahasiswa = {106:mahasiswa1,104:mahasiswa2}
print(list_mahasiswa[104]) |
3dfc2952a75b3645d1ad79c6d21239047f0e16a6 | reyandoneil/BelajarPython | /loopingteknik.py | 886 | 3.546875 | 4 | namaband = ['Noah',
'Ungu',
'Vagetoz',
'Kangen Band',
'Kadal Band']
kumpulanlagu = ['Menunggumu',
'Laguku',
'Kehadiranmu',
'Aku kau dan dia',
'Cinta tak direstui']
#Mengunakan "enumerate" untuk penomoran list
for i,band in enumerate(namaband, start=1):
print(i,band)
print("="*99)
#menggunakan ZIP
for band,lagu in zip(namaband,kumpulanlagu):
print(band, "Memainkkan lagu berjudul:",lagu)
print("="*99)
#set
playlist= {'tetap semangat','ada apa dengan cinta','melupakanmu','terlalu lama sendiri'}
for lagu in sorted(playlist):
print(lagu)
#Dictionary
print("="*99)
playlist2 = {'Noah' : 'Walau habis terang',
'Ungu' : 'Cinta dalam hati',
'Vagetoz' : ' Pergi',
}
for i,v in playlist2.items():
print(i,"lagunya",v) |
ac83e2326fa7af2d2bb63315c52faab99c3de3e3 | reyandoneil/BelajarPython | /list_lanjutan.py | 456 | 3.890625 | 4 | Barang = ['laptop','mouse','cangkir','mangkok','piring']
#method
#method menambah di akhir
Barang.append('sendok')
print(Barang)
#menyisipkan
Barang.insert(3,'keyboard')
Barang.insert(3,'laptop')
print(Barang)
Jumlahlaptop = Barang.count('laptop')
print('jumlah laptop dalam list',Jumlahlaptop)
Barang.remove('cangkir')
print(Barang)
Barang.reverse()
print(Barang)
print(100*"=")
stuff=Barang.copy()
stuff.append('kipas')
print(stuff)
print(Barang) |
a69b5adbcdf6934f43a3f7f424c85071840242e4 | aoishiki/randpoesie | /main.py | 412 | 3.53125 | 4 | # coding=utf-8
import random
import sys
args = sys.argv
if len(args) < 2 :
print("put number")
else :
samplenum = int(args[1])
for line in open('word.txt', 'r') :
wordList = line[:-1].split(',')
listlen = len(wordList)
if samplenum > listlen :
print("引数は",listlen,"以下にしてください")
else :
sampleWords = random.sample(wordList,samplenum)
for word in sampleWords :
print(word) |
93276b1fa5e8647e04e1fc34911d427990fea9c1 | pchamburger/AID1910- | /day15/login_db.py | 1,670 | 3.65625 | 4 | """
模拟注册登录
"""
import pymysql
# 链接数据库
db = pymysql.connect(host='localhost',
port=3306,
user='root',
password='123456',
database='dict',
charset='utf8')
# 获取游标(操作数据库,执行sql语句)
cur = db.cursor()
# 注册
def register():
name = input("用户名:")
password = input("密码:")
# 判断用户名是否重复
sql_find = "select * from user where name = %s"
cur.execute(sql_find, [name])
result = cur.fetchone()
if result:
return False
try:
sql_register = "insert into user (name,password) \
values (%s,%s)"
cur.execute(sql_register, [name, password])
db.commit()
return True
except Exception as e:
db.rollback()
print(e)
return False
# 登录
def login():
name = input("用户名:")
password = input("密码:")
sql_find = "select * from user " \
"where name = %s and password = %s"
cur.execute(sql_find, [name, password])
result = cur.fetchone()
if result:
return True
while True:
print("""===============
1.注册 2.登录
===============
""")
cmd = input("输入命令:")
if cmd == '1':
if register():
print("注册成功")
else:
print("注册失败")
elif cmd == '2':
if login():
print("登录成功")
break
else:
print("登录失败")
else:
print("我也做不到")
# 关闭数据库
cur.close()
db.close()
|
9d428c28ad55ea61b5471c8d866e3a7f01c3de40 | h-skye/random_work | /tictactoe.py | 3,514 | 3.765625 | 4 |
# 7 | 8 | 9
# --+---+--
# 4 | 5 | 6
# --+---+--
# 1 | 2 | 3
class Board():
def __init__(self):
self.state = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
self.num_pad = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3']]
self.number_of_moves = 0
def print_avail_spots(self):
'''
Prints the available spots in a num pad fashion
Unavailable spots are marked as '*'
Available spots are marked with numbers 1-9 accordingly
'''
format = '\n';
for index, row in enumerate(self.num_pad):
if index != 0:
format += '\n'
format += '--+---+--'
format += '\n'
for index, value in enumerate(row):
if (index != 2):
format += value + ' | ';
else:
format += value
return format
def print(self):
'''
Prints the current state board of spots with players' markers if any
'''
format = '\n';
for index, row in enumerate(self.state):
if index != 0:
format += '\n'
format += '--+---+--'
format += '\n'
for index, value in enumerate(row):
if (index != 2):
format += value + ' | ';
else:
format += value
return format
def mark_spot(self, num_spot, marker):
'''
Marks a spot on the current state board.
Takes out the available moves of a num pad state board with an '*'
'''
for row_index, row in enumerate(self.num_pad):
for value_index, value in enumerate(row):
if int(value) == num_spot:
self.state[row_index][value_index] = marker
self.num_pad[row_index][value_index] = '*'
return True
return False
def update_total_moves(self):
'''
Keeps track of the total moves
Earliest winning total move is at 5
'''
self.number_number_of_moves += 1
#Pseudo Code
def suggest_spot(self, marker):
'''
Suggests a spot for the player to make based on the current
reading of the available moves, and current board
'''
for row_index, row in enumerate(self.state):
for value_index, value in enumerate(row):
pass
game1 = Board();
def playGame():
start_game = input('Do you want to play a game? Y or N \n')
while (start_game == 'Y'):
new_game = Board()
print(f'Current game board is: {new_game.print()}')
# Player1 picks a marker
player1_marker = input('Pick X or O to start with \n')
print(f'Player 1 marker is {player1_marker}')
print(f'Current spots available: {new_game.print_avail_spots()}')
# Player1 picks a spot
player1_spot = int(input('Pick a spot \n'))
player1_move = new_game.mark_spot(player1_spot, player1_marker)
if player1_move is False:
print('Pick new spots')
print(f'Current spots available: {new_game.print_avail_spots()}')
else:
new_game.update_total_moves()
print(f'Updated game with spot is {new_game.print()}')
print(f'Current spots available: {new_game.print_avail_spots()}')
break;
print('Game has ended')
playGame()
|
0455a80b366388a6e0c7c6449f15417bff5472f2 | Peter-Zheng-Sp/SafeBoard | /hackathon_2017_developers/solutions/python/11.sum.of.digits.hard/solve.py | 518 | 3.5 | 4 | # Author: Maxim Yurchuk
def get_count(digit, pos, n):
k = 10 ** (pos + 1)
full_cycles = n / k
count = full_cycles * (10 ** pos)
reminder = n % k
if reminder > (digit + 1) * (10 ** pos):
count += 10 ** pos
else:
if reminder > (digit) * (10 ** pos):
count += reminder - (digit) * (10 ** pos)
return count
n = int(open("input.txt").read())
count = 0
for pos in range(20):
for digit in range(10):
count += get_count(digit, pos, n+1) * digit
print count
|
21414bdd6d4af5ff2b2ec2a855d7ef490ad44222 | kumar084/python-challenge | /PyPoll/main.py | 1,251 | 3.53125 | 4 | import os
import csv
# Path to collect data from the Resources folder
election_data = os.path.join( 'Resources', 'election_data.csv')
# Read in the CSV file
with open(election_data, 'r') as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, delimiter=',')
print(csvreader)
#Skipping the header
csv_header =next(csvreader)
#Initializing variables
counter = 0
#Initialize candidates list
candidates = []
comparison_list = []
for row in csvreader:
#print(row)
counter = counter + 1
if row[2] in candidates:
comparison_list[candidates.index(row[2])]+=1
else:
candidates.append(row[2])
comparison_list.append(1)
print("Total votes: " + str(counter) + ".")
print(comparison_list)
print(f"List of candidates: {candidates}")
print(f"Votes won by each candidate: {comparison_list}")
#Export Data into a text file
results=open("Analysis/results.txt","w")
results.write("Eelction Results \n------------------\n")
results.write(f"Total Votes: {counter}\n")
results.write(f"List of candidates: {candidates}")
results.write(f"Votes won by each candidate: {comparison_list}")
|
16afc21ac9d3c72905afdcb28558ade43a850f52 | piyushkashyap07/Application-of-time-complexity | /arrayintersection.py | 836 | 3.609375 | 4 | from sys import stdin
def intersection(arr1, arr2, n, m) :
arr1.sort()
arr2.sort()
i=0
j=0
while i<n and j<m:
if arr1[i]==arr2[j]:
print(arr1[i],end=" ")
i+=1
j+=1
else:
if arr1[i]<arr2[j]:
i+=1
else:
j+=1
# Taking input using fast I/O method
def takeInput() :
n = int(stdin.readline().strip())
if n == 0 :
return list(), 0
arr = list(map(int, stdin.readline().strip().split(" ")))
return arr, n
#main
t = int(stdin.readline().strip())
while t > 0 :
arr1, n = takeInput()
arr2, m = takeInput()
intersection(arr1, arr2, n, m)
print()
t -= 1 |
de12c3cb06a024c01510f0cf70e76721a80d506e | ytlty/coding_problems | /fibonacci_modified.py | 1,049 | 4.125 | 4 | '''
A series is defined in the following manner:
Given the nth and (n+1)th terms, the (n+2)th can be computed by the following relation
Tn+2 = (Tn+1)2 + Tn
So, if the first two terms of the series are 0 and 1:
the third term = 12 + 0 = 1
fourth term = 12 + 1 = 2
fifth term = 22 + 1 = 5
... And so on.
Given three integers A, B and N, such that the first two terms of the series (1st and 2nd terms) are A and B respectively, compute the Nth term of the series.
Input Format
You are given three space separated integers A, B and N on one line.
Input Constraints
0 <= A,B <= 2
3 <= N <= 20
Output Format
One integer.
This integer is the Nth term of the given series when the first two terms are A and B respectively.
Note
Some output may even exceed the range of 64 bit integer.
'''
import sys
from math import pow
a,b,n = tuple(map(int, input().split()))
#print(a,b,n)
nums = []
nums.append(a)
nums.append(b)
n_2 = a
n_1 = b
res = 0
for x in range(2, n):
res = n_1*n_1 + n_2
n_2 = n_1
n_1 = res
print(res)
|
00d5af5d8a37988279c8958ed760ad506cae2e91 | Aryan985/C-103 | /scatter.py | 184 | 3.796875 | 4 | import pandas as pd
import plotly.express as px
df = pd.read_csv("data.csv")
graph = px.scatter(df,x="Population",y="Per capita",color = "Country",size="Percentage")
graph.show() |
b2d68fcbcf523fc294e6c0e7d5126359c0a78e2c | lomnpi/data-structures-and-algorithms-python | /Helpers/nodes.py | 635 | 3.515625 | 4 | class SimpleTreeNode:
def __init__(self, val, left=None, right=None) -> None:
self.val = val
self.left = left
self.right = right
class AdvanceTreeNode:
def __init__(self, val, parent=None, left=None, right=None) -> None:
self.val = val
self.parent = parent
self.left = left
self.right = right
class SingleListNode:
def __init__(self, val, next=None) -> None:
self.val = val
self.next = next
class DoubleListNode:
def __init__(self, val, next=None, prev=None) -> None:
self.val = val
self.next = next
self.prev = prev
|
8d97636d1e094ba6070889cc584ad76b1b2aaf4f | pigmonchu/bzChallenges | /dientes_de_leon/diente_leon_v.2.py | 663 | 3.546875 | 4 | import turtle
miT = turtle.Turtle()
'''
Ahora vamos a dibujar dos y para ello vamos a utilizar bucles anidados
'''
#Limpiar pantalla
miT.reset()
#Posición vertical
miT.left(90)
#Diente de leon
miT.pd()
miT.forward(100)
miT.right(90)
miT.pu()
miT.fd(6)
for repes in range (15): #Hacemos 15 repeticiones con un for
miT.pd() #Cada uno de estos bloques es un petalo, hay 15 podemos repetirlos
miT.left(24)
miT.fd(12)
miT.pd()
miT.right(90)
miT.fd(25)
miT.right(90)
miT.circle(6.25)
miT.right(90)
miT.fd(25)
miT.right(90)
miT.backward(6)
miT.left(90)
miT.backward(100)
#Mantener abierto el lienzo
turtle.mainloop() |
2567d52a2276d22ed6dbfc9ec1e9296466682e5e | SH22Hwang/PythonExcercise | /PyPLHomework01/main.py | 553 | 3.625 | 4 | from account import *
def main():
accList = []
accNum = 0
while True:
showMenu()
choice = int(input("선택: "))
if choice == 1:
accList.append(openAcc())
accNum += 1
elif choice == 2:
depositAcc(accList, accNum)
elif choice == 3:
withdrawalAcc(accList, accNum)
elif choice == 4:
showAllAcc(accList, accNum)
return
else:
print("범위에서 벗어난 값!")
if __name__ == "__main__":
main()
|
892bbf925fe73bf5dc94d795137eefa927099103 | DalenWBrauner/Sudoku-Generator | /Puzzle.py | 6,573 | 3.921875 | 4 | """
[Name] Puzzle.py
[Author] Dalen W. Brauner
[DLM] 12/31/2013 01:54 PM
[Purpose] To allow for the creation and manipulation of Sudoku
Puzzles.
"""
#
##
### These functions exist primarily to assist Sudoku object functions
### yet are not exclusive to them.
def any_duplicates(theList):
"""Checks if there are any duplicates in a list."""
s = set(theList)
return len(s) != len(theList)
def Gsec(r,c):
"""Returns which of the 9 sectors your value is in."""
return (r/3)*3 + c/3
def Gslt(r,c):
"""Returns which of the 9 slots in a sector your value is in."""
return c - (c/3)*3 + (r%3)*3
#
##
### Sudoku object ahoy!
class Sudoku(object):
def __init__(self, values):
# Checks if there are enough values.
if 81 != len(values):
raise TypeError("Sudoku puzzles require precisely 81 values.")
# Checks all values are integers 1-9.
for value in values:
if not type(value) == int:
raise TypeError("Sudoku puzzles require integers.")
elif not 0 < value < 10:
print value
raise TypeError("Sudoku puzzles require integers 1-9.")
self.M = {} # self.M is the entire matrix of values
self.row = [] # self.row is the list of values in each row
self.col = [] # self.col is the list of values in each column
self.sec = [] # self.sec is the list of values in each sector
# There are 9 rows, columns and sectors.
for w in xrange(9):
self.row.append([])
self.col.append([])
self.sec.append([])
# Shall we begin?
# Adds each value to...
index = -1
for r in xrange(9):
for c in xrange(9):
index += 1
Key = str(r)+","+str(c)
# ...the entire matrix.
self.M[Key] = values[index]
# ...their appropriate row.
self.row[r].append(values[index])
# ...their appropriate column.
self.col[c].append(values[index])
# ...their appropriate sector.
self.sec[((r/3)*3)+(c/3)].append(values[index])
def __str__(self):
# Creates a string to be returned
string = ""
for row in xrange(9):
string += "[ "
# Adds each row to the string
for value in xrange(9):
string += str(self.row[row][value])+" "
# Inserting vertical seperators for sectors
if value == 2 or value == 5:
string += "| "
string += "]\n"
# Inserting horizontal seperators for sectors
if row == 2 or row == 5:
string += ("_"*25)+"\n"
return string
def setvalue(self,r,c,value):
"""Sets the value located at row number r, column number c, to the
value provided."""
self.M[str(r)+","+str(c)] = value
self.row[r][c] = value
self.col[c][r] = value
self.sec[(r/3)*3 + c/3][c - (c/3)*3 + (r%3)*3] = value
def setrow(self,r,values):
"""Sets the values of row r to the values provided."""
if len(values) != 9:
raise TypeError("Rows require exactly 9 values.")
for c in xrange(9):
self.M[str(r)+","+str(c)] = values[c]
self.row[r][c] = values[c]
self.col[c][r] = values[c]
self.sec[(r/3)*3 + c/3][c - (c/3)*3 + (r%3)*3] = values[c]
def setcol(self,c,values):
"""Sets the values of col c to the values provided."""
if len(values) != 9:
raise TypeError("Columns require exactly 9 values.")
for r in xrange(9):
self.M[str(r)+","+str(c)] = values[r]
self.row[r][c] = values[r]
self.col[c][r] = values[r]
self.sec[(r/3)*3 + c/3][c - (c/3)*3 + (r%3)*3] = values[r]
def swaprow(self,r1,r2):
"""Swaps row r1 with row r2."""
newr1 = []
newr2 = []
for item in self.row[r1]: newr2.append(item)
for item in self.row[r2]: newr1.append(item)
self.setrow(r1,newr1)
self.setrow(r2,newr2)
def swapcol(self,c1,c2):
"""Swaps col c1 with col c2."""
newc1 = []
newc2 = []
for item in self.col[c1]: newc2.append(item)
for item in self.col[c2]: newc1.append(item)
self.setcol(c1,newc1)
self.setcol(c2,newc2)
def Mass_Replacement(self,replacements):
"""Replaces all 1s with the first value in the list, all 2s with the
second, etc."""
for c in xrange(9):
for r in xrange(9):
self.setvalue(r,c,replacements[(self.M[str(r)+","+str(c)])-1])
def isvalid(self):
"""Returns True if the puzzle's values do not violate Sudoku rules,
otherwise returns False."""
TF = True
for row in self.row:
if any_duplicates(row):
print "Duplicates in row",row
TF = False
for col in self.col:
if any_duplicates(col):
print "Duplicates in col",col
TF = False
for sec in self.sec:
if any_duplicates(sec):
print "Duplicates in sec",sec
TF = False
return TF
def isconsistent(self):
"""Returns True if the puzzle's values in self.row/col/sec match the
values in self.M, otherwise returns False."""
TF = True
for c in xrange(9):
for r in xrange(9):
if not (self.M[str(r)+","+str(c)] == self.row[r][c] == self.col[c][r] == self.sec[((r/3)*3)+(c/3)][c - (c/3)*3 + (r%3)*3]):
TF = False
print "Value at",r,c,"inconsistent:"
print "self.M ==",self.M[str(r)+","+str(c)]
print "self.row ==",self.row[r][c]
print "self.col ==",self.col[c][r]
print "self.sec ==",self.sec[((r/3)*3)+(c/3)][c - (c/3)*3 + (r%3)*3]
return TF
def issolvable(self):
"""Returns True if the puzzle can be solved as-is, otherwise returns
False."""
pass
def isunique(self):
"""Returns True if there is only one solution for the puzzle as-is,
otherwise returns False."""
pass
|
a215924f85c43e78eb576ab4c45f40e54eac6bf2 | IngArmando0lvera/Examples_Python | /22 listas detalladas.py | 436 | 3.953125 | 4 | array =["futbool", "pc", 18, 16, [2, 3, 5], True, False]
array.append(66) #agregar datos al final
array.append(True)
array.insert(1,88) #indice 1, registro (dato)
array.extend([1, 88, True, 100]) #Agregamos elementos al final de la lista
print("lista: ",array)
print("longitud: ",len(array))
'''Concatenando listas'''
array2=[200, 250, "hola"]
array3=array+array2
print("--------------------------------")
print(array3) |
960c3725f672166836afded6734d7e47914741b4 | IngArmando0lvera/Examples_Python | /9 entrada de datos.py | 215 | 3.84375 | 4 | # Enetrada de datos
cadena = input("¿Como se llama tu proyecto? : ")
print(f"Tu proyecto se llama {cadena}")
cadena = float(input("¿Que version es?: "))
print(f"La version de tu proyecto es {cadena + 1}") |
47cdeb51b084e1d5eff7380fdfd8de18a6dfa60a | IngArmando0lvera/Examples_Python | /21 array listas.py | 737 | 3.96875 | 4 | #seccion 5
'''En las listas podemos almacenar cualquier tipo de datos,
es decir no tiene que ser de un solo tipo la lista'''
array =["futbool", "pc", 18, 16, [2, 3, 5], True, False]
print("\n\nlista: ", array)#imprimir toda la lista
print("\nprimer elemento: ", array[0])#imprime primer elemento
'''el numero se conoce como indice'''
print("penultimo elemento: ", array[-2])#imprime penultimo elemento
print("dos primeros elementos: ", array[0:2])#imprime los dos primeros elementos
print("3 primeros elementos: ", array[:3])#imprime los primeros 3 elementos
print("elementos 2 y 3: ", array[1:3])#imprime dos datos
print("a partir del tercer elemento: ", array[2:])#imprime a partir del segundo elemento
|
72ae3e467d970bfce2e8a72f17d6690b69867f02 | FayK12/recruiting-exercises | /inventory-allocator/src/test.py | 4,546 | 3.59375 | 4 | import unittest
from shipment import optimal_shipping, warehouse_purchase
class TestCase(unittest.TestCase):
# test empty shipping list
def test_zero(self):
shipment_order_0 = {}
warehouses = [{ "name": "owd", "inventory": { "apple": 6,"mango": 1, "potato": 1} },
{ "name": "oz", "inventory": {}}, { "name": "dm", "inventory": { "apple": 5, "mango": 1} }]
expected_output_0 = []
result = optimal_shipping(shipment_order_0, warehouses)
self.assertEqual(result, expected_output_0, False)
# test 1 item purchase from 1 warehouse
def test_one(self):
shipment_order_1 = {"apple": 1}
warehouses = [{ "name": "owd", "inventory": { "apple": 6,"mango": 1, "potato": 1} },
{ "name": "oz", "inventory": {}}, { "name": "dm", "inventory": { "apple": 5, "mango": 1} }]
expected_output_1 = [{'owd': {'apple': 1}}]
result = optimal_shipping(shipment_order_1, warehouses)
self.assertEqual(result, expected_output_1, False)
# test multiple item purchase from 1 warehouse
def test_two(self):
shipment_order_2 = {"apple": 1, "mango": 1, "potato": 1}
warehouses = [{ "name": "owd", "inventory": { "apple": 6,"mango": 1, "potato": 1} },
{ "name": "oz", "inventory": {}}, { "name": "dm", "inventory": { "apple": 5, "mango": 1} }]
expected_output_2 = [{'owd': {'apple': 1, 'mango': 1, 'potato': 1}}]
result = optimal_shipping(shipment_order_2, warehouses)
self.assertEqual(result, expected_output_2, False)
# test multiple item purchase from multiple warehouses
def test_three(self):
shipment_order_3 = {"apple": 1, "mango": 2, "potato": 1}
warehouses = [{ "name": "owd", "inventory": { "apple": 6,"mango": 1, "potato": 1} },
{ "name": "oz", "inventory": {}}, { "name": "dm", "inventory": { "apple": 5, "mango": 1} }]
expected_output_3 = [{'owd': {'apple': 1, 'mango': 1, 'potato': 1}}, {'dm': {'mango': 1}}]
result = optimal_shipping(shipment_order_3, warehouses)
self.assertEqual(result, expected_output_3, False)
# test purchase of items not available in any warehouse
def test_four(self):
shipment_order_4 = {"apple": 1, "mango": 2, "cantaloupe": 4}
warehouses = [{ "name": "owd", "inventory": { "apple": 6,"mango": 1, "potato": 1} },
{ "name": "oz", "inventory": {}}, { "name": "dm", "inventory": { "apple": 5, "mango": 1} }]
expected_output_4 = []
result = optimal_shipping(shipment_order_4, warehouses)
self.assertEqual(result, expected_output_4, False)
# test purchase of items when first item has 0 quantity in shipping list
def test_five(self):
shipment_order_5 = {"apple": 0, "mango": 2, "potato": 1}
warehouses = [{ "name": "owd", "inventory": { "apple": 6,"mango": 1, "potato": 1} },
{ "name": "oz", "inventory": {}}, { "name": "dm", "inventory": { "apple": 5, "mango": 1} }]
expected_output_5 = [{'owd': {'mango': 1, 'potato': 1}}, {'dm': {'mango': 1}}]
result = optimal_shipping(shipment_order_5, warehouses)
self.assertEqual(result, expected_output_5, False)
# test purchase of items not available in sufficient quantity in warehouses
def test_six(self):
shipment_order_6 = {"apple": 12, "mango": 1}
warehouses = [{ "name": "owd", "inventory": { "apple": 6,"mango": 1, "potato": 1} },
{ "name": "oz", "inventory": {}}, { "name": "dm", "inventory": { "apple": 5, "mango": 1} }]
expected_output_6 = []
result = optimal_shipping(shipment_order_6, warehouses)
self.assertEqual(result, expected_output_6, False)
# test purchase of items when last item has 0 quantity
def test_seven(self):
shipment_order_7 = {"apple": 7, "mango": 0}
warehouses = [{ "name": "owd", "inventory": { "apple": 6,"mango": 1, "potato": 1} },
{ "name": "oz", "inventory": {}}, { "name": "dm", "inventory": { "apple": 5, "mango": 1} }]
expected_output_7 = [{'owd': {'apple': 6}}, {'dm': {'apple': 1}}]
result = optimal_shipping(shipment_order_7, warehouses)
self.assertEqual(result, expected_output_7, False)
# test purchase of items when center item has 0 quantity in shipping list
def test_eight(self):
shipment_order_8 = {"apple": 9, "potato": 0, "mango": 2}
warehouses = [{ "name": "owd", "inventory": { "apple": 6,"mango": 1, "potato": 1} },
{ "name": "oz", "inventory": {}}, { "name": "dm", "inventory": { "apple": 5, "mango": 1} }]
expected_output_8 = [{'owd': {'apple': 6, 'mango': 1}}, {'dm': {'apple': 3, 'mango': 1}}]
result = optimal_shipping(shipment_order_8, warehouses)
self.assertEqual(result, expected_output_8, False)
if __name__ == '__main__':
unittest.main()
|
e5e73a0a462812ea6940811e869beceb82702008 | oddaspa/TDT4120 | /Øving 3/pipesortering2.py | 3,631 | 3.640625 | 4 | #!/usr/bin/python3
from sys import stdin
# Alle kall jeg gjør mer enn 1 gang skal få variabel.
# NOTICE: Random quicksort would be better.
def sort_list(A):
less, equal, greater = [], [], []
if len(A) > 1:
pivot = A[0]
for num in A:
if num > pivot:
greater.append(num)
elif num == pivot:
equal.append(num)
else:
less.append(num)
return sort_list(less) + equal + sort_list(greater)
else:
return A
def find(A, lower, upper):
low = A[0]
if lower <= low:
lower = A[0]
elif lower >= A[-1]:
lower = A[-1]
else:
lower = find_lower(A, lower)
if upper >= A[-1]:
upper = A[-1]
elif upper <= low:
upper = A[0]
else:
upper = find_upper(A, upper)
result = [lower, upper]
return result
def find_lower(A, num):
# (Step 1) Let min = 0 and max = n - 1.
min, max = 0, len(A) - 1
# (Step 2) Compute guess as the average of max and min, rounded down(so that it is an integer).
while min <= max:
guess = (min + max) // 2
# (Step 3) If array[guess] equals target, then stop.You found it! Return guess.
if A[guess] == num:
return num
# (Step 4.1) If number is higher than guess and number is smaller than guess -1 return guess-1.
# --- Logic --- If the number we are looking at is higher than our target and the number before our guess
# is lower then we should pick the lower number because it is our threshold.
if num < A[guess] and num > A[guess - 1]:
return A[guess - 1]
# (Step 4.2) If the guess was too low, that is, array[guess] < target, then set min = guess + 1.
if A[guess] < num:
min = guess + 1
if A[min] > num:
return A[min - 1]
if min == max:
return A[guess]
# (Step 4.3) Otherwise, the guess was too high.Set max = guess - 1. Go back to step 2.
else:
max = guess - 1
if min == max:
return A[max]
def find_upper(A, num):
# (Step 1) Let min = 0 and max = n - 1.
min, max = 0, len(A) - 1
# (Step 2) Compute guess as the average of max and min, rounded down(so that it is an integer).
while min <= max:
guess = (min + max) // 2
# (Step 3) If A[guess] equals num, then stop. You found it! Return num.
if A[guess] == num:
return num
# (Step 4.1) If current guess is at a lower element than our number and the next element is higher, pick
# the higher element.
if num < A[guess] and num > A[guess - 1]:
return A[guess]
# (Step 4.2) If the guess was too low, that is, array[guess] < target, then set min = guess + 1.
if A[guess] < num:
min = guess + 1
if min == max:
return A[min]
# (Step 4.3) Otherwise, the guess was too high.Set max = guess - 1. Go back to step 2.
else:
max = guess - 1
if A[max] < num:
return A[max + 1]
if min == max:
return A[max]
def main():
input_list = []
for x in stdin.readline().split():
input_list.append(int(x))
sorted_list = sort_list(input_list)
for line in stdin:
word = line.split()
minimum = int(word[0])
maximum = int(word[1])
result = find(sorted_list, minimum, maximum)
print(str(result[0]) + " " + str(result[1]))
if __name__ == "__main__":
main()
|
9f955e3f839b7646365a142c85bb139c6c1ef292 | oddaspa/TDT4120 | /Øving 4/flexradix.py | 1,510 | 3.921875 | 4 | #!/usr/bin/python3
from sys import stdin
def flexradix(A, d):
# Returns the list A sorted.
# creates a new list of the words sorted after length
list3 = sort_length(A)
return counting_sort(list3, d)
def counting_sort(A, d):
# creates empty list of length of the longest word
list = [0] * d
# appends the length of a word to the list
for word in A:
list[len(word) - 1] = list[len(word) - 1] + 1
# appends the number of words
for i in range(d - 1, 0, -1):
list[i - 1] = list[i - 1] + list[i]
for i in range(d, -1, -1):
F = A[len(A) - list[i - 1]:]
B = [0] * len(F)
C = [0] * 26
for j in range(len(F)):
index = ord(F[j][i - 1]) - 97
C[index] = C[index] + 1
for j in range(1, 26):
C[j] = C[j] + C[j - 1]
for j in range(len(F) - 1, -1, -1):
index = ord(F[j][i - 1]) - 97
B[C[index] - 1] = F[j]
C[index] = C[index] - 1
A[len(A) - list[i - 1]:] = B
return A
def sort_length(A):
for i in range(len(A)):
for j in range(i + 1, len(A)):
if len(A[i]) > len(A[j]):
temp = A[i]
A[i] = A[j]
A[j] = temp
return A
def main():
d = int(stdin.readline())
strings = []
for line in stdin:
strings.append(line.rstrip())
A = flexradix(strings, d)
for string in A:
print(string)
if __name__ == "__main__":
main()
|
145bf56b934df223e2c4bc366fc9c62a594f0bf3 | akhilmaskeri/lemonade | /15-puzzle/solver.py | 3,586 | 3.578125 | 4 |
# huge respect to Ken'ichiro Takahashi and Orson Peters
import random
# idea is to use iterative deepning A* search
class Solver:
def __init__(self,h,neighbours):
self.h = h
self.neighbours = neighbours
self.found = object()
def solve(self,root,is_goal,max_cost = None):
self.is_goal = is_goal
self.path = [root]
self.is_in_path = {root}
self.path_desc = []
self.nodes_evaluated = 0
bound = self.h(root)
while True:
t = self._search(0,bound)
if t is self.found:
return self.path,self.path_desc,bound,self.nodes_evaluated
if t is None:
return None
bound = t
def _search(self,g,bound):
self.nodes_evaluated += 1
node = self.path[-1]
f = g + self.h(node)
if f > bound:
return f
if self.is_goal(node):
return self.found
m = None
for cost,n,desc in self.neighbours(node):
if n in self.is_in_path: continue
self.path.append(n)
self.is_in_path.add(n)
self.path_desc.append(desc)
t = self._search(g+cost,bound)
if t == self.found: return self.found
if m is None or (t is not None and t < m): m = t
self.path.pop()
self.path_desc.pop()
self.is_in_path.remove(n)
return m
def board_neighbours():
moves = []
for gap in range(16):
x , y = gap % 4 , gap / 4
move = []
if x > 0 : move.append(-1)
if x < 3 : move.append(1)
if y > 0 : move.append(-4)
if y < 3 : move.append(4)
moves.append(move)
def get_neighbours(t):
gap = t.index(0)
l = list(t)
for m in moves[gap]:
l[gap] = l[gap+m]
l[gap+m] = 0
yield (1 , tuple(l) , (l[gap],m) )
l[gap + m ] = l[gap]
l[gap] = 0
return get_neighbours
def display(board):
for i in range(4):
for j in range(4):
if board[i*4 + j] == 0:
print "__ ",
elif board[i*4 + j] <= 9 :
print " "+str(board[i*4 + j])+" ",
else:
print str(board[i*4 + j])+" ",
print ""
def encode(board):
r = 0
for i in range(16):
r |= board[i] << (3*i)
return r
def wd():
goal = [4,0,0,0,0,4,0,0,0,0,4,0,0,0,0,3]
table = {}
to_visit = [(goal,0,3)]
while to_visit:
board,cost,e = to_visit.pop(0)
hash = encode(board)
if hash in table : continue
table[hash] = cost
for d in [-1,1]:
if 0 <= e+d < 4 :
for c in range(4):
if board[4*(e+d) + c] > 0:
nboard = list(board)
nboard[4*(e+d) +c ] -=1
nboard[4*e + c ]+=1
to_visit.append((tuple(nboard),cost+1,e+d))
return table
def H(goal):
h = wd()
goals = {i : goal.index(i) for i in goal }
def caluculate(p):
ht = 0
vt = 0
d = 0
for i,c in enumerate(p):
if c == 0 : continue
g = goals[c]
xi,yi = i%4 , i / 4
xg,yg = g%4 , g / 4
ht += 1 << (3*(4*yi+yg))
vt += 1 << (3*(4*xi+xg))
if yg == yi :
for k in range(i+1,i - i%4 + 4):
if p[k] and goals[p[k]] / 4 == yi and goals[p[k]] < g:
d += 2
if xg == xi:
for k in range(i+4, 16, 4):
if p[k] and goals[p[k]] % 4 == xi and goals[p[k]] < g:
d += 2
d += h[ht] + h[vt]
return d
return caluculate
if __name__ == "__main__":
final = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0)
print "enter the board"
r1 = [int(i) for i in raw_input().split() ]
r2 = [int(i) for i in raw_input().split() ]
r3 = [int(i) for i in raw_input().split() ]
r4 = [int(i) for i in raw_input().split() ]
board = tuple(r1+r2+r3+r4)
is_goal = lambda p: p == final
neighbours = board_neighbours()
solver = Solver(H(final),neighbours)
path,moves,cost,num_eval = solver.solve(board,is_goal,80)
display(board)
print("".join({-1: "L", 1: "R", -4: "U", 4: "D"}[move[1]] for move in moves))
|
27f4d3f333ad5eae6ca281be067c92a006b7c180 | Otteri/python-scripts | /ransac/fitline.py | 2,320 | 3.5 | 4 | from numpy import array
import numpy as np
# Finds eigenvectors and values by doing principal component analysis
# @param data_array: data points (x,y) in column vector
# @return: 2D array of eigenvalues and eigenvectors
def sklearn_pca(data_array):
from sklearn.decomposition import PCA
pca = PCA(2)
pca.fit(data_array)
eigenvalues = pca.explained_variance_
eigenvectors = pca.components_.T # .T: to match w/ numpy
return eigenvalues, eigenvectors
# Does the same as the above function, but without sklearn and PCA
# @param data_array: data points (x,y) in column vector
# @return: 2D array of eigenvalues and eigenvectors
def get_eigenvector(data_array):
centered_matrix = data_array.T - data_array.T.mean(axis=1)[:, np.newaxis]
cov = np.dot(centered_matrix, centered_matrix.T)
eigenvalues, eigenvectors = np.linalg.eig(cov)
return eigenvalues, eigenvectors
# Often, the eigenvalues and vectors are not given in any particular order,
# because only the magnitudes are intresting. If x is valid eigenvector, so is -x.
# However, the 'sign randomnes' can cause problems with other calculations, so some
# standard representation must be established. This function sorts the eigenvalues
# from the greatest to smallest. The eigenvectors are ordered accordingly too.
def eigen_sort(eigenvalues, eigenvectors):
idx = eigenvalues.argsort()[::-1]
eigenvalues = eigenvalues[idx]
eigenvectors = eigenvectors[:,idx]
return eigenvalues, eigenvectors
# Finds a line that fits to given data
# Line is presented in normal form: p = x*cos(theta) + y*sin(theta)
# @param data_array: column vector of data points (x,y)
# @return theta: angle
# @return p: length of perpendicular
def fitline(data_array, pts):
try:
_, eigenvectors = eigen_sort(*sklearn_pca(pts))
except:
_, eigenvectors = eigen_sort(*get_eigenvector(pts))
ev1 = np.array(eigenvectors[:,1]) # pick one vector
theta = -np.arctan2(*ev1)
ev1_col = np.matrix([*ev1]).T # create column vector
mean = np.matrix([np.mean(data_array, axis=0)])
p = mean * ev1_col
return theta, p
# Note: Instead of finding eigenvectors,
# we could also do fitting by using total least squares (TLS)
# Note: Instead of PCA we could also do fitting by using Total least squares (TLS) |
be167e0ae54599d158c82a992c1f37e2a62f646f | AlexanDelimi/PDDYG | /Range_Tree/RangeNode.py | 9,198 | 3.609375 | 4 | class RangeLeaf():
''' Contains a list of points. '''
def __init__(self, point):
self.point_list = [point]
class RangeNode():
'''
Contains a value, left and right children
and the corresponding range tree of the next dimension,
if it has one.
'''
def __init__(self, value):
''' Range node constructor. '''
self.value = value
self.left_child = None
self.right_child = None
self.bst_y = None
def insert_leaves(self, lista, dim):
''' Begin insertion of leaves to node. '''
for point in lista:
self.insert_leaf(point, dim)
def insert_leaf(self, point, dim):
''' Recursively insert leaf at correct branch. '''
if point[dim] <= self.value:
if self.left_child is None:
self.left_child = RangeLeaf(point)
elif RangeNode.is_leaf(self.left_child):
self.left_child.point_list.append(point)
elif not RangeNode.is_leaf(self.left_child):
self.left_child.insert_leaf(point, dim)
else:
if self.right_child is None:
self.right_child = RangeLeaf(point)
elif RangeNode.is_leaf(self.right_child):
self.right_child.point_list.append(point)
elif not RangeNode.is_leaf(self.right_child):
self.right_child.insert_leaf(point, dim)
def insert_bst_y(self, lista):
''' Recursively create all range trees of second dimension. '''
list_y = sorted(list(set([point[1] for point in lista])))
self.bst_y = RangeNode.build_1D_Range_Tree(list_y)
self.bst_y.insert_leaves(lista, 1)
left_lista = []
right_lista = []
for point in lista:
if point[0] <= self.value:
left_lista.append(point)
else:
right_lista.append(point)
if not ( RangeNode.is_leaf(self.left_child) or self.left_child is None ):
self.left_child.insert_bst_y(left_lista)
if not ( RangeNode.is_leaf(self.right_child) or self.right_child is None ):
self.right_child.insert_bst_y(right_lista)
def to_dict(self):
''' Return tree as dictionary to print. '''
dictionary = {
'value': self.value,
'left child': None,
'right child': None,
'bst y': None
}
if self.left_child is not None:
if RangeNode.is_leaf(self.left_child):
dictionary['left child'] = self.left_child.point_list
else:
dictionary['left child'] = self.left_child.to_dict()
if self.right_child is not None:
if RangeNode.is_leaf(self.right_child):
dictionary['right child'] = self.right_child.point_list
else:
dictionary['right child'] = self.right_child.to_dict()
if self.bst_y is not None:
dictionary['bst y'] = self.bst_y.to_dict()
return dictionary
@staticmethod
def build_1D_Range_Tree(nums):
'''
Build the Range Tree of the first dimension
using nums: a sorted list of unique values.
'''
if not nums:
return None
mid_val = len(nums) // 2
node = RangeNode(nums[mid_val])
node.left_child = RangeNode.build_1D_Range_Tree(nums[:mid_val])
node.right_child = RangeNode.build_1D_Range_Tree(nums[mid_val + 1:])
return node
@staticmethod
def is_leaf(node):
''' Return True if argument is leaf. '''
if type(node).__name__ == 'RangeLeaf':
return True
elif type(node).__name__ == 'RangeNode':
return False
@staticmethod
def squared_distance(point_1, point_2):
''' Return the euclidean distance of the points
or infinity if either one is None. '''
if point_1 is None or point_2 is None:
return float('inf')
total = 0
dims = len(point_1)
for i in range(dims):
diff = point_1[i] - point_2[i]
total += diff**2
return total
@staticmethod
def closest_point(temp_best, best_point, target_point):
''' Return closest point to target
between temp and best point. '''
if temp_best is None:
return best_point
if best_point is None:
return temp_best
dist_1 = RangeNode.squared_distance(temp_best, target_point)
dist_2 = RangeNode.squared_distance(best_point, target_point)
if (dist_1 < dist_2):
return temp_best
else:
return best_point
@staticmethod
def nearest_neighbor_x(root, target_point, nearest_list):
''' Get the point nearest to target
according to the x dimension
that is not already reported in nearest_list. '''
if root is None:
# nothing more to do here
return None
else:
nextBranch = None
otherBranch = None
# compare the coordinate for the x axis
if target_point[0] < root.value:
nextBranch = root.left_child
otherBranch = root.right_child
else:
nextBranch = root.right_child
otherBranch = root.left_child
if RangeNode.is_leaf(nextBranch):
# search for best point in y bst
best_point = RangeNode.nearest_neighbor_y(root.bst_y, target_point, nearest_list)
else:
# recurse down the best branch
best_point = RangeNode.nearest_neighbor_x(nextBranch, target_point, nearest_list)
squared_radius = RangeNode.squared_distance(target_point, best_point)
absolute_distance = abs(target_point[0] - root.value)
# check if the other branch is closer
if squared_radius >= absolute_distance**2:
temp_best = None
if RangeNode.is_leaf(otherBranch):
# search for best point in y bst
temp_best = RangeNode.nearest_neighbor_y(root.bst_y, target_point, nearest_list)
else:
# recurse down the other branch
temp_best = RangeNode.nearest_neighbor_x(otherBranch, target_point, nearest_list)
best_point = RangeNode.closest_point(temp_best, best_point, target_point)
return best_point
@staticmethod
def nearest_neighbor_y(root, target_point, nearest_list):
''' Get the point nearest to target
according to the y dimension
that is not already reported in nearest_list. '''
if root is None:
# nothing more to do here
return None
elif RangeNode.is_leaf(root):
# get unreported point in leaf (if there is one) closest to target
best_point = None
min_distance = float('inf')
for point in root.point_list:
if point not in nearest_list:
dist = RangeNode.squared_distance(point, target_point)
if dist < min_distance:
min_distance = dist
best_point = point
return best_point
else: # root is internal node
nextBranch = None
otherBranch = None
# compare the coordinate for the y axis
if target_point[1] < root.value:
nextBranch = root.left_child
otherBranch = root.right_child
else:
nextBranch = root.right_child
otherBranch = root.left_child
# recurse down the best branch
best_point = RangeNode.nearest_neighbor_y(nextBranch, target_point, nearest_list)
squared_radius = RangeNode.squared_distance(target_point, best_point)
absolute_distance = abs(target_point[1] - root.value)
# check if the other branch is closer
if squared_radius >= absolute_distance**2:
temp_best = RangeNode.nearest_neighbor_y(otherBranch, target_point, nearest_list)
best_point = RangeNode.closest_point(temp_best, best_point, target_point)
return best_point
@staticmethod
def get_leaves(node, leaflist):
'''
Recursively report all leaves.
'''
# a deepest node is found
if RangeNode.is_leaf(node):
# report leaves
leaflist += node.point_list
# the node has more children
else:
# continue the search for each child of the node
if node.left_child is not None:
leaflist = RangeNode.get_leaves(node.left_child, leaflist)
if node.right_child is not None:
leaflist = RangeNode.get_leaves(node.right_child, leaflist)
return leaflist
|
a62d496faff1b188215e470952c48e6d071bfcab | zid93/MPM_Repository | /Number2.py | 845 | 3.640625 | 4 | def wordSplit(wordList, word):
listoutputword = []
listword = [[False for i in range(len(word))] for x in range(len(word))]
for i in range(1, len(word) + 1):
for j in range(len(word) - i + 1):
if word[j:j + i] in wordList:
listword[j][j + i - 1] = True
listoutputword.append(word[j:j + i])
else:
for k in range(j + 1, j + i):
if listword[j][k - 1] and listword[k][j + i - 1]:
listword[j][j + i - 1] = True
if listword[0][len(word) - 1] == True:
print(listoutputword)
else:
print('Nothing..')
if __name__ == '__main__':
wordlist = ['pro', 'gram', 'merit','program', 'it', 'programmer']
print('Enter your list:')
input_list = input()
x = wordSplit(wordlist,input_list)
|
f69783e7a620ca692a6b6213f16ef06b491b35e5 | lily-liu-17/ICS3U-Assignment-7-Python-Concatenates | /concatenates.py | 883 | 4.3125 | 4 | #!/usr/bin/env python3
# Created by: Lily Liu
# Created on: Oct 2021
# This program concatenates
def concatenate(first_things, second_things):
# this function concatenate two lists
concatenated_list = []
# process
for element in first_things:
concatenated_list.append(element)
for element in second_things:
concatenated_list.append(element)
return concatenated_list
def main():
concatenated_list = []
# input
user_first_things = input("Enter the things to put in first list (no spaces): ")
user_second_things = input("Enter the things to put in second list (no spaces): ")
# output
print("")
concatenated_list = concatenate(user_first_things, user_second_things)
print("The concatenated list is {0} ".format(concatenated_list))
print("")
print("Done.")
if __name__ == "__main__":
main()
|
30829d7ff346e374e7024dcdb0783009438a88da | yildirimyigit/irl_sfm | /python_ws/dme_irl/environment.py | 10,499 | 3.5625 | 4 | from bisect import bisect_left
import math
import random
import numpy as np
from utils import *
min_goal_dist = 0.2
min_human_dist = 0.2
# This class initializes actions and states arrays and also has the transaction function
class Environment(object):
# delta_distance : this represents the default distance that agents take
# action_div : # of intervals to divide 180 degrees for actions
# theta_human_div : # of intervals to divide 180 degrees for theta_human
# theta_goal_div : # of intervals to divide 180 degrees for theta_goal
# theta_goal and theta_human are vertical. Meaning: 0th
def __init__(self, delta_distance, action_div, theta_human_div, theta_goal_div, start_point, goal_point):
self.delta_distance = delta_distance
self.action_div = action_div
self.theta_human_div = theta_human_div
self.theta_goal_div = theta_goal_div
self.start_point = start_point
self.goal_point = goal_point
self.state_list = [] # list of State objects
self.action_list = [] # list of Action objects
# actions array should start from -90 to +90 degrees thus if divided by 5:
# | -72 | -36 | 0 | 36 | 72 | -> 1/2-(1/10) + i*1/5
def initialize_actions(self):
print('+ Environment.initialize_actions()')
change = 1.0 / self.action_div # the beginning should be in the middle
for i in range(self.action_div):
# it is multiplied with pi in order to give it in radians format
self.action_list.append(Action((-1/2.0 + change / 2.0 + i * change) * math.pi))
# thetas are also initialized the same way with the actions.
# only, they are divided in the range(0,360) degrees instead of (0,180)
def initialize_states(self):
print('+ Environment.initialize_states()')
human_change = 1.0 / self.theta_human_div
goal_change = 1.0 / self.theta_goal_div
# discretizing the distances in logarithmic scale
current_goal_distance = min_goal_dist
max_human_dist = 3.21
max_goal_distance = self.calculate_max_distance()
while current_goal_distance < max_goal_distance:
for i in range(self.theta_goal_div):
tg_change = (-1/2.0 + goal_change/2.0 + i * goal_change) * 2*math.pi
current_human_dist = min_human_dist
while current_human_dist < max_human_dist:
for j in range(self.theta_human_div):
th_change = (-1 / 2.0 + human_change / 2.0 + j * human_change) * 2 * math.pi
self.state_list.append(State(current_goal_distance, tg_change, current_human_dist, th_change))
current_human_dist *= 2
current_goal_distance *= 2
# for s in self.state_list:
# print_state(s)
def random_state(self):
return np.random.choice(self.state_list)
# This method returns the probability distribution on the state space which corresponds to the probabilities of
# the agent's being on each state when it takes the given action in given state.
# The angle 0 represents the front of the agent, and x-y axes are set according to angles. Thus in this
# case x represents vertical axis, and y represents horizontal axis. And sin&cos values are calculated
# accordingly
# left:-y, up:+x, right:+y, down:-x (according to the agent)
def transition(self, state, action):
dhx = state.dh * math.cos(state.th)
dhy = state.dh * math.sin(state.th)
dgx = state.dg * math.cos(state.tg)
dgy = state.dg * math.sin(state.tg)
goal_diff = abs(action.middle_degree - state.tg)
dgxn = dgx - self.delta_distance/2.0 * math.cos(goal_diff)
if dgy * action.middle_degree > 0: # if the action and the goal is on the same side
dgyn = dgy - self.delta_distance/2.0 * abs(math.sin(goal_diff))
else:
dgyn = dgy + self.delta_distance/2.0 * (abs(math.sin(goal_diff)))
tgn = math.atan2(dgyn, dgxn)
dgn = (dgxn ** 2 + dgyn ** 2) ** (1.0 / 2.0)
human_diff = abs(action.middle_degree - state.th)
dhxn = dhx - self.delta_distance * math.cos(human_diff)
if dhy * action.middle_degree > 0: # if the action and the goal is on the same side
dhyn = dhy - self.delta_distance * abs(math.sin(human_diff))
else:
dhyn = dhy + self.delta_distance * (abs(math.sin(human_diff)))
thn = math.atan2(dhyn, dhxn)
dhn = (dhxn ** 2 + dhyn ** 2) ** (1.0 / 2.0)
state_prob_dist = np.zeros(len(self.state_list))
# This part is specific to the deterministic environments
state_prob_dist[self.find_closest_state(State(dgn, tgn, dhn, thn))] = 1
return state_prob_dist
def find_closest_state(self, state):
dg_ind = tg_ind = dh_ind = th_ind = -1
dg_found = tg_found = dh_found = th_found = False
for i in range(len(self.state_list)):
if th_ind == -1 and state.th <= self.state_list[i].th:
if i == 0:
th_ind = 0
else:
th_ind = i if np.abs(state.th - self.state_list[i].th) < \
np.abs(state.th - self.state_list[i-1].th) else (i-1) # discretizing to the closest
th_found = True
if dh_ind == -1 and state.dh <= self.state_list[i].dh:
if i == 0:
dh_ind = 0
else:
dh_ind = i if np.abs(state.dh - self.state_list[i].dh) < \
np.abs(state.dh - self.state_list[i-1].dh) else (i-1)
dh_found = True
if tg_ind == -1 and state.tg <= self.state_list[i].tg:
if i == 0:
tg_ind = 0
else:
tg_ind = i if np.abs(state.tg - self.state_list[i].tg) < \
np.abs(state.tg - self.state_list[i-1].tg) else (i-1)
tg_found = True
if dg_ind == -1 and state.dg <= self.state_list[i].dg:
if i == 0:
dg_ind = 0
else:
dg_ind = i if np.abs(state.dg - self.state_list[i].dg) < \
np.abs(state.dg - self.state_list[i-1].dg) else (i-1)
dg_found = True
if dg_found and tg_found and dh_found and th_found:
break
# if not found, field is discretized into the last cell
if not dg_found:
dg_ind = len(self.state_list)-1
if not tg_found:
tg_ind = len(self.state_list)-1
if not dh_found:
dh_ind = len(self.state_list)-1
if not th_found:
th_ind = len(self.state_list)-1
s = State(distance_goal=self.state_list[int(dg_ind)].dg, theta_goal=self.state_list[int(tg_ind)].tg,
distance_human=self.state_list[int(dh_ind)].dh, theta_human=self.state_list[int(th_ind)].th)
for i in range(len(self.state_list)):
if s.is_equal(self.state_list[i]):
return i
print('Error: ')
print_state(s)
raise ValueError('Environment.find_closest_state failed to find the matching state')
# This returns the closest index for the check_element at the check_array
# bisect_left uses binary search
def closest_index(self, check_element, check_array):
pos = bisect_left(check_array, check_element)
if pos == 0:
return pos
if pos == len(check_array):
return pos - 1
before = check_array[pos - 1]
after = check_array[pos]
if after - check_element < check_element - before:
return pos
else:
return pos - 1
def calculate_max_distance(self):
return ((self.start_point.x - self.goal_point.x) ** 2 +
(self.start_point.y - self.goal_point.y) ** 2) ** (1.0 / 2.0)
# Creates a linear array with states enumerated
# enumeration is like: 00001 - 00002 - 00003 .... 0010 - 0011 - 0011 -...
def save_states(self, file_name):
print('+ Environment.save_states()')
np.save(file_name, np.asarray(self.state_list))
# save actions next to the states
def save_actions(self, file_name):
print('+ Environment.save_actions()')
np.save(file_name, np.asarray(self.action_list))
def save_transitions(self, file_name):
print('+ Environment.save_transitions()')
nof_states = len(self.state_list)
transition_mat = np.zeros([nof_states, len(self.action_list), nof_states], dtype=float) # T[s][a][s']
# Testing ################################################################
# s = a = 0
# print('****************state-action-transition***************')
# print_state(self.state_list[s])
# print_action(self.action_list[a])
# test = self.transition(self.state_list[s], self.action_list[a])
# for i in range(len(test)):
# if test[i] > 0:
# print(i, ": ", test[i])
#
# for i in range(10):
# s = int(random.random()*len(self.state_list))
# a = int(random.random()*len(self.action_list))
# print('current state:')
# print_state(self.state_list[s])
# print('current action:')
# print_action(self.action_list[a])
# test = self.transition(self.state_list[s], self.action_list[a])
# for j in range(len(test)):
# if test[j] > 0:
# print('new state is:')
# print_state(self.state_list[j])
# Testing ################################################################
for i in range(nof_states):
for j in range(len(self.action_list)):
transition_mat[i, j, :] = self.transition(self.state_list[i], self.action_list[j])
np.save(file_name, transition_mat)
print('- Environment.save_transitions()')
def initialize_environment(self):
print('+ Environment.initialize_environment()')
self.initialize_states()
self.initialize_actions()
def print_state(s):
print('dg: {0}, tg: {1}, dh: {2}, th: {3}'.format(s.dg, s.tg, s.dh, s.th))
def print_action(a):
print('mid_deg: {0}'.format(a.middle_degree))
|
22b50722a6e726a6dc88d61bd5010c898d1f0801 | JulianNymark/stone-of-the-hearth | /soth/player.py | 2,410 | 3.546875 | 4 | from .card import *
from .utility import *
from .textstrings import *
class Player:
"""A player in the game"""
mana = 1
mana_used = 0
overload_now = 0
overload_next = 0
health = 30
armour = 0
damage = 0
attack = 0
def __init__(self, ct, npc=False):
self.classtype = ct
self.npc = npc
self.adj = class_adjective[self.classtype]
def feelings(self):
if self.npc:
print('your opponent feels ' + self.adj)
else:
print('you feel ' + self.adj)
print()
def display_choices(self):
self.choice_count = 2 # end turn & hero power
self.choice_count += len(self.hand.cards) # card hand
# attackers
print()
print('1. end turn')
print('2. become more {0}'.format(self.adj))
for i in range(len(self.hand.cards)):
card = self.hand.cards[i]
print('{0}. {1}'.format(i + 3, str(card)))
def start_turn(self):
self.mana_used = 0
if self.mana < 10:
self.mana += 1
def end_turn(self):
pass
def mulligan(self):
print("do you like these cards?\n")
print("1. yes")
print("2. no")
choice = prompt_action(2)
if choice == 1:
handsize = len(self.hand.cards)
self.deck.add(self.hand.cards) # deck your hand
if not self.npc:
print(self.text('mulligan'))
del self.hand.cards[:] # empty your hand
if not self.npc:
print(self.text('shuffleDeck'))
print()
random.shuffle(self.deck.cards)
self.deck.draw(self.hand, handsize) # re-draw hand
def text(self, event):
return text[event][self.classtype]
def take_turn(self):
if not self.npc:
self.start_turn()
while True:
self.display_choices()
choice = prompt_action(self.choice_count)
if choice == 0:
break
elif choice == 1:
self.mana_used += 2
print('you chant {0}... {0}...{0}!'.format(self.adj))
else:
self.hand.play(choice - 2)
self.end_turn()
else:
self.start_turn()
# do random shit
self.end_turn()
|
c797ef3f37f49d5a00e88fc2e76d5809ea82e0dd | andrezaserra/pyChess | /src/checker.py | 9,763 | 3.515625 | 4 | import alert
def check_straight_path(board, start, to):
keep_same_line = start[0] == to[0]
if keep_same_line:
smaller_column = start[1] if start[1] < to[1] else to[1]
bigger_column = start[1] if start[1] > to[1] else to[1]
for i in range(smaller_column + 1, bigger_column):
if board.board[start[0]][i] is not None:
print(alert.blocked_path)
return False
return True
else:
smaller_line = start[0] if start[0] < to[0] else to[0]
bigger_line = start[0] if start[0] > to[0] else to[0]
for i in range(smaller_line + 1, bigger_line):
if board.board[i][start[1]] is not None:
print(alert.blocked_path)
return False
return True
def check_diagonal_path(board, start, to):
move_to_up = to[0] - start[0] > 0
move_to_right = to[1] - start[1] > 0
line_iterator = 1 if move_to_up else -1
column_iterator = 1 if move_to_right else -1
i = start[0] + line_iterator
j = start[1] + column_iterator
while i < to[0] if line_iterator == 1 else i > to[0]:
if board.board[i][j] is not None:
print(alert.blocked_path)
return False
i += line_iterator
j += column_iterator
return True
def check_for_promotion_pawns(game):
is_white_player_turn = game.is_white_player_turn
i = 0
while i < 8:
black_pawn_is_on_eighth_rank = game.board.board[0][i] is not None and game.board.board[0][i].name == "\u265F"
white_pawn_is_on_eighth_rank = game.board.board[7][i] is not None and game.board.board[7][i].name == "\u265F"
if not is_white_player_turn and black_pawn_is_on_eighth_rank:
game.promotion((0, i))
break
elif is_white_player_turn and white_pawn_is_on_eighth_rank:
game.promotion((7, i))
break
i += 1
# returns true if it find a threat in 'position_to_check'
def check_for_opponent_knight(my_color, board, start, check_right, check_up):
check_to_black_side = check_up
check_to_right_side = check_right
i = start[0] + 2 if check_up else start[0] - 2
j = start[1] + 1 if check_right else start[1] + 1
if 0 < i < 7 and 0 < j < 7:
square_to_check = board.board[i][j]
exists_piece = square_to_check is not None
if exists_piece:
piece = square_to_check
piece_is_a_opponent_knight = piece.color != my_color and piece.name == "\u265E"
if piece_is_a_opponent_knight:
return True
i = start[0] + 1 if check_up else start[0] - 1
j = start[1] + 2 if check_right else start[1] + 2
if 0 < i < 7 and 0 < j < 7:
square_to_check = board.board[i][j]
exists_piece = square_to_check is not None
if exists_piece:
piece = square_to_check
piece_is_a_opponent_knight = piece.color != my_color and piece.name == "\u265E"
if piece_is_a_opponent_knight:
return True
return False
# returns true if it find a threat on the piece's straight path to the end of the board
def check_for_opponent_in_straight(my_color, board, start, check_right, check_up):
check_to_black_side = check_up
check_to_right_side = check_right
line_iterator = -1 if check_to_black_side else 1
column_iterator = 1 if check_to_right_side else -1
i = start[0] + line_iterator
j = start[1] + column_iterator
if 0 <= i <= 7 and 0 <= j <= 7:
front_square = board.board[i][start[1]]
exists_front_piece = front_square is not None
side_square = board.board[start[0]][j]
exists_side_piece = side_square is not None
if exists_front_piece:
front_piece = front_square
the_piece_is_opponent_king = front_piece.name == "\u265A" and front_piece.color != my_color
the_piece_is_opponent_rook_or_queen = front_piece.color != my_color and front_piece.name in ["\u265c",
"\u265B"]
if front_piece.color != my_color and (the_piece_is_opponent_king or the_piece_is_opponent_rook_or_queen):
return True
while 0 <= i <= 7 and 0 <= j <= 7:
if exists_front_piece:
front_piece = front_square
the_piece_is_opponent_rook_or_queen = front_piece.color != my_color and front_piece.name in ["\u265c",
"\u265B"]
if the_piece_is_opponent_rook_or_queen:
return True
i += line_iterator
front_square = board.board[i][start[1]]
exists_front_piece = front_square is not None
if exists_side_piece:
side_piece = side_square
the_piece_is_opponent_king = side_piece.name == "\u265A" and side_piece.color != my_color
the_piece_is_opponent_rook_or_queen = side_piece.color != my_color and side_piece.name in ["\u265c",
"\u265B"]
if side_piece.color != my_color and (the_piece_is_opponent_king or the_piece_is_opponent_rook_or_queen):
print("there is a " + str(side_piece.name) + "in the path" + str(i) + str(j))
return True
while 0 <= i <= 7 and 0 <= j <= 7:
if exists_side_piece:
side_piece = side_square
the_piece_is_opponent_rook_or_queen = side_piece.color != my_color and side_piece.name in ["\u265c",
"\u265B"]
if the_piece_is_opponent_rook_or_queen:
return True
j += column_iterator
side_square = board.board[start[1]][j]
exists_side_piece = side_square is not None
return False
# returns true if it find a threat on the piece's diagonal path to the end of the board
def check_for_opponent_in_diagonal(my_color, board, start, check_right, check_up):
check_to_black_side = check_up
check_to_right_side = check_right
line_iterator = -1 if check_to_black_side else 1
column_iterator = 1 if check_to_right_side else -1
i = start[0] + line_iterator
j = start[1] + column_iterator
if 0 <= i <= 7 and 0 <= j <= 7:
square_to_check = board.board[i][j]
if square_to_check is not None:
piece = square_to_check
the_piece_is_pawn = piece.name == "\u265F"
the_piece_is_king = piece.name == "\u265A"
the_piece_is_queen = piece.name == "\u265B"
if (the_piece_is_pawn or the_piece_is_king or the_piece_is_queen) and piece.color != my_color:
print("threat in diagonal: " + str(piece.name))
return True
while 0 <= i <= 7 and 0 <= j <= 7:
square_to_check = board.board[i][j]
if square_to_check is not None:
piece = square_to_check
the_piece_is_bishop = piece.name == "\u265D"
the_piece_is_queen = piece.name == "\u265B"
if (the_piece_is_bishop or the_piece_is_queen) and piece.color != my_color:
print("threat in diagonal: " + str(piece.name))
return True
elif piece.color == my_color:
return False
i += line_iterator
j += column_iterator
return False
def check_if_king_is_in_check(king_position, king_color, board):
checking_diagonals = check_for_opponent_in_diagonal(king_color, board, king_position, True, True) or \
check_for_opponent_in_diagonal(king_color, board, king_position, True, False) or \
check_for_opponent_in_diagonal(king_color, board, king_position, False, True) or \
check_for_opponent_in_diagonal(king_color, board, king_position, False, False)
if checking_diagonals is True:
return True
else:
checking_straights = check_for_opponent_in_straight(king_color, board, king_position, True, True) or \
check_for_opponent_in_straight(king_color, board, king_position, True, False) or \
check_for_opponent_in_straight(king_color, board, king_position, False, True) or \
check_for_opponent_in_straight(king_color, board, king_position, False, False)
if checking_straights is True:
return True
else:
checking_knights = check_for_opponent_knight(king_color, board, king_position, True, True) or \
check_for_opponent_knight(king_color, board, king_position, True, False) or \
check_for_opponent_knight(king_color, board, king_position, False, True) or \
check_for_opponent_knight(king_color, board, king_position, False, False)
if checking_knights:
return True
return False
def check_if_the_move_is_a_checkmate(my_color, to, board):
if board.board[to[0]][to[1]] is not None:
piece_that_will_taken = board.board[to[0]][to[1]]
print(str(piece_that_will_taken))
the_move_ends_in_a_opponent_king = piece_that_will_taken.name == "\u265A" and piece_that_will_taken.color != my_color
if the_move_ends_in_a_opponent_king:
return True
else:
return False
|
a26846eee4e595884b555310b1b8c9ffec969089 | michaelsprintson/me.nu | /menu_read/just_read_food.py | 4,920 | 3.53125 | 4 | import os
import io
from collections import defaultdict
import json
import re
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def findprice(usemenu):
price_list = []
for lineidx in range(len(usemenu)):
if is_number(usemenu[lineidx]):
price_list.append(float(usemenu[lineidx].strip()))
return price_list
def findfood(usemenu):
food_list = []
for lineidx in range(len(usemenu)):
if not is_number(usemenu[lineidx]):
food_list.append(usemenu[lineidx].strip())
return food_list
def findidx(usemenu, findprice):
"""
:param usemenu: menu result from OCR
:param findprice: True if we are finding the price section idx, otherwise for food section idx
:return:
"""
for lineidx in range(len(usemenu)):
if findprice:
if (usemenu[lineidx][0]).isdigit(): # if its a price
sectionidx = lineidx
break
else: # if its a food item
if not (usemenu[lineidx][0]).isdigit():
sectionidx = lineidx
break
if lineidx == len(usemenu) - 1:
return len(usemenu) - 1
return sectionidx
def recallfind(usemenu):
"""
:param usemenu: menu result of OCR
:return: a list of the indexes in the menu lines where it changes from dishes to itesm
"""
current = 0
outto = [0]
pricefind = True
while current < len(usemenu)-1:
sectionplace = findidx(usemenu[current:], pricefind)
current += sectionplace
outto.append(current)
pricefind = not pricefind
print(outto)
return outto
def first_clean(ocr_menu):
menu = io.open(ocr_menu, "r", encoding="utf-8")
menu_lines = menu.readlines()
remove_bad = [] # empty list to hold raw lines of the cleaned up full menu
# get rid of the random numbers from OCR and the menu headings
for lineidx in range(len(menu_lines)):
item = menu_lines[lineidx].strip()
if (len(item) >= 4) and (item[3].isdigit() or ((not item[0].isdigit() and item[1].isdigit()))):
remove_bad.append(menu_lines[lineidx])
#print(remove_bad)
return remove_bad
def make_fooddict(foods, prices):
menu_dict = defaultdict()
#print (len(foods), len(prices))
for foodidx in range(len(foods)):
#print(foods[foodidx], prices[foodidx])
menu_dict[foods[foodidx]] = prices[foodidx]
return menu_dict
def filter(menu_dict, user_pref):
pref = json.load(open(user_pref, "r"))
budget = float(pref['budget'].strip())
# budget = 100.0
eats_meat = not pref['diet-veg'] in ['True']
takeout_pref = (pref['diet-exclude'].strip().split(','))
# filters out dishes based on vegetarian status and budget
meats = ["Beef", "Pork", "Duck", "Chicken", "Lamb", "Blood", "Lung",
"Meat", "Fish", "Clam", "Tripe", "Prawn", "Rib", "Tilapia", "Rabbit", "Bacon"]
newdict = {}
meatcontentbool = {dish:False for dish in menu_dict}
for dish in menu_dict:
if menu_dict[dish] <= budget:
if not eats_meat:
for meat in meats:
if meat in dish:
meatcontentbool[dish] = True
else:
newdict[dish] = menu_dict[dish]
if not eats_meat:
kept = [dish for (dish,boool) in meatcontentbool.items() if boool == False]
for keptmeal in kept:
newdict[keptmeal] = menu_dict[keptmeal]
finaldict= {} # filter out dishes specified as bad by user
for dish in newdict:
badstuffin = False
for takeout in takeout_pref:
if takeout.lower() in dish.lower():
badstuffin = True
if not badstuffin:
finaldict[dish] = newdict[dish]
return finaldict
def final_dump(menu, pref, dump, dumpsavename):
"""
:param menu: OCR result of menu as txt
:param pref: preferences input as txt
:param dump: True if you want to dump menudict result to json
:return:
"""
cleaned = first_clean(menu)
foods = findfood(cleaned)
prices = findprice(cleaned)
menudict = make_fooddict(foods, prices)
menudict = filter(menudict, pref)
if dump:
with open("menu_read/menuJSON/" + dumpsavename + '.json', 'w') as cleaned_menu:
json.dump(menudict, cleaned_menu)
return menudict
# create dictionary
#d = load_words()
# run test with normal pictures
# detect_text('ocr\menupictures\pic6.jpg', 'pic6test')
# run test with weird pictures
# for i in range(2, 5):
# pic_loc = 'ocr\menupictures\weirdpic\wpic' + str(i) + '.jpg'
# weird_file_name = 'weirdfiletest' + str(i)
# detect_text(pic_loc, weird_file_name)
print(final_dump("menu_read/ocr/menu_tests/final.txt",
"menu_read/preferencesData.json", False, "weirdpic"))
|
77569a6d1e2e6a9fa3d3d8d7a49d5adf1d924af6 | carlos-hereee/Algorithms | /rock_paper_scissors/rps.py | 848 | 3.71875 | 4 | #!/usr/bin/python
import sys
# generate all possible plays per game where n is the number of plays per round
# You'll want to define a list with all of the possible Rock Paper Scissors plays.
def rock_paper_scissors(n):
# we're building up a list of results
outcome = []
choices = ['rock', 'paper', 'scissors']
def inner_rps(rounds_left, result=[]):
if rounds_left == 0:
outcome.append(result)
return False
for c in choices:
# recursion
inner_rps(rounds_left-1, result+[c])
inner_rps(n, [])
return outcome
print('\nnumber of plays: ', rock_paper_scissors(3))
if __name__ == "__main__":
if len(sys.argv) > 1:
num_plays = int(sys.argv[1])
print(rock_paper_scissors(num_plays))
else:
print('Usage: rps.py [num_plays]')
|
096f74428c55f6898bdb8f646230d823f5acd7c2 | KebadSew/scratch_python | /numpy_2.py | 1,848 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 24 09:51:18 2020
@author: legen
"""
from clear_console import cls
import numpy as np
cls()
# Generate some random data using numpy
data = np.random.randn(2,3) # 2 by 3 array; 2 rows / 3 columns
print(data)
data=data*2
print(data)
print(data + data)
print(data.shape)
print(data.dtype)
cls()
# Creating ndarrays (N-Dimensional Arrays)
data1 = [1, 2, 9.7, 0, 4]
data2 = np.array(data1)
print(data2)
data3 = [[8,4,2,4],[5,6,7,8]]
data3 = np.array(data3)
print('----')
print(data3)
print(data3.shape)
print(data3.dtype)
print(data3.ndim) # 2-dimensional array
print('----')
data4 = [[8,4,2,4],[5,6,7,8],[4,5,6,9],[4,5,6,9]]
data4 = np.array(data4)
print(data4)
print(data4.ndim) # 2 dimensional
cls()
# Creating ndarrays part II
data = np.zeros(10) # one dimensional
print(data)
print(data.ndim)
print(data.dtype)
data = np.zeros((2,3)) # two dimensional
print(data)
print(data.shape)
print(data.ndim)
print(data.dtype)
data = np.ones((2,3)) # two dimensional
print(data)
print(data.shape)
print(data.ndim)
print(data.dtype)
data = np.empty((2,3)) # 2 dimensional
print(data)
print(data.shape)
print(data.ndim)
print(data.dtype)
cls()
data = np.ones((2,3,2)) # 3 dimensional
print(data)
print(data.shape)
print(data.ndim)
print(data.dtype)
cls()
data = np.ones((2,3,2,2)) # 4 dimensional
print(data)
print(data.shape)
print(data.ndim)
print(data.dtype)
cls()
data = np.arange(10)
print(data)
cls()
# Example: using 'full' function
data = np.full((2,3), 8.5, float,order='C')
print(data)
print(data.astype(np.int64)) #convert to int
print(data.astype(np.int32)) #convert to int
print(data)
data = np.full((2,3), 8, np.int64,order='C')
print(data.astype(np.float)) #convert to float
print(' --- ')
data = np.eye(5) # 2x2 matrix
print(data)
data = np.identity(5)
print(data)
|
894232f801fc4288ba570dbf99ba065ddaf2333d | KebadSew/scratch_python | /tuple1.py | 782 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 22:29:46 2020
@author: legen
"""
from clear_console import cls
cls()
tup = 1,2,3.5,'hello',['a','b','c']
print(tup)
tup[4].append('d')
print(tup)
nested_tup='a','b','c',(1,3,4), 'd',(6,7)
print(nested_tup)
print(tuple("mike world!")[0].upper())
print(tuple(['a','b','c']))
print(tuple("mike world!") + tuple(['a','b','c']))
print(tuple(['a','b','c'])*2)
tup = ('a','b','c')
a,b,c = tup
print('a={0} b={1} c={2}'.format(a,b,c))
tup = 4, 5, (6, 7)
a,b,c = tup
print(c)
a,b,(c,d) = tup
print(d)
c, d = d, c
print(d)
seq = [(1,2,3),(4,5,6),(7,8,9)]
for a,b,c in seq:
print('a={0}, b={1}, c={2}'.format(a,b,c))
values = 1,2,3,4,5,6,7,1
print('count=',values.count(1))
a,b,*_ = values
print(_)
print(a,b)
print((a,b))
|
7994795a5d18192f34008eb09414b943a591f078 | bretcolloff/home | /Python/solutions/inversions/inversions.py | 1,768 | 3.59375 | 4 | import os, sys
from itertools import islice
# def inversionmerge(input):
# length = len(input)
# if len(input) == 1:
# return (0, input)
#
# def merge(left, right):
# resultl = []
# resultc = 0
#
# while left and right:
# if left[0] <= right[0]:
# result.append(left[0])
# del left[0]
# else:
# resultc = resultc + len(left)
# result.append(right[0])
# del right[0]
#
# # One of the lists is empty, add the rest to the end.
# while left:
# result.append(left[0])
# del left[0]
# while right:
# result.append(right[0])
# del right[0]
#
# return (resultc, resultl)
#
# middle = int(length/2)-1
# left = islice(input, 0, middle)
# print (left)
# right = islice(input, middle+1, length-1)
# print (right)
#
# # Subdivide again
# left = inversionmerge(left)
# right = inversionmerge(right)
#
# return merge(left, right)
count = 0
def merge_sort(li, c):
if len(li) < 2: return li
m = len(li) / 2
return merge(merge_sort(li[:int(m)],c), merge_sort(li[int(m):],c),c)
def merge(l, r, c):
result = []
l.reverse()
r.reverse()
while l and r:
s = l if l[-1] < r[-1] else r
result.append(s.pop())
if (s == r): c[0] += len(l)
rest = l if l else r
rest.reverse()
result.extend(rest)
return result
def main(argv=None):
unsorted = []
with open("IntegerArray.txt") as f:
for line in f:
unsorted.append(int(line))
count = [0]
done = merge_sort(unsorted, count)
print (count[0])
if __name__ == '__main__':
main()
|
ee72d1073360456a8cc824b2892529719d7f8933 | bretcolloff/home | /Python/solutions/ctci/arraysandstrings.py | 2,996 | 3.921875 | 4 |
# Implement an algorithm to determine if a string has all unique characeters.
def onepointone(input):
print("1.1")
print(len(set(input)))
# What if you cannot use additional data structures?
total = 0
lastletter = ''
for letter in sorted(input):
if letter != lastletter:
lastletter = letter
total += 1
print (total)
def onepointtwo():
print("1.2")
print("Walk a point to the end, start one at the start. Swap")
# Given two strings, write a method to decide if one is a permutation of the other.
def onepointthree(a, b):
print("1.3")
if len(a) != len (b):
return False
a = sorted(a)
b = sorted(b)
result = True
for i in range(0, len(a)):
if a[i] != b[i]:
result = False
break
print (result)
# Replace spaces with %20s
def onepointfour(input):
print("1.4")
input = list(input)
lastcharacter = len(input) - 1
lastindex = len(input) - 1
start = 0
while True:
if input[lastcharacter] != ' ':
break
lastcharacter -= 1
while True:
if input[start] is not ' ':
start += 1
else:
start -= 1
break
# Walk backwards and keep pushing the characters to the end.
while lastcharacter > start:
if input[lastcharacter] is not ' ':
input[lastindex] = input[lastcharacter]
input[lastcharacter] = ' '
lastcharacter -= 1
lastindex -= 1
else:
lastcharacter -= 1
lastindex -= 3
# Replace the spaces with 'spaces'
for i in range(0, len(input) - 1):
if input[i] == ' ':
input[i] = '%'
input[i + 1] = '2'
input[i + 2] = '0'
i += 3
print (''.join(input))
# String compression
def onepointfive(input):
print("1.5")
output = []
outputlen = 0
lastchar = ''
count = 0
compressed = True
for i, c in enumerate(list(input)):
if c is not lastchar:
if lastchar is '':
lastchar = c
count = 1
continue
output.append(str(lastchar))
output.append(str(count))
outputlen += 2
count = 0
lastchar = c
count += 1
else:
count += 1
if outputlen > i:
compressed = False
break
output.append(str(lastchar))
output.append(str(count))
if compressed:
print(''.join(output))
else:
print(input)
def onepointsix():
print("1.6")
def onepointseven():
print("1.7")
def onepointeight():
print("1.8")
def main(argv=None):
onepointone("abcdefggg")
onepointtwo()
onepointthree("abcde", "edcba")
onepointfour("Mr John Smith ")
onepointfive("aabbcccccaaa")
onepointsix()
onepointseven()
onepointeight()
if __name__ == '__main__':
main()
|
1843aaa61cf284ffe9b28291b272823e0ec17b63 | rkhapov/chip8 | /virtualmachine/timer.py | 607 | 3.65625 | 4 | #!/usr/bin/env python3
class Timer:
def __init__(self, count: int =0):
if not isinstance(count, int) or count < 0 or count > 255:
raise ValueError('Timer count must be integer value in range [0;255]')
self._count = count
def decrease(self):
if self._count != 0:
self._count -= 1
def get_count(self):
return self._count
def set_count(self, count: int):
if not isinstance(count, int) or count < 0 or count > 255:
raise ValueError('Timer count must be integer value in range [0;255]')
self._count = count
|
292dcce71348062f01014015df4525d23502d09e | rumman07/python | /IT210/PythonCode/discount.py | 301 | 3.890625 | 4 | #computer bookstore kilobyte day example.
originalPrice = float(input("Please enter thr price: "))
#dicounted rates
if originalPrice < 128:
discountRate = 0.92
else:
discountRate = 0.84
discountedPrice = discountRate * originalPrice
print("Price $%.2f" % discountedPrice)
|
bdba4dfc4df3eb7d21cccfd4b2c4a5db7464bd70 | rumman07/python | /IT210/PythonCode/msog.py | 340 | 3.875 | 4 | str1 = "string1"
str2 = "some other stuff"
str3 = "still more stuff"
print(str1)
print (str2,str3)
str4 = str3 + str3
print(str4)
x = 4
outstr = "the value of x is" + "x"
print(outstr)
in_val = input("Enter an integer diameter of a circle")
print(in_val)
out_val = int(in_val)
print (out_val)
x = out_val + 2
print(x)
|
3a69e2726e0daddd5219296fbad5ef2b9b1f58ce | rumman07/python | /IT210/PythonCode/Quiz2.py | 375 | 3.75 | 4 | def main():
windSpeed = 0
temp = 0
for i in range (1, 11):
V=i*5
WC = 35.74+0.6215*temp-3.75*V**0.16+0.4275*temp*V**0.16
#temperature
for temp in range (-45, 40, 5):
print (2*" ",temp, end=" ")
print("\n"," "*2,"-"*105)
#Wind Speed
for windSpeed in range (0, 60, 5):
print(windSpeed)
main()
|
d368798240b86c8a85f14cd5cab1318474bcdccc | rumman07/python | /IT210/PythonCode/Algorithm3.py | 255 | 4.0625 | 4 | #Prompt utill a match is found
valid = False
while not valid:
value = int(input("Please enter a positive vlaue < 100: "))
if value > 0 and value < 100:
valid = True
else:
print("The value is not valid")
|
4567497d8e02483b5359e568f6d0e793f898e52f | rumman07/python | /IT210/PythonCode/wage.py | 563 | 4.0625 | 4 | #Lab3 Rumman Ahmed
#Read user input hours worked and hourly rate
hours = float (input("ENTER THE HOURS WORKED AS INTEGER"))
rate = float (input("Enter the hourly pay rate as an integer"))
if hours > 40:
gross = 40 * rate + (hours - 40) * rate * 1.5
print ("Overtime")
else:
gross = hours * rate
print("no overtime:")
print("The gross wage is", gross)
numberOfDependents = int(input("Please enter number of dependents: "))
netwage = gross - (50 * numberOfDependents)
print(netwage)
|
5c0805b05748c02724627dd96a267b15af9312de | rumman07/python | /recursion.py | 181 | 3.953125 | 4 | #!/usr/bin/python3.8
def printTriangle(sideLength):
if sideLength < 1 :
return
printTriangle(sideLength - 1)
print("[]" * sideLength)
printTriangle(2)
|
cff8a895ec8bbe2c1997d04f5b5f6e1851bc731d | jzaldivar/SciData-tareas | /C01_Tarea02b.py | 527 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
C01.Tarea02b
"""
# Definiciones
estaciones = {'PRIMAVERA': ['abril', 'mayo', 'junio'],
'VERANO': ['julio', 'agosto', 'septiembre'],
'OTOÑO': ['octubre', 'noviembre', 'diciembre'],
'INVIERNO': ['enero', 'febrero', 'marzo']}
# Entradas
mes = input('mes = ')
# Proceso
mes = mes.lower()
for estacion, meses in estaciones.items():
if mes in meses:
break
else:
estacion = 'Error de entrada'
# Salidas
print(estacion)
|
5a0cd3cb52e874fd30351a48375beb2806c2843c | Hbodor/MOPSI | /Longstaff Schwartz (BS , Regression + NN ).py | 8,847 | 4 | 4 | from numpy import linalg, zeros, ones, hstack, asarray
import itertools
def basis_vector(n, i):
""" Return an array like [0, 0, ..., 1, ..., 0, 0]
>>> from multipolyfit.core import basis_vector
>>> basis_vector(3, 1)
array([0, 1, 0])
>>> basis_vector(5, 4)
array([0, 0, 0, 0, 1])
"""
x = zeros(n, dtype=int)
x[i] = 1
return x
def as_tall(x):
""" Turns a row vector into a column vector """
return x.reshape(x.shape + (1,))
def multipolyfit(xs, y, deg, full=False, model_out=True, powers_out=False):
"""
Least squares multivariate polynomial fit
Fit a polynomial like ``y = a**2 + 3a - 2ab + 4b**2 - 1``
with many covariates a, b, c, ...
Parameters
----------
xs : array_like, shape (M, k)
x-coordinates of the k covariates over the M sample points
y : array_like, shape(M,)
y-coordinates of the sample points.
deg : int
Degree o fthe fitting polynomial
model_out : bool (defaults to True)
If True return a callable function
If False return an array of coefficients
powers_out : bool (defaults to False)
Returns the meaning of each of the coefficients in the form of an
iterator that gives the powers over the inputs and 1
For example if xs corresponds to the covariates a,b,c then the array
[1, 2, 1, 0] corresponds to 1**1 * a**2 * b**1 * c**0
See Also
--------
numpy.polyfit
"""
y = asarray(y).squeeze()
rows = y.shape[0]
xs = asarray(xs)
num_covariates = xs.shape[1]
xs = hstack((ones((xs.shape[0], 1), dtype=xs.dtype) , xs))
generators = [basis_vector(num_covariates+1, i)
for i in range(num_covariates+1)]
# All combinations of degrees
powers = list(map(sum, itertools.combinations_with_replacement(generators, deg)))
# Raise data to specified degree pattern, stack in order
A = hstack(asarray([as_tall((xs**p).prod(1)) for p in powers]))
beta = linalg.lstsq(A, y)[0]
if model_out:
return mk_model(beta, powers)
if powers_out:
return beta, powers
return beta
def mk_model(beta, powers):
""" Create a callable pyTaun function out of beta/powers from multipolyfit
This function is callable from within multipolyfit using the model_out flag
"""
# Create a function that takes in many x values
# and returns an approximate y value
def model(*args):
num_covariates = len(powers[0]) - 1
args=args[0]
if len(args)!=(num_covariates):
raise ValueError("Expected %d inputs"%num_covariates)
xs = [1]+args
return sum([coeff * (xs**p).prod()
for p, coeff in zip(powers, beta)])
return model
def mk_sympy_function(beta, powers):
from sympy import symbols, Add, Mul, S
num_covariates = len(powers[0]) - 1
xs = (S.One,) + symbols('x0:%d'%num_covariates)
return Add(*[coeff * Mul(*[x**deg for x, deg in zip(xs, power)])
for power, coeff in zip(powers, beta)])
##########################################################################################################################################################################################################
#Neural Network
from keras.models import Sequential
from keras.layers.core import Activation
from keras.layers.core import Flatten
from keras.layers.core import Dense
class ApproxNet:
@staticmethod
def build(input_length):
'''
Documentation ?
'''
# initialize the model
model = Sequential()
#input layer
model.add(Dense(input_length*3 , input_dim=input_length,kernel_initializer='he_normal',activation="selu"))
#hidden layers
model.add(Dense(input_length*2, activation="selu"))
#hidden layers
model.add(Dense(input_length, activation="selu"))
#output layer
model.add(Dense(1,activation="selu"))
model.compile(loss='mse', optimizer='RMSprop', metrics=['accuracy','mse', 'mae', 'mape', 'cosine'])
# return the constructed network architecture
return model
def approximation(j,Tau,paths):
model = ApproxNet.build(len(paths[0][0]))
payOffs=[]
x=np.zeros((len(paths),len(paths[0][0])))
for i,path in enumerate(paths):
payOffs.append(B(j,Tau[i][j+1])*payOff(path[Tau[i][j+1]],K))
x[i,:]=np.asarray(path[j])
# x = np.log(x)
# print(np.mean(x))
print(x.shape,x[0:1].shape)
history = model.fit(x, payOffs, batch_size=32, epochs=100, verbose=0)
return (model,history)
####################################
import numpy as np
from scipy.interpolate import *
#import multipolyfit
#Parameters
sigma=0.3 #Volatility
M=5000 #Number of paths
T=1 # Expiration (in years)
dt = 1/3 # steps of exercise (in years)
N = int(T/dt) #number of iterations
r=0.03 #Risk-free interest rate (annual)
X_0=[20]
K=X_0
reg=True # regression or neural network
############################################################################################################
#Genaerating a p-dimensional Brownian motion
from scipy.stats import norm
# import matplotlib.pyplot as plt
from math import sqrt,log,exp
# Process parameters
def genBM():
W=[]
for i in range(len(X_0)):
# Initial condition.
x = 0
# Number of iterations to compute.
n = N
# Iterate to compute the steps of the Brownian motion.
D=[]
X=[]
for k in range(n):
x = x + norm.rvs(scale=sqrt(dt))
D.append(x)
W.append(D)
return W
Sigma=sigma*np.eye(len(X_0))
#since sum(sigma(i,j)**2) will be calculated a lot of times, we will save iy in variable to reduce time complexity
SIGMA2=[]
for i in range(len(Sigma[0])):
summ=0
for j in range( len(Sigma[0]) ):
summ+=Sigma[i][j]**2
SIGMA2.append(summ)
def next(X,k,W,dt):
L=[]
for i in range(len(X)):
summ=0 #will play the role of sum(sigma(i,j)*Wk(j))
for j in range( len(X)):
summ+=Sigma[i][j]*W[j][k-1] #Because we willl never calculate the first value of the assets
exposant=(r-1/2*SIGMA2[i])*k*dt+summ
L.append(X[i]*exp(exposant))
return L
#########################################################################################################################################################################################################"
#function that generates a path
def pathGen(X_0):
W=genBM()
L=[0 for i in range(N+1)]
L[0]=X_0
for i in range(1,N+1):
L[i]=next(X_0,i,W,dt)
return L
##try it
#print(pathGen(X_0))
#Gain function
def payOff(X,K):
return max(np.sum(K)-np.sum(X),0)
#Interest rate function
def B(j,k):
# P=1
# for i in range(j,k):
# P*=1/(1+r)
return exp(-r*(k-j)*dt)
def price(Taus,paths):
Q=0
M=len(Taus)
for m in range(M):
Q+=B(0,Taus[m][0])*payOff(paths[m][Taus[m][0]],K)
Q=Q/M
return Q
#regression to find the polynom
def regression(j,Tau,paths):
payOffs=[]
x=[]
for (i,path) in enumerate(paths):
payOffs.append(B(j,Tau[i][j+1])*payOff(path[Tau[i][j+1]],K))
x.append(path[j])
p3=multipolyfit(x, payOffs, 5)
return p3
HISTORY=[]
HISTORY2=[]
for kk in range(100):
#Generating paths
paths=[]
for i in range(M):
path=pathGen(X_0)
paths.append(path)
#
#Defining Tausm
Taus=[[0 for i in range(N+1)] for j in range(M)]
for i in range(M):
Taus[i][-1]=N
#construction of Taus
if reg:
#REGRESSION
for j in range(N-1,-1,-1):
regresseur=regression(j,Taus,paths)
for i in range(M):
if ( payOff(paths[i][j],K) >= regresseur( paths[i][j] ) ):
Taus[i][j]=j
else :
Taus[i][j]=Taus[i][j+1]
else:
#Neural Network
for j in range(N-1,-1,-1):
model,history = approximation(j,Taus,paths)
HISTORY.append(history.history["loss"])
HISTORY2.append(history)
for i in range(M):
if ( payOff(paths[i][j],K) >= model.predict( np.resize(paths[i][j],(1,len(X_0))) ) ):
Taus[i][j]=j
else :
Taus[i][j]=Taus[i][j+1]
print(price(Taus,paths))
|
2015152c0424d7b45235cefa678ea2cb90523132 | ChiselD/guess-my-number | /app.py | 401 | 4.125 | 4 | import random
secret_number = random.randint(1,101)
guess = int(input("Guess what number I'm thinking of (between 1 and 100): "))
while guess != secret_number:
if guess > secret_number:
guess = int(input("Too high! Guess again: "))
if guess < secret_number:
guess = int(input("Too low! Guess again: "))
if guess == secret_number:
print(f"You guessed it! I was thinking of {secret_number}.") |
e9a2f1aa4c0059022f39600a3f73453b07901052 | devil927/Python_ap | /calculator.py | 4,724 | 3.734375 | 4 | # Import library
#===========================================================================================================
from tkinter import *
# Button operation
#===========================================================================================================
# Display the input
def btnc(number):
global operator
operator=operator+str(number)
text_str.set(operator)
# Clear Button
def btnclr():
global operator
operator=""
text_str.set(operator)
# For Evaluation of the inputs
def btneval():
global operator
try:
s=str(eval(operator))
text_str.set(s)
except:
text_str.set("Syntax error")
operator=""
# Gui
#===========================================================================================================
cal=Tk()
cal.title("Calculator")
cal.resizable(width=False,height=False)
text_str=StringVar()
text_inp=Entry(cal,font=('arial',20,'bold'),textvariable=text_str,bd=20,insertwidth=4,
bg="powder blue",justify='right')
text_inp.grid(columnspan=4,rowspan=2)
operator=""
# Buttons
#=============================================================================================================
bt7=Button(cal,text='7',font=('arial',20,'bold'),padx=15,pady=8,bd=8,fg="black",bg="powder blue",command=lambda:btnc(7)).grid(row=3,column=0) #Button 7
bt8=Button(cal,text='8',font=('arial',20,'bold'),padx=15,pady=8,bd=8,fg="black",bg="powder blue",command=lambda:btnc(8)).grid(row=3,column=1) #Button 8
bt9=Button(cal,text='9',font=('arial',20,'bold'),padx=15,pady=8,bd=8,fg="black",bg="powder blue",command=lambda:btnc(9)).grid(row=3,column=2) #Button 9
plus=Button(cal,text='+',font=('arial',20,'bold'),padx=15,pady=8,bd=8,fg="black",bg="powder blue",command=lambda:btnc("+")).grid(row=3,column=3)
#=============================================================================================================
bt4=Button(cal,text='4',font=('arial',20,'bold'),padx=15,bd=8,pady=8,fg="black",bg="powder blue",command=lambda:btnc(4)).grid(row=4,column=0) #Button 4
bt5=Button(cal,text='5',font=('arial',20,'bold'),padx=15,bd=8,pady=8,fg="black",bg="powder blue",command=lambda:btnc(5)).grid(row=4,column=1) #Button 5
bt6=Button(cal,text='6',font=('arial',20,'bold'),padx=15,bd=8,pady=8,fg="black",bg="powder blue",command=lambda:btnc(6)).grid(row=4,column=2) #Button 6
sub=Button(cal,text='- ',font=('arial',20,'bold'),padx=15,bd=9,pady=8,fg="black",bg="powder blue",command=lambda:btnc("-")).grid(row=4,column=3)
#=============================================================================================================
bt1=Button(cal,text='1',font=('arial',20,'bold'),padx=15,bd=8,pady=8,fg="black",bg="powder blue",command=lambda:btnc(1)).grid(row=5,column=0) #Button 1
bt2=Button(cal,text='2',font=('arial',20,'bold'),padx=15,bd=8,pady=8,fg="black",bg="powder blue",command=lambda:btnc(2)).grid(row=5,column=1) #Button 2
bt3=Button(cal,text='3',font=('arial',20,'bold'),padx=15,bd=8,pady=8,fg="black",bg="powder blue",command=lambda:btnc(3)).grid(row=5,column=2) #Button 3
multiply=Button(cal,text='X',font=('arial',20,'bold'),padx=15,pady=8,bd=8,fg="black",bg="powder blue",command=lambda:btnc("x")).grid(row=5,column=3)
#=============================================================================================================
remainder=Button(cal,text='%',font=('arial',20,'bold'),padx=15,bd=8,pady=8,fg="black",bg="powder blue",command=lambda:btnc("%")).grid(row=6,column=0)
bt12=Button(cal,text='0',font=('arial',20,'bold'),padx=15,pady=8,bd=8,fg="black",bg="powder blue",command=lambda:btnc(0)).grid(row=6,column=1)
dot=Button(cal,text='. ',font=('arial',20,'bold'),padx=15,bd=8,pady=8,fg="black",bg="powder blue",command=lambda:btnc(".")).grid(row=6,column=2)
div=Button(cal,text='/ ',font=('arial',20,'bold'),padx=15,bd=8,pady=8,fg="black",bg="powder blue",command=lambda:btnc("/")).grid(row=6,column=3)
#=============================================================================================================
clr=Button(cal,text='c',font=('arial',20,'bold'),padx=56,pady=8,bd=8,fg="black",bg="powder blue",command=btnclr).grid(row=2,column=0,columnspan=2)
equal=Button(cal,text='=',font=('arial',20,'bold'),padx=56,pady=8,bd=8,fg="black",bg="powder blue",command=btneval).grid(row=2,columnspan=2,column=2)
#================================================================================================================================= Button ends here
cal.mainloop()
|
de0e2524796403090559ac0db966ce3513474396 | kyien/py-proj | /tuples.py | 494 | 4.03125 | 4 | #control/Decision Making statements
#if statement
#if..else statements
#nested if statements
#elif statement
print('*******Starting a transaction*****')
amount=int(input("Enter amount to withdraw: "))
discount=0
if amount <1000:
discount=amount *0.45
print('Net amount is: ', amount+discount)
elif amount <2000:
discount=amount*0.5
print('Net amount is: ', amount+discount)
else:
discount=amount *0.7
print( 'Net amount is : ',amount+discount)
#print('Net amount :',amount+discount)
|
16457bef18a30cee6b1014e3ae7a46822ea55bc5 | Robert-Kolodziej/Python-Progams- | /Prog4Kolodziej.py | 1,195 | 3.90625 | 4 | ##Bobby Kolodziej
##
##File: Prog4Kolodziej.py
##
##Purpose: The purpose of this program is to play a random gambling game with dice
##
##Input: The input for this program is the ammount of money the player wants to play with.
##
##Output: The output for this program will be the pot, the value on die 1, the value on die 2, the sum of the both dice, and the play number.
##
##Certification of authority:
##I certify that this lab is entirely my own work.
def main():
#Greeting for the player
pot=int(input("Please enter the amount of money you would like to play with: "))
play= 0
maxvalue=0
#Playing the game
while pot > 0:
import random
die1value= random.randint(1,6)
die2value= random.randint(1,6)
sum=die1value + die2value
if sum == 7:
pot=pot+4
else:
pot=pot-1
play=play+1
print("The first die value was", die1value, ", the second die value was", die2value, ", you have $", pot, "in your pot", ", you are on play number", play)
print("Game over: You ran out of money")
print("It took you", play, "plays to run out of money")
main()
|
d8ae1578be3c1d7b4964f09ce344d75f3747249e | Robert-Kolodziej/Python-Progams- | /click.py | 663 | 3.890625 | 4 | #File: click.py
from graphics import *
def main():
#get clicks from the user and tell her where she clicked
radius = 5
clicks = int(input("How many clicks do you want: "))
win = GraphWin("Click Me", 300,300)
center = Point(150,150)
label = Text(center, "Click randomly times around the screen")
label.draw(win)
for i in range (clicks):
p = win.getMouse()
print("You clicked at: ", p.getX(), p.getY())
circ = Circle(p,radius)
circ.setFill("red")
radius+=5
circ.draw(win)
label = Text(p, "Thats all of your clicks")
label.draw(win)
main()
|
7765d35c1b8eba17fe14118d7a2f3873af1cec6c | Robert-Kolodziej/Python-Progams- | /tryGraphics.py | 1,249 | 3.890625 | 4 | #fun with gtraphics
#tryGraphics.py
#import the graphics package
from graphics import *
#we need a graphics window to start
win = GraphWin("My Graphics Window", 400,400)
#make a point or two
p = Point(50,60)
p2 = Point(140,100)
x = p.getX()
y = p.getY()
print(x,y)
p.draw(win)
p2.draw(win)
#draw a circle
center = Point(100,100)
circ = Circle(center,30)
circ.setFill("red")
circ.setOutline("green")
circ.setWidth(5)
circ.draw(win)
#label the circle
label = Text(center, "red circle")
label.draw(win)
#draw an X
startpoint = Point(20,30)
endpoint = Point(180,165)
startpoint2 = Point(20,165)
endpoint2 = Point(180,30)
line = Line(startpoint,endpoint)
line2 = Line(startpoint2,endpoint2)
line.setWidth(5)
line2.setWidth(5)
line.draw(win)
line2.draw(win)
#draw rectangle around the X
rect = Rectangle(startpoint, endpoint)
rect.setWidth(5)
rect.setOutline("blue")
rect.draw(win)
#draw an oval
ovalP1 = Point(300,100)
ovalP2 = Point(380,50)
oval= Oval(ovalP1,ovalP2)
oval.move(-40,0)
oval.setWidth(5)
oval.setOutline("gold")
oval.setFill("purple")
oval.draw(win)
#draw second oval
#oval2 = oval Noooooooooo!!!!!
oval2 = oval.clone()
oval2.move(0,60)
oval2.draw(win)
|
803a94b72c70de9135d1f221c7a2232304b27b11 | Robert-Kolodziej/Python-Progams- | /Prog8Kolodziej.py | 3,059 | 4.375 | 4 | ##Bobby Kolodziej
##
##File: Prog8Kolodziej.py
##
##Purpose: This program gives a list of options and the user picks one
## and this program reads another file and makes a rectangle
##
##Input: The user inputs the width of the rectangle and the height of the rectangle
## and the fillstyle of the rectangle
##
##Output: The program outputs the rectangle with the info that is input by the user
##
##Certification of authority:
##I certify that this lab is entirely my own work. But I communicated with the programming lab.
from rectangleKolodziej import Rectangle
def main():
##Printing the choices
userChoice = 'X'
print("Welcome to the rectangle builder")
print("W: Assign the width")
print("H: Assign the height")
print("F: Assign the fillstyle")
print("A: Calculate the area")
print("P: Calculate the perimeter")
print("T: Text Description of the rectangle")
print("D: Draw the rectangle")
print("Q: Quit")
newRectangle = Rectangle(10, 5, "*")
userChoice = input("Enter your choice: ")
##Interpreting the user choice
while userChoice != 'Q' or 'q' :
if userChoice == 'W' or userChoice =='w':
newWidth = int(input("Enter the new width: "))
if newWidth>0:
newRectangle.setWidth(newWidth)
userChoice = input("Enter your choice: ")
else:
print("Invalid width try again")
newWidth = int(input("Enter the new width: "))
elif userChoice == 'H'or userChoice =='h':
newHeight = int(input("Enter the new height: "))
if newHeight > 0:
newRectangle.setHeight(newHeight)
userChoice = input("Enter your choice: ")
else:
print("Invalid height try again")
userChoice = input("Enter your choice: ")
elif userChoice == 'F' or userChoice == 'f':
newFillstyle = input("Enter the new fillstyle: ")
newRectangle.setFillstyle(newFillstyle)
userChoice = input("Enter your choice: ")
elif userChoice == 'A' or userChoice == 'a':
newRectangle.calcArea()
userChoice = input("Enter your choice: ")
elif userChoice =='P' or userChoice == 'p':
newRectangle.calcPerimeter()
userChoice = input("Enter your choice: ")
elif userChoice == 'T' or userChoice =='t':
newRectangle.text()
userChoice = input("Enter your choice: ")
elif userChoice == 'D' or userChoice == 'd':
newRectangle.drawRectangle()
userChoice = input("Enter your choice: ")
elif userChoice == 'Q' or userChoice =='q':
print("Goodbye")
else:
print("Invalid Choice try again")
userChoice = input("Enter your choice: ")
main()
|
f024329bc3bcc1c260fcffd73d03b0c3308d358d | 11054/eadv-vi20iisa120 | /studentFolders/11019/hangman_project(incomplete).py | 3,172 | 3.96875 | 4 | # hangman display:
def display_hangman(tries):
stages = [ """
--------
| |
| O
| \\|/
| |
| / \\
-
""",
"""
--------
| |
| O
| \\|/
| |
| /
-
""",
"""
--------
| |
| O
| \\|/
| |
|
-
""",
"""
--------
| |
| O
| \\|
| |
|
-
""",
"""
--------
| |
| O
| |
| |
|
-
""",
"""
--------
| |
| O
|
|
|
-
""",
"""
--------
| |
|
|
|
|
-
"""
]
return stages[tries]
# code here:
import random
hang_list = ["Turkey, Chicken, Tango, Zulu, Valentine, Sam, Idiot, School, Job, Cookie, Family, Dog, Cat, Grave, Zero, One, Two, Tree"]
def get_word(word):
word - random.choice(hang_list)
return word.upper()
def play (word):
word_completion = '_' *]en(hang_list)
guessed = False
guessed_letters = []
guessed_words = []
tries = 12
print("Lets play hangman")
print(display_hangman(tries))
print(word_completion)
print(\n)
while guess and tries = 0:
guess = input("Please guess a letter or a word:").upper()
If len(guess) == 1 and guess.isalpha():
if guess in guess_letters:
print("You already guessed the letter"), guess)
elif guess not in letter:
print("is not in the word.")
tries == 1
guess_letters.append(guess)
else:
print ("Good job", guess, "is in the word!")
guess_letters.append (guess)
word_as_list = list(word_completion)
word_completion = "".join(word_completion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
1
elif len(guess) == len(word) and guess.isalpha()
else:
print("Not a valid guess.")
print(display_hangman(tries))
print(word_completion)
print(\n)
|
b9e8f7f83ff89e2066e4128f6d66a624bd7e73fb | piotrszacilowski/adventofcode-2020 | /day-01/day_01.py | 645 | 4.0625 | 4 | from itertools import combinations
def read_file_to_array(file):
with open(file, 'r') as file:
report = [line.strip() for line in file]
return report
def find_the_sum_of_two_numbers(report):
for x, y in combinations(report, 2):
if int(x) + int(y) == 2020:
return int(x) * int(y)
def find_the_sum_of_three_numbers(report):
for x, y, z in combinations(report, 3):
if int(x) + int(y) + int(z) == 2020:
return int(x) * int(y) * int(z)
print(find_the_sum_of_two_numbers(read_file_to_array("input.txt")))
print(find_the_sum_of_three_numbers(read_file_to_array("input.txt")))
|
726d8f6ae44f878b04a9ba0227742dae0dd507c8 | lis5662/Python | /python_crash _course_book/chapter 3/chapter 3 - 1.py | 3,341 | 3.578125 | 4 | bicycles = ['trek', 'cannondle', 'redline', 'specialized']
print(bicycles[0].title())
print(bicycles[1])
print(bicycles[3])
print(bicycles[-1])
bicycles = ['trek', 'cannondle', 'redline', 'specialized']
message = "My first bcycles was a " + bicycles[0].title() + "."
print(message)
# Изменение элементов списка
cars = ['Nissan GTR', 'Acura MDX', 'Infiniti QX', 'BMW X5']
print(cars)
cars[0] = 'Honda Accord'
print(cars)
# присоединение жлементов в конце списка
cars = ['Nissan GTR', 'Acura MDX', 'Infiniti QX', 'BMW X5']
print(cars)
cars.append("Acura RDX")
print(cars)
cars = []
cars.append("Honda")
cars.append("Volvo")
cars.append("Audi")
cars.append("Toyota")
print(cars)
# Вставка элементов в список
cars = ['Nissan GTR', 'Acura MDX', 'Infiniti QX', 'BMW X5']
print(cars)
cars.insert(0, "Audi Q8")
print(cars)
# Удаление из списка del
cars = ['Nissan GTR', 'Acura MDX', 'Infiniti QX', 'BMW X5']
print(cars)
del cars[0]
print(cars)
# удаление с помощью pop()
cars = ['Nissan GTR', 'Acura MDX', 'Infiniti QX', 'BMW X5']
print(cars)
last_owned = cars.pop()
print("The last car I owned was a " + last_owned.title() + ".")
# Извлечение элементов из произвольного списка pop()
cars = ['Nissan GTR', 'Acura MDX', 'Infiniti QX', 'BMW X5']
first_owned = cars.pop(0)
print("The first car I owned was a " + first_owned.title() + ".")
# Удаление элемента по значению remove()
cars = ['Nissan GTR', 'Acura MDX', 'Infiniti QX', 'BMW X5']
print(cars)
cars.remove('Acura MDX')
print(cars)
cars = ['Nissan GTR', 'Acura MDX', 'Infiniti QX', 'BMW X5']
print(cars)
too_exprensive = "BMW X5"
cars.remove(too_exprensive)
print(cars)
print("\n " + too_exprensive.title() + " is too exprensive for me.")
# Упорядочение списка
# sort()
cars = ['dodge', 'chevrolet', 'lexus', 'subaru']
cars.sort() # Список сортируется в алфавитном порядке
print(cars)
cars = ['dodge', 'chevrolet', 'lexus', 'subaru']
cars.sort(reverse=True) # Список сортируется в обратном порядке
print(cars)
# Временная сортировка списка sorted()
cars = ['dodge', 'chevrolet', 'lexus', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:") # Список сортируется временно
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
# Вывод списка в обратном порядке
cars = ['dodge', 'chevrolet', 'lexus', 'subaru']
cars.reverse() # Список сортируется в обратном порядке
print(cars)
# Определение длины списка len()
cars = ['dodge', 'chevrolet', 'lexus', 'subaru']
print(len(cars))
# Ошибки вывода списков
films = []
films.append("Game of the Thrones")
films.append("The Lord of the Rings")
films.append("Luther")
print(films[-1]) |
a1227220847949b53d5dae0e76ea87c41830fec7 | lis5662/Python | /python_crash _course_book/chapter 9/chapter 9.py | 7,915 | 4.53125 | 5 | # Создание и использование классов
class Dog():
"""Простая модель собаки."""
def __init__(self, name, age):
"""Инициализирует атрибуты name и age."""
self.name = name
self.age = age
def sit(self):
"""Собака садится по команде."""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""Собака перекатывается п окоманде."""
print(self.name.ttile() + " rolled over!")
# Создание экземпляра
#class Dog():
...
# my_dog = Dog('willie', 6)
# my_dog.sit()
# my_dog.roll_over()
# print("My dog's name is " + my_dog.name.title() + ".")
# print("My dog is " + str(my_dog.age) + " years old.")
# Создание нескольких экземпляров
#class Dog():
...
# my_dog = Dog('willie', 6)
# your_dog = Dog('lucy', 3)
# print("My dog's name is " + my_dog.name.title() + ".")
# print("My dog is " + str(my_dog.age) + " years old.")
# my_dog.sit()
# print("\nYour dog's name is " + your_dog.name.title() + ".")
# print("Your dog is " + str(your_dog.age) + " years old.")
# your_dog.sit()
# Класс Car
class Car():
"""Простая модель автомобиля."""
def __init__(self, make, model, year):
"""Инициализирует артибуты описания автомобиля"""
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
"""Возвращает аккуратно отформатированное описание."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
# Назначение атрибуту значения по умолчанию
class Car():
"""Простая модель автомобиля."""
def __init__(self, make, model, year):
"""Инициализирует артибуты описания автомобиля"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Возвращает аккуратно отформатированное описание."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""Выводит пробег машины в милях."""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""Устанавливает заданное значение на одометре.
При попытке обратной подкрутки изменения отклоняются."""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
"""Увеличивает показания одометра с заданным приращением."""
self.odometer_reading += miles
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
# Прямое изменение значения атрибута
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
# Изменение атрибута с помощью метода
my_new_car.update_odometer(23)
my_new_car.read_odometer()
my_used_car = Car('subaru', 'outback', 2013)
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(23500)
my_used_car.read_odometer()
my_used_car.increment_odometer(100)
my_used_car.read_odometer()
# Нааследование
class Car():
"""Прсотая модель автомобиля."""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class ElectricCar(Car):
"""Представляет аспекты машины, специфические для электромобилей"""
def __init__(self, make, model, year):
"""Инициализирует атрибуты класса-родителя.
Затем инициализирует артибуты, специфические для электромобиля."""
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
"""Выводит информацию о мощности аккумулятора"""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def fill_gas_tank():
"""У электромобиля нет бензобака."""
print("This car doesn't need a gas tank!")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
# Экземпляры как атрибуты
class Battery():
"""Простая модель аккумулятора электромобиля."""
def __init__(self, battery_size=70):
"""Инициализирует атрибуты аккумулятора."""
self.battery_size = battery_size
def describe_battery(self):
"""Выводит информацию о мощности аккумулятора."""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
"""Выводит приблизительный запас хода от аккумулятора"""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
class ElectricCar(Car):
"""Представляет аспекты машины, специфические для электромобилей"""
def __init__(self, make, model, year):
"""Инициализирует атрибуты класса-родителя.
Затем инициализирует артибуты, специфические для электромобиля."""
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
# Стандартная библиотека python
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".") |
7ef797d1c697f36db885c71a279d9b17d25e1bf8 | lis5662/Python | /decorator_function.py | 811 | 3.6875 | 4 | from datetime import date, datetime
from functools import wraps
# Создаем функцию декоратор
def find_time_for_execute(func):
@wraps(func)
def cover(*args, **kwargs):
start = datetime.now()
my_current_age = func(*args, **kwargs)
before_20000_days = 20000 - int(my_current_age)
end = datetime.now()
print(f"Функция {func.__name__} выполнялась {end - start} секунд")
print(f"До 20000 дней мне осталось: {before_20000_days}")
return cover
@find_time_for_execute
def my_age_in_days(year: int, month: int, day: int):
birthday = date(year, month, day)
today = date.today()
delta = today - birthday
return delta.days
# my_age_in_days(1990, 9, 23)
|
c32d98eba0eaa2db722d2318b87c707f395ff0b3 | lis5662/Python | /python_crash _course_book/chapter 4/chapter 4.py | 3,562 | 4.40625 | 4 | # Работа со списками цикл for
magicians = ['alice', 'david', 'carolina']
for magicians in magicians:
print(magicians)
# Более сложные действия с циклом for
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
# Выполнение действий после цикла for
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
print("Thank you, everyone. That was a great magic show!")
# Создание числовых списков range(), list()
for value in range(1, 5):
print(value)
# Создание списка из вызывающихся чисел
numbers = list(range(1, 6))
print(numbers)
# Построение четных чисел even
even_numbers = list(range(2, 11, 2))
print(even_numbers)
# создание списка квадратов всех целых чисел
squares = []
for value in range(1, 11):
square = value ** 2
squares.append(square)
print(squares)
# компактный вариант
squares = []
for value in range(1, 11):
squares.append(value**2)
print(squares)
# Простая статистика с числовыми списками min(), max(), sum()
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits)) # выводит минимальное значение списка
print(max(digits)) # выводит максимальное значение списка
print(sum(digits)) # выводит сумму значений списка
# Генераторы списокв
squares = [value ** 2 for value in range(1, 11)]
print(squares)
# Работа с частью списка - срезы
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])
# перебор содержимого среза
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
# Копирование списка
my_foods = ['pizza', 'falafel', 'carrot cake']
friends_foods = my_foods[:]
my_foods.append('cannoli')
friends_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friends_foods)
# Кортежи
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
#dimensions[0] = 250 нельзя присваивать новое значение в кортеже
# перебор всех значений в кортеже
dimensions = (200,50)
for dimension in dimensions:
print(dimension)
# замена кортежа
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
|
c6d9bf7de16d662ce134d0437be31efa03a2e3e2 | lis5662/Python | /python_bootcamp/sql_lite_python/select.py | 435 | 4.03125 | 4 | import sqlite3
conn = sqlite3.connect("my_friends.db")
# create cursos object
с = conn.cursor()
# с.execute("SELECT * FROM friends WHERE first_name IS 'Rosa'")
с.execute("SELECT * FROM friends WHERE closeness > 5 ORDER BY closeness")
#Iterate over cursor
# for result in с:
# print(result)
# Fetch One Result
# print(с.fetchone())
# Fetch all results as list
print(с.fetchall())
# commit changes
conn.commit()
conn.close() |
39a794fee3d4e8a05c324571c91453d39c66e801 | lis5662/Python | /python_bootcamp/functions/cpin_flip.py | 472 | 3.78125 | 4 | from random import random
# 1
def flip_coin():
# generate random number 0-1
r = random()
if r > 0.5:
return "Heads"
else:
return "Tails"
print(flip_coin())
# 2
def flip_coin():
if random() > 0.5:
return "HEADS"
else:
return "TAILS"
print(flip_coin())
def generate_evens():
result = []
for x in range(1,50):
if x % 2 == 0:
result.append(x)
return result |
8d59c011088498bf3945544db053c2fc3adc6a53 | clowdcap/Tree | /tree.py | 4,951 | 3.796875 | 4 | import random
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __str__(self):
return str(self.data)
class BinaryTree:
def __init__(self, data=None, node=None):
if node:
self.root = node
elif data:
node = Node(data)
self.root = node
else:
self.root = None
# Root simboliza raiz da árvore
# Percurso em ordem simetrica ( Travessia_simétrica() )
def simetric_traversal(self, node=None):
if node is None:
node = self.root
if node.left:
print('(', end='')
self.simetric_traversal(node.left)
print(node, end='')
if node.right:
self.simetric_traversal(node.right)
print(')', end='')
def postorder_traversal(self, node=None):
if node is None:
node = self.root
if node.left:
self.postorder_traversal(node.left)
if node.right:
self.postorder_traversal(node.right)
print(node)
def height(self, node=None):
if node is None:
node = self.root
hleft = 0
hright = 0
if node.left:
hleft = self.height(node.left)
if node.right:
hright = self.height(node.right)
if hright > hleft:
return hright + 1
return hleft + 1
def inorder_traversal(self, node=None):
if node is None:
node = self.root
if node.left:
self.inorder_traversal(node.left)
print(node, end=' ')
if node.right:
self.inorder_traversal(node.right)
class BinarySearchTree(BinaryTree):
def insert(self, elemento):
parent = None
x = self.root
while x:
parent = x
if elemento < x.data:
x = x.left
else:
x = x.right
if parent is None:
self.root = Node(elemento)
elif elemento < parent.data:
parent.left = Node(elemento)
else:
parent.right = Node(elemento)
def search(self, elemento):
return self._search(elemento, self.root)
def _search(self, elemento, node):
if node == 0:
node = self.root
if node is None:
return node
if node.data == elemento:
return BinarySearchTree(node)
if elemento < node.data:
return self._search(elemento, node.left)
return self._search(elemento, node.right)
if __name__ == "__main__":
random.seed(40)
elemento = random.sample(range(1, 1000), 38)
bst = BinarySearchTree()
for v in elemento:
bst.insert(v)
bst.inorder_traversal()
items = [30, 33, 55, 61, 117]
for item in items:
r = bst.search(item)
if r is None:
print(item, 'não encontrado')
else:
print(r.root.data, 'encontrado')
random.seed(40)
def random_tree(_size=42):
element = random.sample(range(1, 1000), 42)
tree = BinarySearchTree()
for x in element:
tree.insert(x)
return tree
def example_tree():
element = [61, 89, 66, 43, 51, 16, 55, 11, 79, 77, 82, 32]
tree = BinarySearchTree()
for x in element:
tree.insert(x)
return tree
""" if __name__ == "__main__":
tree = BinaryTree()
n1 = Node('a')
n2 = Node('+')
n3 = Node('*')
n4 = Node('b')
n5 = Node('-')
n6 = Node('/')
n7 = Node('c')
n8 = Node('d')
n9 = Node('e')
n6.left = n7
n6.right = n8
n5.left = n6
n5.right = n9
n3.left = n4
n4.right = n5
n2.left = n1
n2.right = n3
tree.root = n2
tree.simetric_traversal()
print('')
tree = BinaryTree('RAIZ')
tree.root.left = Node('ESQUERDA')
tree.root.right = Node('DIREITA')
print(tree.root)
print(tree.root.left)
print(tree.root.right)
# exemplo 2
if __name__ == "__main__":
tree = postorder_exemple_tree()
print("Percurso em pós ordem:")
tree.postorder_traversal()
print('Altura: ', tree.height())"""
'''
def search(self, elemento, node=0):
if node == 0:
node = self.root
if node is None or node.data == elemento:
return BinarySearchTree(node)
if elemento < node.data:
return self.search(elemento, node.left)
return self.search((elemento, node.right))
def postorder_exemple_tree():
tree = BinaryTree()
n1 = Node('I')
n2 = Node('N')
n3 = Node('S')
n4 = Node('C')
n5 = Node('R')
n6 = Node('E')
n7 = Node('V')
n8 = Node('A')
n9 = Node('5')
n0 = Node('3')
n0.left = n6
n0.right = n9
n6.left = n1
n6.right = n5
n5.left = n2
n5.right = n4
n4.right = n3
n9.left = n8
n8.right = n7
tree.root = n0
return tree'''
|
fa6c59bbc3b132d22f51162f1ca2495b30bf609d | ankur715/GUI | /Tkinter/grid.py | 526 | 3.796875 | 4 | # grid(): It organizes the widgets in a table-like structure.
# Much like a Frame, a grid is another way to organize the widgets. It uses the Matrix row-column concept.
import tkinter
from tkinter import *
top = tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
tkinter.Checkbutton(top, text = "Machine Learning", variable=CheckVar1, onvalue=1, offvalue=0).grid(row=0, sticky=W)
tkinter.Checkbutton(top, text = "Deep Learning", variable=CheckVar2, onvalue=0, offvalue =1).grid(row=1, sticky=W)
top.mainloop()
|
1ac0dd4af8183b0cb8708b55363bb6889b1763a3 | StudiousStone/CNN_Accelerator | /Deep_Learning_from_Scratch/Ch04_Learning_Phase_NN/Numerical_Differentiation/derivative.py | 413 | 3.515625 | 4 | import numpy as np
import matplotlib.pylab as plt
def function_1(x):
return 0.01 * x ** 2 + 0.1 * x
def numerical_diff(f, x):
h = 1e-4 # 0.0001
return (f(x+h) - f(x-h)) / (2 * h)
x = np.arange(0.0, 20.0, 0.1) # array from 0 to 20 with step = 0.1
y = function_1(x)
# plt.xlabel("x")
# plt.ylabel("y")
# plt.plot(x, y)
# plt.show()
print(numerical_diff(function_1, 5))
print(numerical_diff(function_1, 10)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.