text stringlengths 37 1.41M |
|---|
import math
import random
import pygame
class Vector(object):
""" The basic 2d vector object for directions and things
"""
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def getMag(self): #Returns the magnitude of the vector
return math.sqrt(self.x**2 + self.y**2)
def norm(self): #Return the unit vector of the vector
return Vector(self.x/self.getMag(), self.y/self.getMag()) if self.getMag()>0 else Vector(0, 0)
def add(self, other):
self.x = self.x + other.x
self.y = self.y + other.y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def sub(self, other):
self.x = self.x - other.x
self.y = self.y - other.y
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def mul(self, other):
self.x = self.x * other
self.y = self.y * other
def __mul__(self, other): #Multiply Vector by scalar
return Vector(self.x * other, self.y * other)
def __str__(self):
return "vec("+str(self.x)+", "+str(self.y)+")"
class Ball(object):
""" The basic ball object that the player interacts with
"""
def __init__(self, pos = Vector(), vel = Vector(), radius = 2, color = (0, 50, 0), held = False, friction = .8):
self.pos = pos
self.vel = vel
self.radius = radius
self.color = color
self.held = held
self.friction = friction
def move(self, displayObject):
self.vel.mul(self.friction)
width = displayObject.width
height = displayObject.height
if self.vel.getMag() < 1:
self.vel = Vector(0, 0)
self.friction = .8 #Return to normal friction
if self.pos.x < 0:
self.vel.x = abs(self.vel.x) #Equivalent to inverting the component but a little more robust
self.pos.x = 0 #Move thing back to border (sometimes it goes so fast that it ends up at like -100)
if self.pos.x > width:
self.vel.x = -abs(self.vel.x)
self.pos.x = width
if self.pos.y < 0:
self.vel.y = abs(self.vel.y)
self.pos.y = 0
if self.pos.y > height:
self.vel.y = -abs(self.vel.y)
self.pos.y = height
self.pos.add(self.vel)
def draw(self, screen):
if not self.held:
self.color = (255 * self.vel.getMag()/100.0, 30 + 225 * self.vel.getMag()/100.0, 0)
pygame.draw.circle(screen, self.color, (int(self.pos.x), int(self.pos.y)), self.radius)
def fire(self, dir = Vector()):
self.friction = .95 #Reduced friction for balls you shoot out
self.vel = dir * random.randint(60, 100)
def __str__(self):
return "Ball at pos: " + str(self.pos) + ", with velocity: " + str(self.vel)
class Player(object):
""" The player object for keeping track of the player
"""
def __init__(self, pos = Vector(), radius = 5, color = (150, 150, 255), suck_radius = 30, pickup_dist = 5, sucking = False, speed = 5, killDist = 10):
self.pos = pos
self.radius = radius
self.color = color
self.suck_radius = suck_radius
self.pickup_dist = pickup_dist
self.sucking = sucking
self.speed = speed
self.killDist = killDist
def draw(self, screen):
pygame.draw.circle(screen, self.color, (int(self.pos.x), int(self.pos.y)), self.radius)
class Enemy(object):
""" Basic NPC Class
"""
def __init__(self, pos = Vector(), radius = 5, color = (255, 0, 0), speed = 7):
self.pos = pos
self.radius = radius
self.color = color
self.speed = speed
def move(self, direction):
self.pos.add(direction * self.speed)
def draw(self, screen):
pygame.draw.circle(screen, self.color, (int(self.pos.x), int(self.pos.y)), self.radius)
def kill(self):
newBalls = []
num_balls = 20
for i in range(num_balls):
angle = ((i*360/num_balls) * math.pi) / 180.0
newBall = Ball(pos = self.pos * 1.0, vel = Vector(math.cos(angle), math.sin(angle)) * 10, friction = .98)
newBalls.append(newBall)
return newBalls
def __str__(self):
return "Enemy at: " + str(self.pos)
class DisplayObject(object):
""" For keeping track of stats about the screen
"""
def __init__(self, width = 0, height = 0):
self.width = width
self.height = height
|
def hard_easy(a, b):
result = 0
for _ in range(abs(a)):
result += abs(b)
if (a < 0 and b > 0) or (a > 0 and b < 0):
result = -result
elif a == 0 or b == 0:
result = 0
print("Only '+' and '-' operations:", result)
print(" Expected:", a * b)
hard_easy(2, 3)
hard_easy(-2, 3)
hard_easy(-2, -3)
hard_easy(-34553, -343535353)
hard_easy(-0, -343535353)
hard_easy(10, 0)
|
#Devuelve la lista sin elementos repetidos
def categorias_repuestos(cat):
salida = []
for n in cat:
if(not n in salida):
salida.append(n)
return salida
#Devuelve el indice en el cual un elemeno se ecuentra con respecto a una lista en unos indices ya dados
def faltan_por_categoria(codigos, categorias, categoria):
salida = []
for i in codigos:
for n in range(len(categorias)):
if(categorias[n] == categoria):
if(n == i):
salida.append(n)
return salida
#Retorna los elemntos de una lista que no estan en otra en una nueva lista
def repuesto_no_existe(codigos1, codigos2):
salida = []
for n in codigos1:
if(not n in codigos2):
salida.append(n)
return salida
#
def cambiar_repuestos(codigo1, codigo2):
capacidad = 0
if(len(codigo1) <= len(codigo2)):
for n in codigo1:
if(not n in codigo2):
capacidad += 1
else:
for i in codigo2:
if(not i in codigo1):
capacidad += 1
return capacidad
print(faltan_por_categoria([7, 43, 38, 45, 20, 33, 30, 16, 28, 14, 19, 4, 15, 6, 37, 12, 9, 2, 49],
[5, 6, 4, 9, 6, 9, 9, 1, 1, 6, 6, 7, 2, 2, 3, 3, 3, 6, 9, 3, 2, 4, 7, 6, 7, 3, 9, 6, 7, 1, 8, 3, 8, 8, 2, 4, 4, 7, 8, 8, 5, 4, 8, 6, 8, 3, 2, 1, 2, 9],
3))
print(faltan_por_categoria([1,3,6,8], ['motor','lubricantes','suspencion','suspencion','suspencion','motor','lubricantes','suspencion','suspencion','suspencion'],'suspencion'))
|
from BankingApp import MinimumBalanceAccount
from BankingApp import Accounts
from BankingApp import WithdrawAmount
from BankingApp import DepositAmount
from BankingApp import FundTransfer
accounts = Accounts()
minimum_balance = 500
fundTransfer = FundTransfer()
global account
def accountCreation():
global account
account = MinimumBalanceAccount(minimum_balance)
accounts.add_account(account)
def withDrawAmount():
amount = input("Enter the amount to be withdrawn")
WithdrawAmount.withdraw(account, amount, minimum_balance, fundTransfer)
def depositAmount():
balance = input("Enter the amount to be deposited")
DepositAmount.deposit(account, balance, fundTransfer)
def transactionHistory():
fundTransfer.getFullHistory()
def exitProgram():
exit()
options = {
1: accountCreation,
2: withDrawAmount,
3: depositAmount,
4: transactionHistory,
5: exitProgram
}
class Interface:
while True:
print("1. Create an account")
print("2. Withdraw Amount")
print("3. Deposit Amount")
print("4. View Transaction History")
print("5. Exit")
choice = int(input())
options[choice]()
print("account_balance -----")
print(account.balance)
print("minimum_balance -----")
print(account.minimum_balance)
|
"""
If 0 ≤ C[a] < 1, then (a, b) is multiplicative only if C[a] = 0
If 1 < C[a] < 2, then C[a] / (C[a] - 1) > 2, therefore C[b] > 2. So, C[b] > C[a], but this is impossible because C[a] ≥ C[b] (because the array is sorted).
If C[a] > 2 then the pair is multiplicative for any C[b] where C[b] ≥ C[a] / (C[a] - 1)
"""
def solution(A, B):
c = list()
for x in range(len(A)):
c.append(A[x] + B[x])
c.sort()
result = 0
length = len(c)
if length > 1:
l_index = 0
r_index = length - 1
while r_index > l_index:
value = float(c[r_index]/(c[r_index]-1))
while l_index < r_index and c[l_index] < value:
l_index += 1
if l_index == r_index:
break
result += (r_index - l_index)
r_index -= 1
if result > pow(10, 9):
result = pow(10, 9)
return result
n = int(input("Enter the number of elements"))
print("Enter the elements of the first Array")
count = 0
A = list()
B = list()
while count < n:
number = input()
A.append(int(number))
count += 1
count = 0
print("Enter the elements of the second Array")
while count < n:
number = int(input())
B.append(float(number/pow(10, 6)))
count += 1
print(solution(A, B))
|
surveyList = []
surveyInt = []
# Displays menu to user to select option
def menu():
print("0 - Quit")
print("1 - Display the menu")
print("2 - Display all the survey information")
print("3 - Given a department display the number of customers that answered the survey and the average result")
print("4 - Display the department(s) with the highest customer satisfaction")
print("5 - Display the department(s) with the lowest customer satisfaction")
print("6 - Display the departments where 50% or more of the customers voted fair or poor.")
print("7 - Display the departments where 60% or more of the customers voted good.")
print("8 - Work out and display the number of people that have used the customer satisfaction devices and the average value.")
thirdNum = int(input("Please select an option: "))
if thirdNum == 0: # Ends survey by exiting loop
print("Goodbye.")
elif thirdNum == 1:
menu()
elif thirdNum == 2:
displayData()
menu()
elif thirdNum == 3:
calculateTotalByDepartment()
calculateAverageByDepartment()
menu()
elif thirdNum == 4:
displayHighest()
menu()
elif thirdNum == 5:
displayLowest()
menu()
elif thirdNum == 6:
displayPoorPerformance()
menu()
elif thirdNum == 7:
displayExcellentPerformance()
menu()
elif thirdNum == 8:
calculateTotal()
calculateAverage()
menu()
else:
print("Option does not exist, please try again.") # Message notifying user of incorrect option entered
menu()
# Reads data from the text file and stores into list
def readData():
del surveyList[:]
surveyFile = open("survey.txt","r")
for line in surveyFile:
line = line.rstrip("\n")
line = line.split()
surveyList.append(line)
for num in surveyList:
surveyInt.append(int(num[1]))
surveyInt.append(int(num[2]))
surveyInt.append(int(num[3]))
surveyFile.close()
print("Data has been read from text file.")
return surveyList
return surveyInt
# Displays the data stored in the list
def displayData():
if surveyList == []:
print("Empty list, please read data.")
else:
print(surveyList)
# Sums up the number of people who took the survey
def calculateTotal():
print("Total number of people who took the survey:", (sum(surveyInt)))
# This function returns the average value of the survey
def calculateAverage():
i = 0
g = 1
f = 2
b = 3
whole = 0
for i in range (len(surveyList)):
good = round(int(surveyList[i][g])) * 3
fair = round(int(surveyList[i][f])) * 2
poor = round(int(surveyList[i][b])) * 1
whole += good + fair + poor
toTal = (sum(surveyInt))
averAge = whole / toTal
print("Average value of the survey rounded is:", round(averAge))
# Sums up the number of people who took the survey per department
def calculateTotalByDepartment():
print("Please select department for total number of votes")
print("0 - Ladies")
print("1 - Gentlemen")
print("2 - Toys")
print("3 - Beauty")
print("4 - Technology")
print("5 - Home")
print("6 - Appliances")
print("7 - Food")
print("8 - Shoes")
print("9 - Children")
thirdNum = int(input("Please select an option: "))
if thirdNum == 0:
print("Number of people who took the survey:", (int(surveyList[0][1]) + int(surveyList[0][2]) + int(surveyList[0][3])))
elif thirdNum == 1:
print("Number of people who took the survey:", (int(surveyList[1][1]) + int(surveyList[1][2]) + int(surveyList[1][3])))
elif thirdNum == 2:
print("Number of people who took the survey:", (int(surveyList[2][1]) + int(surveyList[2][2]) + int(surveyList[2][3])))
elif thirdNum == 3:
print("Number of people who took the survey:", (int(surveyList[3][1]) + int(surveyList[3][2]) + int(surveyList[3][3])))
elif thirdNum == 4:
print("Number of people who took the survey:", (int(surveyList[4][1]) + int(surveyList[4][2]) + int(surveyList[4][3])))
elif thirdNum == 5:
print("Number of people who took the survey:", (int(surveyList[5][1]) + int(surveyList[5][2]) + int(surveyList[5][3])))
elif thirdNum == 6:
print("Number of people who took the survey:", (int(surveyList[6][1]) + int(surveyList[6][2]) + int(surveyList[6][3])))
elif thirdNum == 7:
print("Number of people who took the survey:", (int(surveyList[7][1]) + int(surveyList[7][2]) + int(surveyList[7][3])))
elif thirdNum == 8:
print("Number of people who took the survey:", (int(surveyList[8][1]) + int(surveyList[8][2]) + int(surveyList[8][3])))
elif thirdNum == 9:
print("Number of people who took the survey:", (int(surveyList[9][1]) + int(surveyList[9][2]) + int(surveyList[9][3])))
else:
print("Department does not exist, please try again.")
calculateTotalByDepartment()
# Returns the average value per department
def calculateAverageByDepartment():
print("Please select department for average value")
print("0 - Ladies")
print("1 - Gentlemen")
print("2 - Toys")
print("3 - Beauty")
print("4 - Technology")
print("5 - Home")
print("6 - Appliances")
print("7 - Food")
print("8 - Shoes")
print("9 - Children")
thirdNum = int(input("Please select an option: "))
if thirdNum == 0:
whole = 0
good = round(int(surveyList[0][1])) * 3
fair = round(int(surveyList[0][2])) * 2
poor = round(int(surveyList[0][3])) * 1
whole += good + fair + poor
add = (int(surveyList[0][1]) + int(surveyList[0][2]) + int(surveyList[0][3]))
averAge = whole / add
print("Average value to the nearest whole number:", (round(averAge)))
elif thirdNum == 1:
whole = 0
good = round(int(surveyList[1][1])) * 3
fair = round(int(surveyList[1][2])) * 2
poor = round(int(surveyList[1][3])) * 1
whole += good + fair + poor
add = (int(surveyList[1][1]) + int(surveyList[1][2]) + int(surveyList[1][3]))
averAge = whole / add
print("Average value to the nearest whole number:", (round(averAge)))
elif thirdNum == 2:
whole = 0
good = round(int(surveyList[2][1])) * 3
fair = round(int(surveyList[2][2])) * 2
poor = round(int(surveyList[2][3])) * 1
whole += good + fair + poor
add = (int(surveyList[2][1]) + int(surveyList[2][2]) + int(surveyList[2][3]))
averAge = whole / add
print("Average value to the nearest whole number:", (round(averAge)))
elif thirdNum == 3:
whole = 0
good = round(int(surveyList[3][1])) * 3
fair = round(int(surveyList[3][2])) * 2
poor = round(int(surveyList[3][3])) * 1
whole += good + fair + poor
add = (int(surveyList[3][1]) + int(surveyList[3][2]) + int(surveyList[3][3]))
averAge = whole / add
print("Average value to the nearest whole number:", (round(averAge)))
elif thirdNum == 4:
whole = 0
good = round(int(surveyList[4][1])) * 3
fair = round(int(surveyList[4][2])) * 2
poor = round(int(surveyList[4][3])) * 1
whole += good + fair + poor
add = (int(surveyList[4][1]) + int(surveyList[4][2]) + int(surveyList[4][3]))
averAge = whole / add
print("Average value to the nearest whole number:", (round(averAge)))
elif thirdNum == 5:
whole = 0
good = round(int(surveyList[5][1])) * 3
fair = round(int(surveyList[5][2])) * 2
poor = round(int(surveyList[5][3])) * 1
whole += good + fair + poor
add = (int(surveyList[5][1]) + int(surveyList[5][2]) + int(surveyList[5][3]))
averAge = whole / add
print("Average value to the nearest whole number:", (round(averAge)))
elif thirdNum == 6:
whole = 0
good = round(int(surveyList[6][1])) * 3
fair = round(int(surveyList[6][2])) * 2
poor = round(int(surveyList[6][3])) * 1
whole += good + fair + poor
add = (int(surveyList[6][1]) + int(surveyList[6][2]) + int(surveyList[6][3]))
averAge = whole / add
print("Average value to the nearest whole number:", (round(averAge)))
elif thirdNum == 7:
whole = 0
good = round(int(surveyList[7][1])) * 3
fair = round(int(surveyList[7][2])) * 2
poor = round(int(surveyList[7][3])) * 1
whole += good + fair + poor
add = (int(surveyList[7][1]) + int(surveyList[7][2]) + int(surveyList[7][3]))
averAge = whole / add
print("Average value to the nearest whole number:", (round(averAge)))
elif thirdNum == 8:
whole = 0
good = round(int(surveyList[8][1])) * 3
fair = round(int(surveyList[8][2])) * 2
poor = round(int(surveyList[8][3])) * 1
whole += good + fair + poor
add = (int(surveyList[8][1]) + int(surveyList[8][2]) + int(surveyList[8][3]))
print("Average value to the nearest whole number:", (round(avy)))
elif thirdNum == 9:
whole = 0
good = round(int(surveyList[9][1])) * 3
fair = round(int(surveyList[9][2])) * 2
poor = round(int(surveyList[9][3])) * 1
whole += good + fair + poor
add = (int(surveyList[9][1]) + int(surveyList[9][2]) + int(surveyList[9][3]))
averAge = whole / add
print("Average value to the nearest whole number:", (round(averAge)))
else:
print("Department does not exist, please try again.")
calculateAverageByDepartment()
# Displays department(s) with highest customer satisfaction
def displayHighest():
i = 0
b = 1
n = 2
g = 3
for i in range (len(surveyList)):
whole = int(surveyList[i][b]) + int(surveyList[i][2]) + int(surveyList[i][3])
good = round(int(surveyList[i][b]) / whole * 100)
fair = round(int(surveyList[i][n]) / whole * 100)
poor = round(int(surveyList[i][g]) / whole * 100)
poorAndFair = poor + fair
if good > poorAndFair:
print(surveyList[i][0], "has a high customer satisfaction rating:", str(good) + "%", "voted good,", str(fair) + "%", "voted fair and", str(poor) + "%", "voted poor.")
# Displays department(s) with lowest customer satisfaction
def displayLowest():
i = 0
b = 1
n = 2
g = 3
for i in range (len(surveyList)):
whole = int(surveyList[i][b]) + int(surveyList[i][2]) + int(surveyList[i][3])
good = round(int(surveyList[i][b]) / whole * 100)
fair = round(int(surveyList[i][n]) / whole * 100)
poor = round(int(surveyList[i][g]) / whole * 100)
if good < fair or good < poor:
print(surveyList[i][0], "has a low customer satisfaction rating:", str(good) + "%", "voted good,", str(fair) + "%", "voted fair and", str(poor) + "%", "voted poor.")
# Displays departments with low survey rates of 50% or more of the customers that voted fair or poor
def displayPoorPerformance():
i = 0
b = 1
n = 2
g = 3
for i in range (len(surveyList)):
whole = int(surveyList[i][b]) + int(surveyList[i][2]) + int(surveyList[i][3])
good = round(int(surveyList[i][b]) / whole * 100)
fair = round(int(surveyList[i][n]) / whole * 100)
poorAndfair = round(int(surveyList[i][g]) / whole * 100 + fair)
if poorAndfair >= 50:
print(surveyList[i][0], "department voted low,", str(poorAndfair) + "%", "having voted poor or fair.")
# Displays departments with excellent survey rates of 60% or more of the customers voted good.
def displayExcellentPerformance():
i = 0
b = 1
n = 2
g = 3
for i in range (len(surveyList)):
whole = int(surveyList[i][b]) + int(surveyList[i][2]) + int(surveyList[i][3])
good = round(int(surveyList[i][b]) / whole * 100)
if good >= 60:
print(surveyList[i][0], "has a high survey rate", str(good) + "%", "good")
else:
print("No department displayed an excellent survey rate of 60% or more of the customers voting good.")
break
readData()
menu()
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 09:12:00 2014
@author: koenigin
"""
def grid_part():
"""Draws the top of a 2 x 2 grid"""
line = '+ - - - - + - - - - +'
column = '| | |'
print(line)
print(column)
print(column)
print(column)
print(column)
def small_grid():
"""puts the peices of a 2x2 grid together"""
line = '+ - - - - + - - - - +'
grid_part()
grid_part()
print(line)
def big_grid_part():
"""Draws the top of a 4x4 grid"""
big_line = '+ - - - - + - - - - + - - - - + - - - - +'
big_column = '| | | | |'
print(big_line)
print(big_column)
print(big_column)
print(big_column)
print(big_column)
def large_grid():
"""puts the pieces of a 4x4 grid together"""
big_line = '+ - - - - + - - - - + - - - - + - - - - +'
big_grid_part()
big_grid_part()
big_grid_part()
big_grid_part()
print(big_line)
large_grid()
|
"""
Indra Ratna
CS-UY 1114
Lab 3
"""
import datetime
days = 0
x = input("What is your birthday in yyyymmdd form?")
y = (datetime.datetime.now().strftime("%Y%m%d"))
print("Your date of birth is "+x+ " and today is "+ str(y))
user_day = str(int(x)%100)
user_month = x[4:6]
user_year= x[0:4]
today_day = str(int(y)%100)
today_month= y[4:6]
today_year= y[0:4]
alive_year = int(today_year)-int(user_year)
alive_month = int(today_month)-int(user_month)
alive_day = int(today_day)-int(user_day)
if(int(user_month)%2==0):
days = 31
else:
days = 30
if(today_month<user_month):
alive_year= alive_year-1
if(today_day<user_day):
alive_month=alive_month-1
alive_day= (int(today_day))+(days-int(user_day))
print("Date of birth is "+user_month+"/"+user_day+"/"+user_year)
print("Today's date is "+today_month+"/"+today_day+"/"+today_year)
print("You have been alive for "+str(alive_year)+" years "+str(alive_month)+" month(s) and "+str(alive_day)+" day(s)")
|
import time
def countdown(n):
while n>0:
print(n)
time.sleep(1)
n-=1
if n==0:
print('DONE')
countdown(20)
|
def dictionary_of_metrics(items):
"""
Takes in a list of integers and returns a dictionary of the five number summary.
The function returns numerical values rounded to two decimal places.
Args:
items: list of integers
Returns:
dict (dictionary): a dict with keys 'max', 'median', 'min', 'q1',
and 'q3' corresponding to the maximum, median, minimum, first quartile and third quartile, respectively.
"""
import numpy as np
def mean(items):
mean = np.mean(items)
return mean
maximum = lambda items : max(items)
minimum = lambda items : min(items)
def mid(items):
median = np.median(items)
return median
def stdv(items):
std = np.std(items, ddof=1)
return std
def var(items):
var = np.var(items, ddof=1)
return var
met_dic = {'mean':round(mean(items), 2), 'median':round(mid(items), 2), 'var':round(var(items), 2),
'std':round(stdv(items), 2), 'min':round(minimum(items), 2), 'max':round(maximum(items), 2)}
return met_dic
def five_num_summ(items):
"""
Takes in a list of integers and returns a dictionary of the five number summary.
The function returns numerical values rounded to two decimal places.
Args:
data (list): list of integers
Returns:
dict (dictionary): a dict with keys 'max', 'median', 'min', 'q1',
and 'q3' corresponding to the maximum, median, minimum, first quartile and third quartile, respectively.
"""
import numpy as np
def q1(items):
q1 = np.percentile(items, 25)
return round(q1, 2)
def q3(items):
q3 = np.percentile(items, 75)
return round(q3, 2)
def mid(items):
median = np.median(items)
return round(median, 2)
maximum = lambda items : round(max(items), 2)
minimum = lambda items : round(min(items), 2)
fns = {'max': maximum(items), 'median': mid(items), 'min': minimum(items), 'q1': q1(items), 'q3': q3(items)}
return fns
def date_parser(items):
"""
Takes in a list of strings as input and returns a list of strings
Args:
items (list): a list of strings with each string formatted
as 'yyyy-mm-dd hh:mm:ss'
Returns:
list : a list of strings with each string formatted as 'yyyy-mm-dd'
"""
just_dates = [i[0:10] for i in items]
return just_dates
def extract_municipality_hashtags(df):
"""
Takes in a pandas dataframe.
Extract municipality from a tweet using dictionaries.
Extract hashtags from a tweet using dictionaries.
Args:
df (DataFrame): pandas data DataFrame
Returns:
DataFrame: with information about municipality and hashtags from each tweet.
"""
import numpy as np
import pandas as pd
mun_dict = { '@CityofCTAlerts' : 'Cape Town',
'@CityPowerJhb' : 'Johannesburg',
'@eThekwiniM' : 'eThekwini' ,
'@EMMInfo' : 'Ekurhuleni',
'@centlecutility' : 'Mangaung',
'@NMBmunicipality' : 'Nelson Mandela Bay',
'@CityTshwane' : 'Tshwane'}
municipality1=[]
for i in range(0, len(df)):
found=""
cityFound=""
for handle, city in mun_dict.items():
value=df.iloc[i][0].find(handle)
if value is not -1:
cityFound=city
else:
cityFound=np.nan
municipality1.append(cityFound)
municipality = pd.DataFrame(municipality1, columns=['municipality'])
municipality2 = df.join(municipality, lsuffix='Date', rsuffix='municipality')
hashes = [list(filter(lambda x: x.startswith("#"), df['Tweets'][i].lower().split())) for i in range(len(df.index.values))]
hashtags = pd.DataFrame([np.nan if x == [] else x for x in hashes ], columns=['hashtags'])
extracted_municipality_hashtags = municipality2.join(hashtags, lsuffix='municipality', rsuffix='hashtags')
return extracted_municipality_hashtags
def number_of_tweets_per_day(df):
"""
The function takes a pandas dataframe as inpit and returns a new dataframe,
grouped by day, with the numbers of tweets for that day
Args:
df (DataFrame): a twitter DataFrame
Returns:
DataFrame: with index named "Date" and the column of the new
dataframe should be 'tweets', corresponding to the date and number
of 'Tweets, corresponding to the date and number of tweets, respectively.
The date and number be formated as yyyy-mm-dd
"""
import numpy as np
import pandas as pd
df1=df['Date'].str.split(expand = True)
df['Date'] = df1[0]
df=df.groupby('Date').count()
return df
def word_splitter(df):
"""
Splits the sentences in a dataframe's column into a list of the separate words.
Args:
df (DataFrame): a twitter DataFrame
Returns:
DataFrame: The original twitter DataFrame with a columns "Tweets"
"""
import numpy as np
import pandas as pd
Split_tweets = [x.lower().split() for x in df['Tweets']]
d = pd.DataFrame(np.array(Split_tweets), columns=['Split Tweets'])
df_split = df.join(d, lsuffix='Date', rsuffix='Split Tweets')
return df_split
def stop_words_remover(df):
"""
Removes English stop words from a tweet, tokenises the tweet and places in
them in a column named "Without Stop Words". The stopwords are defined in
the stop_words_dict variable given.
Args:
df (DataFrame): a twitter DataFrame
Returns:
DataFrame: The original twitter DataFrame with a columns "Without Stop Words"
"""
import numpy as np
import pandas as pd
stop_words_dict = {
'stopwords':[
'where', 'done', 'if', 'before', 'll', 'very', 'keep', 'something', 'nothing', 'thereupon',
'may', 'why', '’s', 'therefore', 'you', 'with', 'towards', 'make', 'really', 'few', 'former',
'during', 'mine', 'do', 'would', 'of', 'off', 'six', 'yourself', 'becoming', 'through',
'seeming', 'hence', 'us', 'anywhere', 'regarding', 'whole', 'down', 'seem', 'whereas', 'to',
'their', 'various', 'thereafter', '‘d', 'above', 'put', 'sometime', 'moreover', 'whoever', 'although',
'at', 'four', 'each', 'among', 'whatever', 'any', 'anyhow', 'herein', 'become', 'last', 'between', 'still',
'was', 'almost', 'twelve', 'used', 'who', 'go', 'not', 'enough', 'well', '’ve', 'might', 'see', 'whose',
'everywhere', 'yourselves', 'across', 'myself', 'further', 'did', 'then', 'is', 'except', 'up', 'take',
'became', 'however', 'many', 'thence', 'onto', '‘m', 'my', 'own', 'must', 'wherein', 'elsewhere', 'behind',
'becomes', 'alone', 'due', 'being', 'neither', 'a', 'over', 'beside', 'fifteen', 'meanwhile', 'upon', 'next',
'forty', 'what', 'less', 'and', 'please', 'toward', 'about', 'below', 'hereafter', 'whether', 'yet', 'nor',
'against', 'whereupon', 'top', 'first', 'three', 'show', 'per', 'five', 'two', 'ourselves', 'whenever',
'get', 'thereby', 'noone', 'had', 'now', 'everyone', 'everything', 'nowhere', 'ca', 'though', 'least',
'so', 'both', 'otherwise', 'whereby', 'unless', 'somewhere', 'give', 'formerly', '’d', 'under',
'while', 'empty', 'doing', 'besides', 'thus', 'this', 'anyone', 'its', 'after', 'bottom', 'call',
'n’t', 'name', 'even', 'eleven', 'by', 'from', 'when', 'or', 'anyway', 'how', 'the', 'all',
'much', 'another', 'since', 'hundred', 'serious', '‘ve', 'ever', 'out', 'full', 'themselves',
'been', 'in', "'d", 'wherever', 'part', 'someone', 'therein', 'can', 'seemed', 'hereby', 'others',
"'s", "'re", 'most', 'one', "n't", 'into', 'some', 'will', 'these', 'twenty', 'here', 'as', 'nobody',
'also', 'along', 'than', 'anything', 'he', 'there', 'does', 'we', '’ll', 'latterly', 'are', 'ten',
'hers', 'should', 'they', '‘s', 'either', 'am', 'be', 'perhaps', '’re', 'only', 'namely', 'sixty',
'made', "'m", 'always', 'those', 'have', 'again', 'her', 'once', 'ours', 'herself', 'else', 'has', 'nine',
'more', 'sometimes', 'your', 'yours', 'that', 'around', 'his', 'indeed', 'mostly', 'cannot', '‘ll', 'too',
'seems', '’m', 'himself', 'latter', 'whither', 'amount', 'other', 'nevertheless', 'whom', 'for', 'somehow',
'beforehand', 'just', 'an', 'beyond', 'amongst', 'none', "'ve", 'say', 'via', 'but', 'often', 're', 'our',
'because', 'rather', 'using', 'without', 'throughout', 'on', 'she', 'never', 'eight', 'no', 'hereupon',
'them', 'whereafter', 'quite', 'which', 'move', 'thru', 'until', 'afterwards', 'fifty', 'i', 'itself', 'n‘t',
'him', 'could', 'front', 'within', '‘re', 'back', 'such', 'already', 'several', 'side', 'whence', 'me',
'same', 'were', 'it', 'every', 'third', 'together'
]
}
dates = df['Date'].to_list()
date_list = [dates[i].split()[0] for i in range(len(dates))]
tweets_list = list(df['Tweets'])
z = list(zip(date_list,tweets_list))
k = [y.lower() for x,y in z]
stop_words = tuple(stop_words_dict['stopwords'])
no_swords_list = [list(filter(lambda x: x not in stop_words, k[i].split()))
for i in range(len(df.index.values))]
no_swords_df = pd.DataFrame(np.array(no_swords_list), columns=['Without Stop Words'])
stop_words_remover_df = df.join(no_swords_df, lsuffix=['Date'], rsuffix=['Without Stop Words'])
return stop_words_remover_df
|
'''
Assignment #3
Intro to AI: 8 Puzzle using A*
Daniel Quintana Menjivar
Inspired by: https://www.youtube.com/watch?v=GuCzYxHa7iA
'''
import time
import random
import collections
import itertools
class Node: # reprents a Solver node
def __init__(self, puzzle, parent=None, action=None):
self.puzzle = puzzle # a puzzle instance
self.parent = parent # the preceeding node generated by solver, if any
self.action = action # the action taken to produce the puzzle, if any
if (self.parent != None):
self.g = parent.g + 1
else:
self.g = 0
@property # python simplification of getters and setters
def score(self):
return(self.g + self.h)
@property
def state(self): # returns a hashavle representation of self
return str(self)
@property
def path(self): # reconstructs a apth from the root to the parent
node = self
p = []
while node:
p.append(node)
node = node.parent
yield from reversed(p)
@property
def solved(self): # wrapper checks if puzzle is solved
return self.puzzle.solved
@property
def actions(self): # wrapper for actions accesible in the current state
return self.puzzle.actions
@property
def h(self):
return self.puzzle.manhattan
@property
def f(self):
return self.h + self.g
def __str__(self):
return str(self.puzzle)
class Solver: # an 8 puzzle solver
def __init__(self, start):
self.start = start # a Puzzle instance
def solve(self): #performs BFS and returns a path to solution if it exists
queue = collections.deque([Node(self.start)])
seen = set()
seen.add(queue[0].state)
while queue:
queue = collections.deque(sorted(list(queue), key=lambda node: node.f))
node = queue.popleft()
if node.solved:
return node.path
for move, action in node.actions:
child = Node(move(), node, action)
if child.state not in seen:
queue.appendleft(child)
seen.add(child.state)
class Puzzle: # represents an 8 puzzle
def __init__(self, board):
self.width = len(board[0])
self.board = board
@property
def solved(self): # if numbers are in increasing order from left to right and '0' is in the last position
N = self.width * self.width
return str(self) == ''.join(map(str, range(1, N))) + '0'
@property
def actions(self):
def create_move(at, to):
return lambda: self._move(at, to)
moves = []
for i, j in itertools.product(range(self.width), range(self.width)):
directions = {'R':(i, j-1),
'L':(i, j+1),
'D':(i-1, j),
'U':(i+1, j)}
for action, (r, c) in directions.items():
if r >= 0 and c >= 0 and r < self.width and c < self.width and self.board[r][c] == 0:
move = create_move((i, j), (r, c)), action
moves.append(move)
return moves # a list of move, action pair
@property
def manhattan(self):
distance = 0
for i in range(3):
for j in range(3):
if self.board[i][j] != 0:
x, y = divmod(self.board[i][j] - 1, 3)
distance += abs(x - i) + abs(y - j)
return distance
def shuffle(self): #return a puzzle that has been shuffled with 1K moves
puzzle = self
for _ in range(1000):
puzzle = random.choice(puzzle.actions)[0]()
return Puzzle(board)
def copy(self): # returns a new puzzle with the same board as self
board = []
for row in self.board:
board.append([x for x in row])
return Puzzle(board)
def _move(self, at, to):
copy = self.copy()
i, j = at
r, c = to
copy.board[i][j], copy.board[r][c] = copy.board[r][c], copy.board[i][j]
return copy # returns a new puzzle where at and to have been swapped
def printBoard(self):
for row in self.board:
print(row)
print()
def __str__(self):
return ''.join(map(str, self))
def __iter__(self):
for row in self.board:
yield from row
print('8-Puzzle A* Solver')
print('Enter the puzzle you want to solve like this \'1 2 3 4 5 6 7 8 0\' with \'0\' being the empty space')
puzzle = [int(x) for x in input().split()]
board = [puzzle[0:3], puzzle[3:6], puzzle[6:9]]
#board = [[2,0,5],[8,3,4],[7,6,1]]
puzzle = Puzzle(board)
#puzzle = puzzle.shuffle()
s = Solver(puzzle)
tic = time.time()
p = s.solve()
toc = time.time()
steps = 0
for node in p:
print(node.action)
node.puzzle.printBoard()
steps += 1
print("Total number of steps: " + str(steps))
print("Total amount of time in search: " + str(toc - tic) + " second(s)")
|
def merge_sort(input_array):
if len(input_array) > 1:
mid = len(input_array) // 2
input_array1 = input_array[:mid]
input_array2 = input_array[mid:]
merge_sort(input_array1)
merge_sort(input_array2)
# Create indexes for the 1st sorted array, second and also main array
i = j = k = 0
while i < len(input_array1) and j < len(input_array2):
if input_array1[i] < input_array2[j]:
input_array[k] = input_array1[i]
i += 1
else:
input_array[k] = input_array2[j]
j += 1
k += 1
while i < len(input_array1):
input_array[k] = input_array1[i]
i += 1
k += 1
while j < len(input_array2):
input_array[k] = input_array2[j]
j += 1
k += 1
return input_array
print(merge_sort([1,2,5,7,3,4,4])) |
import argparse
import os
parser = argparse.ArgumentParser(description="""This script creates a new sqlite database,
based on text_blob scores of each youtube comment.""")
parser.add_argument("--src", dest="src", type=str, default="/../../../../../scratch/manoelribeiro/helpers/"
"text_dict.sqlite",
help="Sqlite DataBase source of the comments.")
parser.add_argument("--dst", dest="dst", type=str, default="./../../data/sqlite/sentiment/perspective/data/sqlite/"
"perspective_sqlite/perspective_value.sqlite",
help="Sqlite DataBase to store the perspective values.")
parser.add_argument("--pgm", dest="program", type=str, default="blobtext.py",
help="Where to save the output files.")
parser.add_argument("--init", dest="init", type=int, default="0",
help="Comment where the analysis begin at each split.")
parser.add_argument("--end", dest="end", type=int, default="-1",
help="Finish the program when reaches end.")
parser.add_argument("--loop", dest="loop", type=int, default="1",
help="Number of times the code will be executed")
parser.add_argument("--j", dest="j", type=int, default="1",
help="Split where the analysis begin.")
args = parser.parse_args()
os.system('echo "Starting Program"')
init = args.init
end = args.end
diff = args.end - args.init
for i in range(args.j, args.loop):
cmd = f"python {args.program} --dst {args.dst} --j {i} --end {end}"
os.system(f'echo {cmd}')
os.system(cmd)
|
import keyword
class KeyValueStorage:
"""Wrapper class for a file that works as key-value storage.
Each key-value pair in the file is separated by "=" symbol, example:
name=kek
last_name=top
song_name=shadilay
power=9001
Values can be strings or integer numbers. If a value can be treated both as a
number and a string, it is treated as number.
Warning:
To save all changes in attributes in file-storage you should call
instance_name.rewrite_file() method, otherwise they would be lost after
programme termination.
Attribute:
__path: path to a file-storage.
Raises:
ValueError: if given name cannot be assigned to an attribute;
ValueError: in case of attribute clash with existing built-in attributes.
"""
def rewrite_file(self) -> None:
"""Saves all changes in attributes in the file-storage.
How to use:
instance_name.rewrite_file()
If you haven't called this method all changes in attributes would be lost after
programme termination.
"""
with open(self.__path, "w", encoding="utf-8") as file:
for key, value in self.__dict__.items():
if not key.startswith("_"):
file.write(f"{key}={value}\n")
def _validate_name(self, name: str) -> None:
"""Checks if given name match attribute name rules.
Args:
name: attribute name for validation.
Raises:
ValueError: if given name cannot be assigned to an attribute;
ValueError: in case of attribute clash with existing built-in attributes.
"""
if not name.isidentifier() or keyword.iskeyword(name):
raise ValueError(f"{name} cannot be assigned to an attribute")
elif name in dir(self):
raise ValueError(
f"{name} attribute clash with existing built-in attributes"
)
def __init__(self, path: str) -> None:
"""Creates attributes from path and key-value pairs, received from a
file-storage.
If some value contains of numbers it is converted to int type.
Args:
__path: path to a file-storage.
Raises:
ValueError: if given name cannot be assigned to an attribute;
ValueError: in case of attribute clash with existing built-in attributes.
"""
self.__path = path
with open(self.__path) as file:
for line in file:
key, value = line.rstrip().split("=", maxsplit=1)
self._validate_name(key)
if value.isdigit():
value = int(value) # type: ignore
self.__dict__[key] = value
def __setattr__(self, name, value) -> None:
"""Checks new attribute name and set it up.
Args:
name: attribute name;
value: attribute value.
Raises:
ValueError: if given name cannot be assigned to an attribute;
ValueError: in case of attribute clash with existing built-in attributes.
"""
self._validate_name(name)
object.__setattr__(self, name, value)
def __getitem__(self, name: str) -> str:
"""Makes attributes accessible through square brackets notation.
Args:
name: attribute name.
Returns:
attribute's value.
"""
return self.__dict__[name]
def __setitem__(self, name, value) -> None:
"""Checks new attribute name and assign it through square brackets notation.
Args:
name: attribute name;
value: attribute value.
Raises:
ValueError: if given name cannot be assigned to an attribute;
ValueError: in case of attribute clash with existing built-in attributes.
"""
self._validate_name(name)
self.__dict__[name] = value
def __delitem__(self, name) -> None:
"""Removes attribute with given name if is. Implements deletion through square
brackets notation.
Args:
name: attribute name.
"""
del self.__dict__[name]
|
"""
Write a context manager, that suppresses passed exception.
Do it both ways: as a class and as a generator.
>>> with suppressor(IndexError):
... [][2]
"""
from contextlib import contextmanager
from typing import Iterator
class Suppressor:
"""Context manager, that suppresses passed exception.
Attribute:
exception_type: a name of exception to suppress.
"""
def __init__(self, exception_type=None) -> None:
"""Initialises a class instance.
Args:
exception_type: a name of exception to suppress.
"""
self.exception_type = exception_type
def __enter__(self) -> None:
pass
def __exit__(self, *args) -> bool:
"""Exit the runtime context. The parameters describe the exception that caused
the context to be exited.
Returns:
If an exception is supplied, it return True. Otherwise, the exception will
be processed normally upon exit from this method.
"""
return bool(self.exception_type)
@contextmanager
def suppressor(exception_type) -> Iterator:
"""Context manager, that suppresses passed exception.
Args:
exception_type: a name of exception to suppress.
"""
try:
yield
except exception_type:
pass
|
#define a class for a generic enemy
class Enemy:
# Constructor
# Name - The name of the enemy
# Health - How much HP the enemy currently has
# Damage - How much damage the enemy can do
def __init__(self, name, health, damage):
self.name = name
self.health = health
self.damage = damage
# Determines if the enemy is alive
def is_alive(self):
return self.health > 0
# Create a few examples of enemies
class GiantSpider(Enemy):
def __init__(self):
super().__init__(name="Giant Spider",
health=10,
damage=2)
# Remember, is_alive is inherited by the enemy class
class Ogre(Enemy):
def __init__(self):
super().__init__(name="Ogre",
health=30,
damage=15)
# Remember, is_alive is inherited by the enemy class
|
# imports the function tan and pi from the math module
from math import tan, pi
def polysum(n, s):
""" This function adds the area of a polygon to the length of a polygon returning
the value with an accuracy of 4 places to the right of the decimal point.
The function accepts 2 parameters.
n is the number of sides the polygon has.
s is the length of each side
"""
# calculate the area
area = (.25 * n * (s**2)) / tan(pi/n)
# calculate the perimeter
perimeter = (n * s) ** 2
# return the value of area + perimeter, rounded to 4 places to the right of the decimal point
return round(area + perimeter, 4)
|
#!/usr/bin/python3
# Takes in input from stdin as a csv file, reads it according to a config file, and prints to standard out a file with only data numbers, one per line, or an N if no data
# The first line in output is the name
# If there is an error in parsing the file, such as an out-of-bounds number, warn the user and exit.
import sys
import helper
def get_score(s, line, mi, ma):
s = s.split(',', 1)[0]
if len(s) == 0:
warnings.append('Warning at line %d: No answer (expected between %d and %d)' % (line, mi, ma))
return 'N'
if s in 'afF':
s = '0'
if s in 'btT':
s = '1'
if not s.isnumeric():
errors.append('Error at line %d: malformatted answer %s (expected between %d and %d)' % (line, s, mi, ma))
return 'E'
if int(s) < mi:
errors.append('Error at line %d: Value %s is less than minimum %d' % (line, s, mi))
return 'E'
if int(s) > ma:
errors.append('Error at line %d: Value %s is greater than maximum %d' % (line, s, ma))
return 'E'
return s
if len(sys.argv) < 2:
print ('Big 5 Calculator - Changes .csv stdin to list of numbers - Magnus Anderson\nUsage: ./fix.py format_file', file=sys.stderr)
exit(0)
file_template = sys.argv[1]
with open (file_template) as f:
template = f.read().splitlines()
csvdata = sys.stdin.read().splitlines()
scores = []
warnings = []
errors = []
name = ''
linenumb = 0
for line in template:
conf = line.split(',')
mi = 0
ma = 0
nlines = 0
ignore = False
name = False
for option in conf:
key, val = option.split(':', 1)
if key == 'min':
mi = int(val)
if key == 'max':
ma = int(val)
if key == 'lines':
nlines = int(val)
if key == 'ignore':
ignore = True
if key == 'name':
name = True
if ignore:
linenumb += nlines
continue
if len(csvdata) < linenumb + 1:
errors.append('File ended abruptly')
break
if name:
if csvdata[linenumb].find(',') == -1:
errors.append('No name or incorrectly formatted name')
break
name = csvdata[linenumb].split(',')[0]
linenumb += 1
continue
for i in range(nlines):
val = get_score(csvdata[linenumb], linenumb + 1, mi, ma)
scores.append(val)
linenumb += 1
if len(errors) > 0:
print('Errors in file')
for w in warnings:
print (w, file=sys.stderr)
for e in errors:
print (e, file=sys.stderr)
exit(1)
elif len(warnings) > 0:
print('Warnings in file')
for w in warn:
print (w, file=sys.stderr)
print()
print(name, end='')
for score in scores:
print(',', end='')
print(score, end='')
comma=True
print()
|
def y1(x):
if x != 0:
return 2 / x
return 'NO'
def y2(x):
return (2 * x) + 3**x
x = -5
while x >= -5 and x <= 5:
print('*', end='\n')
print('x = ',x)
print('y1 = ', y1(x))
print('y2 = ', y2(x))
x = x + 1/2
|
import math
x = 2
print(math.pi)
if x >= -math.pi and x <= math.pi:
y = math.cos(3*x)
print(y)
elif x < -math.pi or x > math.pi:
y = x
print(y) |
def arifm(a, b, c):
return (a + b + c)/3
uslov = input("zhelayete nachatj? (y/n)")
while uslov != 'n':
a = int(input('vvidite pervoje chislo a'))
b = int(input('vvedite vtoroye chislo b'))
c = int(input('vvedite tretje chislo c'))
print(arifm(a, b, c))
uslov = input("prodolzhit? (y/n)")
else:
print('spasibo za ispolzovaniye!')
|
import random
import sys
import os
#define classes and functions for 3 different 3D shapes
class Circle():
def __init__(self, radius=1):
self.__radius = radius
self.display()
def find_area(self):
a = self.__radius * self.__radius * 3.142
return(a)
def setRadius(self, rad):
self.__radius = rad
def getRadius(self):
return(self.__radius)
def display(self):
return(self.find_area())
class Square():
def __init__(self, sside=2.3):
self.__sside = sside
self.display()
def find_area(self):
a = self.__sside * self.__sside
return(a)
def setSSide(self, lw):
self.__sside = lw
def getSSide(self):
return(self.__sside)
def display(self):
return(self.find_area())
class Cube():
def __init__(self, cside=2):
self.__cside = cside
self.display()
def find_surfacearea(self):
sa = 6 * self.__cside * self.__cside
return(sa)
def setCSide(self, lwh):
self.__cside = lwh
def getCSide(self):
return(self.__cside)
def display(self):
return(self.find_surfacearea())
#create lists and append data
myList = []
circle = 1
square = 2
cube = 3
circlecount = 0
squarecount = 0
cubecount = 0
for i in range (10):
shape = random.randint(1, 3)
if shape == 1:
circlecount += 1
myList.append(1)
elif shape == 2:
squarecount += 1
myList.append(2)
else:
cubecount += 1
myList.append(3)
print("Circle")
print(circlecount)
print(" ")
print("Square")
print(squarecount)
print(" ")
print("Cube")
print(cubecount)
print(" ")
print(myList, "| Total:", len(myList))
#create and run loops to return properties of shapes
#ask for user input to save output to file, ask for file name if yes
choice = input("\nWould you like to save the output to a file? Y/N ")
print("")
if choice.lower() == "n" or choice.lower() == "no":
for i in range(10):
if myList[i] == 1:
radius = random.randint(1, 20)
circle = Circle(radius)
print("")
print("Class = Circle")
print("The area of circle is ",circle.display())
elif myList[i] == 2:
sside = random.randint(1, 20)
square = Square(sside)
print("")
print("Class = Square")
print("The area of square is ",square.display())
else:
cside = random.randint(1, 20)
cube = Cube(cside)
print("")
print("Class = Cube")
print("The area of cube is ",cube.display())
elif choice.lower() == "y" or choice.lower() == "yes":
filename = input("Enter a filename: ").strip()
fo = open(filename, "w")
for i in range(len(myList)):
if myList[i] == 1:
radius = random.randint(1, 20)
circle = Circle(radius)
fo.write ("\nClass = Circle\nThe area of circle is "+str(circle.display())+"\n")
elif myList[i] == 2:
sside = random.randint(1, 20)
square = Square(sside)
fo.write ("\nClass = Square\nThe area of square is "+str(square.display())+"\n")
else:
cside = random.randint(1, 20)
cube = Cube(cside)
fo.write ("\nClass = Cube\nThe area of cube is "+str(cube.display())+"\n")
fo.close()
else :
print ("Invalid input.")
|
import random
player_one_score = 0
player_two_score = 0
def run_game():
game_type = choose_game_type()
player_one_name = set_player_name()
player_two_name = set_player_name()
while player_one_score < 2 and player_two_score < 2:
if game_type == "1":
player_one_gesture = choose_gesture(player_one_name)
player_two_gesture = choose_gesture(player_two_name)
determine_round_winner(player_one_name, player_one_gesture, player_two_name, player_two_gesture)
display_scoreboard(player_one_name, player_two_name)
check_if_game_winner(player_one_name, player_two_name)
elif game_type == "2":
player_one_gesture = choose_gesture(player_one_name)
player_two_gesture = get_random_gesture(player_two_name)
determine_round_winner(player_one_name, player_one_gesture, player_two_name, player_two_gesture)
display_scoreboard(player_one_name, player_two_name)
check_if_game_winner(player_one_name, player_two_name)
def choose_game_type():
game_type = input("Please choose Player vs Player or Player vs Computer. Type 1 for PvP or 2 for PvC")
return game_type
def set_player_name():
name = input("Please enter a name")
print(f'Hello, {name}!')
return name
def choose_gesture(player_name):
gesture_choice = input("Please choose a gesture. Type R for rock, P for paper, or S for scissors")
print(f'{player_name} chose {gesture_choice}')
return gesture_choice
def get_random_gesture(player_name):
gestures = ['R', 'P', 'S']
random_number = random.randint(0, 2)
random_gesture = gestures[random_number]
print(f'{player_name} chose {random_gesture}')
return random_gesture
def determine_round_winner(player_one_name, player_one_gesture, player_two_name, player_two_gesture):
global player_one_score
global player_two_score
if player_one_gesture == player_two_gesture:
print('Tie!')
elif player_one_gesture == 'R' and player_two_gesture == 'S':
print(f'{player_one_name} wins the round!')
player_one_score += 1
elif player_one_gesture == 'P' and player_two_gesture == 'R':
print(f'{player_one_name} wins the round!')
player_one_score += 1
elif player_one_gesture == 'S' and player_two_gesture == 'P':
print(f'{player_one_name} wins the round!')
player_one_score += 1
else:
print(f'{player_two_name} wins the round!')
player_two_score += 1
def display_scoreboard(player_one_name, player_two_name):
print(f'{player_one_name} score: {player_one_score}')
print(f'{player_two_name} score: {player_two_score}')
def check_if_game_winner(player_one_name, player_two_name):
global player_one_score
global player_two_score
if player_one_score == 2:
print(f'{player_one_name} wins the game!!')
elif player_two_score == 2:
print(f'{player_two_name} wins the game!!')
run_game()
|
'''
You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Return a list of integers representing the size of these parts.
Example 1:
Input: s = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.
Example 2:
Input: s = "eccbbbbdec"
Output: [10]
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters.
'''
class Solution:
def partitionLabels(self, s: List[str]) -> int:
rightmost = {c:i for i, c in enumerate(s)}
left, right = 0, 0
result = []
for i, letter in enumerate(s):
right = max(right,rightmost[letter])
if i == right:
result += [right-left + 1]
left = i+1
return result
|
'''
A complex number can be represented as a string on the form "real+imaginaryi" where:
real is the real part and is an integer in the range [-100, 100].
imaginary is the imaginary part and is an integer in the range [-100, 100].
i2 == -1.
Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.
Example 1:
Input: num1 = "1+1i", num2 = "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Example 2:
Input: num1 = "1+-1i", num2 = "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
'''
# Multiplication of two complex numbers can be done as:
# (a+ib)*(x+iy) = a*x + (i^2*b*y) + i*(bx+ay) = a*x - b*y +i*(bx+ay)
class Solution:
def solve(self, num):
f1 = num.find("+", 0 ,len(num))
return int(num[0:f1]), int(num[f1+1:len(num)-1])
def complexNumberMultiply(self, num1: str, num2: str) -> str:
a, b = self.solve(num1)
x, y = self.solve(num2)
return str(x*a - b*y)+"+"+str(a*y + b*x)+"i"
|
'''
Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.
An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.
A subsequence of a string s is a string that can be obtained after deleting any number of characters from s.
For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).
Example 1:
Input: strs = ["aba","cdc","eae"]
Output: 3
Example 2:
Input: strs = ["aaa","aaa","aa"]
Output: -1
Constraints:
1 <= strs.length <= 50
1 <= strs[i].length <= 10
strs[i] consists of lowercase English letters.
'''
#This code is working for all the test cases. Was a very simple fix to get all the test cases working. All I had to include was a list which carries all the subsequence of elements that have been processed.
from typing import List
from itertools import combinations
class Solution:
def findLUSlength(self, strs: List[str]) -> int:
longelementlist = []
iteration = 0
def get_max_str(lst):
return max(lst, key=len)
#this if the function to get all the subsequences
def get_all_substrings(input_string):
out = set()
for r in range(1, len(input_string) + 1):
for c in combinations(input_string, r):
out.add(''.join(c))
return sorted(out)
def counterFunct(s):
counter = 0
longestElement = get_max_str(s)
for element in s:
if longestElement in element:
counter+=1
return counter,longestElement
def uslen(strs,iteration,longelementlist):
if not strs:
return -1
print(strs,iteration,longelementlist)
iteration = iteration+1
lenlong,longestElement = counterFunct(strs)
print(lenlong,longestElement)
print("Iteration : " , iteration)
if lenlong == 1 and not any(longestElement in string for string in longelementlist):
return len(longestElement)
elif any(longestElement in string for string in longelementlist):
longelementlist.extend( list(set(get_all_substrings(longestElement))) )
strsn = [element for element in strs if element != longestElement]
return uslen(strsn,iteration,longelementlist)
else:
longelementlist.extend( list(set(get_all_substrings(longestElement))) )
print("Longelementlist : ", longelementlist)
print("removing : " , longestElement)
strsn = [element for element in strs if element != longestElement]
return uslen(strsn,iteration,longelementlist)
return uslen(strs,iteration,longelementlist)
|
'''
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:
Input: s = "12"
Output: 2
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: s = "226"
Output: 3
Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Example 3:
Input: s = "0"
Output: 0
Explanation: There is no character that is mapped to a number starting with 0.
The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of which start with 0.
Hence, there are no valid ways to decode this since all digits need to be mapped.
Example 4:
Input: s = "06"
Output: 0
Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
Constraints:
1 <= s.length <= 100
s contains only digits and may contain leading zero(s).
'''
import itertools as it
def func(s):
if not s:
return [s]
binary = it.product(['',' '], repeat=len(s)-1)
zipped = (it.zip_longest(s , comb, fillvalue='') for comb in binary)
# return [it.chain.from_iterable(x) for x in zipped]
return [''.join(it.chain.from_iterable(x)) for x in zipped]
class Solution:
def numDecodings(self, s: str) -> int:
theDict = {chr(y):y-64 for y in range(65,91)}
revDict = { y-64 : chr(y) for y in range(65,91) }
comb = func(s)
print("comb : " , comb)
total_count = 0
for item in comb:
tempItem = str.split(item)
print("tempItem : " , tempItem)
tcount = 0
for titem in tempItem:
print("titem : " , titem)
if (titem.startswith('0')):
if titem in revDict.keys():
tcount += 1
else:
if int(titem) in revDict:
tcount += 1
if tcount == len(tempItem):
total_count += 1
print("tcount : " , tcount , "len(tempItem) : " , len(tempItem))
return total_count
|
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
def recursion(s,i,j):
if i==j or i>j:
return
print("swapping : " , s[i],s[j])
c = s[i]
s[i] = s[j]
s[j] = c
i = i+1
j = j-1
recursion(s,i,j)
recursion(s,0,len(s)-1)
|
import numpy as np
x = np.array([[1, 2], [3, 4]])
print(x)
print(type(x))
y = np.array([[2, 4, 6], [8, 10, 12], [14, 16, 18]])
print(y)
print(type(y))
"""
Perceber o ponto após os números para forçar a troca de inteiro e decimal
"""
z = np.array([[1, 3], [5, 7]], dtype = float) #dtype = foat ou dtype = int
print(z)
print(type(z)) |
num = int(input('Enter a number: '))
assert num >= 0, "Somente números positivos"
print('You entered: ', num)
# Se digitar 100 >> You entered: 100
""" Se digitar menor que 0
File "22_assert.py", line 2, in <module>
assert num >= 0
AssertionError: Somente números positivos
"""
try:
num = int(input('Enter a number: '))
assert (num >= 0), "Somente números positivos"
print('You entered: ', num)
except AssertionError as msg:
print(msg)
|
c = 'copia de texto'
# c2 NÃO é cópia, é referência de c
c2 = c
# ´Cópias do texto
c2 = list(c)
c2 = c[:]
import copy
c2 = copy.copy(c)
lista_a = [1, 2, [3, 4]]
lista_b = lista_a[:]
copylista_b = copy.copy(lista_a)
deepcopylista_b = copy.deepcopy(lista_a)
# Subtituiu o 3 pelo 10
lista_a[2][0] = 10
print(lista_a) # [1, 2, [10, 4]]
print(lista_b) # [1, 2, [10, 4]]
print(copylista_b) # [1, 2, [10, 4]]
print(deepcopylista_b) # [1, 2, [3, 4]]
|
import pandas as pd # quadros de dados fornecidos
import matplotlib.pyplot as plt # suporte para plotagem
df = pd.read_csv("pima-data.csv")
print(df.shape)
print(df.head(5))
print(df.tail(5))
print(df.isnull().values.any())
def plot_corr(df, size=11):
"""
Function plots a graphical correlation matrix for each pair of columns in the dataframe.
Input:
df: pandas DataFrame
size: vertical and horizontal size of the plot
Displays:
matrix of correlation between columns. Blue-cyan-yellow-red-darkred => less to more correlated
0 ------------------> 1
Expect a darkred line running from top left to bottom right
"""
corr = df.corr() # data frame correlation function
fig, ax = plt.subplots(figsize=(size, size))
ax.matshow(corr) # color code the rectangles by correlation value
plt.xticks(range(len(corr.columns)), corr.columns) # draw x tick marks
plt.yticks(range(len(corr.columns)), corr.columns) # draw y tick marks
plt.savefig("plot_correlation_function.png")
# plt.show()
plot_corr(df)
corr = df.corr()
import seaborn as sns
print(sns.heatmap(corr, annot = True))
num_obs = len(df)
num_true = len(df.loc[df['diabetes'] == 1])
num_false = len(df.loc[df['diabetes'] == 0])
print("Number of True cases: {0} ({1:2.2f}%)".format(num_true, (num_true/num_obs) * 100))
print("Number of False cases: {0} ({1:2.2f}%)".format(num_false, (num_false/num_obs) * 100))
from sklearn.model_selection import train_test_split
feature_col_names = ['num_preg', 'glucose_conc', 'diastolic_bp', 'thickness', 'insulin', 'bmi', 'diab_pred', 'age']
predicted_class_names = ['diabetes']
X = df[feature_col_names].values # predictor feature columns (8 X m)
y = df[predicted_class_names].values # predicted class (1=true, 0=false) column (1 X m)
split_test_size = 0.30
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=split_test_size, random_state=42)
# test_size = 0.3 is 30%, 42 is the answer to everything
# 69.92% in training set
print("{0:0.2f}% in training set".format((len(X_train)/len(df.index)) * 100))
# 30.08% in test set
print("{0:0.2f}% in test set".format((len(X_test)/len(df.index)) * 100))
print("Original True : {0} ({1:0.2f}%)".format(len(df.loc[df['diabetes'] == 1]), (len(df.loc[df['diabetes'] == 1])/len(df.index)) * 100.0))
print("Original False : {0} ({1:0.2f}%)".format(len(df.loc[df['diabetes'] == 0]), (len(df.loc[df['diabetes'] == 0])/len(df.index)) * 100.0))
print("")
print("Training True : {0} ({1:0.2f}%)".format(len(y_train[y_train[:] == 1]), (len(y_train[y_train[:] == 1])/len(y_train) * 100.0)))
print("Training False : {0} ({1:0.2f}%)".format(len(y_train[y_train[:] == 0]), (len(y_train[y_train[:] == 0])/len(y_train) * 100.0)))
print("")
print("Test True : {0} ({1:0.2f}%)".format(len(y_test[y_test[:] == 1]), (len(y_test[y_test[:] == 1])/len(y_test) * 100.0)))
print("Test False : {0} ({1:0.2f}%)".format(len(y_test[y_test[:] == 0]), (len(y_test[y_test[:] == 0])/len(y_test) * 100.0)))
# NEED CALLOUT MENTION CHANGE TO SIMPLEIMPUTER
#from sklearn.preprocessing import Imputer
from sklearn.impute import SimpleImputer
#Impute with mean all 0 readings
#fill_0 = Imputer(missing_values=0, strategy="mean", axis=0)
fill_0 = SimpleImputer(missing_values=0, strategy="mean")
X_train = fill_0.fit_transform(X_train)
X_test = fill_0.fit_transform(X_test)
from sklearn.naive_bayes import GaussianNB
# create Gaussian Naive Bayes model object and train it with the data
nb_model = GaussianNB()
nb_model.fit(X_train, y_train.ravel())
|
fibonacci = (lambda n, first=0, second=1:
"" if n == 0 else
str(first) + "\n" + fibonacci(n - 1, second, first + second))
print(fibonacci(10), end="")
fibonacci = (lambda n, first=0, second=1:
[] if n == 0 else
[first] + fibonacci(n - 1, second, first + second))
print(fibonacci(10)) |
import functools
def mult(x, y):
print("x=", x, " y=", y)
return x * y
fact = functools.reduce(mult, range(1, 4))
print('Factorial of 3: ', fact)
"""
x= 1 y= 2
x= 2 y= 3
Factorial of 3: 6
"""
from functools import reduce
def soma(x1, x2):
return x1 + x2
# Saída: 10
print(reduce(soma, [1, 2, 3, 4]))
# Calcula o fatorial de n
def fat(n):
return reduce(lambda x, y: x * y, range(1, n))
# Saída: 720
print(fat(7))
|
try:
print("try block")
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." ) |
class person:
totalObjects = 0
def __init__(self):
person.totalObjects = person.totalObjects + 1
@classmethod
def showcount(cls):
print("Total objects: ", cls.totalObjects)
p1 = person()
p2 = person()
person.showcount() # Total objects: 2
p1.showcount () # Total objects: 2
|
# 1. e 2. Digital as somas dos caracteres:
soma_um = int(input ('Digitar a soma do "primeiro" com o "segundo"' + ' caracteres da senha (da esquerda para a direita) = '))
soma_dois = int(input ('Digitar a soma do "segundo" com o "terceiro"' + ' caracteres da senha (da esquerda para a direita) = '))
soma_tres = int(input ('Digitar a soma do "terceiro" com o "quarto"' + ' caracteres da senha (da esquerda para a direita) = '))
soma_quatro = int(input ('Digitar a soma do "quarto" com o "quinto"' + ' caracteres da senha (da esquerda para a direita) = '))
soma_cinco = int(input ('Digitar a soma do "quinto" com o "sexto"' + ' caracteres da senha (da esquerda para a direita) = '))
# obs: quando estou trabalhando com texto, o "+" é um operador de concatenação
print('')
print('OBSERVAÇÃO: NÃO pode existir somas maiores que 19 (dezenove)')
print('')
# 3. Calcular a soma das somas alternando os sinais:
soma = + soma_um - soma_dois + soma_tres - soma_quatro + soma_cinco
# 4. Calcular a divisao do item anterior por dois:
divisao = round(soma / 2 , 0) # A função <round> servirá para garantir pegar sempre um número inteiro após a divisão
# 5. Executar cálculos finais:
calculo_um = + soma_um - divisao
calculo_dois = - soma_dois + calculo_um
calculo_tres = + soma_tres + calculo_dois
calculo_quatro = - soma_quatro + calculo_tres
calculo_cinco = + soma_cinco + calculo_quatro
print('')
print('A senha é: ' + str(int(abs(divisao))) + str(int(abs(calculo_um))) + str(int(abs(calculo_dois))) + str(int(abs(calculo_tres))) + str(int(abs(calculo_quatro))))
|
import math
def sigmoid(x):
return 1 / (1 + math.exp(-x))
print(sigmoid(1.10)) # 0.7502601055951177
print(sigmoid(1.00)) # 0.7310585786300049
print(sigmoid(0.90)) # 0.7109495026250039
print(sigmoid(0.70)) # 0.6681877721681662
print(sigmoid(0.50)) # 0.6224593312018546
print(sigmoid(2.31)) # 0.9097018552970803
print(sigmoid(-1.89)) # 0.13124446943852333 |
"""Pseudo-Código
Inicio
digitar coeficiente_a
digitar coeficiente_b
digitar coeficiente_c
Se a = 0 Então
Se b != 0 Então
Imprimir "A equação possui uma única raiz"
r_um <- -c/b
Imprimir r_um
Senão b = 0 Então
Imprimir "Indeterminação/Singularidade"
Sair da subrotina
Fim do Se
Senão
delta <- b ** 2 - 4 * a * c
Se delta >= Então
r_um <- (- b - delta ** (1 / 2))/(2 * a)
r_dois <- (- b + delta ** (1 / 2))/(2 * a)
Imprimir "A equação possui duas raízes"
Imprimir r_um
Imprimir r_dois
Senão delta < 0 Então
Imprimir "A equação possui raiz imaginária"
real <- -b / (2 * a)
imaginaria <- (delta ** (1 / 2))/(2 * a)
Imprimir real + imaginaria "j"
Fim do Se
Fim do Se
Fim
"""
a = float(input("Digite o valor do coeficiente 'a' (a * (x ** 2) + b * x + c = 0) da equação do segundo grau: "))
b = float(input("Digite o valor do coeficiente 'b' (a * (x ** 2) + b * x + c = 0) da equação do segundo grau: "))
c = float(input("Digite o valor do coeficiente 'c' (a * (x ** 2) + b * x + c = 0) da equação do segundo grau: "))
if a == 0:
if b != 0:
print("Observações: a equação possui uma única raiz.")
R1 = - c / b
print("Valor da raiz = ", R1)
else:
print("Observações: Indeterminação / Singularidade")
quit()
else:
delta = b ** 2 - 4 * a * c
if delta >= 0:
print("Observações: a equação possui duas raízes reais.")
R1 = (- b - (delta ** (1 / 2))) / (2 * a)
print("Valor da primeira raiz =", round(R1,2))
R2 = (- b + (delta ** (1 / 2))) / (2 * a)
print("Valor da segunda raiz =", round(R2,2))
else:
print("Observações: a equação possui raiz imaginária.")
Re = - b / (2 * a)
print("Valor da parte real (Re) =", round(Re,2))
Im = ((- delta) ** (1 / 2)) / (2 * a)
print("Valor da parte imaginária (Im) =", round(Im,2)) |
import functools
import operator
foldl = lambda func, acc, xs: functools.reduce(func, xs, acc)
result = foldl(operator.sub, 0, [1, 2, 3])
print(result) # -6
result = foldl(operator.add, 'L', ['1', '2', '3'])
print(result) # L123
# FOLDL Function
def foldl(func, acc, xs):
return functools.reduce(func, xs, acc)
print(foldl(operator.sub, 0, [1,2,3])) # -6
print(foldl(operator.add, 'L', ['1','2','3'])) # 'L123' |
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
transposta = []
for i in range(len(matrix[0])):
linha_transposta = []
for linha in matrix:
linha_transposta.append(linha[i])
transposta.append(linha_transposta)
# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
print(transposta)
transposta = [[linha[i] for linha in matrix] for i in range(4)]
# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
print(transposta) |
# Create a global variable `A`.
A = 5
def impure_sum(b):
# Adds two numbers, but uses the
# global `A` variable.
return b + A
def pure_sum(a, b):
# Adds two numbers, using
# ONLY the local function inputs.
return a + b
print(impure_sum(5)) # 10
print(pure_sum(4, 6)) # 10
# Abordagem tradicional Imperativo
prices = [50, 60, 70]
newPrices = []
for price in prices:
newPrice = price * 1.1
newPrices.append(newPrice)
print (newPrices) # [55.00000000000001, 66.0, 77.0]
# Função pura Funcional
prices = [50, 60, 70]
list(map(lambda price: price * 1.1 , prices))
print (prices) # [50, 60, 70]
|
num_iter = int(input("Digitar o valor do número máximo para a sequência de Farey = "))
F = []
"""
for i in range(1, num_iter + 1, 1 :
for j in range(i, num_iter + 1, 1) :
F.append(i / j)
print(F)
F = set(F)
F = sorted(F) #Classificar o set
"""
i = 1
while i <= num_iter:
j = i
while j <= num_iter:
F.append(round(i / j, 2))
print(F)
j = j + i
i = i + 1
F = set(F)
F = sorted(F) # Classificar o set
print(F)
"""
As sequências de Farey são nomeadas a partir do geólogo Britânico John Farey,
que teve suas cartas sobre essas sequências publicadas na revista Philosophical
Magazine em 1816. Farey conjecturou, sem apresentar provas, que cada novo termo
na expansão de uma sequência de Farey é a mediante de seus vizinhos. A carta de
Farey foi lida por Cauchy, que forneceu uma prova em seus Exercices de mathématique,
e atribuiu este resultado a Farey. Na realidade, outro matemático, Charles Haros,
havia publicado resultados similares em 1802 que não eram conhecidos nem por Farey
ou por Cauchy.[2] Portanto foi um acidente histórico que ligou o nome de Farey a
essas sequências. Este é um exemplo da Lei de Stigler.
As sequências de Farey de ordem 1 até 8 são :
F1 = { 0/1, 1/1 }
F2 = { 0/1, 1/2, 1/1 }
F3 = { 0/1, 1/3, 1/2, 2/3, 1/1 }
F4 = { 0/1, 1/4, 1/3, 1/2, 2/3, 3/4, 1/1 }
F5 = { 0/1, 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5, 1/1 }
F6 = { 0/1, 1/6, 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5, 5/6, 1/1 }
F7 = { 0/1, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 2/5, 3/7, 1/2, 4/7, 3/5, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 1/1 }
F8 = { 0/1, 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8, 1/1 }
Order Count
1 2 F1 = {0/1, 1/1}
2 3 F2 = {0/1, 1/2, 1/1}
3 5 F3 = {0/1, 1/3, 1/2, 2/3, 1/1}
4 7 F4 = {0/1, 1/4, 1/3, 1/2, 2/3, 3/4, 1/1}
5 11 F5 = {0/1, 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5, 1/1}
6 13 F6 = {0/1, 1/6, 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5, 5/6, 1/1}
7 19 F7 = {0/1, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 2/5, 3/7, 1/2, 4/7, 3/5, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 1/1}
8 23 F8 = {0/1, 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8, 1/1}
"""
|
def LineCounter(filename):
with open(filename, 'r') as f:
return [line for line in f]
def count(lines):
return len(lines)
arquivo = LineCounter('nome_errado.txt')
print(count(arquivo)) # 7
print(arquivo) # ['Toque Frágil (Walter
print(count(arquivo)) # 7
print(arquivo) # ['Toque Frágil (Walter
|
from tkinter import *
window = Tk()
btn = Button(window, text="This is Button widget", fg='blue')
btn.place(x=80, y=100)
lbl = Label(window, text="This is Label widget", fg='red', font=("Helvetica", 16))
lbl.place(x=60, y=50)
txtfld = Entry(window, text="This is Entry Widget", bd=5)
txtfld.place(x=80, y=150)
window.title('Hello Python')
window.geometry("300x200+10+10")
window.mainloop()
|
import numpy as np
import matplotlib.pyplot as plt
a = -1
b = -2
c = -15
x = np.arange(-10, 10, 0.01)
print(x)
print(type(x))
f = a * x ** 2 + b * x + c
print(f)
print(type(f))
plt.plot(x, f,
color="g",
marker="*",
linestyle="--")
plt.xlabel("x")
plt.ylabel("f")
plt.title("Função Quadrática")
plt.grid()
plt.savefig("plot_funcao_quadratica_example.png")
plt.show()
|
import math as mt
x = float(input("Digitar o valor da tangente: "))
n = int(input("Digitar o valor para a quantidade de termos da séria Taylor-MacLaurin: "))
inicio = 1
passo = 2
radianos = 0
k = 2 #variável auxiliar para alternar o valor do sinal do coeficiente
"""
O parâmetro final 2 * n é para dar a posssibilidade
de calcular até o expoente 19, já que o passo é de 2
"""
for i in range(inicio, 2 * n, passo):
coeficiente = ((-1) ** k)
radianos = radianos + coeficiente * x ** i
k = k + i
print("O valor do ângulo(rad) é de: " + str(radianos) + " rad")
graus = radianos * 180 / mt.pi
print("O valor do ângulo(graus) é de: " + str(graus) + " graus") |
r = range(10)
print(r) # Python 3 range(0, 10) Lazy evaluation
# Python 2.x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(r[3]) # 3
"""
# Python 2.x
r = xrange(10)
print(r) # xrange(10)
lst = [x for x in r]
print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
numbers = range(10)
iterator = iter(numbers)
print(numbers) # range(0, 10)
print(list(numbers)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(iterator) # <range_iterator object at 0x0000018AE309E770>
print(next(iterator)) # 0
print(next(iterator)) # 1
new_iter = iter(numbers)
print(new_iter) # <range_iterator object at 0x0000018AE303C4D0>
print(next(new_iter)) # 0
print(next(new_iter)) # 1
print(next(new_iter)) # 2
|
# -*- coding: utf-8 -*-
"""
Lecture 3 - Introduction into AI Programming with Python
@author: Dominik Jung (dominik.jung42@gmail.com)
"""
# Dataframes with pandas
import pandas as pd
speed = [290, 330, 345]
car = [718, 911, 918]
df = pd.DataFrame()
df["CAR"] = car
df["SPEED"] = speed
df.loc[1:]
df.loc[2]
df.loc[:, 'CAR']
df.loc[1:2, 'CAR':'SPEED']
|
# 입력 값을 변수 두개에 저장하기
a, b = input('문자열 두개를 입력하세요: ').split()
print(a)
print(b)
a = int(a)
b = int(b)
print(a + b)
print(int(a) + int(b))
a, b = map(int, input('숫자 두 개를 입력하세요: ').split())
print(a + b)
|
grade = int(input())
if grade >= 90:
print("A")
elif grade <90 and grade >=80:
print("B")
elif grade <80 and grade >= 70:
print("C")
elif grade <70 and grade >= 60:
print("D")
elif grade <60:
print("F")
|
def outerfunc(a,b):
def innerfunc():
sum=a+b
return sum
moresum = innerfunc()+8
return moresum
result = outerfunc(5,10)
print(result) |
#CSI31 Sabina Akter convert.py
#A program to convert Celsius temps to Fahrenheit
def intro ():
print("This program converts Celsius tempurature to fahrenheit tempurature.")
print()
return
def main():
intro()
for i in range(5):
celsius= eval(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees Fahrenheit.")
print()
main()
"""
This program converts Celsius tempurature to fahrenheit tempurature.
What is the Celsius temperature? 10
The temperature is 50.0 degrees Fahrenheit.
What is the Celsius temperature? 20
The temperature is 68.0 degrees Fahrenheit.
What is the Celsius temperature? 30
The temperature is 86.0 degrees Fahrenheit.
What is the Celsius temperature? 40
The temperature is 104.0 degrees Fahrenheit.
What is the Celsius temperature? 50
The temperature is 122.0 degrees Fahrenheit.
"""
|
#CSI31 Sabina Akter convert.py
#A program to converts distances measured in kilometers to miles
def intro ():
print("This program converts kilometer to miles.")
print()
return
def main():
intro()
k = eval(input(" What is the distance in kilometers?"))
m= 0.62* k
print()
print("The distance is ",m,"miles")
main()
"""
This program converts kilometer to miles.
What is the distance in kilometers?200
The distance is 124.0 miles
"""
|
"""JonathanBalewiczA2Q1
COMP 1012 SECTION A01
INSTRUCTOR Bristow
ASSIGNMENT: A2 Question 1
AUTHOR Jonathan Balewicz
VERSION 2018-02-03
PURPOSE: Calculate Statistics of the average dietary energy supply adequacy percentage
"""
mean=0
entries=0
print("Summarizing <foodData.csv>")
file=open("foodData.csv")
headers=file.readline()
rows=file.readlines()
numbers2015=[]
numbers2008=[]
numbers2000=[]
for row in rows:
columns=row.split(",")
if (columns[0]!="" and columns[1]!="" and columns[2]!=""):#any rows with incomplete data are excluded
num2015=float(columns[0]) #temporary placeholders for row values
num2008=float(columns[1])
try: #prevents error in the case that the third row cannot be a float
num2000=float(columns[2])
numbers2000.append(num2000)
except ValueError:
c=0 #do nothing on error
numbers2015.append(num2015) #numbers2015 is the list of numbers in 2015
numbers2008.append(num2008)
entries+=1 # increment the number of entries
sum2000=0
sum2008=0
sum2015=0
# adds up the numbers
for num in numbers2000:
sum2000+=num
for num in numbers2008:
sum2008+=num
for num in numbers2015:
sum2015+=num
#mean calculation
mean2000=sum2000/entries
mean2008=sum2008/entries
mean2015=sum2015/entries
#sorts the numbers
numbers2000=sorted(numbers2000)
numbers2008=sorted(numbers2008)
numbers2015=sorted(numbers2015)
if entries%2==0:#checks if the number of entries is even
middle1=int((entries)/2-0.5)#finds the lower middle entry
middle2=int((entries)/2+0.5)#finds the upper middle entry
median2000=(numbers2000[middle1]+numbers2000[middle2])/2 #calculates the median
median2008=(numbers2008[middle1]+numbers2008[middle2])/2
median2015=(numbers2015[middle1]+numbers2015[middle2])/2
else: #if the number of entries is odd, the middle value is used
middle=int((entries-1)/2)
median2000=numbers2000[middle]
median2008=numbers2008[middle]
median2015=numbers2015[middle]
#calculates the minimum values
min2000=min(numbers2000)
min2008=min(numbers2008)
min2015=min(numbers2015)
#calculates the maximum values
max2000=max(numbers2000)
max2008=max(numbers2008)
max2015=max(numbers2015)
#calculates the range of values
range2000=max2000-min2000
range2008=max2008-min2008
range2015=max2015-min2015
#print the results
print("2000")
print("\tMean: {:.2f}".format(mean2000))
print("\tMedian: {:.2f}".format(median2000))
print("\tMinimum: {}".format(int(min2000)))
print("\tMaximum: {}".format(int(max2000)))
print("\tRange: {}".format(int(range2000)))
print("\n2008")
print("\tMean: {:.2f}".format(mean2008))
print("\tMedian: {:.2f}".format(median2008))
print("\tMinimum: {}".format(int(min2008)))
print("\tMaximum: {}".format(int(max2008)))
print("\tRange: {}".format(int(range2008)))
print("\n2015")
print("\tMean: {:.2f}".format(mean2015))
print("\tMedian: {:.2f}".format(median2015))
print("\tMinimum: {}".format(int(min2015)))
print("\tMaximum: {}".format(int(max2015)))
print("\tRange: {}".format(int(range2015)))
import time
print("\nProgrammed by the Jonathan Balewicz")
print("Date: "+time.ctime())
print("End of processing") |
- Python Lesson 1 -
By Karl Brown
Here is a series of shorthand tutorials to help individuals learn Python. I will be improving them as more individuals attempt them, and extending them as interest forces me to reach the end of my lessons.
- Tools -
http://learnpython.org/ - Guide that helps me progress my lessons
http://notepad-plus-plus.org/ - Good way to view code in Windows
http://repl.it/ - Way to view the code you write online (Python Interpreter)
http://www.cheatography.com/davechild/cheat-sheets/python/ - Cheat Sheet (for experienced users)
- Guide for Lesson 1 -
http://learnpython.org/en/Hello%2C_World%21 - Site with Guide
- My additional write-up -
Variables in real life: someone says "hey , lets go to dinner at 5:00 pm"
The computer must save the data somehow
A variable is means of saving that data, just like the human brain remembers sentences, numbers, etc
So 'hey, lets go to dinner at 5:00 pm' would be a string. it could have the name 'karlconvo' set to the value of the following characters 'hey, lets go to dinner at 5:00 pm'
If you asked me what time dinner was, and I said 5pm, it could be an integer with the name 'dinnertime' set to the value of '5'
If you asked what time dinner was and you said 5:15 pm, the time could be stored as a float named "dinnertime" with the value '5.15' (if you so choose to store it that way)
Alternatively, you could use 17.15 as it is pm and the day is 24 hours
Integers are whole numbers, floats can have decimals
Everything is an object in python, including variables.
Quotes are how the computer can tell if you are typing in code to be interpretted (typing in code) or just typing it text to be set to a value (setting a string, using text humans understand not code)
HW#1
customized hello world - Print a string that says "Although a teacher can be nice, we know the internet is the best tool"
|
class Agent():
# return an index of a chosen move
def move(self, state):
return NotImplementedError('Class {} does not implement move()'.format(self.__class__.__name__))
# return a list of valid indices
def valid_moves(self, state):
valid = []
for i in range(0, 8):
if state[i] > 0:
valid.append(i)
return valid |
def judge_sum(non_a_sum, a_num):
if a_num == 0:
return non_a_sum, 0
else:
maxsum = non_a_sum + a_num
need_eleven = 0
# 尝试所有A能否取11
for i in range(a_num + 1):
temp = non_a_sum + i * 11 + (a_num - i)
if temp > 21:
break
if temp > maxsum:
maxsum = temp
need_eleven = i
return maxsum, need_eleven
class Card:
def __init__(self, suit, num):
self.suit = suit
self.realnum = num
if '2' <= num <= '9':
self.num = int(num)
elif num == '10' or num == 'J' or num == 'Q' or num == 'K':
self.num = 10
else:
self.num = 0
def __str__(self):
return self.suit + self.realnum
class Hand:
def __init__(self):
self.card = []
self.cardnum = 0
self.non_a_sum = 0
self.sum = 0
self.a_num = 0
self.ten_num = 0
self.a = 0
def addcard(self, card):
self.card.append(card)
self.cardnum += 1
if card.num == 0:
self.a_num += 1
else:
self.non_a_sum += card.num
if card.num == 10:
self.ten_num += 1
self.sum, self.a = judge_sum(self.non_a_sum, self.a_num)
suittype = {'Spade': 1, 'Heart': 2, 'Diamond': 3, 'Club': 4}
realnum = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13}
mycard = Hand()
for i in range(2):
suit, num = input().split()
card = Card(suit, num)
mycard.addcard(card)
while True:
if mycard.sum < 17:
print('Hit')
suit, num = input().split()
card = Card(suit, num)
if card.num == 0:
print(suit, '1 11')
else:
print(suit, str(card.num))
mycard.addcard(card)
else:
print('Stand')
mycard.card = sorted(mycard.card, key=lambda x: (realnum[x.realnum], suittype[x.suit]))
for card in mycard.card:
print(f'{card}', end=' ')
print()
if mycard.sum > 21:
print('Bust')
elif mycard.ten_num > 0 and mycard.a > 0:
print('Blackjack')
else:
print(mycard.sum)
break
|
number = int(input())
command = []
for i in range(number):
command.append(input())
command.sort()
test = input()
for item in command:
if item[0:len(test)] == test:
print(item) |
names={'Mike':95, 'Bob':77, 'Ken':89}
print(names)
print(names['Bob'])
#用key赋值
names['Adam']=67
print(names)
#刷新
names['Adam']=68
print(names)
#key不存在的情况
if 'Thomas'in names:
print(names['Thomas'])
print(names.get('Thomas'))
print(names.get('Thomas', -1))
#删除key
print(names)
print(names.pop('Bob'))
print(names) |
number = 0
number = int(input())
students = {}
while number != 0:
temp = input().split()
choice = int(temp[0])
if choice == 1:
if temp[1] in students:
print('Students already exist')
else:
students[temp[1]] = (temp[2], int(temp[3]), int(temp[4]), int(temp[5]))
print('Add success')
elif choice == 2:
if temp[1] in students:
students.pop(temp[1])
print('Delete success')
else:
print('Students do not exist')
elif choice == 3:
if temp[1] in students:
students[temp[1]] = (students[temp[1]][0], int(temp[2]), int(temp[3]), int(temp[4]))
print('Update success')
else:
print('Students do not exist')
else:
if temp[1] in students:
print('Student ID:'+temp[1])
print('Name:'+students[temp[1]][0])
score = students[temp[1]][1] + students[temp[1]][2] + students[temp[1]][3]
print('Average Score:%.1f'%(score/3))
else:
print('Students do not exist')
number -= 1 |
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print('Restaurant\'s name is: ' + self.restaurant_name + '\nCuisine_type is: ' + self.cuisine_type)
def open_restaurant(self):
print(self.restaurant_name.title() + ' is open!')
def set_number_served(self, number_served):
if number_served >= self.number_served:
self.number_served = number_served
else:
print('You can`t decrease number of people been served')
def increment_number_served(self, inc_number_served):
if inc_number_served > 0:
self.number_served += inc_number_served
else:
print('You can`t decrease number of people been served')
def get_number_served(self):
print('Restaurant has served ' + str(self.number_served) + ' peoples!')
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type, *flavors):
super().__init__(restaurant_name, cuisine_type) # 父类初始化必须显式调用
self.flavors = flavors
def show_flavors(self):
print(self.flavors)
class Teacher:
"""定义一个老师类"""
profession = 'education' # 类的属性
# 先__new__,再__init__;前者是有默认实现的
def __init__(self, name):
self.__name = name # 实例的属性
def show_info(self):
return 'This is a teacher'
print(Teacher.__doc__)
print(Teacher.profession)
print(Teacher.show_info) # 类的方法返回函数的地址:<function Teacher.show_info at 0x000002452CEA2950>
# print(Teacher.show_info()) # 报错,不能用实例的方法
wang = Teacher('Wang')
# print(wang.name)
print(wang.__name) # 对私有属性有保护,会说没有该属性,外界被屏蔽
print(wang._Teacher__name) # 绕过对私有属性的保护
my_restaurant = Restaurant('qianye', 'yun')
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
my_restaurant.set_number_served(20)
my_restaurant.get_number_served()
my_restaurant.increment_number_served(10)
my_restaurant.get_number_served()
flavors = ['Apple', 'Orange']
my_icecreamr = IceCreamStand('qianye', 'yun', *flavors)
my_icecreamr.show_flavors() |
#########################################################
# Fred14 Setup the Left Arm Servos
#########################################################
# We will be using the following services:
# Servo Service
#########################################################
# I Fred's Left Arm, we have the Bicep Rotator, the Elbow,
# the Wrist and the five fingures.
# You know it's just like the Right Arm
# Lets start with the Bicep Rotator.
# All service are created using the Runtime Service.
leftBicep = Runtime.createAndStart("leftBicep", "Servo")
# Next we need to attach ther servo Service to a Controller Service, in this case it will be the head
# Adafruit16ChServoDriver. We also need to tell the Servo Service which pin on the controller
# the servo is connected to, in this case pin 15
leftBicep.attach(leftArm,15)
# Now we tell the Servo Service about our servos limits, in some cases if the servo goes to far, things will break
leftBicep.setMinMax(0,180)
# This allows you to map the input to the Servo service to an actual servo position output
leftBicep.map(0,180,1,180)
# there is a rest command that can be issued to the servo,
# when that happens, this is the position that the servo will go to
leftBicep.setRest(90)
# if your servo run backwards, then set this to true in order to reverse it.
leftBicep.setInverted(False)
# degrees per second rotational velocity, setting -1 will set the speed to the servo's default
leftBicep.setVelocity(60)
# this allows the Servo Sevice to turn off the motor when it has reached the target position.
# the major advantage to this is the servos will use less power and have a lower chance of buring out.
leftBicep.setAutoDisable(UseAuto)
# Ok now that we have fully defined the headX servo lets make sure it is in the rest position.
leftBicep.rest()
# commands not used here but will be in other parts on the program are the following:
# leftBicep.moveTo(x) where x is the position you want move to.
# leftBicep.moveToBlockig(x) as above except execution of the program will pause until the position is reached.
# leftBicep.disable() will turn off the servo without unloading the service.
# leftBicep.enable() the oposite of disable will turn the servo back on after being disabled.
# disable and enable are not required if setAutoDisable is set to True
# For each servo that we have, we need to create a Servo Service, so this will be a process
# of repeating what we did above for each servo just using a diferent object name.
leftElbow = Runtime.createAndStart("leftElbow", "Servo")
leftElbow.attach(leftArm,14)
leftElbow.setMinMax(0,180)
leftElbow.map(0,180,1,180)
leftElbow.setRest(90)
leftElbow.setInverted(False)
leftElbow.setVelocity(60)
leftElbow.setAutoDisable(UseAuto)
leftElbow.rest()
leftWrist = Runtime.createAndStart("leftWrist", "Servo")
leftWrist.attach(leftArm,0)
leftWrist.setMinMax(0,180)
leftWrist.map(0,180,1,180)
leftWrist.setRest(90)
leftWrist.setInverted(False)
leftWrist.setVelocity(60)
leftWrist.setAutoDisable(UseAuto)
leftWrist.rest()
leftThumb = Runtime.createAndStart("leftThumb", "Servo")
leftThumb.attach(leftArm,1)
leftThumb.setMinMax(0,180)
leftThumb.map(0,180,1,180)
leftThumb.setRest(90)
leftThumb.setInverted(False)
leftThumb.setVelocity(60)
leftThumb.setAutoDisable(UseAuto)
leftThumb.rest()
leftIndex = Runtime.createAndStart("leftIndex", "Servo")
leftIndex.attach(leftArm,2)
leftIndex.setMinMax(0,180)
leftIndex.map(0,180,1,180)
leftIndex.setRest(90)
leftIndex.setInverted(False)
leftIndex.setVelocity(60)
leftIndex.setAutoDisable(UseAuto)
leftIndex.rest()
leftMajure = Runtime.createAndStart("leftMajure", "Servo")
leftMajure.attach(leftArm,3)
leftMajure.setMinMax(0,180)
leftMajure.map(0,180,1,180)
leftMajure.setRest(90)
leftMajure.setInverted(False)
leftMajure.setVelocity(60)
leftMajure.setAutoDisable(UseAuto)
leftMajure.rest()
leftRing = Runtime.createAndStart("leftRing", "Servo")
leftRing.attach(leftArm,4)
leftRing.setMinMax(0,180)
leftRing.map(0,180,1,180)
leftRing.setRest(90)
leftRing.setInverted(False)
leftRing.setVelocity(60)
leftRing.setAutoDisable(UseAuto)
leftRing.rest()
leftLittle = Runtime.createAndStart("leftLittle", "Servo")
leftLittle.attach(leftArm,5)
leftLittle.setMinMax(0,180)
leftLittle.map(0,180,1,180)
leftLittle.setRest(90)
leftLittle.setInverted(False)
leftLittle.setVelocity(60)
leftLittle.setAutoDisable(UseAuto)
leftLittle.rest()
|
from cs50 import get_int
height = get_int("height: ")
while True:
if height > 0 and height <= 8:
break
else:
height = get_int("height: ")
line = height
while (line != 0):
for l in range(line - 1):
print(" ", end="")
for j in range(height - (line - 1)):
print("#", end="")
for i in range(2):
print(" ", end="")
for k in range(height - (line - 1)):
print("#", end="")
print()
line -= 1 |
first = float(input("Enter first Number => "))
sec = float(input("Enter Second Number => "))
opr = str(input("Enter Operation (+, -, *, /) => "))
if opr == "+":
total = first + sec
elif opr == "-":
total = first - sec
elif opr == "*":
total = first * sec
elif opr == "/":
total = first / sec
else:
total = str("Please Enter a Valid Operation")
print (total) |
class Employee:
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
# method
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
# instance variable
emp_1 = Employee('Farhana', 'Afrin', 50000)
emp_2 = Employee('Yousra', 'Afrin', 50000)
emp_1.raise_amount = 6.00
print(emp_1.__dict__)
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
|
#sets: A set is an unordered collection with no duplicate elements
#membership testing and eliminating duplicate entries
showroom = {'Acura', 'BMW', 'Honda', 'Toyota'}
print(len(showroom))
print("----------Showroom Length---------------")
showroom.add('Acura')
print(showroom)
print("----------Showroom Add Acura---------------")
showroom.update(['Mercedes', 'Ford'])
print(showroom)
print("----------Showroom Updated Mercedes & Ford---------------")
showroom.discard('Mercedes')
print(showroom)
print("----------Mercedes Deleted Mercedes---------------")
junkyard = {'Acura', 'Honda', 'Cadillac', 'Volkswagon', 'Nissan', 'Kia'}
print(junkyard)
print("----------Junkyard Created---------------")
new_showroom = showroom.intersection(junkyard)
print(new_showroom)
print("--------Junkyard Intersect Showroom-----------------")
updated_showroom = showroom.symmetric_difference(junkyard)
print(updated_showroom)
print("--------difference of both showroom and junkyard-----------------")
final_showroom = updated_showroom.union(new_showroom)
print(final_showroom)
print("--------combined inventory with union without dupes-----------------")
final_showroom.discard('Kia')
print(final_showroom)
print("--------deleted inventory not needed-----------------")
|
def function1():
print "Hi. I'm function 1."
def function2():
print "Hi. I'm function 2."
def function3():
print "Hi. I'm function 3"
def error_function():
print "Invalid Option"
def test1():
while 1:
code = raw_input('Enter "one", "two", "three", or "quit": ')
if code=='quit':
break
if code == 'one':
function1()
elif code == 'two':
function2()
elif code == 'three':
function3()
else:
error_function()
def test2():
mapper = {'one': function1, 'two': function2, 'three': function3}
while 1:
code = raw_input('Enter "one", "two", "three", or "quit": ')
if code == 'quit':
break
func = mapper.get(code,error_function)
func()
def test():
test1()
print '-' * 50
test2()
if __name__=='__main__':
test() |
import os
# VALIDOR EN CONSUMO DE GOLOSINAS
# MOSTRAR VALORES
catidad_caramelos=0
precio_caramelo=0.0
cantidad_chupetines=0
precio_chupetin=0.0
cantidad_galletas=0
precio_galleta=0.0
# INPUT
catidad_caramelos=int(os.sys.argv[1])
precio_caramelo=float(os.sys.argv[2])
cantidad_chupetines=int(os.sys.argv[3])
precio_chupetin=float(os.sys.argv[4])
cantidad_galletas=int(os.sys.argv[5])
precio_galleta=float(os.sys.argv[6])
# PROCESSING
consumo=(catidad_caramelos*precio_caramelo)+(cantidad_chupetines*precio_chupetin)+(cantidad_galletas*precio_galleta)
# OUTPUT
print(catidad_caramelos)
print(precio_caramelo)
print(cantidad_chupetines)
print(precio_chupetin)
print(cantidad_galletas)
print(precio_galleta)
print("total=", consumo)
# CONDICIONAL MULTIPLE
# si el niño consume de acuerdo a las condiciones multiples se cumple que
if(consumo>5 and consumo<15.5):
print("GRACIAS POR COMPRAR")
if(consumo>15.5 and consumo<30.5):
print("CASI GANAS")
if(consumo>30.5 and consumo<50.5):
print("GANATES EL CONSUMO DE GOLOSINAS GRATIS POR UN DIA")
if(consumo>=50.5):
print("FELICITACIONES GANASTES EL CONSUMO DE GOLOSINAS GRATIS POR DOS DIAS")
# fin_if
|
import os
# VALIDOR EN TRIANGULO RECTANGULO
# MOSTRAR VALORES
cat1=0.0
cat2=0.0
# INPUT
cat1=float(os.sys.argv[1])
cat2=float(os.sys.argv[2])
# OUTPUT
print(cat1)
print(cat2)
# PROCESSING
import math
hipotenusa= math.sqrt(cat1**2+cat2**2)
print("hipotenusa=", hipotenusa)
# CONDICIONAL MULTIPLE
# si en la hipotenusa cumplen las siguientes condiciones el triangulo es
if(hipotenusa>10.0 and hipotenusa<20.0):
print("el triangulo rectangulo es pequeño")
if(hipotenusa>20.0 and hipotenusa<30.5):
print("el triangulo rectangulo es regular")
if(hipotenusa>=30.5):
print("el triangulo rectangulo es muy grande")
# fin_if
|
import os
# MOSTRAR VALORES
nombre=""
t_grado_fahrenheit=0.0
# INPUT
nombre=os.sys.argv[1]
t_grado_fahrenheit=float(os.sys.argv[2])
# OUTPUT
print("################################")
print(" TEMPERATURA DE UNA PERSONA ")
print("################################")
print("NOMBRE:", nombre)
print("TEMPERATURA EN GRADO FAHRENHEIT:", t_grado_fahrenheit)
print("################################")
# CONDICION MULTIPLE
# la temperatura de una persona con la siguiente condicion multiple
if(t_grado_fahrenheit>40.0):
print("peligro de muerte")
if(t_grado_fahrenheit>38.1 and t_grado_fahrenheit<39):
print("tiene fiebre alta")
if(t_grado_fahrenheit>37.8 and t_grado_fahrenheit<38.0):
print("tiene fiebre")
if(t_grado_fahrenheit<37.0):
print("temperatura normal")
# fin_if
|
import os
# TRIANGULO RECTANGULO
# MOSTRAR VALORES
cat1=0.0
cat2=0.0
# INPUT
cat1=float(os.sys.argv[1])
cat2=float(os.sys.argv[2])
# PROCESSING
import math
hipotenusa= math.sqrt(cat1**2+cat2**2)
# OUTPUT
print(cat1)
print(cat2)
# VERIFICADOR
triangulo=(hipotenusa>6.0)
# CONDICION DOBLE
# si el la hipotenusa es mayor que 6 es muy grande
if(triangulo==True):
print("ES GRANDE")
else:
print("ES PEQUEÑO")
# fin_if
|
import os
# ASISTENCIAS A CLASES
# MOSTRAR VALORES
estudiante=""
asistencia1=0
asistencia2=0
asistencia3=0
asistencia4=0
asistencia5=0
asistencia6=0
asistencia7=0
asistencia8=0
# INPUT
estudiante=os.sys.argv[1]
asistencia1=int(os.sys.argv[2])
asistencia2=int(os.sys.argv[2])
asistencia3=int(os.sys.argv[2])
asistencia4=int(os.sys.argv[2])
asistencia5=int(os.sys.argv[6])
asistencia6=int(os.sys.argv[6])
asistencia7=int(os.sys.argv[7])
asistencia8=int(os.sys.argv[8])
# OUTPUT
print(estudiante)
print(asistencia1)
print(asistencia2)
print(asistencia3)
print(asistencia4)
print(asistencia5)
print(asistencia6)
print(asistencia7)
print(asistencia8)
# PROCESSING
total=(asistencia1+asistencia2+asistencia3+asistencia4+asistencia5+asistencia6+asistencia7+asistencia8)
# VERIFICADOR
verificador=(total>=60)
# CONDICION SIMPLE
# si el total de asistencias es mayor o igual que 15 es un estudiante responsable
if(verificador==True):
print("eres muy responsable")
# fin_if
|
import speech_recognition as sr
from time import ctime
import time
import os
from gtts import gTTS
def speak(audioString):
print(audioString)
tts = gTTS(text=audioString, lang='en')
tts.save("audio.mp3")
os.system("mpg321 audio.mp3")
def recordAudio():
# Record Audio
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source)
data = ""
try:
data = r.recognize_google(audio)
print("You said: " + data)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
return data
def jarvis(data):
if "how are you" in data:
speak("I am fine")
if "who are you" in data:
speak("I am your assistant")
if "time now" in data:
speak(ctime())
if "where is" in data:
data = data.split(" ")
location = data[2]
speak("Hold on, I will show you where " + location + " is.")
os.system("google-chrome https://www.google.nl/maps/place/" + location + "/&")
if "exit" in data:
exit()
time.sleep(1)
speak("Hi tamil, what can I do for you?")
while 1:
data = recordAudio()
jarvis(data)
|
lista=[]
num1=int(input( " digite um numero"))
lista.append(num1)
num2=int(input(" digite outro numero"))
lista.append(num2)
a= max(lista)
b= min(lista)
c = a%b
lista.append(c)
while lista[len(lista)-1] != 0:
d = lista[len(lista)-2] % lista[len(lista)-1]
lista.append(d)
print (" O Mdc entre %s e %s é %s " %(a,b,lista[len(lista)-2]))
|
import sys
from termcolor import colored, cprint
import time
import random
while True:
print("="*40)
print(" JOGO JUNKENPO - AUTOR -- dougras")
print("="*40)
a = int(input(" Digite \n\n 0 pedra \n 1 para papel \n 2 para tesoura\n"))
if a == 0 :
a = "pedra"
elif a == 1:
a = "papel"
elif a == 2 :
a = "tesoura"
print (" Você escolheu %s" %(a))
b = random.randint(0,2)
if b == 0 :
b = "pedra"
elif b == 1:
b = "papel"
elif b == 2 :
b = "tesoura"
print (" Eu escolhi %s" %(b))
for i in range (0,5):
print("-")
time.sleep(0.1)
if a == b:
print( " Deu empate")
elif a < b:
print (" você venceu")
elif a > b:
print(" PERDEU!")
|
# K-Nearest-Neighbor dient zur Klassifizierung (Algorithmus)
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from helper import plot_classifier
df = pd.read_csv("classification.csv")
# Welche Spalten sollen zur Vorhersage verwendet werden
y = df["success"].values
X = df[["age", "interest"]].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
model = KNeighborsClassifier(n_neighbors = 10) # n_neighbors default ist 5
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
# Trainings-Daten plotten
plot_classifier(model, X_train, y_train, proba = False, xlabel = "Alter", ylabel = "Interesse")
# Testdaten plotten
plot_classifier(model, X_test, y_test, proba = False, xlabel = "Alter", ylabel = "Interesse")
plot_classifier(model, X_train, y_train, proba = True, xlabel = "Alter", ylabel = "Interesse")
# weiß unsicher
# rot / blau sicher |
num=int(input('enter the number'))#564
result=0
while(num!=0):
digit=num%10#4
result=result*10+digit
num=num//10
print(result)
|
# limit=int(input('enter the limit'))
# lst=lst()
# for i in range(1,limit+1):
# lst.append(i)
# print(lst)
limit=int(input('enter the limit'))
lst1=list()
lst2=list()
for i in range(1,limit+1):
if (i%2==0):
lst1.append(i)
else:
lst2.append(i)
print(lst1,lst2) |
class person:
def person_1(self,name,age,gender):
self.name=name
self.age=age
self.gender=gender
def printperson(self):
print('name',self.name)
print('age',self.age)
print('gender',self.gender)
obj=person()
obj.person_1('ajay',24,'male')
obj.printperson()
obj1=person()
obj1.person_1('raju',34,'male')
obj1.printperson() |
num=int(input('enter num'))
def fact(num):
fact=1
for i in range(1,(num+1)):
fact=fact*i
print(fact)
fact(num) |
num=int(input('ENTER THE NUMBER'))
sum=0
i=1
res=0
while(i<=num):
res=num+10*res
sum+=res
i+=1
print(sum)
|
first=[1,2,3]
second=[4,5,6]
pairs=[(i,j) for i in first for j in second]
print(pairs)
#squares
squares=[i**2 for i in first]
print(squares)
#connditioning using list comprehension
fir=[1,2,3,4,5,6,7]
data=[i-1 if i<5 else i+1 for i in fir]
print(data)
#using elif
data=[i+1 if i>5 else i-1 if i<5 else 5 for i in fir ]
print(data)
#input matrix flatten operation
matrix=[[1,2,3],[4,5,6],[7,8,9]]
flat=[j for i in matrix for j in i]
print(flat) |
employees={101:{'empid':101,'name':'raju','designation':'mech','salary':15000},102:{'empid':102,'name':'ramu','designation':'mech','salary':25000},103:{'empid':103,'name':'riju','designation':'ec','salary':35000},104:{'empid':104,'name':'roju','designation':'eee','salary':10000}}
count=1
for i in employees:
# print(employees[i]['name'])
if 'experience' not in employees:
print('enter the experience of',count,'th employee')
n = int(input('enter here'))
employees[i]['experience']=n
print(employees[i])
i+=1
count+=1 |
"""
======================================================================================
Probability, Paradox, and the Reasonable Person Principle
http://nbviewer.jupyter.org/url/norvig.com/ipython/ProbabilityParadox.ipynb
Vocabulary:
P(E, D) The probability of event E, given probability distribution D describing the
complete sample space of possible outcomes.
Outcome What actually happens (like a die rolling a 6). Also called an atomic event.
Event A description of possibly several atomic events (like rolling an even number).
Sample space The set of possible outcomes.
Probability distribution
A mapping from every possible outcome to a number in the range 0 to 1 saying how
likely the outcome is.
Uniform distribution
A probability distribution in which every outcome is equally probable.
======================================================================================
"""
from fractions import Fraction
import random
from IPython.display import HTML
import matplotlib.pyplot as plt
from collections import Counter
def P(predicate, dist):
"""The probability that 'predicate' is true, given the probability distribution 'dist'."""
return sum(dist[e] for e in dist if predicate(e))
class ProbDist(dict):
"""A Probability Distribution; an {outcome: prob} mapping where probabilities sum to 1."""
def __init__(self, mapping=(), **kwargs):
self.update(mapping, **kwargs)
total = sum(self.values())
if isinstance(total, int):
total = Fraction(total, 1)
for key in self: # make probabilities sum to 1
self[key] = self[key] / total
def __and__(self, predicate): # call this method by writing 'probdist & predicate'
"""A new ProbDist, restricted to the outcomes of this ProbDist for which the
predicate is true."""
return ProbDist({e:self[e] for e in self if predicate(e)})
def Uniform(outcomes): return ProbDist({e:1 for e in outcomes})
def joint(A, B, sep=''):
"""The joint distribution of two independent probability distributions.
Result is all entries of the form {a+sep+b: P(a)*P(b)}"""
return ProbDist({a + sep + b: A[a] * B[b] for a in A for b in B})
#-------------------------------------------------------------------------------------
#
# Child Paradoxes
#
## Child Problem 1: Older child is a boy. What is the probability both are boys?
two_kids = Uniform({'BG', 'BB', 'GB', 'GG'})
def two_boys(outcome): return outcome.count('B') == 2
def older_is_a_boy(outcome): return outcome.startswith('B')
# print(P(two_boys, two_kids & older_is_a_boy)) # 1/2
## Child Problem 2: At least one is a boy. What is the probability both are boys?
def at_least_one_boy(outcome): return 'B' in outcome
# print(P(two_boys, two_kids & at_least_one_boy)) # 1/3
## Child Problem 2: Another interpretation.
two_kids_b = Uniform({'BB/b?', 'BB/?b', 'BG/b?', 'BG/?g', 'GB/g?', 'GB/?b', 'GG/g?', 'GG/?g'})
def observed_boy(outcome): return 'b' in outcome
# print(P(two_boys, two_kids_b & observed_boy)) # 1/2
## Child Problem 3: One is a boy born on Tuesday. What's the probability both are boys?
one_kid_w = joint(Uniform('BG'), Uniform('1234567'))
two_kids_w = joint(one_kid_w, one_kid_w)
# print(len(two_kids_w))
# print(random.sample(list(two_kids_w), 8))
# print(P(at_least_one_boy, two_kids)) # 3/4
# print(P(at_least_one_boy, two_kids_w)) # 3/4
# print(P(two_boys, two_kids)) # 1/4
# print(P(two_boys, two_kids_w)) # 1/4
# print(P(two_boys, two_kids & at_least_one_boy)) # 1/3
# print(P(two_boys, two_kids_w & at_least_one_boy)) # 1/3
def at_least_one_boy_tues(outcome): return 'B3' in outcome
# print(P(two_boys, two_kids_w & at_least_one_boy_tues)) # 13/27
## Child Problem 3: Another interpretation.
def observed_boy_tues(outcome): return 'b3' in outcome
two_kids_wb = Uniform({children + '/' + observation
for children in two_kids_w
for observation in (children[:2].lower()+'??', '??'+children[-2:].lower())})
# print(random.sample(list(two_kids_wb), 5))
# print(P(two_boys, two_kids_wb & observed_boy_tues))
#-------------------------------------------------------------------------------------
#
# The Sleeping Beauty Paradox
#
# Sleeping Beauty volunteers to undergo the following experiment and is told all of the following
# details: On Sunday she will be put to sleep. Then a fair coin will be tossed, to determine which
# experimental procedure to undertake:
#
# Heads: Beauty will be awakened and interviewed on Monday only.
# Tails: Beauty will be awakened and interviewed on Monday and Tuesday only.
#
# In all cases she is put back to sleep with an amnesia-inducing drug that makes her forget that
# awakening and sleep until the next one. In any case, she will be awakened on Wednesday without
# interview and the experiment ends. Any time Beauty is awakened and interviewed, she is asked,
# "What is your belief now for the proposition that the coin landed heads?"
#
beauty = Uniform({'heads/Monday/interviewed', 'heads/Tuesday/sleep',
'tails/Monday/interviewed', 'tails/Tuesday/interviewed'})
def t(property):
"""Return a predicate that is true of all outcomes that have 'property' as a substring."""
return lambda outcome: property in outcome
# print(P(t('heads'), beauty & t('interviewed')))
#-------------------------------------------------------------------------------------
#
# The Monty Hall Paradox
#
# Suppose you're on a game show, and you're given the choice of three doors: Behind one door is
# a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's
# behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you
# want to switch your choice to door No. 2?" Is it to your advantage to switch your choice?
#
monty = Uniform({'Car1/Lo/Pick1/Open2', 'Car1/Hi/Pick1/Open3',
'Car2/Lo/Pick1/Open3', 'Car2/Hi/Pick1/Open3',
'Car3/Lo/Pick1/Open2', 'Car3/Hi/Pick1/Open2'})
# print(P(t("Car1"), monty & t("Open3")))
# print(P(t("Car2"), monty & t("Open3")))
#-------------------------------------------------------------------------------------
#
# Reasoning with non-Uniform Probability Distributions
#
DK = ProbDist(GG=121801., GB=126840.,
BG=127123., BB=135138.)
## Child Problem 1 in DK
# print(P(two_boys, DK & older_is_a_boy))
## Child Problem 2 in DK
# print(P(two_boys, DK & at_least_one_boy))
## Child Problem 4. One is a boy born on Feb. 29. What is the probability both are boys?
sexes = ProbDist(B=51.5, G=48.5) # Probability distribution over sexes
days = ProbDist(L=1, N=4*365) # Probability distribution over Leap days and Non-leap days
child = joint(sexes, days) # Probability distribution for one child family
two_kids_L = joint(child, child) # Probability distribution for two-child family
# print(P(two_boys, two_kids_L & t('BL')))
#-------------------------------------------------------------------------------------
#
# The St. Petersburg Paradox
#
# A casino offers a game of chance for a single player in which a fair coin is tossed at each
# stage. The pot starts at 2 dollars and is doubled every time a head appears. The first time a
# tail appears, the game ends and the player wins whatever is in the pot. Thus the player wins
# 2 dollars if a tail appears on the first toss, 4 dollars if a head appears on the first toss
# and a tail on the second, etc. What is the expected value of this game to the player?
## Response 1: Limited Resources
def st_pete(limit):
"""Return the probability distribution for the St. Petersburg Paradox with a limited bank."""
P = {} # The probability distribution
pot = 2 # Amount of money in the pot
pr = 1/2. # Probability that you end up with the amount in pot
while pot < limit:
P[pot] = pr
pot = pot * 2
pr = pr / 2
P[limit] = pr * 2 # pr * 2 because you get limit for heads or tails
return ProbDist(P)
StP = st_pete(limit=10**8)
def EV(P):
"""The expected value of a probability distribution."""
return sum(P[v] * v for v in P)
# print(EV(StP))
## Response 2: Value of Money
def util(dollars, enough=1000):
"""The value of money: only half as valuable after you already have enough."""
if dollars < enough:
return dollars
else:
additional = dollars-enough
return enough + util(additional / 2, enough * 2)
# X = list(range(1000, 1000000, 10000))
# fig = plt.figure()
# plt.plot(X, [util(x) for x in X])
# fig.show()
def EU(P, U):
"""The expected utility of a probability distribution, given a utility function."""
return sum(P[e] * U(e) for e in P)
# print(EU(StP, util))
#-------------------------------------------------------------------------------------
#
# Understanding St. Petersburg through Simulation
#
def flip(): return random.choice(('head', 'tail'))
def simulate_st_pete(limit=10**9):
"""Simulate one round of the St. Petersburg game, and return the payoff."""
pot = 2
while flip() == 'head':
pot <<= 1
if pot > limit:
return limit
return pot
# random.seed(123456)
# c = Counter(simulate_st_pete() for _ in range(100000))
# results = ProbDist(c)
# print(EU(results, util), float(EV(results)))
## Plot the running average of repeated rounds
def running_averages(iterable):
"""For each element in the iterable, yield the mean of all elements seen so far."""
total, n = 0, 0
for x in iterable:
total, n = total + x, n + 1
yield total / n
def plot_running_averages(fn, n):
"""Plot the running average of calling the function n times."""
plt.plot(list(running_averages(fn() for _ in range(n))))
# random.seed('running')
# fig = plt.figure()
# plt.grid(True)
# for i in range(10):
# plot_running_averages(simulate_st_pete, 100000)
# fig.show()
#-------------------------------------------------------------------------------------
#
# The Ellsburg Paradox
#
# An urn contains 33 red balls and 66 other balls that are either black or yellow. You don't know
# the mix of black and yellow, just that they total 66. A single ball is drawn at random. You are
# given a choice between these two gambles:
#
# R: Win $100 for a red ball.
# B: Win $100 for a black ball.
#
# You are also given a choice between these two gambles:
#
# RY: Win $100 for a red or yellow ball.
# BY: Win $100 for a black or yellow ball.
#
def ellsburg():
fig = plt.figure()
show('R', 'r')
show('B', 'k')
show('RY', 'r--')
show('BY', 'k--')
plt.xlabel('Number of black balls')
plt.ylabel('Expected value of each gamble')
fig.show()
blacks = list(range(67))
urns = [Counter(R=33, B=b, Y=66-b) for b in blacks]
def show(colors, line):
scores = [score(colors, urn) for urn in urns]
plt.plot(blacks, scores, line)
def score(colors, urn): return sum(urn[c] for c in colors)
# ellsburg()
def avgscore(colors, urns):
return sum(score(colors, urn) for urn in urns) / len(urns)
def compare(urns):
for colors in ('R', 'B', 'RY', 'BY'):
print(colors.ljust(2), avgscore(colors, urns))
# compare(urns)
# print()
# compare(urns[:33] + 2 * urns[33:])
# print()
# compare(2 * urns[:33] + urns[33:])
def ellsburg2():
fig = plt.figure()
show2('R', 'r')
show2('B', 'k')
show2('RY', 'r--')
show2('BY', 'k--')
plt.xlabel('Different combinations of two urns')
plt.ylabel('Expected value of each gamble')
fig.show()
def show2(colors, line):
urnpairs = [(u1, u2) for u1 in urns for u2 in urns]
urnpairs.sort(key=lambda urns: avgscore('B', urns))
X = list(range(len(urnpairs)))
plt.plot(X, [avgscore(colors, urns) for urns in urnpairs], line)
# ellsburg2()
#-------------------------------------------------------------------------------------
#
# Simpson's Paradox
#
## Good and bad outcomes for kidney stone reatments A and B,
## each in two cases: [small_stones, large_stones]
A = dict(small=Counter(good=81., bad=6.), large=Counter(good=192., bad=71.))
B = dict(small=Counter(good=234., bad=36.), large=Counter(good=55., bad=25.))
def success(case): return ProbDist(case)['good']
# print(success(A['small']), success(B['small']))
# print(success(A['large']), success(B['large']))
# print(success(A['small'] + A['large']))
# print(success(B['small'] + B['large']))
## Batting averages for two baseball players
Jeter = {1995: Counter(hit=12, out=36), 1996: Counter(hit=183, out=399)}
Justice = {1995: Counter(hit=104, out=307), 1996: Counter(hit=45, out=95)}
def BA(case): "Batting average"; return round(float(ProbDist(case)['hit']), 3)
# print(BA(Jeter[1995]), BA(Justice[1995]))
# print(BA(Jeter[1996]), BA(Justice[1996]))
# print()
# print(BA(Jeter[1995] + Jeter[1996]))
# print(BA(Justice[1995] + Justice[1996]))
|
from collections import Counter, deque
import random
import matplotlib.pyplot as plt
from prob_intro import ProbDist
## The board: a list of the names of the 40 squares
## As specified by https://projecteuler.net/problem=84
board = """GO A1 CC1 A2 T1 R1 B1 CH1 B2 B3
JAIL C1 U1 C2 C3 R2 D1 CC2 D2 D3
FP E1 CH2 E2 E3 R3 F1 F2 U2 F3
G2J G1 G2 CC3 G3 R4 CH3 H1 T2 H2""".split()
def monopoly(steps):
"""Simulate given number of steps of Monopoly game,
yielding the number of the current square after each step."""
goto(0) # start at GO
CC_deck = Deck('GO JAIL' + 14 * ' ?')
CH_deck = Deck('GO JAIL C1 E3 H2 R1 R R U -3' + 6 * ' ?')
doubles = 0
jail = board.index('JAIL')
for _ in range(steps):
d1, d2 = random.randint(1, 6), random.randint(1, 6)
goto(here + d1 + d2)
doubles = (doubles + 1) if (d1 == d2) else 0
if doubles == 3 or board[here] == 'G2J':
goto(jail)
elif board[here].startswith('CC'):
do_card(CC_deck)
elif board[here].startswith('CH'):
do_card(CH_deck)
yield here
def goto(square):
"""Update the global variable 'here' to be square."""
global here
here = square % len(board)
def Deck(names):
"""Make a shuffle deck of cards, given a space-delimited string."""
cards = names.split()
random.shuffle(cards)
return deque(cards)
def do_card(deck):
"""Take the top card from deck and do what it says."""
global here
card = deck[0] # The top card
deck.rotate(-1) # Move top card to bottom of deck
if card == 'R' or card == 'U':
while not board[here].startswith(card):
goto(here + 1) # Advance to next railroad or utility
elif card == '-3':
goto(here - 3) # Go back 3 spaces
elif card != '?':
goto(board.index(card)) # Go to destination named on card
results = list(monopoly(400000))
spaces_stats = list(0 for _ in range(40))
for v in results:
spaces_stats[v] += 1
## Graph the results
plt.figure(figsize=(14,7))
plt.bar(range(40), spaces_stats)
avg = len(results) / 40
plt.plot([-0.5, 39.5], [avg, avg], 'r--');
plt.xticks(range(40), board)
plt.savefig('monopoly')
## Show the results as a ProbDist
print(ProbDist(Counter(board[i] for i in results)))
|
def memoize(f):
value = None
has_value = False
def memoized():
nonlocal value, has_value
if has_value:
return value
value = f()
has_value = True
return value
return memoized
|
#Dictionary to store the roman numerals and arabic equivalents
roman = {'I':1, 'V':5, 'X': 10, 'L':50, 'C':100, 'D':500,'M':1000}
print("This takes a user input Roman numeral and converts to equivalent Arabic Numeral")
conv = list(input("\nEnter Roman Numeral to convert [ROMAN NUMERAL IN ALL CAPS]! \n"))
sum = 0
for index,numeral in enumerate(conv):
if (index+1) == len(conv) or roman[conv[index]] >= roman[conv[index+1]]:
#print(index+1)
sum += roman[numeral]
else:
sum -= roman[numeral]
print(sum)
|
l = [1,5,2,8,5,8,3,3,10,11] # to test
def merge(arr, l, mid, r):
n1 = mid -l +1
n2 = r - mid
#cretae temp arrays
L = [0 for i in range(n1)]
R = [0 for i in range(n2)]
#copy data to L and R
for i in range(0, n1):
L[i] = arr[l+i]
for i in range(0, n2):
R[i] = arr[mid+1+i]
# Merge temp arrays back
i=0
j=0
k=l
while i <n1 and j < n2:
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1
# Copy the remaining elements to arr
while i < n1:
arr[k] = L[i]
i+=1
k+=1
while i < n1:
arr[k] = R[j]
j+=1
k+=1
def merge_sort(arr, l, r):
if l<r:
mid = (l+r)//2
merge_sort(arr, l, mid)
merge_sort(arr, mid+1, r)
merge(arr, l, mid, r)
return arr
merge_sort(l, 0, len(l)-1)
print(merge_sort(l, 0, len(l)-1)) # prints [1,2,3,3,5,5,8,8,10,11]
|
name = input("name:")
age=int(input("age:"))
#下行出错 age是数字型,不能与字符串相加
#print("Information of Name "+name+" \nName:"+name+"\nAge:"+age)
print("Information of Name %s \nName:%s\nAge:%s" %(name,name,age))
msg = '''
Information of Name %s
Name:%s
Age:%d
''' %(name,name,age)
print(msg)
msg = '''
Information of Name %s
Name:%s
Age:%d
''' % (name.strip(), name.strip(), age)
print("Strip 去前后字符,默认空格:%s" %msg) |
def find_number_of_bits(number: int) -> int:
bits = 0
while number:
number >>= 1
bits += 1
return bits |
import random
import warnings
warnings.filterwarnings("ignore")
# rand_arr=[]
rand_arr = [5,4,3,2,1]
# for _ in range(100):
# rand_arr.append(random.uniform(0.0,1.0))
ctr_swap=0
ctr_comp=0
def insertion(arr):
for index in range(1,len(arr)):
currentvalue = arr[index]
position = index
while position>0 and arr[position-1]>currentvalue:
arr[position]=arr[position-1]
position = position-1
global ctr_comp
ctr_comp += 1
arr[position]=currentvalue
global ctr_swap
ctr_swap+=1
sel_swap=0
sel_comp=0
def selection(A):
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
global sel_comp
sel_comp+=1
A[i], A[min_idx] = A[min_idx], A[i]
global sel_swap
sel_swap+=1
merge_comp=0
merge_swap=0
def mergeSort(alist):
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
global merge_comp
merge_comp =merge_comp+1
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
insertion(rand_arr)
selection(rand_arr)
mergeSort(rand_arr)
# print(rand_arr)
# comp=0
# comp_2=0
# comp_3=0
# for i in range(20):
# for _ in range(10):
# rand_arr.append(random.uniform(0.0,1.0))
# selection(rand_arr)
# insertion(rand_arr)
# mergeSort(rand_arr)
# global sel_comp
# global ctr_swap
# global merge_comp
# comp+=sel_comp
# comp_2+=ctr_swap
# comp_3+=merge_comp
# sel_comp=0
# ctr_comp=0
# merge_comp=0
# print(comp/10000)
# print(comp_2/100)
# print(comp_3/100)
print("Insertion Compare: " + str(ctr_comp))
print("Selection Swap = " + str(ctr_swap) + " Selection Compare: " + str(sel_comp))
print("Merge Compare: " + str(merge_comp))
# print(sel_swap, sel_comp)
# print(merge_comp, merge_swap)
|
"""
Name : Raghav Dev Kukreti
Group : B1
Roll No : 2017082
Python code to calculate rank of a matrix.
"""
# Formulate the matrix of dimension MxN
def create_matrix(m, n):
matrix = []
for i in range(0,m):
matrix.append([])
for j in range(0,n):
matrix[i].append(int(input('Enter element at (' + str(i) + ', ' + str(j) + '): ')))
return matrix
# Function to swap rows
def swap_rows(a, row1, row2):
# swap rows
for i in range(len(a)):
temp=a[row1][i]
a[row1][i]=a[row2][i]
a[row2][i]=temp
return(a)
# Function to carry out row transformation
def row_transform(a, x, row1, row2):
for i in range(len(a)):
a[row2][i] = a[row2][i] + x*a[row1][i]
return(a)
# Finds rank through RR method
def find_rank(a):
col=len(a[1])
row=len(a)
if(row < col):
rank = row
else:
rank = col
if (row>col):
temp_arr=[]
for m in range(col):
row_arr=[]
for n in range(row):
row_arr.append(a[n][m])
temp_arr.append(row_arr)
a=temp_arr
col,row=row,col
# https://1movies.online/movie/pearl-harbor/6452-watch-online-free.html
for i in range(rank):
if a[i][i]!=0:
for j in range(i+1,row):
a = row_transform(a,-(a[j][i]//a[i][i]),i,j)
else:
ctr=1
for k in range(i+1,row):
if a[k][i]!=0:
a=swap_rows(a,i,k)
ctr=0
break
else:
pass
if(ctr==1):
for m in range(row):
a[m][i]=a[m][rank-1]
a[m][rank-1]=a[i][m]
row-=1
ch=0
for i in a:
if i==[0]*col:
ch+=1
return (rank-ch)
if __name__ == '__main__':
# a = create_matrix(1, 3)
m = int(input('Enter number of rows: '))
n = int(input('Enter number of cols: '))
a=create_matrix(m,n)
# swap_rows(a, 0, 1)
# row_transform(a, 1, 0, 1)
print(a)
print(find_rank(a))
print(a)
# for i in range(len(a)):
# print(a[i][0])
|
"""Description:
Given an input of an array of digits num, return the array with each digit incremented by its position in the array. For example, the first digit will be incremented by 1, the second digit by 2 etc. Make sure to start counting your positions from 1 and not 0.
incrementer([1,2,3]) => [2,4,6]
Your result can only contain single digit numbers, so if adding a digit with it's position gives you a multiple-digit number, only the last digit of the number should be returned
incrementer([4,6,9,1,3]) => [5,8,2,5,8]
- 9 + 3 (position of 9 in array) = 12
- Only its last digit 2 should be returned
Lastly, return [] if your array is empty! Arrays will only contain numbers so don't worry about checking that."""
def incrementer(nums):
x=1
for i in range(len(nums)):
nums[i] += x
if nums[i] >=10:
nums[i] =nums[i]% 10
x+=1
return nums
|
#Title screen function
def titleScreen():
hangmanWord = """
_ _
| | | |
| |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __
| __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
__/ |
|___/
"""
print(hangmanWord)
print('MENU:')
print('1. Single Player')
print('2. Two Player')
print('3. Leaderboard')
print('4. Add Word')
print('5. Help')
print('6. Quit')
playerChoice = eval(input('What would you like to do? '))
print('\n')
return playerChoice
#the pazzaz
def displayHangman(tries):
stages = [ #state 6 (final state)
"""
--------
| |
| O
| \\|/
| |
| / \\
---""",
#state 5
"""
--------
| |
| O
| \\|/
| |
| /
---""",
#state 4
"""
--------
| |
| O
| \\|/
| |
|
---""",
#state 3
"""
--------
| |
| O
| \\|
| |
|
---""",
#state 2
"""
--------
| |
| O
| |
| |
|
---""",
#state 1
"""
--------
| |
| O
|
|
|
---""",
#state 0 (initial state)
"""
--------
| |
|
|
|
|
---"""
]
return stages[tries]
#finding the number of rows in the word bank document
def numLinesWordBank(iFile):
numLines = sum(1 for line in iFile) # open('wordBank.txt','r'))
return numLines
#a simple random number generator using the total length of the word bank
def getRandomNumber(numRow):
from random import randrange as rr
upperLimit = numRow+1
randNum = rr(1,upperLimit)
return randNum
#open word bank
def openWordBank():
iFile = open('wordBank.txt','r')
return iFile
#get random number based on number of lines
def getWord(iFile):
numRow = numLinesWordBank(iFile)
randNum = getRandomNumber(numRow)
#makes reading lines easier
import linecache
wordAndDef = linecache.getline('wordBank.txt',randNum)
wordAndDefSplit = wordAndDef.split('|')
randWord = wordAndDefSplit[0]
randDef = wordAndDefSplit[1]
randWord = randWord.upper()
iFile.close()
return randWord, randDef
#running the game, probably the most important function!!!
def playHangman(word, wordDef = 'null'):
wordCompletion = '_' *len(word)
guessed = False
guessedLetters = []
guessedWords = []
triesLeft = 6
defNeeded = False
print(displayHangman(triesLeft))
print(" ".join(str(x) for x in wordCompletion),'\n')
while not guessed and triesLeft > 0:
guess = input('Please select a letter A-Z or guess the word: ').upper()
if len(guess) == 1 and guess.isalpha():
if guess in guessedLetters:
print('You already guessed this letter', guess)
sassyRemarks()
elif guess not in word:
print('Sorry', guess, 'is not a letter in the word, try again')
triesLeft -= 1
guessedLetters.append(guess)
else:
print('YES!', guess, 'is a letter in the word')
guessedLetters.append(guess)
wordAsList = list(wordCompletion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
wordAsList[index] = guess
wordCompletion = "".join(wordAsList)
if "_" not in wordCompletion:
guessed = True
elif len(guess) == len(word) and guess.isalpha():
if guess in guessedWords:
print("You already guessed the word", guess)
elif guess != word:
print(guess, "is not the word.")
sassyRemarks()
triesLeft -= 1
guessedWords.append(guess)
else:
guessed = True
wordCompletion = word
else:
print("Not a valid guess.")
sassyRemarks()
print(displayHangman(triesLeft))
print(" ".join(str(x) for x in wordCompletion))
print("\n")
if wordDef != 'null' and triesLeft == 1:
print('Looks like you\'re down to your last try!')
print('Here\'s a little hint, the definition is: ' + wordDef)
defNeeded = True
if guessed:
print("Congrats, you guessed the word! You win!\n")
win = True
else:
print("Sorry, you ran out of tries. The word was " + word + ". Better luck next time!")
sassyRemarks()
sassyRemarks()
sassyRemarks()
win = False
return win, word, defNeeded
#getting user info if their score quailifies for the leaderboard
def getPlayerName():
playerName = input('\nPlease enter your initials for the LEADERBOARD: ').upper()
while(True):
if len(playerName) != 3 or playerName.isalpha() == False:
print('##########ERROR PLEASE ENTER YOUR INITIALS IN THIS FORMAT (EX: AAA)##########')
sassyRemarks()
playerName = input('Please enter your initials:')
else:
break
return playerName
#sorting yay!
def sortLeaderboard():
import pandas
with open('leaderboard.txt', 'r') as f:
text = [line.split() for line in f]
#going from str in txt file to string
for i in range(len(text)):
text[i][1] = float(text[i][1])
df = pandas.DataFrame(text, columns = ['NAME:', 'SCORE:'])
#sorting us pandas
dfSorted = df.sort_values("SCORE:", ascending=True) # Sort by values of the SCORE column2
#store NAME: column as list
nameSorted = dfSorted['NAME:'].tolist()
#store SCORE: column as list
scoreSortedFloat = dfSorted['SCORE:'].tolist()
#new list to store strings in
scoreSorted = []
for x in scoreSortedFloat:
scoreSorted.append(str(x))
from itertools import zip_longest #helps combine two lists into list of lists
leaderboardList = list(zip_longest(nameSorted,scoreSorted, fillvalue=""))
#getting the top 10
leaderboardListTrimmed = leaderboardList[:10]
return leaderboardListTrimmed
#replacing leaderboard.txt with updated leaderboard
def updateLeaderboard(updatedLeaderboard):
data = updatedLeaderboard
#create the pandas DataFrame
import pandas as pd
df = pd.DataFrame(data, columns = ['NAME:', 'SCORE:'])
#import numpy
import numpy as np
np.savetxt(r'leaderboard.txt', df.values, fmt='%s')
#prints leaderboard
def getLeaderboard():
iFileR = open('leaderboard.txt', 'r')
print('\n\n*********LEADERBOARD*********')
print('_____________________________')
print('\n', ' NAME: ', ' SCORE:\n')
for i, line in enumerate(iFileR):
name, score = line.split()
print(i+1,'. ', name, ' ', score)
print('\n')
iFileR.close()
#main leaderboard functions
def leadboard(timeTaken, lowestName, lowestScore):
print('Congradulations your time:', timeTaken, 'seconds, is one of the fastest recorded')
print('You kicked', lowestName, 'score of: ', lowestScore, 'outa the top 10!!!!')
playerName = getPlayerName()
iFileTwoA = open('leaderboard.txt', 'a')
score = str(timeTaken)
iFileTwoA.write(playerName + ' ' + score +'\n')
iFileTwoA.close()
updatedLeaderboard = sortLeaderboard()
updateLeaderboard(updatedLeaderboard)
getLeaderboard()
#takes the bottom time from the leaderboad and compares it to the users time
def fastEnough(timeTaken):
iFileR = open('leaderboard.txt', 'r')
lines=iFileR.readlines()
lowScore = lines[9]
name, lowestScoreStr = lowScore.split()
lowestScore = float(lowestScoreStr)
iFileR.close()
return name, lowestScore
def outputIfNotTopTen(timeTaken):
if timeTaken <= 45:
print('Good job on winning, but you were not fast enought to crack the top 10 times ever!')
print('\n\t\t!!!!!YOU GOTTA BE QUICKER THAN THAT!!!!!\n')
elif timeTaken > 45 and timeTaken <= 60:
print('Under a minute, but over 45 seconds')
print('Good, but not great')
print('It\'s like getting a handjob, its fine but we all know what you really want')
print('S/O to gambino for that zinger')
elif timeTaken >= 60 and timeTaken <= 100:
print('It took you over a minute to solve this..')
print('Congrats you\'re a genius....if you\'re in the 3rd grade')
sassyRemarks()
print()
elif timeTaken > 100 and timeTaken <= 150:
print('This took you close to if not over two minutes to solve this')
print('Idk if says more about you or more about me')
print('I mean why am I letting morons use my computer?')
sassyRemarks()
print()
elif timeTaken > 150 and timeTaken <= 240:
print('Almost 3 minutes?')
print('TOUGH LOOKS')
print('I hope you simply got up to go to the bathroom in the middle of the game')
print('That\'s the only logical reason I can think of for solving it that slow')
sassyRemarks()
print()
else:
print('I wanna say something here, but honestly I not gonna throw insults at you')
print('Since your life is already an insult to everyone around you')
sassyRemarks()
print()
#Single player game mode
def runSinglePlayer():
print('****************SINGLE PLAYER****************\n')
iFile = openWordBank()
randWord, randDef = getWord(iFile)
print('\t The CPU has selected a word')
print(' You can only choose WRONG 6 times!')
print('\t CHOOSE WISELY!!!\n')
input('Enter any key to start the game! ')
#allows the program to time how long it takes user to solve the hangman
import time
start = time.time()
win, word, defNeeded = playHangman(randWord, randDef)
end = time.time()
timeTaken = round((end - start),5)
if win == True:
print('You guessed', word ,'in', timeTaken, 'seconds\n')
if defNeeded == False:
print('FUN FACT:')
print('The definition of', word, 'is:', randDef)
lowestName, lowestScore = fastEnough(timeTaken)
if timeTaken < lowestScore:
leadboard(timeTaken, lowestName, lowestScore)
else:
outputIfNotTopTen(timeTaken)
playAgainChoice = playAgain()
return playAgainChoice
#Getting TP basic info
def getTwoPlayerInfo():
print('\n ******************TWO PLAYER******************\n')
print('So either they\'re two of you or you\'re just really lonely')
print('\t Or you couldn\'t handle the CPU\n')
print(' Each player will enter a word for the other to solve\n')
print('\t #######!!!fastest time wins!!!#######\n')
playerOne = input('Player One please enter your name: ').upper()
playerTwo = input('\nPlayer Two please enter your name: ').upper()
print('\nWELCOME ' + playerOne.upper() + ' & ' +playerTwo.upper() + '\n')
return playerOne, playerTwo
#Get's a users word (different than the other function tho this one is for TP)
def getWordsTP(player, otherPlayer):
while(True):
playerWord = input(player + ', Please enter your word: ').upper()
if len(playerWord) < 4 or playerWord.isalpha() == False:
print('Either you fucked up or the word is to short')
print('Let me guess you wanted to put in a 3 letter word')
print('Your words must be AT LEAST 4 letters long')
print('Please keep in mind that there are no special characters/numbers in words')
print('Additional note: this is hangman leave your weird foriegn accent marks at home\n')
else:
if len(playerWord) == 4:
print('This better be a pretty unique 4 letter word')
print('Shorter words are usually easier to solve')
print('Are you trying to loose?\n')
choice = input('Please confirm that ' + playerWord.upper() + ' is indeed your word (Y/N)? ').upper()
if choice == 'Y':
print('\nGOOD LUCK!!!')
break
elif choice == 'N':
print('well let\'t try again shall we?')
else:
print('Well you couldn\'t even enter a Y or N')
print('This is gonna be an easy dub for ' + otherPlayer +' it looks like')
print('Try agian ya dingbat')
return playerWord
#Getting players word
def getTwoPlayerWords(playerOne, playerTwo):
print(playerOne + ' will enter their word first')
print(playerTwo + ' please avert your eyes like you\'re Indiana Jones and the Screen is the Arc of the Covenant\n')
playerOneWord = getWordsTP(playerOne, playerTwo)
print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n')
print('_______________________________________________________________')
print('\n'+ playerTwo + '\'s turn!!!')
print(playerOne + ' please avert your eyes like you\'re looking at ' + playerTwo + '\'s mama heyyyyyyooooooo\n')
playerTwoWord = getWordsTP(playerTwo, playerOne)
print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n')
return playerOneWord, playerTwoWord
def resultsTP(playerOne, playerTwo, playerOneTime, playerTwoTime, timeDifference):
print('The results are in!!!!!')
input('Please enter any key to see who is a WINNER and who is a LOSER: ')
print('\n_______________________________________________________________\n')
#player one wins
if playerOneTime < playerTwoTime:
print()
print('Congradulation ' + playerOne)
print('Looks like you were able to beat ' + playerTwo + ' with a time of ', playerOneTime, 'seconds')
print('That was', timeDifference, 'seconds better than ' + playerTwo)
print(playerTwoTime, 'wasn\'t fast enough ' + playerTwo + ' gotta be quicker than that!!!')
#player two wins
elif playerOneTime > playerTwoTime:
print()
print('Congrats ' + playerTwo + '!!!')
print('Looks like you were able to beat ' + playerOne + ' with a time of ', playerTwoTime, 'seconds')
#to account for the extreme p1 time set if p1 looses
if timeDifference < 1000000000000:
print('That was', timeDifference, 'seconds better than ' + playerOne)
print('Gotta be quicker than that ' + playerOne)
#tie (this will never happen)
elif playerOneTime == playerTwoTime:
print()
print('I have no words for this other than HOLY FUCKING SHIT')
print('You somehow managed to get the same time')
print(playerOne + ' got', playerOneTime, 'seconds & ' + playerTwo + ' got', playerTwoTime, 'seconds')
print('IDK how that happened, but y\'all best get your asses of the computer and go get some lottery tickets')
print('*NOTE: I\'m entitled to at least 3% of the winnings')
#1v1 rust quickscope only! no hard scoping you fuckboi
def runTwoPlayer():
playerOne, playerTwo = getTwoPlayerInfo()
playerOneWord, playerTwoWord = getTwoPlayerWords(playerOne, playerTwo)
print('\n_______________________________________________________________\n')
print('Both players have entered their words\n')
input(playerOne + ' When you are ready enter any key and the clock will start: ')
print('GOODSPEED!')
#allows the program to time how long it takes user to solve the hangman
import time
start = time.time()
#not sure how to deal with this?
win, word, defNeeded = playHangman(playerTwoWord)
end = time.time()
playerOneTime = round((end - start),5)
#setting these up for later
k = True
j = True
if win == False:
print('\nWell looks like '+ playerOne +' is garbage at hangman and couldn\'t even figure out the word')
print('All you have to do ' + playerTwo + ' is guess the word')
print('The heat death of the universe could come and go and you would still win if you finished eventually')
print('See how fast you can get' + playerOne + '\'s word for fun!!!\n')
#makes it impossible for p1 to win
playerOneTime = 10000000000000000000
j = False
else:
print('Hey you got the word!!!')
print(playerTwo + ' maybe pick a harder word than ' + word + ', it helps to read so find yourself a book and expand that vocabulary!')
print('\nYour turn ' + playerTwo)
input('When you are ready enter any key and the clock will start: ')
#run it back
start = time.time()
#not sure how to deal with this?
win, word, defNeeded = playHangman(playerOneWord)
end = time.time()
playerTwoTime = round((end - start),5)
timeDifference = round(abs(playerOneTime - playerTwoTime),5)
if win == False:
k == False
if j == True:
#if p2 looses and p1 won
print('\n' + playerTwo + ' what happened? You couldn\'t even figure out the word')
print('Let me guess...the vocab section was your lowest score on the SAT')
print('Better luck next time looks like ' + playerOne + ' walks away with the dub and a time of', playerOneTime, 'seconds')
print('Maybe y\'all could do a best of 3?\n')
playAgainChoice = playAgain()
return playAgainChoice
#both fail to get word
if j == False and k == False:
print('\nWell you both fucking suck apparently')
sassyRemarks()
print('Guess the only thing to do is run it back!!!')
playAgainChoice = playAgain()
return playAgainChoice
else:
resultsTP(playerOne, playerTwo, playerOneTime, playerTwoTime, timeDifference)
print('\n_______________________________________________________________\n')
print('Thanks for playing, hope you both had fun!!!\n')
playAgainChoice = playAgain()
return playAgainChoice
#just the leaderboard, nothing else to see here
def runLeaderboard():
print('The leaderboard is based on how quickly you solve the hangman')
print('While some words are definately easier than others (rng\'s a bitch ain\'t she?)')
print('My lazy ass didn\'t feel like weighing every god damn word in the word bank')
getLeaderboard()
input('press any key to exit leaderboard...just not esc...or ctrl + alt + delete ')
print()
playAgainChoice = playAgain()
return playAgainChoice
#Getting the new word and def
def getWordandDef():
print('please note: new words CANNOT be propper nouns')
while(True):
newWord = input('Please enter new word: ').lower()
if len(newWord) < 4 or newWord.isalpha() == False:
print('Either you fucked up or the word is to short')
print('Let me guess you wanted to put in a 3 letter word')
print('New words must be AT LEAST 4 letters long')
print('Please keep in mind that there are no special characters/numbers in words')
print('Additional note: this is hangman leave your weird foriegn accent marks at home')
else:
if len(newWord) == 4:
print('\nThis better be a pretty unique 4 letter word')
print('Remember people have 6 guesses so the shorter the word usually means it\'s easier to solve\n')
print(newWord.upper())
choice = input('\nAre you 100% positive this is the CORRECT SPELLING of the word ' + newWord.upper() + ' (Y/N)? ').upper()
if choice == 'Y':
print('Hope you\'re right!!!')
break
elif choice == 'N':
print('well let\'t try again shall we?')
else:
print('\nThat wasn\'t a "Y" or a "N" so we\'re just gonna quit before you mess anything else up\n')
sassyRemarks()
return False, False
print('Now we\'re gonna do the same but with the definition!')
print('PLEASE KEEP THE DEFINITION IN LOWER CASE')
while(True):
newDef = input('Please enter the definition of ' + newWord.upper() +': ').lower()
print(newDef)
choice = input('\nAre you 100% positive this is the CORRECT SPELLING/DEFINITION of,\n' + newDef + ',(Y/N)? ').upper()
if choice == 'Y':
print('Hope you\'re right!!!')
break
elif choice == 'N':
print('well let\'t try again shall we?')
else:
print('\nThat wasn\'t a "Y" or a "N" so we\'re just gonna quit before you mess anything else up\n')
sassyRemarks()
return False, False
print('Last Chance!!!\n')
print(newWord.upper())
print(newDef, '\n')
finalChoice = input('Are you 100% positive this is the right WORD/DEFINITION and EVERYTHING is spelled CORRECTLY, (Y/N)? ').upper()
if finalChoice == 'Y':
print('\nOkay I trust ya!!!')
return newWord, newDef
else:
print('\nWell you can always try again later...\n')
return False, False
#testing if new word is already in the word bank or not
def isWordInWordBank(newWord):
testWordBank = list()
filename = open('wordBank.txt', 'r')
for line in filename:
words = line.split('|')
testWordBank.append(words[0])
res = [ele for ele in testWordBank if(ele in newWord)]
wordOkay = not bool(res)
return wordOkay
#adding new word to word bank and then sorting the word bank alphabetically
def addingNewWord(newWord, newDef):
wordOkay = isWordInWordBank(newWord)
if wordOkay == False:
print('\nSorry ' + newWord + ' is already in the wordbank!')
input('Enter any key to return you to main menu ')
return wordOkay
else:
wordBank = open('wordBank.txt', 'a')
wordBank.write(newWord + '|' + newDef + '\n')
wordBank.close()
filename = 'wordBank.txt'
newWordBank = list()
with open (filename) as fin:
for line in fin:
newWordBank.append(line.strip())
newWordBank.sort()
with open (filename, 'w') as fout:
for band in newWordBank:
fout.write(band + '\n')
return wordOkay
#for people that think they can add a new word plus definition
#can't wait to sort this alphabetically
def runNewWord():
print('\n*********ENTER NEW WORDS/DEFINITIONS*********\n')
while(True):
print('So you wanna enter a new word huh?')
choice = input('Are ya sure? (Y/N)?').upper()
if choice != 'Y' and choice != 'N':
print('If I can\'t trust you with entering Y or N')
print('I sure as hell ain\'t letting you enter in a new word')
sassyRemarks()
print('GTFO my GAME ya NUMSKULL')
playAgainChoice = 'X'
return playAgainChoice
elif choice == 'N':
playAgainChoice = playAgain()
return playAgainChoice
else:
print('Ok better get you dictionary out!!!')
print('& for the love of god check your')
print('########!!!!!SPELLING!!!!!#########\n\n')
newWord, newDef = getWordandDef()
if newWord == False and newDef == False:
print('Something went wrong while entering new word')
print('Returning you to home screen!')
return
else:
print('Adding', newWord, '& it\'s definition to the word bank!!!')
wordOkay = addingNewWord(newWord, newDef)
if wordOkay == False:
playAgainChoice = 'Y'
return playAgainChoice
else:
print(newWord + ' Has been added to the wordbank')
while(True):
newChoice = input('Would you like to add another word? (Y/N)?').upper()
print()
if newChoice == 'Y':
print('Lets run it back!\n')
break
elif newChoice == 'N':
print('Thanks for contributing to the word bank!!!\n')
playAgainChoice = playAgain()
return playAgainChoice
else:
print('\nThat wasn\'t a "Y" or a "N" try again (rhyme not intended)\n')
#single player help
def singlePlayerHelp():
print('\n**********************Single Player Help**********************\n')
print('Single player pits the user against the CPU')
print('The CPU chooses a random word from the word bank for the player to solve')
print('You will see "_" lines next to an empty gallow')
print('The dashed lines represent the number of letters in the word the CPU choose')
print('You then enter any letter or a word with the same number of letters')
print('If the letter is in the word, the "_" will be replaced by the letter')
print('e.g. if the word is "POWER" and one enters the letter "e"')
print('The result will look like "_ _ _ E _"')
print('If the letter is not in the word than a body part gets added to the gallow')
print('You have 6 incorrect guesses before the body is complete and you loose the game')
print('Head, Body, Right Arm, Left Arm, Right Leg, Left Leg')
print('If you guess all of the letters correct or you enter the full word correctly')
print('YOU WIN THE GAME')
print('Your score is recorded as the time it took you to solve the hangman')
print('Once the program runs the clock starts')
print('The clock then finishes only once the word is complete')
print('If you fails to guess the word no score is recorded')
print('If you score is fast enough the you are entered into the leaderboard')
print('More on that later')
print('Hopefully this gave you a basic idea of what hangman is and how to play')
print('If you have any other questions just google them haha')
input('Enter any key to continue: ')
#two player help
def twoPlayerHelp():
print('\n************************Two Player Help***********************\n')
print('This game mode is designed to have two people race each other')
print('Both players will enter their name and a word for the other to solve')
print('e.g. name: "Bill" and word: "Pancakes"')
print('Please note that the word CANNOT be a proper noun')
print('Once the program has the required info it will run 2 games of hangman')
print('Player One will go first, trying to solve Player Two\'s word')
print('Then vice-versa')
print('If both players guess correctly the fastest time wins')
print('If only one player guesses correctly than obviously they win')
print('If both players loose, well thats self explanitory')
input('Enter any key to continue: ')
#leaderboard help
def leadboardHelp():
print('\n***********************Leaderboard Help***********************\n')
print('The leaderboard holds the best times ever recorded on this game')
print('You gotta be pretty quick to be on the leaderboard')
print('There are some really tough words to solve quickley')
print('Yet alone solve')
print('I could have weighed each individual word on how difficult it was,')
print('but there are over 1250 words and I am way to lazy to do that')
print('Plus I am not sure that I would know how to weigh them')
print('Mind that rant leaderboards aren\'t that hard to understand tho')
input('Enter any key to continue: ')
#help adding new words and definitions to the bank
def newWordHelp():
print('\n************************New Word Help*************************\n')
print('This allows the user to add a new word to the word bank')
print('This can be any word in the English Language')
print('Excluding proper nouns e.g. Santana, Anna, Canada, etc...')
print('Additionally the user must provide a definition for the word')
print('Just copy the definition from google please, it works the best')
input('Enter any key to continue: ')
#kills leadboard
def deleteLeaderboard():
#deletes all contents of leaderboard
open('leaderboard.txt', 'w').close()
#add default (AAA with times of 999.99999)
#like old school arcade games
fakeUser = 'AAA'
fakeScore = '999.99999'
leadboard = open('leaderboard.txt', 'a')
for i in range (10):
leadboard.write(fakeUser + ' ' + fakeScore + '\n')
leadboard.close()
#honestly this page is just here as a front to reseting the leaderboard
def helpHelp():
print('\n**************************Help Help***************************\n')
print('Lmao I doubt you need a help page on the help page')
print('Hopefully you now understand the game of Hangman better')
print('Congrats you have now complete the all help pages!!! YAY!!!\n')
resetLeaderboard = input('Enter any key to head back to the main menu ')
if resetLeaderboard == 'b0F$qZD4kn*':
print('\nReally hope this is Elias, otherwise how the fuck did you get this password?')
print('Also how did you know this page even exsisted?\n')
print('\n************************Admin Services************************\n')
print('To edit leadboard enter L')
print('To add a sassy remark press S')
print('To return to main menu enter any other key')
adminChoice = input('What do you want to do? ').upper()
if adminChoice == 'S':
while(True):
newSass = input('Enter your new sassy phrase (capitalize the first letter) ')
isRight = input('"' + newSass + '" are you sure this is right(Y/N)? ').upper()
if isRight == 'Y':
filename = open('sassyRemarks.txt', 'a')
# Append 'hello' at the end of file
filename.write(newSass + '\n')
# Close the file
filename.close()
print('added ' + newSass + ' to sassyRemarks.txt')
break
elif isRight == 'N':
print('Okay lets try again')
print('Note to break this loop enter a letter other than "y" or "n"')
else:
print('if you didn\'t enter "y" or "n" than I assume you wanna return to main menu')
break
elif adminChoice == 'L':
while(True):
newChoice = input('Are you 100% sure you would like to reset the leaderboard? (Y/N)? ').upper()
print()
if newChoice == 'Y':
input('\nLast Change only way out at this point is to kill the terminal! Enter any key to confirm leadboard reset ')
print()
deleteLeaderboard()
print('!!!Leadboard is now RESET!!!\n')
input('Enter any key to return to main menu ')
break
elif newChoice == 'N':
break
else:
print('\nThis probably isn\'t Elias cause he wouldn\'t make that mistake!')
print('Just in case he\'s drunk or something, try again\n')
else:
print()
else:
return
#for the idiots who apperently don't know how to play hangman
#seriously who never played hangman growing up?
def runHelp():
print('\n************************HELP PAGE(S)**************************\n')
print('This section will give you all the basic info for each gamemode')
print('In addition to other options, & little tips/tricks to hangman')
singlePlayerHelp()
twoPlayerHelp()
leadboardHelp()
newWordHelp()
helpHelp()
#rng for sassy remarks
def rngSassyRemarks():
from random import randrange as rr
randNum = rr(1,8)
return randNum
#sassy remarks generator
def sassyRemarks():
randNum = rngSassyRemarks()
if randNum == 4:
filename = open('sassyRemarks.txt', 'r')
numRow = sum(1 for line in filename)
randNum = getRandomNumber(numRow)
#makes reading lines easier
import linecache
sassyRemarks = linecache.getline('sassyRemarks.txt',randNum)
return(print(sassyRemarks))
#duh
def playAgain():
while(True):
playAgain = input('Would you like to play again (Y/N)? ').upper()
if playAgain != 'Y' and playAgain != 'N':
print(playAgain)
print('#######ERROR PLEASE ENTER: Y for Yes or N for No########')
print('Seriously does your dumbass not know the alphabet???')
else:
break
return playAgain
#DUH!?
def runQuit():
quitScreen = """
_____ _ _ __ _ _ _ _ _
|_ _| | | | / _| | | (_) | | | |
| | | |__ __ _ _ __ | | _____ | |_ ___ _ __ _ __ | | __ _ _ _ _ _ __ __ _| | | |
| | | '_ \ / _` | '_ \| |/ / __| | _/ _ \| '__| | '_ \| |/ _` | | | | | '_ \ / _` | | | |
| | | | | | (_| | | | | <\__ \ | || (_) | | | |_) | | (_| | |_| | | | | | (_| |_|_|_|
\_/ |_| |_|\__,_|_| |_|_|\_\___/ |_| \___/|_| | .__/|_|\__,_|\__, |_|_| |_|\__, (_|_|_)
| | __/ | __/ |
|_| |___/ |___/
"""
print(quitScreen)
#could be cleaner
def main():
#show title screen for hangman
while(True):
while(True):
playerChoice = titleScreen()
if playerChoice <= 6 and playerChoice > 0:
break
else:
print("#############ERROR PLEASE ENTER NUMBER 1-6#############")
print('it\'s not that hard')
#Which program to run
if playerChoice == 1:
playAgain = runSinglePlayer()
if playAgain == 'N':
runQuit()
break
if playerChoice == 2:
playAgain = runTwoPlayer()
if playAgain == 'N':
runQuit()
break
if playerChoice == 3:
playAgain = runLeaderboard()
if playAgain == 'N':
runQuit()
break
if playerChoice == 4:
playAgain = runNewWord()
if playAgain == 'N':
runQuit()
break
elif playAgain == 'X':
break
if playerChoice == 5:
runHelp()
if playerChoice == 6:
print('Why\'d you even start me up???')
runQuit()
break
if __name__ == "__main__":
main() |
"""
Just an implementation of linear search.
"""
import timing
import search_in
def linear_search(list, value):
""" Searches for a value in a list linearly! """
for i, val in enumerate(list):
if (val == value):
print(">> Found {} in the list at index {}.".format(value, i))
return
print(">> {} is not in the list.".format(value))
return
def main():
""" Entry point """
# Begin user input
print("> Welcome to this implementation of linear search!")
option = '?'
while(option == '?'): # Check for input error
option = input("> 1. Manually enter input\n> 2. Enter input from a file\n")
if (option == '1'):
# Collect input from command line
l, search = search_in.manual_in()
# Start timer and conduct search
timing.start()
linear_search(l, search)
return
elif (option == '2'):
# Collect input from file
l, search = search_in.file_in()
# Start timer and conduct search
timing.start()
linear_search(l, search)
return
else:
print("> ERROR: Incorrect option.")
option = '?'
continue
if __name__ == "__main__":
main() |
#
# @lc app=leetcode.cn id=9 lang=python3
#
# [9] 回文数
#
# https://leetcode-cn.com/problems/palindrome-number/description/
#
# algorithms
# Easy (56.00%)
# Total Accepted: 78.2K
# Total Submissions: 139.6K
# Testcase Example: '121'
#
# 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
#
# 示例 1:
#
# 输入: 121
# 输出: true
#
#
# 示例 2:
#
# 输入: -121
# 输出: false
# 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
#
#
# 示例 3:
#
# 输入: 10
# 输出: false
# 解释: 从右向左读, 为 01 。因此它不是一个回文数。
#
#
# 进阶:
#
# 你能不将整数转为字符串来解决这个问题吗?
#
#
import math
class Solution:
def isPalindrome(self, x: int) -> bool:
# if(x>=0):
# y=int(str(x)[::-1])
# if(y==x):
# return True
# else:
# return False
# else:
# return False
if(x<0):
return False
elif(x<10):
return True
else:
numbers=[]
number=int(math.log10(x))
max=math.pow(10,number)
for i in range(number+1,0,-1):
power=int(math.pow(10,i-1))
temp=int(x/power)
numbers.append(temp)
x=x-temp*power
if(numbers==numbers[::-1]):
return True
else:
return False
|
import re
import convertToMiles
import convertToKilometers
class Convert:
def __init__(self):()
def convert(self, distance, unit):
if unit == convertToKilometers.kilometerUnit:
return self.convertMiles(distance)
elif unit == convertToMiles.milesUnit:
return self.convertKilometers(distance)
else:
return None
def convertMiles(self, distance):return str(round(convertToMiles.kmToMiles(distance),2))+' miles'
def convertKilometers(self, distance):return str(round(convertToKilometers.milesToKm(distance),2))+' kilometers'
class UserInterface:
def __init__(self):
self.running = False
self.convert = Convert()
self.response = ''
self.start()
def start(self):
self.running = True
while self.running == True:
status = self.mainQuestion()
if status != None and status != 'exit':
print()
print(self.response, ' = ', status)
print()
elif status == 'exit':
return
else:
print()
print("there was an issue with the input. please try again")
print()
def exit(self):
self.running = False
def mainQuestion(self):
print("Convert a distance from Miles to KM or KM to Miles")
print('[type exit to stop processing] (units auto-detected)')
inputDistance = str(input("Enter distance to convert: "))
self.response = inputDistance
if inputDistance.lower() == 'exit':
self.exit()
return 'exit'
else:
result = self.processAnswer(inputDistance)
if result == None:
print()
print('there was an issue with the input. please try again.')
print()
return None
else:
return self.convert.convert(result.get('distance'), result.get('unit'))
def processAnswer(self, ans):
if len(ans) >= 2:
ans = ans.strip().replace(' ', '').lower()
intNum = re.search(r'[0-9]+', ans)
floatNum = re.search(r'[0-9]+\.[0-9]+', ans)
if intNum == None and floatNum == None:
print('input error')
return None
elif floatNum == None and intNum != None:
distance = int(ans[intNum.start(0):intNum.end(0)])
unit = ans[intNum.end(0):len(ans)]
elif floatNum != None and intNum != None:
distance = float(ans[floatNum.start(0):floatNum.end(0)])
unit = ans[floatNum.end(0):len(ans)]
return {'distance': distance, 'unit': unit}
else:
print()
print("input error")
print()
return None
program = UserInterface() |
# Modify your student dictionary program from lists_tuples_dictionaries/dictionaries3.py
# so that it is two separate programs. One should create the data and store it, while the
# other should load the data and use it. Note that you can dump or load the entire
# dictionary at once using pickle.
import pickle
print("This program shows the student average score.")
try:
f = open("students.pck", "rb")
dictionary = pickle.load(f)
student = input("Please enter student number: ")
if student in dictionary.keys():
average = (dictionary[student][2] + dictionary[student][3] + dictionary[student][4]) / 3
print(dictionary[student][1] + "'s marks average to " + str(average))
else:
print("Student does not exist. Session terminated.")
f.close()
except FileNotFoundError:
print("Add some students to the list first.")
|
# This exercise extends the username check program from usinglists3.py.
# Write a program which maintains a list of usernames. It should
# repeatedly show a menu with the following options:
# Add a new username to the list
# Read in a name and check whether it is in the list
# Read in a name and append it to the list
# Read in a name and delete it from the list if it exists
# Read in a name and change it to a new value if it exists
# Exit the program
# The program should make appropriate use of functions.
option = 999
userlist = []
a = ""
def read_user():
global a
a = input("Enter username: ")
def add_user(user):
global userlist
userlist += [user]
print("User " + user + " added.")
def check_user(user):
if (user in userlist):
print("User " + user + " exist in the list.")
return True
else:
print("User " + user + " does not exist in the list.")
return False
def change_user(user, newUser):
global a, userlist
a = userlist.index(user)
userlist[a] = newUser
print("From now on, user " + user + " will be known as " + newUser + ".")
def delete_user(index):
global userlist
del userlist[index]
print("User " + a + " deleted.")
while (option != "0"):
print("Choose an option:")
print("######")
print("1. Add new user.")
print("2. Check for user.")
print("3. Change username.")
print("4. Delete user.")
print("0. Exit.")
print("######")
option = input(": ")
if (option == "1"):
read_user()
add_user(a)
elif (option == "2"):
read_user()
check_user(a)
elif (option == "3"):
read_user()
if (check_user(a)):
newu = input("Please input new username: ")
change_user(a, newu)
elif (option == "4"):
read_user()
if (check_user(a)):
delete_user(userlist.index(a))
elif (option == 0):
print("Goodbye.")
else:
print("Error. Choose again.")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.