text stringlengths 37 1.41M |
|---|
import pandas as pd
df1_title = ['name','id','phone']
df2_title = ['name','sex','age']
df3_title = ['name','grade','score']
count = 101
writer = pd.ExcelWriter('file_name.xlsx')
def generate_df1():
df1 = pd.DataFrame({df1_title[0]:[], df1_title[1]:[], df1_title[2]:[]})
for i in range (1, count):
df1 = df1.append({df1_title[0]:'content_of_1st_column', df1_title[1]:'content_of_2nd_column', df1_title[2]:'content_of_3rd_column'},ignore_index=True)
df1.to_excel(writer, sheet_name="sheet1", index=False)
def generate_df2():
df2 = pd.DataFrame({df2_title[0]:[], df2_title[1]:[], df2_title[2]:[]})
for i in range (1, count):
df2 = df2.append({df2_title[0]:'content_of_1st_column', df2_title[1]:'content_of_2nd_column', df2_title[2]:'content_of_3rd_column'},ignore_index=True)
df2.to_excel(writer, sheet_name="sheet2", index=False)
def generate_df3():
df3 = pd.DataFrame({df3_title[0]:[], df3_title[1]:[], df3_title[2]:[]})
for i in range (1, count):
df3 = df3.append({df3_title[0]:'content_of_1st_column', df3_title[1]:'content_of_2nd_column', df3_title[2]:'content_of_3rd_column'},ignore_index=True)
df3.to_excel(writer, sheet_name="sheet3", index=False)
generate_df1()
generate_df2()
generate_df3()
writer.save()
|
#Задание №1
# Поработайте с переменными, создайте несколько, выведите на экран,
# запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
print("Как тебя зовут?")
name = input()
print("Привет,", name)
print("Сколько тебе лет?")
age = int(input())
print("Когда у тебя день рождения?")
birthday = input()
print ("Спасиб!")
|
"""
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
import time
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务0:
短信记录的第一条记录是什么?通话记录最后一条记录是什么?
输出信息:
"First record of texts, <incoming number> texts <answering number> at time <time>"
"Last record of calls, <incoming number> calls <answering number> at time <time>, lasting <during> seconds"
"""
# sort by text time, reverse is False(default)
texts.sort(key = lambda x: time.strptime(x[2], '%d-%m-%Y %H:%M:%S'), reverse = False)
# get the first record
result_first_text = "First record of texts, {} texts {} at time {}".format(texts[0][0], texts[0][1], texts[0][2])
print( result_first_text )
# sort by call time, reverse is True
calls.sort(key = lambda x: time.strptime(x[2], '%d-%m-%Y %H:%M:%S'), reverse = True)
# get the first record
result_last_call = "Last record of calls, {} calls {} at time {}, lasting {} seconds".format(calls[0][0], calls[0][1], calls[0][2], calls[0][3])
print( result_last_call )
|
#Required Packages
from nltk import sent_tokenize
from spacy.lang.en import English
nlp = English()
tokenizer = nlp.Defaults.create_tokenizer(nlp)
#Split and Tokenize
def split_and_tokenize(text):
"""
Goal: Create a list of list of tokens from sentence(s).
Input:
- text: String containing >= 1 sentence
Output:
- List of list of tokens from sentence(s).
"""
#Split Sentences
sentences = sent_tokenize(text)
#Tokenize Each Sentence
all_tokens = []
for sentence in sentences:
#Internal List for Each Sentence
tokens = []
#Tokenize Sentence
tokenized = tokenizer(sentence)
for token in tokenized:
#Add to Internal List
tokens.append(str(token))
#Add Internal to Overall List
all_tokens.append(tokens)
return all_tokens
#Tokenize
def tokenize(sentence):
"""
Goal: Tokenize input text.
Input:
- sentence: String of text to tokenize via spacy
Output:
- List of tokens from input text
"""
#Token List
tokens = []
#Tokenize
tokenized = tokenizer(sentence)
for token in tokenized:
tokens.append(str(token))
return tokens
#Split Sentences
def split_sentences(text):
"""
Goal: Split sentences from input text.
Input:
- text: String containing >= 1 sentence.
Output:
- List of sentence(s).
"""
#Split Sentences
sentences = sent_tokenize(text)
return sentences |
from string import ascii_lowercase
# "I have no special talent I am only passionately curious"
# ~ Albert Einstein
def TabulaRecta():
mat =[[l for l in ascii_lowercase[i:]] + [' '] +
[l for l in ascii_lowercase[:i]]
for i in range(len(ascii_lowercase)+1)
]
def encrypt(text):
s = ""
for i in range(len(text)):
s += mat[i%len(mat)][mat[0].index(text[i].lower())]
return s
def decrypt(text):
s = ""
for i in range(len(text)):
s += mat[0][mat[i%len(mat)].index(text[i])]
return s
TabulaRecta.encrypt = encrypt
TabulaRecta.decrypt = decrypt
return TabulaRecta
|
from string import ascii_lowercase
"""
"DON’T WORRY ABOUT THE WORLD ENDING TODAY,
IT’S ALREADY TOMORROW IN AUSTRALIA."
~ CHARLES M. SCHULZ
"""
class PlayfairCipher():
def __init__(self, key=None):
self.mat = [[]]
if key:
alpha = key
else:
alpha = ""
alpha = alpha + ascii_lowercase + ' ' + '0' + '_' + ','
for j in range(36):
for k in range(len(self.mat)):
if not alpha:
break
if alpha[0] in self.mat[k]:
alpha = alpha[1:]
break
else:
if len(self.mat[-1]) > 5:
self.mat.append([])
self.mat[-1].append(alpha[0])
alpha = alpha[1:]
def __rc_check(self, ctl, ptl):
ialph, jalph = None, None
for j in range(len(self.mat)):
if ctl in self.mat[j]:
jalph = self.mat[j]
if ptl in self.mat[j]:
ialph = self.mat[j]
if ialph and jalph:
return ialph, jalph
def __it_pad(self, text):
while len(text) % 2 != 0:
text += ' '
return text.lower()
def encrypt(self, text):
s, text = '', self.__it_pad(text)
for i in range(1,len(text), 2):
ialph, jalph = self.__rc_check(text[i], text[i-1])
if ialph is jalph:
# same row
s += ialph[(ialph.index(text[i-1])+1)%len(ialph)]
s += jalph[(jalph.index(text[i])+1)%len(jalph)]
elif jalph.index(text[i]) == ialph.index(text[i-1]):
# same column
jdx, idx = self.mat.index(jalph), self.mat.index(ialph)
s += self.mat[(idx+1)%len(self.mat)][ialph.index(text[i-1])]
s += self.mat[(jdx+1)%len(self.mat)][jalph.index(text[i])]
else:
s += jalph[(ialph.index(text[i-1])+1)%len(ialph)]
s += ialph[(jalph.index(text[i])+1)%len(jalph)]
return s
def decrypt(self, text):
s, text = "", text.lower()
for i in range(1, len(text), 2):
ialph, jalph = self.__rc_check(text[i], text[i-1])
if ialph is jalph:
s += ialph[ialph.index(text[i-1])-1]
s += jalph[jalph.index(text[i])-1]
elif jalph.index(text[i]) == ialph.index(text[i-1]):
jdx, idx = self.mat.index(jalph), self.mat.index(ialph)
s += self.mat[idx-1][ialph.index(text[i-1])]
s += self.mat[jdx-1][jalph.index(text[i])]
else:
s += jalph[ialph.index(text[i-1])-1]
s += ialph[jalph.index(text[i])-1]
return s
|
class Catraca:
def cod(self):
return "XPTO"
def __init__(self, clube):
self.__clube = clube
def identificarPessoa(self, pessoa):
if pessoa.getVinculo() == "Sócio":
if pessoa in self.__clube.consultarSocio():
return self.cod() +""+ str(pessoa)
else:
return str(pessoa)
else:
if pessoa.getSocio() in self.__clube.consultarSocio():
return self.cod() +""+ str(pessoa)
else:
return str(pessoa)
def identificarAnimal(self, animal):
if animal.getSocio() in self.__clube.consultarSocio():
return self.cod() +""+ str(animal)
else:
return str(animal)
def entradaPessoa(self, pessoa):
if self.identificarPessoa(pessoa) == self.cod() +""+ str(pessoa) and self.__clube.adicionarVisitante(pessoa):
return True
else:
return False
def entradaAnimal(self, animal):
if self.identificarAnimal(animal) == self.cod() +""+ str(animal) and self.__clube.adicionarAnimal(animal):
return True
else:
return False
def saidaPessoa(self, pessoa):
return self.__clube.removerVisitante(pessoa)
def saidaAnimal(self, animal):
return self.__clube.removerAnimal(animal) |
def sum_digits(d1, d2):
if (d1 == d2):
return int(d1)
return 0
def sum_neighbor(numbers):
if len(numbers) <= 1:
return 0
sum = 0
for i in range(0, len(numbers)):
if i < len(numbers) - 1:
sum += sum_digits(numbers[i], numbers[i+1])
if len(numbers) > 2:
sum += sum_digits(numbers[0], numbers[-1:])
return sum
def sum_halfway(numbers):
if len(numbers) <= 1:
return 0
if len(numbers) % 2 > 0:
return 0
sum = 0
for i in range(0, len(numbers)):
j = (int(len(numbers)/2)+i)%len(numbers)
if i != j:
sum += sum_digits(numbers[i], numbers[j])
return sum
def main():
with open('day01.input') as f:
in_lines = f.read().splitlines()
with open('day01.output') as f:
out_lines = f.read().splitlines()
for n in range(0, len(in_lines)):
in_line = in_lines[n].split(" ")
in_part = in_line[0]
in_number = in_line[1]
out_line = int(out_lines[n])
if in_part == '1':
actual = sum_neighbor(in_number)
elif in_part == '2':
actual = sum_halfway(in_number)
else:
actual = -1
match = out_line == actual
print('{} {} {} {}'.format(n+1, in_part, actual, match))
if __name__ == '__main__':
main()
|
def check(expected, actual):
if actual == expected:
print(actual, 'OK')
else:
print(f'{actual} != {expected} ERROR')
def open_files():
with open('day09.input') as f:
in_lines = f.read().splitlines()
with open('day09.output') as f:
out_lines = f.read().splitlines()
out_vals = [(list(map(int, out_line.split(' ')))) for out_line in out_lines]
return in_lines, out_vals
def get_score(in_line):
garbage_score = 0
groups_score = 0
group_level = 0
group_scores = []
garbage_flag = False
ignore_flag = False
for char in in_line:
if ignore_flag:
ignore_flag = False
else:
if garbage_flag:
if char == '!':
ignore_flag = True
elif char == '>':
garbage_flag = False
else:
garbage_score += 1
else:
if char == '{':
group_level += 1
group_scores.append(group_level)
elif char == '}':
group_level -= 1
groups_score += group_scores.pop()
elif char == '<':
garbage_flag = True
elif char == '!':
ignore_flag = True
return groups_score, garbage_score
def main():
in_lines, out_vals = open_files()
for i, in_line in enumerate(in_lines):
out_val = out_vals[i]
score1, score2 = get_score(in_line)
check(out_val[0], score1)
check(out_val[1], score2)
if __name__ == '__main__':
main() |
# CSCI3180 Principles of Programming Languages
#
# --- Declaration ---
#
# I declare that the assignment here submitted is original except for source
# material explicitly acknowledged. I also acknowledge that I am aware of
# University policy and regulations on honesty in academic work, and of the
# disciplinary guidelines and procedures applicable to breaches of such policy
# and regulations, as contained in the website
# http://www.cuhk.edu.hk/policy/academichonesty/
#
# Assignment 2
# Name : Huzeyfe KIRAN
# Student ID : 1155104019
# Email Addr : 1155104019@link.cuhk.edu.hk
class GameBoard:
def __init__(self):
self.board = None
def init_gameBoard(self):
self.board = [[' ' for i in range(8)] for j in range(8)]
self.board[3][4] = 'O'
self.board[4][3] = 'O'
self.board[3][3] = 'X'
self.board[4][4] = 'X'
def check_ending(self):
#check whether the game is over or not
if(self.check_legal_move('O') == False and self.check_legal_move('X') == False):
return True
else:
return False
def check_legal_move(self,symbol):
#check if there is a legal move given symbol
if symbol == 'O':
anti_symbol = 'X'
else:
anti_symbol = 'O'
for i in range(0,8):
for j in range(0,8):
if(self.board[i][j] == ' '):
m = i
n = j
while(m <= 6 and self.board[m+1][n] == anti_symbol):
m = m + 1
if(m + 1 <= 7 and self.board[m+1][n] == symbol):
return True
m = i
while(m >= 1 and self.board[m-1][n] == anti_symbol):
m = m - 1
if(m - 1 >= 0 and self.board[m-1][n] == symbol):
return True
m = i
while(n <= 6 and self.board[m][n+1] == anti_symbol):
n = n + 1
if(n + 1 <= 7 and self.board[m][n+1] == symbol):
return True
n = j
while(n >= 1 and self.board[m][n-1] == anti_symbol):
n = n - 1
if(n - 1 >= 0 and self.board[m][n-1] == symbol):
return True
n = j
while(m <= 6 and n <= 6 and self.board[m+1][n+1] == anti_symbol):
m = m + 1
n = n + 1
if(m + 1 <= 7 and n + 1 <= 7 and self.board[m+1][n+1] == symbol):
return True
m = i
n = j
while(m >= 1 and n <= 6 and self.board[m-1][n+1] == anti_symbol):
m = m - 1
n = n + 1
if(m - 1 >= 0 and n + 1 <= 7 and self.board[m-1][n+1] == symbol):
return True
m = i
n = j
while(m <= 6 and n >= 1 and self.board[m+1][n-1] == anti_symbol):
m = m + 1
n = n - 1
if(m + 1 <= 7 and n - 1 >= 0 and self.board[m+1][n-1] == symbol):
return True
m = i
n = j
while(m >= 1 and n >= 1 and self.board[m-1][n-1] == anti_symbol):
m = m - 1
n = n - 1
if(m - 1 >= 1 and n - 1 >= 0 and self.board[m-1][n-1] == symbol):
return True
m = i
n = j
return False
def check_winner(self):
#return a list[s1,s2], represent the total number for O and X
counts = [0,0]
for i in range(8):
for j in range(8):
if(self.board[i][j] == 'O'):
counts[0] = counts[0] + 1
else:
counts[1] = counts[1] + 1
return counts
def execute_flip(self, pos, symbol):
i , j = pos[0], pos[1]
self.board[i][j] = symbol
directions = self.find_direcion_to_flip(i, j, symbol)
self.execute_directional_flips(i,j,directions, symbol)
def find_direcion_to_flip(self, i, j, symbol):
# find the directions to execute the flip
if(symbol == 'O'):
anti_symbol = 'X'
else:
anti_symbol = 'O'
directions_to_flip = []
m = i
n = j
while(m <= 6 and self.board[m+1][n] == anti_symbol):
m = m + 1
if(m + 1 <= 7 and self.board[m+1][n] == symbol):
directions_to_flip.append(1)
m = i
while(m >= 1 and self.board[m-1][n] == anti_symbol):
m = m - 1
if(m - 1 >= 0 and self.board[m-1][n] == symbol):
directions_to_flip.append(2)
m = i
while(n <= 6 and self.board[m][n+1] == anti_symbol):
n = n + 1
if(n + 1 <= 7 and self.board[m][n+1] == symbol):
directions_to_flip.append(3)
n = j
while(n >= 1 and self.board[m][n-1] == anti_symbol):
n = n - 1
if(n - 1 >= 0 and self.board[m][n-1] == symbol):
directions_to_flip.append(4)
n = j
while(m <= 6 and n <= 6 and self.board[m+1][n+1] == anti_symbol):
m = m + 1
n = n + 1
if(m + 1 <= 7 and n + 1 <= 7 and self.board[m+1][n+1] == symbol):
directions_to_flip.append(5)
m = i
n = j
while(m >= 1 and n <= 6 and self.board[m-1][n+1] == anti_symbol):
m = m - 1
n = n + 1
if(m - 1 >= 0 and n + 1 <= 7 and self.board[m-1][n+1] == symbol):
directions_to_flip.append(6)
m = i
n = j
while(m <= 6 and n >= 1 and self.board[m+1][n-1] == anti_symbol):
m = m + 1
n = n - 1
if(m + 1 <= 7 and n - 1 >= 0 and self.board[m+1][n-1] == symbol):
directions_to_flip.append(7)
m = i
n = j
while(m >= 1 and n >= 1 and self.board[m-1][n-1] == anti_symbol):
m = m - 1
n = n - 1
if(m - 1 >= 1 and n - 1 >= 0 and self.board[m-1][n-1] == symbol):
directions_to_flip.append(8)
return directions_to_flip
def execute_directional_flips(self,i,j,directions, symbol):
# flip the pieces in the desired directions
if(symbol == 'O'):
anti_symbol = 'X'
else:
anti_symbol = 'O'
m = i
n = j
for z in directions:
if(z == 1):
while(m <= 6 and self.board[m+1][n] == anti_symbol):
m = m + 1
self.board[m][n] = symbol
m = i
elif(z == 2):
while(m >= 1 and self.board[m-1][n] == anti_symbol):
m = m - 1
self.board[m][n] = symbol
m = i
elif(z == 3):
while(n <= 6 and self.board[m][n+1] == anti_symbol):
n = n + 1
self.board[m][n] = symbol
n = j
elif (z == 4):
while(n >= 1 and self.board[m][n-1] == anti_symbol):
n = n - 1
self.board[m][n] = symbol
n = j
elif (z == 5):
while(m <= 6 and n <= 6 and self.board[m+1][n+1] == anti_symbol):
m = m + 1
n = n + 1
self.board[m][n] = symbol
m = i
n = j
elif (z == 6):
while(m >= 1 and n <= 6 and self.board[m-1][n+1] == anti_symbol):
m = m - 1
n = n + 1
self.board[m][n] = symbol
m = i
n = j
elif (z == 7):
while(m <= 6 and n >= 1 and self.board[m+1][n-1] == anti_symbol):
m = m + 1
n = n - 1
self.board[m][n] = symbol
m = i
n = j
elif (z == 8):
while(m >= 1 and n >= 1 and self.board[m-1][n-1] == anti_symbol):
m = m - 1
n = n - 1
self.board[m][n] = symbol
m = i
n = j
def printGameBoard(self):
for i in range(9):
for j in range(9):
if(i > 0 and j == 0):
print(str(i) + ' | ',end='')
continue
if(i == 0 and j > 0):
print(str(j) + ' | ',end='')
continue
print(self.board[i-1][j-1] + ' | ',end='')
print('')
print('-' * 35)
|
listval = [1,2,3,4,5,6]
print ("value at idx 1 %d " % listval[1])
somenum =2**4
lst = [1, [20,21,somenum],3,4]
print(lst[1][2]) #16
lst[1][2] = somenum**2
print(lst[1][2]) #256 (16^2)
frstList = [4,3,2,1]
secondList = [10,9,8]
print (frstList + secondList) # adds both the list
print (secondList *2) # prints the same list twice.
################# USING LIST - IN operator ############
# checks if the value exists in the list
list1 = ["one","two", ["1three","1four"]]
print ("one" in list1) # True
print ( "1four" in list1) # False
print ( "1four" in list1[2]) # True
################# USING LIST - Append method ############
# appends an value to the end of the list
list1.append("new array");
print ( " new array included ")
print( "new array" in list1) # True
################ USING LIST - len function - not within list like append ############
# len function prints the length of the list
print ("lenght of the list %d " % len(list1))
################ USING LIST - INSERT function ###############
# inserts value between list
list1.insert(2,"new insert")
print (list1)
nums= [9,8,7,6,5]
nums.append(4)
nums.insert(2,11)
print(len(nums))
#################### USING LIST - INDEX method ##################
# returns the int index of the value in the list
indexval = list1.index('new insert')
print("new insert is at the index 2 %d " %indexval)
#There are a few more useful functions and methods for lists.
#max(list): Returns the list item with the maximum value
#min(list): Returns the list item with minimum value
#list.count(obj): Returns a count of how many times an item occurs in a list
#list.remove(obj): Removes an object from a list
#list.reverse(): Reverses objects in a list
print (max(nums))
listtmp = [1,2,2,3,4,5,5,5,5,6,] # end , is allowable
#counts the occurance of the value in the list
print ("Count of 5 in array expected 4 = %d " %listtmp.count(5));
###################### USING LIST - RANGE ###############
# range creates set of sequenctial number in the list
rangeList = list(range(10)) # range itself creates a list object
print(rangeList)
range1= list (range(3,8)) # specify the start and the end of the range
print(range1)
print(range(20) == range(0,20)) # true
#range with three parameter
range2 = list(range(1,15,2)) # 3rd parameter is for increment sequence
print (range2)
|
################## IMPORTATN : OBJECT ORIENTED PROGRAMMING CONCEPT #######
# imperative programming (using statements, loops, and functions as subroutines),
# functional programming (using pure functions, higher-order functions, and recursion).
# Objects in python are created using classes.
# once class is created like other oops programming this can be used again and again
# classes are created using keyword "class"
# intend to include the functions
class Animal:
# __init__ similar to constructor in java
# self -> similar to this in java
def __init__(self,animaltype,legs):
#typeofAnimal & leg are attributes of the class.
self.typeofAnimal=animaltype
self.leg=legs
cat = Animal("cat",4)
dog = Animal("dog",4)
# What type of object is a method in class - Function
################## NOTES : more about class #############
# __init__ => This method is called when an instance of the class is created
# it also uses class name as function
# in the above example, __init__ takes 2 arguments and assign to the object attribute
# self => All the methods should have the self as first parameter
# although it isn't explicitly passed.
# self is more like a this in java
# python adds the self argument to the list when calling or invoking the function
# Within a method definition, self refers to the instance calling the method.
# instances of a class have attributes, which are data associated with them.
# self.attribute => is used to initialize the inital value of instance's attribute
# Refer the above example of class
# how to print the values of the attributes
print(cat.typeofAnimal)
######################## NOTES : using methods in class ####################
# Methods => Classes can have other methods other than __inti__
# This can be created usign def keyword
class Dog:
def __init__(self,name,color): # note if the init is misspelled issues TypeError : object takes no parameter
self.name=name
self.color=color
def bark(self):
print("dog barks")
dog1 = Dog("Coda","brown")
print(dog1.name)
dog1.bark()
########################## NOTES : using class level attributes ###########
class Car:
tires = 4
def __init__(self,name,color):
self.name=name
self.color=color
toyota=Car("toyota","red")
print(toyota.name) # at instance level
print(toyota.tires) # accessing class level attribute from instance
print(Car.tires) # accessing class level attribute directly using class object
# NOTE: class attribute are shared along all instances of class
class Student:
def __init__(self, name):
self.name = name
def sayHi(self):
print("Hi from "+self.name)
s1 = Student("Tom")
s1.sayHi()
# NOTE: AttributeError
# Trying to access an attribute of an instance that isn't defined causes
# an AttributeError. This also applies when you call an undefined method.
s2=Student("Ram")
# uncomment to test Attriute error
# print(s2.section)
# s2.hello()
################### IMPORTANT : INHERITANCE ##################################
# Inheritance -> a way to share functionlity between classes
# parent and child class
class Animal:
def __init__(self,name,color):
self.name=name
self.color=name
class Cat(Animal): # inheritance
def meow(slef):
print("cat meowsss")
class Dog(Animal):
def bark(self):
print ("dogs barksss")
dog1 = Dog("Cram","black")
print(dog1.color)
dog1.bark()
############### NOTES : about inheritance ################
# subclass => class that is inheriting from another class
# superclass => class that is being inhertied
# methods can be overriden
##########################################################
class Birds:
def __init__(self, name, color):
self.name=name
self.color = color
def sing(self):
print("bird sings")
class Parrot(Birds):
def sing(self):
print("parrot talked")
# Birds - super class; Parrot - subclass
parrot1 = Parrot("Grad","green")
parrot1.sing()
# another way of invoking
Birds("CalculatorExample.py","brown").sing()
######################## NOTES : MULTI-LEVEL INHERITANCE ###############
# Inheritance can be indirect. Multiple inheritance.
# class A inherited in class B and class B inhertied in class C
class A:
def method(self):
print("A method")
class B(A):
def bmethod(self):
print("A supercalss inhertied in B")
class C(B):
def cmethod(self):
print("B superclass inhertied in C")
c = C()
c.method()
c.bmethod()
c.cmethod()
###################### NOTES #######################
# CIRCULAR INHERITANCE is not possible in python
### quiz
class A:
def a(self):
print(1)
class B(A):
def a(self):
print(2)
class C(B):
def c(self):
print(3)
c =C()
c.a()
# 2
################# IMPORTANT : SUPER method in inhertiance #############
# super function, used to call the method in the parent class
class SuperClass:
def method1(self):
print ("method1")
def method2(self):
print("method2")
class SubClass(SuperClass):
def methodsub1(self):
print("subclass methodsub1")
#use super
super().method1()
super().method2()
SubClass().methodsub1()
######################### IMPORTANT : Magic methods ###################
# methods that starts and end with __ (double underscore) is special method
# it is used to create a seperate functionality
# it is used on such functionality for creating operator overloading.
# They are also know as DUNDERS.
# one such example is cusom classes that allow operator such as +, *
class Vector2D:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self,other):
return Vector2D(self.x+other.x,self.y+other.y)
first = Vector2D(5,7)
second = Vector2D(3,9)
result = first + second
print("{0} {1} ".format(result.x,result.y))
# The __add__ method allows for the definition of a custom behavior
# for the + operator in our class.
# As you can see, it adds the corresponding attributes
# of the objects and returns a new object, containing the result.
# Once it's defined, we can add two objects of the class together.
class ProductPoints:
def __init__(self,x,y):
self.x = x
self.y = y
def __mul__(self,points):
return ProductPoints(self.x*points.x,self.y*points.y)
point1 = ProductPoints(4,5)
point2 = ProductPoints(4,5)
res = point1 * point2
print ("{0} , {1}".format(res.x,res.y ))
print ("{}".format(res.x))
############## NOTES : other magic methods #################
#__sub__ for -
#__mul__ for *
#__truediv__ for /
#__floordiv__ for //
#__mod__ for %
#__pow__ for **
#__and__ for &
#__xor__ for ^
#__or__ for |
# The x*y is translated to x.__mul__(y)
# NOTE: if x hasn't implemented __add__, x and y are different types
# then y.__radd___(x) is called.
# there are equivalent r method for all magic methods
class Strings:
def __init__(self,txt):
self.txt= txt
def __truediv__(self,other):
line = "=" * len(other.txt)
return "\n".join([self.txt,line,other.txt])
spam = Strings("spam")
strs = Strings("Hello Python!")
print (spam/strs)
# Magic method for comparision - Operator overloading
#__lt__ for <
#__le__ for <=
#__eq__ for ==
#__ne__ for !=
#__gt__ for >
#__ge__ for >=
# if __ne__ is not implemented it returns to the opposite
class SpecialString:
def __init__(self, cont):
self.cont = cont
def __gt__(self, other):
for index in range(len(other.cont)+1):
result = other.cont[:index] + ">" + self.cont
result += ">" + other.cont[index:]
print(result)
spam = SpecialString("spam")
eggs = SpecialString("eggs")
spam > eggs
#There are several magic methods for making classes act like containers.
#__len__ for len()
#__getitem__ for indexing
#__setitem__ for assigning to indexed values
#__delitem__ for deleting indexed values
#__iter__ for iteration over objects (e.g., in for loops)
#__contains__ for in
#__call__ for calling objects as functions
#__int__ converting object to int (built-in types)
#__str__ converting object to string (built-in types)
# below is an example of how length function and indexing function return random number
import random
class VagueList:
def __init__(self, cont):
self.cont = cont
def __getitem__(self, index):
return self.cont[index + random.randint(-1, 1)]
def __len__(self):
return random.randint(0, len(self.cont)*2)
vague_list = VagueList(["A", "B", "C", "D", "E"])
print(len(vague_list))
print(len(vague_list))
print(vague_list[2])
print(vague_list[2])
# its more like an interceptor
############################# IMPORTANT L LIFE CYCLE OF OBJECT ###########
# Object life cycle includes creation, manipulation and destruction.
# 1st stage of life cycle is defintion of the class.
# 2nd stage is calling __init__ the instantiation of an instance.
# 3rd stage, memory is allocated to store the instance
# optional stage before 3rd stage __new__ method of the class is called,
# this usally overriden only in special cases
# finally the object is ready for use
# manipulation, happens by interacting with the attributes of the object
# finally the object will be destroyed.
# When an object is destroyed, the memory allocated to it is freed up,
# and can be used for other purposes.
# Destruction of an object occurs when its reference count reaches zero.
# Reference count is the number of variables and other elements that refer to an object.
# If nothing is referring to it (it has a reference count of zero) nothing
# can interact with it, so it can be safely deleted.
# In some situations, two (or more) objects can be referred to by each
# other only, and therefore can be deleted as well.
# The del statement reduces the reference count of an object by one,
# and this often leads to its deletion.
# The magic method for the del statement is __del__.
# The process of deleting objects when they are no longer needed
# is called garbage collection.
# In summary, an object's reference count increases when it is assigned
# a new name or placed in a container (list, tuple, or dictionary).
# The object's reference count decreases when it's deleted with del,
# its reference is reassigned, or its reference goes out of scope.
# When an object's reference count reaches zero, Python automatically deletes it.
# program with private attribute in class
class PrivateAttrEx:
__var1=10
def print_var1(self):
print (self.__var1)
p = PrivateAttrEx()
p.print_var1()
print("Alternate way to access private attribute of class ")
print(p._PrivateAttrEx__var1)
# property decorator with getter and setter
# declare property using @property
# NOTE: Main importance of making an attribute property is make it read-only
def get_input():
command = input(": ").split()
verb_word = command[0]
if verb_word in verb_dict:
verb = verb_dict[verb_word]
else:
print("Unknown verb {}". format(verb_word))
return
if len(command) >= 2:
noun_word = command[1]
print (verb(noun_word))
else:
print(verb("nothing"))
def say(noun):
return 'You said "{}"'.format(noun)
verb_dict = {
"say": say,
}
while True:
get_input()
|
w=input(" ")
if(w=='Monday' or w=='Tuesday' or w=='Wednesday' or w=='Thrusday' or w=='Friday'):
print("no")
elif(w=='Saturday' or w=='Sunday'):
print("yes")
else:
print("invalid")
|
# O(n^2)T | O(1)S
def TwoNumberSum(array, TargetSum):
for i in range(len(array)):
Firstnum = array[i]
for j in range(i + 1, len(array)):
Secondnum = array[j]
if Firstnum + Secondnum == TargetSum:
print(Firstnum, Secondnum)
array = [1, 2, 3, 8, 5]
TargetSum = 10
TwoNumberSum(array, TargetSum)
# O(n)T | O(1)S
def TwoNumberSum(array, TargetSum):
nums = {} # to store hashing table
for num in array:
potentialmatch = TargetSum - num # y=x+sum
if potentialmatch in nums:
print(potentialmatch, num)
else:
nums[num] = True
array = [1, 2, 3, 8, 5]
TargetSum = 10
TwoNumberSum(array, TargetSum)
|
#KONSTRUKSI DASAR PYTHON
#SEQUENTIAL : EKSEKUSI BERURUTAN
print('Hello World!')
print("by Yakub")
print("tanggal 4 Juli 2021")
print("-"*10)
#PERCABANGAN : Eksekusi Terpilih
ingin_cepat=False
if ingin_cepat:
print('jalan lurus aja ya!')
else:
print('jalan lain!')
#PERULANGAN
jumlah_anak = 4
for index_anak in range(1, jumlah_anak+1):
print(f'Halo anak #{index_anak}')
|
from Game import *
game = Game()
# This module functions as the driver for the game.
while game.gamestatus() is False:
print("\n\n\n\n\n\n\n\n\n\n\n\n\n")
game.displaymap()
print("\n What would you like to do? ")
print(" You can move up 'u', down 'd', left 'l', and right 'r'")
ui = input("\n\tEnter your choice: ")
game.moveplayer(ui)
if game.checkplayerathouse():
game.startbattle()
game.checkwin()
if game._gamewon is True:
print("You won!")
else:
print("You lost!") |
def hello():
print("Hello!")
hello()
name=["たんじろう","ぎゆう","ねずこ","むざん"]
name.append("ぜんいつ")
def namae(name1):
if name1 in name:
print(name1, "は含まれます")
else:
print(name1, "は含まれません")
namae("ぜんいす") |
"""
Sklearn中的make_circles方法生成训练样本
并随机生成测试样本,用KNN分类并可视化。
"""
from sklearn.datasets import make_circles
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import numpy as np
import random
fig = plt.figure(1, figsize=(10, 5))
x1, y1 = make_circles(n_samples=400, factor=0.4, noise=0.1)
# 模型训练 求距离、取最小K个、求类别频率
knn = KNeighborsClassifier(n_neighbors=15)
knn.fit(x1, y1) # X是训练集(横纵坐标) y是标签类别
# 进行预测
x2 = random.random() # 测试样本横坐标
y2 = random.random() # 测试样本纵坐标
X_sample = np.array([[x2, y2]]) # 给测试点
# y_sample = knn.predict(X_sample) # 调用knn进行predict得预测类别
y_sample = []
for i in range(0, 400):
dx = x1[:, 0][i] - x2
dy = x1[:, 1][i] - y2
d = (dx ** 2 + dy ** 2) ** 1 / 2
y_sample.append(d)
neighbors = knn.kneighbors(X_sample, return_distance=False)
plt.subplot(121)
plt.title('data by make_circles() 1')
plt.scatter(x1[:, 0], x1[:, 1], marker='o', s=100, c=y1)
plt.scatter(x2, y2, marker='*', c='b')
plt.subplot(122)
plt.title('data by make_circles() 2')
plt.scatter(x1[:, 0], x1[:, 1], marker='o', s=100, c=y1)
plt.scatter(x2, y2, marker='*', c='r', s=100)
for i in neighbors[0]:
plt.scatter([x1[i][0], X_sample[0][0]], [x1[i][1], X_sample[0][1]], marker='o', c='b', s=100)
plt.show()
|
import numpy as np
class BoardReader:
"""
~ Class BoardReader represents single board reader from picture.
Arguments:
:param picture: picture from which board will be created
:type picture: pil.Image
"""
def __init__(self, picture):
"""
~ Class BoardReader constructor.
"""
self.board = self.create_board_from_picture(picture)
def get_board_size(self):
"""
~ Function returns size of board.
"""
return self.board.shape
def set_value_on_pos(self, posx, posy, value):
"""
~ Method sets value 1 or 0 on board on given positionX and
given position Y.
Parameteres:
:param posx: position X on board
:type posx: int
:param posy: position Y on board
:type posy: int
:param value: number 1 or 0, which will be on board
:type value: int
"""
b_height, b_width = self.get_board_size()
if value in {0, 1} and 0 <= posx < b_width and 0 <= posy < b_height:
self.board[posy, posx] = value
def get_pos_value(self, posx, posy):
"""
~ Method returns value of board on given positionX and
given positionY.
"""
return self.board[posy, posx]
def create_board_from_picture(self, picture):
"""
~ Function creates and returns board for ant (numpy array)
from given black and white picture.
Algorithm:
1) if pixel on (x, y) is white =>
array value on (x, y) position is 0 (int)
2) otherwise if pixel on (x, y) is black =>
array value on (x, y) is 1 (int)
Arguments:
:arg picture: picture from which function creates board
:type picture: PIP.Image
"""
width, height = picture.size
# creating new numpy array
board = np.empty((height, width), dtype=int)
for pix_col in range(width):
for pix_row in range(height):
if picture.getpixel((pix_col, pix_row)) == 0:
board[pix_row, pix_col] = 1
else:
board[pix_row, pix_col] = 0
return board
|
def findSublists(A):
for i in range(len(A)):
for j in range(i, len(A)):
print(A[i:j + 1])
def rotate(arr, n):
x = arr[n - 1] #last element
for i in range(n - 1, 0, -1):
arr[i] = arr[i - 1]
arr[0] = x
print(arr)
if __name__ == '__main__':
A = [2, 7, 5]
B=[1, 4, 6, 8, 7] # [7, 1, 4, 6, 8]
findSublists(A)
rotate(B, len(B))
|
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 1 15:30:27 2019
@author: prash
"""
def process(line: str) -> str:
# Return 'VALID' or 'INVALID'
checksum=line[0:2]
try:
acc_num=int(line[2:len(line)],16)
except (ValueError):
return "INVALID"
sum=0
while(acc_num>0):
dig=acc_num%10
sum=sum+dig
acc_num=acc_num//10
generated_checksum=hex(sum).split('x')[-1]
if checksum.lower()==generated_checksum.lower():
return "VALID"
else:
return "INVALID"
print(process("1C00000"))
def process(line: str) -> str:
# Return 'VALID' or 'INVALID'
if len(line)!=8:
return "INVALID"
checksum=line[0:2]
try:
acc_num=int(line[2:8],16)
except (ValueError):
return "INVALID"
sum=0
while(acc_num>0):
dig=acc_num%10
sum=sum+dig
acc_num=acc_num//10
generated_checksum=hex(sum).split('x')[-1]
if checksum.lower()==generated_checksum.lower():
return "VALID"
else:
return "INVALID"
|
if __name__ == "__main__":
# 입력
string = input()
# 입력받은 문자열을 탐색하면서 따로 구현한 문자열 배열에 문자를 삽입하고, 숫자는 누적해서 더한다.
sort_string = []
total = 0
for i in string:
if i.isalpha():
sort_string.append(i)
else:
total += int(i)
result = sorted(sort_string)
if total != 0:
result.append(total)
print("".join(map(str, result))) |
from tkinter import *
import tkinter.messagebox as tmsg
root=Tk()
root.geometry("455x233")
root.title("Slider")
def getdollar():
print(f"We have credited {myslider2.get()} dollars to your bank account")
tmsg.showinfo("Amount Credited",f"We have credited {myslider2.get()} dollars to your bank account")
# myslider=Scale(root,from_=0,to=100)
# myslider.pack()
Label(root,text="How many dollars do you want?").pack()
myslider2=Scale(root,from_=0,to=100,orient=HORIZONTAL,tickinterval=50)
myslider2.set(34)
myslider2.pack()
Button(root,text="Get Dollars",pady=10,command=getdollar).pack()
root.mainloop()
|
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/bubble', methods=['POST'])
def bubbleSort(arr):
# import user input
bubble = request.form['bubble']
n = len(arr)
# Filter through array
for i in range(n):
# Last i elements are already in place
for j in range(0, n - i - 1):
# Filter the array from 0 to n-i-1
# Swap if the number found is greater than the next number
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# Numbers to be sorted, including user inputted number
arr = [64, 34, 25, 12, 22, 11, 90, bubble]
# sort
bubbleSort(arr)
print("Sorted array is:")
for i in range(len(arr)):
print("%d" % arr[i])
# return home
return render_template("bfsort.html") |
import random
booklist1 = ["The Great Gatsby,", "To Kill a Mockingbird", "Catch-22", "Pride and Prejudice", "The Scarlet Letter", "War and Peace", "One Hundred Years of Solitude", "The Sun Also Rises"]
booklist2 = ["To Kill a Mockingbird,", "The Scarlette Letter", "War and Peace"]
#1: setting up the class
class Books:
"""Initializer of class takes series parameter and returns Class Objects"""
def __init__(self, series):
"""Built in validation and exception"""
if series < 0 or series > 6:
raise ValueError("Series must be between 0 and 6")
self._series = series
self._list = []
self._dict = {}
self._dictID = 0
# Duration timeElapsed;
# Instant start = Instant.now(); // time capture -- start
self.book_series()
# Instant end = Instant.now(); // time capture -- end
# this.timeElapsed = Duration.between(start, end);
#2 defining your series
"""Algorithm for building book series list, this id called from __init__"""
def book_series(self):
limit = self._series
f = [(random.sample((booklist1), k=3))]
while limit > 0:
self.set_data(f[0])
f = [f[0]]
limit -= 1
#3: function to set data
"""Method/Function to set data: list, dict, and dictID are instance variables of Class"""
def set_data(self, num):
self._list.append(num)
self._dict[self._dictID] = self._list.copy()
self._dictID += 1
#4: creating our getters
"""Getters with decorator to allow . notation access"""
@property
def series(self):
return self._series
@property
def list(self):
return self._list
@property
def number(self):
return self._list[self._dictID - 1]
"""Traditional Getter requires method access"""
def get_sequence(self, nth):
return self._dict[nth]
#5: creating our objects and values + testing
if __name__ == "__main__":
'''Value for testing'''
a = 3
'''Constructor of Class object'''
bookrecs = Books(a/a)
print(f"Here are some book recomendations = {bookrecs.list}")
#class FibonacciSeries:
#def __init__(self, series):
#if series < 2 or series > 100:
#raise ValueError("Must be between 2 and 100")
#self._series = series
#self._list = []
#self._dict = {}
#self._dictID = 0
#self.calculate_series()
#def calculate_series(self):
#limit = self._series
#f = [0, 1]
#while limit > 0:
#self.set_data(f[0])
#f = [f[1], f[0] + f[1]]
#limit -= 1
#def set_data(self, num):
#self._list.append(num)
#self._dict[self._dictID] = self._list.copy()
#self._dictID += 1
#@property
#def series(self):
#return self._series
#@property
#def list(self):
#return self._list
#@property
#def number(self):
#return self._list[self._dictID - 1]
#def get_sequence(self, nth):
#return self._dict[nth]
#if __name__ == "__main__":
#n = 69
#fibonacci = FibonacciSeries(n)
#print(f"Fibonacci number for {n} = {fibonacci.number}")
#print(f"Fibonacci series for {n} = {fibonacci.list}")
#for i in range(n):
#print(f"Fibonacci sequence {i + 1} = {fibonacci.get_sequence(i)}") |
# nested loops
listA = list(range(6))
listB = list(range(6))
product1 = [(a, b) for a in listA for b in listB]
product2 = [(a, b) for a in listA for b in listB if a % 2 == 1 and b % 2 == 0]
'''
print(product1)
print(product2)
'''
ports = ['WAW', 'KRK', 'GDN', 'KTW', 'WMI', 'WRO', 'POZ', 'RZE', 'SZZ',
'LUZ', 'BZG', 'LCJ', 'SZY', 'IEG', 'RDO']
connections_with_rep = [(a, b) for a in ports for b in ports]
connections_without_rep = [(a, b) for a in ports for b in ports if a != b]
routes = [(a, b) for a in ports for b in ports if a > b]
print(connections_with_rep)
print(len(connections_with_rep))
print(connections_without_rep)
print(len(connections_without_rep))
print(routes)
print(len(routes))
|
import os
import os.path
import time
def user_dir_file():
user_dir = input("Please enter a directory to save a file in: ")
user_file = None
if os.path.exists(user_dir):
user_file = input("Please enter the name of the file you want to save in the specified directory: ")
else:
os.makedirs(user_dir)
print("Although the specified directory did not exist, I went ahead and created it for you!")
print("------------------------")
time.sleep(1.5)
user_file = input("Please enter the name of the file you want to save in the specified directory: ")
time.sleep(1.5)
print("Processing...")
time.sleep(1)
print("------------------------")
time.sleep(1.5)
write_to_file(user_dir, user_file)
return user_dir, user_file
def write_to_file(user_dir, user_file):
print("Please enter the following information to be written to the specified file: ")
print("------------------------")
user_name = input("Name: ")
user_address = str(input("Address: "))
user_phone_num = str(input("Phone number: "))
print("------------------------")
time.sleep(1.5)
print("Processing....")
print("------------------------")
time.sleep(1)
with open(user_file, 'w') as f:
f.write(user_name)
f.write(user_address)
f.write(user_phone_num)
f = open(user_file, "r")
if f.mode == "r":
contents = f.read()
print("Please verify the data below:")
print("")
time.sleep(1.5)
print(contents)
f.close()
if __name__ == '__main__':
user_dir_file()
|
import math
def calentropy(dict):
entropy={}
for i in dict.keys():
entropy[i]=0
for j in dict[i]:
if j!=0: entropy[i]-=(j*(math.log(j, 2)))
print(entropy)
calentropy({'A':[0.5, 0, 0, 0.5],'B':[0.25, 0.25, 0.25, 0.25],'C':[0, 0, 0, 1],'D':[0.25, 0, 0.5, 0.25]})
|
"""
CMPS 2200 Assignment 1.
See assignment-01.pdf for details.
"""
# no imports needed.
def foo(x):
if x <= 1 :
return x
else:
return foo(x-1)+foo(x-2)
### TODO
pass
def longest_run(mylist, key):
tracker = 0
longest_count = 0
for i in mylist:
if (i > 0 and i==key):
tracker += 1
if tracker > longest_count:
longest_count = tracker
else:
tracker = 0
return count
### TODO
pass
def longest_run(mylist, key):
longest_count = 0
temp_count = 0
for i in mylist:
if i == key:
temp_count += 1
else:
temp_count == 1
return longest_count
class Result:
""" done """
def __init__(self, left_size, right_size, longest_size, is_entire_range):
self.left_size = left_size # run on left side of input
self.right_size = right_size # run on right side of input
self.longest_size = longest_size # longest run in input
self.is_entire_range = is_entire_range # True if the entire input matches the key
def __repr__(self):
return('longest_size=%d left_size=%d right_size=%d is_entire_range=%s' %
(self.longest_size, self.left_size, self.right_size, self.is_entire_range))
def longest_run_recursive(mylist, key):
if len(mylist) == 1:
if mylist[0] == key:
fin = Result(1,1,1,True)
return fin
else:
fin = Result(0,0,0,False)
return fin
else:
mid = len(mylist)//2
left = longest_run_recursive(mylist[:mid],key)
right = longest_run_recursive(mylist[mid:],key)
lr = left.right_size
rl = right.left_size
size = 0
if lr!=0 and rl!=0:
size = rl + lr
if size > left.longest_size and size > right.longest_size:
if left.is_entire_range and right.is_entire_range:
fin = Result(size,size,size,True)
return fin
elif left.is_entire_range:
res = Result(size,right.right_size,size,False)
return fin
elif right.is_entire_range:
fin = Result(left.left_size,size,size,False)
return fin
else:
fin = Result(left.left_size,right.right_size,size,False)
return fin
else:
size = max(left.longest_size,right.longest_size)
fin = Result(left.left_size,right.right_size,size,False)
return fin
### TODO
pass
print(longest_run_recursive([2,12,12,8,12,12,12,0,12,1], 12))
## Feel free to add your own tests here.
def test_longest_run():
assert longest_run([2,12,12,8,12,12,12,0,12,1], 12) == 3
|
def soma(numero1, numero2):
return numero1 + numero2
def validador(numero):
return type(numero) == int
def test_soma():
assert soma(2,2) == 4
def test_soma_numero_negativo():
assert soma(2,-2) == 0, "a função soma() não está somando corretamente números negativos"
def test_valida_numero():
assert not validador('x')
if __name__ == '__main__':
test_soma()
test_soma_numero_negativo()
test_valida_numero()
# try:
# 10/0
# except ZeroDivisionError:
# print("divisor igual a zero")
|
print("mario sergio".replace('a', 'b').startswith('m'))
meses = {'01': 'janeiro',
'02': 'fevereiro',
'03': 'março',
'04': 'abril'}
data = '26/04/2018'.split('/')
mes = meses[data[1]]
|
# import numpy as np
# np = numpy
lista1 = [1,2,3]
lista2 = list(lista1)
print(lista2, lista1)
print(lista1 == lista2)
print(lista1 is lista2)
lista1.append(10)
print(lista2, lista1)
print(lista1 == lista2)
print(lista1 is lista2)
def soma(num1, num2):
return num2 + num1
class Calculadora():
def soma(self, num1, num2):
return num2 + num1
print(soma(1,2))
calc = Calculadora()
print(calc.soma(1,3))
|
import numpy as np
def getH(x):
return x[1] - x[0]
def getForwardDifferences(g):
out = [g[0]]
temp = [each for each in g]
for i in range(len(temp)-1):
temp2 = [temp[i+1]-temp[i] for i in range(len(temp)-1)]
out.append(temp2[0])
temp = temp2
return out
def factorial(n):
out = 1
for i in range(1, n+1):
out = out*i
return out
def combination(u, n):
out = 1
for i in range(n):
out = out * (u-i)
return out/factorial(n)
def newtonForward(x0, g, x):
h = getH(x0)
f0_arr = getForwardDifferences(g)
u = (x-x0[0])/h
out = 0
for i in range(0, len(f0_arr)):
out = out + combination(u,i)*f0_arr[i]
return out
if __name__ == "__main__":
x0 = [0, 1, 2, 4, 5, 6]
g = [1, 14, 15, 5, 6, 19]
x = 3
fx = newtonForward(x0, g, x)
h = getH(x0)
fn_arr = getForwardDifferences(g)
print("Given x: ", x0)
print("Given f(x): ", g)
print("Given x at which to evaluate: ", x)
print("Forward differences: ")
for i in range(len(fn_arr)):
print("\t(▽^"+str(i)+")fn: ", fn_arr[i])
print("Obtained f(x): ", fx) |
# -*- coding: utf-8 -*-
import numpy as np
import xlrd
import pandas as pd
#read the data from the excel file
def read(file):
wb = xlrd.open_workbook(filename=file)#open the file
sheet = wb.sheet_by_index(0) #obtain the table data from the index
rows = sheet.nrows # calculate the number of rows
all_content = [] #store the readed data
for j in range(2, 4): #select the 3-th column data (matual information) and 4-th column (pearson correlation cofficient).
temp = []
for i in range(1,rows):
cell = sheet.cell_value(i, j) #obtain the data
temp.append(cell)
all_content.append(temp) #add the results into the array according to the column
temp = []
return np.array(all_content)
#print np.array(all_content)
#Calculate the very small measure
def dataDirection_1(datas):
return np.max(datas)-datas
#calculate the intermediate measure
def dataDirection_2(datas, X_max, X_min):
answer_list = []
for i in datas:
if (X_Min<= i <= (X_max+X_min)/2):
answer_list.append(2*(i-X_min)/(X_max - X_min))
elif ((X_max+X_min)/2<= i <= X_max):
answer_list.append(2*(X_man-i)/(X_max - X_min))
elif i<=X_min or i>=X_max:
return 0
return np.array(answer_list)
#calculate the interval type measure
def dataDirection_3(datas, X_min, X_max):
M_min = X_min - np.min(datas)
M_max = np.max(datas) - X_max
answer_list = []
for i in datas:
if(i < X_min):
answer_list.append(1 - (X_min-i) /M_min)
elif( X_min <= i <= X_max):
answer_list.append(1)
else:
answer_list.append(1 - (i - X_max)/M_max)
return np.array(answer_list)
#Normalize the forward matrix
def temp2(datas):
K = np.power(np.sum(pow(datas,2),axis =1),0.5)
for i in range(0,K.size):
for j in range(0,datas[i].size):
datas[i,j] = datas[i,j] / K[i]
#print datas
return datas
#calculate the weights of measures by using the information entropy
def EntropyWeight(answer2):
#anwser2 = np.array(anwser2)
#anormalized processing
a=[]
wei=[]
for k in range(0,2): #go through each row
Z = answer2[k,:] / answer2[k,:].sum(axis=0)
entropy = np.sum(-Z * np.log(Z) / np.log(len(answer2[k,:])), axis=0)
a.append(1-entropy)
b=a[0]+a[1]
wei=a/b
return wei
#calculate the scores and normalize them
def TOPSIS(answer2, weight=None):
list_max = np.array([np.max(answer2[0,:]),np.max(answer2[1,:])]) #calculate the maximum value of each column
list_min = np.array([np.min(answer2[0,:]),np.min(answer2[1,:])]) #calculate the minimum value of each column
max_list = [] #store the maximum distance between i-th object and maximum value
min_list = [] #store the minimum value between i-th object and minimum value
answer_list=[] #strore the un-normalized scores of objects
weight = EntropyWeight(answer2) if weight is None else np.array(weight)
#print weight
for k in range(0,np.size(answer2,axis = 1)): #traversing each column of data
max_sum = 0
min_sum = 0
for q in range(0,2): #have two measures
#print np.power(answer2[q,k]-list_max[q],2)
max_sum += np.power(answer2[q,k]-list_max[q],2) #calculate the Di+ by column
min_sum += np.power(answer2[q,k]-list_min[q],2) #*weight[k] #calculate the Di- by column
max_sum=max_sum*weight[0]
min_sum=min_sum*weight[1]
max_list.append(pow(max_sum,0.5))
min_list.append(pow(min_sum,0.5))
answer_list.append(min_list[k]/ (min_list[k] + max_list[k])) #according tothe fomula: Si = (Di-) / ((Di+) +(Di-))
max_sum = 0
min_sum = 0
answer = np.array(answer_list) #normalize the socres
#answer = answer / np.sum(answer)
#print answer
rank=sorted(answer, reverse=True)
print answer
A=rank[0:len(rank)]
I = []
for i in range(0,len(A)):
for k in range(0,len(answer)):
if answer[k] == A[i]:
I.append(k)
print rank[0:len(rank)]
print I[0:len(I)]
rank=[I, rank]
rank=list(map(list, zip(*rank)))
return rank
|
from queue import Queue
def bfs(start_state, goaltest):
"""
Find a sequence of moves through a state space by breadth first search.
This function returns a policy, i.e. a sequence of actions which, if
applied to `start_state` in order, will transform it to a state which
satisfies `goaltest`.
Parameters
----------
start_state : State
State object with `successors` function.
goaltest : Function (State -> bool)
A function which takes a State object as parameter and returns true if
the state is an acceptable goal state.
Returns
-------
list of actions
The policy for transforming start_state into one which is accepted by
`goaltest`.
"""
# Is the start_state also a goal state? Then just return!
if goaltest(start_state):
return []
# Otherwise...
# Need to keep track of visited states to make sure that there are no loops.
# The start_state is already checked above, so add that.
visited = {start_state}
# And we also need a dictionary to look up predecessor states and the
# the actions which took us there. It is empty to start with.
predecessor = {}
# Use a queue to track the states which should be expanded.
Q = Queue()
# Initially there's only the start state.
Q.put(start_state)
# Begin search.
while not Q.empty():
# Get next state to be expanded.
state = Q.get()
# Check all its successor states.
for (action,ss) in state.successors():
print("action", action)
print("ss", ss)
# Only work with states not already visited.
if ss not in visited:
# Update predecessor.
predecessor[ss] = (state,action)
# Check goal.
if goaltest(ss):
# This is the state we are looking for!
# Create a of actions path by stepping back through
# the predecessors.
(last_state, last_action) = predecessor[ss]
pi = [last_action]
# As long as the predecessor state is not the initial state
while last_state != start_state:
# Update the policy.
(last_state, last_action) = predecessor[last_state]
pi.append(last_action)
# Return the policy, reversed (because we constructed it
# from end to start state).
return reversed(pi)
# Not a goal state, need to keep searching.
# Mark state as visited.
visited.add(ss)
# Enqueue successor.
Q.put(ss)
# If the queue becomes empty without the goal test triggering a return
# there is no policy, so return None.
return None
if __name__ == "__main__":
from knightsstate import KnightsState
# Example 1
#
# KK...... ........
# KK...... ........
# ........ ..KK....
# ........ ..KK....
# ........ ........
# ........ ........
# ........ ........
# ........ ........
print("Move four knights in a 2 by 2 formation 2 steps diagonally.")
print("This will take about a second to solve.")
ks1 = KnightsState([(0,0),(0,1),(1,0),(1,1)])
ks2 = KnightsState([(2,2),(2,3),(3,2),(3,3)])
print("Start state:")
print(ks1)
print("Target state:")
print(ks2)
pi = bfs(ks1, lambda s : s == ks2)
print(f"Policy: {', '.join(str(a) for a in pi)}")
print("---------------------------------------------------")
# Example 2
# KKK..... ........
# KK...... ........
# ........ ..KKK...
# ........ ..KK....
# ........ ........
# ........ ........
# ........ ........
# ........ ........
print("Move five knights in a 3+2 formation 2 steps diagonally.")
print("This will take about 20 seconds to solve.")
ks1 = KnightsState([(0,0),(0,1),(0,2),(1,0),(1,1)])
ks2 = KnightsState([(2,2),(2,3),(2,4),(3,2),(3,3)])
print("Start state:")
print(ks1)
print("Target state:")
print(ks2)
pi = bfs(ks1, lambda s : s == ks2)
print(f"Policy: {', '.join(str(a) for a in pi)}")
print("---------------------------------------------------")
# Example 3
#
# KKK..... ........
# KKK..... ........
# ........ ..KKK...
# ........ ..KKK...
# ........ ........
# ........ ........
# ........ ........
# ........ ........
print("Move six knights in a 3+3 formation 2 steps diagonally.")
print("This will take about one minute to solve.")
ks1 = KnightsState([(0,0),(0,1),(0,2),(1,0),(1,1),(1,2)])
ks2 = KnightsState([(2,2),(2,3),(2,4),(3,2),(3,3),(3,4)])
print("Start state:")
print(ks1)
print("Target state:")
print(ks2)
pi = bfs(ks1, lambda s : s == ks2)
print(f"Policy: {', '.join(str(a) for a in pi)}")
print("---------------------------------------------------")
|
"""
Solve a Sudoku puzzle using logic constraints.
"""
# This exercise uses Microsoft's Z3 SMT solver (https://github.com/Z3Prover/z3).
# You can install it for python using e.g. pip: `pip install z3-solver`
# or see the github page for more option.s
#
# z3 is an SMT - Satisfiability Modulo Theories - solver, and isn't restricted
# to working with Booleans, but for the purpose of instruction we will only
# use the Bool sort in this round.
from z3 import And,Or,Not,Bool,Solver,sat
######### Cardinality constraints #########
def allpairs(lst):
"""
Helper function, giving all pairs of a list of formulas.
Parameter
--------
lst : list of formulas
Returns
-------
generator of pairs
Each unique pairing of the formulas in `lst`.
"""
return ( (lst[i],lst[j]) for i in range(0,len(lst)) \
for j in range(i+1,len(lst)) )
def atLeast1(fmas):
"""
Expresses that at least one formula in a list must be true.
Parameters
----------
fmas : list of formulas (len > 1)
Of this list, at least one expression must evaluate to true.
Returns
-------
Formula
"""
# At least one true is easy. Disjuction.
return Or(fmas)
def atMost1(fmas):
"""
Expresses that at most one formula in a list must be true.
Parameters
----------
fmas : list of formulas (len > 1)
Of this list, at least at most one must be true.
Returns
-------
Formula
"""
# TASK 1: Implement atMost1 - see lecture material for definition.
# Hint: You can use the function 'allpairs' above to get the pairing
# of formulas.
return And([Not(And(pair)) for pair in allpairs(fmas)]) # YOUR FORMULA HERE
def exactly1(fmas):
"""
Expresses that exactly one formula in a list must be true.
Parameters
----------
fmas : list of formulas (expressed as And, Or, Not, or using a Bool Atom).
Of this list, at least one expression must evaluate to true.
Returns
-------
Formula
"""
# TASK 2: Implement exactly1 - see lecture material for definition.
return And(atLeast1(fmas), atMost1(fmas)) # YOUR FORMULA HERE
######### Translation of Sudoku to propositional logic #########
def S(c,r,n):
"""
Creates an atom expressing that the cell at r,c contains number n.
This is just a wrapper to create a Bool constant with a string
representing the particular row, column, number.
Note: In the lecture material the order of row and column are swapped,
so that S(r,c,v) is denoted S_{c,r,v}.
Parameters
----------
r : int in [1,9]
Row coordinate.
c : int in [1,9]
Column coordinate.
n : int in [1,9]
Integer.
Returns
-------
z3.BoolRef
Boolean valued atom to be used in formulas.
"""
return Bool(f"{r}_{c}_{n}")
def sudoku2fma(puzzle):
"""
Map 9X9 Sudoku instances to propositional formulas.
Parameters
----------
puzzle : dict of (row, column) : number
The given Sudoku clues as the number for location (row, column).
row, column, and number all in the range [1,9]
A missing (row,column) key indicates that the number at that location
is unknown.
Returns
-------
tuple
(C1,C2,C3,C4,C5) as Z3 formulas.
"""
# Note: In the lecture material the order of row and column are swapped,
# so that S(r,c,v) is denoted S_{c,r,v}.
# Consequently the constraints C2 and C3 have changed order here.
# This does not really matter due to symmetry - as long as one of them deals
# with rows and the other with columns, but just in case you notice
# and wonder about it while reading the code.
# In formulas C2 to C4 below, instead of exactly1 it would be logically
# equivalent to use Or - the lecture slides show both alternatives.
# However, the exactly1 allows Unit Propagation in basic DPLL solvers
# to infer far more new literals, and cutting down the size of the search tree
# to a small fraction.
# For z3 - the solver we use now, this should matter little in this case,
# but have a go at using exactly1 in any case.
# Note: In the lecture material the order of row and column are swapped,
# so that S(r,c,v) is denoted S_{c,r,v}.
# This does not really matter due to symmetry - as long as one of them deals
# with rows and the other with columns, but just in case you notice
# and wonder about it while reading the code.
# Constraints
# -----------
# Every grid cell has exactly one value, basically:
# there is exactly one of numbers 1..9 in (1,1) and in (1,2) and in (1,3)
# ... and in (2,1) and ... in (9,9).
C1 = And([exactly1([S(r,c,n) for n in range(1,10)]) for r in range(1,10) for c in range(1,10) ])
# Tasks 3-4
# Every column/row has all numbers.
# E.g. for columns this is saying:
# exactly one of (1,1), (2,1), ... is number 1 for column 1,
# and exactly one of (2,1), (2,2) ... is number 1 for column 2,
# AND so on for all columns and numbers.
# TASK 3: constraint for rows (or columns)
C2 = And([exactly1([S(r,c,n) for r in range(1,10)]) for n in range(1,10) for c in range(1,10)]) #YOUR FORMULA HERE
# TASK 4: constraint for columns (rows if you did columns in TASK 2).
C3 = And([exactly1([S(r,c,n) for c in range(1,10)]) for n in range(1,10) for r in range(1,10)]) #YOUR FORMULA HERE
# TASK 5 Implement the constraint for sub-squares.
# Every 3X3 sub-grid has all numbers.
# This should state that for all locations within the sub-square 1..3 x 1..3
# there can be only a single number 1, AND within the sub-square 4..6 x 1.3
# there can be only a single number 1, AND ...
# so on for every sub-square and for every number.
#
# It is then a conjunction (And) of a long list of exactly1 over the sub-squares
# for each number and for each sub-square.
C4 = And([exactly1([S(3*r+i,3*c+j,n) for i in range(1,4) for j in range(1,4)]) for r in range(3) for c in range(3) for n in range(1,10)]) # YOUR FORMULA HERE
# The solution respects the given clues
C5 = And([S(r,c,puzzle[(r,c)]) for (r,c) in puzzle])
return (C1,C2,C3,C4,C5)
### Print and display helper function
def sudoku2str(puzzle):
"""
Produces a multi-line string representing a Sudoku board.
Fills in the number of a location if it is part of the puzzle or uses '.'
if missing.
Parameters
----------
puzzle : dict of (row, column) : number
The given Sudoku clues as the number for location (row, column).
row, column, and number all in the range [1,9]
A missing (row,column) key indicates that the number at that location
is unknown.
Returns
-------
str
Multi-line string of the board.
"""
board = ""
for r in range(1,10):
for c in range(1,10):
if (r,c) in puzzle:
board+= str(puzzle[(r,c)])
else:
board+='.'
# After column 3 and 6 we put a grid divider, |
if c in (3,6):
board+='|'
# Newline after each row.
board+='\n'
# And a divider line after row 3 and 6.
if r in (3,6):
board+="===|===|===\n"
return board
# Solver function
def solve_sudoku(formulas):
"""
Attempts to solve a Sudoku instance given formulas.
Parameters
----------
formulas : tuple (or list)
These are the formulas describing the Sudoku instance, e.g. as returned
by `sudoku2fma`.
Returns
-------
dict of (row,column) : number or None
None if no solution is found, or a solution in the form of a dictionary
mapping from row,column pairs to the number at that location.
"""
# Create z3 solver
s = Solver()
# Add formulas.
s.add(formulas)
if s.check() != sat:
# There is no solution!
return None
# There's a solution, get a model and reconstruct the puzzle.
m = s.model()
# Now we have to check which of the atoms (i.e Boolean constants -
# see function `S` above) is True, this indicates that the solution
# has the number at that row,col coordinate.
solution = {} # We'll place the solution in this dict.
for r in range(1,10):
for c in range(1,10):
for n in range(1,10):
# Reconstruct the atom and evaluate it in the model.
# If true it means that that number is on that location, and
# we add it to the model.
if m.evaluate(S(r,c,n)) == True:
solution[(r,c)] = n
return solution
if __name__ == "__main__":
print("Example Sudokus. These should all take at most a few seconds each to solve.")
print("---------------------------------------------------------------------------")
print("AN EASY SUDOKU")
print("--------------\n")
# The easy ones are solved almost without search, just by performing
# unit propagation. A little bit harder ones require from humans looking
# ahead at the possibilities, and this means case analysis on at least
# some of the propositional variables.
puzzle0 = {(8, 1): 9, (6, 1): 8, (5, 2): 4, (1, 2): 5, (9, 3): 4, (7, 3): 8, (6, 3): 5, (2, 3): 9, (1, 3): 3, (7, 4): 9, (6, 4): 1, (4, 4): 4, (3, 4): 5, (2, 4): 7, (7, 5): 3, (2, 5): 8, (7, 6): 1, (6, 6): 9, (4, 6): 6, (3, 6): 3, (2, 6): 2, (9, 7): 8, (7, 7): 4, (6, 7): 3, (2, 7): 6, (1, 7): 7, (5, 8): 6, (1, 8): 9, (8, 9): 6, (6, 9): 2}
print(sudoku2str(puzzle0))
puzzle0fma = sudoku2fma(puzzle0)
p0sol = solve_sudoku(puzzle0fma)
if None == p0sol:
print("No solution found [There should be one]!")
else:
print(sudoku2str(p0sol))
print("-------------------------------------------------------------------\n")
print("SUDOKU FROM LECTURE")
print("-------------------\n")
puzzle1 = {(7, 1): 3, (2, 1): 4, (8, 2): 5, (3, 2): 2, (6, 3): 1, (5, 3): 8, (9, 4): 8, (8, 4): 1, (7, 4): 4, (6, 5): 9, (4, 5): 5, (9, 6): 6, (7, 7): 2, (5, 7): 3, (4, 7): 4, (1, 8): 1, (4, 9): 7}
print(sudoku2str(puzzle1))
puzzle1fma = sudoku2fma(puzzle1)
p1sol = solve_sudoku(puzzle1fma)
if None == p1sol:
print("No solution found [There should be one]!")
else:
print(sudoku2str(p1sol))
print("-------------------------------------------------------------------\n")
print("ARTO INKALA'S 'WORLD'S HARDEST SUDOKU'")
print("--------------------------------------\n")
puzzle2 = {(1, 1): 8, (9, 2): 9, (4, 2): 5, (3, 2): 7, (8, 3): 8, (7, 3): 1, (2, 3): 3, (8, 4): 5, (6, 4): 1, (2, 4): 6, (5, 5): 4, (3, 5): 9, (5, 6): 5, (4, 6): 7, (9, 7): 4, (5, 7): 7, (3, 7): 2, (8, 8): 1, (7, 8): 6, (6, 8): 3, (7, 9): 8}
print(sudoku2str(puzzle2))
puzzle2fma = sudoku2fma(puzzle2)
p2sol = solve_sudoku(puzzle2fma)
if None == p2sol:
print("No solution found [There should be one]!")
else:
print(sudoku2str(p2sol))
|
import random
from math import inf
# Evaluate a state
# Monte Carlo search: randomly choose actions
def mc_trial(player, state, steps_left):
"""
Recursively perform Monte Carlo Trial randomly choosing among available
actions for next state.
Performs at most steps_left moves, if steps_left = 0 or if there are no
applicable actions for `player` in `state`, it will return the state value.
Parameters
----------
player : int in [0,1]
Current player.
state : GameState object.
See `gamestate.py`.
steps_left : int >= 0
Maximum number of recursive levels to perform.
Returns
-------
float
Value of final state.
"""
# TASK 2.1: Implement mc_trial such that your code chooses one action uniformly
# at random, executes it to obtain a successor state, and continues simulation
# recursively from that successor state, until there are no steps left. Then the
# value of the state is returned.
# CODE HERE
if steps_left == 0 or len(state.applicable_actions(player)) == 0:
return state.value()
player_2 = 1 - player
# Choose one action uniformly at random out of the possible actions
action = random.choice(state.applicable_actions(player))
# Execute action to obtain a successor state
successor = state.successor(player, action)
# Continue simulation recursively from successor state
value = mc_trial(player_2, successor, steps_left - 1)
return value
def mc_search(player, state, trials, trial_depth):
"""
Repeatedly perform Monte Carlo Trials and return the average value.
Parameters
----------
player : int in {0,1}
Current player.
state : GameState object.
See `gamestate.py`.
trials : int > 0
Number of Monte Carlo Trials to perform.
trial_depth : int > 0
Maximum number of recursive depth per for each trial.
Returns
-------
float
Average value of the trials.
"""
# TASK 2.2: Execute mc_trial `trial` number of times, and return the average of
# the results.
# CODE HERE
sum_value = 0
for n in range(trials):
sum_value += mc_trial(player, state, trial_depth)
return sum_value / n
# ------------------------------------------------------------------------------
### TOP-LEVEL PROCEDURE FOR USING MONTE CARLO SEARCH
### The game is played by each player alternating
### with a choice of their best possible action,
### which is chosen by evaluating all possible
### actions in terms of the value of the random
### walk in the state space a.k.a. Monte Carlo Search.
def mc_execute(player, state, moves_left, trials):
"""
Recursively play a game using Monte Carlo Search printing successive states.
Function alternates between players.
Parameters
----------
player : int in {0,1}
Current player.
state : Object representing game state.
See `gameexamples.py` for examples.
moves_left : int >= 0
Number of moves to simulate.
trials : int > 0
Number of Monte Carlo Trials in each sample.
"""
if moves_left > 0:
if player == 0:
bestScore = inf # Default score for minimizing player
else:
bestScore = -inf # Default score for maximizing player
actions = state.applicable_actions(player)
if len(actions) > 0:
for action in actions:
state0 = state.successor(player, action)
v = mc_search(1 - player, state0, trials, moves_left)
if player == 1 and v > bestScore: # Maximizing player chooses highest score
bestAction = action
bestScore = v
if player == 0 and v < bestScore: # Minimizing player chooses lowest score
bestAction = action
bestScore = v
state2 = state.successor(player, bestAction)
return mc_execute(1 - player, state2, moves_left - 1, trials)
return state.value()
if __name__ == "__main__":
from tictactoestate import *
from pursuitstate import *
ttt = TicTacToeState();
# Next tests play the games by choosing the next actions according
# to the most promising action found by Monte Carlo Search.
# Comments:
# If both players play optimally, Tic Tac Toe ends in a draw. A basic tree
# search trivially finds the optimal moves for both players, but MCS even
# with thousands of simulations does not always yield the best moves, and
# the above simulation often ends up one player winning.
# The pursuit-escape game is played better by MCS. Only in testgrid3 can
# the crook evade capture by the police. MCS often chooses the best
# moves for the police, but not always.
# No score printed due to the nondeterministic nature.
print("###################### PLAY TIC TAC TOE ######################")
v = mc_execute(0, ttt, 12, 5000)
if v == 0:
print("Draw")
elif v < 0:
print("Player 0 wins.")
else:
print("Player 1 wins.")
testgrid1 = PursuitState(6, 4, [[0, 0, 0, 0, 0, 0, 0],
[0, -1, 0, -1, 0, -1, 0],
[0, -1, 0, -1, 0, -1, 0],
[1, -1, 1, -1, 1, -1, 1],
[1, -1, 1, -1, 1, -1, 1]],
0, 0, 6, 0, 0);
testgrid2 = PursuitState(3, 3, [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 0]],
0, 0, 3, 0, 0);
testgrid3 = PursuitState(3, 3, [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, -1, 0],
[1, 0, 0, 0]],
0, 0, 3, 0, 0);
testgrid4 = PursuitState(3, 3, [[0, 0, 0, 0],
[0, -1, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 0]],
0, 0, 3, 0, 0);
print("###################### CHASE IN TEST GRID 1 ######################")
v = mc_execute(0, testgrid1, 20, 2000)
if v < 0:
print("The robber got caught (at least once).")
else:
print("The robber can avoid the police.")
print("###################### CHASE IN TEST GRID 2 ######################")
v = mc_execute(0, testgrid2, 30, 3000)
if v < 0:
print("The robber got caught (at least once).")
else:
print("The robber can avoid the police.")
print("###################### CHASE IN TEST GRID 3 ######################")
v = mc_execute(0, testgrid3, 30, 2000)
if v < 0:
print("The robber got caught (at least once).")
else:
print("The robber can avoid the police.")
print("###################### CHASE IN TEST GRID 4 ######################")
v = mc_execute(0, testgrid4, 30, 2000)
if v < 0:
print("The robber got caught (at least once).")
else:
print("The robber can avoid the police.")
|
#27 Process Class in python
class Process:
def __init__(self,slice,input_output,waiting,arrival,burst):
self.slice=slice
self.input_output=input_output
self.waiting=waiting
self.arrival=arrival
self.burst=burst
self.remainingQuantum=0
self.comming_back_time=0
def showProcess(self):
print(str(self.slice)+" "+str(self.input_output)+" "+str(self.waiting)+" "+str(self.arrival)\
+" "+str(self.burst))
def change_burst(self,value):
self.burst=self.bust-value
def return_all(self):
list=[self.slice,self.input_output,self.waiting,self.arrival,self.burst]
return list
class Que:
def __init__(self,s):
if(s>0):
self.size=s
self.array={}
self.inque=-1
self.deque=-1
else:
print("Que of negative size or zero size is not allowed")
exit(0)
def IsEmpty(self):
return (self.inque == -1)
def IsFull(self):
return ((self.inque == self.size-1 and self.deque == 0) or (self.inque == self.deque-1))
def enque(self,value):
if (self.IsFull()):
print("You cannot enter more items in que because que is full.")
else:
if (self.IsEmpty()):
self.deque=0
self.inque=(self.inque+1)%self.size
temp_list=[]
temp_list.append(value)
self.array[self.inque]=value
def deeque(self):
if(self.IsEmpty()):
print("The que is already empty")
else:
if(self.deque!=self.inque):
temporay=self.array[self.deque].return_all()
self.deque = (self.deque+1)%self.size
return temporay
else:
temporay=self.array[self.deque].return_all()
self.inque=-1
self.deque=-1
return temporay
def showQue(self):
if self.IsEmpty():
print("Que is empty")
elif self.deque < self.inque:
for i in range (self.deque,self.inque+1):
print(self.array[i].return_all())
# print("First")
elif(self.inque < self.deque):
i=self.deque
while i!=self.inque:
print(self.array[i].return_all())
# print("Second")
i=(i+1)%size
print(self.array[i])
else:
print(self.array[self.inque].return_all())
def clear(self):
if (not self.IsEmpty()):
self.inque=-1
self.deque=-1
def get_deque_value(self):
temporary=self.array[self.deque].return_all()
return temporary
def convert_list_to_Process(list):
process=Process(list[0],list[1],list[2],list[3],list[4])
return process
def check_which_equal_values_tabelQue(i,Q):#this one is for tabel Que que
while True:
c=0
Return_list=[]
temp_list=Q.get_deque_value()
if(i==temp_list[3]):
c+=1
Return_list.append(temp_list)
garbage=Q.deeque()
temp_list=Q.get_deque_value()
if(i==temp_list[3]):
continue
else:
break
if(c!=0):
R=[]
R.append(c)
R.append(Return_list)
return R
else:
R=[-1]
return R
def check_which_equal_values_of_waitingQue(i,Q):#this one is for waiting que
while True:
c=0
Return_list=[]
temp_list=Q.get_deque_value()
if(i==temp_list[6]):
c+=1
Return_list.append(temp_list)
garbage=Q.deeque()
temp_list=Q.get_deque_value()
if(i==temp_list[3]):
continue
else:
break
if(c!=0):
R=[]
R.append(c)
R.append(Return_list)
return R
else:
R=[-1]
return R
def check_and_change_all_ques(i,tabelQue,waitingQue,readyQue):
receive=check_which_equal_values_tabelQue(i,tabelQue)
if(receive[0]=-1):#checkinng is there any process arives.
count=receive[0]
temp_list=receive[1]
for k in range (count):
temp=convert_list_to_Process(temp_list[i])
readyQue.enque(temp)
receive=check_which_equal_values_of_waitingQue(i,waitingQue)
if(receive[0]=-1):#checkinng is there any process is ready to come from waiting Que.
count=receive[0]
temp_list=receive[1]
for k in range (count):
temp=convert_list_to_Process(temp_list[i])
readyQue.enque(temp)
#Main
print("Main")
tabelQue=Que(1000)
readyQue=Que(1000)
waitingQue=Que(1000)
dictionary={}#for sorting purpose
no_of_inputs=int(raw_input("How Many processes you want to enter? : "))
if no_of_inputs<0:
print("Sorry negative or zero number of processes are not allowed.")
exit(0)
else:
slice=int(raw_input("Enter the slice time : "))
if slice<0:
print("Zero or negative slice time is not allowed ")
exit(0)
else:
input_output=int(raw_input("Enter Input/output time\nOR\nEnter the time after which"\
" the process will go for inputs : "))
waiting=int(raw_input("Enter the waiting time : \nOR\nEnter the time"\
"for which a process will wait in waiting que: "))
for i in range(no_of_inputs):
temporary_dic2={}#for sorting purpose
arrival=int(raw_input("Enter the Arrival time : "))
burst=int(raw_input("Enter the burst time : "))
temporary_dic2["arival"]=arrival
temporary_dic2["burst"]=burst
dictionary[i]=temporary_dic2
#insertion sort starts
n=len(dictionary)
i=1
for i in range(n):
j=i
while (j>0) and (dictionary[j].get("arival")<dictionary[j-1].get("arival")):
temporary_value=dictionary[j]
dictionary[j]=dictionary[j-1]
dictionary[j-1]=temporary_value
j-=1
#tested
i=0
while True:
if i<no_of_inputs:
process=Process(slice,input_output,waiting,dictionary[i].get("arival"),\
dictionary[i].get("burst"))
#tested
tabelQue.enque(process)
i+=1;
else:
break
#tested
i=0#universal time
j=0
w=0 #waiting counter
k=0
while True:
if (readyQue.IsEmpty() and tabelQue.IsEmpty() and waitingQue.IsEmpty()):
break #this condition tells that our all process are ended.
else:
check_and_change_all_ques(i,tabelQue,waitingQue,readyQue)
list_temp=readyQue.deeque()
while(i != list_temp[3]):
i+=1
check_and_change_all_ques(i,tabelQue,waitingQue,readyQue)
continue
slice=list[0]
input_output=list[1]
waiting=list[2]
arrival=list[3]
burst=list[4]
remainingQuantum=list[5]
j=0
if(remainingQuantum>0):
while j<remainingQuantum:
j+=1
i+=1
list[5]-=1#Remaninig Quantum time
list[4]=list[4]-1#burst
list[1]=list[1]-1#input/output going time
check_and_change_all_ques(i,tabelQue,waitingQue,readyQue)
if(j!=input_output and j!=burst):
continue
else:
if (j== input_output):
list[6]=i+list[2]
list=convert_list_to_Process(list)
waitingQue.enque(list)
break
else:
break
else:
list[5]=0
while True:
if(j!=input_output and j!= slice and j!=burst):
list[5]-=1#Remaninig Quantum time
list[4]=list[4]-1#burst
list[1]=list[1]-1#input/output going time
j+=1
i+=1
check_and_change_all_ques(i,tabelQue,waitingQue,readyQue)
elif(i==burst):
break
elif(i==input_output):
list[6]=i+list[2]
list=convert_list_to_Process(list)
readyQue.enque(list)
break
elif(i==slice):
list=convert_list_to_Process(list)
readyQue.enque(list)
break
|
class Coordenada:
def __init__(self,x,y):
self.x, self.y = x, y
def move(self, delta_x, delta_y):
return Coordenada(self.x + delta_x, self.y + delta_y)
def dist(self, other_coor):
dif_x = self.x - other_coor.x
dif_y = self.y - other_coor.y
return(dif_x**2 + dif_y**2)**.5 |
class Employee:
company = 'Google'
def getSalary(self):
print (f'Salary for {self.name} working in {self.company} is {self.salary}')
nirmit = Employee()
nirmit.name = 'Nirmit'
nirmit.salary = 100000
nirmit.getSalary()
# Employee.getSalary(nirmit)
# actually nirmit.getSalary() converts to Employee.getSalary(nirmit) in machine point of view
|
# fizbuzz test
def fizzbuzz(start, end):
fizzbuzz = []
for i in range(start,end):
if i % 3 == 0 and i % 5 == 0:
fizzbuzz.append('fizzbuzz')
elif i % 3 == 0:
fizzbuzz.append('fizz')
elif i % 5 == 0:
fizzbuzz.append('buzz')
else:
fizzbuzz.append(str(i))
return fizzbuzz
print(fizzbuzz(1,101))
def fizzbuzz2(start, end):
fizzbuzz = []
for i in range(start,end):
output = ''
if i % 3 == 0: output += 'fizz'
if i % 5 == 0: output += 'buzz'
if output == '':
fizzbuzz.append(str(i))
else:
fizzbuzz.append(output)
return fizzbuzz
print(fizzbuzz2(1,101)) |
# coding=utf-8
c = int(input("请您输入当前的摄氏温度"))
f = 9*c/5+32
print("当前的华氏温度为: " + str(f)) |
# coding=utf-8
successed = "no" #这是个开关
while successed == "no":
username = input("Please input your username/请输入你的用户名")
pw = input("Please input your password/请输入你的密码")
if username == "will":
if pw == "1234":
print("欢迎登陆, "+ username)
successed = "yes"
else:
print(username+ "你是不是输错了密码?")
elif username == "tom":
if pw == "abcd":
print("欢迎登陆, " + username)
successed = "yes"
else:
print(username+ "你是不是输错了密码?")
else:
print("你是不是连用户名都忘啦!")
print("欢迎进入xxx系统,请开始您的操作吧!")
|
# coding=utf-8
score = 0
print("来参加这个小测试,试验一下你有多了解我吧!")
print("题目1:我喜欢什么颜色?")
print("a:黑色black?")
print("b:白色white?")
print("c:粉红色pink?")
ans = input("please input your answer ")
if ans == "a":
print("恭喜你选对啦!")
score = score +10
else:
print("你猜错啦!")
print("题目2:我喜欢吃什么?")
print("a:蔬菜vegetables?")
print("b:汉堡burgers?")
print("c:鱼fish?")
ans = input("please input your answer ")
if (ans == "b"):
print("恭喜你选对啦!")
score = score +10
else:
print("你猜错啦!")
print("你与我的熟识度为"+ str(score) + "分")
|
# Time Complexity : O(NlogN) for sorting
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
# sort the numbers at add all numbers at even positions
# to get the maximum sum of the minimum element of all pairs
# sorting works as when sorted, the pairs have the first element(even index element)
# as the minimum of the pair
# if we sort and take pairs as idx (0, n-1), (1, n-2) and so on,
# we get minimum sum
class Solution:
def arrayPairSum(self, nums):
if nums is None or len(nums) == 0:
return 0
result = 0
nums.sort()
for i in range(0, len(nums), 2):
result += nums[i]
return result |
class Track:
def __init__(self, trackname, tracklength):
self.name = trackname
self.length = tracklength
def __str__(self):
return f'Name: \"{self.name}\" | Length: {self.length} minutes'
def __lt__(self, other):
return print(self.length < other.length)
def __gt__(self, other):
return print(self.length > other.length)
def __eq__(self, other):
return print(self.length == other.length)
def __le__(self, other):
return print(self.length <= other.length)
def __ge__(self, other):
return print(self.length >= other.length)
class Album:
def __init__(self, albumname, band):
self.name = albumname
self.band = band
self.tracklist = []
def __str__(self):
printable_tracklist = ''
for track in self.tracklist:
printable_tracklist += ('\t' + str(track) + '\n')
return f'Album name: \"{self.name}\" \nAlbum author: \"{self.band}\"\nTracks: \n{printable_tracklist}'
def add_track(self, trackname, tracklength):
self.tracklist.append(Track(trackname, tracklength))
def get_duration(self):
duration = 0
for track in self.tracklist:
duration += track.length
return duration
def create_audio_collection():
global album_a
global album_b
album_a = Album('The album A', 'The band A')
album_b = Album('The album B', 'The band B')
album_a.add_track('The song one', 1)
album_a.add_track('The song two', 2)
album_a.add_track('The song three', 3)
album_b.add_track('The song four', 4)
album_b.add_track('The song five', 5)
album_b.add_track('The song six', 6)
album_a.tracklist[1] > album_b.tracklist[2]
album_a.tracklist[1] < album_b.tracklist[2]
album_a.tracklist[1] == album_b.tracklist[2]
album_a.tracklist[1] <= album_b.tracklist[2]
album_a.tracklist[1] >= album_b.tracklist[2]
print(album_a)
print(album_b)
create_audio_collection()
print(f'Album A duration: {album_a.get_duration()} mins.')
print(f'Album B duration: {album_b.get_duration()} mins.') |
from enum import Enum
class Suit(Enum):
spades = 1
clubs = 2
diamonds = 3
hearts = 4
def __str__(self):
suit_names = {
1: "spades",
2: "clubs",
3: "diamonds",
4: "hearts"
}
return suit_names[self.value]
|
"""
This is an example to show how usefull (or not!) is to create
objects by reference in python
"""
# Lets create a dictionary like this one:
# a = {
# "dog" : {
# "name" : "Boobis",
# "eats" : ["meat", "treats", "anything that smells great"]
# },
# "cat" : {
# "name" : "Logan",
# "eats" : ["meat", "fish", "Boobis' food"]
# },
# # ....
# }
# For a lot of animals
kinds_of_animals = ["dog", "cat", "elephant", "fish"]
animal_information = {
"name" : "",
"eats" : []
}
animals = dict(zip(
kinds_of_animals,
[animal_information]*len(kinds_of_animals)
))
animals["dog"]["name"] = "Boobis"
print(animals)
# All the animals' names are now "Boobis" because
# the animal_information dictionary is passed by reference
|
def insert(self, val):
if self.root== None:
self.root= Node(val)
root= self.root
while True:
if val > root.info:
if root.right:
root= root.right
else:
root.right=Node(val)
break
elif val < root.info:
if root.left:
root= root.left
else:
root.left = Node(val)
break
else:
break |
## Module Car
## This is the main module of this project.
# It observes the reaction of the solution and
# controls the move and stop of the motors according
# to the timing reaction.
from motor import Motor
from timer import Timer
class Car:
def __init__(self):
self.timer = Timer()
self.motor = Motor()
def start_competition(self):
# if blue is detected, move the motor, and
self.timer.wait_solution(self.motor.light_on, self.motor.light_off)
# start the car
self.motor.move()
# wait for the timing reaction
self.timer.timing_reaction()
# when the reaction ends, stop the car
self.motor.stop()
if __name__ == '__main__':
car = Car()
car.start_competition() |
# -*- coding: utf-8 -*-
"""
Created on Fri May 8 19:54:20 2020
@author: Carlos Henrique
"""
for a in range(1,1000):
for b in range(1,1000):
for c in range(1,1000):
if (a**2 + b**2 == c**2 and a < b and b < c):
if a + b + c == 1000:
print(a*b*c) |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 7 16:19:04 2020
@author: Carlos Henrique
"""
circ = []
primes = []
def prime(n):
if n == 2:
return True
if n > 2:
if any(n%i == 0 for i in range(2,n)):
return False
else:
return True
def circular(n):
a = [int(d) for d in str(n)]
z = str(n)
b = []
b.append(n)
for j in range(len(a)):
c = z[j:] + z[:j]
c = int(c)
b.append(c)
if all(prime(c) == True for c in b):
circ.append(n)
for k in range(2,1000000):
circular(k)
print("There are", len(circ), "numbers.")
print(prime(4))
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 19 18:07:36 2020
@author: Carlos Henrique
"""
collatz_sequence = []
collatz_sequence_2 = []
def start():
global collatz_sequence
global collatz_sequence_2
global i
collatz_sequence_2.append(i)
if i%2 == 0:
while i%2 == 0:
i = i/2
if i%2 == 0:
collatz_sequence_2.append(i)
if i == 1:
collatz_sequence_2.append(i)
if len(collatz_sequence_2) >= len(collatz_sequence):
collatz_sequence = collatz_sequence_2
collatz_sequence_2 = []
if i%2 != 0 and i !=1:
start()
if i%2 != 0 and i !=1:
i = 3*i + 1
collatz_sequence_2.append(i)
while i%2 == 0:
i = i/2
if i%2 == 0:
collatz_sequence_2.append(i)
if i%2 != 0 and i != 1:
start()
if i == 1:
collatz_sequence_2.append(i)
if len(collatz_sequence_2) >= len(collatz_sequence):
collatz_sequence = collatz_sequence_2
collatz_sequence_2 = []
for i in range(2,1000000):
start()
print(collatz_sequence)
print("The starting number which provides the longest chain is", collatz_sequence[0])
print("The lenght of the sequence is", len(collatz_sequence))
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 12:16:53 2020
@author: Carlos Henrique
"""
fibonacci = [1,1]
for i in fibonacci:
a = fibonacci[-1] + fibonacci[-2]
b = str(a)
fibonacci.append(a)
if len(b) == 1000:
print(len(fibonacci))
break
|
# -*- coding: utf-8 -*-
"""
"""
import itertools
'''
Dada la lista L de longitudes de las palabras de un código
q-ario, decidir si pueden definir un código.
'''
def kraft1(L, q=2):
acum = 0
for lon in L:
acum += 1/(q**lon)
return acum <= 1
'''
Dada la lista L de longitudes de las palabras de un código
q-ario, calcular el máximo número de palabras de longitud
máxima, max(L), que se pueden añadir y seguir siendo un código.
'''
def kraft2(L, q=2):
maxLon = max(L)
acum = 0
numWords = 0
for lon in L:
acum += 1/(q**lon)
numWords = (1 - acum) * (q**maxLon)
return int(numWords)
'''
Dada la lista L de longitudes de las palabras de un
código q-ario, calcular el máximo número de palabras
de longitud Ln, que se pueden añadir y seguir siendo
un código.
'''
def kraft3(L, Ln, q=2):
acum = 0
numWords = 0
for lon in L:
acum += 1/(q**lon)
numWords = (1 - acum) * (q**Ln)
return int(numWords)
'''
Dada la lista L de longitudes de las palabras de un
código q-ario, hallar un código prefijo con palabras
con dichas longitudes
'''
def cartProduct(list1, list2):
if not list2: # al ser una vacía el producto cartesiano también lo es
return list1
else:
return [''.join(elem) for elem in itertools.product(list2, list1)]
def Code(L,q=2):
LSorted = sorted(L)
alphabet = [str(elem) for elem in range(q)]
Code = []
prevLen = 0
remainingWords = []
for length in LSorted:
if length != prevLen:
index = 0
actLen = length - prevLen
wordsNeededLeng = [''.join(elem) for elem in itertools.product(alphabet, repeat = actLen)]
wordsActLeng = cartProduct(wordsNeededLeng, remainingWords)
else:
index += 1
Code.append(wordsActLeng[index])
remainingWords = wordsActLeng[index+1:]
prevLen = length
return Code
'''
Ejemplo
'''
L=[1,3,5,5,10,3,5,7,8,9,9,2,2,2]
print(sorted(L),' codigo final:',Code(L,3))
print(kraft1(L))
|
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cache_size = capacity
self.length = 0
self.cache = OrderedDict()
def get(self, key: int) -> int:
#print(f'trying to get key: {key}')
try:
if self.cache[key] >= 0:
#print(f'key here it is {key}')
self.cache.move_to_end(key, last=True)
return self.cache[key]
except KeyError:
#print(f'key not here it was {key}')
return -1
def put(self, key: int, value: int) -> None:
try:
# key exists -> update
if self.cache[key] >= 0:
self.cache[key] = value
except:
# key doesn't exist -> ? pop and add
if self.length < self.cache_size:
self.length += 1
else:
self.cache.popitem(last=False)
self.cache[key] = value
self.cache.move_to_end(key, last=True)
#print(f'after put operation cache is {self.cache}')
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
|
import sys
import math
while True :
text = input()
if text =="" :
break
num = long(text)
if num <= 1:
print(num)
else :
print(2*(num-1)) |
import trig
def add(a, b):
return a+b
def subtract(a, b):
return add(a, -b)
def multiply(a, b):
return a*b
def divide(a, b):
if b == 0:
return "Undefined"
else:
return multiply(a, power(b, -1))
def factorial(a):
x = 1
if a < 0:
return("Undefined")
else:
for i in range(1, a+1):
x *= i
return(x)
def power(b, x):
return b**x
def root(b, n):
if n == 2:
return sqrt(b)
else:
return power(b, power(n, -1))
def sqrt(a):
x = 10
b = abs(a)
for i in range(100):
x = ((x + (b / x)) / 2)
if a >= 0:
return x
else:
return complex(0, x)
def mod(a, b):
return a%b
|
from typing import Union
def naive_exponentiation(a: int, b: int) -> Union[int, float]:
r = 1
if b < 0:
a = 1 / a
b *= -1
for i in range(b):
r *= a
return r
def power_of_two_with_multiplication(a: int, b: int) -> Union[int, float]:
r = a
pwr = 1
previous = 0
if b < 0:
a = 1 / a
r = a
if b == -1:
return a
b *= -1
while pwr * 2 <= b:
r *= r
pwr *= 2
previous = pwr
if pwr != b:
for _ in range(b-previous):
r *= a
return r
def squaring_exponentiation(a: int, b: int) -> Union[int, float]:
# https://en.wikipedia.org/wiki/Exponentiation_by_squaring
r = 1
if b < 0:
a = 1 / a
b *= -1
if not b:
return r
while b > 0:
if b % 2:
r *= a
a *= a
b //= 2
return r
|
def gcd_subtraction(a: int, b: int) -> int:
while a != b:
if a > b:
a = a - b
else:
b = b - a
return a
def gcd_division(a: int, b: int) -> int:
while b != 0:
t = b
b = a % b
a = t
return a
def gcd_bitwise(a: int, b: int) -> int:
# recursive algorithm from https://en.wikipedia.org/wiki/Binary_GCD_algorithm
if a == b:
return a
if a == 0:
return b
if b == 0:
return a
a_is_even = ~a & 1
b_is_even = ~b & 1
if a_is_even and b_is_even: # 2. gcd(u, v) = 2·gcd(u/2, v/2)
return gcd_bitwise(a >> 1, b >> 1) << 1
elif a_is_even or b_is_even: # 3. gcd(u, v) = gcd(u/2, v) or gcd(u, v) = gcd(u, v/2)
return gcd_bitwise(a >> 1, b) if a_is_even else gcd_bitwise(a, b >> 1)
else:
if a >= b:
return gcd_bitwise((a - b) >> 1, b) # 4. gcd(u, v) = gcd((u − v)/2, v)
else:
return gcd_bitwise((b - a) >> 1, a) # 4. gcd(u, v) = gcd((v − u)/2, u)
|
from cs1graphics import *
#################################
# Global variables
index_list = [ ( 0, (0, 0) ), ( 1, (0, 2) ), ( 2, (2, 0) ), ( 3, (2, 4) ), ( 4, (4, 2) ) ]
word_list = [ ( 'ACROSS', 0, (0, 0), 3, 'BAA' ), ( 'ACROSS', 2, (2, 0), 5, 'SOLID' ), ( 'ACROSS', 4, (4, 2), 3, 'WIT' ), ( 'DOWN', 0, (0, 0), 3, 'BUS' ), ( 'DOWN', 1, (0, 2), 5, 'ALLOW' ), ( 'DOWN', 3, (2, 4), 3, 'DOT' ) ]
word_description = [ ( 'ACROSS', 0, 'Sheep sound' ), ( 'ACROSS', 2, 'Neither liquid nor gas' ), ( 'ACROSS', 4, 'Humour' ), ( 'DOWN', 0, 'Road passenger transport' ), ( 'DOWN', 1, 'Permit' ), ( 'DOWN', 3, 'Shortened form of Dorothy' ) ]
word_state = [ 0, 0, 0, 0, 0, 0 ]
cell_size = 70
row_size = 5
col_size = 5
canvas_width = cell_size * col_size
canvas_height = cell_size * row_size
canvas = Canvas( canvas_width, canvas_height, 'black', 'CS101 - Crossword Puzzle' )
#################################
# Definition of functions
def draw_indices( _canvas, _index_list, _cell_size ) :
for i in range( len( _index_list ) ) :
a_word_index = Text()
'''
[ Goal ]
Draw each index in the '_index_list' on the right location of the crossword game canvas.
[ Requirements ]
Each index is represented by a 'Text' object, which has attributes as follows :
(1) The color of a 'Text' object is 'black'.
(2) The size of a 'Text' object is 15.
(3) The depth of a 'Text' object is 30.
(4) The proper index should be set to a 'Text' object.
(5) The position of a 'Text' object is upper-left corner of the cell.
Note : Do not use global variables. Otherwise, you will get penalized.
Hint : getDimensions() function returns the size of a 'Text' object by 'tuple' object.
x_pos, y_pos = a_word_index.getDimensions()
x_pos = x_pos/2 + _cell_size * (column_of_the_text_object)
y_pos = y_pos/2 + _cell_size * (row_of_the_text_object)
'''
# Do something on here !!!
_canvas.add( a_word_index )
def draw_horizontal_line( _canvas, _row_size, _cell_size ) :
_canvas_width = _canvas.getWidth()
for y in range( 1, _row_size ) :
line = Path()
'''
[ Goal ]
Draw each horizontal line on the right location of the crossword game canvas.
[ Requirements ]
Each horizontal line is represented by a 'Path' object, which has attributes as follows :
(1) The border color of a 'Path' object is 'dark gray'.
(2) The depth of a 'Path' object is 10.
(3) Each line must stretch from the left-side border of the canvas to the right-side border of the canvas.
Note : Do not use global variables. Otherwise, you will get penalized.
Hint : addPoint() function is used to add points to a 'Path' object by using 'Point' object.
'''
# Do something on here !!!
_canvas.add( line )
def draw_vertical_line( _canvas, _col_size, _cell_size ) :
_canvas_height = _canvas.getHeight()
for x in range( 1, _col_size ) :
line = Path()
'''
[ Goal ]
Draw each horizontal line on the right location of the crossword game canvas.
[ Requirements ]
Each horizontal line is represented by a 'Path' object, which has attributes as follows :
(1) The border color of a 'Path' object is 'dark gray'.
(2) The depth of a 'Path' object is 10.
(3) Each line must stretch from the top-side border of the canvas to the bottom-side border of the canvas.
Note : Do not use global variables. Otherwise, you will get penalized.
Hint : addPoint() function is used to add points to a 'Path' object by using 'Point' object.
'''
# Do something on here !!!
_canvas.add(line)
def get_a_word( _length, _word, _cell_size, _direction, _empty ) :
a_word = Layer()
for i in range( _length ) :
a_word_cell = Square()
a_word_text = Text()
'''
[ Goal ]
Draw each word cell on the right location of a word layer.
[ Requirements ]
Each word cell is represented by a 'Square' object, which has attributes as follows :
(1) The size of a 'Square' object is '_cell_size'.
(1) A 'Square' object must be filled by 'white' color.
If a word is not empty, there will be a letter on each word cell.
And each letter is represented by a 'Text' object, wich has attributes as follows :
(1) The font size is 20.
(2) The font color is 'black'
(3) The depth of a 'Text' object is 30.
(4) The proper letter should be set to a 'Text' object.
Note : Do not use global variables. Otherwise, you will get penalized.
Note : A word layer has a direction 'across' or 'down'.
If the direction of a word layer is 'across', each word cell must be put in 'horizontal' direction.
If the direction of a word layer is 'down', each word cell must be put in 'vertical' direction.
For example,
the word layer for 'down0' consists of 'B', 'U', and 'S', and the direction of the word layer is 'down'.
So, the layer must be formed like following :
==
| B |
==
| U |
==
| S |
==
The word layer for 'across2' consists of 'S', 'O', 'L', 'I', and 'D', and the direction of the word layer is 'across'.
So, the layer must be formed like following :
== == == == ==
| S | O | L | I | D |
== == == == ==
'''
# Do something on here !!!
a_word.add( a_word_cell )
if not _empty :
a_word.add( a_word_text )
if not _empty :
a_word.setDepth( 30 )
return a_word
def draw_a_word( _canvas, _row, _col, _a_word, _cell_size ) :
_a_word.moveTo( _cell_size*_col, _cell_size*_row )
_canvas.add( _a_word )
def draw_word_list( _canvas, _word_list, _word_state, _cell_size ) :
for i in range( len( _word_list ) ) :
a_word = get_a_word( _word_list[i][3], _word_list[i][4], _cell_size, _word_list[i][0], ( _word_state[i] == 0 ) )
draw_a_word( _canvas, _word_list[i][2][0], _word_list[i][2][1], a_word, _cell_size )
def is_all_found( _word_state ) :
all_found = False
'''
[ Goal ]
Check if there is a word not found yet.
[ Requirements ]
If there are still words left which are not found, 'is_all_found' function should return 'False'.
If there is no word left which are not found, 'is_all_found' function should return 'True'
Note : Do not use global variables. Otherwise, you will get penalized.
'''
# Do something on here !!!
return all_found
def print_description( _word_state, _word_description ) :
'''
[ Goal ]
Print out all the descriptions for the words, which are not found yet.
[ Requirements ]
Each line should keep the format of 'direction_num : description'.
For example,
if a word 'BAA' for 'across_0' and a word 'BUS' for 'down_0' are not found yet,
then the text like follwing is expected :
across_0 : Sheep sound
down_0 : Road passenger transport
Note : Do not use global variables. Otherwise, you will get penalized.
Note : The descriptions only for the words not found yet should be print out.
( Do not print the descriptions for the word which are already found. )
'''
# Do something on here !!!
def is_right_choice( _user_choice, _word_description, _word_state ) :
right_input = False
'''
[ Goal ]
Check if an user's choice is correct.
[ Requirements ]
If an user's choice is in the list of words which are not found yet, 'is_right_choice' function should return 'True'.
If an user's choice is not in the list of words which are not found yet, 'is_right_choice' function should return 'False'
Note : Do not use global variables. Otherwise, you will get penalized.
'''
# Do something on here !!!
return right_input
def is_right_word( _user_word, _user_choice, _word_list, _word_state ) :
right_word = False
'''
[ Goal ]
Check if an user's input word is correct.
[ Requirements ]
If an user's input word is in the list of words which are not found yet, 'is_right_word' function should return 'True'
and set the word state of the chosen word from 0 to 1.
If an user's input word is not in the list of words which are not found yet, 'is_right_word' function should return 'False'
Note : Do not use global variables. Otherwise, you will get penalized.
Note : Do not forget to set the word state of the word found from 0 to 1.
'''
# Do something on here !!!
return right_word
#################################
# Run of the program
print 'Welcome to CS101 Crossword Puzzle!'
print ''
while not is_all_found(word_state) :
canvas.clear()
draw_indices( canvas, index_list, cell_size )
draw_horizontal_line( canvas, row_size, cell_size )
draw_vertical_line( canvas, col_size, cell_size )
draw_word_list( canvas, word_list, word_state, cell_size )
print_description( word_state, word_description )
print ''
user_choice = raw_input( 'Enter a direction and number : ' )
if is_right_choice( user_choice, word_description, word_state ) :
user_word = raw_input( 'Enter a word : ' )
if not is_right_word( user_word, user_choice, word_list, word_state ) :
print 'Please, enter a word, correctly!'
else :
print 'Please, enter a direction and number, correctly!'
print ''
print 'Game complete!'
print ''
draw_indices( canvas, index_list, cell_size )
draw_horizontal_line( canvas, row_size, cell_size )
draw_vertical_line( canvas, col_size, cell_size )
draw_word_list( canvas, word_list, word_state, cell_size ) |
remainder = []
list1 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
def deci_to_any(n, rad):
a1 = n/rad
r1 = n%float(rad)
remainder.append(list1[int(r1)])
while a1 > rad:
r1 = a1%float(rad)
a1 /= rad
remainder.append(list1[int(r1)])
remainder.append(list1[int(a1%float(rad))])
remainder.append(list1[(a1/rad)])
remainder.reverse()
print "".join(remainder)
|
# ver1
from abc import abstractmethod
class Calc:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def subtract(self):
return self.x - self.y
class Calc2:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def multiply(self):
return self.x * self.y
# ver2
class Calc:
def __init__(self, x, y):
self.x = x
self.y = y
self.calc2 = Calc2(x, y)
def add(self):
return self.x + self.y
def subtract(self):
return self.x - self.y
def multiply(self):
return self.calc2.multiply()
calc1 = Calc(1, 2)
print(calc1.add())
print(calc1.subtract())
print(calc1.multiply())
class Character:
def __init__(self, name='yourname', health_point=100, striking_power=3, defensive_power=3):
self.name = name
self.health_point = health_point
self.striking_power = striking_power
self.defensive_power = defensive_power
def info(self):
print(self.name, self.health_point, self.striking_power, self.defensive_power)
@abstractmethod
def attack(self, second):
pass
@abstractmethod
def receive(self):
pass
|
#coding:utf-8
from Tkinter import *
def calcular():
print "VALORES"
lb["text"] = "VALORES"
tela = Tk()
lb = Label(tela, text="Bem Vindo!") # Isso é um componente
lb.place(x=120, y=150) #Gerenciador é o place. ()
bt = Button(tela, width=20, text="CALCULAR", command=calcular)
bt.place(x=50, y=180)
lb = Label(tela, text="") # Isso é um componente
lb.place(x=120, y=220) #Gerenciador é o place. ()
tela.title("Calculadora")
tela.geometry("300x400+200+100") #dimensões, espaços para iniciar direita,top
#tela.wm_iconbitmap('calculadora.ico')
tela["bg"] = "purple" #background
tela.mainloop()
|
import random
import itertools
from termcolor import cprint
from gameactions import play_card
def sort_hand_value(card_list):
return card_list.sort(key=lambda x: x.run_value)
class Game: # environment for the game, global var/objects should be available here
def __init__(self, first_player, second_player, deck, crib):
self.first_player = first_player # reference for the players in the game
self.second_player = second_player
self.assign_active()
self.deck = deck
self.crib = crib
self.active_player = None # determines the order of the game sequence, determined below
self.nonactive_player = None
self.turn = None
self.sequence = []
self.count = 0
self.last_play = None # True mean first_player played last, False is second_player played last
self.pair_counter = 0 # for counting how many pairs are in the sequence
self.winner = None
def assign_active(self):
self.first_player.active = random.choice([True, False])
if self.first_player.active:
self.second_player.active = False
else:
self.second_player.active = True
def give_points(self, player, points):
player.score += points
if player.score > 121 and self.winner is None:
self.winner = player
def counting_sequence(self):
self.turn = False # starts as false, so active player always plays first
while self.active_player.hand != [] or self.nonactive_player.hand != []: # play until hands are empty
input(". . .")
print("\n\n\n\n\n\n\n")
play_card(self)
self.reset_count()
self.clean_up()
input(". . .")
print("\n")
def reset_vars(self):
self.count = 0
self.sequence = []
self.pair_counter = 0
self.active_player.first_go = False
self.nonactive_player.first_go = False
self.active_player.playable_card = True
self.nonactive_player.playable_card = True
# if active_player has no cards in hand after a reset_count, it will assume nonactive player has no playable-
# cards even if they do. Setting both playable_card to True after reset_count prevents this
def reset_count(self):
if self.count == 31:
self.reset_vars()
elif not self.active_player.playable_card and not self.nonactive_player.playable_card:
self.reset_vars()
if self.last_play:
self.give_points(self.active_player, 1)
print(self.active_player.name + " gets 1 point for last card")
else:
self.give_points(self.nonactive_player, 1)
print(self.nonactive_player.name + " gets 1 point for last card")
def clean_up(self):
if self.count != 31:
if self.last_play:
self.give_points(self.active_player, 1)
print(self.active_player.name + " gets 1 point for last card")
else:
self.give_points(self.nonactive_player, 1)
print(self.nonactive_player.name + " gets 1 point for last card")
self.active_player.hand = self.active_player.void.copy()
self.nonactive_player.hand = self.nonactive_player.void.copy()
self.active_player.void.clear()
self.nonactive_player.void.clear()
self.reset_vars()
def determine_active(self): # assigns players to either active or nonactive, all subsequent events reference these
if self.first_player.active: # checks the active argument of the player
self.active_player = self.first_player
self.nonactive_player = self.second_player
else:
self.active_player = self.second_player
self.nonactive_player = self.first_player
def nibs(self):
for c in self.deck.the_cut:
if c.description == "Jack":
self.give_points(self.nonactive_player, 2)
print(self.nonactive_player.name + " gets 2 points for nibs")
def count_hand(self, player): # determine number of points in hand
hand_total = 0 # this local variable will display the amount of point in the hand
player.hand.extend(self.deck.the_cut) # adding cut to hand for counting
def sum_card_values(cards):
return sum(e.value for e in cards)
def is_run(cards):
if all((card.run_value - index) == cards[0].run_value for index, card in enumerate(cards)):
return True
def is_pair(cards):
if cards[0].run_value == cards[1].run_value:
return True
for c in range(len(player.hand)): # determining all 15's in hand
for seq in itertools.combinations(player.hand, c + 1):
if sum_card_values(seq) == 15:
self.give_points(player, 2)
hand_total += 2
cprint("15 for " + str(hand_total) + ":", "cyan")
print(seq)
run = False # this parameter helps not runs of 3 if run of 4 exists, or run of 4 if run of 5 exists
run_hand = player.hand.copy()
run_hand.sort(key=lambda x: x.run_value)
for seq in itertools.combinations(run_hand, 5): # check if there is a run of five first
if is_run(seq):
self.give_points(player, 5)
hand_total += 5
cprint("run of 5 for " + str(hand_total) + ":", "cyan")
print(seq)
run = True
if not run:
for seq in itertools.combinations(run_hand, 4): # check for runs of 4
if is_run(seq):
self.give_points(player, 4)
hand_total += 4
cprint("run of 4 for " + str(hand_total) + ":", "cyan")
print(seq)
run = True
if not run:
for seq in itertools.combinations(run_hand, 3): # check for runs of 3
if is_run(seq):
self.give_points(player, 3)
hand_total += 3
cprint("run of 3 for " + str(hand_total) + ":", "cyan")
print(seq)
for seq in itertools.combinations(player.hand, 2): # check for pairs
if is_pair(seq):
self.give_points(player, 2)
hand_total += 2
cprint("pair for " + str(hand_total) + ":", "cyan")
print(seq)
first_suit = player.hand[0].suit
flush_five = all(c == first_suit for c in ([d.suit for d in player.hand]))
if flush_five:
self.give_points(player, 5)
hand_total += 5
cprint("flush of 5 " + first_suit + " for " + str(hand_total), "cyan")
flush_four = all(c == first_suit for c in ([d.suit for d in player.hand[0:4]]))
if flush_four and not flush_five:
self.give_points(player, 4)
hand_total += 4
cprint("flush of " + first_suit + " for " + str(hand_total), "cyan")
for c in player.hand[0:4]: # check to see if there is a jack in hand and if it's the same suit as the cut
if c.run_value == 11 and c.suit == player.hand[4].suit:
self.give_points(player, 1)
hand_total += 1
cprint("right Jack for " + str(hand_total), "cyan")
print("hand total = " + str(hand_total))
def round(self): # sequence for a round of the game
self.determine_active() # determine active player
print("\n")
cprint(self.nonactive_player.name + "'s deal", "yellow")
cprint(self.nonactive_player.name + "'s crib", "yellow")
cprint(self.active_player.name + " plays and counts first", "yellow")
input(". . .")
print("\n")
self.active_player.discard_phase()
self.nonactive_player.discard_phase()
print("\n") # get the cut and check nibs
self.deck.cut()
self.nibs()
self.counting_sequence()
print("\n")
print(self.first_player.name + " score = " + str(self.first_player.score))
print(self.second_player.name + " score = " + str(self.second_player.score))
input(". . .")
sort_hand_value(self.active_player.hand)
sort_hand_value(self.nonactive_player.hand)
sort_hand_value(self.crib.cards)
print("\n") # active player show hand and count points in it
cprint(self.active_player.name + "'s hand:", "yellow")
self.active_player.show_hand_counting()
self.count_hand(self.active_player)
print(self.active_player.name + " score = " + str(self.active_player.score))
input(". . .")
print("\n") # nonactive player show hand and count point in it
cprint(self.nonactive_player.name + "'s hand:", "yellow")
self.nonactive_player.show_hand_counting()
self.count_hand(self.nonactive_player)
print(self.nonactive_player.name + " score = " + str(self.nonactive_player.score))
input(". . .")
self.active_player.empty_hand() # return hand cards to deck
self.nonactive_player.empty_hand()
print("\n") # add cards from crib to nonactive player hand and count points in hand
cprint(self.nonactive_player.name + "'s crib:", "yellow")
self.nonactive_player.crib_hand()
self.nonactive_player.show_hand_counting()
self.count_hand(self.nonactive_player)
print(self.nonactive_player.name + " score = " + str(self.nonactive_player.score))
self.nonactive_player.empty_hand()
input(". . .")
print("\n")
print("\n")
print("End Round")
print(self.first_player.name + " score = " + str(self.first_player.score))
print(self.second_player.name + " score = " + str(self.second_player.score))
input(". . .")
self.deck.empty_cut() # return cut to deck
self.deck.shuffle()
if self.first_player.active: # switch active and nonactive player
self.first_player.active = False
self.second_player.active = True
else:
self.first_player.active = True
self.second_player.active = False
|
def addition(x, y):
return x + y
def substraction(x, y):
return x - y
def division(x, y):
return x / y
def multiplication(x, y):
return x * y
PI = 3.1415
def print_text():
print("Module mathematics") |
# Funkcie v Pythone sú takzvané funkcia prvej triedy 'First class functions'
def hello_world():
print("helllo world")
print(type(hello_world)) # Aj funkcia je len objekt (pre tych co videli moj kurz OOP)
# To znamená že ich napríklad vieme priradiť do premenných
x=hello_world # vsimni si ze nepouzivam okruhle zatvorky to znamena ze nevolam funkciu
x()
# Ale aj poslat ako parameter funkcie
def function_wrapper(func):
print("This is function wrapper")
func()
function_wrapper(hello_world)
# Funkcia tiez vie vratit funkciu, ktora sa v nej vytvori
def function_factory():
def hello_world():
print("Hello world but different")
return hello_world
print(function_factory)
print(function_factory())
print(function_factory()())
# Funkcie vies ulozit do pola presne ako akekolvek ine hodnoty
def adder(x, y):
return x + y
def substractor(x, y):
return x - y
def multiplier(x, y):
return x * y
math_functions = [adder, substractor, multiplier]
for function in math_functions:
print(function(1, 2))
# Annonymous function
def function_wrapper2(func, x, y):
print("This is function wrapper")
return func(x, y)
print(function_wrapper2(lambda x,y: x+y, 10, 20))
|
# Video https://youtu.be/VH_YaAI-BKI
numbers = [1, 2, 3, 4, 5, 10]
# Pomocou for cyklu vieme prechadzat cez polia
for number in numbers:
print(number)
# Alebo cez retazce.
for letter in "Michal Hucko":
print(letter)
# Funkcia range nam pomaha vytvorit pocitadlo, alebo pole cisel <dolnyny interval; horny interval)
counter = range(0, 5)
print(counter)
# Mozme definovat o kolko sa maju prvky v pcitadle zvysovat pomocou tretieho argumentu
range(0, 10, 2)
range(10, 1, -2)
# Pozor na nekonecne pole
range(0, 10, -2)
# Funkcia range a cyklus for sa casto pouzivaju spolu
for number in range(0, 10, 2):
print(number)
# Takti vieme iterovat cez akekolvek pole
letters = ["M", "i", "c", "h", "a", "l", 7, 8.7, [4, 5]]
for item in letters:
print(item)
# Do cyklu vieme pridat aj podmienky. Pozor na odsadenie (tabulator, 4 medzery)
letters = ["M", "i", "c", "h", "a", "l"]
for letter in letters:
if letter != 'c':
print(letter) |
import datetime
from random import randint
long_list = [randint(0, 3000) for element in range(1000000)]
# Przeszukiwanie liniowe (bez przygotowania)
t1 = datetime.datetime.now()
for i in long_list:
if i == -1:
print("Znaleziono!")
t2 = datetime.datetime.now() - t1
print("Czas trwania algorytmu: ", t2)
# Przeszukiwanie liniowe z wykorzystaniem SET
t1 = datetime.datetime.now()
test_set = set(long_list)
for i in test_set:
if i == -1:
print("Znaleziono!")
t2 = datetime.datetime.now() - t1
print("Czas trwania algorytmu: ", t2)
#
# Wynik działania algorytmu na moim komputerze:
#
# Czas trwania algorytmu: 0:00:00.050011
# Czas trwania algorytmu: 0:00:00.019004
#
|
"""
Для даного імені виводить ім'я та по-батькові
Вхідні дані очікуються з аргумент стрічки (1 строковий параметр).
При відсутності імені в базі, виводить відповідне повідомлення
"""
import sys
import argparse
def createParser():
parser = argparse.ArgumentParser()
parser.add_argument('name', nargs='?', default=" ")
return parser
if __name__ == '__main__':
namespace = createParser().parse_args(sys.argv[1:])
dictionary = {"Олександр": "Вікторович", "Вадим": "Олександрович", "Ольга": "Петрівна",
"Василь": "Миколайович", "Віктор": "Федорович"}
if namespace.name in dictionary.keys():
print("Привіт, {} {}".format(namespace.name, dictionary[namespace.name]))
else:
print("Я з Вами не знайома")
|
# Hamming
def distance(strand_a, strand_b):
strand_length = len(strand_a)
hamming_distance = 0
if len(strand_a) != len(strand_b): raise ValueError('Strand lengths are not equal')
for x in range(strand_length):
if strand_a[x] != strand_b[x]:
hamming_distance += 1
return hamming_distance
|
#print "Hello WOrld"
#var = int(raw_input(""))
#var2 = int(raw_input(""))
#print (var+var2)
#print (var-var2)
#print (var*var2)
#if var2!=0:
# print (var/var2)
# print (var%var2)
print ":)"
o = 0
while ( o != 3 ):
o = int(raw_input("1. Calculadora \n2. Par o impar\n3. Salir"))
if o == 1:
st = raw_input("")
op = st[0]
num1 = int(st[2:4])
num2 = int(st[5:7])
print num1,(" "), num2
if op == "+":
print num1+num2
if op == "-":
print num1-num2
if op == "*":
print num1*num2
if op == "/":
if num2 != 0:
print num1/num2
else:
print "indeterminado"
if op == "%":
if num2 != 0:
print num1%num2
else:
print "indeterminado"
if o == 2:
num = int(raw_input(""))
if num%2 == 0:
print "Par"
else:
print "Impar"
print ":)"
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 13 03:40:08 2018
@author: star
"""
"""
Deletion of elements in python dictionary is quite easy. You can just use del keyword.
It will delete single element from Python Dictionary. But if you want to delete all elements from the dictionary.
You can use clear() function. Deletion of elements from Python Dictionary is shown in the following code:
"""
dictionary = {
'name' : 'Alex',
'age' : 23,
'sex' : 'male'
}
#print initial dictionary
print(dictionary)
#delete a single element
del dictionary['name']
print('After deleting name')
print(dictionary)
'''
you cannot the element which is not int the dictionary. so the below statement
will raise error
del dictionary['name']
'''
#delete all elements from the list
dictionary.clear()
print(dictionary) #this will show an empty dictionary
#delete the entire variable
del dictionary
print(dictionary) #this will produce error |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 13 19:56:07 2018
@author: star
"""
One of the first cautions programmers encounter when learning Python is the fact
that there are no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation, which
is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the
block must be indented with same amount of spaces
Block 1:
if True:
print "True"
else:
print "False"
However, the second block in this example will generate an error:
Block 2:
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Thus, in Python all the continuous lines indented with similar number of spaces
would form a block.
Note: Use 4 spaces for indentation as a good programming practice.
"""
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an example.
"""
""" Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes the code more readable. For example:"""
if True:
print('Hello')
a = 5
if True: print('Hello'); a = 5
""" both are valid and do the same thing. But the former style is clearer.
Incorrect indentation will result into IndentationError."""
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 13 10:18:04 2018
@author: star
"""
"""
Traversing 2D-array using for loop
The following code print the elements row wise then the next part prints each element of the given array.
"""
arrayElement2D = [ ["Four", 5, 'Six' ] , [ 'Good', 'Food' , 'Wood'] ]
for i in range(len(arrayElement2D)):
print(arrayElement2D[i])
for i in range(len(arrayElement2D)):
for j in range(len(arrayElement2D[i])):
print(arrayElement2D[i][j])
# Python array append
arrayElement = ["One", 2, 'Three' ]
arrayElement.append('Four')
arrayElement.append('Five')
for i in range(len(arrayElement)):
print(arrayElement[i])
# You can also append an array to another array. The following code shows how you can do this.
# Now our one dimensional array arrayElement turns into a multidimensional array.
arrayElement = ["One", 2, 'Three' ]
newArray = [ 'Four' , 'Five']
arrayElement.append(newArray);
print(arrayElement)
|
import random
from classes import Prints
out = Prints(False)
def Battle(p1,p2):
global out, p1damage,p2damage
p1damage = 0
p2damage = 0
IQcheck(p1,p2)
STRcheck(p1,p2)
CHAcheck(p1,p2)
Critical(p1,p2)
p1.hp = p1.hp- p2damage
p2.hp = p2.hp- p1damage
return p1.hp,p2.hp
def IQcheck(p1,p2):
global p1damage,p2damage
if p1.iq > p2.iq:
p1damage = p1damage + (p1.iq - p2.iq)
out.line = ("{}'s IQ is larger than {}'s. {} takes {} damage.\n".format(p1.name,p2.name, p2.name,(p1.iq-p2.iq)))
out.slow_print()
if p1.iq < p2.iq:
p2damage = p2damage + (p2.iq - p1.iq)
out.line = ("{}'s STR is larger than {}'s. {} takes {} damage.\n".format(p2.name,p1.name, p1.name,(p2.iq-p1.iq)))
out.slow_print()
return p1damage,p2damage
def STRcheck(p1,p2):
global p1damage,p2damage
if p1.strength > p2.strength:
p1damage = p1damage + (p1.strength - p2.strength)
out.line = ("{}'s STR is larger than {}'s. {} takes {} damage.\n".format(p1.name,p2.name, p2.name,(p1.strength-p2.strength)))
if p1.strength < p2.strength:
p2damage = p2damage + (p2.strength - p1.strength)
out.line = ("{}'s STR is larger than {}'s. {} takes {} damage.\n".format(p2.name,p1.name, p1.name,(p2.strength-p1.strength)))
out.slow_print()
def CHAcheck(p1,p2):
global p1damage,p2damage
if p1.charisma > p2.charisma:
p1damage = p1damage + (p1.charisma - p2.charisma)
out.line = ("{}'s CHA is larger than {}'s. {} takes {} damage.\n".format(p1.name,p2.name, p2.name,(p1.charisma-p2.charisma)))
out.slow_print()
if p1.charisma < p2.charisma:
p2damage = p2damage + (p2.charisma - p1.charisma)
out.line = ("{}'s STR is larger than {}'s. {} takes {} damage.\n".format(p2.name,p1.name, p1.name,(p2.charisma-p1.charisma)))
out.slow_print()
return p1damage,p2damage
def Critical(p1,p2):
global p1damage,p2damage
hit = random.randint(1,5)
multiplier = int(random.random()*10) / 10.0+1
if hit == 1:
p1damage = p1damage*multiplier
out.line = "{}'s attack was critical! His damage got a {}x multiplier!\n".format(p1.name,multiplier)
out.slow_print()
if hit ==5:
p2damage = p2damage*multiplier
out.line = "{}'s attack was critical! His damage got a {}x multiplier!\n".format(p2.name,multiplier)
out.slow_print()
return p1damage, p2damage |
#사전 속 자료 찾기
# values 메소드 사용
my_number = {
'a': 1,
'b': 2,
'c': 3,
'd': 4
}
print(my_number.values())
for value in my_number.values(): #my_number.values 안에 들어있는 녀석들을 순차적으로 불러옴.
print(value)
print(my_number.keys())
for key in my_number.keys(): #my_number.keys 안에 들어있는 녀석들을 차례대로 불러옴
print(key, my_number[key])
for key, value in my_number.items():
print(key, value) |
# 빈 리스트 만들기
numbers = []
print(numbers)
# numbers에 값들 추가
numbers.append(1)
numbers.append(7)
numbers.append(3)
numbers.append(6)
numbers.append(5)
numbers.append(2)
numbers.append(13)
numbers.append(14)
print(numbers)
# numbers에서 홀수 제거
index = 0
while index < len(numbers):
if numbers[index] % 2 != 0:
del(numbers[index]) #여기에서 지워지면 index들이 한칸씩 앞으로 땡겨진다.. 그래서 7이 안지워졌던 것!
else:
index += 1
print(numbers)
# numbers의 인덱스 0 자리에 20이라는 값 삽입
numbers.insert(0, 20) #리스트.index(a,b) a앞자리에 b를 대입하세요 라는 의미!
print(numbers)
# numbers를 정렬해서 출력
numbers.sort()
print(numbers)
'''
중간에 if.. else 부분을 더 깔끔하게 바꿀 수 있는 방법:
index 호출법에는 -를 이용해 오른쪽부터 호출하는 방법이 있다!
''' |
#1
# in을 이용하면 boolean을 통해 찾고자 하는 값이 있는지 아닌지 확인할 수 있어요!
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
print(13 in primes)
print(1 in primes)
print(13 not in primes)
print(1 not in primes)
print()
#2
#nested list : list 안에 또 리스트가 있지용
a = [62, 75, 77]
b = [78, 81, 86]
c = [85, 91, 89]
grades = []
grades.append(a)
grades.append(b)
grades.append(c)
print(grades)
#첫번째 학생의 성적
print(grades[0])
#두번째 학생의 둘째과목 성적
print(grades[1][1])
#세번째 시험의 평균
print((grades[0][2] + grades[1][2] + grades[2][2]) / len(grades)) #list는 ','로 묶여있기만 하면 하나의 item으로 취급!
print()
#3
#sort 메소드 & sorted 함수
some_list = [5, 3, 7, 1]
new_list = sorted(some_list) #새로운 리스트에 정렬된 기존 리스트를 선언
some_list.sort() #기존 리스트 자체를 새로 정렬시킴
print(new_list)
print(some_list)
print()
#4
#reverse 메소드 : some_list.reverse()는 some_list의 원소들을 뒤집어진 순서로 배치
numbers = [5, 3, 7, 1]
numbers.reverse()
print(numbers)
print()
#5
#index 메소드 : some_list.index(x) 는 some_list에서 x값의 인덱스를 알려줌.
num = [1, 1, 1, 2, 2, 3]
print(num.index(1)) #여러개 중복될 경우 맨 앞의 인덱스로 알려줌.
print()
#6
#some_list.remove(x) : some_list에서 첫번째로 x 값을 가지는 원소를 삭제함.
fruits = ["딸기", "사과", "복숭아", "수박"]
fruits.remove("사과")
print(fruits) |
# 화씨 온도에서 섭씨 온도로 바꿔 주는 함수
def fahrenheit_to_celsius(fahrenheit):
global Celcius # Celcius를 글로벌 변수로 선언.
count = 0
length = len(fahrenheit)
Celcius = []
while count < length:
temp_F = fahrenheit[count]
temp_C = (temp_F - 32) * 5 / 9
temp_C = round(temp_C, 1)
Celcius.append(temp_C)
count += 1
fahrenheit = Celcius
temperature_list = [40, 15, 32, 64, -4, 11]
print("화씨 온도 리스트: " + str(temperature_list)) # 화씨 온도 출력
temperature_list = Celcius
fahrenheit_to_celsius(temperature_list)
print("섭씨 온도 리스트: " + str(temperature_list)) # 섭씨 온도 출력
#모범답안
# 화씨 온도에서 섭씨 온도로 바꿔 주는 함수
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9 #def된 함수 호출하면 함수 실행 뒤 다시 return값 호출
#return으로 함수 호출부에 값을 돌려줄 생각을 했어야!
temperature_list = [40, 15, 32, 64, -4, 11]
print("화씨 온도 리스트: " + str(temperature_list)) # 화씨 온도 출력
# 리스트의 값들을 화씨에서 섭씨로 변환하는 코드
i = 0
while i < len(temperature_list):
temperature_list[i] = round(fahrenheit_to_celsius(temperature_list[i]), 1)
i += 1
print("섭씨 온도 리스트: {}".format(temperature_list)) # 섭씨 온도 출력 |
#while 과 for 사이 차이?
'''
for문은 리스트의 내역을 반복할 시에 좋음
my_list = [2, 3, 5, 7, 11]
for numbers in my_list:
print(numbers)
여기서 numbers는 다르게 지정되어도 괜춘해!
'''
#for 반복문을 이용해서 1~10까지 출력하는 프로그램 제작해보자.
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
pass
#근데.. 1~ 100이면? 1000이면? 귀찮슴다..
#Sol. range 함수 : 리스트 슬라이싱이랑 비슷혀!
#장점 : 간편, 깔끔, 메모리 효율성
#파라미터 1개
for i in range(10): #0부터 9까지 출력
print(i)
print("")
#파라미터 2개
for i in range(2, 10): #2부터 9까지 출력
print(i)
print("")
#파라미터 3개
for i in range(1, 10, 3): #1부터 9까지 3의 간격으로 출력
print(i) |
year = 2019
month = 10
day = 29
#format classmethod
'''
1. 우리가 쓰고 싶은 문장을 우선 작성한다.
2. 원하는 값을 넣어야하는 공간을 {}로 대체해준다.
'''
date_string = "오늘은 {}년 {}월 {}일 입니다."
#문자열을 계속 반복해서 사용할 것이면 선언을 미리 해주자.
print(date_string.format(year, month, day))
#그냥 그자리에 그대로 숫자를 대입할거면 굳이 중괄호에 번호 안적어도 괜춘해요
#.format의 괄호 안에서 연산을 해도 괜춘!
num_1 = 1
num_2 = 3
print("{0} 나누기 {1} 은 {2:}입니다.".format(num_1, num_2, num_1 / num_2))
'''소수 반올림 방법
1. round(n)하면 소수점 n자리까지 출력
2. :.nf 사용 -> .n은 소수점 n번째자리까지 하기, f는 float라고 선언해주는 것
''' |
def ToPigLatin(a):
word = ""
for i in range(0, len(a)):
a[i] = a[i].lower()
a[i] = a[i][1:] + a[i][0] + "ay"
for i in a:
word += i + " "
word = word.capitalize()
return word
def ToEnglish(b):
word = ""
for i in range(0, len(b)):
b[i] = b[i].lower()
b[i] = b[i][-3] + b[i][:-3]
for i in b:
word += i + " "
word = word.capitalize()
return word
a = input("Enter text: ").split()
while True:
print("Enter 'P' to convert to Pig Latin or 'E' to convert to English")
language = input().lower()
if language == "p":
print(ToPigLatin(a))
break
elif language == "e":
print(ToEnglish(a))
break
else:
print("You have entered an invalid input") |
def median(arr):
l=len(arr)
if(l%2!=0):
return arr[l//2]
else:
return (arr[(l//2)-1]+arr[l//2])//2
n=int(input())
x=[int(i) for i in input().split(' ')]
x.sort()
#Q2
Q2=median(x)
#Q1
Q1=median(x[:n//2])
#Q3
if(n%2!=0):
Q3=median(x[((n//2)+1):n])
else:
Q3=median(x[n//2:n])
print(Q1)
print(Q2)
print(Q3)
|
total = 0
for a in range(1,11):
#print(a)
total = total + a
a = a + 1
print(total)
|
str_N = input("Please enter a number to find summation of 1..N: ")
N = int(str_N) + 1
total = sum(range(1,N))
print(total)
|
def binary_search(array, value_to_be_searched):
left_bound = 0
right_bound = len(array) - 1
found = False
while left_bound <= right_bound and not found:
middle = (left_bound + right_bound) // 2
if array[middle] == value_to_be_searched:
return middle
else:
if value_to_be_searched < array[middle]:
right_bound = middle + 1
else:
left_bound = middle + 1
if not found:
print("Error: item not in tree")
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(binary_search(arr, 3))
|
from itertools import cycle
import itertools
Name_1 = list(''.join(I1 for I1 in input("Enter Your Name :").lower()))
Name_2 = list(''.join(e for e in input("Enter Your Partner Name :").lower()))
Flames_List = ["Friendship","Love","Affection","Marriage","Enemy","Siblings"]
Flames_Dict = {Output_List_1[x]:Flames_List[x] for x in range(len(Flames_List))}
Output_List_1 = ['F','L','A','M','E','S']
for x in Name_1:
for y in Name_2:
if x in y:
Name_1.remove(x),Name_2.remove(y)
break
def cycle_Flames(*List):
List = list(List[0])
# print(List)
if len(List) == 1:
return List[0]
elif len(List) >= 1:
list_cycle = itertools.cycle(List)
for i in range(len(Name_1+Name_2)):
next_element = next(list_cycle)
Index = List.index(next_element)
List.remove(next_element)
Temp_List = []
for i in range(len(List)):
Temp_List.append(List[Index % len(List)])
Index += 1
return cycle_Flames(Temp_List)
print(cycle_Flames(Output_List_1),'-->',Flames_Dict[cycle_Flames(Output_List_1)]) |
def Sum_Of_Intergers(Arg_1):
Temp_Var = 0
for Loop_Var in Arg_1:
Temp_Var += int(Loop_Var)
if(len(str(Temp_Var)) == 1):
return Temp_Var
else:
return Sum_Of_Intergers(str(Temp_Var))
|
# https://projecteuler.net/problem=4
#A palindromic number reads the same both ways.
# The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
n = 0
for i in range(999, 100, -1):
for j in range(999, 100, -1):
x = i * j
if x > n:
s = str(i * j)
if s == s[::-1]:
n = i * j
print(n)
input()
|
# https://dodona.ugent.be/nl/courses/359/series/3491/activities/112444173
def hit(base, occupied = None):
"""
>>> hit(2)
(0, [2])
>>> hit(0, [1, 3])
(0, [1, 3])
>>> hit(1, (1, 3))
(1, [1, 2])
>>> hit(2, occupied=[1, 3])
(1, [2, 3])
>>> hit(3, occupied=(1, 3))
(2, [3])
>>> hit(4, occupied=[1, 3])
(3, [])
"""
# default
if occupied == None:
occupied = []
# move position
occupied = [position + base for position in occupied]
# add batter to the field
if base:
occupied.append(base)
# calculate score:
score = len([position for position in occupied if position >= 4])
# new occupation
occupied = sorted([position for position in occupied if position < 4])
return score, occupied
def inning(nbases):
"""
>>> inning([0, 1, 2, 3, 4])
(4, [])
>>> inning((4, 3, 2, 1, 0))
(2, [1, 3])
>>> inning([1, 1, 2, 1, 0, 0, 1, 3, 0])
(5, [3])
"""
score, occupied = 0, []
for base in nbases:
score_each, occupied = hit(base, occupied)
score += score_each
return score, occupied
if __name__ == '__main__':
import doctest
doctest.testmod() |
# https://dodona.ugent.be/nl/courses/359/series/3489/activities/1266098554
def splitsing(soort):
"""
Splitst de parameter (str) in een prefix en een suffix, waarbij de prefix
bestaat uit alle medeklinkers aan het begin van de gegeven string.
>>> splitsing('schaap')
('sch', 'aap')
>>> splitsing('geit')
('g', 'eit')
"""
# find position of first vowel
# pos = 0
# while pos < len(soort) and soort[pos].lower() not in 'aeiou':
# pos += 1
# return soort[:pos], soort[pos:]
consonants = 'aeiouAEIOU'
list = []
for letter in soort:
if letter in consonants:
index = soort.index(letter)
left = soort[:index]
right = soort[index:]
break
list.append(left)
list.append(right)
return tuple(list)
def kruising(soort1, soort2):
"""
Geeft tuple met twee strings terug, waarvan de eerste gevormd wordt door de
samenstelling van de prefix van de eerste parameter (str) en de suffix van
de tweede paramter (str), en de tweede gevormd wordt door de prefix van de
tweede paramter en de suffix van de eerste paramter.
>>> kruising('schaap', 'geit')
('scheit', 'gaap')
>>> kruising('leeuw', 'tijger')
('lijger', 'teeuw')
>>> kruising('hond', 'kat')
('hat', 'kond')
"""
list = []
new1 = splitsing(soort1)[0] + splitsing(soort2)[1]
new2 = splitsing(soort2)[0] + splitsing(soort1)[1]
list.append(new1)
list.append(new2)
return tuple(list)
# # split species names in prefix and suffix
# prefix1, suffix1 = split(species1) prefix2, suffix2 = split(species2)
# # hybridize the species names
# return prefix1 + suffix2, prefix2 + suffix1
if __name__ == '__main__':
import doctest
doctest.testmod() |
# https://dodona.ugent.be/nl/courses/359/series/3491/activities/1158810383
def serial_number(serial):
"""
>>> serial_number(834783)
'00834783'
>>> serial_number('47839')
'00047839'
>>> serial_number(834783244839184)
'834783244839184'
>>> serial_number('4783926132432*')
Traceback (most recent call last):
AssertionError: invalid serial number
"""
serial = str(serial)
assert (serial.isdigit()), 'invalid serial number'
assert (set(list(serial)) != {'0'}), 'invalid serial number'
if len(serial) < 8:
serial = '0' * (8 - len(serial)) + serial
return serial
def solid(number):
"""
>>> solid(44444444)
True
>>> solid('44544444')
False
"""
return len(set(list(serial_number(number)))) == 1
## 老师的答案
# number = serial_number(number)
# return number == number[0] * len(number)
def radar(number):
"""
>>> radar(1133110)
True
>>> radar('83289439')
False
"""
number = serial_number(number)
half = len(number) // 2
return number[:half] == number[half:][::-1] and not solid(number)
## 注意[::是跳过的位置] 不要把它和string 的reverse搞混了!!
def repeater(number):
"""
>>> repeater(20012001)
True
>>> repeater('83289439')
False
"""
number = serial_number(number)
half = len(number) // 2
return number[:half] == number[half:] and not solid(number)
def radar_repeater(number):
"""
>>> radar_repeater('12211221')
True
>>> radar_repeater('83289439')
False
"""
return repeater(number) and radar(number)
def numismatist(listort, kind = solid):
"""
>>> numismatist([33333333, 1133110, '77777777', '12211221'])
[33333333, '77777777']
>>> numismatist([33333333, 1133110, '77777777', '12211221'], radar)
[1133110, '12211221']
>>> numismatist([33333333, 1133110, '77777777', '12211221'], kind=repeater)
['12211221']
"""
return [number for number in listort if kind(number)]
if __name__ == '__main__':
import doctest
doctest.testmod() |
# https://dodona.ugent.be/nl/courses/359/series/3491/activities/1652372190
def next_letter(v, w):
"""
>>> next_letter('e', 'HERDSMAN')
'R'
>>> next_letter('LC', 'sepulchre')
'H'
>>> next_letter('onf', 'Teleconference')
'E'
>>> next_letter('EURO', 'DOLLAR')
''
>>> next_letter('LF', 'ALFALFA')
''
>>> next_letter('USE', 'TREEHOUSE')
''
"""
v, w = v.upper(), w.upper()
if w.count(v) == 1 and w[-len(v):] != v:
return w[w.find(v)+len(v)]
return ''
def extend(p, W_):
"""
>>> extend('Pe', ['HERDSMAN', 'WONDERFUL', 'FURNACE', 'HELIUM', 'PALINDROME', 'PAPERBACK'])
'PERFUMER'
>>> extend('ALC', ['sepulchre', 'satchel', 'Bohemian', 'pandemic', 'hemisphere', 'resistor'])
'ALCHEMIST'
>>> extend('nonc', ['Teleconference', 'Disinfect', 'Defector', 'Election', 'Section', 'Vibration', 'Pioneer', 'Loner'])
''
"""
result = p.upper()
letter = p[1:]
for word in W_:
next = next_letter(letter, word)
if not next:
return ''
result += next
letter = letter[1:] + result[-1]
return result
def profession(word_, length = 2):
"""
>>> profession(['OPERATOR', 'HERDSMAN', 'WONDERFUL', 'FURNACE', 'HELIUM', 'PALINDROME', 'PAPERBACK'])
'PERFUMER'
>>> profession(['falcon', 'sepulchre', 'satchel', 'Bohemian', 'pandemic', 'hemisphere', 'resistor'], length=3)
'ALCHEMIST'
>>> profession(['Nonconformist', 'Teleconference', 'Disinfect', 'Defector', 'Election', 'Section', 'Vibration', 'Pioneer', 'Loner'], 4)
'CONFECTIONER'
"""
for word in word_:
word_list = [word[index:index + length] for index in range(len(word)- length + 1)]
for prefix in word_list:
word1 = extend(prefix, word_[1:])
if word1:
return word1
return ''
if __name__ == '__main__':
import doctest
doctest.testmod() |
# https://dodona.ugent.be/nl/courses/359/series/3488/activities/2009241681
# input the separator and number of lines
separator = input()
line_number = int(input())
for _ in range(line_number): # 循环的东西在loop中用不到
line = input()
sep_index = line.index(separator)
# exchange place and combine
new_line = line[sep_index+1:] + line[:sep_index]
print(new_line) |
# https://dodona.ugent.be/nl/courses/359/series/3486/activities/56374393
# give the input
start = str(input())
end = str(input())
move = ''
# process
start1, start2 = start
end1, end2 = end
if ord(start1) == ord(end1) or int(start2) == int(end2): # should be L shape
move = 'cannot'
elif abs(ord(start1)-ord(end1)) + abs(int(start2)-int(end2)) == 3:
move = 'can'
else:
move = 'cannot'
# give output
print(f'a knight {move} jump from {start} to {end}') |
# https://dodona.ugent.be/nl/courses/359/series/3487/activities/1898834779
# https://dodona.ugent.be/nl/courses/359/series/3486/activities/182880102
first = input()
while first != 'stop':
sum = int(first)
for index in range(2, 10):
next_digit = int(input())
sum += index * next_digit
sum %= 11
ten = int(input())
print('OK' if ten == sum else 'WRONG')
# read next ten
first = input() |
import random
choices = ['rock','paper','scissors']
# let the computer choose
def compChoice():
cChoice = random.randint(1,3)
if cChoice == 1:
cChoice = 'rock'
elif cChoice == 2:
cChoice = 'paper'
else:
cChoice = 'scissors'
return cChoice
# get the users choice
def userChoice():
userC = 1
while userC:
try:
userC = input('Please enter your choice! rock,paper,or scissors: ')
userC = userC.lower()
if userC not in choices:
raise ValueError
except ValueError:
print('I did not understand your entry')
print('Please choose', choices)
else:
break
userC = userC.lower()
return userC
def main():
again = 'y'
# declare the accumulators outside of the while loop
# this way they don't keep resetting to 0 inside the loop
# these hold the game stats
userWins = 0
computerWins = 0
gamesPlayed = 0
ties = 0
while again:
user = userChoice()
computer = compChoice()
if user == computer:
print('It\'s a tie!')
userWins = userWins
computerWins = computerWins
ties += 1
elif user == 'rock' and computer == 'paper':
print('You lose!', computer,'covers',user)
computerWins = computerWins + 1
userWins = userWins
elif user == 'rock' and computer == 'scissors':
print('You win!', user,'smashes',computer)
userWins = userWins + 1
computerWins = computerWins
elif user == 'paper' and computer == 'rock':
print('You win', user,'covers',computer)
userWins = userWins + 1
computerWins = computerWins
elif user == 'paper' and computer == 'scissors':
print('You lost!', computer,'slices',user)
computerWins = computerWins + 1
userWins = userWins
elif user == 'scissors' and computer == 'rock':
print('You lost!',computer,'smashes',user)
computerWins = computerWins + 1
userWins = userWins
elif user =='scissors' and computer == 'paper':
print('You won!', user, 'slices', computer)
userWins = userWins + 1
computerWins = computerWins
gamesPlayed += 1
again = input('Go again? y/n: ')
again = again.lower()
# if the user enters anything but y exit the loop
if again != 'y':
break
# print the games stats:
print('Thanks for playing!')
print('----GAME STATS----')
print('you played:',gamesPlayed,'games')
print('you won:', userWins,'games')
print('the computer won:',computerWins,'games')
print('you tied:', ties,'times')
print('------------------')
main()
|
import numpy as np
import pandas as pd
from problem2 import *
# Note: please don't import any new package. You should solve this problem using only the package(s) above.
#-------------------------------------------------------------------------
'''
Problem 3: (Moneyball) Data Preprocessing in Baseball Dataset (24 points)
In this problem, you will practise data preprocessing with baseball dataset
A list of all variables being used in this problem is provided at the end of this file.
'''
#----------------------------------------------------
'''
(Loading Data) Let's start with the raw data, 'moneyball_batting.csv'. Let's load this CSV file into a pandas dataframe (X)..
---- Inputs: --------
* filename: the file name of a CSV file, a string.
---- Outputs: --------
* X: a dataframe containing the batting data of all players in all years, loaded from moneyball_batting.csv.
---- Hints: --------
* This problem can be solved using 1 line(s) of code.
'''
#---------------------
def load_batting(filename='moneyball_batting.csv'):
#########################################
## INSERT YOUR CODE HERE (3 points)
#########################################
return X
#-----------------
'''
TEST: Now you can test the correctness of your code above by typing the following in the terminal:
---------------------------------------------------
nosetests -v test3.py:test_load_batting
---------------------------------------------------
'''
#----------------------------------------------------
'''
(Filtering by Year) The dataset contains records of all years. In this study, suppose we just want to choose players for the year 2002, based upon data of year 2001. We need to first search the data records of year 2001 only..
---- Inputs: --------
* X: a dataframe containing the batting data of all players in all years, loaded from moneyball_batting.csv.
* year: an integer scalar, the year of the data to be used.
---- Outputs: --------
* X1: a dataframe containing the batting data only in the searched year (2001).
---- Hints: --------
* This problem can be solved using 1 line(s) of code.
'''
#---------------------
def filter_batting(X, year):
#########################################
## INSERT YOUR CODE HERE (3 points)
#########################################
return X1
#-----------------
'''
TEST: Now you can test the correctness of your code above by typing the following in the terminal:
---------------------------------------------------
nosetests -v test3.py:test_filter_batting
---------------------------------------------------
'''
#----------------------------------------------------
'''
If you have passed the previous test case, the result data frame should have been saved into a file, called 'moneyball_X1.csv'. This 2001 dataset contains multiple records for each player: a same player may have two/three records, because the player has changed team in year 2001. For example, playerID='guilljo01' (or 'houstty01') has two rows. We need to sum the game statistics of the same player together, so that each player only contains one row in the data frame. For example if the same player with ID 'player1' has three rows of records, 'player2' has two rows of records:
player ID | H | AB
---------------------
player 1 | 5 | 10
player 1 | 3 | 20
player 1 | 1 | 30
player 2 | 1 | 40
player 2 | 2 | 50
player 3 | 1 | 60
---------------------
we should sum the data for each player into one row:
player ID | H | AB
-----------------------------------------
player 1 | 9=(5+3+1) | 60 = (10+20+30)
player 2 | 3=(1+2) | 90 = (40+50)
player 3 | 1 | 60
-----------------------------------------
(Group by playerID) Given a data frame of batting statistics (X1), group the data records with respect to playerID, so that the game statistics are added together for each player. For example, player 'houstty01' has two rows, where the number of hits (column H) has values: 58, 4 We want to combine these two rows into one row, such that all the game statistics are the sum of the raw values (for example, number hits now should be 58+4 = 62) .
---- Inputs: --------
* X1: a dataframe containing the batting data only in the searched year (2001).
---- Outputs: --------
* X2: a dataframe containing the batting data in the year (2001) after grouping the statistics for players.
---- Hints: --------
* You could use some function implemented in problem2.py to solve this problem.
* This problem can be solved using 1 line(s) of code.
'''
#---------------------
def group_batting(X1):
#########################################
## INSERT YOUR CODE HERE (3 points)
#########################################
return X2
#-----------------
'''
TEST: Now you can test the correctness of your code above by typing the following in the terminal:
---------------------------------------------------
nosetests -v test3.py:test_group_batting
---------------------------------------------------
'''
#----------------------------------------------------
'''
If you have passed the previous test case, the result data frame should have been saved into a file, called 'moneyball_X2.csv. Now the dataset only contains game statistics, but no information about the players is available, like first name, last name, weight, height, etc. We have another CSV file 'moneyball_player.csv', which contains the player information, such as first name, weight, height, etc. It would be better if we can combine these two datasets into one data frame, so the new data frame contains both game statistics and player information.
(Merge the two dataframes) Given a data frame (X2) of batting statistics , and a data frame (Y) of player information (loaded from 'moneyball_player.csv'), Combine the two data frames into one, according to the playerID column. .
---- Inputs: --------
* X2: a dataframe containing the batting data in the year (2001) after grouping the statistics for players.
* Y: a dataframe containing the player information, such as first name, weight, height, which is loaded from moneyball_player.csv.
---- Outputs: --------
* X3: a dataframe containing both batting data and player information in the year (2001).
---- Hints: --------
* You could use some function implemented in problem2.py to solve this problem.
* This problem can be solved using 1 line(s) of code.
'''
#---------------------
def merge_player(X2, Y):
#########################################
## INSERT YOUR CODE HERE (3 points)
#########################################
return X3
#-----------------
'''
TEST: Now you can test the correctness of your code above by typing the following in the terminal:
---------------------------------------------------
nosetests -v test3.py:test_merge_player
---------------------------------------------------
'''
#----------------------------------------------------
'''
If you have passed the previous test case, the result data frame should have been saved into a file, called 'moneyball_X3.csv'. Now the dataset contains both game statistics and player information. However, we still need to know the salary of each player in year 2002, which represents the market price of each player in 2002, in order to hire the player into our team. We have another CSV file 'moneyball_salary.csv', which contains the player's salary information in all years. We first need to find the players' salaries only in year 2002, then we want to merge the salary information into the dataset.
(Filter salary for year 2002) Given the dataframe (Z) containing players' salary data of all years, filter the dataframe with year 2002, return the salary data only in year 2002.
---- Inputs: --------
* Z: a dataframe containing the salary data of all players in all years.
* year: an integer scalar, the year of the data to be used.
---- Outputs: --------
* Z1: a dataframe containing the salary data only in the searched year (2002).
---- Hints: --------
* This problem can be solved using 1 line(s) of code.
'''
#---------------------
def filter_salary(Z, year):
#########################################
## INSERT YOUR CODE HERE (3 points)
#########################################
return Z1
#-----------------
'''
TEST: Now you can test the correctness of your code above by typing the following in the terminal:
---------------------------------------------------
nosetests -v test3.py:test_filter_salary
---------------------------------------------------
'''
#----------------------------------------------------
'''
If you have passed the previous test case, the result data frame should have been saved into a file, called 'moneyball_Z1.csv'. Now let's merge the salary information into the dataset.
(Join the batting data with salary data) Given a data frame X3 (containing both batting statistics and player information, loaded from 'moneyball_X3.csv'), and a dataframe (Z1) of salary information (loaded from 'moneyball_Z1.csv'), combine the two data frames into one, according to the 'playerID' column.
---- Inputs: --------
* X3: a dataframe containing both batting data and player information in the year (2001).
* Z1: a dataframe containing the salary data only in the searched year (2002).
---- Outputs: --------
* X4: a dataframe containing all the required data (batting data, player information and salary data) for player evaluation in the year (2001).
---- Hints: --------
* This problem can be solved using 1 line(s) of code.
'''
#---------------------
def merge_salary(X3, Z1):
#########################################
## INSERT YOUR CODE HERE (3 points)
#########################################
return X4
#-----------------
'''
TEST: Now you can test the correctness of your code above by typing the following in the terminal:
---------------------------------------------------
nosetests -v test3.py:test_merge_salary
---------------------------------------------------
'''
#----------------------------------------------------
'''
If you have passed the previous test case, the result data frame should have been saved into a file, called 'moneyball_X4.csv'. This file contains all the information we need for player evaluation.
(Filter At-Bats) Given a dataframe (X4) of all the players on the market in year 2002, find the candidate players who have sufficient experience: the players with minimum number of At-Bats(AB). Any player who has smaller number of AB than min_AB in X4 should be excluded. The remaining players are candidate players (in the dataframe X5), who have sufficient previous experience (AB >= min_AB) .
---- Inputs: --------
* X4: a dataframe containing all the required data (batting data, player information and salary data) for player evaluation in the year (2001).
* min_AB: an integer scalar, the threshold on AB (at-Bat). To find good players, we should exclude those without sufficient experience. The players with AB less than the min_AB should be excluded from the ranked list..
---- Outputs: --------
* X5: a dataframe containing all the candidate players for evaluation in the year (2001), who have sufficient experience (at least min_AB).
---- Hints: --------
* This problem can be solved using 1 line(s) of code.
'''
#---------------------
def filter_min_AB(X4, min_AB):
#########################################
## INSERT YOUR CODE HERE (3 points)
#########################################
return X5
#-----------------
'''
TEST: Now you can test the correctness of your code above by typing the following in the terminal:
---------------------------------------------------
nosetests -v test3.py:test_filter_min_AB
---------------------------------------------------
'''
#----------------------------------------------------
'''
If you have passed the previous test case, the result data frame should have been saved into a file, called 'moneyball_X5.csv'. Now let's remove the players who are too expensive.
(Find Affordable Players) Given a dataframe (X5) of all the players with sufficient experience, find the candidate players who are affordable: the players with salary no higher than max_salary. Any player who has higher salary than max_salary in X5 should be excluded. The remaining players are candidate players (in the dataframe X6), who have both sufficient experience (AB >= min_AB) and are affordable (salary < max_salary).
---- Inputs: --------
* X5: a dataframe containing all the candidate players for evaluation in the year (2001), who have sufficient experience (at least min_AB).
* max_salary: an integer scalar, the maximum salary that we can afford for a player. To find affordable players, we should exclude those too expensive player. The players with higher salaries than max_salary should be excluded from the ranked list..
---- Outputs: --------
* X6: a dataframe containing all the candidate players for evaluation in the year (2001), who have sufficient experience (at least min_AB) and affordable price tag (at most max_salary).
---- Hints: --------
* This problem can be solved using 1 line(s) of code.
'''
#---------------------
def filter_max_salary(X5, max_salary):
#########################################
## INSERT YOUR CODE HERE (3 points)
#########################################
return X6
#-----------------
'''
TEST: Now you can test the correctness of your code above by typing the following in the terminal:
---------------------------------------------------
nosetests -v test3.py:test_filter_max_salary
---------------------------------------------------
'''
#--------------------------------------------
'''
TEST problem 3:
Now you can test the correctness of all the above functions by typing the following in the terminal:
---------------------------------------------------
nosetests -v test3.py
---------------------------------------------------
If your code passed all the tests, you will see the following message in the terminal:
----------- Problem 3 (24 points in total)--------------------- ... ok
* (3 points) load_batting ... ok
* (3 points) filter_batting ... ok
* (3 points) group_batting ... ok
* (3 points) merge_player ... ok
* (3 points) filter_salary ... ok
* (3 points) merge_salary ... ok
* (3 points) filter_min_AB ... ok
* (3 points) filter_max_salary ... ok
----------------------------------------------------------------------
Ran 8 tests in 0.006s
OK
'''
#--------------------------------------------
#--------------------------------------------
'''
List of All Variables
* filename: the file name of a CSV file, a string.
* year: an integer scalar, the year of the data to be used.
* X: a dataframe containing the batting data of all players in all years, loaded from moneyball_batting.csv.
* X1: a dataframe containing the batting data only in the searched year (2001).
* X2: a dataframe containing the batting data in the year (2001) after grouping the statistics for players.
* X3: a dataframe containing both batting data and player information in the year (2001).
* X4: a dataframe containing all the required data (batting data, player information and salary data) for player evaluation in the year (2001).
* X5: a dataframe containing all the candidate players for evaluation in the year (2001), who have sufficient experience (at least min_AB).
* X6: a dataframe containing all the candidate players for evaluation in the year (2001), who have sufficient experience (at least min_AB) and affordable price tag (at most max_salary).
* Y: a dataframe containing the player information, such as first name, weight, height, which is loaded from moneyball_player.csv.
* Z: a dataframe containing the salary data of all players in all years.
* Z1: a dataframe containing the salary data only in the searched year (2002).
* min_AB: an integer scalar, the threshold on AB (at-Bat). To find good players, we should exclude those without sufficient experience. The players with AB less than the min_AB should be excluded from the ranked list..
* max_salary: an integer scalar, the maximum salary that we can afford for a player. To find affordable players, we should exclude those too expensive player. The players with higher salaries than max_salary should be excluded from the ranked list..
'''
#-------------------------------------------- |
#zasieg zmiennych, zmienne lokalne i globalneabs
#precyzja liczby(zaokrąglenie do 3 miejsc po przecinku)
x="{0:.3f}".format(5)
print(x)
def plnToChf(value):
kursChf=3.7536
iloscChf=value / kursChf
iloscChf="{0:.0f}".format(iloscChf)
print(f'Ilosc CHF: {iloscChf}')
plnToChf(100)
Ile=input("Podaj ile masz złotówek: ")
Ile=float(Ile)
def zwrot(wartosc):
kursEuro=4.28755406
iloscEuro=Ile/kursEuro
iloscEuro="{0:.0f}".format(iloscEuro)
print(f'Ilosc Euro:{iloscEuro}')
zwrot(Ile)
#zmienna globalna
kursUSD=3.8281908
print(f'id usd: {id(kursUSD)}')
pln=input('Podaj kwotę PLN jaką chcesz wymienić na USD: ')
pln=float(pln)
def zwrotUSD(wartosc):
#kursUSD=3.8281908
iloscUSD=pln/kursUSD
iloscUSD="{0:.0f}".format(iloscUSD)
return iloscUSD
print(f'\nId dolara: {id(kursUSD)}')
print(f'\nKurs dolara: {kursUSD}')
usd=zwrotUSD(pln)
print(f'Ilość {pln}PLN={usd}USD')
print(f'Kurs USD:{kursUSD}')
###########################################################################################
zmiennaGlobalna=10
print(f'\n Wartość zmiennaGlolobalna: {zmiennaGlobalna}')
print(f'\n ID zmiennaGlobalna: {id(zmiennaGlobalna)}')
def spr():
global zmiennaGlobalna
zmiennaGlobalna=20
print(f'\nWartość zmiennaGlolobalna: {zmiennaGlobalna}')
print(f'\n ID zmiennaGlobalna: {id(zmiennaGlobalna)}')
spr()
print(f'\nWartość zmiennaGlolobalna: {zmiennaGlobalna}')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.