text
stringlengths 37
1.41M
|
---|
#Um professor quer sortear um dos seus quatro alunos para apagar o quadro.
#Faça um programa que ajude ele, lendo o onme deles e escrevendo o nome do escolhido.
alunos = []
#['d','a','e','g']
for i in range(4):
alunos.append(input('Inform o nome do {}º aluno(a): '.format(i+1)))
from random import random, randint
escolhido = randint(0,3)
print(escolhido)
print('O escolhido para apagar o quadro é o(a) aluno(a) {}'.format(alunos[escolhido]))
|
#Crie um programa que leia um número inteiro e mostre na tela se ele é PAR OU IMPAR.
numero = int(input('Informe o número inteiro a ser verificado: '))
print('Número é PAR' if numero % 2 == 0 else 'Número é IMPAR' )
|
tempo = int(input('Quanto antos tem o seu carro? '))
if tempo <=3:
print('Carro novo')
else:
print('Carro usado')
print('--FIM--')
print('carro novo' if tempo<=3 else 'carro velho')
#PARTE 2
nome = str(input('Qual é o seu nome? '))
if nome == 'Michael':
print('Que nome lindo você tem!!')
else:
print('Seu nome é tão normal!')
print('Bom dia, {}'.format(nome))
#PARTE 3
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1+n2)/2
print('A sua média foi {:.1f}'.format(m))
if m >= 6.0:
print('Parabéns')
else:
print('ESTUDE MAIS!')
|
#Faça um progrma que leia um âgulo qualquer e
# mostre na tela o valor do seno, cosseno e tangete
# desse ângulo.
from math import cos, sin, tan, radians
angulo = float(input('Informe o ângulo para calcular o seno e cosseno: '))
print('O seno deste ângulo radial é: {:.2f}.'.format(sin(radians(angulo))))
print('O cosseno deste ângulo radial é: {:.2f}.'.format(cos(radians(angulo))))
print('O tangente deste ângulo radial é: {:.2f}.'.format(tan(radians(angulo))))
|
#Faça um programa que mostre na tela uma contagem regressiva
#para o estouro de fogos de artifício, indo de 10 até 0, com uma pausa de 1 segundo entre eles.
import time
for i in range(10,0,-1):
print(i)
time.sleep(1)
print('Xablau, tempo acabou!')
|
#Crie um programa que leia o nome completo de uma pessoa e mostra:
# * O nome com todas as letras maiúsculas.
# * O nome com todas minúsculas
# * Quantas letras ao todo(sem considerar espaços)
nomeCompleto = input('Favor informar o seu nome completo!')
print(nomeCompleto.upper())
print(nomeCompleto.lower())
print(len(nomeCompleto.strip()))
print(len(nomeCompleto) - nomeCompleto.count(' '))
print(nomeCompleto.strip().find(' '))
print(len(nomeCompleto.strip().split()[0]))
|
#!/usr/bin/env python
"""Audit phones (phone numbers)"""
import xml.etree.cElementTree as ET
import re
import pprint
phone_re = re.compile(r'^\+1-[2-9]\d{2}-\d{3}-\d{4}$')
# dictionary for lookup searches
malformed_numbers = {}
wellformed_numbers = set()
duplicate_numbers = set()
did_not_catch = []
# ************************************** audit_phone() ************************************
def audit_phone(phone_number):
"""Checks if phone number follows the pattern +1-###-###-#### (US phone pattern)
Separates phone numbers into Wellformed and Malformed numbers based on standard
US pattern including country code. Identifies duplicate numbers found.
Prints summary of information and the malformed dictionary of numbers and returns
malformed dictionary which can then be run through the phone_partial_clean function
in helper_functions for partial cleaning.
"""
wellformed = phone_re.search(phone_number)
if phone_number in malformed_numbers.keys() or phone_number in wellformed_numbers:
duplicate_numbers.add(phone_number)
elif wellformed:
explore_phone_number = wellformed.group()
wellformed_numbers.add(explore_phone_number)
elif phone_number:
malformed_numbers[phone_number] = 'fix_number'
else:
did_not_catch.append(phone_number)
# ************************************** print_audit_phone_results() ************************************
def print_audit_phone_results(print_list):
""" Print results of phone audit. """
if isinstance(print_list, str) and print_list.lower() == 'all':
print_type_list = ['malformed', 'duplicate', 'wellformed']
elif isinstance(print_list, list):
print_type_list = print_list.copy()
elif isinstance(print_list, str):
print_type_list.append(print_list)
if did_not_catch:
print('\n*** Did not check these numbers. ***\n')
pprint.pprint(did_not_catch)
else:
print("\nAll phone numbers were checked.\n")
print("There are {} malformed numbers, {} duplicate numbers and {} wellformed numbers.\n"
.format(len(malformed_numbers), len(duplicate_numbers), len(wellformed_numbers)))
for item in print_type_list:
if 'malformed' == item:
print("The malformed numbers found are: \n")
pprint.pprint(malformed_numbers)
elif 'duplicate' == item:
print('\nThe {} duplicated items are: \n'.format(len(duplicate_numbers)))
print(duplicate_numbers)
elif 'wellformed' == item:
print('\nWellformed has {} items: \n'.format(len(wellformed_numbers)))
pprint.pprint(wellformed_numbers)
else:
print('Pass "malformed", "wellformed", "duplicate" or "All" as paramaters to print dictionary of numbers.')
# ************************************** audit_phones() ************************************
def audit_phones(OSM_FILE = "data\\round_rock.xml",
print_number_type = ['malformed', 'duplicate']):
""" Audit phone and confirm they follow US phone structure of +1-###-###-####."""
# clear persistent data
malformed_numbers.clear()
wellformed_numbers.clear()
duplicate_numbers.clear()
did_not_catch.clear()
# osm_file = open(OSM_FILE, "r")
with open(OSM_FILE, "r", encoding="UTF-8") as osm_file:
for event, elem in ET.iterparse(osm_file, events=("start",)):
if elem.tag == "node" or elem.tag == "way":
for tag in elem.iter("tag"):
if tag.attrib['k'] == 'phone':
audit_phone(tag.attrib['v'])
osm_file.close()
print_audit_phone_results(print_number_type)
print('\n Note: The returned malformed number dictionary can be run through \n' \
'\tmodules.helper_functions phone_partial_clean(phone_dict) \n' \
'\tfunction to partially clean the numbers given in the key.\n')
return malformed_numbers
if __name__ == "__main__":
audit_phones(OSM_FILE = "data\\round_rock_sample.xml")
|
import random
# Letters, numbers and symbols that password can contain
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
# User selects how many letters, numbers or symbols they need
print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
total_num = nr_letters + nr_symbols + nr_numbers
letter_counter = 0
symbol_counter = 0
number_counter = 0
passList = [""] * total_num # creating an empty list with total number of elements required
general_counter = 0
while True:
random_pos = random.randint(0, total_num-1) # selects random position in list
if passList[random_pos] == "": # if that random position is empty
if letter_counter < nr_letters: # if the letter counter is less than the number of letters that the user wants then fill it with a random letter
random_letter = letters[random.randint(0, len(letters)-1)]
passList[random_pos] = random_letter
letter_counter += 1
general_counter += 1
elif number_counter < nr_numbers:
random_number = numbers[random.randint(0, len(numbers)-1)]
passList[random_pos] = random_number
number_counter += 1
general_counter += 1
elif symbol_counter < nr_symbols:
random_symbol = symbols[random.randint(0, len(symbols)-1)]
passList[random_pos] = random_symbol
symbol_counter += 1
general_counter += 1
elif general_counter == total_num: # if all the positions in the list is filled then break out of this while loop
break
password_string = "".join(passList)
print(password_string)
|
import random, time
def mergeSort(arr):
print("Splitting ", arr)
if len(arr) > 1:
mid = len(arr) // 2
lefthalf = arr[:mid]
righthalf = arr[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
arr[k] = lefthalf[i]
i = i + 1
else:
arr[k] = righthalf[j]
j = j +1
k = k + 1
while i < len(lefthalf):
arr[k] = lefthalf[i]
i = i + 1
k = k + 1
print("Merging ", arr)
def merge(left, right):
if not len(left) or not len(right):
return left or right
result = []
i, j = 0, 0
while (len(result) < len(left) + len(right)):
if left[i] < right[j]:
result.append(left[i])
i+= 1
else:
result.append(right[j])
j+= 1
if i == len(left) or j == len(right):
result.extend(left[i:] or right[j:])
break
#print("Done merging: ", result[:3])
return result
def mergesort(arr):
if len(arr) < 2:
return arr
middle = len(arr)//2
left = mergesort(arr[:middle])
right = mergesort(arr[middle:])
print("Going to merge: ", merge(left, right))
return merge(left, right)
def testStation(arr):
timeStamps = []
timeStamp = time.clock()
mergesort(arr)
timeStamp = time.clock() - timeStamp
timeStamps.append(timeStamp)
print("Done! It took: ", timeStamps)
def main():
arr = []
left = []
right = []
for i in range(0,10):
arr.append(i)
random.shuffle(arr)
testStation(arr)
#print(arr)
#mergesort(arr)
#print("Done")
main()
|
# Module 2 - Practice / letter to Number Function
def let_to_num() :
phone_letters = [' ',"","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"]
letter = input("Enter a single letter, space, or empty string: ")
key = 0
while key < 10 :
if letter == "" :
return 1
break
elif letter.lower() in phone_letters[key].lower() :
return key
else :
key += 1
return("Not found")
print(let_to_num())
# Module 2 - Practice / reverse
some_numbers = [1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77]
new_string = []
while len(some_numbers) != 0 :
pop_num = some_numbers.pop(0)
new_string.insert(0,pop_num)
print(new_string)
# Module 2 - End of Assignment
set_list = ["fish", "trees", "books", "movies", "songs"]
while len(set_list) != 0 :
string = input("Enter a string or \"quit\" if you wanna quit: ")
if string.lower() == "quit" :
break
else :
def list_o_matic() :
if string == "" :
set_list.pop()
print("pop msg")
elif string in set_list :
set_list.remove(string)
print("remove msg")
else :
set_list.append(string)
print("append msg")
list_o_matic()
|
class listNode:
def __init__(self,x):
self.val = x
self.next = None
def createList(self,a):
if a is None:
print 'no elements'
return
head=listNode(a[0])
p=head
i=1
n=len(a)
while i<n:
t=listNode(a[i])
p.next=t
p=t
i=i+1
return head
def scanList(self,head):
if head is None:
print "no elements"
return
print head.val
while head.next:
p=head.next
print p.val
head=p
def sortList(self, head):
if head is None or head.next is None:
return head
mid = (head.val + head.next.val) / 2
if head.val > head.next.val:
lhead, rhead = head.next, head
else:
lhead, rhead = head, head.next
lit, rit = lhead, rhead
it = head.next.next
while it is not None:
if it.val > mid:
rit.next = it
rit = it
else:
lit.next = it
lit = it
it = it.next
lit.next, rit.next = None, None
lhead = self.sortList(lhead)
rhead = self.sortList(rhead)
it = lhead
while it.next is not None:
it = it.next
it.next = rhead
return lhead
if __name__ == '__main__':
l=listNode(0)
a=[2,5,9,3,6,1,0,7,4,19]
head=l.createList(a)
import pdb;pdb.set_trace()
print 'old list:'
l.scanList(head)
newhead=l.sortList(head)
print 'sorted list:'
l.scanList(newhead)
|
#coding:utf-8
def half_search(lst,value,low,high):
if high < low:
return None
mid = (low + high)/2
if lst[mid] > value:
return half_search(lst, value, low, mid-1)
elif lst[mid] < value:
return half_search(lst, value, mid+1, high)
else:
return mid
def binary_search_loop(lst,value):
low, high = 0, len(lst)-1
while low <= high:
mid = (low + high) / 2
if lst[mid] < value:
low = mid + 1
elif lst[mid] > value:
high = mid - 1
else:
return mid
return None
if __name__ == '__main__':
N = [1,2,3,4,8,9,10]
val = half_search(N,8,0,len(N))
print val
|
import math
from tempfile import NamedTemporaryFile
from openpyxl import Workbook, load_workbook
wb = Workbook()
ws = wb.active
ws1 = wb.create_sheet('MySheet') # insert at the end (default)
ws2 = wb.create_sheet('MySheet1', 0) # insert at first position
ws3 = wb.create_sheet('MySheet2', -1) # insert at the penultimate position
ws.title = 'New Title'
ws.sheet_properties.tabColor = '1072BA'
ws3 = wb['New Title']
# print(wb.sheetnames)
# for sheet in wb:
# print(sheet.title)
source = wb.active
target = wb.copy_worksheet(source)
"""
Accessing one cell
Now we know how to get a worksheet,
we can start modifying cells content.
Cells can be accessed directly as keys of the worksheet:
"""
ws['A4'] = 4
c = ws['A4']
# c.value = 'hello, world'
d = ws.cell(row=4, column=2, value=10)
# print(c)
# print(c.value)
# print(d)
# print(d.value)
for x in range(1, 101):
for y in range(1, 101):
ws.cell(row=x, column=y)
cell_range = ws['A1':'C2'] # 切片
# print(cell_range) # 二维元组:先行再列
colC = ws['C'] # 共计1列、100行
# print(colC) # 一维元组
col_range = ws['C:D'] # 共计2列、100行
# print(col_range) # 先列再行
row10 = ws[10]
# print(row10)
row_range = ws[5:10] # 先行再列
# print(row_range)
'''先行后列'''
for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
for cell in row:
print(cell)
print()
'''先列后行'''
for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
for cell in col:
print(cell)
print()
# print(tuple(ws.rows))
# print(tuple(ws.columns))
"""
Values only
If you just want the values from a worksheet you can use the Worksheet.values property.
This iterates over all the rows in a worksheet but returns just the cell values:
"""
# for row in ws.values:
# for value in row:
# print(value)
"""
Both Worksheet.iter_rows() and Worksheet.iter_cols() can take the values_only parameter to return just the cell’s value:
"""
for row in ws.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True):
print(row)
"""
Data storage
Once we have a Cell, we can assign it a value:
"""
c.value = 'hello, world'
print(c)
print(c.value)
d.value = math.pi
print(d)
print(d.value)
"""
Saving to a file
The simplest and safest way to save a workbook is by using the Workbook.save() method of the Workbook object:
"""
# wb.save('balances.xlsx') # This operation will overwrite existing files without warning.
with NamedTemporaryFile(delete=False) as tmp:
wb.save(tmp.name)
tmp.seek(0)
stream = tmp.read() # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file
tmp.close()
wb1 = load_workbook('document.xlsx')
wb1.template = True
wb1.save('document_template.xltx')
wb2 = load_workbook('document_template.xltx')
wb2.template = False
wb2.save('document2.xlsx')
wb3 = load_workbook('balances.xlsx')
print(wb3.sheetnames)
|
def change(i, s):
l = list(t)
l[i] = s
return tuple(l)
def main():
# tuple的陷阱:当你定义一个tuple时,在定义的时候,tuple的元素就必须被确定下来
# t = ('骆昊', 38, True, '四川成都')
print('元组: ', t)
print(t[::-1])
for member in t:
print(member, end=' ')
print()
tuple1 = ('王大锤', 20, True, '云南昆明')
print(tuple1)
list1 = list(tuple1)
print(list1)
# tuple1[0] = '张三' # TypeError: 'tuple' object does not support item assignment
list1[0] = '张三'
print(list1)
print(tuple(list1))
tuple2 = () * 10
print(tuple2)
t2 = change(-1, '广东佛山')
print(t2)
if __name__ == '__main__':
t = ('骆昊', 38, True, '四川成都')
main()
|
import sys
def main():
f = [x for x in range(1, 10)] # 数列初始化
print(f)
f = [x + y for x in 'ABCDE' for y in '123']
print(f)
f = [x ** 2 for x in range(1, 100)]
print(sys.getsizeof(f))
print(f)
for val in f:
print(val, end=' ')
if __name__ == '__main__':
main()
|
'''
Created on 2019年8月28日
打印各种三角形图案
*
**
***
****
*****
*
**
***
****
*****
*
***
*****
*******
*********
@author: jinshuang1
'''
row = int(input('请输入行数:'))
for i in range(row):
for j in range(i + 1):
print('*', end='') # 给end赋值为空,就不会换行
print()
for i in range(row):
for j in range(row - 1 - i):
print(' ', end='')
for j in range(i + 1):
print('*', end='')
print()
for i in range(row):
for j in range(row - 1 - i):
print(' ', end='')
for j in range(2 * i + 1):
print('*', end='')
print()
|
'''
Provides several utility functions for extracting data from websites (including HTML pages as well as JSON files from APIs).
'''
from contextlib import closing
from bs4 import BeautifulSoup
from requests import get
from requests.exceptions import RequestException
__author__ = "Finn Frankis"
__copyright__ = "Copyright 2019, Crypticko"
# Extracts the content located at any URL.
def getPageContent(url):
try:
with closing(get(url, stream = True)) as page:
return page.content.decode("utf-8")
except RequestException as e:
print(e)
return
# Parses a string representing HTML, returning the parsed result for convenient iteration.
def parseHTML(url):
return BeautifulSoup(getPageContent(url), 'html.parser')
def get_cnn_text(url):
'''
' Retrieves the body of a given CNN article, excluding the headline and any advertisements.
'
' url (string): the URL where the specific article is located
'''
htmlParser = parseHTML(url)
text = ''
for element in htmlParser.select('div'):
if element.has_attr('class') and 'zn-body__paragraph' in element['class']:
text += element.text
text = text.replace('"', ' ')
return text
def get_coin_desk_text(url):
'''
' Retrieves the body of a given CoinDesk article.
'
' url (string): the URL where the specific article is located
'''
parser = parseHTML(url)
text = ""
for element in parser.findAll("div", {"class": "article-pharagraph"}):
text += element.text
return text
def get_business_insider_text(url):
'''
' Retrieves the body of a given Business Insider article.
'
' url (string): the URL where the specific article is located
'''
parser = parseHTML(url)
text = ""
paragraphs = parser.findAll("p", {"class": ""})
for element in paragraphs:
if element.img == None:
text += element.text
return text.replace("\n", "").replace("\xa0", " ")
|
def parzyste(wyraz):
for index in range(0,len(wyraz),2):
yield wyraz[index]
prz=parzyste("Zadanie")
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
|
import unittest
from Calculator import Calculator as calc
class TestCalc(unittest.TestCase):
def test_add(self):
self.assertEqual(calc.add(1, 5), 6)
self.assertEqual(calc.add(-1, 2), 1)
self.assertEqual(calc.add(-1, -3), -4)
def test_subtract(self):
self.assertEqual(calc.subtract(10, 2), 8)
self.assertEqual(calc.subtract(-1, 3), -4)
self.assertEqual(calc.subtract(-1, -1), 0)
def test_multiply(self):
self.assertEqual(calc.multiply(10, 3), 30)
self.assertEqual(calc.multiply(-1, 2), -2)
self.assertEqual(calc.multiply(-1, -2), 2)
def test_divide(self):
self.assertEqual(calc.divide(10, 5), 2)
self.assertEqual(calc.divide(-1, 1), -1)
self.assertEqual(calc.divide(-1, -1), 1)
self.assertEqual(calc.divide(5, 2), 2.5)
if __name__ == '__main__':
unittest.main()
|
import numpy as np
from sklearn.linear_model import LinearRegression
def rss(y_true,y_pred):
"""
A utility function that returns residual sum of squares
"""
return np.sum((y_true-y_pred)**2)
num_splits = 5
"""
Store all errors and coefficients in arrays and find optimum after all iterations
"""
err = []
coeffs = []
# Loop for different splits
for i in range(1,num_splits+1):
# Read in each split and assign as features and labels
train = np.genfromtxt("../Dataset/CandC-train"+str(i)+".csv",delimiter=",")
test = np.genfromtxt("../Dataset/CandC-test"+str(i)+".csv",delimiter=",")
x_train,y_train = train[:,:-1],train[:,-1]
x_test,y_test = test[:,:-1],test[:,-1]
# A linear regression model is initialised and fit on the training data
regressor = LinearRegression()
regressor.fit(x_train,y_train)
# A prediction is made on the test dataset based on the model fitted on train set
y_pred = regressor.predict(x_test)
# Append coefficients and error values
coeffs.append(regressor.coef_)
err.append(rss(y_test,y_pred))
print 'Average Residual Error:',np.mean(err)
# Choose the split with lowest residual sum of squares
best_fit_index = np.argmin(err)
# save coefficients as .csv
np.savetxt('coeffs.csv',coeffs[best_fit_index],delimiter=',')
|
"""
A program to visualise feature extraction by PCA and its decision boundary
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # For 3-D plot of dataset
from matplotlib.axes import Axes
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.linear_model import LinearRegression
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
# Threshold for classification
threshold = 1.5
# Directory where dataset is stored
dataset_directory = '../Dataset/'
colours=['r','b']
markers = ['o','x']
# Name of test and train files
train_files =['train','train_labels']
test_files =['test','test_labels']
def read_data(filename):
"""
An utility function that takes as argument the file name and returns dataset as
an array
"""
return np.genfromtxt(dataset_directory+filename+'.csv',delimiter=',')
def lda_transform(x,y):
"""
A function that transforms a dataset into 1 dimension using LDA given
features and labels
"""
lda = LDA(n_components=1)
return lda.fit_transform(x,y)
# Reading dataset
x_train,y_train = [read_data(filename) for filename in train_files]
x_test,y_test = [read_data(filename) for filename in test_files]
# Call function that transforms test,train features into 1D by LDA
x_train1 = lda_transform(x_train,y_train)
x_test1 = lda_transform(x_test,y_test)
# Plotting the data in DS3 as such
fig = plt.figure('Original Data')
ax = fig.add_subplot(111, projection='3d')
ax.set_title('DS3')
for c, m, label in zip(colours,markers,np.unique(y_train)):
x = x_train[y_train==label]
xs = x[:,0]
ys = x[:,1]
zs = x[:,2]
ax.scatter(xs, ys, zs,zdir='z',c=c, marker=m)
ax.legend(['Class 1','Class 2'],loc='upper left')
plt.show()
#Initialising linear regressor
regressor = LinearRegression(fit_intercept=True)
# Fit regressor on train data
regressor.fit(x_train1,y_train)
# Predict values on test data
y_pred = regressor.predict(x_test1)
# Make a prediction based on a certain threshold
y_pred[y_pred>=threshold]=2
y_pred[y_pred<threshold]=1
# Reporting the various performance metrics
print classification_report(y_test,y_pred)
print "Accuracy",accuracy_score(y_test,y_pred)
# Get the coefficients and intercept of the linear regressor
beta0 = regressor.intercept_
beta1 = regressor.coef_
"""
Plot the extracted data
"""
plt.figure('Transformed Data')
plt.title('LDA transformed DS3')
# Creating uniform variables between max and min values
x_min, x_max = x_train1.min() - 1, x_train1.max() + 1
xx = np.linspace(x_min, x_max, 50)
y_min, y_max = y_pred.min() - 0.2, y_pred.max() + 0.2
yy = np.linspace(y_min, y_max, 50)
# Setting the plot size based on min and max in each direction
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
for c, m, label in zip(colours,markers,np.unique(y_train)):
xs = x_train1[y_train==label]
ys = y_train[y_train==label]
plt.scatter(xs,ys,c=c,marker=m)
plt.xlabel('Projected dimension values')
plt.ylabel('Y label')
# Find the line fitted
y_boundary = beta0 + beta1*xx
# Getting the decision boundary based on threshold and line found
decision_x = (threshold - beta0)/beta1
# line1,=plt.plot(xx,y_boundary,'k-',lw=1)
decision_bound,=plt.plot([decision_x]*len(yy),yy,'g-',lw=3)
plt.legend(['Decision boundary','Class 1','Class 2'])
plt.show()
|
import numpy as np
np.random.seed(7)# To ensure repeatability
"""
The number of features and the number of examples per class
"""
num_features = 20
num_examples = 2000
# The centroid of the first class is generated randomly.
mean1 = np.random.rand(num_features)
"""
Since second centroid must be close to first one
we create a small vector in random different and add it to first centroid
"""
u = np.random.rand(num_features)
u = u / np.linalg.norm(u) # Normalising the random vector to get a unit vector
epsilon = 2
mean2 = mean1 + epsilon*u
"""
A random matrix is generated and multiplied by it's transponse
to obtain a positive semi-definite and symmetric covariance matrix
"""
rand_matrix = np.random.rand(num_features,num_features)
cov = np.matmul(rand_matrix,rand_matrix.T)
"""
Two classes are generated from multivariate Gaussian distribution
"""
x1 = np.random.multivariate_normal(mean1, cov, num_examples)
x2 = np.random.multivariate_normal(mean2, cov, num_examples)
# Each class is assigned a label and the label is appended to data
label_1 = np.zeros((num_examples,1),dtype=np.int)
label_2 = np.ones((num_examples,1),dtype=np.int)
x1 = np.hstack((x1,label_1))
x2 = np.hstack((x2,label_2))
"""
Two classes data is shuffled and 70% of each class is put into
the training set and remaining is put into test set
"""
np.random.shuffle(x1)
np.random.shuffle(x2)
x1_train = x1[:int(x1.shape[0]*0.7)]
x2_train = x2[:int(x2.shape[0]*0.7)]
train = np.vstack((x1_train,x2_train))
x1_test = x1[int(x1.shape[0]*0.7):]
x2_test = x2[int(x2.shape[0]*0.7):]
test = np.vstack((x1_test,x2_test))
# Both train and tests sets are saved to Dataset folder
np.savetxt("../Dataset/DS1-train.csv", train, delimiter=",")
np.savetxt("../Dataset/DS1-test.csv", test, delimiter=",")
print 'Dataset Generated'
|
import random
while True:
### Prompts user for attack modifier then simulates d20 roll
while True:
try:
attack_modifer = int(input("What is your Attack Modifier? "))
break
except ValueError:
print("That is not a valid modifier")
base = random.randint(1, 20)
result = base + int(attack_modifer)
### Automatically assumes a miss and continues the program
if base == 1:
print("Oh no!! You critically missed!!")
#### Automatically assumes a hit and calcutes double damage
elif base == 20:
print("Awesome!! A critical hit!!")
total_damage = 0
i = 0
while True:
try:
dice_size = int(input("What number-sided dice does your attack use? "))
break
except ValueError:
print("That is not a valid modifier")
while True:
try:
number_of_dice = int(input("How many damage dice does your attack use? "))
break
except ValueError:
print("That is not a valid modifier")
while True:
try:
damage_modifier = int(input("Do you have a damage modifier (Enter 0 if no modifier)? "))
break
except ValueError:
print("That is not a valid modifier")
crit_dice = number_of_dice * 2
while i < crit_dice:
single_dice = random.randint(1, dice_size)
total_damage += single_dice
i += 1
total_damage += damage_modifier
print("You did " + str(total_damage) + " points of damage!!")
### Checks to see if user hits then proceeds to damage roll simulation
else:
print(str(base) + " + " + str(int(attack_modifer)))
print("You hit an Armor Class of " + str(result))
while True:
hit_prompt = input("Did you hit? (Y or N): ")
if hit_prompt.upper() == 'N' or hit_prompt.upper() == "Y":
break
else:
print("Invalid response.")
if hit_prompt.upper() == "Y":
total_damage = 0
i = 0
while True:
try:
dice_size = int(input("What number-sided dice does your attack use? "))
break
except ValueError:
print("That is not a valid modifier")
while True:
try:
number_of_dice = int(input("How many damage dice does your attack use? "))
break
except ValueError:
print("That is not a valid modifier")
while True:
try:
damage_modifier = int(input("Do you have a damage modifier (Enter 0 if no modifier)? "))
break
except ValueError:
print("That is not a valid modifier")
while i < number_of_dice:
single_dice = random.randint(1, dice_size)
total_damage += single_dice
i += 1
total_damage += damage_modifier
print("You did " + str(total_damage) + " points of damage!!")
### This section allows you to attack again and check for valid responses
while True:
attack = input("Can you attack again? (Y or N): ")
if attack.upper() == 'N' or attack.upper() == "Y":
break
else:
print("Invalid response.")
if attack.upper() == "N":
break
else:
continue
print("Your attack is done!!")
|
import random
# TODO:
# "Scissors cuts paper, paper covers rock, rock crushes lizard, lizard poisons Spock, Spock smashes scissors,
# scissors decapitates lizard, lizard eats paper, paper disproves Spock, Spock vaporizes rock,
# and as it always has, rock crushes scissors."
while True:
print("Make your choice")
choice = str(input())
choice = choice.lower()
print("Your Choice is: ", choice)
choices = ['rock', 'paper', 'scissors']
computer_choice = random.choice(choices)
print("Computer's Choice is: ", computer_choice)
if choice in choices:
if choice == computer_choice:
print("It's a Tie!")
if choice == 'rock':
if computer_choice == 'paper':
print('you lose, sorry :(')
elif computer_choice == 'scissors':
print('You win!!!!! congrats :)')
if choice == 'paper':
if computer_choice == 'scissors':
print('you lose, sorry :(')
elif computer_choice == 'rock':
print('You win!!!!! congrats :)')
if choice == 'scissors':
if computer_choice == 'rock':
print('you lose, sorry :(')
elif computer_choice == 'paper':
print('You win!!!!! congrats :)')
else:
print('invalid choice, try again')
print()
|
#-*-coding:utf-8-*-
# 6.py说明 将新增的TXT文件删除
import os
def del_files(path):
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith(".txt"):
os.remove(os.path.join(root, name))
print("Delete File: " + os.path.join(root, name))
# test
if __name__ == "__main__":
path = "./knn-digits/newDigits"
del_files(path)
|
import matplotlib.pyplot as plt
import numpy as np
x = [0,20,50,75,100,150,200,250,300,350,400,450,500]
y1=[0,0.56, 0.72, 0.81,0.9,0.94,0.93,0.92,0.95,0.96,0.96,0.96,0.96]
y2=[0,0.26, 0.36,0.58,0.65,0.73,0.82,0.86,0.84,0.85,0.87,0.88,0.88]
nnet_100_line = plt.plot(x, y1, label='MCTS with NNet')
mcts_100_line = plt.plot(x, y2,label='MCTS without NNet')
plt.xlabel('MCTS iterations')
plt.ylabel('Percent 100 Games within 1.1 of Optimal')
plt.legend()
plt.title(" Plotting the % within 1.1 of optimal versus MCTS Iterations")
plt.show()
|
is_asian = True
is_american = False
name = input()
age = int(input())
kids = int(input())
print(name)
if name == "Nurtazim":
print("Asian")
else:
print("American")
if age > 18:
print("Mojno voity")
else:
print("Nelzya")
if kids < 2:
print("Mojno s detmi")
else:
print("Nelzya")
if False:
print("True working!")
else:
print("Not Working")
|
age = int(input())
currency = str(float(int(input())))
print(type(age))
print(type(currency))
print(age + 90 + 12341)
print(currency)
|
print("Hello, World!")
# print(input("Введите текст: "))
def ab():
a = int(input())
b = int(input())
print(a + b)
def a_mul_b():
a = int(input())
b = int(input())
print(a * b)
def a_div_b():
a = int(input())
b = int(input())
while b == 0:
print("нельзя делить на 0")
b = int(input())
print("Результат деления равен", a / b)
a_div_b()
a_div_b()
|
#!/usr/bin/python3
import json
MSG_WELCOME = "Welcome to the birthday dictionary. We know the birthdays of:"
MSG_WHOSBDAY = "\nWho's birthday do you want to look up?\n"
MSG_NO_RES = "\nNo such name in the dictionary!"
MSG_RES = "\n{}'s birthday is {}."
MSG_SAVE = "New name and birthday saved!"
FILE = "birthday_dictionary.json"
def read_dictionary(file_name):
with open(file_name, "r") as f:
birthday_dictionary = json.load(f)
return birthday_dictionary
def print_names(dictionary):
for name in dictionary.keys():
print(" - " + str(name))
def get_date(name, dictionary):
try:
return dictionary[name]
except KeyError:
print(MSG_NO_RES)
def new_user():
while True:
new_user_yn = input("\nWould you like to add a new name and birthday? [y/n]: ")
if new_user_yn == "y":
name = input("Name: ")
birthday = input("Birthday: ")
return [name, birthday]
elif new_user_yn == "n":
break
def add_element_to_dictionary(dictionary, name, birthday):
updated_dictionary = dictionary
updated_dictionary[name] = birthday
return updated_dictionary
def save_dictionary_to_file(file_name, dictionary):
with open(file_name, "w") as f:
json.dump(dictionary, f)
print(MSG_SAVE)
def save_new_user(dictionary):
new_user_name_and_birthday = new_user()
if new_user_name_and_birthday:
new_name = new_user_name_and_birthday[0]
new_birthday = new_user_name_and_birthday[1]
dictionary = add_element_to_dictionary(dictionary, new_name, new_birthday)
save_dictionary_to_file(FILE, dictionary)
def query_handler(dictionary):
print(MSG_WELCOME)
print_names(dictionary)
name = input(MSG_WHOSBDAY)
date = get_date(name, dictionary)
if date:
print(MSG_RES.format(name, date))
dictionary = read_dictionary(FILE)
query_handler(dictionary)
save_new_user(dictionary)
|
#!/usr/bin/python3
MAX_X = 3
MAX_Y = 3
ERROR_MSG_NO_COMMA = "ERROR: There is no , in the input!"
ERROR_MSG_ONLY_XY = "ERROR: Only X and Y coordinates are needed!"
ERROR_MSG_NUMERIC = "ERROR: Inputs should be numeric!"
ERROR_MSG_X_BETWEEN = "ERROR: X should be between 1 and "
ERROR_MSG_Y_BETWEEN = "ERROR: Y should be between 1 and "
INPUT_MSG = "Please enter X and Y coordinates - [x,y]: "
def input_checker(input_string, range_x, range_y):
error_flag = True
is_numeric_flag = True
if "," not in input_string:
print(ERROR_MSG_NO_COMMA)
error_flag = False
splitted_input = input_string.split(",")
if len(splitted_input) > 2:
print(ERROR_MSG_ONLY_XY)
error_flag = False
if (splitted_input[0].isnumeric() == False) or (splitted_input[1].isnumeric() == False):
print(ERROR_MSG_NUMERIC)
is_numeric_flag = False
error_flag = False
if is_numeric_flag == False or range_x < int(splitted_input[0]) or int(splitted_input[0]) < 1:
print(ERROR_MSG_X_BETWEEN + str(range_x))
error_flag = False
if is_numeric_flag == False or range_y < int(splitted_input[1]) or int(splitted_input[1]) < 1:
print(ERROR_MSG_Y_BETWEEN + str(range_y))
error_flag = False
if error_flag == False:
return False
else:
return splitted_input
def input_handler():
value = str(input(INPUT_MSG))
result = input_checker(value, MAX_X, MAX_Y)
if result != False:
numeric_result = [int(result[0]), int(result[1])]
return numeric_result
return False
def update_game(game, player, x, y):
new_game = game
new_game[x-1][y-1] = player
return new_game
game = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
print(game)
x_y_input = input_handler()
if x_y_input != False:
game = update_game(game, 1, x_y_input[0], x_y_input[1])
print(game)
|
#!/usr/bin/python3
def save_to_file(filename, content):
open_file = open(filename, 'w')
open_file.write(content)
open_file.close()
def get_input(message):
input_message = str(input(message))
return input_message
filename = get_input("Enter the filename: ")
content = get_input("Enter the content: ")
save_to_file(filename, content)
|
# !/usr/bin/python3
class Animal:
numberOfAnimals = 0
def __init__(self, name):
Animal.numberOfAnimals += 1
print("Animal {} created.".format(Animal.numberOfAnimals))
self.name = name
def getInfo(self):
print("{} is the name of the animal.".format(self.name))
class Mammal(Animal):
def __init__(self, name, numberOfLegs = 4):
super().__init__(name)
self.numberOfLegs = numberOfLegs
def getInfo(self):
print("{} has {} legs.".format(self.name, self.numberOfLegs))
class Bird(Animal):
def __init__(self, name, numberOfLegs = 2, numberOfWings = 2):
super().__init__(name)
self.numberOfLegs = numberOfLegs
self.numberOfWings = numberOfWings
def getInfo(self):
print("{} has {} legs and {} wings.".format(self.name, self.numberOfLegs, self.numberOfWings))
animal = Animal("Generopida")
dog = Mammal("Rex")
whale = Mammal("Mr. Whale", 0)
blackbird = Bird("Blacky")
animal.getInfo()
dog.getInfo()
whale.getInfo()
blackbird.getInfo()
|
#!/usr/bin/python3
from random import randint
def user_input():
player_1_name = str(input("Player 1: "))
player_2_name = str(input("Player 2: "))
players = [player_1_name,player_2_name]
return players
def num_to_value(num):
if(num == 0):
return "rock"
elif(num == 1):
return "paper"
else:
return "scissors"
def game(players):
player_1_result = randint(0,2)
player_2_result = randint(0,2)
while player_1_result == player_2_result:
player_1_result = randint(0,2)
player_2_result = randint(0,2)
#0=rock, 1=paper, 2=scissors
if((player_1_result == 0 and player_2_result == 2)
or (player_1_result == 2 and player_2_result == 1)
or (player_1_result == 1 and player_2_result == 0)):
print("\nThe winner is " + players[0] + " (" + str(num_to_value(player_1_result)) + " beats " + str(num_to_value(player_2_result)) + ")")
else:
print("\nThe winner is " + players[1] + " (" + str(num_to_value(player_1_result)) + " beats " + str(num_to_value(player_2_result)) + ")")
def game_loop():
players = user_input()
game(players)
while True:
user_command = str(input("Would you like to play again [y/n]: "))
if user_command == "y":
game(players)
elif user_command == "n":
break
else:
continue
game_loop()
|
"""
搭建一个最简单的网络,只有输入层和输出层
输入数据的维度是 28*28 = 784
输出数据的维度是 10个特征
激活函数使用softmax
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
# one_hot 表示的是一个长度为n的数组,只有一个元素是1.0,其他元素都是0.0
# 比如在n=4的情况下,标记2对用的one_hot 的标记是 [0.0 , 0.0 , 1.0 ,0.0]
# 使用 one_hot 的直接原因是,我们使用 0~9 个类别的多分类的输出层是 softmax 层
# softmax 它的输 出是一个概率分布,从而要求输入的标记也以概率分布的形式出现,进而可以计算交叉熵
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def add_layer(inputs, in_size, out_size, activation_function=None,):
# add one more layer and return the output of this layer
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1,)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b,)
return outputs
def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs})
# tf.argmax (y_pre,1 ) 返回每一行 下标最大的元素,1表示按行
correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
return result
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784]) # 28x28
ys = tf.placeholder(tf.float32, [None, 10])
# add output layer
prediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)
# loss函数(即最优化目标函数)选用交叉熵函数
# 交叉熵用来衡量预测值和真实值的相似程度,如果完全相同,它们的交叉熵等于零。
# prediction 表示预测值 ,ys表示真实的输出
#### 感觉这样写 ,也应该可以 : cross_entroy = tf.reduce_mean( tf.nn.softmax_cross_entroy_with_logits(ys,prediction))
#### 用tf.nn.softmax_cross_entropy_with_logits 来计算预测值y与真实值y_的差值,并取均值
cross_entropy = tf.reduce_mean(-tf.reduce_sum( ys * tf.log(prediction),reduction_indices=[1])) # loss
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.Session()
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100) #每次只取100张图片,免得数据太多训练太慢。#在每次循环中我们都随机抓取训练数据中 100 个数据点
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
if i % 50 == 0:
# 注意,这里改成了测试集
print(compute_accuracy(mnist.test.images, mnist.test.labels))
"""
输出:
0.0841
0.6386
0.7359
0.7792
0.7999
0.8145
0.8312
0.8395
0.8491
0.8509
0.8584
0.8645
0.8653
0.865
0.868
0.8671
0.8738
0.8716
0.8793
0.879
"""
|
# 这个是sklearn带的一个手写字符集合
# 可以熟悉一下这个数据集合,然后使用pca + kmeans 对这个数据进行一个处理
from sklearn import datasets
from matplotlib import pyplot as plt
from sklearn import decomposition
from sklearn.cluster import KMeans
import numpy as np
digits_data = datasets.load_digits()
for index,image in enumerate(digits_data.images[:5]):
plt.subplot(2,5,index+1)
plt.imshow(image)
plt.show()
|
#Projeto Sistemas Operacionais 2018.2
#Fabio e Raissa
#Gerenciamento de Memória
#Imports
from random import shuffle
#Define Functions
# exemplo de entrada print(calculadora("12+34-+"))
def calculadora(equacao):
stack = []
a = b = 0
for c in equacao:
if c == '-':
if len(stack) != 0:
b = stack.pop()
a = stack.pop()
stack.append(a-b)
elif c == '+':
if len(stack) != 0:
b = stack.pop()
a = stack.pop()
stack.append(a+b)
elif c == '*':
if len(stack) != 0:
b = stack.pop()
a = stack.pop()
stack.append(a*b)
elif c == '/':
if len(stack) != 0:
b = stack.pop()
a = stack.pop()
if b != 0:
stack.append(a/b)
elif c == '^':
if len(stack) != 0:
b = stack.pop()
a = stack.pop()
if b != 0:
stack.append(a**b)
else:
stack.append(ord(c)-48)
return stack.pop()
#---------Open FIle-----------
"""
Abre o Arquivo txt onde estão os processos (Equações)
Retorna uma Lista de Processos aleatórizada
"""
memory = []
index = []
lista_processo = []
#size = 0
def openfile(path):
lines = [line.rstrip('\n') for line in open(path)]
return lines
def calculateCost(proc):
#print(proc)
result = ''.join([i for i in proc if not i.isdigit()])
#print(result)
cost = 0
for i in result:
if i == '+' or i =='-':
cost += 1
elif i == '*' or i =='/':
cost += 3
elif i == '^':
cost += 5
return cost
def inicialize_memory():
for n in range(50):
memory.append(0)
index.append(0)
def cleanFromMemory(id):
for i in range(len(memory)):
if memory[i] == id:
memory[i] = 0
def calculateExpressionFromID(id):
true_id = id-1
equation = lista_processo[true_id]
result = calculadora(equation)
print(equation)
print(result)
def calculateFrommemory():
for id in memory:
if id != 0:
calculateExpressionFromID(id)
cleanFromMemory(id)
def incert_into_memory(id, cost):
insert_with_sucess = 1
index_start = 0
index_fim = 0
pointer = 0
count = 0
the_end = 0
for slot in index:
if count == cost:
index_fim = pointer
the_end = 1
if the_end == 0:
if slot == 0:
count += 1
else:
count = 0
index_start = pointer +1
pointer += 1
if pointer == 49 and count != cost:
insert_with_sucess = 0
#print("no Space")
elif pointer == 49 and count == cost:
index_fim = pointer
#print(index_start,index_fim, cost)
if insert_with_sucess == 1:
#print("Inserted")
for i in range(index_start,index_fim+1):
memory[i] = id
index[i] = 1
#----------------Main-------------
path = "equations.txt"
inicialize_memory()
lista_processo = openfile(path)
id = 1
for proc in lista_processo:
#print(proc)
size = calculateCost(proc)
incert_into_memory(id, size)
calculateFrommemory()
id += 1
"""
index [0] = 1
index [1] = 1
index [2] = 1
index [5] = 1
index [6] = 1
index [7] = 1
memory [0] = 1
memory [1] = 1
memory [2] = 1
memory [5] = 3
memory [6] = 3
memory [7] = 3
incert_into_memory(2,5)
for i in memory:
print(i)
"""
|
# Created 27 March 2021
from math import radians, sin, cos, asin, sqrt
def haversine_formula(lat1, lon1, lat2, lon2):
R = 6371000 # radius of Earth in metres
# convert latitudes and longitudes to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
inside = sin((lat2-lat1)/2)**2+cos(lat1)*cos(lat2)*sin((lon2-lon1)/2)**2
d = 2*R*asin(sqrt(inside))
return d
if __name__ == "__main__":
nylat, nylon = 40.7128, -74.006
madlat, madlon = 40.4168, -2.99
toklat, toklon = 35.652832, 139.839478
print("NY - Madrid", haversine_formula(nylat, nylon, madlat, madlon)/1000)
print("Madrid - Tokyo", haversine_formula(madlat, madlon, toklat, toklon)/1000)
print("NY - Tokyo", haversine_formula(nylat, nylon, toklat, toklon)/1000)
|
from collections import namedtuple
City = namedtuple('City', 'name country population coordinates')
tokyo = City('Tokyo', 'JP', 100, (0,1))
if __name__ == '__main__':
print(f"city = {City}")
print(f"tokyo = {tokyo}")
print(f"tokyo.population = {tokyo.population}")
print(f"tokyo.coordinates = {tokyo.coordinates}")
print(f"tokyo._asdict() = {tokyo._asdict()}")
|
'''
Created on Dec 9, 2017
@author:akash
'''
a=int(input("1st number?\n"))
b=int(input("2nd number?\n"))
'''a=a+b
b=a-b
a=a-b'''
a=a^b
b=a^b
a=a^b
print("1st number is = ",a,end='\n')
print("2nd number is = ",b,end='\n')
|
'''
Created on Jan 27, 2018
files
@author: akash
'''
f=open("readme1.txt",mode='r',encoding='utf-8')
print(f.read(200))
f.close()
f=open("readme1.txt",mode='w',encoding='utf-8')
a=['akash','mummy','papa']
f.write(input())
f.write("\nhello\nmy name is khan\n:-)\n")
lines=['hello\n','my name\n','is mogambo\n']
f.writelines(lines)
#f.write(a) // wont work, it requires only string
f.write("""the world is
a beautiful place""")
f.close()
f=open("readme1.txt",mode='a+')
f.write("YO YO YO\n")
f.seek(0)#to shift the pointer to a specified position
print(f.read())
print(f.tell())#to show current pointer position
f.close()
|
'''to find grade according to the given system
90-100--->O
80-89---->E
70-79---->A
else ---->F'''
n=float(input("Enter marks of the student\n"))
if n>100 or n<0:
print("Marks should be in range 0 to 100")
elif n>=90 and n<=100:
print("O grade")
elif n>=80 and n<=89:
print("E grade")
elif n>=70 and n<=79:
print("A grade")
else:
print("F grade\nSorry you have failed the examination :-(")
|
from tkinter import *
# creating the root window
root = Tk()
# creating a Label widget-defining widget
# Essentially answers the question of how the
# widget should look
myLabel1 = Label (root, text = "Hello World!")
myLabel2 = Label (root, text = "My name is Dennis")
#shoving it on the screen
# Essentially puts what it description of what it should
# look like and creates a GUI that fits, in this case it we
# position the onjects on the widget using a grid system.
# it does this by calling the the grid method and making row and columns as parameters
myLabel1.grid(row= 0, column = 0)
myLabel2.grid(row= 0, column = 2)
#this creates a loop around the GUI
root.mainloop()
|
import random, sys
print('ROCK, PAPER, SCISSORS')
wins = 0
losses = 0
ties = 0
while True:
print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties))
while True:
print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit')
move = input()
if move == 'q':
sys.exit()
if move == 'r' or move == 'p' or move == 's':
break
print('Type one of r, p, s, or q.')
if move == 'r':
print('ROCK versus...')
elif move == 'p':
print('PAPER versus...')
elif move == 's':
print('SCISSORS versus...')
randomNumber = random.randint(1,3)
if randomNumber == 1:
pcmove = 'r'
print('ROCK')
elif randomNumber == 2:
pcmove = 'p'
print('PAPER')
elif randomNumber == 3:
pcmove = 's'
print('SCISSORS')
if pcmove == move :
print('It´s a tie!')
ties = ties + 1
elif move == 'r' and pcmove == 's':
print('You win!')
wins = wins + 1
elif move == 's' and pcmove == 'p':
print('You win!')
wins = wins + 1
elif move == 'p' and pcmove == 'r':
print('You win!')
wins = wins + 1
elif pcmove == 'r' and move == 's':
print('You Lose!')
losses = losses + 1
elif pcmove == 's' and move == 'p':
print('You Lose!')
losses = losses + 1
elif pcmove == 'p' and move == 'r':
print('You Lose!')
losses = losses + 1
|
import requests
from bs4 import BeautifulSoup
import string
import os
import sys
import re
class GeniusApi:
def __init__(self, access_token):
self.base_url = 'https://api.genius.com'
self.headers = {
'Authorization': f'Bearer {access_token}'
}
self.script_path = os.path.dirname(os.path.realpath(__file__))
return
def get_songs_for_all_artists(self, artist_list, num_songs=20, sort='popularity', out_folder='songs'):
"""
Loops through the artist list and gets the lyrics for n most popular songs
"""
for artist in artist_list:
self.get_artist_songs(artist, num_songs, sort, out_folder=out_folder)
return
def get_artist_songs(self, artist_name, num_songs=20, sort='popularity', out_folder='songs'):
"""
Uses the Genius API to get the top n songs for an artist
Then uses Beautiful Soup to scrape the lyric data off of genius.com website
"""
artist_id = self.get_artist_id(artist_name)
endpoint = f'/artists/{artist_id}/songs'
params = {
'sort': sort,
'per_page': num_songs
}
r = requests.get(self.base_url + endpoint, params=params, headers=self.headers)
# loop through the songs and extract the title and song id
for song_details in r.json()['response']['songs']:
# only retrieve the songs where the artist is the primary artist of the song
if song_details['primary_artist']['id'] == artist_id:
title = song_details['title']
title = title.translate(str.maketrans('', '', string.punctuation)) # remove puncuation
song_text = self.get_song_text(song_details['url'])
self.create_lyric_file(artist_name, title, song_text, out_folder=out_folder)
return
def get_artist_id(self, artist_name):
endpoint = '/search/'
params = {
'q': artist_name
}
r = requests.get(self.base_url + endpoint, params=params, headers=self.headers)
artist_id = r.json()['response']['hits'][0]['result']['primary_artist']['id']
return artist_id
def get_song_text(self, url):
lyric_page = requests.get(url)
html = BeautifulSoup(lyric_page.text, 'html.parser')
lyrics = html.find('div', class_='lyrics').get_text()
lyrics = lyrics.encode('utf8', 'ignore').decode('utf8').strip()
lyrics = re.sub('\[.*\]', '', lyrics) # Remove [Verse] and [Bridge] stuff
lyrics = re.sub('\n{2}', '\n', lyrics) # Remove gaps between verses
lyrics = str(lyrics).strip('\n')
return lyrics
def create_lyric_file(self, artist_name, song_title, song_text, filename='auto', out_folder='songs'):
out_folder_path = os.path.join(self.script_path, out_folder)
if filename == 'auto':
filename = f'{artist_name}_{song_title}.txt'
if not os.path.exists(out_folder_path):
os.makedirs(out_folder_path)
with open(os.path.join(out_folder_path, filename), 'wb') as f:
f.write(song_text.encode('utf-8'))
return
|
from random import randint
from . import game
class AI:
"""
a class representing an AI object which plays 4 in a row.
"""
def __init__(self, game):
"""
the initializng method of the AI, which gets a game object.
"""
self.game = game
def find_legal_move(self, timeout=None):
"""
a method which finds a legal move which the AI can do.
"""
if self.game.get_winner() is None:
guess = randint(0, game.Game.BOARD_COLUMNS - 1)
while self.game.get_player_at(0, guess) is not None:
guess = randint(0, game.Game.BOARD_COLUMNS - 1)
return guess
raise Exception("No possible AI moves")
def get_last_found_move(self):
pass
|
import turtle # may need to pip install turtle
def main():
turtle.setup(500, 500) # size in pixels
# we need a window
window = turtle.Screen()
window.title('Move and rotate using arrow keys')
window.bgcolor('lightblue')
Gordon = turtle.Turtle()
def moveForward():
Gordon.forward(50)
# def moveBackward():
# Gordon.backward(50)
def turnLeft():
Gordon.left(30) # degrees
def turnRight():
Gordon.right(30)
def start():
window.onkey(moveForward, 'Up')
window.onkey(turnLeft, 'Left')
window.onkey(turnRight, 'Right')
# start listening for events
window.listen()
# we need a run loop
window.mainloop()
start()
if __name__ == '__main__':
main()
|
class NewsPublisher:
def __init__(self):
self.__subscribers = []
self.__latestNews = None
def attach(self, subscriber): # attach a new subscriber
self.__subscribers.append(subscriber)
def detach(self):
self.__subscribers.pop()
def subscribers(self):
return [type(x).__name__ for x in self.__subscribers] # show all the current subscribers
def notifySubscribers(self):
for sub in self.__subscribers:
sub.update()
def addNews(self, news):
self.__latestNews = news
def getNews(self):
return 'News: {}'.format(self.__latestNews)
class EmailSubscriber:
def __init__(self, publisher):
self.publisher = publisher
self.publisher.attach(self)
def update(self):
print(type(self).__name__, self.publisher.getNews() )
class PrintSubscriber:
def __init__(self, publisher):
self.publisher = publisher
self.publisher.attach(self)
def update(self):
print(type(self).__name__, self.publisher.getNews() )
class MediaSubscriber:
def __init__(self, publisher):
self.publisher = publisher
self.publisher.attach(self)
def update(self):
print(type(self).__name__, self.publisher.getNews() )
if __name__ == '__main__':
news_publisher = NewsPublisher()
# iterate over the collection of subscribers, notifying each
for Subscriber in [MediaSubscriber, PrintSubscriber, EmailSubscriber]:
Subscriber(news_publisher)
print('\nSubscribers: {}'.format( news_publisher.subscribers() ))
news_publisher. addNews('something newsworthy happened')
news_publisher.notifySubscribers()
|
import threading
import time
import random
class TicketSeller(threading.Thread):
ticketsSold = 0
def __init__(self, semaphore):
threading.Thread.__init__(self)
self.__semaphore = semaphore
print('Ticket seller starts selling tickets')
def run(self):
global ticketsAvailable
running = True
while running: # auto release when done
self.randomDelay()
self.__semaphore.acquire()
if ticketsAvailable <=0:
running = False
else:
self.ticketsSold += 1
ticketsAvailable -= 1
print('{} sold {} so there are {} remaining'.format(self.getName(), self.ticketsSold, ticketsAvailable) )
self.__semaphore.release() # ... so other sellers can use it!
print('Ticket seller {} sold {} tickets in total'.format(self.getName(), self.ticketsSold))
def randomDelay(self):
time.sleep(random.randint(0, 4)/4) # 0, 0.25, 0.5 or 0.75 sec
def main():
semaphore = threading.Semaphore(value=4) # up to 4 at a time
sellers = [] # a list of ticket sellers
for i in range(4):
seller = TicketSeller(semaphore)
seller.start()
sellers.append(seller)
for seller in sellers:
seller.join()
if __name__ == '__main__':
ticketsAvailable = 200 # a global variable
main()
|
currency_str_value = input("请输带单位的货币金额:")
RATE = 6.77
if currency_str_value[-3:] == 'CNY':
rmb_str_value = currency_str_value[:-3]
rmb_value = eval(rmb_str_value)
usd_value = rmb_value / RATE
print("美元:", usd_value)
elif currency_str_value[-3:] == 'USD':
usd_str_value = currency_str_value[:-3]
usd_value = eval(usd_str_value)
rmb_value = usd_value * RATE
print("人民币:", rmb_value)
else:
except_else = '改程序目前版本不支持该种货币'
print(except_else)
# rmb_value = eval(rmb_str_value)
# dollar = rmb_value / rate
# print("美元:", dollar,rmb_str_value)
|
'''def sample():
print("hello function")
def sam():
print("inside function")
sam()
sample()'''
'''#a=int(input())
#b=int(input())
#c=int(input())
def sample(a,b,c):
#def sample(a,b,c=10):
if(a==b and b==c and c==a):
print(0)
elif(a!=b and b!=c and a!=c):
print(a+b+c)
else:
if(a==b):
print(c)
elif(b==c):
print(a)
else:
print(b)
#sample(a,b,c)
#sample(2,3)=2+3+10
#sample(2,3,20)=2+3+20
sample(a=2,b=3,c=2)
'''
def l(s,b,*var):
#def l(*var,s=100,b=100) s&b are default values
#variable length argument * meaning is all
for i in var:
print(i)
print(s,b)
l(10,2,3,5,6,7,8,5,4,3,4,6,7,7,4,23,34,5,6,5,1)# s=10 in the last position
|
a =(int(input("Enter the number to taken the factorial")))
counter=a
resault=1
for i in range(a):
resault*=a-(a-counter)
counter-=1
print(resault)
|
# toplama fonksiyonu
def topla():
sayi1 = int(input(" Sayı1: "))
sayi2 = int(input(" Sayı2: "))
print( sayi1 + sayi2 )
# çıkarma fonksiyonu
def cikar():
sayi1 = int(input(" Sayı1: "))
sayi2 = int(input(" Sayı2: "))
print( sayi1 - sayi2)
# çarpma fonksiyonu
def carp():
sayi1 = int(input(" Sayı1: "))
sayi2 = int(input(" Sayı2: "))
print (sayi1 * sayi2 )
# bölme fonksiyonu
def bol():
sayi1 = int(input(" Sayı1: "))
sayi2 = int(input(" Sayı2: "))
print (sayi1 / sayi2)
# üs alma fonksiyonu
def us():
sayi1 = int(input(" Sayı1: "))
sayi2 = int(input(" Sayı2: "))
print (sayi1 ** sayi2)
# kök alma fonksiyonu
def kok():
sayi1 = int(input(" Sayı1: "))
print( sayi1 ** 0.5)
print("1.Toplama, 2.Çıkarma, 3.çarpma, 4.Bölme, 5.üsalma, 6.kökal ")
secim = input("Seçiminiz:):")
# sayılara tıknadıında hangi fonksiyonu çalıştırmaları gerektiğini söylüyor.
if secim == '1':
topla()
elif secim == '2':
cikar()
elif secim == '3':
carp()
elif secim == '4':
bol()
elif secim == '5':
us()
elif secim == '6':
kok()
|
ay=int(input("Enter the month value between 1 and 12."))
if ay ==1 or ay ==2 or ay =12 :
print("winter")
if ay ==3 or ay ==4 or ay =5 :
print(" spring")
if ay ==6 or ay ==7 or ay =8 :
print("summer")
if ay ==9 or ay ==10 or ay =11 :
print("autumn")
|
class Node:
def __init__(self, letter):
self.letter = letter
self.children = [None]*26
# isEndOfWord is True if node represent the end of a word
self.isEndOfWord = False
self.meaning = ''
class Trie:
def __init__(self):
self.root = Node('')
def insertion(self, word, meaning):
word.lower()
current = self.root
for char in word:
index = self._charToIndex(char)
if current.children[index] is None:
node = Node(char)
current.children[index] = node
current = current.children[index]
node = current
node.isEndOfWord = True
node.meaning = meaning
def search(self, word):
word.lower()
current = self.root
for char in word:
index = self._charToIndex(char)
if current.children[index] is None:
return False
else:
current = current.children[index]
return current.meaning
def _charToIndex(self, char):
# private helper function
# Converts key current character into index
# use only 'a' through 'z' and lower case
return ord(char)-ord('a')
trie = Trie()
trie.insertion("language", "the method of human communication")
trie.insertion("map", "a diagrammatic representation of an area")
trie.insertion("computer", "A computer is a machine that can be \
instructed to carry out sequences of arithmetic or \
logical operations automatically via computer programming")
trie.insertion("book", "a written or printed work \
consisting of pages glued or sewn together along one \
side and bound in covers.")
trie.insertion("science", "the intellectual and \
practical activity encompassing the systematic study \
of the structure and behaviour of the physical and \
natural world through observation and experiment.")
print('Language:', trie.search('language'))
print('Map:', trie.search('map'))
print('Computer:', trie.search('computer'))
print('Book:', trie.search('book'))
print('Science:', trie.search('science'))
|
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def insertion(self, key):
node = Node(key)
if self.root is None:
self.root = node
else:
current = self.root
while current is not None:
if key > current.key:
if current.right is None:
current.right = node
break
else:
current = current.right
else:
if current.left is None:
current.left = node
break
else:
current = current.left
def delete(self, key):
if self.root is not None:
current = self.root
while current is not None:
# key is greater than current - go right
if key > current.key:
last = current
current = current.right
to_right = True
# key is lesser than current - go left
elif key < current.key:
last = current
current = current.left
to_right = False
# key is equal
else:
# current node has no child
if current.left is None and current.right is None:
if to_right:
last.right = None
else:
last.left = None
# current node has only left child
elif current.left is not None and current.right is None:
if to_right:
last.right = current.left
else:
last.left = current.left
# current node has only right child
elif current.left is None and current.right is not None:
if to_right:
last.right = current.right
else:
last.left = current.right
# current node has both children
else:
# find the minimum value in the current node right subtree
minor = current.right
while minor and minor is not None:
minor = minor.left
# replace current with minor node key
current.key = minor.key
# delete the minor node found
self.delete(minor.key)
break
def search(self, key):
if self.root is not None:
current = self.root
while current is not None:
# key found
if key is current.key:
return current.key
# key is greater than current - go right
elif key > current.key:
current = current.right
# key is lesser than current - go left
else:
current = current.left
return None
def inorder_single(self, root):
if root is not None:
self.inorder_single(root.left)
print(root.key)
self.inorder_single(root.right)
def inorder(self):
self.inorder_single(self.root)
tree = Tree()
tree.insertion(12)
tree.insertion(5)
tree.insertion(15)
tree.insertion(3)
tree.insertion(7)
tree.insertion(9)
print('Tree: ')
tree.inorder()
tree.delete(7)
print('\nTree after delete: ')
tree.inorder()
print('\nx: ', tree.search(9))
print('y: ', tree.search(10))
|
import os
import sys
from argparse import ArgumentParser, HelpFormatter
import startds
class CommandParser(ArgumentParser):
"""
Customized ArgumentParser class to improve some error messages and prevent
SystemExit in several occasions, as SystemExit is unacceptable when a
command is called programmatically.
"""
def __init__(self, *, missing_args_message=None, **kwargs):
self.missing_args_message = missing_args_message
super().__init__(**kwargs)
def parse_args(self, args=None, namespace=None):
# Catch missing argument for a better error message
if (self.missing_args_message and (args is not None) and
not (args or any(not arg.startswith('-') for arg in args))):
self.error(self.missing_args_message)
return super().parse_args(args, namespace)
def error(self, message):
super().error(message)
class BaseCommand:
"""
1. loads the command class and calls its ``run_from_argv()`` method.
2. The ``run_from_argv()`` method calls ``create_parser()`` to get
an ``ArgumentParser`` for the arguments, parses them, and then
calls the ``execute()`` method, passing the parsed arguments.
3. The ``execute()`` method attempts to carry out the command by
calling the ``handle()`` method with the parsed arguments; any
output produced by ``handle()`` will be printed to stdout.
Thus, the ``handle()`` method is typically the starting point for
subclasses; many built-in commands and command types either place
all of their logic in ``handle()``, or perform some additional
parsing work in ``handle()`` and then delegate from it to more
specialized methods as needed.
Several attributes affect behavior at various steps along the way:
``help``
A short description of the command, which will be printed in
help messages.
"""
# Metadata about this command.
help = ''
def __init__(self):
pass
def create_parser(self, prog_name, subcommand, **kwargs):
"""
Create and return the ``ArgumentParser`` which will be used to
parse the arguments to this command.
"""
parser = CommandParser(
prog='%s %s' % (os.path.basename(prog_name), subcommand),
description=self.help or None,
missing_args_message=getattr(self, 'missing_args_message', None),
**kwargs
)
self.add_arguments(parser)
return parser
def add_arguments(self, parser):
"""
Entry point for subclassed commands to add custom arguments.
"""
pass
def print_help(self, prog_name, subcommand):
"""
Print the help message for this command, derived from
``self.usage()``.
"""
parser = self.create_parser(prog_name, subcommand)
parser.print_help()
def run_from_argv(self, argv):
parser = self.create_parser(argv[0], argv[1])
parser.add_argument('args', nargs='*') # catch-all
parser.add_argument('-f', nargs='*') # catch-all
parser.add_argument('--api', nargs='*') # catch-all
parser.add_argument('--mode', nargs='*') # catch-all
options = parser.parse_args(argv[2:])
cmd_options = vars(options)
# Move positional args out of options to mimic legacy optparse
args = cmd_options.pop('args', ())
try:
self.execute(*args, **cmd_options)
except Exception:
sys.exit()
def execute(self, *args, **options):
"""
Try to execute this command, performing system checks if needed (as
controlled by the ``requires_system_checks`` attribute, except if
force-skipped).
"""
output = self.handle(*args, **options)
return output
def handle(self, *args, **options):
"""
The actual logic of the command. Subclasses must implement
this method.
"""
raise NotImplementedError('subclasses of BaseCommand must provide a handle() method')
|
"""
Capstone Project. Code to run on a LAPTOP (NOT the robot).
Constructs and returns Frame objects for the basics:
-- teleoperation
-- arm movement
-- stopping the robot program
This code is SHARED by all team members. It contains both:
-- High-level, general-purpose methods for a Snatch3r EV3 robot.
-- Lower-level code to interact with the EV3 robot library.
Author: Your professors (for the framework and lower-level code)
and Yifei Xiao.
Winter term, 2018-2019.
"""
import tkinter
from tkinter import ttk
import time
def get_teleoperation_frame(window, mqtt_sender):
"""
Constructs and returns a frame on the given window, where the frame
has Entry and Button objects that control the EV3 robot's motion
by passing messages using the given MQTT Sender.
:type window: ttk.Frame | ttk.Toplevel
:type mqtt_sender: com.MqttClient
"""
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Teleoperation")
left_speed_label = ttk.Label(frame, text="Left wheel speed (0 to 100)")
right_speed_label = ttk.Label(frame, text="Right wheel speed (0 to 100)")
left_speed_entry = ttk.Entry(frame, width=8)
left_speed_entry.insert(0, "100")
right_speed_entry = ttk.Entry(frame, width=8, justify=tkinter.RIGHT)
right_speed_entry.insert(0, "100")
forward_button = ttk.Button(frame, text="Forward")
backward_button = ttk.Button(frame, text="Backward")
left_button = ttk.Button(frame, text="Left")
right_button = ttk.Button(frame, text="Right")
stop_button = ttk.Button(frame, text="Stop")
# Grid the widgets:
frame_label.grid(row=0, column=1)
left_speed_label.grid(row=1, column=0)
right_speed_label.grid(row=1, column=2)
left_speed_entry.grid(row=2, column=0)
right_speed_entry.grid(row=2, column=2)
forward_button.grid(row=3, column=1)
left_button.grid(row=4, column=0)
stop_button.grid(row=4, column=1)
right_button.grid(row=4, column=2)
backward_button.grid(row=5, column=1)
# Set the button callbacks:
forward_button["command"] = lambda: handle_forward(
left_speed_entry, right_speed_entry, mqtt_sender)
backward_button["command"] = lambda: handle_backward(
left_speed_entry, right_speed_entry, mqtt_sender)
left_button["command"] = lambda: handle_left(
left_speed_entry, right_speed_entry, mqtt_sender)
right_button["command"] = lambda: handle_right(
left_speed_entry, right_speed_entry, mqtt_sender)
stop_button["command"] = lambda: handle_stop(mqtt_sender)
return frame
def get_arm_frame(window, mqtt_sender):
"""
Constructs and returns a frame on the given window, where the frame
has Entry and Button objects that control the EV3 robot's Arm
by passing messages using the given MQTT Sender.
:type window: ttk.Frame | ttk.Toplevel
:type mqtt_sender: com.MqttClient
"""
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Arm and Claw")
position_label = ttk.Label(frame, text="Desired arm position:")
position_entry = ttk.Entry(frame, width=8)
raise_arm_button = ttk.Button(frame, text="Raise arm")
lower_arm_button = ttk.Button(frame, text="Lower arm")
calibrate_arm_button = ttk.Button(frame, text="Calibrate arm")
move_arm_button = ttk.Button(frame,
text="Move arm to position (0 to 5112)")
blank_label = ttk.Label(frame, text="")
# Grid the widgets:
frame_label.grid(row=0, column=1)
position_label.grid(row=1, column=0)
position_entry.grid(row=1, column=1)
move_arm_button.grid(row=1, column=2)
blank_label.grid(row=2, column=1)
raise_arm_button.grid(row=3, column=0)
lower_arm_button.grid(row=3, column=1)
calibrate_arm_button.grid(row=3, column=2)
# Set the Button callbacks:
raise_arm_button["command"] = lambda: handle_raise_arm(mqtt_sender)
lower_arm_button["command"] = lambda: handle_lower_arm(mqtt_sender)
calibrate_arm_button["command"] = lambda: handle_calibrate_arm(mqtt_sender)
move_arm_button["command"] = lambda: handle_move_arm_to_position(
position_entry, mqtt_sender)
return frame
def get_drive_system_frame(window, mqtt_sender):
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Drive System")
label1 = ttk.Label(frame, text="Duration of Movement OR Desired Distance:")
time_entry = ttk.Entry(frame, width=8)
color_label = ttk.Label(frame, text="Color Sensor Movement")
ir_label = ttk.Label(frame, text="IR Movement")
delta_label = ttk.Label(frame, text="Delta")
inches_label = ttk.Label(frame, text="Inches")
camera_label = ttk.Label(frame, text="Camera Movement")
less_than_entry = ttk.Entry(frame, width=8)
greater_than_entry = ttk.Entry(frame, width=8)
straight_until_color_is_entry = ttk.Entry(frame, width=8)
straight_until_color_is_not_entry = ttk.Entry(frame, width=8)
forward_until_less_than_entry = ttk.Entry(frame, width=8)
backward_until_greater_than_entry = ttk.Entry(frame, width=8)
distance_within_entry_delta = ttk.Entry(frame, width=8)
distance_within_entry_inches = ttk.Entry(frame, width=8)
clockwise_area_entry = ttk.Entry(frame, width=8)
counterclockwise_area_entry = ttk.Entry(frame, width=8)
straight_until_less_button = ttk.Button(frame, text="Go straight until intensity is less than:")
straight_until_greater_button = ttk.Button(frame, text="Go straight until intensity is greater than:")
straight_until_color_is_button = ttk.Button(frame, text="Go straight until color is:")
straight_until_color_is_not_button = ttk.Button(frame, text="Go straight until color is not:")
forward_until_less_than_button = ttk.Button(frame, text="Go forward until dist less than:")
backward_until_greater_than_button = ttk.Button(frame, text="Go backward until dist greater than:")
go_until_within_button = ttk.Button(frame, text="Go until distance is within:")
go_for_seconds = ttk.Button(frame, text="Go straight for seconds")
go_for_time = ttk.Button(frame, text="Go straight for inches using time")
go_for_encoder = ttk.Button(frame, text="Go straight for inches using encoder")
camera_display_button = ttk.Button(frame, text="Display Camera Data")
clockwise_area_button = ttk.Button(frame, text="Spin Clockwise Area:")
counterclockwise_area_button = ttk.Button(frame, text="Spin Counterclockwise Area:")
blank_label = ttk.Label(frame, text="")
# Grid the widgets:
frame_label.grid(row=0, column=1)
camera_label.grid(row=5, column=7)
label1.grid(row=1, column=0)
time_entry.grid(row=1, column=1)
color_label.grid(row=5, column=1)
less_than_entry.grid(row=6, column=1)
greater_than_entry.grid(row=7, column=1)
straight_until_color_is_entry.grid(row=8, column=1)
straight_until_color_is_not_entry.grid(row=9, column=1)
ir_label.grid(row=5, column=3)
forward_until_less_than_entry.grid(row=6, column=3)
backward_until_greater_than_entry.grid(row=7, column=3)
delta_label.grid(row=8, column=3)
inches_label.grid(row=8, column=4)
distance_within_entry_delta.grid(row=9, column=3)
distance_within_entry_inches.grid(row=9, column=4)
clockwise_area_entry.grid(row=7, column=7)
counterclockwise_area_entry.grid(row=8, column=7)
blank_label.grid(row=2, column=1)
forward_until_less_than_button.grid(row=6, column=2)
backward_until_greater_than_button.grid(row=7, column=2)
straight_until_color_is_button.grid(row=8, column=0)
straight_until_color_is_not_button.grid(row=9, column=0)
straight_until_less_button.grid(row=6, column=0)
straight_until_greater_button.grid(row=7, column=0)
go_until_within_button.grid(row=9, column=2)
blank_label.grid(row=4, column=1)
go_for_seconds.grid(row=3, column=0)
go_for_time.grid(row=3, column=1)
go_for_encoder.grid(row=3, column=2)
camera_display_button.grid(row=6, column=7)
clockwise_area_button.grid(row=7, column=6)
counterclockwise_area_button.grid(row=8, column=6)
# Set the Button callbacks:
go_for_seconds["command"] = lambda: handle_go_straight_for_seconds(time_entry, mqtt_sender)
go_for_time["command"] = lambda: handle_go_straight_for_inches_using_time(time_entry, mqtt_sender)
go_for_encoder["command"] = lambda: handle_go_straight_for_inches_using_encoder(time_entry, mqtt_sender)
straight_until_less_button["command"] = lambda: handle_straight_until_less_than(less_than_entry, mqtt_sender)
straight_until_greater_button["command"] = lambda : handle_straight_until_greater_than(greater_than_entry, mqtt_sender)
straight_until_color_is_button["command"] = lambda: handle_straight_until_color_is(straight_until_color_is_entry, mqtt_sender)
straight_until_color_is_not_button["command"] = lambda: handle_straight_until_color_is_not(straight_until_color_is_not_entry, mqtt_sender)
forward_until_less_than_button["command"] = lambda: handle_forward_until_less(forward_until_less_than_entry, mqtt_sender)
backward_until_greater_than_button["command"] = lambda: handle_backward_until_greater(backward_until_greater_than_entry, mqtt_sender)
go_until_within_button["command"] = lambda: handle_go_until_within(distance_within_entry_delta, distance_within_entry_inches, mqtt_sender)
clockwise_area_button["command"] = lambda: handle_go_clockwise(clockwise_area_entry, mqtt_sender)
counterclockwise_area_button["command"] = lambda: handle_go_counterclockwise(counterclockwise_area_entry, mqtt_sender)
camera_display_button["command"] = lambda: handle_camera_display(mqtt_sender)
return frame
def get_control_frame(window, mqtt_sender):
"""
Constructs and returns a frame on the given window, where the frame has
Button objects to exit this program and/or the robot's program (via MQTT).
:type window: ttk.Frame | ttk.Toplevel
:type mqtt_sender: com.MqttClient
"""
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Control")
quit_robot_button = ttk.Button(frame, text="Stop the robot's program")
exit_button = ttk.Button(frame, text="Stop this and the robot's program")
# Grid the widgets:
frame_label.grid(row=0, column=1)
quit_robot_button.grid(row=1, column=0)
exit_button.grid(row=1, column=2)
# Set the Button callbacks:
quit_robot_button["command"] = lambda: handle_quit(mqtt_sender)
exit_button["command"] = lambda: handle_exit(mqtt_sender)
return frame
def get_sound_system_frame(window, mqtt_sender):
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Sound System")
beep_label = ttk.Label(frame, text="Beep for a number of times:")
freq_label = ttk.Label(frame, text="Play a frequency (box 1) for a period of time(box 2):")
speak_label = ttk.Label(frame, text="Speak a phrase:")
beep_entry = ttk.Entry(frame, width=8)
beep_entry.insert(0, "")
freq_entry = ttk.Entry(frame, width=8, justify=tkinter.RIGHT)
freq_entry.insert(0, "")
time_entry = ttk.Entry(frame, width=8)
time_entry.insert(0, "")
speak_entry = ttk.Entry(frame, width=8)
speak_entry.insert(0, "")
beep_button = ttk.Button(frame, text="Beep")
freq_button = ttk.Button(frame, text="Play Frequency")
speak_button = ttk.Button(frame, text="Speak")
# Grid the widgets:
frame_label.grid(row=0, column=1)
beep_label.grid(row=1, column=0)
speak_label.grid(row=1, column=1)
freq_label.grid(row=1, column=2)
beep_entry.grid(row=2, column=0)
freq_entry.grid(row=2, column=1)
speak_entry.grid(row=2, column=2)
time_entry.grid(row=2, column=3)
beep_button.grid(row=3, column=0)
freq_button.grid(row=3, column=2)
speak_button.grid(row=3, column=1)
# Set the button callbacks:
beep_button["command"] = lambda: handle_beep(beep_entry, mqtt_sender)
freq_button["command"] = lambda: handle_freq(freq_entry, time_entry, mqtt_sender)
speak_button["command"] = lambda: handle_speak(speak_entry, mqtt_sender)
return frame
###############################################################################
###############################################################################
# The following specifies, for each Button,
# what should happen when the Button is pressed.
###############################################################################
###############################################################################
###############################################################################
# Handlers for Buttons in the Teleoperation frame.
###############################################################################
def handle_forward(left_entry_box, right_entry_box, mqtt_sender):
"""
Tells the robot to move using the speeds in the given entry boxes,
with the speeds used as given.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: com.MqttClient
"""
print('Forward', [left_entry_box.get(), right_entry_box.get()])
mqtt_sender.send_message("forward", [left_entry_box.get(), right_entry_box.get()])
def handle_backward(left_entry_box, right_entry_box, mqtt_sender):
"""
Tells the robot to move using the speeds in the given entry boxes,
but using the negatives of the speeds in the entry boxes.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: com.MqttClient
"""
print('Backward', [left_entry_box.get(), right_entry_box.get()])
mqtt_sender.send_message("backward", [left_entry_box.get(), right_entry_box.get()])
def handle_left(left_entry_box, right_entry_box, mqtt_sender):
"""
Tells the robot to move using the speeds in the given entry boxes,
but using the negative of the speed in the left entry box.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: com.MqttClient
"""
print('Left')
mqtt_sender.send_message("left", [left_entry_box.get(), right_entry_box.get()])
def handle_right(left_entry_box, right_entry_box, mqtt_sender):
"""
Tells the robot to move using the speeds in the given entry boxes,
but using the negative of the speed in the right entry box.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: com.MqttClient
"""
print('Right')
mqtt_sender.send_message("right", [left_entry_box.get(), right_entry_box.get()])
def handle_stop(mqtt_sender):
"""
Tells the robot to stop.
:type mqtt_sender: com.MqttClient
"""
print('Stop')
mqtt_sender.send_message("stop")
###############################################################################
# Handlers for Buttons in the ArmAndClaw frame.
###############################################################################
def handle_raise_arm(mqtt_sender):
"""
Tells the robot to raise its Arm until its touch sensor is pressed.
:type mqtt_sender: com.MqttClient
"""
print('Raise arm')
mqtt_sender.send_message("hoist")
def handle_lower_arm(mqtt_sender):
"""
Tells the robot to lower its Arm until it is all the way down.
:type mqtt_sender: com.MqttClient
"""
print('Lower arm')
mqtt_sender.send_message("lower")
def handle_calibrate_arm(mqtt_sender):
"""
Tells the robot to calibrate its Arm, that is, first to raise its Arm
until its touch sensor is pressed, then to lower its Arm until it is
all the way down, and then to mark taht position as position 0.
:type mqtt_sender: com.MqttClient
"""
print('Calibrating arm')
mqtt_sender.send_message("calibrate")
def handle_move_arm_to_position(arm_position_entry, mqtt_sender):
"""
Tells the robot to move its Arm to the position in the given Entry box.
The robot must have previously calibrated its Arm.
:type arm_position_entry ttk.Entry
:type mqtt_sender: com.MqttClient
"""
print('Moving arm to position')
mqtt_sender.send_message("movetopos", [arm_position_entry.get()])
###############################################################################
# Handlers for Buttons in the Control frame.
###############################################################################
def handle_quit(mqtt_sender):
"""
Tell the robot's program to stop its loop (and hence quit).
:type mqtt_sender: com.MqttClient
"""
print('Quit')
mqtt_sender.send_message("quit")
def handle_exit(mqtt_sender):
"""
Tell the robot's program to stop its loop (and hence quit).
Then exit this program.
:type mqtt_sender: com.MqttClient
"""
print('Exit')
handle_quit(mqtt_sender)
exit()
###############################################################################
# Handlers for Buttons in the Drive System frame.
###############################################################################
def handle_go_straight_for_seconds(time_entry, mqtt_sender):
print('Going straight for seconds')
mqtt_sender.send_message("straightforseconds", [time_entry.get()])
def handle_go_straight_for_inches_using_time(time_entry, mqtt_sender):
print('Going straight for inches using time')
mqtt_sender.send_message("straightusingtime", [time_entry.get()])
def handle_go_straight_for_inches_using_encoder(time_entry, mqtt_sender):
print('Going straight for inches using encoder')
mqtt_sender.send_message("straightusingencoder", [time_entry.get()])
def handle_straight_until_less_than(less_than_entry, mqtt_sender):
print('Going straight until intensity is less than ')
mqtt_sender.send_message("straightuntilless", [less_than_entry.get()])
def handle_straight_until_greater_than(greater_than_entry, mqtt_sender):
print('Going straight until intensity is greater than ')
mqtt_sender.send_message("straightuntilgreater", [greater_than_entry.get()])
def handle_straight_until_color_is(straight_until_color_is_entry, mqtt_sender):
print('Going straight until color is ')
mqtt_sender.send_message("straightuntilcoloris", [straight_until_color_is_entry.get()])
def handle_straight_until_color_is_not(straight_until_color_is_not_entry, mqtt_sender):
print('Going straight until color is not ')
mqtt_sender.send_message("straightuntilcolorisnot", [straight_until_color_is_not_entry.get()])
def handle_forward_until_less(forward_until_less_than_entry, mqtt_sender):
print('Going forward until distance is less than ')
mqtt_sender.send_message("straightdistless", [forward_until_less_than_entry.get()])
def handle_backward_until_greater(backward_until_greater_than_entry, mqtt_sender):
print('Going backward until distance is greater than ')
mqtt_sender.send_message("straightdistmore", [backward_until_greater_than_entry.get()])
def handle_go_until_within(distance_within_entry_delta, distance_within_entry_inches, mqtt_sender):
print('Going forward until distance is within entry')
mqtt_sender.send_message("distwithinrange", [distance_within_entry_delta.get(), distance_within_entry_inches.get()])
def handle_go_clockwise(clockwise_area_entry, mqtt_sender):
print('Going clockwise for area ')
mqtt_sender.send_message("clockwise", [clockwise_area_entry.get()])
def handle_go_counterclockwise(counterclockwise_area_entry, mqtt_sender):
print('Going counterclockwise for area ')
mqtt_sender.send_message("counterclockwise", [counterclockwise_area_entry.get()])
def handle_camera_display(mqtt_sender):
print('Displaying Camera Feed')
mqtt_sender.send_message("display")
###############################################################################
# Handlers for Buttons in the Sound System frame.
###############################################################################
def handle_beep(beep_entry, mqtt_sender):
print('Beeping')
mqtt_sender.send_message("beep", [beep_entry.get()])
def handle_freq(freq_entry, time_entry, mqtt_sender):
print('Playing frequency')
mqtt_sender.send_message("freq", [freq_entry.get(), time_entry.get()])
def handle_speak(speak_entry, mqtt_sender):
print('Speaking')
mqtt_sender.send_message("speak", [speak_entry.get()])
|
'''
Created on Nov 3, 2018
@authors: Haram Koo, Duncan Van Keulen
'''
def file_to_line(file):
'''
This function turns a file into a string
'''
with open(file, 'r') as file:
list_1 = []
for line in file:
list_1.append(str(line))
string_list = ''.join(list_1)
nl_string = string_list.replace('\n', '\\n')
final_string = nl_string.replace(' ', '\\t')
return final_string
def file_to_line_overwrite(overwrite, to_1):
'''Dangerous, overwrites files, meant to be copied into another file'''
# from file_to_line import *
# with open("<file you're in/want to overwrite>", 'w') as file:
# file.write('''{}'''.format(str(file_to_string('<file you want to be converted to 1 line>'))))
with open(overwrite, 'w') as file:
file.write('''{}'''.format(str(file_to_string(to_1))))
def file_to_line_print(file_handle):
'''Prints the file in one line'''
# If you want to copy this code...
# from file_to_string import *
# print(str(file_to_line('<file to be converted to 1 line>')))
print(str(file_to_line(str(file_handle))))
|
# This is the program for rock paper scissor game
# import random module to select random characters from the list
import random
print("Enter the number to select your characters")
print("0 for rock")
print("1 for paper")
print("2 for scissor")
print("only 6 rounds.... let's play the game")
def main():
k=0
p=0
for i in range(1,7):
# This list for the computer
list1=["rock","paper","scissor"]
computer=random.choice(list1)
# This list for the user
a=int(input("enter the number:"))
# This condition is for ....when user input is wrong
if a>2:
print("invalid input")
break
b=list1[a]
print(f"because of opponent character is {computer} and your character {b}")
if computer == b:
print("both the characters are same play again")
# This condition is for user in Which user can win this round
elif (b == "paper" and computer == "rock") or (b == "scissor" and computer == "paper") or (b == "rock" and computer == "scissor"):
print("you win the game")
k=k+1
print(f"you got {k} points")
else:
print("opponent win the game")
p=p+1
print(f"opponent got {p} points")
if k>p:
print(f"your points are {k} you won the game......opponent points are {p}")
elif p>k:
print(f"opponent points are {p} opponent won the game......your points are {k}")
else:
print(f"your points {k} and opponent points {p} game is draw")
def main2():
Repeat=input("want to play again press yes/no\n")
if Repeat=="yes" or Repeat=="YES" or Repeat=="Yes":
main()
elif Repeat=="no" or Repeat=="NO":
print("bye")
exit()
else:
print("Invalid input")
main2()
main2()
main()
|
class Player(object) :
"""
A player for a specific team with needed stats.
Class is designed for input of the url for player's advanced stats page.
"""
def __init__(self,html_link) :
'''
Takes in a player's advanced stats page from kenpom.com and breaks it into a usuable class
'''
#html_string = get_page(html_link)
soup = BeautifulSoup(html_link,'html.parser')
try :
self.name = soup.find_all('div',attrs={'id' : 'content-header'})[0].find_all('span',attrs={'class' : 'name'})[0].get_text()
except :
raise ValueError("No player name found.")
try :
self.year_stats = soup.find_all('table',attrs={'id' : 'schedule-table'})[0]
except :
raise ValueError("No player stats found.")
stuff2 = player.year_stats.get_text().split('\n')
stuff = []
for i in range(len(stuff2)) :
if stuff2[i] == '' or stuff2[i] == '\xa0' or stuff2[i] == '\xb0' :
pass
elif stuff2[i] == '--' :
stuff.append(0)
stuff.append(0)
else :
stuff.append(stuff2[i])
stuff = stuff[11:-11]
columns = ['Date','Opponent','Result','Site','MP','ORtg','%Ps','Pts','2Pt','3Pt','FT','OR','DR','A','TO','Blk','Stl','PF']
m = len(columns)
self.stats = {}
for i in range(m) :
self.stats[columns[i]] = []
for i in range(len(stuff)) :
if str(stuff[i])[-12:] == "Did not play" :
n = i%m
for j in range(n,m) :
self.stats[columns[j]].append(0)
else :
self.stats[columns[i%m]].append(stuff[i])
|
from .Converters import *
# print(,file=args["output"], file=args["output"])
def call_(args):
fn_name = args["remaining_command"][0]
arguments = args["remaining_command"][1]
# Function can be called multiple times in a file.
# We need to create labels uniquely in the same file.
unique_key = fn_name_with_line_number(args)
# dummy_spacing
# When there are 0 arguments. Return address & ARG point to the same address
# As a result, When the function returns, return value becomes the return address.
# To prevent this, we are introducing a dummy_spacing between ARG & return address.
print("@0", file=args["output"])
print("D=A", file=args["output"])
pushD(args)
# Push return address
print("@"+ unique_key + ".finish.address", file=args["output"])
print("D=A", file=args["output"])
pushD(args)
# Push old LCL
print("@LCL", file=args["output"])
print("D=M", file=args["output"])
pushD(args)
# Push old ARG
print("@ARG", file=args["output"])
print("D=M", file=args["output"])
pushD(args)
# Push old THIS
print("@THIS", file=args["output"])
print("D=M", file=args["output"])
pushD(args)
# Push old THAT
print("@THAT", file=args["output"])
print("D=M", file=args["output"])
pushD(args)
# Compute new ARG
print("@SP", file=args["output"])
print("D=M", file=args["output"])
# dummy_spacing, return, lcl, arg, this, that
print("@6", file=args["output"])
print("D=D-A", file=args["output"])
print("@"+ arguments, file=args["output"])
print("D=D-A", file=args["output"])
# Change ARG
print("@ARG", file=args["output"])
print("M=D", file=args["output"])
# Change LCL
print("@SP", file=args["output"])
print("D=M", file=args["output"])
print("@LCL", file=args["output"])
print("M=D", file=args["output"])
# Jump to callee function
print("@" + fn_name, file=args["output"])
print("0;JMP", file=args["output"])
# Creating unique return address to caller after all of the call statements
# By using line number in vm file + fn_name + .return.address
print("("+ unique_key + ".finish.address)", file=args["output"])
def function_(args):
fn_name = args["remaining_command"][0]
local_vars = args["remaining_command"][1]
# The labels in this function will continue to use this.
# There is no way to tell, if the function has ended.
# Any labels following this function also will continue to use the same name.
# But that's okay. These functionless labels, just need filename as unique key
# Filename + Functioname is just added advantage
# What if there is a conflict between, label outside & same label inside a function?
args["fn_name"] = fn_name
# For Function as well as labels inside function
unique_key = fn_name
print("("+ unique_key +")", file=args["output"])
# Save counter in 13
print("@"+local_vars, file=args["output"])
print("D=A", file=args["output"])
print("@13", file=args["output"])
print("M=D", file=args["output"])
# Start Loop to initialize local vars
print("("+ unique_key +".initialize_local_vars.begin)", file=args["output"])
# Check counter to exit loop
print("@13", file=args["output"])
print("D=M", file=args["output"])
print("@"+ unique_key +".initialize_local_vars.end", file=args["output"])
print("D;JEQ", file=args["output"])
# If not, reduce counter, set D to 0, pushD & Repeat
print("@13", file=args["output"])
print("M=M-1", file=args["output"])
print("@0", file=args["output"])
print("D=A", file=args["output"])
pushD(args)
print("@"+ unique_key +".initialize_local_vars.begin", file=args["output"])
print("0;JMP", file=args["output"])
# End Loop
print("("+ unique_key +".initialize_local_vars.end)", file=args["output"])
def return_(args):
# Fetch return value of callee & set it for caller.
print("@SP", file=args["output"])
print("A=M-1", file=args["output"])
print("D=M", file=args["output"])
print("@ARG", file=args["output"])
print("A=M", file=args["output"])
print("M=D", file=args["output"])
# Set SP to ARG + 1 (We need to be 1 step the return value)
# A is already set to the value of @ARG from previous steps
print("D=A+1", file=args["output"])
print("@SP", file=args["output"])
print("M=D", file=args["output"])
# Save pop address in 13
print("@LCL", file=args["output"])
print("D=M", file=args["output"])
print("@13", file=args["output"])
print("M=D", file=args["output"])
# Reset THAT
print("@13", file=args["output"])
print("AM=M-1", file=args["output"])
print("D=M", file=args["output"])
print("@THAT", file=args["output"])
print("M=D", file=args["output"])
# Reset THIS
print("@13", file=args["output"])
print("AM=M-1", file=args["output"])
print("D=M", file=args["output"])
print("@THIS", file=args["output"])
print("M=D", file=args["output"])
# Reset ARG
print("@13", file=args["output"])
print("AM=M-1", file=args["output"])
print("D=M", file=args["output"])
print("@ARG", file=args["output"])
print("M=D", file=args["output"])
# Reset LCL
print("@13", file=args["output"])
print("AM=M-1", file=args["output"])
print("D=M", file=args["output"])
print("@LCL", file=args["output"])
print("M=D", file=args["output"])
# Return
print("@13", file=args["output"])
print("AM=M-1", file=args["output"])
print("A=M", file=args["output"])
print("0;JMP", file=args["output"])
|
print('-'*20)
print('Gerador de PA: ')
p = int(input('Primeiro termo: '))
r = int(input('Razao da PA: '))
amais = 10
total = 0
termo = p
c = 1
while amais != 0:
total += amais
while c <=total:
print('{} - '.format(termo), end='')
termo += r
c += 1
amais = int(input('Quantos termo a mais deseja ver: '))
|
n = int(input('Digite um numero: '))
c = 1
print('O numero escolhido foi: {}. Vamos ver a sua tabuada:'.format(n))
while c < 10:
print('{} x {} = {}'.format(n, c, c * n))
c += 1
for i in range (10):
print('{} x {} = {}'.format(n, i, i * n))
|
l = float(input('Digite a largura: '))
c = float(input('Digite o comprimento: '))
area = l * c
litros = area/2
print('Com a largura de {} e o comprimento de {} a area será de {}.'.format(l, c, area))
print('Para pintar uma area de {:.2f} será necessario {:.2f} litros de tinta.'.format(area, litros))
|
grupo = [[], []]
for p in range(0, 7):
n = int(input('Digite um valor: '))
if n % 2 == 0:
grupo[0].append(n)
if n % 2 == 1:
grupo[1].append(n)
print(f'A lista com numeros pares foi {sorted(grupo[0])}')
print(f'A lista com numeros impares foi {sorted(grupo[1])}')
|
s = 0
n = int(input('Digite um numero para saber se ele é primo: '))
for x in range(1, n + 1):
if n % x == 0:
s += 1
if s == 2:
print('O numero {} é Primo'.format(n))
else:
print('O numero {} nao é primo'.format(n))
|
contador = 0
total = 0
res = ''
maior = 0
menor = 0
while res != "N":
n = int(input('Digite um valor: '))
res = str(input('Deseja continuar? [s/n] ')).strip().upper()[0]
contador += 1
total += n
if contador == 1:
maior = menor = n
else:
if n > maior:
maior = n
if n < menor:
menor = n
media = total/contador
print('A quantidade de numeros foi {}'.format(contador))
print('A media entre os numeros foi {:.2f}'.format(media))
print('O maior numero digitado foi {}'.format(maior))
print('O menor numero digitado foi {}'.format(menor))
|
something = input('Digite alguma coisa para ser avaliada: ')
print('O tipo primitivo desse valor é', type(something))
print('So tem espaco:', something.isspace())
print('É um numero: ', something.isnumeric())
print('É alfabetico: ', something.isalpha())
print('É alfanumerico:', something.isalnum())
print('Está maiscula ', something.isupper())
print('Está minuscula ', something.islower())
print('Está capitalizada ', something.istitle())
|
import random
computador = 0
user = int(input('Digite um numero inteiro e tente adivinhar o numero que o computador pensou de 0 a 5: '))
while computador != user:
computador = random.randint(0, 5)
user = int(input('Voce perdeu, digite novamente para tentar acertar!'))
print('Acertou voces pensaram no {}'.format(computador))
|
s = 0
c = 0
contador = 0
# caso queria tirar a subtracao 999 basta adicionar antes do while
# c = int(input('Digite um numero: [999 para parar] '))
while c != 999:
c = int(input('Digite um numero: [999 para parar] '))
contador+= 1
s+=c
print('O total de numeros digitados foi {}'.format(contador-1))
print('A soma dos numeros digitados foi {}'.format(s - 999))
|
reais = float(input('Quantos reais R$ voce tem na carteira: '))
dolar = reais / 3.27
print('Com R${:.2f} voce conseguirá comprar {:.2f} USD'.format(reais, dolar))
|
# Perceptron.py
import numpy as np
class Perceptron(object):
def __init__(self, no_of_inputs, threshold=100, learning_rate=0.01):
self.threshold = threshold
self.learning_rate = learning_rate
self.weights = np.zeros(no_of_inputs + 1)
self.errors = [0]
self.squareError= [0]
def predictTroll(self, inputs):
return np.dot(inputs, self.weights[1:]) + self.weights[0]
def predict(self, inputs):
summation = np.dot(inputs, self.weights[1:]) + self.weights[0]
if summation > 0:
activation = 1
else:
activation = 0
return activation
def train(self, training_inputs, labels):
for _ in range(self.threshold):
error = 0
squareError = 0
for inputs, label in zip(training_inputs, labels):
prediction = self.predict(inputs)
self.weights[1:] += self.learning_rate * (label - prediction) * inputs
self.weights[0] += self.learning_rate * (label - prediction)
error = error + abs(label - prediction)
squareError = error + (label - prediction)^2
self.errors.append(str(error))
self.squareError.append(str(error))
def getWeights(self):
return self.weights
def getSquareError(self):
return self.squareError
def getErrors(self):
return self.errors
|
from SecondSem.CG.Lab_03.src.Sorter import Sorter
import math
class GiftWrap2D:
def __init__(self, points):
self.length = len(points)
self.points = points
def getMinYPoint(self):
index = 0
minY = self.points[0][1]
minPoint = self.points[0]
for i in range(1, self.length):
if (self.points[i][1] < minY):
index = i
minY = self.points[i][1]
minPoint = self.points[i]
return minPoint, index
def calculateAngle(self, point, center):
y = (point[1]-center[1])
x = (point[0]-center[0])
angle = math.atan2(y, x)
if(angle < 0):
angle += 2 * math.pi
# if(x == 0 and y == 0):
# return 7888
# if (x == 0 and y > 0):
# angle = angle + math.pi/2
# elif (x == 0 and y < 0):
# angle -= math.pi/2
# elif(x < 0 and y >= 0):
# angle += 2 * math.pi
# elif(x < 0 and y < 0):
# angle -= 2 * math.pi
print(center, point, x, y, angle)
return angle
def getMinSlopePoint(self, center, points):
return sorted(
points, key=lambda point: self.calculateAngle(point, center))
def getHull(self):
# exit(self.getMinSlopePoint((0, 3),
# [(0, 3), (3, 3), (4, 4), (0, 0), (1, 1), (1, 2), (3, 1), (2, 2)]))
if (self.length < 3):
return "Not Possible."
minPoint, index = self.getMinYPoint()
vertices = [minPoint]
points = self.points.copy()
points.pop(index)
i = 1
while i < len(self.points):
points = self.getMinSlopePoint(minPoint, self.points)
print(points, minPoint)
if points[1] != minPoint:
minPoint = points[1]
points.pop(0)
vertices.append(minPoint)
else:
break
i += 1
return vertices[0:4]
|
import string
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
if not S:
return []
res = ['']
for i in S:
temp = []
for j in res:
if i in string.ascii_letters:
temp.append(j + i.upper())
temp.append(j + i.lower())
else:
temp.append(j + i)
res = temp
return res
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name: {self.name}\nAge: {self.age}"
def print(self):
print(self.__str__())
class Staff(Person):
def __init__(self, name, age, job_title, salary):
super().__init__(name, age)
self.job_title = job_title
self.salary = salary
def calculate_annual_income(self):
return self.salary * 12
def print(self):
print(f"{super().__str__()}\nJob Title: {self.job_title}\nAnnual Income: {self.calculate_annual_income()}")
print("==========================")
person = Person("John", 30)
person.print()
print("==========================")
staff = Staff("Max", 40, "Farmer", 3000)
staff.print()
print("==========================")
staff2 = Staff("Brian", 25, "Jr Programmer", 2500)
staff2.print()
print("==========================")
|
import sqlite3
connection = sqlite3.connect("../resources/dummy.db")
cursor = connection.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS PERSON
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL);
''')
# cursor.execute("INSERT INTO PERSON ('ID', 'NAME', 'AGE') VALUES ('1', 'John', 30), ('2', 'Max', 25);")
# connection.commit()
cursor.execute("SELECT * FROM PERSON")
rows = cursor.fetchall()
for row in rows:
print(f"ID: {row[0]} Name: {row[1]} Age: {row[2]}")
connection.close()
|
def divide(x, y):
try:
return x / y
except ZeroDivisionError:
print("cannot divide by zero")
except TypeError:
print("Incorrect type")
except:
pass
def open_file(file_path):
try:
f = open(file_path, "r")
except FileNotFoundError:
print(f"{file_path} not found")
else:
f.close()
divide(10, 0)
divide("10", "10")
open_file("abc.txt")
try:
_ = int(input("Enter a number: "))
except ValueError:
print('You are supposed to enter a number.')
|
# -*- coding: utf-8 -*-
"""
nome: prog5.py
@author: auro
"""
#este programa converte milimetros em metros
x = float(input("digite um valor em milimetros: "))
#calculo
metros = x / 1000
print("o valor em metros eh: ", metros, "m")
|
#
# CS6613 Artificial Intelligence
# Project 1 Mini-Checkers Game
# Shang-Hung Tsai
#
import tkinter
from CheckerGame import *
class BoardGUI():
def __init__(self, game):
# Initialize parameters
self.game = game
self.ROWS = 6
self.COLS = 6
self.WINDOW_WIDTH = 600
self.WINDOW_HEIGHT = 600
self.col_width = self.WINDOW_WIDTH / self.COLS
self.row_height = self.WINDOW_HEIGHT / self.ROWS
# Initialize GUI
self.initBoard()
def initBoard(self):
self.root = tkinter.Tk()
self.c = tkinter.Canvas(self.root, width=self.WINDOW_WIDTH, height=self.WINDOW_HEIGHT,
borderwidth=5, background='white')
self.c.pack()
self.board = [[0]*self.COLS for _ in range(self.ROWS)]
self.tiles = [[None for _ in range(self.COLS)] for _ in range(self.ROWS)]
# Print dark square
for i in range(6):
for j in range(6):
if (i + j) % 2 == 1:
self.c.create_rectangle(i * self.row_height, j * self.col_width,
(i+1) * self.row_height, (j+1) * self.col_width, fill="gray", outline="gray")
# Print grid lines
for i in range(6):
self.c.create_line(0, self.row_height * i, self.WINDOW_WIDTH, self.row_height * i, width=2)
self.c.create_line(self.col_width * i, 0, self.col_width * i, self.WINDOW_HEIGHT, width=2)
# Place checks on the board
self.updateBoard()
# Initialize parameters
self.checkerSelected = False
self.clickData = {"row": 0, "col": 0, "checker": None}
# Register callback function for mouse clicks
self.c.bind("<Button-1>", self.processClick)
# make GUI updates board every second
self.root.after(1000, self.updateBoard)
def startGUI(self):
self.root.mainloop()
def pauseGUI(self):
self.c.bind("<Button-1>", '')
def resumeGUI(self):
self.c.bind("<Button-1>", self.processClick)
# Update the positions of checkers
def updateBoard(self):
if self.game.isBoardUpdated():
newBoard = self.game.getBoard()
for i in range(len(self.board)):
for j in range(len(self.board[0])):
if self.board[i][j] != newBoard[i][j]:
self.board[i][j] = newBoard[i][j]
self.c.delete(self.tiles[i][j])
self.tiles[i][j] = None
# choose different color for different player's checkers
if newBoard[i][j] < 0:
self.tiles[i][j] = self.c.create_oval(j*self.col_width+10, i*self.row_height+10,
(j+1)*self.col_width-10, (i+1)*self.row_height-10,
fill="black")
elif newBoard[i][j] > 0:
self.tiles[i][j] = self.c.create_oval(j*self.col_width+10, i*self.row_height+10,
(j+1)*self.col_width-10, (i+1)*self.row_height-10,
fill="red")
else: # no checker
continue
# raise the tiles to highest layer
self.c.tag_raise(self.tiles[i][j])
# tell game logic that GUI has updated the board
self.game.completeBoardUpdate()
# make GUI updates board every second
self.root.after(1000, self.updateBoard)
# this function checks if the checker belongs to the current player
# if isPlayerTurn() returns True, then it is player's turn and only
# postive checkers can be moved. Vice versa.
def isCurrentPlayerChecker(self, row, col):
return self.game.isPlayerTurn() == (self.board[row][col] > 0)
# callback function that process user's mouse clicks
def processClick(self, event):
col = int(event.x // self.col_width)
row = int(event.y // self.row_height)
# If there is no checker being selected
if not self.checkerSelected:
# there exists a checker at the clicked position
# and the checker belongs to the current player
if self.board[row][col] != 0 and self.isCurrentPlayerChecker(row, col):
self.clickData["row"] = row
self.clickData["col"] = col
self.clickData["color"] = self.c.itemcget(self.tiles[row][col], 'fill')
# replace clicked checker with a temporary checker
self.c.delete(self.tiles[row][col])
self.tiles[row][col] = self.c.create_oval(col*self.col_width+10, row*self.row_height+10,
(col+1)*self.col_width-10, (row+1)*self.row_height-10,
fill="green")
self.checkerSelected = True
else: # no checker at the clicked postion
return
else: # There is a checker being selected
# First reset the board
oldrow = self.clickData["row"]
oldcol = self.clickData["col"]
self.c.delete(self.tiles[oldrow][oldcol])
self.tiles[oldrow][oldcol] = self.c.create_oval(oldcol*self.col_width+10, oldrow*self.row_height+10,
(oldcol+1)*self.col_width-10, (oldrow+1)*self.row_height-10,
fill=self.clickData["color"])
# If the destination leads to a legal move
self.game.move(self.clickData["row"], self.clickData["col"],row, col)
self.checkerSelected = False
|
def read_nums(filename):
with open(filename) as f:
content = f.readlines()
content = [line.strip() for line in content]
return content
def main():
nums = read_nums('./nums.txt')
carry = 0
total = ''
index = len(nums[0]) - 1
while index >= 0:
cur = carry % 10
carry = carry // 10
for num in nums:
cur += int(num[index])
carry += cur // 10
total = str(cur % 10) + total
index -= 1
total = str(carry) + total
print(total)
if __name__ == '__main__':
main()
|
#! /usr/bin/python
import unittest
class TestBasicString(unittest.TestCase):
testString = "APRIL is the cruellest month, breeding"
def test_concat(self):
result = "Tonle " + "Sap"
self.assertEqual(result, "Tonle Sap")
def test_repeat(self):
result = "Ha" * 5 + "!"
self.assertEqual(result, "HaHaHaHaHa!")
def test_slice(self):
self.assertEqual(TestBasicString.testString[4], 'L')
self.assertEqual(TestBasicString.testString[:5], "APRIL")
self.assertEqual(TestBasicString.testString[6:], "is the cruellest month, breeding")
self.assertEqual(TestBasicString.testString[13:22], "cruellest")
def test_slice_negative(self):
self.assertEqual(TestBasicString.testString[-4], 'd')
self.assertEqual(TestBasicString.testString[-8:], "breeding")
self.assertEqual(TestBasicString.testString[:-10], "APRIL is the cruellest month")
def test_slice_invariant(self):
self.assertEqual(TestBasicString.testString[:10] + TestBasicString.testString[10:], TestBasicString.testString)
def test_get_length(self):
self.assertEqual(len("12345"), 5)
if __name__ == '__main__':
unittest.main()
|
#primer ejercicio
a = int(input('Ingrese el primer número entero : '))
b = int(input('Ingrese el segundo número entero : '))
def numeros (a,b):
if a > b :
print (f'{a} es el número mayor')
elif b > a :
print (f'{b} es el número mayor')
else:
print ('Los números ingresados son iguales')
numeros (a,b)
#segundo ejercicio
def mostrarLista (lista):
for elemento in lista :
print (elemento)
listaNombres = ['Luis', 'Maria', 'Angela', 'Valentina', 'Rodrigo']
mostrarLista (listaNombres)
#tercer ejercicio
peso = float(input('Por favor ingresa tu peso en Kg : '))
altura = float(input('Por favor ingresa tu altura en metros : '))
def IMC (peso, altura):
return round((peso /(altura ** 2)), 3)
print (IMC(peso, altura))
#cuarto ejercicio
class Persona:
def __init__(self, idin,
nombrein, pesoin, alturain, sexoin):
self.id = idin
self.nombre = nombrein
self.peso = pesoin
self.altura = alturain
self.sexo = sexoin
class Estudiante (Persona):
def __init__ (self, semestre, universidad, carrera, idin, nombrein, pesoin, alturain, sexoin):
Persona.__init__(self,idin,nombrein, pesoin, alturain, sexoin)
self.semestre = semestre
self.universidad = universidad
self.carrera = carrera
def materia (self):
print (f'Hola soy {self.nombre} y voy a estudiar Física')
Laura = Estudiante ('Tercer', 'CES', 'Biomédica', 1004691625, 'Laura', 50, 1.59, 'F')
print (Laura.nombre)
print (Laura.id)
print (Laura.peso)
print (Laura.altura)
print (Laura.sexo)
print (f'Hola soy {Laura.nombre} , estoy en {Laura.semestre} semestre de {Laura.carrera} en la Universidad {Laura.universidad}')
Laura.materia()
|
#Cree la clase Torta con atributos forma, sabor, altura, también tendrá una función donde muestre todos sus atributos
class Torta ():
def __init__ (self,formaIn, saborIn,alturaIn):
self.forma = formaIn
self.sabor = saborIn
self.altura = alturaIn
def mostrar_atributos(self):
print (f'Es una torta de forma {self.forma} , de sabor {self.sabor} y de una altura {self.altura}cm')
cake = Torta ('redonda', 'chocolate',20)
cake.mostrar_atributos()
#ESTUDIANTE
class Estudiante ():
def __init__ (self, nombreIn, edadIn,idIn, carreraIn, semestreIn):
self.nombre = nombreIn
self.edad = edadIn
self.id = idIn
self.carrera = carreraIn
self.semestre = semestreIn
def estudiar_materia (self, materia,tiempo) :
print (f'Hola soy {self.nombre} y tengo que estudiar : {materia} por {tiempo} horas')
estudent = Estudiante('pepe', 23, 123789, 'Sistemas', 4)
estudent.estudiar_materia('física',12)
#imc
class Nutricionista():
def __init__ (self, nombreIn, edadIn,idIn, universidadIn):
self.nombre = nombreIn
self.edad = edadIn
self.id = idIn
self.universidad = universidadIn
def calcular_imc(self, peso,estatura) :
return round ((peso/estatura**2), 3)
aleja = Nutricionista('Aleja', 27,13024789,'CES')
print (f'Hola soy {aleja.nombre} y tengo {aleja.edad} años, mi id es {aleja.id} y estudio en Universidad {aleja.universidad}')
print (aleja.calcular_imc ( 80 , 1.67))
#Cree una clase Canguro que tenga los atributos edad, id, nombre
class Canguro():
def __init__ (self, nombreIn, edadIn,idIn):
self.nombre = nombreIn
self.edad = edadIn
self.id = idIn
def saltar (self, saltos) :
for i in range(saltos):
print (f'El canguro {self.nombre} ha dado {i+1} saltos')
jack = Canguro('Jack', 12, 134098)
jack.saltar(12)
#Instrumento
class Violin():
def __init__ (self, marca, color, material, tipo):
self.marca = marca
self.color = color
self.material = material
self.tipo = tipo
def interpetar (self, cancion):
print (f'Vamos a escuchar : {cancion}')
instrumento = Violin ('yamaha', 'café', 'madera', 'acustico')
print (f'El violin es marca {instrumento.marca}, color {instrumento.color}, hecho de {instrumento.material} y {instrumento.tipo}')
instrumento.interpetar('Recuérdame')
|
#-----Numeroteclado-----#
preguntaNumero = "Ingrese un número entero o digite cero para finalizar y realizar la sumatoria : "
numeroIngresado = int(input(preguntaNumero))
suma = 0
while(numeroIngresado != 0) :
suma += numeroIngresado
numeroIngresado = int(input(preguntaNumero))
print(f"Este es el resultado de la sumatoria {suma}")
#-----2numerosenteros-----#
preguntaNumero1 = "Por favor ingresa el primer número entero : "
preguntaNumero2 = "Por favor ingresa el segundo número entero : "
numeroIngresado1 = int(input(preguntaNumero1))
numeroIngresado2 = int(input(preguntaNumero2))
while(numeroIngresado2 <= numeroIngresado1) :
print ("Por favor digita un número mayor que el primero")
numeroIngresado2 = int(input(preguntaNumero2))
print (f"{numeroIngresado1} , {numeroIngresado2}")
#-----Numeros+Grandes----#
preguntaNumeroM = "Por favor ingresa un número entero : "
preguntaNumeroN = "Ahora ingresa un número mayor al anterior : "
numeroIngresadoM = int(input(preguntaNumeroM))
numeroIngresadoN = int(input(preguntaNumeroN))
while(numeroIngresadoN > numeroIngresadoM) :
numeroIngresadoM = numeroIngresadoN
numeroIngresadoN = int(input(preguntaNumeroN))
print("Has ingresado un número menor o igual al anterion, fin.")
#-----MontosCompras----#
total = 0
monto = float(input("Monto de una venta: $"))
while monto != 0 :
if monto < 0 :
print("Monto no válido.")
else:
total += monto
monto = float(input("Monto de una venta: $"))
if total > 1000:
total -= total * 0.1
print("Monto total a pagar: $", total)
|
#lista
def mostrarLista (lista):
for elemento in lista :
print (elemento)
listaEdades = [20,18,18,18,21,20,18,18]
mostrarLista (listaEdades)
#mayor, menor, promedio
listaD = [20000,30000,4000,2500,1000,7600]
mayor = max (listaD)
menor = min (listaD)
totalSuma = 0
for elemento in listaD :
totalSuma += elemento
promedio= round(totalSuma/len(listaD))
print ('El mayor ingreso fue de : ', mayor)
print ('El menor ingreso fue de : ', menor)
print ('El promedio de ingresos tiene un valor total de : ', promedio)
#salude n veces
def saludo (n = 0):
print ('Hola, ' * n)
saludo (15)
#numeros pares
def paresLista(lista):
pares = []
for elemento in lista:
if elemento % 2 == 0 :
pares.append (elemento)
return pares
numeros = [63, 24, 85, 16, 18, 25, 3, 2, 24]
numerosPares = paresLista(numeros)
print (numerosPares)
#numeros > 24
def mayores24 (lista):
m24 = []
for elemento in lista:
if elemento > 24 :
m24.append (elemento)
return m24
numeros = [63, 24, 85, 16, 18, 25, 3, 2, 24]
numerosm24 = mayores24(numeros)
print (numerosm24)
#IMC
peso = float(input('Por favor ingresa tu peso en Kg : '))
altura = float(input('Por favor ingresa tu altura en metros : '))
def calcularIMC (peso, altura):
return (peso / (altura ** 2))
print (calcularIMC(peso, altura))
#despedida
def despedida ():
print ('Gracias por usar el codigo, hasta pronto!')
despedida ()
|
import unittest
from user_file import User, Credentials
import pyperclip
class Test(unittest.TestCase):
'''
Test class that defines test cases for the user class
Args:
unittest.TestCase: TestCase class helping to create test cases
'''
def setUp(self):
'''
set up method to run befor each test cases.
'''
self.new_user = User('Tamminga-Givondo','123456007psych')# creates user object
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_user.username, "Tamminga-Givondo")
self.assertEqual(self.new_user.password,'123456007psych')
def tearDown(self):
'''
tearDown method that does clean up after each test case has run.
'''
User.user_list=[]
def test_save_username(self):
'''
test_save_username test case to test if the username object is saved into
the user list
'''
self.new_user.save()
self.assertEqual(len(User.user_list),1)
def test_save_multiple_username(self):
'''
test_save_multiple username test case is to test if multiple username objects are saved into the user list
'''
self.new_user.save()
test_save = User("Budds",'5432juan')
test_save.save()
self.assertEqual(len(User.user_list),2)
def test_delete_username(self):
'''
test_delete_user to test if it's possible to remove a user from user_list
'''
self.new_user.save()
test_user = User("Tamminga","000")# adds a contact
test_user.save()
self.new_user.delete()
self.assertEqual(len(User.user_list),1)
def test_user_exists(self):
'''
Test_find_by_username is used to test if it's possible to find an existing username
'''
self.new_user.save()
test_user = User('Tamminga','0000') # new user
test_user.save()
exist_user = User.user_exists('Tamminga')
self.assertTrue(exist_user)
def test_user_display (self):
'''
Test_user_display is to test if the display is working accordingly
'''
self.assertEqual(User.display_user(),User.user_list)
class TestCredentials(unittest.TestCase):
'''
Test class that defines test cases for the Credential class
Args:
unittest.TestCase: TestCase class helping to create test cases
'''
def setUp(self):
'''
Set up method to run before each test cases.
'''
self.new_user = Credentials('Github','budds300','opensaysme') # create new credentials
Credentials.credential_list = []
def tearDown(self):
'''
clears tests after a test has been run
'''
Credentials.credential_list=[]
def test_init_credentials(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_user.account_name,"Github")
self.assertEqual(self.new_user.username,"budds300")
self.assertEqual(self.new_user.password,"opensaysme")
def test_save_credentials(self):
'''
test_save_credentials test case to test if the credentials object has been saved into the credentials list
'''
self.new_user.save_credential()
self.assertEqual(len(Credentials.credential_list),1)
def test_save_multiple_credentials(self):
'''
'''
self.new_user.save_credential()
new_credentials = Credentials('Facebook','Tamminga','knockknock')
new_credentials.save_credential()
self.assertEqual(len(Credentials.credential_list),2)
def test_delete_credentials (self):
'''
tests if we can delete a credential from our credentials list
'''
self.new_user.save_credential()
new_credentials=Credentials('Google','budds300','whatdoyouthink?')
new_credentials.save_credential()
self.new_user.delete_credential()
self.assertEqual(len(Credentials.credential_list),1)
def test_find_credentials_by_username(self):
'''
to check if we can find a credential by the account name and display more information about it
'''
self.new_user.save_credential()
new_credentials=Credentials('Google','budds300','whatdoyouthink?')
new_credentials.save_credential()
found_credentials = Credentials.find_account_name("Google")
self.assertEqual(found_credentials.password,new_credentials.password)
def test_exists_credentials (self):
'''
checks if we can return a boolean if we cannot find the credentials
'''
self.new_user.save_credential()
new_credentials=Credentials('Google','budds300','whatdoyouthink?')
new_credentials.save_credential()
existing_credentials= Credentials.credential_exist("Google")
self.assertTrue(existing_credentials)
def test_display_credentials (self):
'''
returns a list of all credentials saved
'''
self.assertEqual(Credentials.display_credential(),Credentials.credential_list)
if __name__ == '__main__':
unittest.main()
|
"""
ハングマンゲーム(単語当てゲーム)
回答者が1文字ずつ文字を入力して、最終的に単語を当てる。
単語に含まれていない文字を入力した場合、変数stagesの絵を1パーツ毎表示する。
最終的に絵が全て表示されたら負け、絵が表示される前に単語を当てられたら勝ち。
word : 答える単語
wrong : 間違った回数
rletters : 答えを1文字ずつ分けたリスト。答えなければならない残りの文字を記憶させておく
bord : rlettersと同様のリスト。回答者に見せるヒント用
"""
import random
def hangman(word):
wrong = 0
stages = ["",
"_______ ",
"| ",
"| | ",
"| o ",
"| /|\ ",
"| / \ ",
"| "
]
rletters = list(word)
# 最初は文字数分アンダースコアを表示させる
bord = ["_"] * len(word)
win = False
print("ハングマン、スタート")
while wrong < len(stages) - 1:
print("\n")
msg = "1文字入力してください。"
char = input(msg)
# 正解
if char in rletters:
char_index = rletters.index(char)
# 変数bordは回答者に表示させるのでindex値を使って正しい文字に置き換え
bord[char_index] = char
# 変数rlettersは正解した文字を$マークに置き換える。同じ文字が複数あった場合indexメソッドが正常に動作しないため
rletters[char_index] = '$'
# 不正解
else:
wrong += 1
print(" " .join(bord))
e = wrong + 1
print("\n" .join(stages[0:e]))
if "_" not in bord:
print("あなたの勝ちです")
print(" " .join(bord))
win = True
break
if not win:
print("\n" .join(stages[0:wrong + 1]))
print("あなたの負けです")
print("正解は {}." .format(word))
characters = ["captainamerica",
"ironman",
"hulk",
"hawkeye",
"thor",
]
list_index = random.randint(0,4) # index値をランダムで生成
answer = characters[list_index]
hangman(answer)
|
from selenium.webdriver.support.ui import Select
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(executable_path='C:/Users/user/PycharmProjects/selenium_python/driver/chromedriver.exe')
driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407")
element = driver.find_element(By.ID,'RESULT_RadioButton-9')
element1 = Select(element)
#approach 1 using visible text
element1.select_by_visible_text("Morning")
#approach 2 using index
element1.select_by_index(2)
#Approach 3 select by value
element1.select_by_value('Radio-2')
# count number of elements in dropdown
print(len(element1.options))
#capture all the options
var_store = element1.options
for item in var_store:
print(item.text)
|
#assignment-1
'''
a = 'AbcdefghIjk'
b = list(a.lower())
print(b)
count = 0
for i in b:
if i =='a' or i == 'e' or i =='i' or i=='o' or i=='u':
print(b.index(i), i)
'''
a = 'HArsha PatnAIk'
b = list(a.lower())
print(b)
count_a, count_i = 0 , 0
for i in b:
if i =='a':
count_a +=1
print('count of a: {}'.format(count_a))
for i in b:
if i =='i':
count_i +=1
print('count of i: {}'.format(count_i))
#assignment-2
a = 'hello world happy birthday'
b = a.split( )
print(b)
b.reverse()
print(b)
#assignment-3
a = [1,2,3,3,2,4]
a.sort()
print(a)
b = []
for i in a:
if i not in b:
b.append(i)
print(b)
|
import numpy as np
from scipy import ndimage
import os
import random
import glob
def toOnehot(array, num_classes=10):
"""
Takes a 1 dimensional array and returns a 2 dimensional array of one-hots with the dimension 0 with the same size of input array and dimension 1 with the size of `num_of_classes`.
Inputs:
- array: 1D array in which each element is a class index.
- num_classes: number of classes that each element of `array` falls into.
Outputs:
- A 2D array of one-hots.
"""
count = len(array)
onehot_array = np.zeros((count, num_classes), np.int8)
onehot_array[np.arange(count), array] = 1
return onehot_array
def showMultipleArraysHorizontally(array, labels=None, max_per_row=10):
"""
Takes an array with the shape [number of images, width, height] and shows the images in rows.
Inputs:
- array: a 3 dimensional array with the shape: [number of images, width, height]
- labels: a 1 dimensional array with the length of number of images in which each element is the label of corresponding image in input `array`.
- max_per_row: maximum number of images in each row before going to the next row.
"""
from matplotlib.pyplot import figure, imshow, axis
# from matplotlib.image import imread
# from random import sample
# from matplotlib.pyplot import matshow
import matplotlib.pyplot as plt
fig = figure()
number_of_images = len(array)
rows = np.floor(number_of_images / max_per_row)+1
columns = min(number_of_images, max_per_row)
for i in range(number_of_images):
ax = fig.add_subplot(rows, columns, i + 1)
if labels is not None:
ax.set_title(labels[i])
plt.imshow(array[i], cmap=plt.get_cmap('gray'))
axis('off')
plt.show()
def dataGenerator(batch_size, file_name):
file_handle = open(file_name, "rb")
while True:
# get data array
try:
data = np.load(file_handle)
# if reached end of file
except IOError:
# go to the beginning
file_handle.seek(0)
# and try loading again
data = np.load(file_handle)
# get batches
number_of_datapoints = data.shape[0]
full_batches = number_of_datapoints//batch_size
for batch_count in range(0, full_batches):
batch_data = data[batch_count*batch_size:(batch_count+1)*batch_size]
yield batch_data
def arrayToFile(file_name, array, batch_size):
file_handle = open(file_name, "wb")
number_of_data = array.shape[0]
print('Saving %d data samples into "%s" ...' %(number_of_data,file_name))
# iterate over data in big batches
for batch_start in range(0, number_of_data, batch_size):
np.save(file_handle, array[batch_start: batch_start + batch_size])
# process status
completion_percentil = 100 * \
min(batch_start + batch_size, number_of_data) / number_of_data
print("Compeleted %%%d" % completion_percentil)
# always close the file
file_handle.close()
def imageToArray(file_name):
return ndimage.imread(file_name).astype(float)
def fileListToArray(file_list):
image_data = imageToArray(file_list[0])
dataset = np.ndarray(shape=(len(file_list), image_data.shape[0], image_data.shape[1]),
dtype=np.float32)
dataset[0, :, :] = image_data
for i in range(1, len(file_list)):
try:
dataset[i, :, :] = imageToArray(file_list[i])
except IOError:
pass
return dataset
def ls(directory, extension='*.*'):
return glob.glob(os.path.join(directory, extension))
def shuffleFiles(array):
return random.sample(array, len(array))
def shuffleMultipleArrays(list_of_arrays):
assert type(list_of_arrays[0]) == list
indx = np.random.permutation(len(list_of_arrays[0]))
return [array[indx] for array in list_of_arrays]
def scaleData(array, depth):
"""
Scales values of elements in an array that range between [0, depth] into an array with elements between [-0.5, .05]
Inputs:
- array: a numpy array with elements between [0, depth]
- depth: depth of values (e.g. maximum value that any element is allowed to have)
Output:
- An array with the same shape of input array with elements between [-0.5, 0.5]
"""
return array / depth - .5
|
# Given a non-empty array of positive integers arr[]. Write a program to find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
# Example 1
# Input: arr[] = [1, 6, 11, 6]
# Output: true
# Explanation: The array can be partitioned as [6, 6] and [1, 11].
# Example 2
# Input: arr[] = [2, 6, 7]
# Output: false
# Explanation: The array cannot be partitioned into equal sum sets
def check(arr):
if len(arr) == 0:
return False
sum = 0
for elem in arr:
sum += elem
if sum % 2 != 0:
return False
return is_contain_subset_of_sum_dynamic_programming(arr, sum // 2)
# using dynamic programming O(N*M)
# when N is the size of the number list and M is sum of the elements
def is_contain_subset_of_sum_dynamic_programming(arr, wanted_sum):
n = len(arr)
m = wanted_sum + 1
dp = [[False for j in range(m)] for i in range(n)]
for i in range(n):
num = arr[i]
for j in range(m):
if i == 0:
if arr[i] == j:
dp[i][j] = True
else:
exist_subset_with_num = dp[i - 1][j - num]
exist_subset_without_num = dp[i - 1][j]
if exist_subset_with_num or exist_subset_without_num:
dp[i][j] = True
return dp[n - 1][m - 1]
# Using brute force approach O(2^N)
def is_contain_subset_of_sum_brute_force(arr, wanted_sum):
if len(arr) == 1:
return arr[0] == wanted_sum
first = arr[0]
with_first = is_contain_subset_of_sum_brute_force(arr[1:],
wanted_sum - first)
if with_first:
return True
without_first = is_contain_subset_of_sum_brute_force(arr[1:], wanted_sum)
if without_first:
return True
return False
|
# File with sample functions.
def sum(x, y): # sums up two numbers
""" Adds two numbers.
Returns the sum."""
return x + y
# Returns the product.
def mul(x, y): # multiplies two numbers
# z is a local variable
z = x * y
return z
def print_pretty(a):
print("The result is {:.3f}.".format(a))
# test these functions:
print_pretty(mul(10, sum(3, 5)))
|
# DWAYNE FRASER
############## Problem 4. Function Visualization ##############################
import math
import numpy as np
import matplotlib.pyplot as plt
# Defines Plot Function
def plot_function(fun_str, domain, ns):
# Computes x-list
interval = (domain[1] - domain[0]) / ns
xs = []
for i in range(ns):
xs.append(domain[0] + interval * i)
# Computes y-list
ys = []
for x in xs:
y = eval(fun_str)
ys.append(y)
# Displays Values
print("x y")
print("------------------")
for i in range(ns):
print('{:.3f} {:.3f}'.format(xs[i],ys[i]))
# Displays Graph
plt.xlabel('X')
plt.ylabel('y')
plt.title(fun_str)
plt.plot(xs, ys, color='blue', marker= 'o')
plt.show()
# Gets User Input
fun_str = input('Enter function with variable x: ')
ns = int(input('Enter number of samples: '))
xmin = float(input('Enter xmin: '))
xmax = float(input('Enter xmax: '))
domain = xmin, xmax
plot_function(fun_str, domain, ns)
|
# TASK:
# Шоколадка имеет вид прямоугольника, разделенного на n×m долек. Шоколадку можно один
# раз разломить по прямой на две части. Определите, можно ли таким образом отломить от
# шоколадки часть, состоящую ровно из k долек. Программа получает на вход три числа: n, m, k
# и должна вывести YES или NO.
# SOLUTION:
import sys
n = int(sys.argv[1])
m = int(sys.argv[2])
k = int(sys.argv[3])
# Overall area must be bigger than parts number
if (n * m) < k:
print("NO")
elif k % n == 0 or k % m == 0: # At least one dimension must divide with remainder equal to 0
print("YES")
else:
print("NO")
|
# TASK:
# два цілих невід'ємних числа (0<=a1<=a2<=999999) - аргументи командного
# рядка.
# Результат роботи: кількість "щасливих квитків", чиї номери лежать на проміжку від a1 до
# a2 включно.
# SOLUTION:
import sys
a1 = int(sys.argv[1])
a2 = int(sys.argv[2])
# Initializing variables
input_str = ''
counter = 0
# Including last value in loop
for i in range(a1, a2+1):
input_str = str(i) # convert and working with strings
zeros = 6 - len(input_str) # calculating number of zeros to add
input_str = zeros * "0" + input_str # adding them
# checking if sum of first 3 numbers is equal to second
if (int(input_str[0]) + int(input_str[1]) + int(input_str[2])) == (int(input_str[3]) + int(input_str[4]) + int(input_str[5])):
counter = counter + 1
print(counter) # print overall quantity of such "happy tickets"
|
class A():
def sum(self, a,b):
self.c = a+b
print (self.c)
class B():
def sum(self, a,b):
self.c = a-b
print (self.c)
class C(B,A):
def sum(self,a,b):
self.c = a*b
print (self.c)
obj1 = C()
obj1.sum(10,20)
|
#from collections import namedtuple
import collections
emp1 =collections.namedtuple("Learntek", 'name age empid', rename= False ) # creating own data type
list1 = ['shankar',28, 123456]
record1 = emp1._make(list1)
print (record1)
print (record1.name)
print (record1.age)
print (record1.empid)
|
import re
p1 = "wit+h"
text = "Peace begin wittth with smile "
m1 = re.findall(p1, text)
print (m1)
print ("Total number of occurrence ", len(m1))
'''
if m1:
print (m1.group())
print ("start at ",m1.start())
print ("Ends at ", m1.end())
'''
|
str1 = "Learning Python in Learntekeee"
i=0
for each in str1:
if "e" == each:
i= i+1
print ("e repeated %d times"%(i))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.