text
stringlengths 37
1.41M
|
---|
'''
Description: A program that implements the Python turtle library to draw a tree.
(I did not discuss this assignment with anyone.)
Written By: Anh Mac
Date: 11/6/2018
'''
from turtle import *
# I've implemented this function for you; do not edit it.
def tree( trunkLength, angle, levels ):
left(90)
sidewaysTree(trunkLength, angle, levels)
# This is the function you have to implement.
def sidewaysTree( trunkLength, angle, levels ):
""" draws a sideways tree
trunklength = the length of the first line drawn ("the trunk")
angle = the angle to turn before drawing a branch
levels = the depth of recursion to which it continues branching
"""
if levels == 0:
return
else:
forward(trunkLength)
left(angle)
sidewaysTree(trunkLength*0.5, angle, levels-1)
right(angle*2)
sidewaysTree(trunkLength*0.5, angle, levels-1)
left(angle)
backward(trunkLength)
# tree(128,30,6)
|
#Chapter 5 - Challenge 1
#Chris Looney
#November 10,2014
import random
first_word = input("Please enter your first word: ")
second_word = input("Please enter your second word: ")
third_word = input("Please enter your third word: ")
fourth_word = input("Please enter your fourth word: ")
fifth_word = input("Please enter your fifth word: ")
word_list = (first_word,second_word,third_word,fourth_word,fifth_word)
random_word_list = []
while len(random_word_list) != len(word_list):
word = random.choice(word_list)
if word not in random_word_list:
random_word_list += word
print(random_word_list)
input("\n\nPress enter to exit...")
|
#string_value.join(list_name)
list_1 = ["I", "am" , "learning", "python"]
outputStr ="_".join(list_1)
print(outputStr)
#string functions
var ="Learn python"
print(var.title()) #converts first letter of each word into upper case and others to lower case
print(var.swapcase()) #upper case to lower case and vice versa
print(var.upper()) # all to upper case
print(var.lower()) #all to lower case
print(var.capitalize()) #only first letter becomes upper case.rest to lower case
#use of \
path = "C:\myfile"
print(path)
path = "C:\newfile"
print(path)
path = "C:\\newfile"
print(path)
path = r"C:\newfile"
print(path)
|
#find the sum of 2 binary numbers:
def addBinary( a, b):
length = max(len(a),len(b) + 1)
sum = ['0' for i in range(length)]
if len(a)>len(b):
b= '0' * (len(a)-len(b))+b
elif len(b)>len(a):
a = '0' * (len(b)-len(a))+a
carry = 0
i = len(a)-1
while i>=0:
if int(a[i])+int(b[i])==3:
carry = 1
sum[i+1] = 1
elif int(a[i])+int(b[i])==2:
carry = 1
sum[i+1] = 0
elif int(a[i])+int(b[i])==1:
carry = 0
sum[i+1] = 1
else:
sum[i+1] = 0
if carry == 1:
sum[0] = 1
else:
sum = sum[1:length]
sum = ''.join(sum)
return sum
sum= addBinary('110','011')
print(sum)
|
target_list = input().split()
command = input()
while not command == "End":
what, where, how = command.split()
if what == "Shoot":
if len(target_list) >= int(where) >= 0:
target_list[int(where)] = int(target_list[int(where)]) - int(how)
if int(target_list[int(where)]) <= 0:
target_list.remove(target_list[int(where)])
else:
target_list[int(where)] = str(target_list[int(where)])
elif what == "Add":
if len(target_list) > int(where) >= 0:
target_list.insert(int(where), how)
else:
print("Invalid placement!")
elif what == "Strike":
first = int(where) - int(how)
last = int(where) + int(how)
if first >= 0:
if len(target_list) >= last:
for delete in range(first, last + 1):
target_list.remove(target_list[first])
else:
print("Strike missed!")
else:
print("Strike missed!")
command = input()
target_list = "|".join(target_list)
print(target_list)
|
list_with_numbers = input().split()
list_with_numbers = [int(num) for num in list_with_numbers]
average_number = sum(list_with_numbers) / len(list_with_numbers)
greater_that_average = [num for num in list_with_numbers if num > average_number]
if len(greater_that_average) == 0:
print('No')
else:
greater_that_average.sort(reverse=True)
for i in range(len(greater_that_average)):
if i > 4:
break
print(greater_that_average[i], end=" ")
|
password = input()
line = input()
while not line == "Done":
line = line.split()
command = line[0]
if command == "TakeOdd":
old_password = password
password = ""
for i in range(len(old_password)):
if not i % 2 == 0:
password += old_password[i]
print(password)
elif command == "Cut":
start = int(line[1])
stop = start + int(line[2])
password = password[:start] + password[stop::]
print(password)
elif command == "Substitute":
substring = line[1]
substitute = line[2]
if substring in password:
password = password.replace(substring, substitute)
print(password)
else:
print("Nothing to replace!")
line = input()
print(f"Your password is: {password}")
|
word = input()
dictionary = {}
for i in range(len(word)):
if word[i] == " ":
pass
elif word[i] not in dictionary:
dictionary[word[i]] = 1
else:
dictionary[word[i]] += 1
for char in dictionary:
print(f"{char} -> {dictionary[char]}")
|
number = int(input())
start = 97
end = start + number
for i in range(start, end):
for j in range(start, end):
for k in range(start, end):
print(f'{chr(i)}{chr(j)}{chr(k)}')
|
start = int(input())
second_num = int(input())
end = start * second_num
multiples_list = []
for i in range(start, end + 1, start):
multiples_list.append(i)
print(multiples_list)
|
import sys
num_1 = int(input())
num_2 = int(input())
num_3 = int(input())
def small(num_1, num_2, num_3):
smallest_of_all = sys.maxsize
if num_1 <= smallest_of_all:
smallest_of_all = num_1
if num_2 <= smallest_of_all:
smallest_of_all = num_2
if num_3 <= smallest_of_all:
smallest_of_all = num_3
result = smallest_of_all
return result
result = small(num_1, num_2, num_3)
print(result)
|
list_with_elements = input().split()
list_with_elements = [int(el) for el in list_with_elements]
while True:
user_input = input()
if user_input == "end":
break
user_input = user_input.split()
command = user_input[0]
if command == "swap":
first_element = int(user_input[1])
second_element = int(user_input[2])
list_with_elements[first_element], list_with_elements[second_element] = list_with_elements[second_element], list_with_elements[first_element]
elif command == "multiply":
first_element = int(user_input[1])
second_element = int(user_input[2])
list_with_elements[first_element] = list_with_elements[first_element] * list_with_elements[second_element]
elif command == "decrease":
list_with_elements = [(el-1) for el in list_with_elements]
list_with_elements = [str(el) for el in list_with_elements]
print(", ".join(list_with_elements))
|
happiness_list = input().split()
happiness_multiply = int(input())
multiplied_happiness_list = []
for every in happiness_list:
multiplied_happiness_list.append(int(every) * happiness_multiply)
border = sum(multiplied_happiness_list) / len(multiplied_happiness_list)
happy_employees = [employee for employee in multiplied_happiness_list if int(employee) >= border]
if len(happy_employees) >= (len(multiplied_happiness_list) / 2):
print(f'Score: {len(happy_employees)}/{len(multiplied_happiness_list)}. Employees are happy!')
else:
print(f'Score: {len(happy_employees)}/{len(multiplied_happiness_list)}. Employees are not happy!')
|
# Create calculate_insurance_cost() function below:
def calculate_insurance_cost(name, age, sex, bmi, num_of_children, smoker):
estimated_cost = 250*age - 128*sex + 370*bmi + 425*num_of_children + 24000*smoker - 12500
message = "The estimated insurance cost for " + name + " is " + str(estimated_cost) + " dollars."
print(message)
return (message, estimated_cost)
# Calculate the difference in insurance costs for a given two individuals
def calculate_difference_in_insurance_costs(cost1, cost2):
difference = abs(cost1 - cost2)
print("The difference in insurance cost is " + str(difference) + " dollars.")
return difference
# Estimate Maria's insurance cost
maria_insurance_cost = calculate_insurance_cost(name = "Maria", age = 28, sex = 0, bmi = 26.2, num_of_children = 3, smoker = 0)
# Estimate Omar's insurance cost
omar_insurance_cost = calculate_insurance_cost(name = "Omar", age = 35, sex = 1, bmi = 22.2, num_of_children = 0, smoker = 1)
# Estimate my own insurance cost
my_insurance_cost = calculate_insurance_cost(name = "Emmanuel", age = 26, sex = 1, bmi = 26.2, num_of_children = 0, smoker = 0)
# Display a new line
print("\n")
# Difference in insurance costs for Maria and Omar
difference_in_insurance_cost_maria_omar = calculate_difference_in_insurance_costs(5469.0, 28336.0)
# Difference in insurance costs for Emmanuel and Omar
difference_in_insurance_cost_emmanuel_and_omar = calculate_difference_in_insurance_costs(3566.0, 28336.0)
# Difference in insurance costs for Emmanuel and Maria
difference_in_insurance_cost_emmanuel_and_maria = calculate_difference_in_insurance_costs(3566.0, 5469.0)
|
'''
Author: Michele Alladio
es:
Dato un albero etichettato con numeri naturali, scrivere una funzione
nodeNumber() che restituisca il numero dei nodi
'''
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data): #ricorsiva
#confronta il valore del nodo da aggiungere con il nodo corrente
if self.data: #se esiste
if data < self.data:
if self.left is None: #se arriviamo su una foglia crea il nodo
self.left = Node(data)
else:
self.left.insert(data) #continua la ricerca
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
#attraversamento in ordine
def inOrderTraversal(self, root):
res = []
if root:
res = self.inOrderTraversal(root.left)
res.append(root.data)
res = res + self.inOrderTraversal(root.right)
return res
def sumNode(self):
somma = 0
lista = root.inOrderTraversal(self) #lettura dei valori dell'albero
for numero in lista: #aggiornamento della somma seguendo la lista di valori ricavata
somma += numero
return somma
def nodeNumber(self):
return len(self.inOrderTraversal(self))
def height(self, root):
if root:
if self.height(root.left) >= self.height(root.right):
return 1 + self.height(root.left)
else:
return 1 + self.height(root.right)
else:
return -1
root = Node(27) #12 è la radice
#inserimento dei rami/foglie
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
#numero di nodi
nNodi = root.nodeNumber()
print(nNodi)
height = root.height(root)
print(height)
|
import sys
class Triangle:
def __init__(self, a, b , c):
self.a = int(a)
self.b = int(b)
self.c = int(c)
def isValid(self):
return (self.a + self.b > self.c) and (self.a + self.c > self.b) and (self.b + self.c > self.a)
class TriangleParser:
def __init__(self, datas):
self.datas = datas
def getTriangles(self):
triangles = []
count = 0
tempDatas = []
for data in self.datas:
data = data.replace("\n", "")
dataTokens = data.split();
tempDatas.append(dataTokens)
count += 1
if count == 3:
# Construct triangle here
triangles.append(Triangle(tempDatas[0][0], tempDatas[1][0], tempDatas[2][0]))
triangles.append(Triangle(tempDatas[0][1], tempDatas[1][1], tempDatas[2][1]))
triangles.append(Triangle(tempDatas[0][2], tempDatas[1][2], tempDatas[2][2]))
# Re init for next 3 rows
count = 0
tempDatas = []
return triangles
numberOfArgs = len(sys.argv)
if(numberOfArgs == 1):
inputFile = "03.txt"
elif(numberOfArgs == 2):
inputFile = sys.argv[1]
f = open(inputFile, 'r')
triangleDatas = f.readlines()
triangleParser = TriangleParser(triangleDatas)
triangles = triangleParser.getTriangles()
valid = 0
notValid = 0
for triangle in triangles:
print "triangle a=" + str(triangle.a) + ", b=" + str(triangle.b) + ", c=" + str(triangle.c)
if triangle.isValid():
valid += 1
else:
notValid += 1
print "Total triangles : " + str(len(triangles))
print "Valid triangles : " + str(valid)
print "Not valid triangles: " + str(notValid)
#for triangleInfo in triangleInfos:
#
#
# keyPressed = keypad.pressKey(instruction.replace("\n", ""))
# print "Key pressed=" + str(keyPressed)
|
# Path setup - do not modify
from inspect import getsourcefile
import os.path as path, sys
current_dir = path.dirname(path.abspath(getsourcefile(lambda:0)))
sys.path.insert(0, current_dir[:current_dir.rfind(path.sep)])
class Solution:
def mergesort(self, arr: list , begin: int, end: int) -> list:
if len(arr) == 0 or begin > end:
return list()
if begin == end:
return [arr[end]]
left = self.mergesort(arr, begin, begin + (end - begin) // 2)
right = self.mergesort(arr, begin + (end - begin) // 2 + 1, end)
return self.merge(left, right)
def merge(self, l1: list, l2: list):
len1 = len(l1)
len2 = len(l2)
res = list()
i = j = 0
while i < len1 and j < len2:
if l1[i] < l2[j]:
res.append(l1[i])
i += 1
else:
res.append(l2[j])
j += 1
# remaining elements for l1
while i < len1:
res.append(l1[i])
i += 1
# remaining elements for l2
while j < len2:
res.append(l2[j])
j += 1
return res
def is_sorted(arr):
n = len(arr)
for i in range(n-1):
if arr[i] > arr[i+1]:
return False
return True
if __name__ == '__main__':
s = Solution()
arr = [1, 31, 24, 9, 11, 2, 10, 7, 77, 18, 21]
sorted_arr = s.mergesort(arr, 0, len(arr)-1)
print(sorted_arr)
print("pass" if is_sorted(sorted_arr) else "failed")
|
random_list = [19, 2, 31, 45, 6, 11, 121, 27]
def bubble_sort(nums):
# по умолчанию от меньшего к большему
swapped = True # чтобы цикл запустился хотя один раз
while swapped:
swapped = False
for i in range(len(random_list) - 1):
if nums[i] < nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]
print(nums)
swapped = True
print(random_list)
bubble_sort(random_list)
|
# Take a number and display its factors
import sys
if len(sys.argv) < 2:
print("Number required!")
exit(0)
num = int(sys.argv[1])
for i in range(2, num // 2 + 1):
if num % i == 0:
print(i, end=' ')
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} - {self.age}"
def __eq__(self, other):
return self.name == other.name and self.age == other.age
def __hash__(self):
return self.age
# def __gt__(self, other):
# # print(self, other)
# return self.age > other.age
p1 = Person("Mike", 35)
p2 = Person("Mike", 30)
# print(p1) # str(p1) -> p1.__str__()
# print(p1 == p2) # p1.__eq__(p2)
# print(p1 > p2) # p1.__gt__(p2)
# print(p1 < p2)
# team = [Person('Jack', 30), Person('Jason', 25), Person('Billy', 22)]
# for p in sorted(team):
# print(p)
team = {Person('Jack', 30), Person('Jack', 30), Person('Jason', 25),
Person('Billy', 22)}
for p in team:
print(p)
|
# Function to print table for the given number
def print_table(num, length):
for i in range(1, length + 1):
print(f"{num:2} * {i:2} = {i * num:4}")
print_table(15, 5) # Call function using positional arguments
print_table(length=5, num=23) # Using keyword arguments
|
a = int(input())
b = int(input())
if a>b:
a,b = b,a
for i in range(b,0,-1):
if a%i==0 and b%i==0:
print('gcd of',a,'and',b,'is',i)
break
|
#Leia uma temperatura em Cº e apresente ela em F
#formula f = c*(9.0/5.0) + 32.0
c = float(input("Digite a temperatura em graus Celsius: "))
f = c*(9.0/5.0) + 32.0
print("Valor em Fahrenheit: %.2f"%f,"º")
|
from Shapes import *
from Node import *
class Projection(object):
def __init__(self, mini, maxi):
""" Create the projection with it's two values: min, max"""
self.min = mini;
self.max = maxi;
def overlap(self, p2):
""" Check if this projection overlaps with the passed one"""
return (not(p2.max < self.min or self.max < p2.min))
def test_collision(A, B):
"""Test collisions between two Shapes: they can be any type of Shape (Circle or Polygon)"""
axes = A.get_axes() + B.get_axes() # Get the list of all the axes to project the shapes along
for axis in axes:
# project both Shapes onto the axis
pA = project(A, axis)
pB = project(B, axis)
# do the projections overlap?
if not(pA.overlap(pB)):
#If they don't, the shapes don't either so return false
return False
# All the projections overlap: the shapes collide -> return True
return True
def project(a, axis):
""" Project the shapes along the axis"""
mini = axis.dot(a.get_node(0, axis)) # Get the first min
maxi = mini
for i in range(1,a.num_of_nodes()):
p = axis.dot(a.get_node(i, axis)) # Get the dot product between the axis and the node
if p < mini:
mini = p
elif p > maxi:
maxi = p
return Projection(mini, maxi)
|
#7/12/21
import csv
#for reference
header = [["Time", "Velocity", "Wheel Angle", "Push Button", "X Pose", "Y Pose", "Z Orien", "X PF", "Y PF", "Z Orien PF"]]
#2D list to store all the values in
csv_data = []
app_folder = 'Data_Collection/'
def flip_data():
#cut the header off to more easily manipulate the numbers within
del csv_data[0]
for row in csv_data:
#flip wheel angles
row[2] = 1 - float(row[2]) #= -(wheel_angle - 0.5) + 0.5
#my left and right is y and my forward back is x. should be changed in another script,
#but I figure for now I should just flip my data appropriately
row[8] = float(row[8]) * -1
#swap Zorien - I think this can be flipped by making Z orien negative?
row[9] = float(row[9]) * -1
#add the header back to the front
csv_data.insert(0, header)
#takes in the name of the csv to read and stores its data to csv_data 2D list
def read_csv(csv_name):
#clear any data csv_data has in it already
del csv_data[:]
csv_name += ".csv"
with open(str(app_folder + csv_name)) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
#add every row of the read csv to the csv_data 2d list
for row in csv_reader:
csv_data.append(row)
#print(csv_data)
#takes collected data and writes it to the csv file in the same directory
def write_to_csv(csv_name):
#open the file - cleaner than having to close seperately
with open(str(app_folder + csv_name + ".csv"), 'w+') as file:
#create a csv writer
writer = csv.writer(file)
#print('csv_data: {}'.format(csv_data))
#write all rows to that csv file
writer.writerows(csv_data)
print("Data saved to csv {}!".format(csv_name))
#helper function to iterate through all of the csvs
def flip_csvs():
#iterate through all shoebox and tissue box positions
for sb_pos in range(7):
for tb_pos in range(5):
run = "{}-{}".format(sb_pos, tb_pos)
#read the csv of the given run -> over
read_csv(run)
#flip that data accordingly
flip_data()
#write that data to an accordingly named .csv file
write_to_csv(str("flipped_" + run))
if __name__ == '__main__':
print("Running main!")
flip_csvs()
print("All .csvs iterated through")
#STEPS NEEDED:
#Pose:
#Flip sign on y values
#(swap x and y) (another script)
#flip wheel angles:
#-(wheel_angle - 0.5) + 0.5 = 1 - wheel_angle
#Zorien:
#figure this one out... flip sign?
#1 --> 180
# i think flipping sign is good?
#PF:
#align PF with other vals? (pf lags so)
|
import streamlit
import streamlit as st
from pororo import Pororo
summa = Pororo(task='text_summarization', lang='ko')
def summaizer(text):
global summa
output = summa(text)
return output
def write_header():
st.title('Korean Text Summarizer')
st.markdown('''
- Paste any article in the text area below and click on the 'Summarize!' button to get the summarized textual data.
- This application is using KakaoBrais' Pororo library for text summarization.
''')
def write_textbox():
input_text = st.text_area(label='Paste your copied text here...', key=1, height=200)
button = st.button(label='Summarize!')
if button:
with st.spinner(text='This may take a moment...'):
output = summaizer(input_text)
st.text_area(label='Summary:', key=2, height=200, value=output)
else:
st.text_area(label='', key=2, height=200)
if __name__ == '__main__':
st.set_page_config(page_title='English-HindUrdu Translator', page_icon='☮️', layout='wide')
write_header()
write_textbox()
|
inventory=[]
max_hp=150
hp=150
name=""
hero_class= ""
attack = 6
defense = 6
n_turn = 0
xp=0
lv=1
#Intro
name=input("---- AVANTIA'S ADVENTURE ----\nFor those who love a good adventure\n\nWrite your hero's name to Start\n-")
print("KASSANDRIA: It's a pleasure to meet you finally, {}. My name is Kassandria, Queen of Avantia and I bring you here\nbecause you have the potential to save our reign from the caos.".format(name))
kassa_q1 = input("Will you fight for us?\n\n-")
while not (("yes" in kassa_q1.casefold()) or ("ok" in kassa_q1.casefold())):
print()
kassa_q1 = input("KASSANDRIA: Please hero... WE REALLY NEED YOU? Will you help us? Yes or no?\n\n-")
print("KASSANDRIA: Oh {}! A hero has born! In that case let me explain your quest. 3 years ago, Galandrion, the king of the\nEvelonds created a military revolution and killed my husband, King Nefesto...".format(name))
print("*A tear slowly downs Kassandria's cheek.*")
print("Kassandria: {}, if we want to beat Galandrion, we need to collect the 4 crystals of magic.\nAll what I can do is to give you one of the Relics from our family, what do you want?\n\n*There are three objects in front of you:*\n-An Ancient book.\n-A Gold Sword.\n-A flute\n".format(name))
object = input("-")
object_rec = None
while object_rec == None:
if "book" in object.casefold():
print("KASSANDRIA: Oh... Looks like you're a powerful mage!\n")
object_rec = 1
hero_class="Mage"
attack+=5
max_hp=150
inventory.append("Ancient Book")
elif "sword" in object.casefold():
print("KASSANDRIA: A brave warrior is in front of me!\n")
object_rec = 1
hero_class="Warrior"
attack+=3
defense+=2
max_hp=200
inventory.append("Gold Sword")
elif "flute" in object.casefold():
print("KASSANDRIA: The music of this bard will save Avantia!\n")
object_rec = 1
hero_class="Bard"
attack+=1
defense+=4
max_hp=150
inventory.append("Flute")
else:
object = input("KASSANDRIA: I don't have that, please choose and object:\n-")
print("{0} - {1} lv {2}\nHP: {3}\nAttack: {4}\nDefense: {5}\n".format(name,hero_class,lv,max_hp,attack,defense))
print("KASSANDRIA: Enter this portal to go to the Noiseless Woods and start looking for the first Avantia's Crystal\n *A portal is created in front of you by Kassandria*\nKASSANDRIA: Good luck, {}.\n".format(name))
#Instructions
tutorial = input("DO YOU WANT TO SEE THE TUTORIAL?\n-")
if "y" in tutorial.casefold():
print(input("HOW TO PLAY AVANTIA'S ADVENTURE\nIn this game you need to write what you want to do. Use 'Inspect' to check or see something,\n'Walk' or 'Go' to move, 'Talk' to interact with people, etc!\nPRESS ENTER TO END THE TUTORIAL"))
#Forest
print("---- NOISELESS FOREST ----\n*After crossing the portal, the warm room turns into a cold forest full of trees,\nnear you, there's nothing more than a girl crying on the ground*\n")
forest_done = False
jenna_heal=False
import random
hp = max_hp
while forest_done== False:
d1=input("You're in the middle of the clearing of Noiseless Forest\n-")
if ("inspect" in d1.casefold()) and ("girl" in d1.casefold()):
print("*The girl looks really tired and worried for something... would be a good idea to talk with her.*")
elif (("area" in d1.casefold()) or ("around" in d1.casefold()) or ("place" in d1.casefold())) and ("inspect" in d1.casefold()):
print("*There are 3 possible ways:\n-A way to the West full of an extrange fog.\n-On the North, the girl is on a path who goes to a dangerous pass.\nThere's a swamp on the East.\n")
elif (("woman" in d1.casefold()) or ("girl" in d1.casefold()) or ("jenna" in d1.casefold())) and ("talk" in d1.casefold()) and (jenna_heal==True) and ("Jenna's Necklace" in inventory) and ("Boots" in inventory):
print("JENNA: Good luck with your hourney, hero! Let me help you...")
print("*Your life is now {}.*".format(hp))
hp = max_hp
elif (("woman" in d1.casefold()) or ("girl" in d1.casefold()) or ("jenna" in d1.casefold())) and ("talk" in d1.casefold()) and (jenna_heal==True) and ("Jenna's Necklace" in inventory):
print("JENNA: My necklace! Thanks hero! As a reward, take my boots, you'll be able to take the East path with them")
print("*You've received a pair of boots!*")
inventory.append("Boots")
hp = max_hp
elif (("woman" in d1.casefold()) or ("girl" in d1.casefold()) or ("jenna" in d1.casefold())) and ("talk" in d1.casefold()) and (jenna_heal==True):
print("JENNA: Let me heal your wounds... That necklace was a present from my parent, please, help me!")
hp = max_hp
print("*Your life is now {}.*".format(hp))
elif (("woman" in d1.casefold()) or ("girl" in d1.casefold())) and ("talk" in d1.casefold()):
print("JENNA: Who... Snif... Who are you? Snif... {}? A group of goblins attacked me and have stolen my necklace,\nthey took that path to the north... Please hero, bring it back to me!")
jenna_heal=True
elif (("go" in d1.casefold()) or ("walk" in d1.casefold())) and ("north" in d1.casefold()):
print("*You go to the north*")
f1=input("The pass looks dangerous and probably someone attacks you, do you want to continue?\n")
if "yes" in f1.casefold():
n_goblins=random.randint(1,3)
hp_goblins=(n_goblins*15)
if n_goblins == 1:
print("A Goblin attacks you!")
plur=""
else:
print("{0} Goblins attack you!".format(n_goblins))
plur="s"
con1=input("Press Enter to start fighting. (On combat, use 'Attack' to fight, or 'Run' to escape.)")
print()
while ((hp>0) and (hp_goblins>0)):
print("{0}: {1} HP\n{2} Goblin{3}: {4} HP\n".format(name,hp,n_goblins,plur,hp_goblins))
n_turn += 1
turn=input("Turn {}\n".format(n_turn))
if "run" in turn.casefold():
percentage_to_run=random.randint(1,20)
if percentage_to_run>5:
print("You runaway from the combat!")
n_turn=0
break
else:
print("You can't escape from here!\nYou receive{} of damage.".format(5*n_goblins))
hp-=5*n_goblins
elif "attack" in turn.casefold():
ata1=attack+(random.randint(0,attack))
hp_goblins-=ata1
print("You make {} of damage!".format(ata1))
for i in range(0,n_goblins):
dmg1=5+random.randint(0,5)
hp-=dmg1
print("You receive {0} damage from Goblin {1}".format(dmg1,i+1))
if hp<=0:
print("\nYou lose...")
n_turn=0
elif hp_goblins<=0:
lootv=random.randint(1,20)
loot=n_goblins*lootv
print()
if loot > 15:
print("You've received the Jenna's Necklace!")
inventory.append("Jenna's Necklace")
xp+= 10*n_goblins
print("You won! {0} received {1} exp.".format(name,10*n_goblins))
n_turn=0
if xp >=50:
lv+=1
attack+=1
defense+1
max_hp+=50
xp=0
print("{0} is now level {1}".format(name,lv))
else:
continue
elif (("go" in d1.casefold()) or ("walk" in d1.casefold())) and ("south" in d1.casefold()):
print("*You go to the south*")
elif (("go" in d1.casefold()) or ("walk" in d1.casefold())) and ("east" in d1.casefold()):
print("*You go to the east*")
elif (("go" in d1.casefold()) or ("walk" in d1.casefold())) and ("west" in d1.casefold()):
print("*You go to the west*")
|
"""Is Temer still president of Brazil?
Simple Flask app that returns a text response stating
if Michel Temer is still president of Brazil.
"""
from flask import Flask
import president_fetcher
app = Flask(__name__)
@app.route('/')
def isTemerPresident():
"""Returns if Michel Temer is president of Brazil"""
president = president_fetcher.getEnWikiPresident()
if "Michel" not in president and "Temer" not in president:
return "Fora Temer!!"
return 'Sim :('
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080)
|
'''
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
largest_palindrome = 0
for i in range (100,999):
for j in range (100,999):
number = i * j
number_string = str(number)
if number_string[0] == number_string[-1] and number_string[1] == number_string[-2]: #instead of one big line
if number_string[2] == number_string[-3] and number_string[3] == number_string[-4]:
if number > largest_palindrome:
largest_palindrome = number
first_factor = i
second_factor = j
print largest_palindrome , first_factor , second_factor , ",woohoo! :D"
|
# https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3299/
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
all_shift = 0
for i in shift:
if i[0]:
all_shift += i[1]
else:
all_shift -= i[1]
if all_shift < 0:
all_shift = len(s) + all_shift
return s[-all_shift % len(s):] + s[:-all_shift % len(s)]
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
def traverse(root, path):
if not root:
path.append(None)
return
path.append(root.val)
traverse(root.left, path)
traverse(root.right, path)
p_path, q_path = [], []
traverse(p, p_path)
traverse(q, q_path)
return p_path == q_path
|
n=int(input("enter the no of terms "))#input from the user
a=int(input("enter the first number "))#input from the user
b= int(input("enter the second number "))#input from the user
i=2 #i is initialised from 2 because we have taken two elements of the fibonacci already
print(a)
print(b)
while(i<n):
fibbonacci=a+b #adding last two numbers
print(fibbonacci)
a=b #storing the value of b in a
b=fibbonacci #storing the value of fibbonacci in b
i=i+1 #increasing the value of i
|
#coding=utf-8
from Tkinter import *
'''
#RadioButtonTest
root = Tk()
# label = Label(root,text='Hello,Tknter')
# label.pack()
label = Label(root,text='RadioButtonTest')
label.pack()
#Vn means default choic from all riadiobutton
V1 = IntVar()
V1.set(1)
V2=IntVar()
V2.set(2)
V3=IntVar()
V3.set(3)
V4=IntVar()
V4.set(4)
Radiobutton(root,text='roarain',value=1).pack(anchor=N)
# Radiobutton(root,text='roarain',variable=V1,value=1).pack(anchor=N)
Radiobutton(root,text='dog',variable=V2,value=2).pack(anchor=S)
Radiobutton(root,text='cat',variable=V3,value=3).pack(anchor=W)
Radiobutton(root,text='pig',variable=V4,value=4).pack(anchor=E)
root.mainloop()
'''
'''
#CheckButtonTest
root = Tk()
var = IntVar()
c = Checkbutton(root,text='this is roarain',variable = var)
c1 = Checkbutton(root,text='this is dog',variable = var)
c.pack()
c1.pack()
root.mainloop()
'''
'''
#EntryTest
root = Tk()
e = Entry(root)
e.pack(padx=20,pady=20)
e.delete(0,END)
e.insert(0,'This is Roarain,My name is Wangxiaoyu,I`m learning Python...')
root.mainloop()
'''
'''
#listbox test
root = Tk()
listbox = Listbox(root)
listbox.pack(fill=BOTH,expand=False)
for i in ['dog','cat','pig','roarain']:
listbox.insert(0,i)
root.mainloop()
'''
'''
#Pack test
root = Tk()
# Label(root,text='red',bg='red',fg='white').pack(fill=BOTH)
# Label(root,text='green',bg='green',fg='black').pack(fill=Y)
# Label(root,text='yellow',bg='yellow',fg='black').pack(fill=Y)
Label(root,text='red',bg='red',fg='white').pack(side=LEFT)
Label(root,text='green',bg='green',fg='black').pack(side=RIGHT)
Label(root,text='blue',bg='blue',fg='white').pack(side=BOTTOM)
Label(root,text='yellow',bg='yellow',fg='black').pack(side=TOP)
root.mainloop()
'''
#grid test
root = Tk()
Label(root,text='First Line').grid(row=0)
Label(root,text='Third Line').grid(row=2)
Entry(root).grid(column=0,row=1)
Entry(root).grid(column=1,row=1)
root.mainloop()
|
class Stack(object):
def __init__(self, count):
self.__count = count
self.__content = [None for _ in range(count)]
self._cursor = 0
@property
def is_empty(self):
return self._cursor == 0
@property
def is_full(self):
return self._cursor == self.__count
def peek(self):
return self.__content[self._cursor-1]
def push(self, item):
self.__content[self._cursor] = item
self._cursor += 1
def pop(self):
if self.is_empty:
raise IndexError("栈为空")
self._cursor -= 1
return self.__content[self._cursor]
stack = Stack(3)
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop())
print(stack.pop())
print(stack.peek())
print(stack.pop())
|
class TrieNode(object):
def __init__(self):
self.passed = 0
self.end = 0
self.next_node = {}
class TrieTree(object):
def __init__(self):
self._head = TrieNode()
def add(self, string):
tmp = self._head
tmp.passed += 1
for s in string:
next_node = tmp.next_node.get(s)
if next_node is None:
tmp.next_node[s] = TrieNode()
tmp = tmp.next_node[s]
tmp.passed += 1
tmp.end += 1
def __contains__(self, string):
tmp = self._head
for item in string:
tmp = tmp.next_node.get(item)
if tmp is None:
return False
return tmp.end != 0
def remove(self, string):
if string in self:
tmp = self._head
tmp.passed -= 1
for s in string:
last = tmp
tmp = tmp.next_node.get(s)
tmp.passed -= 1
if tmp.passed == 0:
last.next_node.pop(s)
return 1
tmp.end -= 1
return 1
return 0
def search(self, string):
tmp = self._head
for item in string:
tmp = tmp.next_node.get(item)
if tmp is None:
return 0
return tmp.end
def prefix_number(self, string):
tmp = self._head
for i in range(len(string)):
tmp = tmp.next_node.get(string[i])
if tmp is None:
return 0
return tmp.passed
__len__ = lambda self: self._head.passed
a = TrieTree()
a.add("abc")
a.add("abe")
a.add("abkf")
a.remove("abkf")
print(len(a))
|
class UnionFindSet(object):
"""
并查集,使用O(1)的时间来判断两个元素是否在同一个集合中。
"""
def __init__(self, iterable):
self._size = {}
self._parent = {}
for i in iterable:
self._parent[i] = i
self._size[i] = 1
def is_same_set(self, item1, item2):
if self._parent.get(item1) is None or self._parent.get(item2) is None:
return False
item1_father = self._get_father(item1)
item2_father = self._get_father(item2)
return item1_father == item2_father
def _get_father(self, item):
stack = [item, ]
while stack:
item = stack[-1]
tmp = self._parent[item]
if tmp == item:
stack.pop()
for i in stack:
self._parent[i] = tmp
break
else:
stack.append(tmp)
return item
def union(self, item1, item2):
if self._parent.get(item1) is None or self._parent.get(item2) is None:
return
item1_father = self._get_father(item1)
item2_father = self._get_father(item2)
if self._size[item1_father] >= self._size[item2_father]:
self._parent[item2] = item1_father
self._size[item1_father] += self._size[item2_father]
self._size.pop(item2_father)
else:
self._parent[item1] = item2_father
self._size[item2_father] += self._size[item1_father]
self._size.pop(item1_father)
a = UnionFindSet([1, 2, 3, 4, 5])
a.union(2, 3)
print(a.is_same_set(2, 3))
|
class BinaryTree:
def __init__(self, root):
self.root = root
self.result = []
def depthFirstPreOrderTraverse(self):
self.__preDFT(self.root)
return ','.join(self.result)
def __preDFT(self, node):
if node == None:
return
self.result.append(node.data)
self.__preDFT(node.left)
self.__preDFT(node.right)
def depthFirstInOrderTraverse(self):
self.__inDFT(self.root)
return ','.join(self.result)
def __inDFT(self, node):
if node == None:
return
self.__inDFT(node.left)
self.result.append(node.data)
self.__inDFT(node.right)
def depthFirstPostOrderTraverse(self):
self.__postDFT(self.root)
return ','.join(self.result)
def __postDFT(self, node):
if node == None:
return
self.__postDFT(node.left)
self.__postDFT(node.right)
self.result.append(node.data)
class Queue:
head = None
tail = None
class Node:
def __init__(self, data):
self.data = data
self.next = None
def enqueue(self, input):
node = self.Node(input)
if self.head is None:
self.head = node
if self.tail is not None:
self.tail.next = node
self.tail = node
def dequeue(self):
if self.head is None:
return None
delete = self.head
self.head = delete.next
result = delete.data
delete = None
return result
def empty(self):
return self.head is None
def breathFirst(self):
queue = self.Queue()
queue.enqueue(self.root)
while queue.empty() == False:
treeNode = queue.dequeue()
self.result.append(treeNode.data)
if treeNode.left is not None:
queue.enqueue(treeNode.left)
if treeNode.right is not None:
queue.enqueue(treeNode.right)
return ','.join(self.result)
|
class SinglyLinkedList:
head = None
tail = None
length = 0
def __init__(self):
pass
class Node:
def __init__(self, data):
self.data = data
self.next = None
def toString(self):
tmp = self.head
result = []
for i in range(self.length):
result.append(tmp.data)
tmp = tmp.next
return ','.join(result)
def addFirst(self, input):
node = self.Node(input)
if self.head is not None:
node.next = self.head
if self.tail is None:
self.tail = node
self.head = node
self.length += 1
def addLast(self, input):
node = self.Node(input)
if self.tail is not None:
self.tail.next = node
if self.head is None:
self.head = node
self.tail = node
self.length += 1
def __node(self, idx):
tmp = self.head
for i in range(idx):
if tmp is not None:
tmp = tmp.next
return tmp
def addFront(self, idx, input):
if idx == 0:
self.addFirst(input)
elif idx >= self.length:
self.addLast(input)
else:
frontNode = self.__node(idx - 1)
node = self.Node(input)
node.next = frontNode.next
frontNode.next = node
self.length += 1
def addBack(self, idx, input):
if idx >= self.length:
self.addLast(input)
else:
frontNode = self.__node(idx)
node = self.Node(input)
if frontNode is not None:
node.next = frontNode.next
frontNode.next = node
if self.head is None:
self.head = self.tail = node
if node.next is None:
self.tail = node
self.length += 1
def removeFirst(self):
if self.head is None:
return None
deleteNode = self.head
self.head = deleteNode.next
result = deleteNode.data
deleteNode = None
self.length -= 1
return result
def remove(self, idx):
if idx == 0:
return self.removeFirst()
elif idx >= self.length:
return None
else:
prevNode = self.__node(idx - 1)
deleteNode = prevNode.next
prevNode.next = deleteNode.next
if prevNode.next is None:
self.tail = prevNode
result = deleteNode.data
deleteNode = None
self.length -= 1
return result
def removeLast(self):
if self.length == 0:
return None
return self.remove(self.length - 1)
def size(self):
return self.length
def empty(self):
return self.head is None
def get(self, idx):
node = self.__node(idx)
if node is None:
return None
else:
return node.data
def indexOf(self, data):
tmp = self.head
for i in range(self.length):
if tmp.data == data:
return i
tmp = tmp.next
return -1
|
import unittest
from disJointSetTree import DisJointSetTree
class DisJointSetTreeTest(unittest.TestCase):
def setUp(self):
self.set = DisJointSetTree()
def test_makeSet(self):
self.set.makeSet(0)
self.set.makeSet(1)
self.set.makeSet(2)
self.set.makeSet(3)
self.set.makeSet(4)
self.set.makeSet(5)
self.set.makeSet(6)
self.set.makeSet(7)
self.set.makeSet(8)
self.assertEqual('0,1,2,3,4,5,6,7,8', self.set.toString())
with self.assertRaises(IndexError):
self.set.makeSet(9)
def test_find(self):
self.set.makeSet(0)
self.set.makeSet(1)
self.set.makeSet(2)
self.set.makeSet(3)
self.set.makeSet(4)
self.set.makeSet(5)
self.set.makeSet(6)
self.set.makeSet(7)
self.set.makeSet(8)
self.assertEqual(0, self.set.find(0))
self.assertEqual(1, self.set.find(1))
self.assertEqual(2, self.set.find(2))
self.assertEqual(3, self.set.find(3))
self.assertEqual(4, self.set.find(4))
self.assertEqual(5, self.set.find(5))
self.assertEqual(6, self.set.find(6))
self.assertEqual(7, self.set.find(7))
self.assertEqual(8, self.set.find(8))
with self.assertRaises(IndexError):
self.set.find(-1)
self.set.find(9)
def test_union(self):
self.set.makeSet(0)
self.set.makeSet(1)
self.set.makeSet(2)
self.set.makeSet(3)
self.set.makeSet(4)
self.set.makeSet(5)
self.set.union(1, 3)
self.assertEqual('0,3,2,3,4,5', self.set.toString())
self.set.union(4, 1)
self.assertEqual('0,3,2,3,3,5', self.set.toString())
self.set.union(2, 0)
self.assertEqual('0,3,0,3,3,5', self.set.toString())
self.set.union(1, 2)
self.assertEqual('0,3,0,0,3,5', self.set.toString())
self.set.union(1, 5)
self.assertEqual('0,3,0,0,3,0', self.set.toString())
self.assertEqual('2,0,0,1,0,0', self.set.toStringRank())
if __name__ == '__main__':
unittest.main()
|
class Stack:
head = None
size = 0
class Node:
next = None
def __init__(self, data):
self.data = data
def toString(self):
tmp = self.head
result = []
for i in range(self.size):
result.append(str(tmp.data))
tmp = tmp.next
return ','.join(result)
def push(self, input):
node = self.Node(input)
node.next = self.head
self.head = node
self.size += 1
def top(self):
if self.head == None:
return None
else:
return self.head.data
def pop(self):
if self.head == None:
return None
node = self.head
self.head = node.next
result = node.data
node = None
self.size -= 1
return result
def empty(self):
return self.head == None
|
import unittest
from hashSet import HashSet
class Phone:
def __init__(self, number, name):
self.number = number
self.name = name
def hash(self):
return int(self.number[:3])
def equals(self, obj):
return self.number == obj.number
class HashSetTest(unittest.TestCase):
def setUp(self):
self.set = HashSet()
def test_find(self):
phone1 = Phone('017-0774-1234-5678', 'Maria');
phone2 = Phone('112-4567-1122-9740', 'Sasha');
phone3 = Phone('150-2570-7171-7575', 'Helen');
self.set.add(phone1);
self.set.add(phone2);
self.set.add(phone3);
self.assertTrue(self.set.find(phone1));
self.assertTrue(self.set.find(phone2));
self.assertTrue(self.set.find(phone3));
self.assertFalse(self.set.find(Phone('123', 'test')));
def test_remove(self):
phone1 = Phone('017-0774-1234-5678', 'Maria');
phone2 = Phone('112-4567-1122-9740', 'Sasha');
phone3 = Phone('150-2570-7171-7575', 'Helen');
self.set.add(phone1);
self.set.add(phone2);
self.set.add(phone3);
self.assertEqual('Maria', self.set.remove(phone1).name)
self.assertEqual('Sasha', self.set.remove(phone2).name)
self.assertEqual('Helen', self.set.remove(phone3).name)
self.assertIsNone(self.set.remove(Phone('123', 'test')))
if __name__ == '__main__':
unittest.main()
|
# zip function
# zip function are used zip two lists
# it awlays returns tuples
l1=[1,2,3,4]
l2=[5,6,7,8]
new_list=[]
'''last_name=[10,11,14,17]
l3=list(zip(l1,l2,last_name))
print(l3)'''
#l=[(1,2),(3,4),(5,6),(7,8)]
#print(list(zip(*l)))
'''l1,l2=list(zip(*l))# list unpacking
print(list(l1))
print(list(l2))'''
for i in zip(l1,l2):
new_list.append(max(i))
print(new_list)
|
#first_name= "koushik"
#last_name= "bose"
#full_name= first_name+ " " + last_name
#print(full_name)
#print(first_name + str(7))
#print(first_name+"7")
#print(first_name*7)
#print(first_name*7)
#print("\n")
#name=input("enter your name: ")
#print(" hello\t " + name)
#age=(input("enter your age : "))
#print("your name is : " + age)
#number_one=int(input("enter first number: "))
#number_two=int(input("enter second number: "))
#total=number_one+number_two
#print("total number is: "+ str(total))
#print(total)
number1=str(4)
number2=float("44")
number3=int("33")
#print(number1 + number3)
print(number2)
|
from functools import wraps
# new functionality in decoraters
def function_data(function):
@wraps(function)
def wrapper(*args,**kwargs):
print(f" you are calling {function.__name__} ")
print(f"{function.__doc__}")
return function(*args,**kwargs)
return wrapper
@function_data
def add(a,b):
"""this function takes two numbers as their argument return their sum"""# docstring
return a+b
print(add(4,7))
#print(add.__doc__)
#print(add.__name__)
|
# tuple data structure
# tuple can store any data type
# most important tuple are immutable,once tuple is created you can't update
# data inide tuple
# no append ,no insert,no pop,no remove methods() available in tuple()
# tuple are faster than list
# count,index
# length function
# slicing
#print(dir(tuple))
#looping
t=(1,2,3,4,5,6,7)
# for loop and tuple
#for i in t:
#print(i)
#i=0
#while i <len(t):
#print(t)
#i+=1
#tuple with one element
#nums=(1,)# one element tuple is created with single comma
#words=('words1',)
#print(type(words))
#tuple without parenthesis
guiter='koushik','arnok','john'
#print(type(guiters))
#tuple unpacking
#guiter1,guiter2,guiter3=(guiter)
#print(guiter1)
#guiter1,guiter2=(guiter)
#print(guiter)
# list inside tuple
t1=('koushik',['arnok','john'])
#t1[1].pop()
#print(t1)
t1[1].append("we are made it.")
#print(t1)
# min(),max,sum methods in tuple
#print(min(t))
#print(max(t))
#print(sum(t))
# more about tuple
# function returning two values
def func(int1,int2):
add= int1+int2
multiply=int1*int2
return add,multiply
#print(func(2,7))
#add,multiply=func(4,7)
#print(add)
#print(multiply)
#num=tuple(range(1,10))
#print(num)
n=str((1, 2, 3, 4, 5, 6, 7, 8, 9))
print(n)
print(type(n))
|
import sys
def main():
count = int(input())
numbers = list()
for i in range(2, count + 2):
numbers.append(int(input()))
case = 1
for num in numbers:
issue_checks(num, case)
case += 1
def issue_checks(num, case_num):
digits = list(int(d) for d in str(num))
result = ""
result_left = ""
flag = False
for digit in digits:
if digit != 4:
result += str(digit)
if flag:
result_left += str(0)
else:
result += str(2)
result_left += str(2)
flag = True
print("Case #%s: %s %s" % (case_num, result, result_left))
if __name__ == '__main__':
main()
|
"""
Author: Manasi Gund
Source: CodeChef
Link: https://www.codechef.com/problems/PALIN
"""
def get_middle(number):
mid = int(len(number) // 2)
if len(number) % 2 == 0:
return mid - 1, mid
else:
return mid, mid
def next_palindrome(number):
if number == '9' * len(number):
return '1' + ('0' * int(len(number) - 1)) + '1'
number = [ch for ch in number]
i, j = get_middle(number)
while i >= 0 and j < len(number) and number[i] == number[j]:
i -= 1
j += 1
switch = False
if i < 0 or number[i] < number[j]:
switch = True
if switch:
i, j = get_middle(number)
carry = False
while number[i] == '9':
number[i] = '0'
number[j] = number[i]
carry = True
i -= 1
j += 1
if i >= 0 or carry:
number[i] = str(int(number[i]) + 1)
while i >= 0:
number[j] = number[i]
i -= 1
j += 1
return ''.join(number)
def main():
for _ in range(int(input())):
print(next_palindrome(input()))
if __name__ == '__main__':
main()
|
"""
$5 + 10 CHF = $10 if rate is 2:1
$5 + $5 = $10
Return Money from $5 + $5
Bank.reduce(Money)
Reduce Money with conversion
Reduce(Bank, String)
Sum.plus
Expression.times
"""
from unittest import TestCase
from abc import abstractmethod
class Expression(object):
@abstractmethod
def reduce(self, bank, to_currency_code):
raise NotImplementedError
@abstractmethod
def plus(self, addend):
raise NotImplementedError
@abstractmethod
def times(self, multiplier):
raise NotImplementedError
class Money(Expression):
def __init__(self, amount, currency_code):
self.amount = amount
self.currency_code = currency_code
def currency(self):
return self.currency_code
def times(self, multiplier):
return Money(self.amount * multiplier, self.currency_code)
def plus(self, addend):
return Sum(self, addend)
def reduce(self, bank, to_currency_code):
rate = bank.rate(self.currency_code, to_currency_code)
return Money(self.amount/rate, to_currency_code)
def __eq__(self, other):
return self.amount == other.amount and self.currency_code == other.currency_code
def __repr__(self):
return 'Money(%s, %s)' % (self.amount, self.currency_code)
@staticmethod
def dollar(amount):
return Money(amount, 'USD')
@staticmethod
def franc(amount):
return Money(amount, 'CHF')
class Sum(Expression):
def __init__(self, augend, addend):
self.augend = augend
self.addend = addend
def reduce(self, bank, currency_code):
augend = bank.reduce(self.augend, currency_code)
addend = bank.reduce(self.addend, currency_code)
amount = augend.amount + addend.amount
return Money(amount, currency_code)
def plus(self, addend):
return Sum(self, addend)
def times(self, multiplier):
augend = self.augend.times(multiplier)
addend = self.addend.times(multiplier)
return Sum(augend, addend)
class Bank(object):
def __init__(self):
self.rates = dict()
def reduce(self, expression, to_currency_code):
return expression.reduce(self, to_currency_code)
def rate(self, from_currency_code, to_currency_code):
k = (from_currency_code, to_currency_code)
return self.rates.get(k, 1)
def add_rate(self, from_currency_code, to_currency_rate, rate):
k = (from_currency_code, to_currency_rate)
self.rates[k] = rate
class MoneyTestCase(TestCase):
def test_multiplication(self):
five = Money.dollar(5)
self.assertEqual(five.times(2), Money.dollar(10))
self.assertEqual(five.times(3), Money.dollar(15))
def test_equality(self):
self.assertTrue(Money.dollar(5) == Money.dollar(5))
self.assertFalse(Money.dollar(5) == Money.dollar(6))
self.assertFalse(Money.dollar(5) == Money.franc(5))
def test_currency(self):
self.assertEqual(Money.dollar(1).currency(), 'USD')
self.assertEqual(Money.franc(1).currency(), 'CHF')
def test_simple_addition(self):
five = Money.dollar(5)
s = five.plus(five)
bank = Bank()
reduced = bank.reduce(s, 'USD')
self.assertEqual(reduced, Money.dollar(10))
def test_plus_returns_sum(self):
five = Money.dollar(5)
s = five.plus(five)
self.assertEqual(s.augend, five)
self.assertEqual(s.addend, five)
def test_reduce_sum(self):
s = Sum(Money.dollar(3), Money.dollar(4))
bank = Bank()
result = bank.reduce(s, 'USD')
self.assertEqual(result, Money.dollar(7))
def test_reduce_money(self):
bank = Bank()
result = bank.reduce(Money.dollar(1), 'USD')
self.assertEqual(result, Money.dollar(1))
def test_reduce_money_different_currencies(self):
bank = Bank()
bank.add_rate('CHF', 'USD', 2)
result = bank.reduce(Money.franc(2), 'USD')
self.assertEqual(result, Money.dollar(1))
def test_identity_rate(self):
bank = Bank()
self.assertEqual(bank.rate('USD', 'USD'), 1)
def test_mixed_addition(self):
five_bucks = Money.dollar(5)
ten_francs = Money.franc(10)
bank = Bank()
bank.add_rate('CHF', 'USD', 2)
result = bank.reduce(five_bucks.plus(ten_francs), 'USD')
self.assertEqual(Money.dollar(10), result)
def test_sum_plus_money(self):
five_bucks = Money.dollar(5)
ten_francs = Money.franc(10)
bank = Bank()
bank.add_rate('CHF', 'USD', 2)
s = Sum(five_bucks, ten_francs).plus(five_bucks)
result = bank.reduce(s, 'USD')
self.assertEqual(result, Money.dollar(15))
def test_sum_times(self):
five_bucks = Money.dollar(5)
ten_francs = Money.franc(10)
bank = Bank()
bank.add_rate('CHF', 'USD', 2)
s = Sum(five_bucks, ten_francs).times(2)
result = bank.reduce(s, 'USD')
self.assertEqual(result, Money.dollar(20))
|
num1 = input("enter number 1")
num2 = input("enter number 2")
print("before swapping")
print("num1=" , num1)
print("num2=" , num2)
num1 = num1 + num2
num2 = num1 - num2
num1 = num1-num2
print("after swapping")
print("num1=" , num1)
print("num2=" , num2)
|
## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
## TODO: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# As an example, you've been given a convolutional layer, which you may (but don't have to) change:
# 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel
# convolutional layer (sees 224x224x1 tensor)
# size of the imput image=W-F+2P/S+1
self.conv1 = nn.Conv2d(1, 16, 5)
self.bn1= nn.BatchNorm2d(16)
# convolutional layer (sees 111x111x16 tensor)
self.conv2 = nn.Conv2d(16, 32, 5, padding=1)
self.bn2= nn.BatchNorm2d(32)
# convolutional layer (sees 54x54x32 tensor)
self.conv3 = nn.Conv2d(32, 64, 5, padding=1)
self.bn3= nn.BatchNorm2d(64)
# convolutional layer (sees 26x26x64 tensor)
self.conv4 = nn.Conv2d(64, 128, 5, padding=1)
self.bn4= nn.BatchNorm2d(128)
# convolutional layer (sees 12x12x128 tensor)
self.conv5 = nn.Conv2d(128, 256, 5, padding=1)
self.bn5= nn.BatchNorm2d(256)
# max pooling layer
self.pool = nn.MaxPool2d(2, 2)
# linear layer (256 * 5 * 5 -> 1024)
self.fc1 = nn.Linear(256 * 5 * 5 , 1024)
# linear layer (1024 -> 136)
self.fc2 = nn.Linear(1024, 136)
# dropout layer (p=0.25)
self.dropout = nn.Dropout(0.25)
## Note that among the layers to add, consider including:
# maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting
def forward(self, x):
## TODO: Define the feedforward behavior of this model
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.bn1(self.conv1(x))))
x = self.pool(F.relu(self.bn2(self.conv2(x))))
x = self.pool(F.relu(self.bn3(self.conv3(x))))
x = self.pool(F.relu(self.bn4(self.conv4(x))))
x = self.pool(F.relu(self.bn5(self.conv5(x))))
# flatten image input
x = x.view(-1, 256 * 5 * 5)
# add dropout layer
x = self.dropout(x)
# add 1st hidden layer, with relu activation function
x = F.relu(self.fc1(x))
# add dropout layer
x = self.dropout(x)
# add 2nd hidden layer, with relu activation function
x = self.fc2(x)
# a modified x, having gone through all the layers of your model, should be returned
return x
|
while True:
text = input("Insert Regular Text And Turn It Into Semi Russian: ")
russianText = ""
for i in text:
if i == "A":
letter = "A"
elif i == "a":
letter = "a"
elif i == "a":
letter = "a"
elif i == "B":
letter = "B"
elif i == "b":
letter = "b"
elif i == "C":
letter = "C"
elif i == "c":
letter = "c"
elif i == "D":
letter = "Д"
elif i == "d":
letter = "д"
elif i == "E":
letter = "E"
elif i == "e":
letter = "e"
elif i == "F":
letter = "Г"
elif i == "f":
letter = "г"
elif i == "G":
letter = "Б"
elif i == "g":
letter = "б"
elif i == "H":
letter = "H"
elif i == "h":
letter = "h"
elif i == "I":
letter = "Ф"
elif i == "i":
letter = "ф"
elif i == "J":
letter = "Ь"
elif i == "j":
letter = "ь"
elif i == "K":
letter = "K"
elif i == "k":
letter = "k"
elif i == "L":
letter = "П"
elif i == "l":
letter = "п"
elif i == "M":
letter = "M"
elif i == "m":
letter = "m"
elif i == "N":
letter = "И"
elif i == "n":
letter = "и"
elif i == "O":
letter = "O"
elif i == "o":
letter = "o"
elif i == "P":
letter = "P"
elif i == "p":
letter = "p"
elif i == "Q":
letter = "Ю"
elif i == "q":
letter = "ю"
elif i == "R":
letter = "Я"
elif i == "r":
letter = "я"
elif i == "S":
letter = "Л"
elif i == "s":
letter = "л"
elif i == "T":
letter = "T"
elif i == "t":
letter = "t"
elif i == "U":
letter = "Ц"
elif i == "u":
letter = "ц"
elif i == "V":
letter = "У"
elif i == "v":
letter = "y"
elif i == "W":
letter = "Ш"
elif i == "w":
letter = "ш"
elif i == "X":
letter = "X"
elif i == "x":
letter = "x"
elif i == "Y":
letter = "Ч"
elif i == "y":
letter = "ч"
elif i == "Z":
letter = "Й"
elif i == "z":
letter = "й"
elif i == " ":
letter = " "
elif i == "?":
letter = "?"
elif i == "!":
letter = "!"
elif i == ".":
letter = "."
elif i == ",":
letter = ","
elif i == "1":
letter = "1"
elif i == "2":
letter = "2"
elif i == "3":
letter = "3"
elif i == "4":
letter = "4"
elif i == "5":
letter = "5"
elif i == "6":
letter = "6"
elif i == "7":
letter = "7"
elif i == "8":
letter = "8"
elif i == "9":
letter = "9"
elif i == "0":
letter = "0"
elif i == "'":
letter = "'"
elif i == ":":
letter = ":"
elif i == ";":
letter = ";"
elif i == "=":
letter = "="
elif i == "-":
letter = "-"
elif i == "_":
letter = "_"
elif i == "<":
letter = "<"
elif i == ">":
letter = ">"
elif i == "[":
letter = "["
elif i == "]":
letter = "]"
elif i == "@":
letter = "@"
elif i == "#":
letter = "#"
elif i == "$":
letter = "$"
elif i == "%":
letter = "%"
elif i == "^":
letter = "^"
elif i == "&":
letter = "&"
elif i == "*":
letter = "*"
elif i == "(":
letter = "("
elif i == ")":
letter = ")"
elif i == "+":
letter = "+"
elif i == "/":
letter = "/"
elif i == "{":
letter = "{"
elif i == "}":
letter = "}"
elif i == "`":
letter = "`"
elif i == "~":
letter = "~"
elif i == "\\":
letter = "\\"
elif i == "|":
letter = "|"
elif i == "\"":
letter = "\""
else:
letter = " "
russianText += letter
print(russianText)
class Writter(object):
def __init__(self, name)
self.name = name
self.CODE["if", "elif", "else",]
def write(self):
open(str(self.name) + ".py", "w")
|
from string import ascii_lowercase, digits
from hashlib import md5
def sanitize_channel_name(name: str) -> str:
whitelist = ascii_lowercase + digits + "-_"
name = name.lower().replace(" ", "-")
for char in name:
if char not in whitelist:
name = name.replace(char, "")
while "--" in name:
name = name.replace("--", "-")
return name
def derive_colour(string: str) -> int:
return int(md5(string.encode()).hexdigest()[:6], 16)
|
#!/usr/bin/env python
"""
Spy snippets
============
You've been recruited by the team building Spy4Rabbits, a highly advanced search engine used to help fellow agents discover files and intel needed to continue the operations against Dr. Boolean's evil experiments. The team is known for recruiting only the brightest rabbit engineers, so there's no surprise they brought you on board. While you're elbow deep in some important encryption algorithm, a high-ranking rabbit official requests a nice aesthetic feature for the tool called "Snippet Search." While you really wanted to tell him how such a feature is a waste of time in this intense, fast-paced spy organization, you also wouldn't mind getting kudos from a leader. How hard could it be, anyway?
When someone makes a search, Spy4Rabbits shows the title of the page. Your commander would also like it to show a short snippet of the page containing the terms that were searched for.
Write a function called answer(document, search_terms) which returns the shortest snippet of the document, containing all of the given search terms. The search terms can appear in any order.
The length of a snippet is the number of words in the snippet. For example, the length of the snippet "tastiest color of carrot" is 4. (Who doesn't like a delicious snack!)
The document will be a string consisting only of lower-case letters [a-z] and spaces. Words in the string will be separated by a single space. A word could appear multiple times in the document.
searchTerms will be a list of words, each word comprised only of lower-case letters [a-z]. All the search terms will be distinct.
Search terms must match words exactly, so "hop" does not match "hopping".
Return the first sub-string if multiple sub-strings are shortest. For example, if the document is "world there hello hello where world" and the search terms are ["hello", "world"], you must return "world there hello".
The document will be guaranteed to contain all the search terms.
The number of words in the document will be at least one, will not exceed 500, and each word will be 1 to 10 letters long. Repeat words in the document are considered distinct for counting purposes.
The number of words in searchTerms will be at least one, will not exceed 100, and each word will not be more than 10 letters long.
Inputs:
(string) document = "many google employees can program"
(string list) searchTerms = ["google", "program"]
Output:
(string) "google employees can program"
Inputs:
(string) document = "a b c d a"
(string list) searchTerms = ["a", "c", "d"]
Output:
(string) "c d a"
"""
import math
import sys
def answer(document, search_terms):
"""Write a function called answer(document, search_terms) which
returns the shortest snippet of the document, containing all of
the given search terms. The search terms can appear in any order.
"""
idx = {k: [] for k in search_terms}
doc = document.split()
[idx[term].append(i) for i, term in enumerate(doc, start=1) if term in search_terms]
min_score = sys.maxint
winning_slice = None
for term in idx.keys(): # ignore duplicate terms
for position in idx[term]:
positions = [position]
for other_term in idx.keys():
distances = \
[int(math.fabs(position - x)) for x in idx[other_term]]
positions.append(
idx[other_term][distances.index(min(distances))])
score = max(positions) - min(positions) + 1
if score < min_score:
winning_slice = (min(positions) - 1, max(positions),)
min_score = score
return " ".join(doc[slice(*winning_slice)])
|
import time
def bubble_sort(a):
n = len(a)
start_time=time.time()
for i in range(n):
for j in range(0,n-i-1):
if (a[j]>a[j+1]):
a[j],a[j+1]=a[j+1],a[j]
end_time=time.time()
print("the sorted array is :",a)
print("The time taken is : ",time.time()-start_time)
num=int(input("Enter array size : "))
list=[]
for i in range(0,num):
ele=int(input("ENTER ARRAY : "))
list.append(ele)
print(list)
bubble_sort(list)
#def selection_sort()
|
## step 3.2 Re-organize the Terms by Topic (5pts)
# You are asked to re-organize the terms by 5 topics.
# For the i-th topic, you should create a file named topic-i.txt.
# Separate each line in word-assignment.dat by topics assigned to them.
# For example, the lines in word-assignment.dat can be considered as the following form
# ( Note that here we replace the integers with the real terms for better illustration):
# 004 automatic:02 acquisition:02 proof:02 method:02
# 005 classification:03 noun:02 phrase:03 concept:01 individual:03
### argv: result/word-assignments.dat
### create topic files
import sys
def main():
count = 0
output = [open('topic-{}.txt'.format(i),'w') for i in range(5)]
with open(sys.argv[1], 'r') as input:
for line in input:
words = line.split()[1:]
# write words in this line into certain file
tpAdd = []
for item in words:
(word,ti) = item.split(':')
tpAdd += [int(ti)]
output[int(ti)].write(word+" ")
# write a newline in last changed output files
for i in set(tpAdd):
output[i].write('\n')
for fin in output:
fin.close()
if __name__ == '__main__':
main()
|
with open("Erik/inputs/input01.txt") as f:
partsList = []
for line in f:
partsList.append(int(line.strip()))
def fuelCalc(weight):
return (weight // 3) - 2
def recFuelCalc(weight):
addedFuel = fuelCalc(weight)
totalFuel = addedFuel
while(addedFuel > 8):
addedFuel = fuelCalc(addedFuel)
totalFuel += addedFuel
return totalFuel
fuelSum = 0
fuelSum2 = 0
for part in partsList:
fuelSum += fuelCalc(part)
fuelSum2 += recFuelCalc(part)
print(f"First case fuel is {fuelSum} units of fuel")
print(f"Second case fuel is {fuelSum2} units of fuel")
|
import random
# Choisir un nombre aléatoire
nb_choisi = random.randint(0, 100)
print(nb_choisi)
# Demander un nombre
nb_donne = input("Veuillez enter un nombre compris entre 0 et 100:\n")
while int(nb_donne) != nb_choisi:
# si c'est plus grand que le nombre choisi
if int(nb_donne) > nb_choisi:
# Dire que c'est plus petit
print("C'est plus petit 🔻")
#Si c'est plus petit que le nombre choisi
if int(nb_donne) < nb_choisi:
# Dire que c'est plus grand
print("C'est plus grand 🔺")
nb_donne = input("Veuillez enter un nombre compris entre 0 et 100:\n")
# C'est gagné
print("C'est gagné !!")
|
print("CURS 1 - TEMA - Variabile si structuri conditionale\n")
# PENTRU A TRECE LA URMATORUL PUNCT DOAR
# INTRODUCETI next :)
# 1
print("EX 1 - SIR DE NUMERE SAU DE CARACTERE? \n")
nume = input("Numele tau este: ")
while True:
text = input("Textul pe care vrei sa il verifici este: ")
if text == "next":
print("\n")
break
elif text.isdigit():
print("Sirul de numere a fost gasit de " + nume + "\n")
else:
print("Sirul de caractere a fost gasit de " + nume + "\n")
# 2
print("EX 2 - NUMAR PAR SAU IMPAR? \n")
while True:
nr = input("Introduceti un numar: ")
if nr == "next":
print("\n")
break
elif not nr.isdigit():
print("Mai incearca\n")
elif int(nr) % 2 == 0:
print("Nr e par\n")
else:
print("Nr e impar\n")
# 3
print("EX 3 - AN BISECT SAU NU? \n")
while True:
an = input("Introduceti un an: ")
if an == "next":
print("\n")
break
elif not an.isdigit() or len(an) != 4:
print("Mai incearca\n")
continue
elif int(an)%4 == 0:
print("Anul e bisect\n")
else:
print("Anul nu e bisect\n")
# 4
print("EX 4 - NUMAR <10 SAU NEGATIV? \n")
while True:
nr = input("Introduceti un numar: ")
if nr == "next":
print("\n")
break
elif nr.isdigit() and int(nr) < 10 and int(nr) != 0:
print("Numarul este mai mic decat 10\n")
elif nr[0] == "-" and nr[1:].isdigit():
print(nr[1:] + "\n")
elif nr.isdigit() and int(nr) == 0:
print("Numarul este 0\n")
elif nr.count(".") == 1 and nr[0] != "." and nr[len(nr)-1] != ".":
a = nr.split(".")
if a[0].isdigit() and a[1].isdigit() and float(a[0]) < 10 and float(a[1]) != 0:
print("Numarul este mai mic decat 10\n")
elif a[0].isdigit() and a[1].isdigit() and float(a[0]) == 0 and float(a[1]) == 0:
print("Numarul este 0\n")
elif a[0][0] == "-" and a[1].isdigit():
print(nr[1:] + "\n")
else:
print("Mai incercati\n")
else:
print("Mai incercati\n")
# 5
print("EX 5 - MENIU \n")
while True:
print("""1 – Afisare lista de cumparaturi
2 – Adaugare element
3 – Stergere element
4 – Sterere lista de cumparaturi
5 - Cautare in lista de cumparaturi \n"""
)
command = input()
if command == "1":
print("Afisare lista de cumparaturi\n")
elif command == "2":
print("Adaugare element\n")
elif command == "3":
print("Stergere element\n")
elif command == "4":
print("Sterere lista de cumparaturi\n")
elif command == "5":
print("Cautare in lista de cumparaturi\n")
else:
print("Alegerea nu exista. Reincercati\n")
|
import pandas as pd
df = pd.read_csv('/Users/oklesing/Desktop/Tensorflow-Bootcamp-master/00-Crash-Course-Basics/salaries.csv')
# Get column Salary from dataframe
salary = df['Salary']
print(salary)
# Get columns Salary and Name from dataframes
# For multiple columns use array
salary_name = df[['Salary', 'Name']]
print(salary_name)
# Get the max Salary
max_salary = df['Salary'].max()
print(max_salary)
# Describe pandas dataframe
description = df.describe()
print(description)
# Boolean filters, just like numpy
filter_df = df['Salary'] > 60000
print(filter_df)
# Print out numbers from filter
filter_df = df[df['Salary'] > 60000]
print(filter_df)
matrix = df.as_matrix()
print(matrix)
|
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
import pandas as pd
data = np.random.randint(0, 100, (10, 2))
scalar_model = MinMaxScaler()
#############################################
# Fit to training data #
# Transform to training data and test data #
#############################################
# Will convert data into floating points
# scalar_model.fit(data)
# Transforms data
# scalar_model.transform(data)
# Fit and transform in 1 step
scalar_model.fit_transform(data)
# ML Supervisied learning model
############
my_data = np.random.randint(0, 101, (50, 4))
# 3 features (f1, f2, f3)
# Predicting the label
df = pd.DataFrame(data=np.random.randint(0, 101, (50, 4)), columns=['f1', 'f2', 'f3', 'label'])
# x is the training set
x = df[['f1', 'f2', 'f3']]
# y is test data
y = df['label']
# Train Test Split
# test_size is percentage of data to go to the test set
# random_state is for repeatability. random_state is same as using a seed.
# x_train is feature data for the training set.
# x_test evaluate model using test data. Tensorflow will predict what labels should be.
# For true evaluation you can then compare predicted values against y_test values.
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.3,random_state=101)
print(x_train.shape)
print(x_test.shape)
print(y_test.shape)
print(y_train.shape)
|
#!/usr/bin/env python3
"""
stack.py - Stack Implementation
Author: Hoanh An ([email protected])
Date: 10/18/2017
"""
class Node(object):
"""
Model Node as a class.
"""
def __init__(self, value, next=None):
"""
Create an instance of Stack.
:param value: The value of a node.
:param next: The next node that it points to.
:return: Node instance.
"""
self.value = value
self.next = next
class Stack(object):
"""
Model Stack as a class.
"""
def __init__(self, top=None):
"""
Create an instance of Stack.
:param top: The top node of stack.
:return: Stack instance.
"""
self.top = top
def push(self, value):
"""
Push a node on top of a stack.
:param value: The value of a node to be pushed to a stack.
:return: None.
Complexity:
- Time: O(1)
- Space: O(1)
"""
self.top = Node(value, self.top)
def pop(self):
"""
Remove the top node of a stack.
:return: The value of that node
Complexity:
- Time: O(1)
- Space: O(1)
"""
if self.top is None:
return None
value = self.top.value
self.top = self.top.next
return value
def peek(self):
"""
Return the top value of a stack.
:return: The top value of a stack.
Complexity:
- Time: O(1)
- Space: O(1)
"""
return self.top.value if self.top is not None else None
def is_empty(self):
"""
Check if the stack is empty.
:return: True if it's empty, otherwise False
Complexity:
- Time: O(1)
- Space: O(1)
"""
return self.peek() is None
|
#!/usr/bin/env python3
"""
linked_list_test.py - Linked Listed UnitTest
Author: Hoanh An ([email protected])
Date: 10/18/2017
"""
from linked_list import *
import unittest
class TestLinkedList(unittest.TestCase):
def test_insert_to_front_empty_list(self):
linked_list = LinkedList(None)
linked_list.insert_to_front(10)
self.assertEqual(linked_list.get_all_data(), [10])
def test_insert_to_front_none(self):
linked_list = LinkedList(None)
linked_list.insert_to_front(None)
self.assertEqual(linked_list.get_all_data(), [])
def test_insert_to_front_mutiple_elements(self):
linked_list = LinkedList(None)
linked_list.insert_to_front('a')
linked_list.insert_to_front('bc')
self.assertEqual(linked_list.get_all_data(), ['bc', 'a'])
def test_append_empty_list(self):
linked_list = LinkedList(None)
linked_list.append(10)
self.assertEqual(linked_list.get_all_data(), [10])
def test_append_none(self):
linked_list = LinkedList(None)
linked_list.append(None)
self.assertEqual(linked_list.get_all_data(), [])
def test_append_multiple_elements(self):
linked_list = LinkedList(None)
linked_list.append('a')
linked_list.append('bc')
self.assertEqual(linked_list.get_all_data(), ['a', 'bc'])
def test_find_empty_list(self):
linked_list = LinkedList(None)
node = linked_list.find('a')
self.assertEqual(node, None)
def test_find_none(self):
head = Node(10)
linked_list = LinkedList(head)
node = linked_list.find(None)
self.assertEqual(node, None)
def test_find_match(self):
linked_list = LinkedList(None)
linked_list.insert_to_front('a')
linked_list.insert_to_front('bc')
node = linked_list.find('a')
self.assertEqual(str(node), 'a')
def test_find_no_match(self):
linked_list = LinkedList(None)
node = linked_list.find('aaa')
self.assertEqual(node, None)
def test_delete_empty_list(self):
linked_list = LinkedList(None)
linked_list.delete('a')
self.assertEqual(linked_list.get_all_data(), [])
def test_delete_none(self):
linked_list = LinkedList(None)
linked_list.delete(None)
self.assertEqual(linked_list.get_all_data(), [])
def test_delete_match(self):
linked_list = LinkedList(None)
linked_list.insert_to_front('a')
linked_list.insert_to_front('bc')
linked_list.delete('a')
self.assertEqual(linked_list.get_all_data(), ['bc'])
def test_delete_no_match(self):
linked_list = LinkedList(None)
linked_list.delete('aa')
self.assertEqual(linked_list.get_all_data(), [])
def test_len_empty_list(self):
linked_list = LinkedList(None)
self.assertEqual(len(linked_list), 0)
def test_len_multiple_elements(self):
head = Node(10)
linked_list = LinkedList(head)
linked_list.insert_to_front('a')
linked_list.insert_to_front('bc')
self.assertEqual(len(linked_list), 3)
def main():
test_linked_list = TestLinkedList()
test_linked_list.test_insert_to_front_empty_list()
test_linked_list.test_insert_to_front_none()
test_linked_list.test_insert_to_front_mutiple_elements()
test_linked_list.test_append_empty_list()
test_linked_list.test_append_none()
test_linked_list.test_append_multiple_elements()
test_linked_list.test_find_empty_list()
test_linked_list.test_find_none()
test_linked_list.test_find_match()
test_linked_list.test_find_no_match()
test_linked_list.test_delete_empty_list()
test_linked_list.test_delete_none()
test_linked_list.test_delete_match()
test_linked_list.test_delete_no_match()
test_linked_list.test_len_empty_list()
test_linked_list.test_len_multiple_elements()
if __name__ == '__main__':
main()
|
"""
[2, 3, 6] -> [2, 3, 7]
[9, 9, 9] -> [1, 0, 0, 0]
"""
# def add_one(given_array):
# carry = 1
#
# for index in range(len(given_array))
#
if __name__ == '__main__':
temp_array = []
for i in range(5):
temp_array.append(0)
print(temp_array)
|
"""
Assign Numbers in Minesweeper
Implement a function that assigns correct numbers in a field of Minesweeper, which is represented as a 2 dimensional array.
Example:
The size of the field is 3x4, and there are bombs at the positions [0, 0] (row index = 0, column index = 0) and [0, 1] (row index = 0, column index = 1).
Then, the resulting field should be:
[[-1, -1, 1, 0],
[2, 2, 1, 0],
[0, 0, 0, 0]]
"""
# Implement your function below.
def mine_sweeper(bombs, num_rows, num_cols):
# NOTE: field = [[0] * num_cols] * num_rows would not work
# because you need to create a new list for every row,
# instead of copying the same list.
field = [[0 for i in range(num_cols)] for j in range(num_rows)]
return field
# NOTE: Feel free to use the following function for testing.
# It converts a 2-dimensional array (a list of lists) into
# an easy-to-read string format.
def to_string(given_array):
list_rows = []
for row in given_array:
list_rows.append(str(row))
return '[' + ',\n '.join(list_rows) + ']'
# NOTE: The following input values will be used for testing your solution.
# mine_sweeper([[0, 2], [2, 0]], 3, 3) should return:
# [[0, 1, -1],
# [1, 2, 1],
# [-1, 1, 0]]
# mine_sweeper([[0, 0], [0, 1], [1, 2]], 3, 4) should return:
# [[-1, -1, 2, 1],
# [2, 3, -1, 1],
# [0, 1, 1, 1]]
# mine_sweeper([[1, 1], [1, 2], [2, 2], [4, 3]], 5, 5) should return:
# [[1, 2, 2, 1, 0],
# [1, -1, -1, 2, 0],
# [1, 3, -1, 2, 0],
# [0, 1, 2, 2, 1],
# [0, 0, 1, -1, 1]]
|
# 古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子
# 假如兔子都不死,问每个月的兔子总数为多少?
m = input('月份:')
if m == 1:
rabbits = 1
elif m == 2:
rabbits = 1
else:
rabbits = (1 / (5 ** 0.5)) * (((1 + (5 ** 0.5)) / 2) ** m - ((1 - (5 ** 0.5)) / 2) ** m)
print(rabbits)
|
#一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。
for i in range(1,1001):
list = []
for j in range(1,i):
if i % j == 0:
list.append(j)
sum_list = sum(list)
if sum_list == i:
print(i)
|
# 利用递归方法求5!。
def factorial(n):
if n == 1:
fn = 1
else:
fn = n * factorial(n - 1)
return fn
print(factorial(5))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymysql.cursors
import classe as cl
# connection to the database
conn = pymysql.connect(host='localhost', user='root', passwd='', db='Openfoodfacts', charset='utf8')
cursor = conn.cursor()
def select_categories(dict_categories):
category0 = ("veloutes")
category1 = ("sandwichs garnis de charcuteries")
category2 = ("gratins")
category3 = ("yaourts a boire")
category4 = ("batonnets glaces")
cursor.execute("""USE Openfoodfacts""")
cursor.execute("""SELECT name FROM Categories\
WHERE name LIKE %s OR name LIKE %s OR name LIKE %s OR name LIKE %s OR name LIKE %s""", \
(category0, category1, category2, category3, category4))
categories = cursor.fetchall()
# fill in the dict_categories with the five categories
print("Voici les 5 catégories permettant une recherche:")
index = 1
for i in categories:
categories_affich = cl.Categories(i, index)
dict_categories[categories_affich.index] = (categories_affich.name, categories_affich.id)
print(index, " : ", categories_affich.name)
index += 1
return dict_categories
def find_a_susbstitut():
"" "The user can choose a product from a list and our application will return a substitute" ""
dict_categories = {}
dict_product = {}
# Search for a product until it matches the chosen category
while len(dict_product) == 0:
while dict_categories == {}:
select_categories(dict_categories)
choice = user_choix_input(len(dict_categories))
# Display a list of products in the chosen category
# The user must choose a product
print(" Vous avez choisi la categorie: {}".format(dict_categories[choice][0]))
dict_product = poster_list_products(select_products(dict_categories[choice][0]))
if len(dict_product) == 0:
print("\n Il n'y a pas de produits pour cette catégorie... \n")
dict_categories = {}
choice = user_choix_input(len(dict_product))
chosen_product = extract_product(dict_product[choice])
# Display the description of the chosen product
print('\n Vous avez choisi ce produit : \n')
print_product(chosen_product)
# Find a substitute and display it
try:
substitute = search_substitute(chosen_product)
print('\n Vous pouvez remplacer ce produit par : \n')
print_product(substitute)
ajout_backup(chosen_product, substitute)
except (AttributeError, TypeError):
pass
def select_products(category):
"" "Selects the BDD products contained in the user's chosen category" ""
category = "%" + category + "%"
cursor.execute('USE openfoodfacts;')
cursor.execute(
"""SELECT DISTINCT id, name, categories_id, nutri_score, stores, url FROM Food WHERE name LIKE %s or categories_id LIKE %s """,
(category, category))
products = cursor.fetchall()
return products
def poster_list_products(products):
"""Use the result of the product selection function and display it """
print('\n Choisir un produit : ')
dict_product = {}
index = 1
for i in products:
poster_products = cl.Food(i, index)
dict_product[poster_products.index] = poster_products.name
print(index, " : ", poster_products.name)
index += 1
return dict_product
def user_choix_input(number_of_choice):
running = True
while running is True:
user_choice = input("Entrez le chiffre de votre choix ici: \n")
try:
int(user_choice)
if int(user_choice) < 0 or int(user_choice) > number_of_choice:
print("Vous devez entrer un chiffre dans la selection")
else:
running = False
return int(user_choice)
except ValueError:
print("Ceci n'est pas un chiffre, vous devez entrer un chiffre")
def print_product(product):
"""Takes a product and displays its characteristics"""
try:
print("\n \
Name : {} \n \
Categories : {} \n \
Nutri-score : {} \n \
Stores : {} \n \
URL : {}".format(product.name, product.category, product.nutri_score, product.stores, product.url))
except TypeError:
print("Désolé, il n'y a pas de substitut pour ce product...")
def ajout_backup(product, substitute):
"""Add the chosen product and its substitute to the TABLE Backup in the database"""
print('\n Voulez-vous enregistrer cette comparaison comme favori ?')
print('1. Oui')
print('2. Non')
choix = user_choix_input(2)
if choix == 1:
cursor.execute('USE openfoodfacts;')
cursor.execute("""INSERT INTO Backup (produit_id, substitut_id) \
VALUES (%s,%s)""", (product.id[0], substitute.id[0]))
conn.commit()
print('Sauvegarde effectuée')
elif choix == 2:
print('Non sauvegardé')
def poster_product_list(product):
"""Use the result of the product selection function and display it"""
print('\n Séléctionner un product : ')
dict_produit = {}
index = 1
for i in product:
poster_product = cl.Food(i, index)
dict_produit[poster_product.index] = poster_product.name
print(index, " : ", poster_product.name)
index += 1
return dict_produit
def search_substitute(product):
"""Find a product substitute in the database"""
cursor.execute('USE openfoodfacts;')
# Make a string with the categories used in the query
search = product.category
# Other variable
product_name = product.name
product_score = product.nutri_score
cursor.execute("""SELECT Food.id, Food.name, categories_id, nutri_score, url, stores \
FROM Food \
INNER JOIN Categories ON Food.categories_id = Categories.name\
WHERE categories_id LIKE %s AND Food.name NOT LIKE %s \
AND Food.nutri_score <= %s """, (search, product_name, product_score))
substitute = cursor.fetchone()
try:
return cl.Food(substitute)
except TypeError:
print("Désolé, il n'y a pas de substitut pour ce product...")
def extract_product(product):
"""Take the name of a product and return an object containing the specifications of this product"""
product = "%" + product + "%"
cursor.execute("USE openfoodfacts;")
cursor.execute("""SELECT Food.id, Food.name, categories_id, nutri_score, url, stores \
FROM Food \
INNER JOIN Categories ON Food.categories_id LIKE Categories.name\
WHERE Food.name LIKE %s;""", (product))
product = cursor.fetchone()
product_class = cl.Food(product)
return product_class
def affiche_favoris():
"""Afficher tous les favoris de l'utilisateur"""
# Liste des favoris utilisés pour la fonction "select_favorite"
favorite_dict = {}
# pour les produits dans Count
cursor.execute('USE openfoodfacts;')
cursor.execute("""SELECT F1.name as Product, F2.name as Substitute \
FROM Backup \
INNER JOIN Food F1 ON Backup.produit_id = F1.id
INNER JOIN Food F2 ON Backup.substitut_id = F2.id""")
favorite = cursor.fetchall()
index = 1
for i in favorite:
favorite_tuple = (i[0], i[1])
print("\n {}. {}, Peut être remplacé par {}.".format(index, \
favorite_tuple[0], favorite_tuple[1]))
favorite_dict[index] = favorite_tuple
index += 1
if not favorite_dict:
print ("La liste des favoris est vide.")
else:
print('Choisissez un chiffre pour plus de détail.')
select_favorite(favorite_dict)
def select_favorite(favoris_dict):
"""Display the information of the product and the substitute"""
choice = user_choix_input(len(favoris_dict))
# Extract the specifitions of the product to display it
product = extract_product(favoris_dict[choice][0])
# Extract the specifitions of the substitute to display it
substitute = extract_product(favoris_dict[choice][1])
print_product(product)
print('\n Vous pouvez remplacer ceci par: \n')
print_product(substitute)
def main():
"""Fonction main du programme"""
print('Bienvenu sur notre application !')
running = True
while running is True:
print(" _________________________________________ ")
print('|_____________MENU PRINCIPAL_____________|\n')
print('1. Choisir des aliments et les remplacer ?')
print('2. Retrouver mes aliments substitués.')
print('3. Exit.')
choix = user_choix_input(3)
if choix == 1:
find_a_susbstitut()
elif choix == 2:
affiche_favoris()
elif choix == 3:
running = False
if __name__ == "__main__":
main()
|
#팩토리얼 프로그램
fac=int(input("숫자를 입력하세요."))
sum1=0
for i in range(1,fac+1,1):
sum=sum*i
print(sum1)
|
# 참석자에 맞추어서 치킨(1인당 1마리), 맥주(1인당 2캔),
# 케익(1인당 4개)를 출력하는 프로그램을 작성해보자.
cham=int(input("참석자를 넣어주세요"))
ch=cham*1
beer=cham*2
cake=cham*4
print("치킨=",ch, "마리")
print("맥주=",beer,"잔")
print("케익=",cake, "개")
|
# Variables of different types
# 기본형 타입
b=True
i=1
f=0.1
c="c"
str="hello"
n=None
# 변수 타입 확인
print("b", type(b))
print("i", type(i))
print("f", type(f))
print("c", type(c))
print("str", type(str))
print("n", type(n))
# 복합형 타입
set1=set([1,2,3,1,2])
set2=set("Hello")
l=[0,1,2,0,3]
t=(0,1,2)
d={0:"Zero"}
# 변수 타입 확인
|
import random
from overlap import isOverlapR2
def newrandom():
'''
used to generate sample and process some controled testing
'''
def getRandom(min,max):
for m in range(2):
(a,b)=random.randint(min, max),random.randint(min, max)
(c,d)=random.randint(min, max),random.randint(min, max)
return (a,b), (c,d)
n=100
v1=[]
v2=[]
i=0
while i<n:
#-5,5 ==>output1.txt
#-10,0 ==>output2.txt
#0,100 ==> output3.txt
(a,b), (c,d)=getRandom(-20,20)
v1.append((a,b))
v2.append((c,d))
i+=1
for i in range(n):
print(v1[i], v2[i],isOverlapR2(v1[i], v2[i]))
'''
#used to generate testsample.txt
print (n+1)
for i in range(n):
print(v1[i][0],',', v1[i][1], ',', v2[i][0], ',', v2[i][1] )
'''
newrandom()
|
# https://leetcode.com/problems/richest-customer-wealth/
def rich_customer(accounts):
max_wealth = 0
for customer in accounts:
new_wealth = sum(customer)
if new_wealth > max_wealth:
max_wealth = new_wealth
return max_wealth
print(rich_customer([[1, 2, 3], [3, 2, 1]]))
print(rich_customer([[1, 5], [7, 3], [3, 5]]))
print(rich_customer([[2, 8, 7], [7, 1, 3], [1, 9, 5]]))
|
# https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
def kids_with_candies(candies, extraCandies):
original_greatest = max(candies)
output = list()
for original in candies:
updated_candies = original + extraCandies
output.append(updated_candies >= original_greatest)
return output
print(kids_with_candies([2, 3, 5, 1, 3], 3))
print(kids_with_candies([4, 2, 1, 1, 2], 1))
print(kids_with_candies([12, 1, 12], 10))
|
def print_comments():
"""check if a phrase is correct in respect to parenthesis openings and closings"""
with open('a_cpp_file.cpp', 'r') as file:
data = file.read()
to_print = ''
should_print = False
for i, char in enumerate(data):
if i > 1:
if data[i-1] == '*' and data[i-2] == '/':
should_print = True
if char == '*' and data[i+1] == '/' and should_print:
should_print = False
print(to_print)
to_print = ''
if should_print:
to_print += char
should_print = False
for i, char in enumerate(data):
if i > 1:
if data[i-1] == '/' and data[i-2] == '/':
should_print = True
if char == '\n' and should_print:
should_print = False
print(to_print)
to_print = ''
if should_print:
to_print += char
print_comments()
|
print('This calculator will change the temperature from Fahrenite to Celcius. Check it out!\nTemperature in Fahrenheit!')
temp_nite = int(input())
def convert_temp(nite):
return ((temp_nite - 32) * 5/9)
def converted_temp(cel):
return "The temperature is {} in celcius.".format(cel)
result = convert_temp(temp_nite)
celcius = converted_temp(result)
print(celcius)
|
INF = float('inf')
class Card:
def __init__(self, s, v):
self.suit = s
self.value = v
def merge(A, left, mid, right):
n1 = mid - left
n2 = right - mid
L = [A[left + i] for i in xrange(n1)] + [Card('', INF)]
R = [A[mid + i] for i in xrange(n2)] + [Card('', INF)]
i = j = 0
for k in xrange(left, right):
if L[i].value <= R[j].value:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
def mergeSort(A, left, right):
if left + 1 < right:
mid = (left + right) / 2
mergeSort(A, left, mid)
mergeSort(A, mid, right)
merge(A, left, mid, right)
def partition(A, p, r):
x = A[r].value
i = p - 1
for j in range(p, r):
if A[j].value <= x:
i += 1
A[i], A[j] = A[j], A[i]
A[i + 1], A[r] = A[r], A[i + 1]
return i + 1
def quickSort(A, p, r):
if p < r:
q = partition(A, p, r)
quickSort(A, p, q - 1)
quickSort(A, q + 1, r)
def main():
n = input()
A = [None] * n
for i in xrange(n):
s, v = raw_input().split()
A[i] = Card(s, int(v))
B = list(A)
quickSort(A, 0, n - 1)
mergeSort(B, 0, n)
if A == B:
print 'Stable'
else:
print 'Not stable'
for a in A:
print a.suit, a.value
if __name__ == '__main__':
main()
|
print("Var bor du")
land = input()
Norden = ["Sverige", "sverige", "Norge", "norge", "Finland", "finland", "Danmark", "danmark", "Island", "island"]
Storbritanien = ["England", "england", "Wales", "wales", "Nordirland", "nordirland", "Skottland", "skottland"]
if land in Norden: #om din input är finns i listan norden:
print("Du bor i Norden")
else:
if land in Storbritanien:
print("Du bor i Storbritanien")
else: #om din input varken passar in på listan norden eller strbritanien får du ett elakt errormeddelande
print("Error 404, du suger för du bor varken i Norden eller Storbritanien")
|
import requests
print("Skriv in namn på stad")
city = str(input()) #gör inputen till en string
cities = [ #städer i sringern
"stockholm",
"uppsala",
]
if city.lower() in cities:
forecasts = requests.get('https://54qhf521ze.execute-api.eu-north-1.amazonaws.com/weather/' + city.lower()).json()["forecasts"]
#gör en request för värden från apien och tar de värden från city.lower och gör en lista
print(forecasts[0]["date"] + " will be " + forecasts[0]["forecast"] )
for i in forecasts:
print(i["date"] + " will be " + i["forecast"])
else:
print("Invalid city")
|
#coding:gb2312
#ʹpop()del()бɾ
names=['cby','lyl','fjy','hl','sch']
message_1="Since the reserved table could not be delivered in time, I could only invite two guests."
print(message_1)
message_2="I'm So Sorry I Can't Have Dinner With You"
popped_names=names.pop(-1)
print(popped_names.title()+", "+message_2+"!")
popped_names=names.pop(-1)
print(popped_names.title()+", "+message_2+"!")
popped_names=names.pop(-1)
print(popped_names.title()+", "+message_2+"!")
#print(names)
message_3=", "+"Would You Like To Have Dinner With Me"+"?"
print(names[0].title()+message_3)
print(names[1].title()+message_3)
del names[0]
del names[0]
print(names)
|
#coding:gb2312
#ifϰ1
#if-else
alien_color='yellow'
if alien_color=='green': #==ȣ=鲻
print("һ÷5")
else:
print("һ÷10")
#if-elif-else
alien_color='red'
if alien_color=='green':
print("÷5")
elif alien_color=='yellow':
print("һ÷10")
else:
print("һ÷15")
|
#coding:gb2312
#ifѧϰ
#if䣬ִеһ
print("if䣺\n")
age=18
if age>=18: #ifforеҪðţһжҪ
print("You are old enough to vote!") #ifͨˣŻִifĵĴ
print("Have you registersd to vote yet?")
#if-else
print("\n\nif-else䣺\n")
age=17
if age>=18:
print("You are old enough to vote!")
print("Have you registersd to vote yet?") #age>=18ִͨд˿
else:
print("Sorry ,you are too young to vote.")
print("Please register as soon as you turn 18.") #age=17ͨԣִelse
#if-elif-elseṹڼ鳬ΣһͨIJԽµIJԣշѵֳ
print("\n\nif-elif-elseṹ\n")
age=23
if age<4:
print("your admission cost is $0.") #4
elif age<18:
print("your admission cost is $5.") #4<=age<18շ$5
else :
print("your admission cost is $10.") #ڵ18շ$10
#εageֵ
#⣬Դ˼
print("\n\nĺ\n")
age=12
if age<4:
price=0
elif age<18:
price=5
else:
price=10
#print("Your admission cost is "+price+".") ###һдΪpriceֵûstr()ֵַתΪֵַ
print("Your admission cost is "+"$"+str(price)+".")
#ϰʹöelif
print("\n\nelif飺\n")
age=65
if age<4:
price=0
elif age<18:
price=5
elif age>=65:
price=0
else:
price=10
print("Your admission cost is "+"$"+str(price)+".")
#ʡelse
print("\n\nʡelse飺\n")
age=65 #ı˶ֵԤڽ
if age<4:
price=0
elif 4<=age<18:
price=5
elif 18<=age<65:
price=10
elif age>=65:
price=0
print("Your admission cost is "+"$"+str(price)+".")
#ܽif-elif-elseһͨIJԱЧʸߣ˵ִֻһ
#ҪжĻһϵжif
|
#coding:gb2312
#if䴦бϰ
#ϰ1
print("ϰ1")
users=['lyl','cby','ft','fjy','cxk'] #5ûб
for user in users: #ûб
if user=='lyl': #ʹǡlylʱһʺϢ
print("Hello Lyl,would you like to see a status report?")
else: #˵ʱһϢ
print("Hello "+user.title()+",thank you for logging in again.\n\n")
#ϰ2
print("ϰ2")
users=['lyl','cby','ft','fjy','cxk'] #бΪִif
#popped_users=users.pop(0)
#popped_users=users.pop(0)
#popped_users=users.pop(0)
#popped_users=users.pop(0)
#popped_users=users.pop(0) #ȡעͣбΪִelse
if users:
for user in users:
print("Hello "+user.title()+",thank you for logging in again.\n")
else:
print("We need to find some users.")
|
#coding:gb2312
#Ƭϰ1
letters=['c','g','j','f','i']
print("The first three items in the list are :")
print(letters[:3])#ͷʼȡ3ֹ
print("\nThe items from the middle of the list are :")
print(letters[1:4])#1ʼȡ4ֹ
print("\nThe last three items in the list are :")
print(letters[-3:])#-3ʼȡĩβֹ
|
#coding:gb2312
#Ԫѧϰ
#Ԫ鿴бԲŶǷʶʵDzɱб
dimensions=(200,50)
#print(dimensions[0])
#print(dimensions[1]) #ͷбʽһ
#dimensions[0]=250 #˴лʾΪԪIJDZֹģpythonܸԪԪظֵΪѧϰ漸дע͵
#ȻԪԪأԸ洢Ԫıֵ
print("Original Dimensions :")
for dimension in dimensions: #Ԫ
print(dimension)
dimensions=(400,100) #洢Ԫı¸ֵ
print("\nModified Dimensions :")
for dimension in dimensions: #¸ֵ֮Ԫ
print(dimension)
|
#coding:gb2312
#ϰforѭ
numbers=['9','6','2','4']
for number in numbers:#for֮ðţҪ
print(number+", "+"is my favorite number"+"!")
print("This is my lucky number "+number+"!\n")
print("I love these numbers"+" !")#56Ķѭһ֣вִֻһ
#ע⣺for֮ðţΪ˸pythonһѭĵһУ©
#½ԼҪģʱҪؿһԼ
|
#coding:gb2312
#ϰ2ʹreplace()ַеضʶ滻Ϊһ
filename = 'python_note.txt'
with open(filename) as f:
lines = f.readlines()
for line in lines:
line = line.rstrip()
print(line.replace('Python', 'C')) #ղǸеÿһ'Python'滻Ϊ'C'
|
#coding:gb2312
#if䴦б
requested_toppings=['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
if requested_topping=="green peppers":
print("Sorry,we are out of green peppers right now.")
else:
print("Please adding "+requested_topping +"!")
print("\nFinished making pizza.")
#бΪգpizzaʲô
requested_toppings=[ ]
if requested_toppings:
for requested_topping in requested_toppings:
print("Please adding "+requested_topping +"!")
else:
print("Are you sure you want a plain pizza?") #бִelse飬ԪصĻִif
|
def math(A , B):
return A + B, A - B, A * B, A // B
A = int(input("Введите число А: "))
B = int(input("Введите число В: "))
if( B == 0 ):
print(f"({A + B},{A - B},{A * B},Ошибка:деление на ноль)")
else:
math(A, B)
print(math(A, B))
|
"""Generate sales report showing total melons each salesperson sold."""
salespeople = [] #creating empty list to use
melons_sold = [] #creating empty list to use
f = open('sales-report.txt') #opens the report
for line in f:
line = line.rstrip() #strips the white space at end of line
entries = line.split('|') #splits the text at the pipe char
salesperson = entries[0] #name of sales person are index 0
melons = int(entries[2]) #takes the 2nd indx and makes them integers
if salesperson in salespeople: #checking to see if name in new list
position = salespeople.index(salesperson) #if they are in the list, we find the index of where they are in the list
melons_sold[position] += melons #adds melons to their total (running )
else: #if name not in list, add it to the salesperson dictionary
salespeople.append(salesperson) #adds the name
melons_sold.append(melons) # adds the melons
for i in range(len(salespeople)):
print(f'{salespeople[i]} sold {melons_sold[i]} melons')
#prints out the name of sales people and how many melons they sold
#could create a dictionary and add the key being the name and the value being the melons sold # Create a list of data and unpack its values
"""name, total, melons_sold = line.split('|')
sales_people_and_sales={}
# Set or increment the salesperson's total melons sold
if salesperson_name in mels_by_sales:
sales_people_and_sales[name] += int(melons_sold)
else:
sales_people_and_sales[name] = int(melons_sold)"""
|
#Encoding
# -*- coding: utf-8 -*-
#lista=[1,2,3,4,5,6,7]
#print lista[2]
#print lista[2:5]
#print lista[5:]
#print lista[:5]
#print lista[:]
#m=0
#for i in range(len(lista)):
# if m<lista[i]:
# m = lista[i]
# print i,m
#
#lista.append("adsasd")
#lista.insert(1,'asdasdasdasdfgg')
#print lista
#lista.pop()
#lista.pop(4)
#lista.remove(7)
#print lista
#lista= []
print lista
lista= []
for index in range(input('cuantas palabras quieres?:')):
lista.append(raw_input('Palabra #'+str(index+1)+':'))
print '\n'.join(lista)
print "\t\t".join(map(lambda x: "".join(raw_input("Dame uno elemento\t\t")) ,range(input("Dame tamaño de la lista: \t"))))
|
import re
while True:
regex='^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.w\{2,3})+$'
mail=input("enter your mail:")
if(re.search(regex,mail)):
break
else:
print("please enter valid mail id")
continue
while True:
pas=input("enter your password:")
if len(pas)==6 or len(pas)==7 or len(pas)==8:
break
else:
print("not valid")
continue
while True:
phnum=input("enter your phone number:")
if phnum[0]=="9":
break
else:
print("enter valid number")
continue
def deposite():
balance=0
amount=0
amount=float(input("enter amount"))
balance+=amount
print("amount deposited",amount)
def withdrawal():
balance=0
amount=0
amount=float(input("enter amount to be withdrawal"))
if balance>=amount:
balance-=amount
print("you withdrew:",amount)
else:
print("insufficient balance")
def avlbalance():
balance=0
print("your Available balance is:",balance)
print("enter your choice")
i=int(input("1.Deposite/2.Withdraw/3.Available balance"))
if i==1:
deposite()
elif i==2:
withdraw()
elif i==3:
avlbalance()
else:
print("please Enter valid number")
|
#Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada.
n = int(input('Digite um número: '))
d = n*2
t = n*3
r = n ** (1/2)
print('O dobro de {} vale {}.'.format(n, d))
print('O triplo de {} vale {}.'.format(n, t))
print('A raiz quadrada de {} vale {}.'.format(n, r))
|
#!/usr/bin/env/python3
""" Keyword in Context
Author: Jinghua Xu
Description: an interface for visualizing keywords in context using tries
Honor Code: I pledge that this program represents my own work.
"""
from kwic.word_matching_trie import WordMatchingTrie
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="KWIC app")
parser.add_argument("-f", "--file", type=argparse.FileType(mode="r",
encoding="utf-8"), default="kwic/data/2701-0.txt")
parser.add_argument("-w", "--window-size", type=int, default=50)
parser.add_argument("-m", "--max-count", type=int, default=10)
# key word to search
parser.add_argument("-k", "--keyword", type=str, default='')
args = parser.parse_args()
text = ''
# read from file
with args.file as file:
for line in file:
# remove any newlines from the text
text += line.strip('\n')
# trie to store text
trie = WordMatchingTrie(text)
keyword = args.keyword
w_sz = args.window_size
# The program should keep asking for a new keyword until the user terminates the loop by presses enter without inputting any characters.
while True:
values = trie.find(keyword)
len_keyword = len(keyword)
# query the text for the keyword
if values:
# it should print the args.max_count contexts for the word
values = values[:args.max_count]
for idx in values:
# args.w chars(including spaces) to the left of keyword
context_to_left = text[idx-w_sz: idx]
# args.w chars(including spaces) to the right of keyword
context_to_right = text[idx+len_keyword: idx+len_keyword+w_sz]
# left justification of suceeding context(optional line of code, depending on requirement)
# context_to_right = context_to_right.lstrip()
# right justification of preceding context(optional line of code, depending on requirement)
# context_to_left = context_to_left.rstrip()
# In cases where the contexts are smaller than window_sz
if len(context_to_left) < args.window_size:
# right justification of preceding context
num_spaces = args.max_count - len(context_to_left)
print(' '*num_spaces + context_to_left + ' ' *
4 + keyword + ' '*4 + context_to_right)
else:
print(context_to_left + ' '*4 +
keyword + ' '*4 + context_to_right)
else:
print('Keyword not found in text.')
nextcommand = input(
"Enter new keyword(bare word: with no quotes surrounded) to search or press Enter to terminate:")
if nextcommand == '':
break
else:
keyword = nextcommand
|
"""
AngryTurtle
2018. 10. 23
동의대학교 컴퓨터 소프트웨어 공학과
20153308 송민광
이미지 출처
병아리 - https://m.blog.naver.com/lovedesign01/150168487961
토끼 - http://m.inven.co.kr/board/powerbbs.php?come_idx=4538&l=3232417&iskin=overwatch
박스 - https://social.lge.co.kr/product/795_/
"""
import turtle
import random
import math
turtle.title("Angry Turtle")
IMGList = ["box.gif", "bird.gif", "rabbit.gif", "chick1.gif", "chick2.gif", "chick3.gif", "chick4.gif"]
Box = []
Enemy = []
############## 적, 박스 이미지가 없을 때 대체할 함수
############## 주석풀고 아래쪽 함수 두개 주석 후 사용가능
"""
#박스 생성
for x in range(5):
t = turtle.Turtle()
Box.append(t) #리스트에 터틀 객체를 넣어준다
Box[x].shape("square")
Box[x].shapesize(2,2,1)
Box[x].up()
Box[x].hideturtle()
Box[x].setposition(0,-260)
t = None #객체를 삭제한다
#적 생성
for x in range(5):
temp = random.randrange(1,7)
t = turtle.Turtle()
Enemy.append(t)
Enemy[x].shape("circle")
Enemy[x].shapesize(2,2,1)
Enemy[x].up()
Enemy[x].hideturtle()
Enemy[x].setposition(0,-260)
t = None
"""
################################################################
# 박스 생성
for x in range(5):
turtle.register_shape(IMGList[0]) # 터틀모양을 이미지로 대체한다
t = turtle.Turtle()
Box.append(t) # 리스트에 터틀 객체를 넣어준다
Box[x].shape(IMGList[0])
Box[x].up()
Box[x].hideturtle()
Box[x].setposition(0, -260)
t = None # 객체를 삭제한다
# 적 생성
for x in range(5):
temp = random.randrange(1, 7)
turtle.register_shape(IMGList[temp]) # 터틀모양을 이미지로 대체한다
t = turtle.Turtle()
Enemy.append(t)
Enemy[x].shape(IMGList[temp])
Enemy[x].up()
Enemy[x].hideturtle()
Enemy[x].setposition(0, -260)
t = None
# 거북이 속성
class BulletInfo:
def __init__(self, inturtle): # 생성자
self.bullet = inturtle # 터틀객체 삽입
self.bullet.shape("turtle")
self.bullet.color("green")
self.bullet.up()
self.speed = 0 # 속도
self.accel = 1 ###########느릴경우 이거 올리기
self.head = 0 # 방향
self.live = True # 생사여부
self.hit = False # 적중여부
def __del__(self):
self.bullet = None # 객체 삭제
def SetStage(self, Stage, Enemy): # Stage값과 Enemy리스트 가져오기
self.Enemy = Enemy
self.Stage = Stage
def CrushJudgment(self): # 충돌 계산
for x in Enemy:
if (self.bullet.distance(x.position()) < 30): # 적 적중 성공 시(hit True로 바꾸고 True리턴)
x.up()
x.setposition(0, -250)
x.hideturtle()
self.hit = True
self.bullet.hideturtle()
return True
break # 필요한가?
# 상자 충돌 판단(hit는 그대로 놔두고 True리턴)
elif (
self.Stage != 1 and self.bullet.xcor() < -90 and self.bullet.xcor() > -125 and self.bullet.ycor() > -210 and self.bullet.ycor() < (
-210 + ((self.Stage // 2) * 40))):
self.bullet.hideturtle()
return True
break # 필요한가?
else:
pass
return False # 충돌 없을 시 False리턴
# 마우스로 거북이 당겼을 때
def PullBullet(self, x, y):
if (x > -440 and x < -300 and y > -220 and y < -120):
self.bullet.goto(x, y) # 마우스 좌표로 거북이 이동
self.head = math.degrees(math.atan((-(self.bullet.ycor() + 130)) / (-(self.bullet.xcor() + 290)))) # 거북이 방향 계산
self.bullet.setheading(self.head) # 거북이 방향 설정
self.speed = (self.bullet.distance(-290, -130) / 10) # 속도 설정
# 마우스 버튼 뗏을 떄
def ShootBullet(self, x, y):
while (self.bullet.ycor() > -250): # 바닥보다 큰 동안만 반복
if (self.speed > 10): # 속도가 10보다 커지지않도록 제한
self.bullet.speed(10)
else:
self.bullet.speed(int(self.speed))
self.bullet.forward(self.speed * 1 * self.accel) # 앞으로 진행
# 유사 중력
if (self.speed < 5.0): # 속도가 작을 때 더 많이 하강
self.bullet.right(3 * self.accel)
else:
self.bullet.right(1 * self.accel)
# 속도 조절
if (self.bullet.heading() > 270 and self.bullet.heading() < 360): # 떨어질때 가속
self.speed = self.speed + (0.1 * self.accel)
else: # 올라갈때 감속
self.speed = self.speed - (0.1 * self.accel)
if (self.speed < 3.0):
self.speed = 3.0
if self.CrushJudgment(): # 충돌 판정
break
if (self.bullet.ycor() <= -250):
break
if self.hit == False:
self.bullet.color("red") # 바닥에 충돌한 애는 빨강
self.live = False
# 땅 만들기 클래스
class MakeGround:
Creator = turtle.Turtle()
def __init__(self):
# 터틀 속성 설정
self.Creator.shape("turtle")
self.Creator.speed(0)
self.Creator.up()
def __del__(self):
self.Creator = None
# 바닥 그리기
def DrawGround(self):
self.Creator.showturtle() # 갈색배경
self.Creator.setposition(480, -250)
self.Creator.down()
self.Creator.begin_fill()
self.Creator.color("#8E4E32")
self.Creator.setposition(480, -400)
self.Creator.setposition(-480, -400)
self.Creator.setposition(-480, -250)
self.Creator.end_fill()
self.Creator.up() # 초록색 배경
self.Creator.setposition(480, -250)
self.Creator.down()
self.Creator.setposition(-480, -250)
self.Creator.begin_fill()
self.Creator.color("green")
self.Creator.setposition(-480, -280)
while (self.Creator.xcor() <= 480):
angle = random.randrange(0, 90)
if (self.Creator.ycor() > -290):
self.Creator.setheading(300)
self.Creator.forward(random.randrange(1, 10))
self.Creator.setheading(0)
elif (self.Creator.ycor() < -350):
self.Creator.setheading(60)
self.Creator.forward(random.randrange(1, 10))
self.Creator.setheading(0)
else:
self.Creator.setheading(-(angle - 45))
self.Creator.forward(50)
self.Creator.setheading(0)
self.Creator.setheading(90)
self.Creator.setposition(480, -250)
self.Creator.setheading(0)
self.Creator.end_fill()
self.Creator.hideturtle()
self.Creator.up()
# 새총그리기
def DrawShooter(self):
self.Creator.showturtle()
self.Creator.color("#8E6E61")
self.Creator.down()
self.Creator.begin_fill()
self.Creator.setposition(-300, -250)
self.Creator.setposition(-280, -250)
self.Creator.setposition(-280, -200)
self.Creator.setheading(0)
for x in range(0, 90):
self.Creator.left(1)
self.Creator.forward(1)
self.Creator.forward(25)
self.Creator.setheading(180)
self.Creator.forward(20)
self.Creator.left(90)
self.Creator.forward(25)
for x in range(0, 90):
self.Creator.right(1)
self.Creator.forward(0.5)
self.Creator.forward(40)
for x in range(0, 90):
self.Creator.right(1)
self.Creator.forward(0.5)
self.Creator.forward(25)
self.Creator.setheading(180)
self.Creator.forward(20)
self.Creator.left(90)
self.Creator.forward(25)
for x in range(0, 90):
self.Creator.left(1)
self.Creator.forward(1)
self.Creator.setposition(-300, -200)
self.Creator.setposition(-300, -250)
self.Creator.end_fill()
self.Creator.hideturtle()
# 박스 위치 지정
def SetBox(Stage, Box):
for x in range(0, (Stage) // 2):
Box[x].showturtle()
Box[x].up()
Box[x].setposition(-100, -230 + (40 * x))
# 타겟 위치 지정
def SetEnemy(Stage, Enemy):
poslist = []
poslist.append(random.randrange(0, 440))
for x in range(1, ((Stage + 1) // 2)):
while (True):
temp = random.randrange(0, 440)
for y in poslist:
if (y < temp + 40 and y > temp - 40):
temp = -1
break;
if (temp != -1):
poslist.append(temp)
break
ind = 0
for z in poslist:
Enemy[ind].showturtle()
Enemy[ind].up()
Enemy[ind].setposition(poslist[ind], -230)
ind = ind + 1
# 메모리 반환
del poslist
# Stage 출력
def WriteStage(Stage):
turtle.up()
turtle.setposition(0, 260)
turtle.write("Stage:", True, align="Center", font=("Arial", 15, "normal"))
turtle.setposition(50, 260)
turtle.color("white")
turtle.begin_fill()
turtle.circle(10)
turtle.end_fill()
turtle.color("black")
turtle.write(Stage, True, align="Center", font=("Arial", 15, "normal"))
turtle.hideturtle()
def GameInfo():
print("20153308 송민광")
print("주의사항 : 1. 시작 시 초반 이미지 로딩 및 위치 설정때문에 시간이 조금 걸립니다.")
print(" 조금만 기다려 주세요")
print(" 2. 드래그 시 거북이가 가만히 있을때 까지 기다렸다가 마우스를 떼 주세요")
print()
print("게임방법: 1. 시작 할 스테이지를 입력해주세요.")
print(" (1~10까지 입력가능)")
print(" 2. 거북이를 마우스 왼쪽버튼으로 드래그 후 떼면 발사")
print(" 3. 상자를 피해 캐릭터를 모두 맞추면 다음스테이지로 넘어갑니다")
######################main
GameInfo()
Stage = 1
NowB = 0
# 빨리그려지게하기
turtle.delay(0)
# 배경 그리기 호출
backGround = MakeGround()
backGround.DrawGround()
backGround.DrawShooter()
del backGround # 객체삭제 = 메모리 반환
turtle.delay(2)
# 시작할 스테이지 팝업 띄우기(int로 받는다)
Stage = int(turtle.numinput("스테이지 설정", "시작 할 스테이지를 입력하세요(1 ~ 10)", default=1, minval=1, maxval=10))
StartStage = True
hitCount = 0
###############################################게임시작
while (NowB < 10): # 무한루프(NowB가 10까지 안올라가고 올라가서는 안됨)
hitCount = 0
# 초기화
if StartStage:
StartStage = False
WriteStage(Stage) # 스테이지 출력
for e in (Enemy): # 적 위치 초기화
e.setposition(0, -260)
for b in (Box): # 상자위치 초기화
b.setposition(0, -260)
SetBox(Stage, Box) # 스테이지에 맞는 상자위치 설정
SetEnemy(Stage, Enemy) # 스테이지에 맞는 적 위치 설정
Bullet = [] # 리스트 선언
for x in range(0, 5):
t = turtle.Turtle()
Bullet.append(BulletInfo(t)) # 리스트에 객체 삽입
Bullet[x].SetStage(Stage, Enemy) # 객체에 스테이지, 적 리스트 삽입
del t
NowB = 0
for c in Bullet: # 사용할 탄환 탐색
if c.live: # 탄환 살아있으면 탈출
break
else:
NowB = NowB + 1 # 다음번호로
if (NowB == 5 and StartStage == False): # end flag
break
check = 0
for x in range(NowB, 5): # 탄환 위치 설정
if (check == 0):
Bullet[x].bullet.setposition(-290, -130)
check = check + 1
elif (check == 1):
Bullet[x].bullet.setposition(-370, -240)
check = check + 1
elif (check == 2):
Bullet[x].bullet.setposition(-410, -240)
check = check + 1
elif (check == 3):
Bullet[x].bullet.setposition(-370, -220)
check = check + 1
elif (check == 4):
Bullet[x].bullet.setposition(-410, -220)
check = check + 1
else:
pass
NowBullet = Bullet[NowB] # 사용할 터틀 객체 설정
# 마우스 입력
NowBullet.bullet.ondrag(NowBullet.PullBullet)
NowBullet.bullet.onrelease(NowBullet.ShootBullet)
for c in Bullet: # 적중 카운트
if c.hit:
hitCount = hitCount + 1
if hitCount == ((Stage + 1) // 2): # success flag
Stage = Stage + 1
for t in range(5):
Bullet[t].bullet.hideturtle()
Bullet[t] = None
del Bullet
StartStage = True
############################################게임 종료
turtle.up()
turtle.setposition(0, 150)
turtle.color("red")
turtle.write("Fail", True, align="Center", font=("Arial", 30, "normal"))
|
"""
Realizar un programa que ordena nombres alfabeticamente. Primero debe pedir al usuario que ingrese el número de nombres que serán ingresados, luego debe pedir al usuario que ingrese un nombre y repetir ese pedido la cantidad de veces indicada. Los nombres se deben ir agregando a una lista. Por último, ordenar la lista alfabéticamente y mostrar en pantalla de a uno por vez los nombres ordenados (usando un for).
"""
lista = []
numeroNombres = int(input("Ingrese el num de nombres a ingresar:"))
for x in range(0, numeroNombres, 1):
nombre = input("Ingrese un nombre:")
lista.append(nombre)
lista.sort()
for elemento in lista:
print(elemento)
|
"""
Escribir una función que chequee los siguientes usuarios y contraseñas:
Usuario: Juan - Contraseña: 12345_
Usuario: Pablo - Contraseña: xDcFvGbHn
La función debe recibir como parámetros el usuario y la contraseña, y debe devolver el valor True o False.
"""
def chequarLogin(user, password):
if (user == "Juan" and password == "12345_") or (user == "Pablo" and password == "xDcFvGbHn"):
return True
else:
return False
print(chequarLogin("Pablo", "xDcFvGbHn"))
print(chequarLogin("Juan", "12345_"))
print(chequarLogin("Pablo", "12345_"))
|
from static_values import *
# Create a board of size 8x8
BOARD = {}
# "king": 1
# "queen": 2
# "knight": 3
# "bishop": 4
# "rook": 5
# "pawn": 6
TWO_BOARD = [[5, 3, 4, 2, 1, 4, 3, 5],
[6, 6, 6, 6, 6, 6, 6, 6],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[6, 6, 6, 6, 6, 6, 6, 6],
[5, 3, 4, 2, 1, 4, 3, 5]
]
LIST_BOARD = []
def index_2d(myList, v):
for i, x in enumerate(myList):
if v in x:
return (i, x.index(v))
class Player:
def __init__(self, name, position, color, worth, DefendedValue=0, AttackedValue=0):
self.name = name
self.position = position
self.moves = []
self.color = color
self.worth = worth
self.has_moved = False
self.DefendedValue = 0
self.AttackedValue = 0
def __str__(self):
return self.name
def get_Name(self):
print("I am a ", self.name)
return self.name
def get_Position(self):
print("I am at: ", self.position)
return self.position
def moves_Available(self, list_board, board, turn):
print("Im just a nameless player")
class Pawn(Player):
def __str__(self):
return self.name
def moves_Available(self, list_board, board, turn):
self.moves.clear()
i, j = index_2d(list_board, self.position)
if self.color == "Black" and turn == "Black":
if '7' in self.position:
if board[list_board[i+1][j]] == 'E':
self.moves.append(self.position+list_board[i+1][j])
if board[list_board[i+2][j]] == 'E':
self.moves.append(self.position+list_board[i+2][j])
else:
if board[list_board[i+1][j]] == 'E':
self.moves.append(self.position+list_board[i+1][j])
# If not right most
if (j != 7):
# If the diagonal has an ENEMY piece
if board[list_board[i+1][j+1]] != 'E':
if board[list_board[i+1][j+1]].color == "White":
self.moves.append(self.position+list_board[i+1][j+1])
# If not left most
if (j != 0):
# If the diagonal has an ENEMY piece
if board[list_board[i+1][j-1]] != 'E':
if board[list_board[i+1][j-1]].color == "White":
self.moves.append(self.position+list_board[i+1][j-1])
elif self.color == "White" and turn == "White":
if '2' in self.position:
if board[list_board[i-1][j]] == 'E':
self.moves.append(self.position+list_board[i-1][j])
if board[list_board[i-2][j]] == 'E':
self.moves.append(self.position+list_board[i-2][j])
else:
if board[list_board[i-1][j]] == 'E':
self.moves.append(self.position+list_board[i-1][j])
# If not right most
if (j != 7):
# If the diagonal has an ENEMY piece
if board[list_board[i-1][j+1]] != 'E':
if board[list_board[i-1][j+1]].color == "Black":
self.moves.append(self.position+list_board[i-1][j+1])
# If not left most
if (j != 0):
# If the diagonal has an ENEMY piece
if board[list_board[i-1][j-1]] != 'E':
if board[list_board[i-1][j-1]].color == "Black":
self.moves.append(self.position+list_board[i-1][j-1])
class Knight(Player):
def __str__(self):
return self.name
def moves_Available(self, list_board, board, turn):
# if self.color == turn:
self.moves.clear()
i, j = index_2d(list_board, self.position)
X = [2, 1, -1, -2, -2, -1, 1, 2]
Y = [1, 2, 2, 1, -1, -2, -2, -1]
# Check if each possible move
# is valid or not
for a in range(8):
# Position of knight after move
x = i + X[a]
y = j + Y[a]
# count valid moves
if x >= 0 and y >= 0 and x < 8 and y < 8:
if board[list_board[x][y]] != 'E':
# print(board[list_board[x][y]])
if board[list_board[x][y]].color != self.color:
# print(x, y)
self.moves.append(self.position+list_board[x][y])
else:
self.moves.append(self.position+list_board[x][y])
class Bishop(Player):
def __str__(self):
return self.name
def moves_Available(self, list_board, board, turn):
# if self.color == turn:
self.moves.clear()
x, y = index_2d(list_board, self.position)
def Append(dx, dy):
for i in range(1, 8):
newx = x + dx*i
newy = y + dy*i
if 0 <= newx < 8 and 0 <= newy < 8:
if board[list_board[newx][newy]] != 'E':
# print(board[list_board[newx][newy]])
if board[list_board[newx][newy]].color != self.color:
self.moves.append(
self.position+list_board[newx][newy])
break
break
else:
self.moves.append(
self.position+list_board[newx][newy])
else:
break
for dx in (-1, 1):
for dy in (-1, 1):
Append(dx, dy)
class Rook(Player):
# def __init__(self, has_moved=False):
# self.has_moved = has_moved
def __str__(self):
return self.name
def moves_Available(self, list_board, board, turn):
# if self.color == turn:
self.moves.clear()
x, y = index_2d(list_board, self.position)
def Append(dx, dy):
for i in range(1, 8):
newx = x + dx*i
newy = y + dy*i
if 0 <= newx < 8 and 0 <= newy < 8:
if board[list_board[newx][newy]] != 'E':
# print(board[list_board[newx][newy]])
if board[list_board[newx][newy]].color != self.color:
self.moves.append(
self.position+list_board[newx][newy])
break
break
else:
self.moves.append(
self.position+list_board[newx][newy])
else:
break
Append(0, 1)
Append(0, -1)
Append(1, 0)
Append(-1, 0)
class Queen(Player):
def __str__(self):
return self.name
def moves_Available(self, list_board, board, turn):
# if self.color == turn:
self.moves.clear()
x, y = index_2d(list_board, self.position)
def Append(dx, dy):
for i in range(1, 8):
newx = x + dx*i
newy = y + dy*i
if 0 <= newx < 8 and 0 <= newy < 8:
if board[list_board[newx][newy]] != 'E':
# print(board[list_board[newx][newy]])
if board[list_board[newx][newy]].color != self.color:
self.moves.append(
self.position+list_board[newx][newy])
break
break
else:
self.moves.append(
self.position+list_board[newx][newy])
else:
break
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if dx == 0 and dy == 0:
pass
else:
Append(dx, dy)
class King(Player):
# def __init__(self, has_moved=False):
# self.has_moved = has_moved
def __str__(self):
return self.name
def moves_Available(self, list_board, board, turn):
if self.position not in ['e1', 'e8']:
self.has_moved = True
# if self.color == turn:
self.moves.clear()
x, y = index_2d(list_board, self.position)
def Append(dx, dy):
newx = x + dx
newy = y + dy
if 0 <= newx < 8 and 0 <= newy < 8:
if board[list_board[newx][newy]] != 'E':
# print(board[list_board[newx][newy]])
if board[list_board[newx][newy]].color != self.color:
self.moves.append(
self.position+list_board[newx][newy])
else:
self.moves.append(self.position+list_board[newx][newy])
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if dx == 0 and dy == 0:
pass
else:
Append(dx, dy)
if self.has_moved == False:
if self.color == 'White':
rook1 = list_board[7][0]
rook2 = list_board[7][7]
if board[rook1] != 'E':
if board[rook1].name == 'r':
if board[rook1].has_moved == False:
can_castle = True
for i in range(1, 4):
if board[list_board[7][y-i]] != 'E':
can_castle = False
if can_castle:
self.moves.append("e1c1")
if board[rook2] != 'E':
# print("Rook 2 found at ", rook2)
if board[rook2].name == 'r':
# print("r found")
if board[rook2].has_moved == False:
# print("Rook 2 hasnt moved")
can_castle = True
# print("y: ", y, end=" ")
for i in range(1, 3):
# print("Checking: ", list_board[7][y+i])
if board[list_board[7][y+i]] != 'E':
can_castle = False
if can_castle:
self.moves.append("e1g1")
else:
rook1 = list_board[0][0]
rook2 = list_board[0][7]
if board[rook1] != 'E':
if board[rook1].name == 'R':
if board[rook1].has_moved == False:
can_castle = True
for i in range(1, 4):
if board[list_board[0][y-i]] != 'E':
can_castle = False
if can_castle:
self.moves.append("e8c8")
if board[rook2] != 'E':
if board[rook2].name == 'R':
if board[rook2].has_moved == False:
can_castle = True
for i in range(1, 3):
if board[list_board[0][y+i]] != 'E':
can_castle = False
if can_castle:
self.moves.append("e8g8")
class Board:
def __init__(self, player="White", AI="Black"):
self.player = player
self.AI = AI
self.turn = "White"
self.board = {}
self.check = False
self.check_Mate = False
self.create_Board()
self.history = {'R': [], 'r': [], 'N': [], 'n': [], 'B': [], 'b': [
], 'Q': [], 'q': [], 'K': [], 'k': [], 'P': [], 'p': []}
self.over_written = []
self.over_writer = []
self.last_move = []
self.moves_log = []
self.reverse_moves_log = []
self.pawn_worth = 100
self.knight_worth = 320
self.bishop_worth = 330
self.rook_worth = 500
self.queen_worth = 900
self.king_worth = 10000
self.stale_mate = False
self.named_move = []
def legal_moves_of(self, board):
global LIST_BOARD
moves_list = []
for key in board:
if board[key] != 'E' and self.turn != board[key].color:
# print(BOARD[key].position)
board[key].moves_Available(
LIST_BOARD, board, board[key].color)
moves = board[key].moves
if (len(moves) > 0):
moves_list.append(moves)
x = [j for sub in moves_list for j in sub]
return x
def legal_moves(self):
global LIST_BOARD
moves_list = []
for key in self.board:
if self.board[key] != 'E' and self.turn == self.board[key].color:
# print(BOARD[key].position)
self.board[key].moves_Available(
LIST_BOARD, self.board, self.turn)
moves = self.board[key].moves
if (len(moves) > 0):
moves_list.append(moves)
x = [j for sub in moves_list for j in sub]
# if self.check is True:
y = self.is_CheckMate(x)
if len(y) == 0:
self.check_Mate = True
# self.check = False
s = self.is_Stalemate(y)
if s == True:
self.stale_mate = True
print("It's a draw!")
return y
# return x
def create_Board(self):
global BOARD
global TWO_BOARD
global LIST_BOARD
a = ord('a')
n = ord('8')
alph = [chr(i) for i in range(a, a+8)]
numbers = [chr(i) for i in range(n, n-8, -1)]
for i_index, i in enumerate(numbers):
mylist = []
for j_index, j in enumerate(alph):
if (TWO_BOARD[i_index][j_index] == 0):
BOARD[j+i] = "E"
elif (TWO_BOARD[i_index][j_index] == 1):
if (i == '8'):
BOARD[j+i] = King("K", j+i, "Black", 10000)
else:
BOARD[j+i] = King("k", j+i, "White", 10000)
elif (TWO_BOARD[i_index][j_index] == 2):
if (i == '8'):
BOARD[j+i] = Queen("Q", j+i, "Black", 9)
else:
BOARD[j+i] = Queen("q", j+i, "White", 9)
elif (TWO_BOARD[i_index][j_index] == 3):
if (i == '8'):
BOARD[j+i] = Knight("N", j+i, "Black", 3)
else:
BOARD[j+i] = Knight("n", j+i, "White", 3)
elif (TWO_BOARD[i_index][j_index] == 4):
if (i == '8'):
BOARD[j+i] = Bishop("B", j+i, "Black", 3)
else:
BOARD[j+i] = Bishop("b", j+i, "White", 3)
elif (TWO_BOARD[i_index][j_index] == 5):
if (i == '8'):
BOARD[j+i] = Rook("R", j+i, "Black", 5)
else:
BOARD[j+i] = Rook("r", j+i, "White", 5)
elif (TWO_BOARD[i_index][j_index] == 6):
if (i == '7'):
BOARD[j+i] = Pawn("P", j+i, "Black", 1)
else:
BOARD[j+i] = Pawn("p", j+i, "White", 1)
mylist.append(j+i)
LIST_BOARD.append(mylist)
# print_Board()
self.board = BOARD
self.print_ChessBoard()
def print_ChessBoard(self):
print("\n\n~~~~~ {}'s TURN ~~~~~\n".format(self.turn))
print(" ", end=" ")
for i in range(ord('a'), ord('a')+8):
print(chr(i), end=" ")
print("\n")
for i, key in enumerate(self.board):
if (i) % 8 == 0:
print("{} | ".format(key[1]), self.board[key], end=" ")
else:
print(self.board[key], end=" ")
if (i+1) % 8 == 0 and i != 0:
print(" | {}".format(key[1]))
print("\n ", end=" ")
for i in range(ord('a'), ord('a')+8):
print(chr(i), end=" ")
print("\n")
def print_Board(self):
for i, key in enumerate(self.board):
print("['{}': ".format(key), self.board[key], end="] ")
if (i+1) % 8 == 0 and i != 0:
print("")
def promote(self, new_position):
promotion = ''
while True:
if self.board[new_position].name == 'P':
promotion = input(
"Please enter the promotion name for the Pawn: (R, N, Q, B)")
if promotion in ['R', 'N', 'Q', 'B']:
break
else:
promotion = input(
"Please enter the promotion name for the Pawn: (r, n, q, b)")
if promotion in ['r', 'n', 'q', 'b']:
break
if promotion in ['R', 'r']:
self.board[new_position] = Rook(
promotion, new_position, self.turn, 5)
elif promotion in ['N', 'n']:
self.board[new_position] = Knight(
promotion, new_position, self.turn, 3)
elif promotion in ['Q', 'q']:
self.board[new_position] = Queen(
promotion, new_position, self.turn, 9)
elif promotion in ['B', 'b']:
self.board[new_position] = Bishop(
promotion, new_position, self.turn, 3)
def CalculatePieceActionValue(self, pieceType):
if pieceType == 'P' or pieceType == 'p':
return 6
elif pieceType == 'N' or pieceType == 'n':
return 3
elif pieceType == 'B' or pieceType == 'b':
return 3
elif pieceType == 'R' or pieceType == 'r':
return 2
elif pieceType == 'Q' or pieceType == 'q':
return 1
elif pieceType == 'K' or pieceType == 'k':
return 1
def count_attacks(self, moves, board, latest_pos):
count_attacks = 0
attacked = False
for move in moves:
new_position = move[2:]
old_position = move[:2]
if board[new_position] != 'E':
count_attacks += 1
if new_position == latest_pos:
attacked = True
return count_attacks, attacked
def enemy_Attacks(self, board):
enemy_moves = self.legal_moves_of(board)
enemy_attacks = []
count_attacks = 0
for move in enemy_moves:
new_position = move[2:]
old_position = move[:2]
if board[new_position] != 'E':
count_attacks += 1
enemy_attacks.append(move)
return enemy_attacks, count_attacks
def moves_to_be_safe(self):
lmoves = self.legal_moves()
safe_moves = []
count = 0
enemy_attacks, ecount = self.enemy_Attacks(self.board)
for emoves in enemy_attacks:
enew_position = emoves[2:]
eold_position = emoves[:2]
for moves in lmoves:
new_position = moves[2:]
old_position = moves[:2]
if enew_position == old_position:
if self.board[old_position] != 'E':
# print("some piece is under attack")
# print("NAME ",self.board[old_position].name)
self.board[old_position].DefendedValue += self.CalculatePieceActionValue(
self.board[old_position].name)
safe_moves.append(moves)
count += 1
return count, safe_moves
def moves_to_attack(self):
legalmoves = self.legal_moves()
for moves in legalmoves:
new_position = moves[2:]
old_position = moves[:2]
if self.board[new_position] != 'E':
self.board[old_position].AttackedValue += self.CalculatePieceActionValue(
self.board[old_position].name)
def Defending_pieces(self):
board_copy = self.board
legalmoves = self.legal_moves()
enemy_attacks, ecount = self.enemy_Attacks(self.board)
for move in legalmoves:
new_position = move[2:]
old_position = move[:2]
if self.board[old_position].name in ['k', 'K']:
self.board[old_position].has_moved = True
temp_piece = self.board[new_position]
self.board[new_position] = self.board[old_position]
self.board[new_position].position = new_position
self.board[old_position] = 'E'
enemy_attacks2, ecount2 = self.enemy_Attacks(self.board)
if ecount2 < ecount:
if self.board[new_position] != 'E':
self.board[new_position].DefendedValue += self.CalculatePieceActionValue(
self.board[new_position].name)
self.board[old_position] = self.board[new_position]
self.board[old_position].position = old_position
self.board[new_position] = temp_piece
if self.board[old_position].name in ['k', 'K']:
self.board[old_position].has_moved = False
def is_CheckMate(self, moves):
# print(moves)
board_copy = self.board
new_moves_list = []
for move in moves:
new_position = move[2:]
old_position = move[:2]
if self.board[old_position].name in ['k', 'K']:
self.board[old_position].has_moved = True
temp_piece = board_copy[new_position]
board_copy[new_position] = board_copy[old_position]
board_copy[new_position].position = new_position
board_copy[old_position] = 'E'
if self.is_Check_of(board_copy) != True:
new_moves_list.append(move)
board_copy[old_position] = board_copy[new_position]
board_copy[old_position].position = old_position
board_copy[new_position] = temp_piece
if self.board[old_position].name in ['k', 'K']:
self.board[old_position].has_moved = False
return new_moves_list
def is_Check_of(self, board):
moves = self.legal_moves_of(board)
king_position = ''
# Check danger on a white king, given turn for a black piece and vice versa
for key in board:
if board[key] != 'E':
if (board[key].name == 'k' and self.turn == 'White') or (board[key].name == 'K' and self.turn == 'Black'):
king_position = board[key].position
# If any new position in legal moves targetting the King, it's a check
for move in moves:
if king_position == move[2:]:
return True
return False
def is_Check(self):
moves = self.legal_moves()
king_position = ''
# Check danger on a white king, given turn for a black piece and vice versa
for key in self.board:
if self.board[key] != 'E':
if (self.board[key].name == 'k' and self.turn == 'Black') or (self.board[key].name == 'K' and self.turn == 'White'):
king_position = self.board[key].position
# If any new position in legal moves targetting the King, it's a check
for move in moves:
if king_position == move[2:]:
self.check = True
def is_Stalemate(self, moves):
if self.is_Check_of(self.board) == False:
if(len(moves) == 0):
return True
return False
def move_From(self, new_move):
# SET THE NEW POSITION OF THIS PIECE TO LATTER HALF OF THE new_move
new_position = new_move[2:]
old_position = new_move[:2]
castle_bool = False
if new_move in ['e1g1', 'e8g8', 'e1c1', 'e8c8']:
if self.board[old_position].name in ['k', 'K']:
self.board[old_position].has_moved = True
self.castle(new_move)
castle_bool = True
if castle_bool == False:
if (self.board[new_position] != 'E' and self.board[new_position].name in ['k', 'K']):
print("AAAAAAA YOU ARE WRONG")
self.check_Mate = True
return
self.board[new_position] = self.board[old_position]
self.board[new_position].position = new_position
if '1' in new_position and self.board[new_position].name == 'P':
self.promote(new_position)
elif '8' in new_position and self.board[new_position].name == 'p':
self.promote(new_position)
# SET THE OLD POSITION OF THIS PIECE TO EMPTY
self.board[old_position] = 'E'
# self.is_Check()
# FLIP TURN
if self.turn == "White":
self.turn = "Black"
else:
self.turn = "White"
name = self.board[new_position].name
self.history[name].append(name + '-' + new_move)
self.named_move.append(name+'-'+new_move)
def material_Worth(self):
bp = wp = bb = wb = bn = wn = bq = wq = br = wr = bk = wk = 0
for key in self.board:
if self.board[key] != 'E':
if self.board[key].name == 'p':
wp += 1
elif self.board[key].name == 'P':
bp += 1
elif self.board[key].name == 'b':
wb += 1
elif self.board[key].name == 'B':
bb += 1
elif self.board[key].name == 'n':
wn += 1
elif self.board[key].name == 'N':
bn += 1
elif self.board[key].name == 'q':
wq += 1
elif self.board[key].name == 'Q':
bq += 1
elif self.board[key].name == 'r':
wr += 1
elif self.board[key].name == 'R':
br += 1
elif self.board[key].name == 'k':
wp += 1
elif self.board[key].name == 'K':
bp += 1
material_worth = self.pawn_worth * (wp-bp)
material_worth += self.knight_worth * (wn-bn)
material_worth += self.bishop_worth * (wb-bb)
material_worth += self.rook_worth * (wr-br)
material_worth += self.queen_worth * (wq-bq)
material_worth += self.king_worth * (wk-bk)
return material_worth
def individual_Worth(self):
worth = 0
for key in self.board:
if self.board[key] != 'E':
if self.board[key].color == 'White':
x, y = index_2d(LIST_BOARD, key)
if self.board[key].name.lower() == 'p':
worth += PAWN[x][y]
elif self.board[key].name.lower() == 'n':
worth += KNIGHT[x][y]
elif self.board[key].name.lower() == 'b':
worth += BISHOP[x][y]
elif self.board[key].name.lower() == 'r':
worth += ROOK[x][y]
elif self.board[key].name.lower() == 'q':
worth += QUEEN[x][y]
elif self.board[key].name.lower() == 'k':
worth += KING[x][y]
else:
x, y = index_2d(LIST_BOARD, key)
if self.board[key].name.lower() == 'p':
worth += (- PAWN[7-x][y])
elif self.board[key].name.lower() == 'n':
worth += (- KNIGHT[7-x][y])
elif self.board[key].name.lower() == 'b':
worth += (- BISHOP[7-x][y])
elif self.board[key].name.lower() == 'r':
worth += (- ROOK[7-x][y])
elif self.board[key].name.lower() == 'q':
worth += (- QUEEN[7-x][y])
elif self.board[key].name.lower() == 'k':
worth += (- KING[7-x][y])
return worth
# Greater the worth of the board, less likely to be selected in minmax
# So choose minimum worth
def calculate_Board_Worth(self):
worth = 0
# for key in self.board:
# if self.board[key] != 'E' and self.board[key].color != self.turn:
# worth -= self.board[key].worth
material_worth = self.material_Worth()
scoredefend = 0
scoreattack = 0
# for key in self.board:
# if self.board[key] != 'E' and self.board[key].color == self.turn:
# if self.board[key].color == 'White':
# x, y = index_2d(LIST_BOARD, key)
# if self.board[key].name.lower() == 'p':
# worth += self.board[key].worth * PAWN[x][y]
# elif self.board[key].name.lower() == 'n':
# worth += self.board[key].worth * KNIGHT[x][y]
# elif self.board[key].name.lower() == 'b':
# worth += self.board[key].worth * BISHOP[x][y]
# elif self.board[key].name.lower() == 'r':
# worth += self.board[key].worth * ROOK[x][y]
# elif self.board[key].name.lower() == 'q':
# worth += self.board[key].worth * QUEEN[x][y]
# elif self.board[key].name.lower() == 'k':
# worth += self.board[key].worth * KING[x][y]
# else:
# x, y = index_2d(LIST_BOARD, key)
# if self.board[key].name.lower() == 'p':
# worth += self.board[key].worth * (- PAWN[7-x][y])
# elif self.board[key].name.lower() == 'n':
# worth += self.board[key].worth * (- KNIGHT[7-x][y])
# elif self.board[key].name.lower() == 'b':
# worth += self.board[key].worth * (- BISHOP[7-x][y])
# elif self.board[key].name.lower() == 'r':
# worth += self.board[key].worth * (- ROOK[7-x][y])
# elif self.board[key].name.lower() == 'q':
# worth += self.board[key].worth * (- QUEEN[7-x][y])
# elif self.board[key].name.lower() == 'k':
# worth += self.board[key].worth * (- KING[7-x][y])
indv_worth = self.individual_Worth()
worth += indv_worth
worth += material_worth
repititions = len(self.moves_log) - len(set(self.moves_log))
for move1 in (self.moves_log):
for move2 in (self.reverse_moves_log):
if move1 == move2:
repititions += 1
safe_moves = []
# self.moves_to_attack()
# count, safe_moves = self.moves_to_be_safe()
# self.Defending_pieces()
# for key in self.board:
# if self.board[key] != 'E':
# scoredefend += self.board[key].DefendedValue
# scoreattack += self.board[key].AttackedValue
worth -= repititions * 4
#worth += scoredefend
#worth += scoreattack
if self.turn == "Black":
worth *= -1
return worth
def is_capture(self, new_move):
new_position = new_move[2:]
if self.board[new_position] != 'E':
return True
return False
def castle(self, new_move):
xK, yK = index_2d(LIST_BOARD, new_move[:2])
if new_move in ['e1g1', 'e8g8']:
old_position = new_move[:2]
new_position = new_move[2:]
self.board[new_position] = self.board[old_position]
self.board[new_position].position = new_position
self.board[old_position] = 'E'
# King moved
name = self.board[new_position].name
self.history[name].append(name + '-' + new_move)
rook_position = 'h' + old_position[1]
rook_newposition = LIST_BOARD[xK][yK+1]
self.board[rook_newposition] = self.board[rook_position]
self.board[rook_newposition].position = rook_newposition
self.board[rook_position] = 'E'
# Rook moved
name = self.board[rook_newposition].name
self.history[name].append(
name + '-' + rook_position+rook_newposition)
if self.turn == "White":
self.turn = "Black"
else:
self.turn = "White"
elif new_move in ['e1c1', 'e8c8']:
old_position = new_move[:2]
new_position = new_move[2:]
self.board[new_position] = self.board[old_position]
self.board[new_position].position = new_position
self.board[old_position] = 'E'
# King moved
name = self.board[new_position].name
self.history[name].append(name + '-' + new_move)
rook_position = 'h' + old_position[1]
rook_newposition = LIST_BOARD[xK][yK-1]
self.board[rook_newposition] = self.board[rook_position]
self.board[rook_newposition].position = rook_newposition
self.board[rook_position] = 'E'
# Rook moved
name = self.board[rook_newposition].name
self.history[name].append(
name + '-' + rook_position+rook_newposition)
if self.turn == "White":
self.turn = "Black"
else:
self.turn = "White"
def push(self, new_move):
# print("Pushing ", new_move)
new_position = new_move[2:]
old_position = new_move[:2]
if self.board[old_position].name in ['k', 'K']:
self.board[old_position].has_moved = True
# Save the overwritten and overwrite pieces for pop
self.over_written.append(self.board[new_position])
self.over_writer.append(self.board[old_position])
self.last_move.append(new_move)
self.board[new_position] = self.board[old_position]
self.board[new_position].position = new_position
if '1' in new_position and self.board[new_position].name == 'P':
self.board[new_position] = Queen(
'Q', new_position, self.turn, 9)
elif '8' in new_position and self.board[new_position].name == 'p':
self.board[new_position] = Queen(
'q', new_position, self.turn, 9)
# SET THE OLD POSITION OF THIS PIECE TO EMPTY
self.board[old_position] = 'E'
if self.turn == "White":
self.turn = "Black"
else:
self.turn = "White"
name = self.board[new_position].name
# self.history[name].append(name + '-' + new_move)
self.moves_log.append(new_move)
self.reverse_moves_log.append(new_move[2:] + new_move[:2])
def pop(self):
# print("Popping ", self.last_move[-1])
# print(self.board[self.last_move[-1][:2]])
# print(self.board[self.last_move[-1][2:]].position)
self.board[self.last_move[-1][:2]] = self.over_writer[-1]
self.board[self.last_move[-1][2:]] = self.over_written[-1]
self.board[self.last_move[-1][:2]].position = self.last_move[-1][:2]
if self.board[self.last_move[-1][2:]] != 'E':
self.board[self.last_move[-1][2:]
].position = self.last_move[-1][2:]
if self.board[self.last_move[-1][:2]].name in ['k', 'K']:
self.board[self.last_move[-1][:2]].has_moved = False
# print(self.board[self.last_move[-1][:2]].position)
# print(self.board[self.last_move[-1][2:]])
self.over_writer.pop()
self.over_written.pop()
self.last_move.pop()
self.check_Mate = False
self.check_Mate = False
self.moves_log.pop()
if self.turn == "White":
self.turn = "Black"
else:
self.turn = "White"
|
class Student:
def __init__(self,firstName,lastName,phone):
self.firstName=firstName
self.lastName=lastName
self.phone=phone
def display(self):
print ("First Name:",self.firstName)
print ("Last Name:",self.lastName)
print ("Phone:",self.phone)
class Grade(Student):
def __init__(self, firstName, lastName, phone, score):
self.firstName = firstName
self.lastName = lastName
self.phone = phone
self.score = score
def calculate(self):
if(90 <= self.score <= 100):
return 'O'
if(75 <= self.score < 90):
return 'E'
if(60 <= self.score < 75):
return 'A'
if(40 <= self.score < 60):
return 'B'
if(self.score < 40):
return 'D'
firstName=input().strip()
lastName=input().strip()
phone=int(input())
score=int(input())
stu=Grade(firstName,lastName,phone,score)
stu.display()
print ("Grade:",stu.calculate())
|
import sys
val1= 'hi'
if (len(sys.argv)>1):
val1=str(sys.argv[1])
def parityOf(int_type):
parity = 0
while (int_type):
parity = ~parity
int_type = int_type & (int_type-1)
if (parity==-1):
return(0)
return(1)
def calcLRC(input):
lrc = ord(input[0])
for i in range(1,len(input)):
lrc ^= ord(input[i])
return lrc
def showLRC(input,res):
input = input[:7]
print 'Char\tHex\tBinary'
print '------------------------------------'
for i in range(0,len(input)):
print input[i],"\t",hex(ord(input[i])),"\t",bin(ord(input[i]))
print '\nBit\tBinary LRC'
print '----------------------------'
print ' \t',
for i in range(0,len(input)):
print input[i],
print ""
mask=1
for bitpos in range(0,7):
bit = (res & mask) >> bitpos
print "b",bitpos,"\t",
for i in range(0,len(input)):
bitchar = (ord(input[i]) & mask) >> bitpos
print bitchar,
print bit
mask = mask << 1
# Show VRC
print "VRC\t",
for i in range(0,len(input)):
print parityOf(ord(input[i])),
print parityOf(res),
return
res = calcLRC(val1)
print ""
print "Input: ",val1," LRC is ",hex(res),"- Char: ",chr(res)
print ""
showLRC(val1,res)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.