text stringlengths 37 1.41M |
|---|
'''O programa abaixo organiza os numeros da tabela ROL de forma crescente'''
numero = int(input('Digite um número e [0] para encerrar:'))
lista=[numero]
while numero != 0:
numero = int(input('Digite um número e [0] para encerrar:'))
lista.append(numero)
print('\033[31m ESSA MERDA ORGANIZADA FICA ASSIM:\033[0;0m \n',sorted(lista)) |
# from random import randint
import random as rand
def random_verb():
random_num = rand.randint(0, 1)
print random_num
if random_num == 0:
print "Lama"
return "run"
else:
print "Lama"
return "kayak"
def random_noun():
random_num = rand.randint(0,1)
print random_num
if random_num == 0:
print "sofa"
return "sofa"
else:
print "Lama"
return "llama"
def word_transformer(word):
# your code here
if word == "NOUN":
print "Lama"
return random_noun()
if word == "VERB":
print "Lama"
return random_verb()
word = "The sentence contains NOUN and a VERB see if it works"
# word = " NOUN is a name of person place or thing. what is VERB"
# word = "In english sometimes sentence ends with VERB"
print word_transformer(word)
|
# String Manipulation
# Write Python code that prints out the number of hours in 7 weeks.
week =7
days = 7
hr_in_day=24
hr_in_7_week = week*days*hr_in_day
print hr_in_7_week
#
s=''
str1 = ('a'+ s ) [1:]
str3 = s+ ''
str4 = s[0:]
print str1
print str3
print str4
s = 'udacity'
t = 'bodacious'
print s[0:2] + t[3:]
sentence = "A NOUN went on a walk. It can VERB really fast."
print sentence.find('VERB')
print sentence[:2]
print sentence[6:30]
print sentence[34:]
text = "We believe university-level zip education can be both high quality and low cost. Using the economics of the Internet, we've connected some of the greatest teachers to hundreds of thousands of students all over the world."
pos1= text.find("zip") +3
print text[pos1:]
pos2 = text[pos1:].find("zip")
print pos2+3
print text[pos2:]
|
#dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
# print "dict['Name']: ", dict['Name']
# print "dict['Age']: ", dict['Age']
#
fill_in_quiz = {
"list_easy" :['''__1__ twinkle __2__ star''',["Twinkle", "little"]],
"list_mod" :['''Five little __1__ jumping on the __2__''',["monkeys","bed"]],
"list_diff" :['''Freedom __1__ __2__ on a __3__''',["fighter","standing","mountain"]]}
print "fill_in_quiz['Name']: ", fill_in_quiz['list_easy']
a = fill_in_quiz['list_easy']
print a[0] , " ___ ",a[1]
print fill_in_quiz['list_easy'][0]
|
#Write a program that prints
#out the numbers 1 to 100 (inclusive).
# If the number is divisible by 3, print
#Crackle instead of the number.
#If it's divisible by 5, print Pop.
# If it's divisible by both 3 and 5, print CracklePop.
# You can use any language.
for x in range(101):
if x%3==0 and x%5==0:
print("CracklePop")
elif x%3==0:
print("Crackle")
elif x%5==0:
print("Pop")
elif x in range(101):
print(x)
|
#OPERACION DE FORMATO
#manipulador de texto nro 16
cad="TE EXTRAÑADO MUCHO"
print(cad.rjust(20)) #va correr 20 espacios a la derecha
#manipulador de texto nro 17
cad="TE EXTRAÑADO MUCHO"
print(cad.center(30)) #me a centrar la cadena
#manipulador de texto nro 18
numero="8"
print(numero.zfill(4)) #me imprimira ceros a la isquierda de 8
#manipulador de texto nro 19
msg="precio del {celular}"
print(msg.format(celular="samsung"))
#manipulador de texto nro 20
msg="precio del {celular}"
marca="samsung"
print(msg.format(celular=marca))
#manipulador de texto nro 21
msg="hola {} tu nota es {}"
print(msg.format("julian","16"))
#manipulador de texto nro 22
msg="el cumpleaños de {1} es el dia {0}" #-> los valores de la cadena
print(msg.format("carlos","25")) #toma los valores ordenados
#manipulador de texto nro 23
marca="adidas"
msg="la marca de tus zapatillas es {}"
print(msg.format(marca))
#manipulador de texto nro 24
msg="hola {} tu nota es {}"
nombre="elmer"
nota="20"
print(msg.format(nombre,nota))
#manipulador de texto nro 25
msg="como estas {0:20}"
print(msg.format("hermosa"))
#manipulador de texto nro 26
msg="como estas {0:>20}"
print(msg.format("hermosa"))
#manipulador de texto nro 27
msg="hay {:d} ingresantes a la escuela de ingenieria electronica"
print(msg.format(40))
#manipulador de texto nro 28
cad1="BOLETA DE VENTAS "
print("#"*30)
print(cad1.center(30))
informacion="el producto {} tien el precio de {}"
producto="huevos"
precio=5
print(informacion.format(producto,precio))
#manipulador de texto nro 29
ingrediente_1="cebolla"
ingrediente_2="pollo"
ingrediente_3="arroz"
ingredientes="el {} es utilizado con la {} y con el {}"
print(ingredientes.format(ingrediente_2,ingrediente_1,ingrediente_3))
#manipulador de texto nro 30
marcas="la marcas de ropa son {0} , {1} ,{2}."
print(marcas.format("nike","puma","adidas"))
|
from abc import ABC, abstractmethod
class Zoo:
def __init__(self, name):
self.name = name
self._animals = []
def add_animal(self, animal):
if not self.is_in_zoo(animal):
self._animals.append(animal)
def is_in_zoo(self, animal):
if len(self._animals) == 0:
return False
else:
for item in self._animals:
if id(item) == id(animal):
return True
return False
def has_attr(self, animal_type):
for item in self._animals:
if type(item) is animal_type:
return True
else:
return False
@property
def animals(self):
return self._animals
class Animal(ABC):
@abstractmethod
def __init__(self, name, group, size, character):
pass
@property
def is_dangerous(self):
if (self.size == '中等' or self.size == '大') and self.group == '食肉':
return '是凶猛动物'
else:
return '不是凶猛动物'
class Cat(Animal):
def __init__(self, name, group, size, character):
self.name = name
self.group = group
self.size = size
self.character = character
self._bark_type = '喵喵'
@property
def is_pet(self):
if self.is_dangerous == '是凶猛动物':
return '不适合作为宠物'
else:
return '适合作为宠物'
@property
def bark_type(self):
return self._bark_type
@bark_type.setter
def bark_type(self, value):
self._bark_type = value
class Dog(Animal):
def __init__(self, name, group, size, character):
self.name = name
self.group = group
self.size = size
self.character = character
self._bark_type = '汪汪'
@property
def is_pet(self):
if self.is_dangerous == '是凶猛动物':
return '不适合作为宠物'
else:
return '适合作为宠物'
@property
def bark_type(self):
return self._bark_type
@bark_type.setter
def bark_type(self, value):
self._bark_type = value
if __name__ == '__main__':
# 实例化动物园
zoo = Zoo('时间动物园')
# 实例化一只猫,属性包括名字、类型、体型、性格
cat1 = Cat('大花猫 1', '食肉', '小', '温顺')
# 增加一只猫到动物园
zoo.add_animal(cat1)
# 动物园是否有猫这种动物
have_cat = zoo.has_attr(Cat)
print(have_cat) |
a = 13
b = 14
if(a % 2 == 0) and (b % 2 == 0):
print('두 수 모두 짝수입니다.')
if(a % 2 == 0) or (b % 2 == 0):
print('두 수 중 하나 이상이 짝수입니다.')
|
def false_position(func, a , b):
# modified from: https://www.geeksforgeeks.org/program-for-method-of-false-position/
if func(a) * func(b) >= 0:
print("You have not assumed right a and b")
return -1
maxit = 200
c = a
iters = 0
while iters < maxit:
iters+=1
c = (a * func(b) - b * func(a))/ (func(b) - func(a))
if abs(func(c)) == 0:
return c, iters
elif func(c) * func(a) < 0:
b = c
else:
a = c
return c, iters |
#主要是利用了array is sorted 的这个property
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
if len(numbers)==0:
return []
start=0
end=len(numbers)-1
while start<=end:
cursum=numbers[start]+numbers[end]
if cursum==target:
return [start+1,end+1]
elif cursum<target:
start+=1
else:
end-=1
return []
|
class Solution(object):
def helper(self,array,start,end):
while start<end:
if array[start]!=array[end]:
return False
start+=1
end-=1
return True
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
start=0
end=len(s)-1
while start<end:
if s[start]!=s[end]:
#try skip left & skip right
if self.helper(s,start+1,end) or self.helper(s,start,end-1):
return True
else:
return False
else:
start+=1
end-=1
return True
|
class Solution(object):
def DFS(self,nestedList,depth):
cursum=0
for ele in nestedList:
#if it's a single int
if ele.isInteger():
cursum+=depth*ele.getInteger()
else:
cursum+=self.DFS(ele.getList(),depth+1)
return cursum
def depthSum(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
return self.DFS(nestedList,1)
|
'''
A script circle.py that describe a Circle Class
'''
import math
'''Class'''
class Circle(object):
''' Constructor '''
def __init__(self, radius):
self.__radius = radius
def set_center(self, center):
self.__center = center
def set_color(self, color):
self.__color = color
def set_name(self, name):
self.name = name
def area(self):
return (self.__radius ** 2) * math.pi
def get_color(self):
return self.color
def get_center(self):
return self.center
|
########################################################################
# @author Mike Ames
# @author Phil Garza
########################################################################
import random
from observer import Observer
from observable import Observable
from mob_factory import Mob, MonsterTypes
########################################################################
# Home Class. Generates and stores a list of monsters. Observes the
# monster class and removes monsters from the list when they die.
# Observed by the world class. Notifies the world class when the number
# of monsters it contains changes.
########################################################################
class Home(Observable, Observer):
####################################################################
# Constructor. Generates a random number of monsters and stores them
# in a list.
####################################################################
def __init__(self):
super().__init__()
random.seed()
numMonsters = random.randrange(1, 11)
self.monsters = []
for i in range(numMonsters):
# represents the type of monster to be created
monsterRand = random.randrange(1, 5)
# get the name of the monster defined in the enum in the
# mob_factory module and use it
# to create a new monster and add it to the home's list
monster = Mob.factory(MonsterTypes(monsterRand).name)
self.monsters.append(monster)
monster.addObserver(self)
self.numBaddies = len(self.monsters)
#####################################################################
# Update method. When invoked by the monster class on the monster's
# death, this method removes the monster from the home's list. It
# then notifies the world class the number of monsters in the home
# has decreased.
#####################################################################
def update(self, other):
self.monsters.remove(other)
self.numBaddies -= 1
self.monsters.append(Mob.factory("person"))
super().update(self)
|
comparisonCount = 0
with open("QuickSort.txt","r") as f:
arr = [int(integers.rstrip()) for integers in f.readlines()]
def medianOfThree(start,end):
length = end - start + 1
middleIndex = int(length/2) - 1 if length % 2 == 0 else int(length/2)
middleIndex = start + middleIndex # move middleIndex to correct position
firstElement = arr[start]
lastElement = arr[end]
middleElement = arr[middleIndex]
if firstElement <= middleElement <= lastElement or lastElement <= middleElement <= firstElement:
return middleIndex
elif middleElement <= firstElement <= lastElement or lastElement <= firstElement <= middleElement:
return start
elif middleElement <= lastElement <= firstElement or firstElement <= lastElement <= middleElement:
return end
def partition(arr,start,end):
global comparisonCount
comparisonCount = comparisonCount + (end-start)
p = arr[start] # chose the pivot as first element for now
i = start + 1 # i denotes the left most index s.t arr[i]>p
for j in range(start+1,end+1):
if arr[j] < p: # if element seen is smaller
arr[i],arr[j] = arr[j],arr[i] # swap with left most element >p
i = i+1 # advance the boundry
arr[i-1],arr[start] = arr[start],arr[i-1] # put the pivot into place
return i-1 # position of pivot
def quicksort(arr,start,end):
if start >= end:
return
pivot = start # index for pivot element, modify this for assignment
arr[start],arr[pivot] = arr[pivot],arr[start] # swap the pivot with first element for partition subroutine
positionOfPivot = partition(arr,start,end)
quicksort(arr,start,positionOfPivot-1)
quicksort(arr,positionOfPivot+1,end)
return
quicksort(arr,0,len(arr)-1)
print(arr)
print(comparisonCount)
|
#!/usr/bin/python
# encoding:utf-8
import urllib, json, urllib2, requests
import time
import datetime as dt
#####define customer class first
####define the customer class
class Customer:
'''Fields: userID(Str),password(Str),gold(float),deposit(float),
upper(float),lower(float),trade(float),build_trade(bool)'''
def __init__(self,id,password,gold,money):
self.userID = id
self.password = password
self.gold = gold
self.deposit = money
self.trade = 0
self.build_trade= False
self.message()
print("new Customer initialized")
print("do you want to build a automatic trade right now?(y/n)")
answer = raw_input()
if (answer == "y"):
self.build_trade = True
self.upper = float(input("set up upper bound: "))
self.lower = float(input("set up lower bound: "))
self.trade = float(input("set the trade amount of gold: "))
self.message()
print("\n")
def message(self):
print("userID: "+ str(self.userID))
print("current gold deposit: "+ str(self.gold))
print("current money deposit: "+ str(self.deposit))
auto_trade = self.build_trade
if (auto_trade): print("automatic trade already build up")
else: print("automatic trade have not build up")
def check_price(self,price):
if (self.build_trade == True):
if (price >= self.upper):
sell = self.trade * price ## calculate the price of gold u want to sell
self.deposit += sell
self.gold -= self.trade
elif (price <= self.lower):
buy = self.trade * price ## calculate price of gold u want to buy
cost = self.deposit - buy
if (cost <= 0): ## client's deposit is not enough to buy so many gold
buy = self.deposit / price
self.gold += buy
self.deposit = 0
else:
self.gold += self.trade
self.deposit -= buy
self.trade = 0 ## reset the trade amount
### otherwise we do not do any operation
self.build_trade = False
self.message()
print("\n")
return
elif (self.build_trade== False):
self.message()
print("\n")
return
print("now create a customer")
name = raw_input("please input userID: ")
password = raw_input("please input password: ")
while (True):
recheck = raw_input("please re-input password: ")
if (password == recheck): break
else: print("password is wrong!")
gold = float(input("please input gold amount: "))
deposit = float(input("please input initial deposit: "))
client = Customer(name,password,gold,deposit)
###############################################################
## now we build the API connection to get current gold price
###############################################################
data = {}
data["appkey"] = "apppkey"
url_value = urllib.urlencode(data)
url = "requested_url" + url_value
#request = urllib2.Request(url)
#result = urllib2.urlopen(request)
#jsonarr = result.json()
result = requests.get(url).json()
i = 0
while(i < 5):
time.sleep(5)
current_price = float(result["result"][0]["price"])
temp_peak = float(result["result"][0]["maxprice"])
temp_trough = float(result["result"][0]["minprice"])
##change_percent = (result["result"][0]["changepercent"])
##last_closing_price = result["result"][0]["lastclosingprice"]
time = result["result"][0]["updatetime"]
print("Current gold price: "+ str(current_price))
print("Contemporary peak: "+ str(temp_peak))
print("Contemporary trough: "+ str(temp_trough))
##print("Change percent: "+ str(change_percent))
##print("Last closing price: "+ str(last_closing_price))
print("Current time: "+ str(time))
client.check_price(current_price)
i += 1
|
Question:Arrange String characters such that lowercase letters should come first
Given input String of combination of the lower and upper case arrange characters in such a way that all lowercase letters should come first.
s=input("enter the string")
s1=""
lower = []
upper = []
for i in s:
if i.islower():
lower.append(i)
else:
upper.append(i)
print(s1.join(lower+upper))
|
"""
@author Disha Gupta
"""
# Import all of the necessary modules.
import matplotlib.pyplot as plt
import pylab
import csv
# Define a function to graph the number of retweets each tweet got.
def rts():
# Store the file.
tweets = "tweets_edited.csv"
try:
# Try to open the file.
data = open(tweets, "r")
except:
# Print a message to the user if the file won't open.
print("The file cannot be found.")
else:
# Create empty lists that will store the values of the information gathered.
# Indexes stores the indexes of each tweet.
indexes = []
# rtsHillary stores the number of RTs Hillary got.
rtsHillary = []
# rtsDonald stores the number of RTs Donald got.
rtsDonald = []
# Use the csv.reader() method to read the file.
myCSV = csv.reader(data)
# Loop through every row in the csv file.
for row in myCSV:
# Store the indexes.
indexes.append(row[0])
# Check to see if Hillary was tweeting.
if row[2] == "HillaryClinton":
# If she was, append the number of rts she got to the list.
rtsHillary.append(row[10])
# If she wasn't, append the number 0 to Donald's list.
rtsDonald.append(0)
# Check to see if Donald was tweeting.
if row[2] == "realDonaldTrump":
# If he was, append the number of rts he got to the list.
rtsDonald.append(row[10])
# If he wasn't, append the number 0 to Hillary's list.
rtsHillary.append(0)
# Add the graph title.
pylab.title("Number of RTs (Hillary vs. Donald)")
# Plot the indexes from 2 onwards (that's where the index is 1), plot the number of RTs
# Hillary got, change Hillarys graph line to blue, and add a label.
pylab.plot(indexes[2:],rtsHillary[1:], color="blue", label="Hillary RTs")
# Plot the indexes from 2 onwards (that's where the index is 1), plot the number of RTs
# Donald got, change Donalds graph line to red, and add a label.
pylab.plot(indexes[2:], rtsDonald[1:],color="red", label="Donald RTs")
# Label the x axis.
pylab.xlabel("# of Tweet")
# Label the y axis.
pylab.ylabel("# of RTs")
# Add a legend.
pylab.legend(loc='upper right')
# Show the graph.
pylab.show()
# Call the function.
rts()
# Define a function to graph the number of favorites each tweet got.
def favorites():
# Store the file.
tweets = "tweets_edited.csv"
try:
# Try to open the file.
data = open(tweets, "r")
except:
# Print a message to the user if the file won't open.
print("The file cannot be found.")
else:
# Create empty lists that will store the values of the information gathered.
# Indexes stores the indexes of each tweet.
indexes = []
# favsHillary stores the number of favorites Hillary got.
favsHillary = []
# favsDonald stores the number of favorites Donald got.
favsDonald = []
# Use the csv.reader() method to read the file.
myCSV = csv.reader(data)
# Loop through every row in the csv file.
for row in myCSV:
# Store the indexes.
indexes.append(row[0])
# Check to see if Hillary was tweeting.
if row[2] == "HillaryClinton":
# If she was, append the number of favorites she got to the list.
favsHillary.append(row[11])
# If she wasn't, append the number 0 to Donald's list.
favsDonald.append(0)
# Check to see if Donald was tweeting.
if row[2] == "realDonaldTrump":
# If he was, append the number of favorites he got to the list.
favsDonald.append(row[11])
# If he wasn't, append the number 0 to Hillary's list.
favsHillary.append(0)
# Add the graph title.
pylab.title("Number of Favorites (Hillary vs. Donald)")
# Plot the indexes from 2 onwards (that's where the index is 1), plot the number of favorites
# Hillary got, change Hillarys graph line to blue, and add a label.
pylab.plot(indexes[2:],favsHillary[1:], color="blue", label="Hillary Favs")
# Plot the indexes from 2 onwards (that's where the index is 1), plot the number of favorites
# Donald got, change Donalds graph line to red, and add a label.
pylab.plot(indexes[2:], favsDonald[1:],color="red", label="Donald Favs")
# Label the x axis.
pylab.xlabel("# of Tweet")
# Label the y axis.
pylab.ylabel("# of Favs")
# Add a legend.
pylab.legend(loc='upper right')
# Show the graph.
pylab.show()
# Call the function.
favorites()
# Define a function that makes a pie chart based on an analysis of Donald's tweets.
def donaldTweetAnalysis():
# Store the file.
tweets = "tweets_edited.csv"
try:
# Try to open the file.
data = open(tweets, "r")
except:
# Print a message to the user if the file won't open.
print("The file cannot be found.")
else:
# Create empty lists that will store the values of the information gathered.
# Sad stores whether or not he tweeted the phrase "sad!".
sad = []
# Hashtags stores whether or not they used a hashtag.
hashtags = []
# Original Tweet checks if they wrote the tweet or not.
originalTweet = []
# Indexes stores the indexes of each tweet.
indexes = []
# Use the csv.reader() method to read the file.
myCSV = csv.reader(data)
# Loop through every row in the csv file.
for row in myCSV:
# This list keeps track of the number of tweets made by Donald.
if row[2] == "realDonaldTrump":
indexes.append(1)
else:
indexes.append(0)
# Check to see if Donald was tweeting and if it was his own tweet.
if row[2] == "realDonaldTrump" and row[4] == "True":
# If he was, append the number 1 to the list to keep track of how many times he did.
originalTweet.append(1)
else:
# Else, append the number 0.
originalTweet.append(0)
# Check to see if Donald was tweeting and if he said "sad!".
if row[2] == "realDonaldTrump" and row[16] == "True":
# If he was, append the number 1 to the list to keep track of how many times he did.
sad.append(1)
else:
# Else, append the number 0.
sad.append(0)
# Check to see if Donald was tweeting and if he used a hashtag.
if row[2] == "realDonaldTrump" and row[17] == "True":
# If he was, append the number 1 to the list to keep track of how many times he did.
hashtags.append(1)
else:
# Else, append the number 0.
hashtags.append(0)
# Calculate the percentage of original tweets out of all tweets.
originalTweetPercentage = ( (sum(originalTweet)/sum(indexes)) * 100 )
# Calculate the percentage of tweets that had the phrase "sad!" out of all tweets.
sadPercentage = ( (sum(sad)/sum(indexes)) * 100 )
# Calculate the percentage of tweets that had hashtags out of all tweets.
hashtagsPercentage = ( (sum(hashtags)/sum(indexes)) * 100 )
# Label the pie chart.
labels = ('said "sad!" ', "original tweet", "used hashtags")
sizes = [sadPercentage,originalTweetPercentage,hashtagsPercentage]
explode = [0.1,0.1,0.1]
figure1, ax1 = plt.subplots()
ax1.pie(sizes,explode=explode,labels=labels, autopct="%1.1f%%")
# Add the graph title.
ax1.set_title("Donald Trump Tweets Analysis")
ax1.axis("equal")
# Show the graph.
plt.show()
# Call the function.
donaldTweetAnalysis()
# Define a function that makes a pie chart based on an analysis of Hillary's tweets.
def hillaryTweetAnalysis():
# Store the file.
tweets = "tweets_edited.csv"
try:
# Try to open the file.
data = open(tweets, "r")
except:
# Print a message to the user if the file won't open.
print("The file cannot be found.")
else:
# Create empty lists that will store the values of the information gathered.
# Hashtags stores whether or not they used a hashtag.
hashtags = []
# Original Tweet checks if they wrote the tweet or not.
originalTweet = []
# Indexes stores the indexes of each tweet.
indexes = []
# Use the csv.reader() method to read the file.
myCSV = csv.reader(data)
# Loop through every row in the csv file.
for row in myCSV:
# This list keeps track of the number of tweets made by Hillary.
if row[2] == "HillaryClinton":
indexes.append(1)
else:
indexes.append(0)
# Check to see if Hillary was tweeting and if it was her own tweet.
if row[2] == "HillaryClinton" and row[4] == "True":
# If she was, append the number 1 to the list to keep track of how many times she did.
originalTweet.append(1)
else:
# Else, append the number 0.
originalTweet.append(0)
# Check to see if Hillary was tweeting and if she used a hashtag.
if row[2] == "HillaryClinton" and row[17] == "True":
# If she was, append the number 1 to the list to keep track of how many times she did.
hashtags.append(1)
else:
# Else, append the number 0.
hashtags.append(0)
# Calculate the percentage of original tweets out of all tweets.
originalTweetPercentage = ( (sum(originalTweet)/sum(indexes)) * 100 )
# Calculate the percentage of tweets that had hashtags out of all tweets.
hashtagsPercentage = ( (sum(hashtags)/sum(indexes)) * 100 )
# Label the pie chart.
labels = ("original tweet", "used hashtags")
sizes = [originalTweetPercentage,hashtagsPercentage]
explode = [0.1,0.1]
figure1, ax1 = plt.subplots()
ax1.pie(sizes,explode=explode,labels=labels, autopct="%1.1f%%")
# Add the graph title.
ax1.set_title("Hillary Clinton Tweets Analysis")
ax1.axis("equal")
# Show the graph.
plt.show()
# Call the function.
hillaryTweetAnalysis()
|
print(6)
imie = "ola"
print(imie)
imie = "ola"
imie = imie.upper()
print(imie)
True and True
False and True
True or 1 == 1
1 != 2
|
#hw4.py
# Peter Podniesinski + ppodnies + H
"""
hwb Reasoning over code
f1.
#answer: x=8 y=2.
#you start the problem off by seeing x+y==10
#therefore x is between (6,8) and y can be between (2,4)
#since x>y. Then you look at the bit wise function assert.
#So you should test the possibilities. 8,2 works because
#8<<2 is 32 and 32>>2 is simply 8
f2.
#answer x=31 y=13
#in this function x>y and x+y ==44 therefore
#you can determine that x must be larger that 22
# and y can be anything less than 22. Next, you figure out
#that x%y==5 so you must choose two numbers that satisfy this
#by checking numbers after 22 you find 31, 13 work. so
#31+13 ==44 and 31 mod 13==5. This also satisfies
#13==31%10*10 + x/10 since this = 1*10 +3=13
f3.
#answer: x=67 y=1
#in this function you can determine that y cannot equal
#2 because any x >10 will already make a sumation larger than 100.
#for example 10**2==100. That means that y must equal 1. x=67 will
# satisfy the boolen restraints because 67/2=33 +67==100
f4.
#anwer: x=32 y=8
#this is because x+y==40 and x>y. The hard part
# was to satisfy the bitwise or operation. so
#(x|y == 40) Basically this will demostrate the or operation
#for binary. 32 is 100000 because binary works by 2*n and
#8 is 1000. Therefore x bitwise or y will go through the binary
#and decide if there is a the index satisfies the or which is only
#false when both are 0. Since 100000+1000=101000 you just add the two
f6.
#answer f6(18)
#First off you know that 100>x>1 next you figure out
#that y=x originally and ends up as 21 so x should be <21
#but not too small. You also know that by going through
#the loop y increments if z%7==0. If you pick 18 then y
#will increment 3 times at z=0,7,14
f9.
#answer:31
#First, you see that 100>x>10
#Next, you see that z multiplys each time by 2.
#so possible z values are 2,4,8,16,32. and one of
#these values is 1 greater than x. Next you must
#look at these numbers and figure out what x/6 equals.
#because this will be the number of times y increments.
#x=31 will work because z*2 will happen 6 times making
#z=32. then y==31/6= 5 this value works because y will
#increment 5 times accoring to the while condition z<x
"""
######################################################################
# Place your non-graphics solutions here!
######################################################################
import random
import math
import string
def convertToNumber(s,solution):
number=0
for index in xrange(len(s)):
for digits in xrange(len(solution)):
if(s[index]==solution[digits]):
#if index in s1== index in puzzle
#add the index to digits to start converting
number*=10
number+=digits
#multiply to shift total over one place holder
return number
#print convertToNumber("MONEY","OMY--ENDRS")
def solvesCryptarithm(puzzle, solution):
(s1,s2,s3)=(puzzle[:puzzle.find("+")],puzzle[puzzle.find("+")+1:puzzle.find("=")],
puzzle[puzzle.find("=")+1:len(puzzle)])
#this splits the puzzle into 3 different string
number1=convertToNumber(s1,solution)
number2=convertToNumber(s2,solution)
number3=convertToNumber(s3,solution)
#if the sum of converted numbers=number3 we have a correct
#solution.
if(number1+number2==number3):
return True
else:
return False
#print solvesCryptarithm("SEND+MORE=MONEY","OMY--ENDRS")
import copy
def findWords(dictionary,hand):
word=""
copyHand=copy.copy(hand)
possibleWords=[]
i=0
charUseCount=0
charRepeatCount=[0]*len(hand)
for i in xrange(len(dictionary)):
for j in xrange(len(dictionary[i])):
for k in xrange(len(hand)):
#create possible hands by reaarranging char's in list hand
if ((dictionary[i][j]==hand[k])and charRepeatCount[k]==0
and charUseCount==0):
#charRepeatCount makes sure the same character is not
#used more than once
print word
word+=hand[k]
charRepeatCount[k]+=1
charUseCount+=1
charUseCount=0
#for every word in dictionary reset charRepeatCount
if (word==dictionary[i]):
#if the word == word in dictionary at end of loop
#add word to possible Words.
possibleWords+=[word]
charRepeatCount=[0]*len(hand)
word=""
if(len(possibleWords)==0):
return None
else:
return possibleWords
print findWords(['xyz', 'zxy', 'zzy', 'yy', 'yx', 'wow'], ['x', 'y', 'z', 'y'])
def score(letterScores,hand):
score=0
alphabet = string.ascii_lowercase
#finds the possible words that can be made from the hand.
if(hand==None):
return 0
for i in xrange(len(hand)):
for j in xrange(len(hand[i])):
for k in xrange(len(letterScores)):
if(hand[i][j]==alphabet[k]):
#if the character is the same char in alphabet
#add the value from letterscore to score since alphabet
#and letterscore is same length
score+=letterScores[k]
return score
#print score([1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5,
# 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1], ['x', 'y', 'z'])
def bestScrabbleScore(dictionary, letterScores,hand):
bestScrabbleScore=[]
bestScore=0
possibleMoves=findWords(dictionary,hand)
if(possibleMoves==None):
return None
print possibleMoves
for index in xrange(len(possibleMoves)):
if(score(letterScores,possibleMoves[index])>=bestScore):
#compares bestscore so far, finds the index
#print bestScore, bestScrabbleScore
bestScore=score(letterScores,possibleMoves[index])
bestScrabbleScore+=[possibleMoves[index]]
if(len(bestScrabbleScore)==1):
return bestScrabbleScore[0], bestScore
else:
return bestScrabbleScore, bestScore
print bestScrabbleScore(['xyz', 'zxy', 'zzy', 'yy', 'yx', 'wow'],
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5,
1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1], ['w', 'x', 'z'])
######################################################################
##### ignore_rest: The autograder will ignore all code below here ####
######################################################################
# Othello case study
import random
def make2dList(rows, cols):
a=[]
for row in xrange(rows): a += [[0]*cols]
return a
def hasMove(board, player):
(rows, cols) = (len(board), len(board[0]))
for row in xrange(rows):
for col in xrange(cols):
if (hasMoveFromCell(board, player, row, col)):
return True
return False
def hasMoveFromCell(board, player, startRow, startCol):
(rows, cols) = (len(board), len(board[0]))
if (board[startRow][startCol] != 0):
return False
for dir in xrange(8):
if (hasMoveFromCellInDirection(board, player, startRow, startCol, dir)):
return True
return False
def hasMoveFromCellInDirection(board, player, startRow, startCol, dir):
(rows, cols) = (len(board), len(board[0]))
dirs = [ (-1, -1), (-1, 0), (-1, +1),
( 0, -1), ( 0, +1),
(+1, -1), (+1, 0), (+1, +1) ]
(drow,dcol) = dirs[dir]
i = 1
while True:
row = startRow + i*drow
col = startCol + i*dcol
if ((row < 0) or (row >= rows) or (col < 0) or (col >= cols)):
return False
elif (board[row][col] == 0):
# no blanks allowed in a sandwich!
return False
elif (board[row][col] == player):
# we found the other side of the 'sandwich'
break
else:
# we found more 'meat' in the sandwich
i += 1
return (i > 1)
def makeMove(board, player, startRow, startCol):
# assumes the player has a legal move from this cell
(rows, cols) = (len(board), len(board[0]))
for dir in xrange(8):
if (hasMoveFromCellInDirection(board, player, startRow, startCol, dir)):
makeMoveInDirection(board, player, startRow, startCol, dir)
board[startRow][startCol] = player
def makeMoveInDirection(board, player, startRow, startCol, dir):
(rows, cols) = (len(board), len(board[0]))
dirs = [ (-1, -1), (-1, 0), (-1, +1),
( 0, -1), ( 0, +1),
(+1, -1), (+1, 0), (+1, +1) ]
(drow,dcol) = dirs[dir]
i = 1
while True:
row = startRow + i*drow
col = startCol + i*dcol
if (board[row][col] == player):
# we found the other side of the 'sandwich'
break
else:
# we found more 'meat' in the sandwich, so flip it!
board[row][col] = player
i += 1
def getPlayerLabel(player):
labels = ["-", "X", "O","."]
return labels[player]
def printColLabels(board):
(rows, cols) = (len(board), len(board[0]))
print " ", # skip row label
for col in xrange(cols): print chr(ord("A")+col),
print
def printBoard(board,player):
(rows, cols) = (len(board), len(board[0]))
printColLabels(board)
for row in xrange(rows):
print "%2d" % (row+1),
for col in xrange(cols):
if(not isLegalMove(board,player,row,col)):
print getPlayerLabel(board[row][col]),
else:
print ".",
print "%2d" % (row+1)
printColLabels(board)
def isLegalMove(board, player, row, col):
(rows, cols) = (len(board), len(board[0]))
if ((row < 0) or (row >= rows) or (col < 0) or (col >= cols)): return False
return hasMoveFromCell(board, player, row, col)
def getMove(board, player):
print "\n**************************"
printBoard(board,player)
row=len(board)
col=len(board)
while True:
if(getPlayerLabel(player)!="X"):
rows=random.randrange(1,row+1)
cols=random.randrange(1,col+1)
while isLegalMove(board,player,rows,cols)!=True:
rows=random.randrange(1,row+1)
cols=random.randrange(1,col+1)
return (rows,cols)
prompt = "Enter move for player " + getPlayerLabel(player) + ": "
move = raw_input(prompt).upper()
# move is something like "A3"
if ((len(move) < 2) or (not move[0].isalpha()) or (not move[1].isdigit())):
print "Wrong format! Enter something like A3 or D5."
else:
col = ord(move[0]) - ord('A')
#fix condition for boards larger than 9
row = int(move[1:])-1
if (not isLegalMove(board, player, row, col)):
print "That is not a legal move! Try again."
else:
return (row, col)
def getLegalMoves(board,player):
legalMoves=[]
for rows in xrange(len(board)):
for cols in xrange(len(board[row])):
if(isLegalMove(board,player,rows,cols)):
legalMoves+=[(rows,cols)]
return LegalMoves
def score(board,player,score):
for row in range(len(board)):
for col in range(len(board)):
if(board[row][col]==player):
score+=1
return score
def playOthelloAgainstRandomComputer(rows,cols):
# create initial board
board = make2dList(rows, cols)
board[rows/2][cols/2] = board[rows/2-1][cols/2-1] = 1
board[rows/2-1][cols/2] = board[rows/2][cols/2-1] = 2
(currentPlayer, Computer) = (1, 2)
scoreCurrentPlayer,scoreOtherPlayer=(0,0)
# and play until the game is over
while True:
if (hasMove(board, currentPlayer) == False):
if (hasMove(board, Computer)):
print "No legal move! PASS!"
(currentPlayer, Computer) = (Computer, currentPlayer)
else:
print "No more legal moves for either player! Game over!"
break
print "Score:", score(board,currentPlayer,scoreCurrentPlayer), "," ,
print score(board,Computer,scoreOtherPlayer)
(row, col) = getMove(board, currentPlayer)
makeMove(board, currentPlayer, row, col)
(currentPlayer, Computer) = (Computer, currentPlayer)
print "Goodbye!"
#playOthelloAgainstRandomComputer(8,8)
def playOthello(rows, cols):
# create initial board
board = make2dList(rows, cols)
board[rows/2][cols/2] = board[rows/2-1][cols/2-1] = 1
board[rows/2-1][cols/2] = board[rows/2][cols/2-1] = 2
(currentPlayer, otherPlayer) = (1, 2)
scoreCurrentPlayer,scoreOtherPlayer=(0,0)
# and play until the game is over
while True:
if (hasMove(board, currentPlayer) == False):
if (hasMove(board, otherPlayer)):
print "No legal move! PASS!"
(currentPlayer, otherPlayer) = (otherPlayer, currentPlayer)
else:
print "No more legal moves for either player! Game over!"
break
print "Score:", score(board,currentPlayer,scoreCurrentPlayer), "," ,
print score(board,otherPlayer,scoreOtherPlayer)
(row, col) = getMove(board, currentPlayer)
makeMove(board, currentPlayer, row, col)
(currentPlayer, otherPlayer) = (otherPlayer, currentPlayer)
print "Goodbye!"
#playOthello(8,8)
#start of Memory Game
import time
import math
def make2dList(rows,cols):
a=[]
for row in xrange(rows): a += [[0]*cols]
return a
def getPlayerLabel(player):
labels = ["$", "X", "O"]
return labels[player]
def printColLabels(board):
(rows, cols) = (len(board), len(board[0]))
print " ", # skip row label
for col in xrange(cols): print chr(ord("A")+col),
print
def printBoard(board,hidden):
(rows, cols) = (len(board), len(board[0]))
printColLabels(board)
for row in xrange(rows):
print "%2d" % (row+1),
for col in xrange(cols):
if(board[row][col]!=0):
print hidden[row][col],
else:
print getPlayerLabel(board[row][col]),
print "%2d" % (row+1)
printColLabels(board)
def spacesHidden(board):
spacesHidden=0
for row in range(len(board)):
for col in range(len(board)):
#print board[row][col]
if(board[row][col]!=0):
pass
else:
spacesHidden+=1
return spacesHidden
def isLegalMove(board,row1, col1, row2,col2):
(rows, cols) = (len(board), len(board[0]))
if ((row1 < 0) or (row1 >= rows) or (row2<0) or(row2>=rows) or (col1 < 0) or (col1 >= cols)
or (col2<0) or(col2>=cols)):
return False
return True
def getMove(board,hidden,score):
print "\n**************************"
printBoard(board,hidden)
prompt= "Enter your guess:"
move=raw_input(prompt).upper()
if ((len(move)<7)or((move[1].isalpha() and move[4].isalpha())!=True)
or ((move[2].isdigit() and move[5].isdigit()) !=True)):
print "Wrong format! Enter something like (A3,D5)"
else:
col1 = ord(move[1]) - ord('A')
row1 = int(move[2:move.find(",")])-1
col2 = ord(move[4]) - ord('A')
row2 = int(move[5:move.find(")")])-1
if (not isLegalMove(board, row1, col1,row2,col2)):
print "That is not a legal move! Try again."
else:
return makeMove(board,hidden, row1, col1, row2,col2,score)
def makeMove(board,hidden,row1,col1,row2,col2,score):
#check if hidden numbers are the same
rows=len(board)
cols=len(board[0])
#hidden=hiddenNumbers(rows,cols)
if(hidden[row1][col1]==hidden[row2][col2]):
board[row1][col1]=hidden[row1][col1]
board[row2][col2]=hidden[row2][col2]
print "You guessed right!"
else:
print "Try another guess"
board[row1][col1]=hidden[row1][col1]
board[row2][col2]=hidden[row2][col2]
printBoard(board,hidden)
board[row1][col1]=0
board[row2][col2]=0
score+=1
#print board, hidden
def hiddenNumbers(rows,cols):
#this function encodes the numbers from 1 to RC
#into an array a random amount exactly 2 times
hiddenNumbers=make2dList(rows,cols)
maxNumber=(rows*cols)/2
randomNumberCount=[0]*maxNumber
#print maxNumber, len(randomNumberCount)
for row in xrange(rows):
for col in xrange(cols):
randomNumber=random.randrange(1,maxNumber+1)
#range 1,R*C
while randomNumberCount[randomNumber-1]>=2:
#subtract 1 to avoid index out of range
#makes sure you choose a number no more than twice.
randomNumber=random.randrange(1,maxNumber+1)
else:
hiddenNumbers[row][col]=randomNumber
randomNumberCount[randomNumber-1]+=1
return hiddenNumbers
def playMemoryGame(rows,cols):
board=make2dList(rows,cols)
#printBoard(board)
hidden=hiddenNumbers(rows,cols)
score=0
startTime=time.time()
while spacesHidden(board)!=0:
getMove(board,hidden,score)
printBoard(board,hidden)
endTime=time.time()
return "Your score is:", score, "Your time is:", round(endTime-startTime),"seconds!"
#return 42
#print playMemoryGame(2,2)
######################################################################
# Place your (optional) additional tests here
######################################################################
import sys
from cStringIO import StringIO
def consoleFreeCall(fn, args, inputStrings=[]):
outputStrings = "<failed to capture console output>"
originalOut = sys.stdout
global raw_input
originalRawInput = raw_input
try:
sys.stdout = StringIO()
if (inputStrings != []):
def newRawInput(prompt=""): return inputStrings.pop(0)
raw_input = newRawInput
fn(*args)
outputStrings = sys.stdout.getvalue()
sys.stdout.close()
finally:
sys.stdout = originalOut
raw_input = originalRawInput
return outputStrings
def g(x):
while True:
y = int(raw_input("Enter y (0 when done): "))
if (y == 0): break
print "%d*%d is %d" % (x, y, x*y)
def runConsoleFreeTests():
print "running console-free tests...",
assert(consoleFreeCall(f, [42]) == "2*42 is 84\n")
assert(consoleFreeCall(g, [2], ["3", "4", "0"]) == "2*3 is 6\n2*4 is 8\n")
print "passed!"
#runConsoleFreeTests()
def runMoreStudentTests():
print "Running additional tests...",
def testBestScrabbleScore():
print "testing.. " ,
assert(bestScrabbleScore(["hi","hey","hello"],[
# a, b, c, d, e, f, g, h, i, j, k, l, m
1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3,
# n, o, p, q, r, s, t, u, v, w, x, y, z
1, 1, 3,10, 1, 1, 1, 1, 4, 4, 8, 4,10], [
"h","y","e","l","i","l","o"]) == ["hello"],14)
print "passed BestScrabbleScore "
def testSolvesCryptarithm():
print "testing.. ",
assert(solvesCryptarithm("SEND+MORE=MONEY","OMY--ENDRS")==True)
assert(solvesCryptarithm("SEND+MARE=MONEY","OMY--ENDRS")==False)
assert(solvesCryptarithm("SzND+ARE=MONEY","OSY--EZDRW")==False)
print "passed..SolvesCryptarithm "
print "Passed them all!"
######################################################################
# Place your graphics solutions here!
######################################################################
######################################################################
# Drivers: do not modify this code
#####################################################################
######################################################################
# Main: you may modify this to run just the parts you want to test
######################################################################
def main():
# include following line to autograde when you run this file
#execfile("hw2-public-grader.py", globals())
runMoreStudentTests()
#testBestScrabbleScore()
#testSolvesCryptarithm()
if __name__ == "__main__":
main()
|
# hw8.py
# <ppodnies>, <H>
# Implement the required classes (all above the ignore_rest line)
# so that the testAll function runs without errors.
# There are 4 classes to implement: Util, Line, Frog, and RepetitiveFrog.
# Be sure not to modify any code below the ignore_rest line!
# One of the classes models the mathematical notion of a line,
# represented in slope-intercept (m,b) form. Note that this class
# stores m and b as instances of Python's built-in Fraction class.
# You should read more about that class here:
# http://docs.python.org/2/library/fractions.html
# One curious thing is that several of our Line class's methods return
# int values for integers but otherwise return Fractions.
# For example, if the slope m is 2, getSlope returns 2, but if the slope is
# 2/3, getslope returns Fraction(2,3). This is unusual.
from fractions import Fraction
########################
# YOUR CODE GOES HERE! #
########################
class Frog(object):
message="ribbit!"
def speak(self):
return Frog.message
def __eq__(self):
pass
@classmethod
def setMsg(cls,message):
Frog.message=message
class RepetitiveFrog(Frog):
def speak(self):
return Frog.message+" "+Frog.message+" "+Frog.message
class Util(object):
def __init__(self,number):
pass
@classmethod
def intOrFraction(cls,number):
if(int(number)==number):
return int(number)
else:
return number
def __str__(self):
pass
def __eq__(self):
pass
from fractions import Fraction
class Line(object):
def __init__(self,slope,intercept):
self.slope=slope
self.intercept=intercept
def getSlope(self):
"""Return the slope (m) of the line."""
return self.slope
def getIntercept(self):
return self.intercept
def getIntersection(self,other):
pass
#@classmethod
def isParallelTo(self,other):
if(Line.getSlope(self)== Line.getSlope(other)):
return True
else:
return False
def __str__(self):
if(self.slope==0):
return "y=%s"%(self.intercept)
elif(abs(self.slope)==1):
if(self.slope==1):
if(self.intercept>0):
return "y=x+%s"%(self.intercept)
else:
return"y=x%s"%(self.intercept)
else:
if(self.intercept>0):
return "y=-x+%s"%(self.intercept)
else:
return"y=-x%s"%(self.intercept)
elif(self.slope>1):
if(self.intercept>0):
return "y=%sx+%s" % (self.slope, self.intercept)
else:
return "y=%sx%s" % (self.slope, self.intercept)
elif(self.slope<0):
if(self.intercept>0):
return "y=-%sx+%s" % (self.slope, self.intercept)
else:
return "y=-%sx%s" % (self.slope, self.intercept)
#if slope and intercept are both a fraction
elif(int(self.slope)!=self.slope)and(int(self.intercept)!=self.intercept):
if(self.slope>0):
if(self.intercept>0):
return "y=%s/%sx+%s/%s" % (self.slope.numerator, self.slope.denominator,
self.intercept.numerator,self.intercept.denominator)
else:
return "y=%s/%sx%s/%s" % (self.slope.numerator, self.slope.denominator,
self.intercept.numerator,self.intercept.denominator)
elif(self.slope<0):
if(self.intercept>0):
return "y=-%s/%sx+%s/%s" % (self.slope.numerator, self.slope.denominator,
self.intercept.numerator,self.intercept.denominator)
else:
return "y=-%s/%sx%s/%s" % (self.slope.numerator, self.slope.denominator,
self.intercept.numerator,self.intercept.denominator)
#if slope is only a fraction
elif(int(self.slope)!=self.slope):
if(self.slope>0):
if(self.intercept>0):
return "y=%s/%sx+%s" % (self.slope.numerator, self.slope.denominator,
self.intercept)
else:
return "y=%s/%sx%s" % (self.slope.numerator, self.slope.denominator,
self.intercept)
elif(self.slope<0):
if(self.intercept>0):
return "y=-%s/%sx+%s" % (self.slope.numerator, self.slope.denominator,
self.intercept)
else:
return "y=-%s/%sx%s" % (self.slope.numerator, self.slope.denominator,
self.intercept)
#only intercept is fraction
elif(int(self.intercept)!=self.intercept):
if(self.slope>0):
if(self.intercept>0):
return "y=%sx+%s/%s" % (self.slope,self.intercept.numerator,self.intercept.denominator)
else:
return "y=%sx%s/%s" % (self.slope,
self.intercept.numerator,self.intercept.denominator)
elif(self.slope<0):
if(self.intercept>0):
return "y=-%sx+%s/%s" % (self.slope,
self.intercept.numerator,self.intercept.denominator)
else:
return "y=-%sx%s/%s" % (self.slope,
self.intercept.numerator,self.intercept.denominator)
def __repr__(self):
return "Line(%r, %r)" %(self.slope,self.intercept)
def __hash__(self):
return hash((self.slope,self.intercept))
def __eq__(self, other):
if(type(self)==type(other)):
return True
else:
return False
if((Line.getSlope(self)==Line.getSlope(other))and
(Line.getIntercept(self)==Line.getIntercept(other))):
return True
else:
return False
def getIntersection(self,other):
intersectionXNum=(Line.getIntercept(other)-Line.getIntercept(self))
intersectionXDen=(Line.getSlope(self)-Line.getSlope(other))
#print intersectionXNum,intersectionXDen
cx=Fraction(intersectionXNum,intersectionXDen)
#print cx.numerator, cx.denominator
y=(Line.getSlope(self)*cx)+Line.getIntercept(self)
return (cx,y)
def getNormalLine(self,x):
self.slope=-1*(1/self.slope)
######################################################################
##### ignore_rest: The autograder will ignore all code below here ####
######################################################################
def testUtilClass():
print "Testing Util class...",
x = Fraction(1,2) # 1/2
y = Util.intOrFraction(x)
assert(x is y)
x = Fraction(2,1)
y = Util.intOrFraction(x)
assert((x is not y) and (x == y) and (type(x) == Fraction) and (type(y) == int))
print "Passed!"
def testLineClass():
print "Testing Line class...",
assert(str(Line(2,5)) == "y=2x+5")
assert(str(Line(2,-5)) == "y=2x-5")
assert(str(Line(0,5)) == "y=5")
assert(str(Line(1,5)) == "y=x+5")
assert(str(Line(-1,5)) == "y=-x+5")
assert(str(Line(0,-5)) == "y=-5")
assert(str(Line(0,0)) == "y=0")
assert(str(Line(Fraction(2,3),Fraction(1,3))) == "y=2/3x+1/3")
assert(str(Line(Fraction(2,3),Fraction(-2,6))) == "y=2/3x-1/3")
# hint: be sure to understand the difference between str(x) and repr(x)
assert(str([Line(0,1), Line(1,0)]) == "[Line(0, 1), Line(1, 0)]")
assert(str([Line(Fraction(1,2),3)]) == "[Line(Fraction(1, 2), 3)]")
line1 = Line(2,3)
assert(str(line1) == "y=2x+3")
assert(line1.getSlope() == 2)
assert(type(line1.getSlope()) == int)
assert(line1.getIntercept() == 3)
assert(line1.getSlope.__doc__ == "Return the slope (m) of the line.")
line2 = Line(6,-5)
assert(str(line2) == "y=6x-5")
assert(line2.getSlope() == 6)
assert(line2.getIntercept() == -5)
assert(line1.getIntersection(line2) == (2, 7))
line3 = Line(2, -3)
assert(line3.isParallelTo(line1) == True)
assert(line3.isParallelTo(line2) == False)
# Two lines intersect in a point!
assert(line3.getIntersection(line2) == (Fraction(1,2), -2))
# The normal line is the line that is perpendicular to
# the given line, intersecting at the given x value.
# Note that the product of the slopes of perpendicular lines is -1.
line4 = line3.getNormalLine(4)
assert(str(line4) == "y=-1/2x+7")
assert(line4.getSlope() == Fraction(-1,2))
assert(line4.getIntercept() == 7)
assert(Line(1, 2) == Line(1, 2))
assert(Line(1, 2) != Line(1, 3))
assert(not (Line(1, 2) == "don't crash here!"))
s = set()
assert(Line(1, 2) not in s)
s.add(Line(1, 2))
assert(Line(1, 2) in s)
s.remove(Line(1, 2))
assert(Line(1, 2) not in s)
print "Passed!"
def testFrogClass():
print "Testing Frog class...",
frog1 = Frog()
assert(frog1.speak() == "ribbit!")
frog2 = RepetitiveFrog()
assert(isinstance(frog2, Frog) == True)
assert(type(frog2) == RepetitiveFrog)
assert(frog2.speak() == "ribbit! ribbit! ribbit!")
Frog.setMsg("oink?")
assert(frog1.speak() == "oink?")
assert(frog2.speak() == "oink? oink? oink?")
print "Passed!"
def testAll():
testUtilClass()
testLineClass()
testFrogClass()
testAll()
|
def flatten(l):
if type(l) != type([]): return [l]
if l == []: return l
else:
return flatten(l[0]) + flatten(l[1:])
assert(flatten([1,[2]]) == [1,2])
print "hi2"
assert(flatten([1,2,[3,[4,5],6],7]) == [1,2,3,4,5,6,7])
print "hi3"
assert(flatten(['wow', [2,[[]]], [True]]) ==['wow', 2, True])
#print "hi4"
assert(flatten([]) ==[])
assert(flatten([[]]) ==[])
assert(flatten(3) == 3)
|
def maximum():
for x in range(100):
for y in range(100):
if((x|y) >= max(x,y))==False:
print x,y, (x|y), max(x,y)
return False
return True
print maximum()
|
from opcodes import *
class StackFullError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class StackedEmulator(object):
"""
Stacked is a basic stack machine emulator. The memory architecture and structure
follows a Harvard Architecture:
+-----------+ +-------------+
| CPU |<=====>| Data Memory |
| | +-------------+
| |
| | +----------------+
| |<=====>| Program Memory |
| | +----------------+
+-----------+
Instructions are 16-bits wide, all data paths are 16 bits.
"""
def __init__(self, pmem, dmem, N=32): # Initialize pmem and dmem
self.pmem = pmem # program memory
self.dmem = dmem # data memory [FIXME]
self.pc = 0 # Program Counter
self.dstack = [] # data stack of size N
self.rstack = [] # return stack
self.ir = 0 # current instruction register
self.N = N
def fetch(self):
"""
Load instruction from program memory into the instruction register.
"""
self.ir = self.pmem[self.pc]
def __popr(self):
return self.rstack.pop()
def __popd(self):
return self.dstack.pop()
def __pushr(self, val):
if len(self.rstack) < self.N:
self.rstack.append(val)
return 0
else:
raise
def __pushd(self, val):
if len(self.dstack) < self.N:
self.dstack.append(val)
return 0
else:
raise
def decode(self, cmd=None):
"""
Decode things
"""
opcode = (self.ir & 0xf000) >> 12
imm = (self.ir & 0x0fff)
state = 1
self.pc += 1
if opcode == Opcodes.HALT:
print "HALT"
self.state = 0
self.pc -= 1
elif opcode == Opcodes.PUSH:
print "PUSHI {0}".format(self.dmem[imm])
try:
self.__pushd(self.dmem[imm])
except:
print "Oh No... Stack Full"
elif opcode == Opcodes.PUSHI:
print "PUSH {0}".format(imm)
try:
self.__pushd(imm)
except:
print "Oh No... Stack Full"
elif opcode == Opcodes.STORE:
self.dmem[imm] = self.dstack.pop()
print "STORE {0}".format(self.dmem[imm])
elif opcode == Opcodes.DUP:
self.dstack.append(self.dstack[-1]) # duplicate the TOS
print "DUP"
elif opcode == Opcodes.OVER:
self.dstack.append(self.dstack[-2])
print "OVER"
elif opcode == Opcodes.SWAP:
n1 = self.dstack.pop()
n2 = self.dstack.pop()
self.dstack.append(n2)
self.dstack.append(n1)
print("SWAP {0} {1}".format(n1, n2))
elif opcode == Opcodes.BEZ:
print "BZE",
res = self.dstack.pop()
if (res == 0):
print "MOVE TO {0}".format(imm)
self.pc = imm
else:
print "NO JUMP"
elif opcode == Opcodes.BNEZ:
print "BNZE",
res = self.dstack.pop()
if (res != 0):
print "MOVE TO {0}".format(imm)
self.pc = imm
else:
print "NO JUMP"
elif opcode == Opcodes.ALU:
if imm == Opcodes.ALU_ADD:
one = self.dstack.pop()
two = self.dstack.pop()
res = (two + one) & 0xFF
print "{0} {1} ADD = {2}".format(one, two, res)
self.dstack.append(res)
elif imm == Opcodes.ALU_SUB:
one = self.dstack.pop()
two = self.dstack.pop()
res = (two - one) & 0xFF
print "{0} {1} SUB = {2}".format(one, two, res)
self.dstack.append(res) |
import unittest # unittest is a LIBRARY
from simple_calc import SimpleCalc # we do not currently have this {file} or this {class}.
class Calctest(unittest.TestCase):
calc = SimpleCalc()
def test_add(self):
self.assertEqual(self.calc.add(2, 4), 6)
self.assertEqual(self.calc.add(4, 4), 8)
def test_subtract(self):
self.assertEqual(self.calc.subtract(2, 4), -2)
self.assertEqual(self.calc.subtract(10, 5), 5)
def test_multiply(self):
self.assertEqual(self.calc.multiply(2, 3, ), 6)
self.assertEqual(self.calc.multiply(10, 8, ), 80)
def test_divide(self):
self.assertEqual(self.calc.divide(8, 4), 2)
self.assertEqual(self.calc.divide(16, 8), 2)
|
'''File Name: writer-bot-ht.py
Author: Longxin Li
Purpose: this program will print out the random lyrics
that follow the Markov chain analysis, and
each line has ten words.
CS120'''
import random # import the random.
SEED = 8
NONWORD = '@'
random.seed(SEED) # set the random seed.
class Hashtable:
def __init__(self, size):
'''Initializes the object with information
extracted from line.
Parameters: size is the size of the hashtable.
Returns: None.
Pre-condition: size is an integer.
Post-condition: None.'''
self._size = size
self._pair = [None] * size
def _hash(self, key):
'''The method to calc the index of the key.
Parameters: key is a the pair of the words.
Returns: The index of the key.
Pre-condition: key is a string.
Post-condition: index is an integer.'''
p = 0
for c in key:
p = 31 * p + ord(c)
return p % self._size
def put(self, key, value):
'''To put the key and value into the hashtable.
Parameters: key is a the pair of the words, value is
the next words behind key.
Returns: None.
Pre-condition: key is a string, value is a list.
Post-condition: None.'''
hash_value = self._hash(key)
flag = True
if self._pair[hash_value] is None:
self._pair[hash_value] = [key, [value]]
else:
while self._pair[hash_value] is not None:
if self._pair[hash_value][0] == key:
self._pair[hash_value][1].append(value)
flag = False
break
hash_value -= 1
if flag:
self._pair[hash_value] = [key, [value]]
def get(self, key):
'''To find if the key is available in the hashtable.
Parameters: key is a the pair of the words.
Returns: The value of the key or None.
Pre-condition: key is a string.
Post-condition: string or None.'''
index1 = self._hash(key)
for i in range(self._size):
if self._pair[index1] is None:
return None
elif self._pair[index1][0] ==key:
return self._pair[index1][1]
index1-=1
if index1==-1:
index1=self._size-1
return None
def __contains__(self, key):
'''To find if the key is in the hashtable.
Parameters: key is a the pair of the words.
Returns: True or False.
Pre-condition: key is a string.
Post-condition: True or None.'''
return self.get(key) is None
def __str__(self):
'''This function is to just return the
attributes of the each class.
Parameters: None.
Returns: The attributes of the each class.
Pre-condition: None.
Post-condition: String.'''
return str(self._pair)
def enter():
'''Ask user to input the name of the lyrics, the
size for prefix in Markov chain analysis, and how
many words user wants to print out.
Parameters: None.
Returns: source_txt is the txt name for the lyrics.
prefix_size is the size for prefix in Markov chain
analysis, random_size is number of the words user
wants to print out.
Pre-condition: None.
Post-condition: source_txt is a string, prefix_size
and random_size are all int'''
source_txt = input()
table_size = int(input())
prefix_size = int(input())
if prefix_size < 1:
print('ERROR: specified prefix size is less than one')
exit()
random_size = int(input())
if random_size < 1:
print('ERROR: specified size of the generated text is less than one')
exit()
return source_txt, prefix_size, random_size, table_size
def readfile(source_txt, prefix_size):
'''Go through the lyrics and stored it in to a list.
Parameters: source_txt is the txt name for the lyrics. prefix_size
is the size for prefix in Markov chain analysis.
Returns: list1 is a list that sotred the lyrics word by
word, stored is a tuple that stored NONWORD as
first word's prefix.
Pre-condition: source_txt is a string, prefix_size is int.
Post-condition: list1 is a list, stored is a tuple.'''
list1 = []
for i in range(prefix_size):
list1.append(NONWORD) # create the empty for first word's prefix.
key=' '.join(list1)
open_file = open(source_txt) # open the file.
for line in open_file:
line = line.strip('/n').strip(' ').split() # split every word by space.
for word in line:
list1.append(word) # store the words orderly.
return list1,key
def store(list1, prefix_size, hash):
'''Store the data from the lyrics into a dictionary, prefix is key
and values will be the word behind key. The text generation
continues until the last suffix is reached, or until a sufficient
amount of text has been generated.
Parameters: list1 is a list that sotred the lyrics word by
word, prefix_size is the size for prefix in Markov chain
analysis.
Returns: dict1 is a dictionary that stord the lyrics data.
Pre-condition: list1 is a list, prefix_size is int.
Post-condition: dict1 is a dictionary'''
key1 = tuple(list1) # make list1 hasable, and will save as tuple.
for i in range(len(list1) - prefix_size):
key = ' '.join(key1[i:prefix_size + i])
value = list1[i + prefix_size]
hash.put(key, value)
def output(hash, random_size, key):
'''Find all the words that should print out folllow the Markov chain
analysis and store that word by word into a list.
Parameters: dict1 is a dictionary that stord the lyrics data,
random_size is number of the words user wants to print out.
stored is a tuple that stored NONWORD as first word's prefix.
Returns: output_list is a list that with all the words should print out.
Pre-condition: dict1 is a dictionary, random_size is int, stored is a
tuple.
Post-condition: output_list is a list'''
output_list = []
while len(output_list) < random_size: #length need same with random_size.
values = hash.get(key)
if values is None:
break
if len(values) > 1: #ckeck if there has more than one values.
loca = random.randint(0,len(values)-1)
value = values[loca] #get 'random' value folllow the seed.
else:
value = values[0]
output_list.append(value)
key = key.split(' ')+[value] #change key to next one.
key=' '.join(key[1:])
return output_list
def printout(output_list):
'''Check the nomber of words each line, make sure every line at most has
ten words, then print out those words every line with ten words.
Parameters: output_list is a list that with all the words should print
out.
Returns: The random lyrics folllow the Markov chain analysis.
Pre-condition: output_list is a list.
Post-condition: The output are many strings'''
out_list = []
number1 = 0
number2 = 10 # max words for each line is 10.
for times in range(len(output_list)):
data = []
data.append(output_list[number1:number2]) # find words in each line.
out_list.append(data[0])
number1 += 10
number2 += 10 # move to next ten words.
if output_list[number1:number2] == []:
break # if run over all the words, stop.
for i in out_list:
print(' '.join(i)) # put all word togeter, space between two words.
def main():
source_txt, prefix_size, random_size, table_size = enter()
list1,key= readfile(source_txt, prefix_size)
hash = Hashtable(table_size)
store(list1, prefix_size, hash)
result=output(hash, random_size, key)
printout(result)
main()
|
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def create(self, data):
if self.root is None:
self.root = Node(data)
else:
temp = self.root
while True:
if data < temp.data:
if temp.left is None:
temp.left = Node(data)
break
else:
temp = temp.left
elif data > temp.data:
if temp.right is None:
temp.right = Node(data)
break
else:
temp = temp.right
else:
break
def preorder(root):
if root is None:
return
print(root.data)
preorder(root.left)
preorder(root.right)
a = BinaryTree()
l = int(input("Enter length: "))
for i in range(l):
num = int(input("Enter num: "))
a.create(num)
preorder(a.root)
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linked_list:
def __init__(self):
self.head = None
self.temp = None
def push(self, data):
node = Node(data)
if self.head is None:
self.head = node
else:
self.temp.next = node
self.temp = node
def getNode(head, pos):
current = head
prev = None
following = current.next
while current is not None:
current.next = prev
prev = current
current = following
if following is not None:
following = following.next
head = prev
count = 0
n = head
while n is not None:
if count == pos:
return n.data
else:
n = n.next
count = count +1
test = int(input("Enter no. of test cases: "))
for i in range(test):
a = Linked_list()
l = int(input("Enter length of list: "))
for j in range(l):
num = int(input("Enter no.: "))
a.push(num)
pos = int(input("Enter pos: "))
print(getNode(a.head, pos)) |
def deans_list(grades):
empty_dict = {}
store = set()
for key,value in grades.items():
if value >= 3.5:
empty_dict[key] = value
print(empty_dict)
for key in empty_dict.keys():
store.add(key)
print(store)
deans_list({"Hermione": 4, "Harry": 3.4, "Ron": 3.4, "Ginny": 3.8, "Draco": 3.7})
|
sandwich_orders = ["Bacon","Beef","cheese","chicken"]
finished_sandwiches = []
while sandwich_orders:
done = sandwich_orders.pop()
print(f"\nI made your {done} sandwich...\n")
finished_sandwiches.append(done)
print("-- sandwiches that was made --\n")
for finished_sandwich in finished_sandwiches:
print("-",finished_sandwich.title())
|
#dictionary is collection of key-value pairs
students = { "key1":"value1" ,"key2":"value2","key3":"value3" } #general syntax of dictionary
print(students)
alien = {"color":"green","points":100}
print(alien)
#keys are unique
print(alien.get("color"))
print(alien["color"])
alien["red"] = 200
alien["black"] = 150
alien["yellow"] = "color"
print(alien)
print("__"*30)
color = {} #empty dictionary
color = {"green":100}
color["red"] = 200
color["black"] = 90
print(color)
#access the value
print(color["black"])
#modify the value
color["red"]=500
print(color)
#remove the value
del color["green"]
print(color)
print("__"*30)
#loop through all key/value pairs
for key,value in color.items():
print(key,value)
print("__"*30)
for key in color.keys():
print(key)
print("__"*40)
for key in sorted(color.keys()):
print(key)
print("__"*40)
for value in color.values():
print(value)
print("__"*40)
persons = {"Allison":18 , "Benson":48 , "Paul":28 , "Erik":20, "Grace":25}
print(persons)
persons["stuart"]=98
print(persons)
#when we add entries in dictionary order is not maintained
#order is random
#key must be initialized = ""
persons[""] = 34
print(persons)
#why dict is so important data structure
#dictionary lookup is very fast
if "Paul" in persons.keys(): #membership
print("paul's age",persons["Paul"])
|
def print_numbers1():
for i in range(1,5+1):
for j in range(i):
print(i,end="")
j += 1
print()
print_numbers1() |
dot1 = 4
num = 1
dot2 = 0
for i in range(5):
for j in range(5):
print("." * dot1,num ,"." * dot2,sep="")#sep= is used to remove unwanted space
break
dot1 = dot1 - 1
num = num + 1
dot2 = dot2 + 1
|
def floyds_triangle(n):
k= 1
for i in range(1,n+1):
for j in range(1,i+1):
print(k,end=" ")
k = k + 1
print()
floyds_triangle(5) |
def print_numbers2():
dot = 4
num = 1
for i in range(5):
for j in range(5):
print("." * dot, f"{num}"*num ,sep="")
break
dot = dot - 1
num = num +1
print_numbers2() |
#write a program to check if given number is odd or even
def isEvenOdd(number):
if number % 2 == 0:
print(number,"is even")
else:
print(number,"is odd")
isEvenOdd(number=int(input("enter a number:")))
#for i in range(0,5):
# isEvenOdd(i)
#for countdown in 5,10,3,1:
# print(countdown)
#how to create a list
#cities = ["mumbai","pune","New York"]
#for city in cities:
# print(city)
|
# Game - object represents the current game state
import random
class Game():
# Static Variables
ships = ["carrier", "battleship", "cruiser", "submarine", "destroyer"]
ship_size = {"carrier": 5, "battleship": 4, "cruiser": 3, "submarine": 3, "destroyer": 2}
ship_color = {"carrier": "cyan", "battleship": "green", "cruiser": "purple", "submarine": "blue", "destroyer": "yellow"}
team_colors = ["Red", "Blue", "Green", "Purple"]
move_markers = {"HIT": "red", "MISS": "dark gray", "SUNK": "black", "DEFAULT": "SystemButtonFace"}
rows = ["+", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
row_map = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "I": 9, "J": 10}
cardinals = ["N", "S", "W", "E"]
def __init__(self, player_count):
self.player_count = player_count
self.players = {} # key: player num, value: player object
self.player_update = {} # key: player object, value: need update (T) or up to date (F)
self.teams = {} # key: team color, value: list of players (by player_num)
self.teams_alive = {} # key: team color, alive (T) or dead (F)
self.team_turn = None # Keeps track of whose turn it is
self.first_team_turn = None # Keeps track of which team took the first turn
self.turn_count = 1 # Current turn count
self.team_winner = None
# Game Phases
self.player_join_count = 0 # Keep track of players ready to transition to setup phase
self.player_ready_count = 0 # Keep track of players ready to transition to game phase
self.player_end_count = 0 # Keep track of players ready to transition to end phase
self.game_setup = False
self.game_start = False
self.game_end = False
self.player_nums = 0
def assign_player_num(self):
self.player_nums += 1
return self.player_nums
def add_player(self, player, player_num):
self.players[player_num] = player
self.player_update[player] = False
def get_player(self, player_num):
return self.players[player_num]
def add_team(self, team, player_num):
if team not in self.teams:
self.teams[team] = []
self.teams_alive[team] = True
team_list = self.teams[team]
team_list.append(player_num)
def enough_teams(self):
if len(list(self.teams.keys())) > 1:
return True
else:
return False
def select_first_team(self):
# Randomly select a team to be first
team_list = list(self.teams.keys())
self.team_turn = team_list[random.randrange(len(team_list))]
self.first_team_turn = self.team_turn
def get_current_team_turn(self):
return self.team_turn
def make_move(self, attacker, defender, row, col):
msg = defender.set_move(row, col)
# Update state buffers for every player
self.add_to_state_buffer(msg + ' ' + attacker.username + ' ' + defender.username + ' ' +
str(row) + ' ' + str(col))
self.game_update(attacker, defender) # Update the game state
def game_update(self, attacker, defender):
# Update ship state for updating player, update state buffer for every player
sunk_msg = defender.update_ship_state(attacker)
sunk_tokens = sunk_msg.split()
if sunk_tokens[0] == "SUNK":
self.add_to_state_buffer(sunk_msg)
# Check if defending player in team with updating player is still alive
if defender.check_if_dead():
self.add_to_state_buffer("ELIM_PLAYER " + attacker.username + ' ' + defender.username)
# Check if team has been eliminated as well
if self.teams_alive[defender.team]:
team_alive = False
player_list = self.teams[defender.team]
for player_num in player_list:
if self.players[player_num].is_alive:
team_alive = True
break
if not team_alive:
self.teams_alive[defender.team] = False
self.add_to_state_buffer("ELIM_TEAM " + attacker.team + ' ' + defender.team)
# Check if game is over
self.is_game_over()
attacker.taken_turn = True # Set attacker turn as taken
# If game is not over from move, check if team's turn is over
if not self.game_end:
self.check_team_taken_turn()
def is_game_over(self):
alive_count = 0
winning_team = None
for team in self.teams_alive:
if self.teams_alive[team]:
alive_count += 1
winning_team = team
if alive_count == 1: # Game has ended
# Set the team winner
self.team_winner = winning_team
self.add_to_state_buffer("GAME_END " + winning_team)
self.game_end = True
def check_team_taken_turn(self):
# Find current team's turn
index = self.get_current_team_turn()
turn_taken = True
for player_num in self.teams[index]: # Determine if each player has taken their turn
if not self.players[player_num].taken_turn:
turn_taken = False
break
if turn_taken:
# Reset current team's turn taken flag, then change turn
for player_num in self.teams[index]:
self.players[player_num].taken_turn = False
self.change_team_turn()
def change_team_turn(self):
# Find current team's turn
team_list = list(self.teams.keys())
index = team_list.index(self.get_current_team_turn())
while True: # Find next team that is alive
index = (index + 1) % len(team_list)
next_team = team_list[index]
if self.teams_alive[next_team]: # Found next team's turn
self.team_turn = team_list[index]
if next_team == self.first_team_turn: # All teams took their turn, increment turn counter
self.turn_count += 1
# Add team change to state buffers
self.add_to_state_buffer("TURN_CHANGE " + str(self.turn_count) + ' ' + next_team)
break
def add_to_state_buffer(self, msg):
for player_num in self.players:
player = self.players[player_num]
player.add_state(msg) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def leafSimilar(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
array1 = self.helper(root1, [])
array2 = self.helper(root2, [])
print array1
print array2
if array1 == array2:
return True
return False
def helper(self,root, array):
if root == None:
return array
if root.right == None and root.left == None:
array.append(root.val)
if root.right != None:
self.helper(root.right, array)
if root.left != None:
self.helper(root.left, array)
return array |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if root is None:
return 0
depth = 1
for i in range(len(root.children)):
tempRoot = root.children[i]
traverseDepth = self.maxDepth(tempRoot)
depth = max(depth, traverseDepth + 1)
return depth
|
"""
user_guess = 0
secret_number = 20
user_attempt_number = 1
while user_guess != secret_number and user_attempt_number < 8:
# Tell the user what attempt we are on, and get their guess:
print("*Atempt:",user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
user_attempt_number += 1
# Print if we are too high or low, or we got it.
if user_guess > secret_number:
print("Too high.")
elif user_guess < secret_number:
print("Too low.")
else:
print("You got it!")
if user_attempt_number == 8:
print("You lose! The number was:", secret_number)
"""
total = 0
for i in range(5):
number = int(input("Enter a number: "))
total = total + number
print("The total is: ", total)
for i in range(10):
print(i)
for i in range(10):
print(i+1)
for i in range(1, 11):
print(i)
for i in range(2, 12, 2):
print(i)
for i in range(5):
print((i + 1) * 2)
for i in range(10, 0, -1):
print(i)
for i in range(3):
print("a")
for j in range(3):
print("b")
for i in range(5):
print("I will ont chew gum in class.")
# Ask
repetitions = int(input("How many times should I repeat? "))
# Loop
for i in range(repetitions):
print("I will not chew gum in class.")
def print_about_gum(repetitions):
for i in range(repetitions):
print("I will not chew gum in class.")
def main():
print("Main")
print_about_gum(5)
main()
|
class Dog():
def __init__(self):
self.age = 0
self.name = ""
self.weight = 0
def bark(self):
"""
The first parameter of any method in a class must be self.
This parameter is required even if the function does not use it.
"""
print("Woof says", self.name)
# Review I guess
class Star():
def __init__(self):
print("A star is born!")
# 1
class Cat():
def __init__(self):
self.color = ""
self.name = ""
self.weight = 0
def meow(self):
print("meow")
# 3
class Monster():
def __init__(self, name, health):
self.name = name
self.health = health
def decrease_health(self, amount):
self.health -= amount
if self.health <= 0:
print("dead")
def main():
# 2
my_cat = Cat()
my_cat.name = "Spot"
my_cat.weight = 20
my_cat.color = "black"
my_cat.meow()
main()
|
print("Problem 1")
for i in range(10):
print("*", end=" ")
print("\n")
print("Problem 2")
for i in range(35):
print("*", end=" ")
if i == 9 or i == 14:
print("\n")
print("\n")
print("Problem 3")
for i in range(10):
for j in range(10):
print("*", end=" ")
print("\n")
print("Problem 4")
for i in range(10):
for j in range(5):
print("*", end=" ")
print("\n")
print("Problem 5")
for i in range(5):
for j in range(20):
print("*", end=" ")
print("\n")
print("Problem 6")
for i in range(10):
for j in range(10):
print(j, end=" ")
print("\n")
print("Problem 7")
for i in range(10):
for j in range(10):
print(i, end=" ")
print("\n")
print("Problem 8")
for i in range(10):
for j in range(i + 1):
print(j, end=" ")
print("\n")
print("Problem 9")
for i in range(10):
k = 0
for j in range(10 - i, 0, -1):
print(k, end=" ")
k += 1
print("\n")
for j in range(i + 1):
print(" ", end="")
print("\n")
print("Problem 10")
for i in range(1, 10):
for j in range(1, 10):
n = j * i
if n < 10:
print(" ", end="")
print(n, end=" ")
print("\n")
print("Problem 11")
for i in range(1, 10):
for j in range(10, i, -1):
print(" ", end="")
for j in range(1, i + 1):
print(j, end=" ")
for j in range(i - 1, 0, -1):
print(j, end=" ")
print("\n")
#No more please :(
print("Problem 12")
for i in range(1, 10):
for j in range(10, i, -1):
print(" ", end="")
for j in range(1, i + 1):
print(j, end=" ")
for j in range(i - 1, 0, -1):
print(j, end=" ")
print("\n")
for i in range(10):
k = 1
print(" ", end = "")
for j in range(8 - i, 0, -1):
print(k, end=" ")
k += 1
print("\n")
for j in range(i + 1):
print(" ", end="")
print("\n")
#Whatever...
print("Problem 12")
for i in range(1, 10):
for j in range(10, i, -1):
print(" ", end="")
for j in range(1, i + 1):
print(j, end=" ")
for j in range(i - 1, 0, -1):
print(j, end=" ")
print("\n")
for i in range(8):
k = 1
print(" ", end = "")
for j in range(8 - i, 1, -1):
print(k, end=" ")
k += 1
for j in range(k, 0, -1):
print(j, end=" ")
print("\n")
for j in range(i + 1):
print(" ", end="")
print("\n")
|
#思路:先考虑正常场景写完流程,再补充if语句覆盖异常情况。
testWord=input("请输入测试的单词:")
if(len(testWord)<=0):
print("这不是一个合法的单词。")
elif(testWord.isalpha()==False):
print("单词里面有其他字符。")
else:
changeWord = testWord[1:] + testWord[0] + "ay"
print("转换后的单词为:{}".format(changeWord.lower()))
|
import argparse
import sys
import io
'''
Class CurrencyConvert with 4 attributes field, multiplier, i(input), o(output) and methods as required.
'''
class CurrencyConvert():
'''
Function: by using argparse to add 4 arguments field, multiplier, i, o to __init__ function
and to parse 4 arguments either from console or stdin/stdout.
'''
def __init__(self):
parser = argparse.ArgumentParser(prog="currency_convert",
usage="%(prog)s <--field N> [--multiplier N] [-i input] [-o output]")
parser.add_argument("--field", required=True, help="价格信息在CSV的第N行需要进行转换")
parser.add_argument("--multiplier", default= 0.8, help="转换方法为把当前的数值乘以N,这个N表示汇率")
parser.add_argument("-i", nargs="?", default=sys.stdin, help="从input文件内读取CSV文件内容(或者从stdin读取)")
parser.add_argument("-o", nargs="?", default=sys.stdout, help="输出到output文件中(或者输出到stdout)")
arguments = parser.parse_args()
self.field = arguments.field
self.multiplier = arguments.multiplier
self.i = arguments.i
self.o = arguments.o
'''
One argument: the current line from the input file
Return: the element of the list amount regarding input value field
Function: get the USD amount text line, split line by comma, use the field number minus 1 to get the actual usd
value element.
'''
def get_the_usd_amount(self, line):
amount = line.split(",")
return amount[int(self.field) - 1]
'''
One argument: the current line from the input file
Return: combination of two elements of the list amount regarding input value field
Function: get the Euro amount text line, split line by comma, use the field number minus 1 and the field number
combination to get the actual eur value element by deleting the euro symbol and replacing the comma with dot
'''
def get_the_eur_amount(self, line):
amount = line.split(",")
print(amount[int(self.field) - 1].replace("€", "") + "." + amount[int(self.field)])
return amount[int(self.field) - 1].replace("€", "") + "." + amount[int(self.field)]
'''
One argument: amount, the usd amount from function get_the_usd_amount()
Return: the eur amount with an euro symbol, replace the dot with comma between digits
Function: get the usd amount times the multiplier with 2 decimal points
'''
def convert_to_eur(self, amount):
euro = round(float(amount) * float(self.multiplier), 2)
return "€" + str(euro).replace(".", ",")
'''
One argument: amount, the eur amount from function get_the_eur_amount()
Return: the usd amount, replace the comma with dot between digits
Function: get the eur amount times the multiplier with 2 decimal points
'''
def convert_to_usd(self, amount):
usd = round(float(amount) / float(self.multiplier), 2)
return str(usd)
'''
One argument: text_name
Return: new text that replaces the usd by the eur
Function: read line by line from the text and replace the usd by the euro,
if there is no usd value, it just copies the line
'''
def read_file(self, text_name):
newline = ""
for line in text_name:
try:
newline += line.replace(self.get_the_usd_amount(line),
self.convert_to_eur(float(self.get_the_usd_amount(line))))
except ValueError:
newline += line
return newline
'''
Function: if the input/output is TTY, screen prints tips to let user enter the arguments
if the input/output is redirection, it reads from the console
if the input/output is with arguments, it reads from the arguments
From read_file gets the new text then export it
'''
def usd_eur_file_export(self):
new_text = ""
if isinstance(self.i, io.TextIOWrapper):
if self.i.isatty():
self.i = input("Please enter the input file name: ")
self.o = input("Please enter the output file name: ")
with open(self.i, "r", encoding="utf-8") as text:
new_text = self.read_file(text)
else:
new_text = self.read_file(self.i)
elif isinstance(self.i, str):
with open(self.i, "r", encoding="utf-8") as text:
new_text = self.read_file(text)
if isinstance(self.o, io.TextIOWrapper):
self.o = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
self.o.write(new_text)
else:
with open(self.o, "w", encoding="utf-8") as text2:
text2.write(new_text)
#usd file export
def eur_usd_file_export(self):
pass
'''
Create a CurrencyConvert instance usdeur,
call the function usd_eur_file_export() to covert usd to eur
'''
if __name__ == '__main__':
usdeur = CurrencyConvert()
usdeur.usd_eur_file_export()
#similar function as usd to eur
#usdeur.eur_usd_file_export()
|
#=======================
# Author: Susmita Datta
# Algorithm: Bubble Sort
# Title: bubbleSort
#
# Time Complexity of Solution:
# Best O(n^2); Average O(n^2); Worst O(n^2).
#
# Sample Input: [8,5,3,1,9,6,0,7,4,2,5]
# Sample Output: [0,1,2,3,4,5,5,6,7,8,9]
#----------------------------------------
def bubbleSort(unsorted):
sort_count = 0
for k in range(0, len(unsorted)-1):
num1 = unsorted[k]
num2 = unsorted[k+1]
if num1 > num2:
unsorted[k+1] = num1
unsorted[k] = num2
sort_count += 1
if sort_count != 0:
return bubbleSort(unsorted)
if sort_count == 0:
return unsorted
if __name__ == "__main__":
import random
unsorted_list = random.sample(range(99), 11)
print(" Unsorted list of numbers:\n",unsorted_list,'\n')
sorted_list = bubbleSort(unsorted_list)
print(" Sorted list:\n",sorted_list,"\n")
|
for i in range(100):
if i%3 == 0 and i%5== 0 :
print ("FizzBuzz");
continue;
if i%3 == 0 :
print ("Fizz")
continue
if i%5 == 0 :
print ("Buzz")
continue
print (i)
|
#Approach 0
# We can sort the two strings
# and then sorted_1 == sorted_2
#Approach1
#We use the hashtables
def is_anagram (str_1, str_2):
#delete white spaces
str_1 = str_1.replace(" ","")
str_2 = str_2.replace(" ","")
if len(str_1) != len (str_2):
return False
#deal with lowercases
str_1 = str_1.lower
str_2 = str_2.lower
#use hash tables
alphabet = "abcdefghijklmnopqrstuvwxyz"
dict_1 = dict.fromkeys(list(alphabet), 0)
dict_2 = dict.fromkeys(list(alphabet), 0)
for i in range(len(str_1)):
dict_1[str_1[i]] += 1
dict_2[str_2[i]] += 1
return dict_1 == dict_2
|
'''
The composite design pattern maintains a tree data structure to represent part-whole relationships.
Here we like to build a recursive tree data structure so that an element of the tree can have its
own sub-elements. An example of this problem is creating menu and submenu items. The submenu items
can have their own sub-submenu items. So our coding challenge is to display menu and submenu items
using this composite design pattern.
Our solution consists of three major elements. The first one is component, the second one is child,
and the third one is composite. The component element is an abstract class. A concrete class
called child inherits from this component class. And then we have another concrete class
called composite, which is also inheriting from the component class. Finally, our composite
class maintains child objects by adding and removing them to a tree data structure.
Decorator, iterator, and visitor are related to the composite design pattern.
'''
class Component(object):
"""Abstract class"""
def __init__(self, *args, **kwargs):
pass
def component_function(self):
pass
class Child(Component): #Inherits from the abstract class, Component
"""Concrete class"""
def __init__(self, *args, **kwargs):
Component.__init__(self, *args, **kwargs)
#This is where we store the name of your child item!
self.name = args[0]
def component_function(self):
#Print the name of your child item here!
print("{}".format(self.name))
class Composite(Component): #Inherits from the abstract class, Component
"""Concrete class and maintains the tree recursive structure"""
def __init__(self, *args, **kwargs):
Component.__init__(self, *args, **kwargs)
#This is where we store the name of the composite object
self.name = args[0]
#This is where we keep our child items
self.children = []
def append_child(self, child):
"""Method to add a new child item"""
self.children.append(child)
def remove_child(self, child):
"""Method to remove a child item"""
self.children.remove(child)
def component_function(self):
#Print the name of the composite object
print("{}".format(self.name))
#Iterate through the child objects and invoke their component function printing their names
for i in self.children:
i.component_function()
#Build a composite submenu 1
sub1 = Composite("submenu1")
#Create a new child sub_submenu 11
sub11 = Child("sub_submenu 11")
#Create a new Child sub_submenu 12
sub12 = Child("sub_submenu 12")
#Add the sub_submenu 11 to submenu 1
sub1.append_child(sub11)
#Add the sub_submenu 12 to submenu 1
sub1.append_child(sub12)
#Build a top-level composite menu
top = Composite("top_menu")
#Build a submenu 2 that is not a composite
sub2 = Child("submenu2")
#Add the composite submenu 1 to the top-level composite menu
top.append_child(sub1)
#Add the plain submenu 2 to the top-level composite menu
top.append_child(sub2)
#Let's test if our Composite pattern works!
top.component_function()
|
#!/usr/bin/env python3
""" Barron finishes cooking while Olivia cleans """
import threading
import time
def kitchen_cleaner():
while True:
print('Olivia cleaned the kitchen.')
time.sleep(1)
# Threads that are performing background tasks, like garbage collection, can be detached from the main program by
# making them what's called a demon thread. A demon thread, which you may also hear pronounced as daemon, is a thread
# that will not prevent the program from exiting if it's still running. By default, new threads are usually spawned
# as non-demon or normal threads and you have to explicitly turn a thread into a demon or background thread.
if __name__ == '__main__':
olivia = threading.Thread(target=kitchen_cleaner)
# if below line is False, Olivia will be running forever
# it is false by default. So non-daemon thread will prevent the program from ending
olivia.daemon = True
olivia.start()
print('Barron is cooking...')
time.sleep(0.6)
print('Barron is cooking...')
time.sleep(0.6)
print('Barron is cooking...')
time.sleep(0.6)
print('Barron is done!')
|
class User:
_all_users = []
def __init__(self, name):
"""
Constructor of the user class
Parameters: name
Returns: an instance of the class User
"""
self._name = name
self._type=None
self._information = []
self._email = None
self._password = None
self._status=False
User._all_users.append(self)
def get_name(self):
return self._name
def set_name(self, name):
"""
We need to make sure that name is a string
"""
assert isinstance(name, str)
self._name = name
def changeUserInformation(tp,email,password):
self._type=tp
self._email=email
self._password=password
_information.append(tp,email,password)
def get_userInformation(self):
return self._information
def get_login(self):
self._status=True
class Forum():
def _init_(self):
_forum_list = []
_forum_description = []
def search_post(self):
self.counter = 0
if _forum_list = [counter] and counter < len._forum_list[]:
print (_forum_list[counter], _forum_description[counter])
else if counter >= len._forum_list[]:
print ("The post has not been found")
else:
counter = counter + 1
def addPost(name, description, content):
self._froum_list.append(name)
self._froum_desciption.append(description)
self._forum_content.append(content)
def deletePost(name):
print ("Do you want to delete the post with post name: " + name)
self.counter = 0
if _forum_list == [counter] and counter < len._forum_list[]:
del _froum_list[counter]
del _forum_description[counter]
del _forum_content[counter]
else if counter >= len._forum_list[]:
print ("The post has not been found")
else:
counter = counter + 1
class Post(Forum):
def _init_(self):
super._init_()
self.reply_to_post = []
_post_content= []
self._like = 0
self._forward = 0
def viewPost(self):
print (_forum_list, _forum_description, _post_content, _reply_to_post, _like, _forward)
def replyPost(reply):
self.reply_to_post.append(reply)
def likePost(self):
_like = _like + 1
def forwardPost(self):
_forward = _forward + 1
def subscribe(self):
postSubscribed()
class ChatList():
def _init_(self):
self._student_list = []
self._student_year = []
self._student_infor = []
self._partial_chat_history = []
print (_student_list[], _student_year[], _student_infor[], _partial_chat_history[])
def viewChat():
print(_student_list, _student_basic_infor,_partial_chat_history)
def search_student(student_name,year):
self.counter = 0
if student_name == _student_list[counter] and year == _student_year[counter]:
print (_student_list[counter], _student_year[counter], _student_infor[counter])
else if counter > len._student_list:
print("student not found")
else:
counter = counter + 1
def chat():
Chatroom._messageTo()
class ChatRoom(Chatlist):
def _init(self):
self._chat_content=[]
self._student_name = []
def _messageTo(message):
return message
class Attendence():
def _init_(self):
self._instruction = ("Please scan the QR code")
self._module = [DB, SE, BRM]
self._total_lessons = 10
self._attended_lessons = [0,0,0]
def scanQrCode(module,_attended_lessons):
print(_instruction)
_attended_lessons = _attended_lessons + 1
self.counter = 1
if module == _module[counter] and counter < len._module[]:
_attended_lessons[counter] = _attended_lessons
print("Attendence has been taken")
else if counter > len.module[]:
print("Module has not been found")
else:
counter = counter + 1
def flashlight():
turnOnFlashLight()
def tapOnRecord():
self.counter = 0
if counter < len.module:
print(_module[counter])
print(_attended_lessons/_total_lessons)
else if counter > len.module[]:
break
else:
counter = counter + 1
def reportIssue(issue):
issueReported()
class Notification(Post):
def _init_(self):
self._notification = "you have an update from your subscribed post"
def _noticication(self):
print(_notification)
def viewPost(self):
super.viewPost()
def unsubscribe(self):
postUnsubscribed()
|
""" ALLEN ZHAI, WEI LIN, STEVEN GANDHAM """
class Student:
def __init__(self, StLastName, StFirstName, Grade, Classroom, Bus, GPA, TLastName, TFirstName):
self.StLastName = StLastName
self.StFirstName = StFirstName
self.Grade = Grade
self.Classroom = Classroom
self.Bus = Bus
self.GPA = GPA
self.TLastName = TLastName
self.TFirstName = TFirstName
def __repr__(self):
return "Last Name: {}\nFirst Name: {}\nGrade: {}\nClassroom: {}\nBus: {}\nGPA: {}\nTeacher Last Name: {}\nTeacher First Name: {}\n".format(self.StLastName, self.StFirstName, self.Grade, self.Classroom, self.Bus, self.GPA, self.TLastName, self.TFirstName)
def parseStudents(filename):
Students = []
try:
with open(filename, "r") as studentsFile:
for line in studentsFile:
info = line.strip("\n").split(",")
if len(info) == 8:
try:
s = Student(info[0], info[1], int(info[2]), int(info[3]), int(info[4]), float(info[5]), info[6], info[7])
Students.append(s)
except:
return Students
else:
return Students
except:
return Students
return Students
|
# work with the variable 'my_numbers'
# my_numbers = [1, 2, 3, 4, 5]
print( [num for num in my_numbers if num % 2 == 0])
|
import pyphen #Programa que calcula el numero de silabas en un texto
import re
dic = pyphen.Pyphen(lang='es')
texto='Hola, como; estas? yo estoy muy bien, y ¿tu vas? (sorpresa)'
texto1=re.sub(r'[\?\!\-\¿\;\%\$\#\"\'\,]', '', texto)
texto1=re.sub(r'[aeiou]y', 'oi', texto1)
print(texto1)
a=dic.inserted(texto1)
print(a.split("-"))
print(len(a.split("-")))
#Programa que calcula el numero de palabras en un texto
listaPalabras = texto.split()
print(listaPalabras)
print(len(listaPalabras))
texto2=re.sub(r'[\¿\¡\(]', '', texto)
texto2=re.sub(r'[\:\;\.\)\!\?]','.', texto2)
print(texto2.split("."))
print(len(texto2.split(".")))
|
#f(f(x))=f(x)
def add_ten(num):
return num+10
print add_ten(10)
print add_ten(add_ten(10))
##The above function is not ideempotent the reason is when the function is passed into a function
#it should retun the same original result
#Example of idempotent
print abs(-10)
print abs(abs(-10)) |
# coding: utf-8
# Pemrograman Berbasis Objek
# Class and Object
# September 03 2018
# We can create "things" with:
# - atributes things those "things" have => merupakan barang atau properti yang ada
# - methods things those "things" can do => suatu rancangan yang menggunakan properti dari atributes
#
# Pengertian Class and Object
# - Class merupakan suatu entitas yang berupa bentuk program yang menjadi sebuah tempat untuk menyimpan data, nilai-nilai dan perilaku (behavior) bersama-sama. Instans dari class merupakan realisasi dari beberapa objek.
# - Object merupakan Instance dari class. Jika class secara umum merepresentasikan (template) sebuah object, maka sebuah instance adalah representasi nyata dari class itu sendiri.
#
# Perbedaan Class and Object
# - Class = adalah tempatnya atau wadah
# - Object = Instansi dari Class (membuat suatu rancangan dengan menggunakan Class)
# keyword Class diikuti dengan nama Class yang kita inginkan
# lebih baik digunakan kata yang diawali huruf kapital
#contoh class
class Persegi:
def __init__(self,s): #constructor
self.sisi = s
def tampilkansisi(self):
print("Sisi =",self.sisi)
def luas(self):
print("Luas =",self.sisi ** 2)
#main program
kotak = Persegi(4)
kotak.tampilkansisi()
kotak.luas()
# Kubus
class Kubus:
def __init__(self,s):
self.sisi = s
def tampilkansisi(self):
print("Sisi =",self.sisi)
def luassisi(self):
print("Luas Sisi =",self.sisi ** 2)
def volume(self):
print("Volume =",self.sisi**3)
def luaspermukaan(self):
print("Luas Permukaan =",self.sisi**2 * 6)
#mainKubus
kub = Kubus(4)
kub.luassisi()
kub.volume()
kub.luaspermukaan()
# Data Mahasiswa
class Mahasiswa:
def __init__(self,nim,nama,nilai):
self.npm = nim
self.name = nama
self.ipk = nilai
def datamahasiswa(self):
print("NIM :",self.npm)
print("NAMA :",self.name)
print("IPK :",self.ipk)
def predikat(self):
nil = self.ipk
print("Hasil Nilai ",end="")
if nil >= 3.5:
print("Cumlaud")
elif 3.5 > nil and nil > 3:
print("Sangat Memuaskan")
elif 3 >= nil and nil > 2.5:
print("Memuaskan")
elif nil <= 2.5:
print("Cukup")
mhs = Mahasiswa(11100045,"Bagus",3)
mhs.datamahasiswa()
mhs.predikat()
# ATM Rekening
class Nasabah:
def __init__(self,nonasabah,nama,norekening):
self.nonas = nonasabah
self.name = nama
self.norek = norekening
def rekening(self):
return self.norek
def isisnya(self):
print("No Nasabah :",self.nonas)
print("Nama :",self.name)
print("No Rekening :",self.norek)
class Rekening:
def __init__(self,saldo,norekening):
self.saldo = saldo
self.norek = norekening
def ceksaldo(self):
print("Saldo Anda =",self.saldo)
def setor(self):
setor = int(input("Masukkan Nominal yang disetor = "))
self.saldo -= setor
print("Transfer Uang Berhasil")
print("Nominal =",setor)
def ambiluang(self):
ambil = int(input("Masukkan Nominal yang ingin anda ambil = "))
self.saldo -= ambil
print("Uang Berhasil di ambil")
#main Nasabah and Rekening
nama = str(input("Masukkan Nama = "))
nas = Nasabah(1704111,nama,541120028590)
norek = nas.rekening()
rek = Rekening(15000,norek)
rek.ceksaldo()
rek.setor()
rek.ceksaldo()
rek.ambiluang()
rek.ceksaldo()
# Operasi Bilangan Bulat
class Operasi:
def __init__(self,bil1,bil2):
self.bil = bil1
self.bil2 = bil2
def jumlah(self):
print("{} + {} = ".format(self.bil,self.bil2),self.bil + self.bil2)
def kurang(self):
print("{} - {} = ".format(self.bil,self.bil2),self.bil - self.bil2)
def bagi(self):
print("{} / {} = ".format(self.bil,self.bil2),self.bil / self.bil2)
def kali(self):
print("{} * {} = ".format(self.bil,self.bil2),self.bil * self.bil2)
op = Operasi(12,4)
op.jumlah()
op.kurang()
op.bagi()
op.kali()
|
more18 = m20 = man = 0
while True:
print('='*30)
while True:
sexo = continuar = ' '
age = input('Quantos anos? ').strip()
if age.isnumeric() == True:
age = int(age)
break
while sexo not in 'mf':
sexo = input('Qual o sexo? [M/F] ').lower().strip()[0]
print('='*30)
if age > 18: more18 += 1
if sexo == 'm': man += 1
if sexo == 'f' and age < 20: m20 += 1
while continuar not in 'sn':
continuar = input('Quer continuar? [s/n] ').strip().lower()[0]
if continuar == 'n': break
print(f'Tem {man} homens, {more18} pessoas com mais de 18 anos e {m20} mulheres com menos de 20')
|
from abc import abstractproperty
tempdados = []
dados = []
maior = []
menor = []
while True:
name = input('Nome: ').strip().title()
peso = float(input('Peso: '))
tempdados.append(name)
tempdados.append(peso)
dados.append(tempdados[:])
if len(dados) == 1:
maior.append(tempdados[:])
menor.append(tempdados[:])
else:
if peso > maior[0][1]:
maior.clear()
maior.append(tempdados[:])
elif peso < menor[0][1]:
menor.clear()
menor.append(tempdados[:])
elif peso == maior[0][1]:
maior.append(tempdados[:])
if peso == menor[0][1]:
menor.append(tempdados[:])
tempdados.clear()
reuse = input('Quer continuar? s/n ').strip().lower()[0]
if reuse == 'n':
break
print(f'O programa rodou {len(dados)} vezes')
print('Os mais pesados são:')
for p in maior:
print(f'{p[0]} com {p[1]}Kg')
print('E os mais leves:')
for p in menor:
print(f'{p[0]} com {p[1]}Kg')
|
numbers = list()
for cont1 in range(0, 3):
numbers.append(int(input(f'Digite o valor para a posiçao {cont1}: ')))
print(f'Os valores digitados foram {numbers}')
maior = max(numbers)
menor = min(numbers)
print(f'O menor numero foi {menor} nas posições', end=' ')
for i1, val1 in enumerate(numbers):
if val1 == menor:
print(f'{i1}...', end=' ')
print(f'\nO maior numero foi {maior} nas posições', end=' ')
for i2, val2 in enumerate(numbers):
if val2 == maior:
print(f'{i2}...', end=' ')
|
val = float(input('\nDigite um valor em metros: '))
# km hm dam m dm cm mm
# 1000 100 10 1 01 001 0001
km = val / 1000
hm = val / 100
dam = val / 10
dm = val * 10
cm = val * 100
mm = val * 1000
print('\n{}m tem:\n{}dam \n{}hm \n{}km '.format(val, dam, hm, km))
print('{}dm \n{}cm \n{}mm \n'.format(dm, cm, mm)) |
from random import randint
from os import system as sy
while True:
sy('cls')
usr = ''
comp = randint(1, 10)
print('# ================================= #')
print('# Um numer entre 1 e 10 foi gerado, #')
print('# descubra qual é o numero #')
print('# ================================= #')
while usr != comp:
usr = int(input('# Qual é o numero? '))
if usr < comp:
print('# Mais... ')
elif usr > comp:
print('# Menos...')
print(f'Parabens vc consegiu, o numero era {comp}')
program = input('Precione enter para jogar novamente ou q para sair ').lower()
if program == 'q':
sy('cls')
break
|
print()
algo = input('Digite qualquer coisa: ')
print()
#print(algo, 'e um numero?', algo.isnumeric())
if algo.isnumeric() == True:
print(algo, 'é um numero!')
elif algo.isalpha() == True:
print(algo, 'é uma palavra!')
elif algo.isspace() == True:
print(algo, 'é espaço!') |
ant = 0
dep = 1
n = int(input('Quantos numeros quer ver? '))
i = 3
print(ant)
print(dep)
while i <= n:
soma = ant + dep
ant = dep
dep = soma
print(soma)
i += 1
|
n = int(input('Digite um numero inteiro: '))
print('''Escolha uma das bases para conversão
[0]Converter para Binario
[1]Converter para Octal
[2]Converter para Hexadecimal
[3]Converter para todas
''')
option = int(input('Sua opção: '))
if option == 0:
print('{} em binario é: {}'.format(n, bin(n)))
elif option == 1:
print('{} em octal é: {}'.format(n, oct(n)))
elif option == 2:
print('{} em hexadecimal é: {}'.format(n, hex(n)[2:]))
elif option == 3:
print('{} em binario é: {}'.format(n, bin(n)[2:]))
print('{} em octal é: {}'.format(n, oct(n)))
print('{} em hexadecimal é: {}'.format(n, hex(n)[2:]))
else:
print('Opção invalida!')
|
aluno = {}
aluno['name'] = input('Nome: ').strip().title()
aluno['media'] = float(input(f'Média de {aluno["name"]}: '))
if aluno['media'] < 7:
aluno['situação'] = 'reprovado'
else:
aluno['situação'] = 'aprovado'
for k, v in aluno.items():
print(f'{k} é igual a {v}')
|
notam = float(input('Sua nota mensal: '))
notab = float(input('Sua nota bimestral: '))
media = (notam + notab) / 2
print()
if media >= 7:
print('Parabens voce passou!!!')
else:
print('Puts, nao foi dessa vez')
print('Media: {}'.format(media)) |
n = int(input('Qual numero voce quer saber a tabuada? '))
'''
print('-'*15)
print('| {0} * 1 = {1} |'.format(n, (n * 1)))
print('| {0} * 2 = {1} |'.format(n, (n * 2)))
print('| {0} * 3 = {1} |'.format(n, (n * 3)))
print('| {0} * 4 = {1} |'.format(n, (n * 4)))
print('| {0} * 5 = {1} |'.format(n, (n * 5)))
print('| {0} * 6 = {1} |'.format(n, (n * 6)))
print('| {0} * 7 = {1} |'.format(n, (n * 7)))
print('| {0} * 8 = {1} |'.format(n, (n * 8)))
print('| {0} * 9 = {1} |'.format(n, (n * 9)))
print('| {0} * 10 = {1} |'.format(n, (n * 10)))
print('-'*15)
'''
print('-'*15)
print(' {0} * 1 = {1} '.format(n, (n * 1)))
print(' {0} * 2 = {1} '.format(n, (n * 2)))
print(' {0} * 3 = {1} '.format(n, (n * 3)))
print(' {0} * 4 = {1} '.format(n, (n * 4)))
print(' {0} * 5 = {1} '.format(n, (n * 5)))
print(' {0} * 6 = {1} '.format(n, (n * 6)))
print(' {0} * 7 = {1} '.format(n, (n * 7)))
print(' {0} * 8 = {1} '.format(n, (n * 8)))
print(' {0} * 9 = {1} '.format(n, (n * 9)))
print(' {0} * 10 = {1} '.format(n, (n * 10)))
print('-'*15) |
def main():
count = 0
for line in open('3.in'):
sides = [int(side) for side in line.split()]
sides.sort()
print sides
if (sides[0] + sides[1]) > sides[2]:
count += 1
print count
if __name__ == "__main__":
main()
|
'''
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists
(without duplicates).
Make sure your program works on two lists of different sizes.
Created on Jul 1, 2017
@author: shikhadubey
'''
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
overlaplist= []
i= len(a)-1
for x in range(0, i):
if a[x] in b:
overlaplist.append(a[x])
set1= list(set(overlaplist))
print(set1) ##It will give this result if you just do print(overlaplist):[1, 1, 2, 3, 5, 8, 13]
''' If you dont want the 1 to come two times?, use the set function...
But if only set(overlaplist) is used, it will give output as set(1,2,3,5 .....)
Therfore, enclose that set is a list again
Reason????
Dont know
''' |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from socket import *
import os
import sys
import struct
import time
import select
import binascii
def checksum(data):
n = len(data)
m = n % 2
sum = 0
for i in range(0, n - m, 2):
sum += (data[i]) + ((data[i+1]) << 8)
if m:
sum += (data[-1])
sum = (sum >> 16) + (sum & 0xffff)
sum += (sum >> 16)
answer = ~sum & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def handle_error(type, code):
'''
This method is used to distinguish which kind of error occurs or no error occurs
Parameter:
type <class 'int'>: the type of ICMP
code <class 'int'>: the code of ICMP
Return:
Normal string: the name of the error
Null string: there is no error
'''
if type == 0 and code == 0:
return ''
elif type == 3:
if code == 0:
return 'network unreachable'
elif code == 1:
return 'host unreachable'
elif code == 2:
return 'protocol unreachable'
elif code == 3:
return 'port unreachable'
elif code == 4:
return 'fragmentation needed but no frag. bit set'
elif code == 5:
return 'source routing failed'
elif code == 6:
return 'destination network unknown'
elif code == 7:
return 'destination host unknown'
elif code == 8:
return 'source host isolated(obsolete)'
elif code == 9:
return 'destination network administratively prohibited'
elif code == 10:
return 'destination host administratively prohibited'
elif code == 11:
return 'network unreachable for TOS'
elif code == 12:
return 'host unreachable for TOS'
elif code == 13:
return 'communication administratively prohibited by filtering'
elif code == 14:
return 'host procedence violation'
elif code == 15:
return 'precedence cutoff in effect'
elif type == 4 and code == 0:
return 'source quench'
elif type == 5:
if code == 0:
return 'redirect for network'
elif code == 1:
return 'redirect for host'
elif code == 2:
return 'redirect for TOS and network'
elif code == 3:
return 'redirect for TOS and host'
elif type == 9 and code ==0:
return 'router solicitation'
elif type == 10 and code ==0:
return 'router solicatation'
elif type == 11:
if code == 0:
return 'TTL equals 0 during transit'
elif code == 1:
return 'TTL equals 0 during reassermbly'
elif type == 12:
if code == 0:
return 'IP header bad (catchall error)'
elif code == 1:
return 'required potions missing'
elif type == 13 and code == 0:
return 'timestamp request(obsolete)'
elif type == 14:
return 'timestamp reply(obsolete)'
elif type == 15 and code == 0:
return 'information request'
elif type == 16 and code == 0:
return 'information reply (obsolete)'
elif type == 17 and code == 0:
return 'address mask request'
elif type == 18 and code == 0:
return 'address mask reply'
else:
return ''
def traceroute(ip_address, timeout=3):
'''
This method is used to trace router
Parameter:
ip_address <class 'str'>: the destination of the traceroute
timeout <class 'int'> [default = 3]: the timeout of each ICMP requst of the traceroute
Return:
None
'''
# at the begin, set the ttl equal to 1
ttl = 1
while True:
# create the ICMP socket
send = socket(AF_INET,SOCK_RAW,getprotobyname('icmp'))
send.setsockopt(IPPROTO_IP,IP_TTL,ttl)
send.settimeout(timeout)
# construct the header of the ICMP packet
type = 8
code = 0
cksum = 0
id = 3
seq = 0
body_data = b'testtesttesttesttesttesttesttest'
packet = struct.pack('>BBHHH32s',type,code,cksum,id,seq,body_data)
cksum = checksum(packet)
packet = struct.pack('>BBHHH32s',type,code,cksum,id,seq,body_data)
# the print string
printResult = ''
# the ip between the source IP and the destination IP
tempIP = ''
# the try time is 3, which is as same as the tracert at cmd in windows system
tries = 3
# printTime is a counter, because the error must be same if we send ICMP packet to one destination, we just need to add the error message once,
printTime = 1
while tries > 0:
# send the packet to the destination
send.sendto(packet, (ip_address, 0))
# record the send time
sendTime = time.time()
# try to find some packet whose ttl equals 0
try:
reply = select.select([send], [], [], timeout)
# record the receive time
receiveTime = time.time()
# if the packet is empty, we will print a '*'
if reply[0] == []:
printResult += '* '
tempTimeout = 9999
else:
tempTimeout = timeout
# receive the data
receiveData = send.recvfrom(1024)
# destuct the packet
type, code, cksum, id, seq = struct.unpack(">BBHHH", receiveData[0][20:28])
if printTime == 1:
# add the error message into the print result
printResult = handle_error(type, code) + ' ' + printResult
printTime -= 1
# if the delay is greater than the timeout, we will print a '*'
if tempTimeout < receiveTime-sendTime:
printResult += '* '
# in other situation, we will print the normal delay
else:
temp = int((receiveTime-sendTime)*1000+0.5)
if temp == 0:
temp = 1
printResult += str(temp)+'ms '
tempIP = receiveData[1][0]
tries -= 1
# sometimes the packet will lost, and we can catch the exception
except error as er:
tries -= 1
# if there is no packet which we received, we should think the packets are lost
if tempIP == '':
printResult = 'packet lost '+printResult
# in other situation, we should try to get its domain
else:
try:
# try to get the domain of the ip
domain = gethostbyaddr(tempIP)
printResult += domain[0]
printResult += '[' + tempIP + ']'
# if we donot get the domian
except error as e:
printResult += tempIP
# print the result
printResult = str(ttl)+' '+printResult
print(printResult)
ttl+=1
send.close()
# if the ttl equal 256, we should exit, because the greatest ttl is equal to 255
if ttl == 256:
break
# if the packet arrive the destination, we also should exit
if tempIP == ip_address:
print("finished")
break
return
if __name__ == '__main__':
dest = input('please input the destination:\n')
timeout = input("please input the timeout:\n")
try:
ip_address = gethostbyname(dest)
print('tracing: '+dest+' ['+ip_address+']')
traceroute(ip_address,int(timeout))
except ValueError as v:
print("Please input a integer timeout")
except gaierror as g:
print('wrong destination')
|
def getwords(filename):
words = []
f = open(filename);
for line in f.readlines():
words.append(line.split()[0].lower())
return words
#words = getwords("wordlist.txt");
#print words
|
import math
input_str = input().split(' ')
a = int(input_str[0])
b = int(input_str[1])
gcd = math.gcd(a, b)
lcd = (math.fabs(a) * math.fabs(b)) // gcd
print(gcd, int(lcd))
|
#Mobile Money Account
print("1. send money")
print("2. withdraw money")
phone_number = "0546819106"
user = input("select choice:\n")
if user == "1":
print("send Money")
print("1. MTN user")
print("2. Tigo user")
x = input("choice:\n")
if x == "1":
print("MTN User:")
number = input("Enter Mobile Number\n")
if number == phone_number:
amount = input("Enter Amount to send\n")
print(amount," sent sucessfully to number",phone_number)
else:
print("wrong phone number or input details")
exit()
if x == "2":
print("Tigo User:")
number = input("Enter Mobile Number\n")
print(amount,"sent sucessfully to number",phone_number)
else:
print("wrong phone number or input details")
exit()
|
from .base import Bracket
class Function(Bracket):
'''A :class:`~.Bracket` representing a function.
A function is defined a-la Python as::
func(expression, **kwargs)
where *kwargs* is a dictionary of input parameters.
For example, the rolling-standard deviation
is defined as::
std(expression,window=20)
'''
def __init__(self, func, expression, pl, pr):
self.func = func
super().__init__(expression, pl, pr)
def info(self):
return '{0}{1}'.format(self.func, super().info())
def _unwind(self, values, backend, **kwargs):
args, kwargs = super()._unwind(values, backend, **kwargs)
return self.func(*args, **kwargs)
|
from numpy import dot, linalg
class ols(object):
'''The ordinary least squares (OLS) or linear least squares is a method
for estimating the unknown parameters in a linear regression model.
The matrix formulation of OLS is given by the linear system of equations:
.. math::
y = X \beta + \epsilon
.. attribute:: y
The *regressand* also known as the the *endogenous* or *dependent* variable.
This is a n-dimensional vector.
.. attribute:: x
The *regressor* also known as the *exogenous* or *independent* variable
This is a :math:`n \times k` matrix, where each column of which is a
n-dimensional vector which must be linearly independent from the others.
'''
def __init__(self, y, X):
self.y = y
self.X = X
def beta(self):
'''\
The linear estimation of the parameter vector :math:`\beta` given by
.. math::
\beta = (X^T X)^-1 X^T y
'''
t = self.X.transpose()
XX = dot(t,self.X)
XY = dot(t,self.y)
return linalg.solve(XX,XY)
|
length = float(input("what is the length of the field?"))
width = float(input("what is the width of the field?"))
total_area = length * width / 43560
print("The total area is: " , total_area , "acres")
|
'''Brad Allen. Scratch work.'''
import pandas as pd
import os
from collections import namedtuple
import numpy as np
class dfs:
'''This class employs a depth first search strategy - the main function is explore_branch(),
which will traverse a branch until it:
(1) uses up too much weight (the "floor" is negative),
(2) is exhausted, or
(3) does not have the potential to have more value than the current best answer.
The state of the next branch for exploring is calculated using the next_branch() function,
which updates the next node for searching, as well as the starting floor and max potential
value.'''
def __init__(self, input_data):
'''As the algo traverses different branches, many variables are required to keep state -
for global values as well as updating nodes to explore.'''
# global variables
self.input_data = input_data
self.iterations = 0
self.items, self.item_count, self.capacity = self._load_data()
self.best_value = 0
self.best_set = np.zeros(len(self.items)).astype(int)
# node-specific variables - "kept_value" is value accrued, "floor" is weight left
self.kept_value = 0
self.floor = self.capacity
self.current_set = np.zeros(len(self.items)).astype(int)
self.current_level = 0
self.max_potential_value = self._value_estimate(items=self.items,
capacity=self.capacity,
level=self.current_level,
function_set=np.ones(len(self.items)).astype(int),
iterations=self.iterations)
self.current_max_value = self.max_potential_value
self.next_level = self.current_level
def explore_branch(self):
'''Traverses an individual branch until it:
(1) uses up too much weight (the "floor" is negative),
(2) is exhausted, or
(3) does not have the potential to have more value than the current best answer.
Then updates state for next exploration. This function is used in a while loop.
'''
for item in range(self.next_level, len(self.items), 1):
# if we already have a best value that is higher than what is possible, break
if self.current_max_value < self.best_value:
break
# if the next item leads us to go "over" in weight, break otherwise, include
# and update state. If we are at the end of a branch, update
if self.items[item].weight <= self.floor:
self.kept_value += self.items[item].value
self.floor -= self.items[item].weight
self.current_set[item] = 1
if self.kept_value > self.best_value:
self.best_value = self.kept_value
self.best_set = self.current_set.copy()
# when we go over from weight, update state and break
else:
break
self.iterations += 1
return self.best_value, self.best_set, self.iterations, self.next_branch(item)
def next_branch(self, item):
'''Updates state values for next branch to be traversed. Calculates:
(1) max_potential_value
(2) floor
(3) kept_value
(4) index_level and item set'''
# update floor and max_potential_value
if item == len(self.items) - 1: # branch exhausted
if self.current_set[0] == 1:
# find first 0, set level to one higher and that value to 0
self.current_level = np.where(self.current_set == 0)[0][0] - 1
self.current_set[self.current_level] = 0
self.current_set[item] = 1
else:
# find first 1, set value to 0 and make current level; subsequent levels to 1
self.current_level = np.where(self.current_set == 1)[0][0]
self.current_set[self.current_level] = 0
self.current_set[self.current_level+1:] = 1
else:
self.current_level = item
# calculate floor and kept value
self.floor, self.kept_value = self._update_floor_and_kept_value(items=self.items,
capacity=self.capacity,
level=self.current_level,
function_set=self.current_set.copy(),
iterations=self.iterations)
# calculate max value
self.current_max_value = self._value_estimate(items=self.items,
capacity=self.capacity,
level=self.current_level,
function_set=self.current_set.copy(),
iterations=self.iterations)
self.next_level = self.current_level + 1
return self.current_max_value, self.floor, self.kept_value, self.next_level, self.current_set
@staticmethod
def _value_estimate(items, capacity, level, function_set, iterations):
'''This finds the best fractional value that the bag can hold.'''
# initialize. since this is an update, it is called when branches
# "move left" - therefore, the current level will be 0 (item not included)
estimated_value = 0
if iterations > 0:
function_set[level] = 0
function_set[level+1:] = 1
# for new branch, calculate potential/fractional value creation
for i, item in enumerate(items):
if (item.weight < capacity) & (function_set[i] == 1):
estimated_value += item.value
capacity -= item.weight
elif function_set[i] == 0:
pass
else:
return(estimated_value + capacity*item.density)
return estimated_value
@staticmethod
def _update_floor_and_kept_value(items, capacity, level, function_set, iterations):
'''This finds the floor and "starting value" for the node in the new branch.'''
# initialize. set later values to 0 - this allows us to loop through the
# branch fully without accounting for those items' value
floor = capacity
kept_value = 0
if iterations > 0:
function_set[level] = 0
function_set[level+1:] = 0
for i, item in enumerate(items):
if (item.weight < capacity) & (function_set[i] == 1):
floor -= item.weight
kept_value += item.value
elif function_set[i] == 0:
pass
return floor, kept_value
def _load_data(self):
'''Takes Coursera input files splits them, and creates a tuple in
their preferred format. Sorted - needs to be unsorted for output.'''
def density_sort(item_list):
return(sorted(item_list, key=lambda item:-item.density))
Item = namedtuple("Item", ['index', 'value', 'weight', 'density'])
# parse the input
lines = self.input_data.split('\n')
firstLine = lines[0].split()
item_count = int(firstLine[0])
capacity = int(firstLine[1])
items = []
for i in range(1, item_count+1):
line = lines[i]
parts = line.split()
items.append(Item(i-1, int(parts[0]), int(parts[1]),
float(parts[0])/float(parts[1])))
items = density_sort(items)
return items, item_count, capacity
def _generate_output(self):
'''Since we sorted the output to improve the runtime, we need to resort
it back to the original value for grading.'''
# sort "back" the selected items
index_list = []
for i, item in enumerate(self.items):
index_list.append(self.items[i].index)
zipped_list = zip(index_list, self.best_set)
resorted_selection = sorted(list(zipped_list), key=lambda x: x[0])
final_selection = [y for (x, y) in resorted_selection]
# prepare the solution in the specified output format
output_data = str(self.best_value) + ' ' + str(0) + '\n '
output_data += ' '.join(map(str, final_selection))
return output_data |
# Exercise 3
# Fermat’s Last Theorem says that there are no positive integers a, b, and c such that
a**n + b**n == c**n
for
# any values of n greater than 2.
# Write a function named check_fermat that takes four parameters—a, b, c and n —and checks to see if Fermat’s theorem holds. If n is greater than 2 and a**n + b**n = c**n the program should print, "Holy smokes, Fermat was wrong!" Otherwise the program should print, "No, that doesn't work."
# Write a function that prompts the user to input values for a, b, c and n, converts them to integers, and uses check_fermat to check whether they violate Fermat’s theorem.
# Objective challenge:
# As you write Python programs, it is important to know when to use a certain data structure and when to use something else. Write out an explanation of when and why you would use each data structure: a list, a dictionary, a tuple, and a set.
#
# Objective challenge:
# Complete the following either in a python script file or directly in the python interpreter: |
import random
import time
print("Welcome To Mallaya Bank:")
time.sleep(0.44)
print("")
print("")
print("TO CREATE AN ACCOUNT,WAIT FOR 5 SECONDS WITHOUT TERMINATION")
time.sleep(5)
print("Enter the Details as per your aadhar card")
time.sleep(3)
b=int(input("Enter your 16 digit AADHAR NUMBER:"))
b = str(b)
d = input("Enter Your Name:")
if len(b)==16:
print('Yes, 16 numbers are there')
print(d)
e=int(input("Enter your Indian Phone Number: +91"))
c=input("Enter Your Plot number:")
f=input("Enter your street name:")
g=input("Enter your area name:")
h=input("Enter your City and State seperated by a comma:")
print("Congratulations" ,d, "Your account has been created in the name of:",d)
print("Your Mailing Address And Ph.no Will be:",c,",",f,",",g,",",h,",",e)
anum=0
acc = ""
for i in range(13):
num = (random.randint(0,9))
acc += str(num)
print("Your new account number is ",acc)
print("You will have a minimum account balance of Rs.500")
anum+=500
time.sleep(2)
def welcomeMessage():
print("Welcome Again:")
time.sleep(2)
print("ENTER 1 TO ATTAIN A DEBIT CARD OR A CREDIT CARD")
print("ENTER 2 TO APPLY FOR A LOAN:")
print("ENTER 3 FOR WITHDRAWLS OR DEPOSITS")
print("ENTER 7 FOR FOREIGN EXCHANGE")
print("ENTER 8 TO KNOW ABOUT YOUR A/C STATUS/BALANCE ")
output=int(input("Enter the required number:"))
return output
output = welcomeMessage()
if output==1:
DE=""
re=""
DE=input("ENTER DR TO APPLY FOR DEBIT CARD,ENTER CR TO APPLY FOR CREDIT CARD:")
if DE=="DR":
re=int(input("Enter your account number:"))
print("Welcome ",d)
cx = ""
for i in range(16):
nume = (random.randint(0,9))
cx += str(nume)
print("Your new debit card number is ",cx )
oo = ""
for i in range(3):
numer = (random.randint(0,9))
oo += str(numer)
print("Your CVV is:",oo)
WE=input("IF YOU WANT YOUR OWN PIN NUMBER,TYPE'YES',ELSE TYPE 'NO':")
if WE =='YES':
ddd=int(input("Enter Your New Pin:"))
print(ddd,"is your new pin")
else:
oo0 = ""
for i in range(4):
numeroid = (random.randint(0,9))
oo0 += str(numeroid)
print(oo0,"is your pin number")
welcomeMessage()
else:
eds=int(input("CREDIT CARD CHECK:Enter 1 if you are 21,and with a job with a 6 digit income,,,if you have an exception press 2"))
if eds==1:
print("you are eligible")
oo00 = ""
for i in range(17):
numeroid = (random.randint(0,9))
oo00 += str(numeroid)
print(oo00,"is your credit card number:")
WEd=input("IF YOU WANT YOUR OWN PIN NUMBER,TYPE'YES',ELSE TYPE 'NO':")
if WEd =='YES':
dddi=int(input("Enter Your New Pin:"))
print(dddi,"is your new pin")
else:
oo03 = ""
for i in range(5):
numeroid = (random.randint(0,9))
oo033 += str(numeroid)
print(oo03,"is your pin number")
oo11111=""
for i in range(4):
numerthala = (random.randint(0,9))
oo11111 += str(numerthala)
print("Your CVV is:",oo11111)
else:
print("Sorry,You aren't eligible")
elif output==2:
print("You will only be considered as a loan candidate only if your CIBIL is above 580:")
d09=int(input("ENTER YOUR CIBIL SCORE:"))
if d09<=580:
print("PLease have a minimum CIBIL score of 580 ")
else:
print("You are eligible")
lml=int(input("Enter the amount you wish to take as a loan"))
if lml<=400000:
print("The loan amount has been transferred to your account")
anum+=lml
gello=int(input("Enter 1 to continue else enter to 2 to stop"))
if gello==2:
print("end")
else:
print("Enter a different number")
welcomeMessage()
elif output==3:
print("Your account balance is ",anum)
the=int(input("Enter 1 to withdrawl or 2 to deposit"))
if the==1:
trey=int(input("ENTER THE AMOUNT YOU WISH TO WITHDRAWL:"))
if trey>anum:
print("Insufficient Funds")
else:
anum=anum-trey
print("Your withdrawl is succesful and your account balance is:",anum)
time.sleep(3)
welcomeMessage()
else:
Trey=int(input("ENTER THE AMOUNT YOU WISH TO DEPOSIT:"))
anum=anum+Trey
print("Your new account balance is:",anum)
time.sleep(2.88)
welcomeMessage()
elif output==7:
print("We have three foreign currencies to exchange;US dollars(23),Euros(34),Australian dollars(44)")
tyu=int(input("Enter the currenvey code given from above:"))
if tyu==23:
opi=int(input("Enter the INR amount you are willing to offer for the exchange:"))
fv=opi/76
print("The amount of dollars you will be getiing is:",fv)
elif tyu==34:
opt=int(input("Enter the INR amount you are willing to offer for the exchange:"))
fvy=opi/88
print("The amount of euros you will be getiing is:",fvy)
elif tyu==44:
opu=int(input("Enter the INR amount you are willing to offer for the exchange:"))
fgh=opu/55
print("The amount of aus dollars you will be getiing is:",fgh)
time.sleep(2.88)
welcomeMessage()
elif output==8:
print("Your account balance is",anum)
time.sleep(2.88)
welcomeMessage()
|
import unittest
from shopping import Cart, CartItem, Merchandise
from shopping.exceptions import InvalidCartItem, InvalidProduct
class Base(unittest.TestCase):
def setUp(self):
self.book = Merchandise(name='book',
price=1.99,
category='book',
imported=False)
self.perfume = Merchandise(name='perfume',
price='10.19',
category='accessory',
imported=True)
self.music = Merchandise(name='music CD',
price='5.29',
category='music',
imported=False)
class TestCartItem(Base):
def test_cart_item_validity(self):
expected = CartItem(item=Merchandise(name='book',
price=1.99,
category='book',
imported=False),
total=1.99,
tax_amount=0.0,
_qty=1)
cart_item = CartItem(self.book)
self.assertEqual(cart_item, expected)
def test_cart_item_failure(self):
with self.assertRaises(InvalidProduct):
CartItem('Product')
def test_cart_item_price_with_tax(self):
cart_item = CartItem(self.perfume)
self.assertEqual(cart_item.total, 11.74)
self.assertEqual(cart_item.tax_amount, 1.55)
def test_cart_item_quantity(self):
cart_item = CartItem(self.music)
self.assertEqual(cart_item.qty, 1)
self.assertEqual(cart_item.total, 5.84)
self.assertEqual(cart_item.tax_amount, 0.55)
cart_item.qty = 10
self.assertEqual(cart_item.qty, 10)
self.assertEqual(cart_item.total, 58.4)
self.assertEqual(cart_item.tax_amount, 5.5)
def test_cart_item_quantity_failure(self):
cart_item = CartItem(self.music)
with self.assertRaises(ValueError):
cart_item.qty = 'ten'
class TestCart(Base):
def setUp(self):
super().setUp()
self.cart_item_book = CartItem(self.book)
self.cart_item_perfume = CartItem(self.perfume)
self.cart_item_music = CartItem(self.music)
def test_cart_validity(self):
expected = [
CartItem(item=Merchandise(name='book',
price=1.99,
category='book',
imported=False),
total=1.99,
tax_amount=0.0),
CartItem(item=Merchandise(name='perfume',
price=10.19,
category='accessory',
imported=True),
total=11.74,
tax_amount=1.55)
]
items = [self.cart_item_book, self.cart_item_perfume]
cart = Cart(items)
self.assertEqual(cart.items, expected)
def test_cart_failure(self):
with self.assertRaises(InvalidCartItem):
Cart(self.book)
with self.assertRaises(InvalidCartItem):
Cart([self.book, self.music])
def test_cart_add_merchandise(self):
expected_1 = self.cart_item_book
expected_1.qty = 10
cart = Cart()
cart.add_merchandise(self.book, qty=10)
self.assertEqual(cart.items, [expected_1])
cart = Cart()
cart.add_merchandise([self.book, self.perfume])
expected_2 = self.cart_item_perfume
expected_1 = self.cart_item_book
expected_1.qty = 1
self.assertEqual(cart.items, [expected_1, expected_2])
def test_cart_add_merchandise_failure(self):
cart = Cart()
with self.assertRaises(InvalidProduct):
cart.add_merchandise('Product')
def test_cart_total(self):
cart = Cart()
cart.add_merchandise([self.book, self.perfume])
self.assertEqual(cart.cart_total(), 13.73)
def test_cart_total_tax(self):
cart = Cart([self.cart_item_book, self.cart_item_perfume])
self.assertEqual(cart.total_tax(), 1.55)
def test_checkout(self):
import sys
from io import StringIO
expected = [
'Qty - Items - Amount',
' 1 - book - 1.99',
' 1 - perfume - 11.74',
'Sales Tax - 1.55', 'Total(Incl. tax) - 13.73', ''
]
original_stdout = sys.stdout
sys.stdout = StringIO()
cart = Cart([self.cart_item_book, self.cart_item_perfume])
cart.checkout()
result = sys.stdout.getvalue()
sys.stdout = original_stdout
result = result.split('\n')
self.assertEqual(result, expected)
|
import unittest
from shopping import tokenize
from shopping.exceptions import InvalidOrderString
text_order_1 = """3 books at 2.99
2 music CD (imported) at 6.29"""
text_order_2 = """1 imported perfume at 7.99"""
invalid_text_order = """1 perfume 3.99"""
class TestTokenize(unittest.TestCase):
def test_tokenize_1_validation(self):
expected = [(3, 'books', 2.99, False),
(2, 'music CD (imported)', 6.29, True)]
result = []
for qty, name, price, imported in tokenize(text_order_1):
result.append((qty, name, price, imported))
self.assertEqual(result, expected)
def test_tokenize_2_validation(self):
for qty, name, price, imported in tokenize(text_order_2):
pass
self.assertEqual(qty, 1)
self.assertEqual(name, 'imported perfume')
self.assertEqual(price, 7.99)
self.assertEqual(imported, 1)
def test_tokenize_failure(self):
generator = tokenize(invalid_text_order)
with self.assertRaises(InvalidOrderString):
next(generator)
|
#It is possible to show that the square root of two can be expressed as an infinite continued fraction.
#√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
#By expanding this for the first four iterations, we get:
#1 + 1/2 = 3/2 = 1.5
#1 + 1/(2 + 1/2) = 7/5 = 1.4
#1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
#1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
#The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.
#In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
total = 0
# go through each expansion
# each expansion will go through a loop itself
for i in range(0, 1001):
fraction = [1, 2]
for j in range(0, i):
n = fraction[0]
d = fraction[1]
if j == i - 1:
fraction = [n + d, d]
else:
fraction = [d, n + d * 2]
if len(str(fraction[0])) > len(str(fraction[1])):
total += 1
print(total)
|
# Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
#1634 = 1**4 + 6**4 + 3**4 + 4**4
#8208 = 8**4 + 2**4 + 0**4 + 8**4
#9474 = 9**4 + 4**4 + 7**4 + 4**4
#As 1 = 1**4 is not a sum it is not included.
#The sum of these numbers is 1634 + 8208 + 9474 = 19316.
#Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
sum = 0
for i in range(10, 4 * 9**5):
s = str(i)
total = 0
for c in s:
total += int(c)**5
if total == i:
sum += i
print(sum)
|
#onsider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction.
#If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get:
#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
#t can be seen that there are 3 fractions between 1/3 and 1/2.
#How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d ≤ 12,000?
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
total = 0
onethird = 1 / 3
onehalf = 1 / 2
for d in range(5, 12001):
for n in range(1, d + 1):
if onethird < n / d < onehalf and gcd(n, d) == 1:
total += 1
if d > 11950:
print(total)
|
# -*- coding: utf-8 -*-
from DataTypes import SquareType
from Move import Move
class Board(object):
# Represents de possible directions to move on
directions = ((0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1))
def __init__(self, rows, cols):
self._boardData = [[SquareType.EMPTY for _ in xrange(rows)] for _ in xrange(cols)]
self._cols = 0
self._rows = 0
if rows > 0 and cols > 0:
self._rows = rows
self._cols = cols
self.set_position(3, 3, SquareType.WHITE)
self.set_position(3, 4, SquareType.BLACK)
self.set_position(4, 3, SquareType.BLACK)
self.set_position(4, 4, SquareType.WHITE)
def get_row_count(self):
return self._rows
def get_column_count(self):
return self._cols
def get_position(self, row, col):
if 0 <= col < self._cols and 0 <= row < self._rows:
return self._boardData[row][col]
return 3
def set_position(self, row, col, color):
if 0 <= col < self._cols and 0 <= row < self._rows and 0 <= color.value <= 2:
self._boardData[row][col] = color
return color
return 3
def reset_board(self):
self._boardData = [[SquareType.EMPTY for _ in xrange(self._cols)] for _ in xrange(self._rows)]
def in_board(self, row, col):
return 0 <= row < self.get_row_count() and 0 <= col < self.get_column_count()
@staticmethod
def _get_opposite(color):
if color == SquareType.WHITE:
return SquareType.BLACK
elif color == SquareType.BLACK:
return SquareType.WHITE
return color
def is_valid_move(self, move, color):
if not move:
return False
f = move.get_row()
c = move.get_col()
if not self.in_board(f, c) or not self.get_position(f, c) == SquareType.EMPTY:
return False
for step in Board.directions:
row = f + step[0]
col = c + step[1]
if self.in_board(row, col) and self.get_position(row, col) == self._get_opposite(color):
row += step[0]
col += step[1]
flag = True
while self.in_board(row, col) and flag:
# reach a piece of the same color
if self.get_position(row, col) == color:
return True
# if the square is empty
elif self.get_position(row, col) != self._get_opposite(color):
flag = False
row += step[0]
col += step[1]
return False
def get_squares_to_mark(self, move, color):
f = move.get_row()
c = move.get_col()
squares_to_mark = [(f, c)]
for step in Board.directions:
row = f + step[0]
col = c + step[1]
squares_to_mark_tmp = []
if self.in_board(row, col) and self.get_position(row, col) == self._get_opposite(color):
squares_to_mark_tmp.append((row, col))
row += step[0]
col += step[1]
flag = True
# search for a piece of my color
while self.in_board(row, col) and flag:
if self.get_position(row, col) == color:
squares_to_mark += squares_to_mark_tmp
flag = False
elif self.get_position(row, col) != self._get_opposite(color):
flag = False
else:
squares_to_mark_tmp.append((row, col))
row += step[0]
col += step[1]
return squares_to_mark
def get_possible_moves(self, color):
moves = []
for i in xrange(8):
for j in xrange(8):
move = Move(i, j)
if self.is_valid_move(move, color):
moves.append(move)
return moves
def get_as_matrix(self):
# noinspection PyUnresolvedReferences
return [[self._boardData[x][y].value for y in xrange(8)] for x in xrange(8)]
|
# -*- coding:utf-8 -*-
from Player import Player
import random
class GreedyRndPlayer(Player):
"""Jugador que siempre elige la jugada que más fichas come."""
name = 'GreedyRnd'
def __init__(self, color):
self.movs = 0
self.randomMovs=5
super(GreedyRndPlayer, self).__init__(self.name, color)
def random_move(self, board):
possible_moves = board.get_possible_moves(self.color)
i = random.randint(0, len(possible_moves) - 1)
return possible_moves[i]
def move(self, board, opponent_move):
"""
:param board: Board
:param opponent_move: Move
:return: Move
"""
if (self.movs < self.randomMovs):
self.movs+=1
return self.random_move(board)
max_squares = 0
chosen_move = None
for move in board.get_possible_moves(self.color):
tmp = len(board.get_squares_to_mark(move=move, color=self.color))
if max_squares < tmp:
chosen_move = move
max_squares = tmp
return chosen_move
def on_win(self, board):
print 'Gané y soy el color:' + self.color.name
def on_defeat(self, board):
print 'Perdí y soy el color:' + self.color.name
def on_draw(self, board):
print 'Empaté y soy el color:' + self.color.name
def on_error(self, board):
raise Exception('Hubo un error.')
|
'''
Description:
Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once.
Intervals
Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4.
Overlapping Intervals
List containing overlapping intervals:
[
[1,4],
[7, 10],
[3, 5]
]
The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4.
Examples:
sumIntervals( [
[1,2],
[6, 10],
[11, 15]
] ); // => 9
sumIntervals( [
[1,4],
[7, 10],
[3, 5]
] ); // => 7
sumIntervals( [
[1,5],
[10, 20],
[1, 6],
[16, 19],
[5, 11]
] ); // => 19
'''
def sum_of_intervals(intervals):
set_of_unit_interval = set()
for itrvl in intervals:
for i in range( itrvl[0], itrvl[1], 1 ):
unit_interval = (i, i+1)
# set guarantee no repeated elements
set_of_unit_interval.add( unit_interval )
return len(set_of_unit_interval)
def test_bench():
test_data = [
(1, 2),
(6, 10),
(11, 15)
]
# expected output:
'''
9
'''
print( sum_of_intervals( test_data) )
return
if __name__ == '__main__':
test_bench() |
'''
Description:
You are given a node that is the beginning of a linked list. This list always contains a tail and a loop.
Your objective is to determine the length of the loop.
# Use the `next' attribute to get the following node
# Example of geeting next node:
node.next
'''
def count_loop_size( node_of_meet ):
size = 1
visit = node_of_meet
# run the loop again to count loop size
while( visit.next != node_of_meet ):
visit = visit.next
size += 1
return size
def loop_size(node):
slow, fast = node, node
while True:
# use double pointer technique to make a meeting
slow = slow.next
fast = fast.next.next
if slow == fast:
loop_size = count_loop_size(slow)
break
return loop_size |
from flask import Flask, render_template, url_for, request, redirect, jsonify
from beginnersMethod import BeginnersCube
#https://www.speedsolving.com/wiki/index.php/Kociemba's_Algorithm
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html') #the folder is called template for a reason lol
@app.route('/solve', methods=['POST'])
def solve():
cubeDict = request.get_json() # parse as JSON
cube = BeginnersCube(cubeDict)
#print(cubeDict)
#print(cube)
isValid = cube.solve()
if isValid: return jsonify({"valid": True, "solution": cube.movesDone})
else: return jsonify({"valid": False})
if __name__ == "__main__":
app.run(debug=False) #fale to debug python code, True to debug front end
|
import random
PlayerName=input("What is your name?")
print("Welcome to Clash Of Gladiators, "+PlayerName+"! You're a gladiator being put into fight today!")
def start():
print("Note: The Clashes are in a storyline, so if you pick one further on, you will have everything from the list")
print("that you have in the storyline! Now, choose! VVV")
BattleChoice=input("What Battle would you like to fight? (please type the number of the battle of your choice(1-5, or Local)")
def LocalBattle():
class Character:
def __init__(self, name, health):
self.health=health
self.name=name
class Attack:
def __init__(self, name, damage, critical_damage):
self.name=name
self.damage=random.randint((damage-5), (damage+5))
self.critical_damage=critical_damage
while True:
print("Welcome to Local Battle! This is a mode where you fight someone on one computer!")
yesno=input("Do you want to play?(You can type no if you have no friends!)")
if yesno.lower()=="yes":
print("Lets get started!")
health=True
break
elif yesno.lower()=="no":
print("Okay! See ya!")
start()
break
else:
print("Sorry, I didn't understand you!")
print("Type yes or no:")
while True:
player1name=input("Player 1! Please enter your name!")
player2name=input("Player 2! Plaese enter your name!")
if player1name==player2name:
print("Please type different names!")
elif player1name!=player2name:
break
while health:
try:
player1health=int(input(player1name+", please type your desired health!"))
player2health=int(input(player2name+", please type your desired health!"))
if player1health<=0 or player2health<=0:
print("You can't have a health of 0 or less than 0 or you would be dead!")
else:
health=False
Stats=True
except:
print("Please type a number!")
player1=Character(player1name, player1health)
player2=Character(player2name, player2health)
Attacks=["Sword Slash", "Jump Jab", "Fireball", "Lightningbolt", "Weaken", "Blinding Light", "Heal"]
HealCount1=0
HealCount2=0
Blind1=False
Blind2=False
unconscious1=False
unconscious2=False
unconsciousturncount1=0
unconsciousturncount2=0
weaken1=0
weaken2=0
Stats=True
while Stats:
try:
swordslashdamage1=int(input(player1.name+", how much damage would you like SwordSlash to do?"))
swordslashdamage2=int(input(player2.name+", how much damage would you like SwordSlash to do?"))
jumpjabdamage1=int(input(player1.name+", how much damage would you like JumpJab to do?"))
jumpjabdamage2=int(input(player2.name+", how much damage would you like JumpJab to do?"))
fireballdamage1=int(input(player1.name+", how much damage would you like Fireball to do?"))
fireballdamage2=int(input(player2.name+", how much damage would you like Fireball to do?"))
lightningboltturns=int(input("Please decide how many turns you want the lightningbolt to knock players out for:"))
weakenweaken=int(input("Please decide how much damage you want like Weaken to get rid of:"))
weakendamage1=int(input(player1.name+", how much damage would you like Weaken to do?"))
weakendamage2=int(input(player2.name+", how much damage would you like Weaken to do?"))
blindinglightdamage1=int(input(player1.name+", how much damage would you like Blinding Light to do?"))
blindinglightdamage2=int(input(player2.name+", how much damage would you like Blinding Light to do?"))
healdamage1=int(input(player1.name+", how much damage would you like Heal to heal?"))
healdamage2=int(input(player2.name+", how much damage would you like Heal to heal?"))
criticalchoice=int(input("How much more damage should the critical hits do?"))
damageforattackslist=[swordslashdamage1, swordslashdamage2, jumpjabdamage1, jumpjabdamage2, fireballdamage1, fireballdamage2, lightningboltturns, weakenweaken, weakendamage1, weakendamage2, blindinglightdamage1, blindinglightdamage2, healdamage1, healdamage2, criticalchoice]
for x in damageforattackslist:
if x<0:
Go=False
break
elif x>0:
Go=True
SwordSlash1=Attack("swordslash", swordslashdamage1, (swordslashdamage1+criticalchoice))
SwordSlash2=Attack("swordslash", swordslashdamage2, (swordslashdamage2+criticalchoice))
JumpJab1=Attack("jumpjab", jumpjabdamage1, (jumpjabdamage1+criticalchoice))
JumpJab2=Attack("jumpjab", jumpjabdamage2, (jumpjabdamage2+criticalchoice))
Fireball1=Attack("fireball", fireballdamage1, (fireballdamage1+criticalchoice))
Fireball2=Attack("fireball", fireballdamage2, (fireballdamage2+criticalchoice))
Lightningbolt=Attack("lightningbolt", 0, 0)
Weaken1=Attack("weaken", weakendamage1, (weakendamage1+criticalchoice))
Weaken2=Attack("weaken", weakendamage2, (weakendamage2+criticalchoice))
BlindingLight1=Attack("blindinglight", blindinglightdamage1, (blindinglightdamage1+criticalchoice))
BlindingLight2=Attack("blindinglight", blindinglightdamage2, (blindinglightdamage2+criticalchoice))
Heal1=Attack("heal", healdamage1, (healdamage1+criticalchoice))
Heal2=Attack("heal", healdamage2, (healdamage2+criticalchoice))
if Go==True:
run=True
Stats=False
print("That's all the stats set, now it's time to BATTLE!")
break
elif Go==False:
print("Please do not use negatives. It will cause problems!")
except:
print("Please type numbers!")
print("Local Battle! "+player1.name+" Vs. "+player2.name+"!")
while run:
if not unconscious1: #Player1 Attacks HERE
if not Blind1:
print("It's "+player1.name+"'s turn!")
move=input("Here are your attacks:"+str(Attacks)+" Please choose one!").lower()
if move=="swordslash" or move=="sword slash":
print(player1.name+" used Sword Slash!")
hit_chance=random.randint(1, 10)
if hit_chance<4:
player2.health-=(SwordSlash1.damage-weaken2)
print(player1.name+"'s sword met its destination! "+player2.name+"'s health is now "+str(player2.health)+"!")
elif hit_chance>7 and not unconscious2:
print(player2.name+" dodged your attack at the last second. Better luck next time!")
print(player2.name+"'s health is at "+str(player2.health)+"!")
else:
player2.health-=(SwordSlash1.critical_damage-weaken2)
print("WOW! A critical hit! "+player2.name+"'s health is now at"+str(player2.health)+"!")
elif move=="jumpjab" or move=="jump jab":
print(player1.name+" used Jump Jab!")
hit_chance=random.randint(1, 10)
if hit_chance<4:
player2.health-=(JumpJab1.damage-weaken2)
print(player1.name+"'s sword met its destination! "+player2.name+"'s health is now "+str(player2.health)+"!")
elif hit_chance>8 and not unconscious2:
print(player2.name+" dodged your attack at the last second. Better luck next time!")
print(player2.name+"'s health is at "+str(player2.health)+"!")
else:
player2.health-=(JumpJab1.critical_damage-weaken2)
print("WOW! A critical hit! "+player2.name+"'s health is now "+str(player2.health)+"!")
elif move=="fireball" or move=="fire ball":
print(player1.name+" used Fireball!")
hit_chance=random.randint(1, 10)
if hit_chance<6:
player2.health-=(Fireball1.damage-weaken2)
print(player1.name+"'s Fireball hit "+player2.name+"! "+player2.name+"'s health is at "+str(player2.health)+"!")
elif hit_chance>=6 and hit_chance<8 and not unconscious2:
print(player2.name+" was to fast!")
else:
player2.health-=(Fireball1.critical_damage-weaken2)
print("Critical hit! Good job! "+player2.name+"'s health is now "+str(player2.health)+"!")
elif move=="lightningbolt" or move=="lightning bolt":
chance=random.randint(1, 10)
if unconscious2==False:
print(player1.name+" used Lightningbolt!")
print("Lightningbolt knocks out the opponent for 2 turns, but doesn't do any damage.")
if chance>5:
print("The lightningbolt hit! "+player2.name+"'s health is at "+str(player2.health)+"!")
unconscious2=True
else:
print("Oh no, the lightningbolt missed! "+player2.name+"'s health is at "+str(player2.health)+"!")
else:
print("You are not alowed to use this move if the enemy is still unconscious.")
elif move=="weaken":
print(player1.name+" used Weaken!")
print("Weaken weakens the opponents attacks.")
chance=random.randint(1,10)
if chance<3:
print("Uh oh! The Weaken didn't work! "+player2.name+"'s health is at "+str(player2.health)+"!")
else:
weaken1=weakenweaken
chance=random.randint(1,10)
if chance<7:
player2.health-=(Weaken1.damage-weaken2)
print("The Weaken also did damage! "+player2.name+"'s health is now at "+str(player2.health)+"!")
else:
player2.health-=(Weaken1.critical_damage-weaken2)
print("The Weaken also did critical damage! "+player2.name+"'s health is at "+str(player2.health)+"!")
elif move=="blindinglight" or move=="blinding light":
chance=random.randint(1,10)
print(player1.name+" used Blinding Light!")
print("Blinding Light makes your opponent very blind and have a 10% chance of hitting you.")
Blind2=True
if chance<4:
player2.health-=(BlindingLight1.damage-weaken2)
print("The Blinding Light also did damage! "+player2.name+"'s health is now "+str(player2.health)+".")
elif chance>=4 and chance<8:
player2.health-=(BlindingLight1.damage-weaken2)
print("The Blinding Light also did critical damage! "+player2.name+"'s health is now "+str(player2.health)+".")
else:
print("The Blinding Light didn't do any damage!")
elif move=="heal":
if HealCount1<3:
chance=random.randint(1,10)
print(player1.name+" used Heal!")
print("Note: You can only heal 3 times in each Battle regardless of wheather the heal works or not.")
HealCount1+=1
if chance<5:
player1.health+=(Heal1.damage-weaken2)
print("The Heal worked! "+player1.name+"'s health is now at "+str(player1.health)+"!")
elif chance>=5 and chance<8:
player1.health+=(Heal1.critical_damage-weaken2)
print("The Heal worked extra well! "+player1.name+"'s health is now at "+str(player1.health)+"!")
else:
print("The Heal didn't work at all! "+player1.name+"'s health is at "+str(player1.health)+"!")
else:
print("You can't use heal more than 3 times. You turn has been skipped.")
else:
print("That is not a valid attack choice. Skipping your turn.")
elif Blind1:
print("It's "+player1.name+"'s turn!")
print(player1.name+" is blind!")
move=input("Here are your attacks:"+str(Attacks)+" Please choose one!").lower()
if move=="swordslash" or move=="sword slash":
print(player1.name+" used Sword Slash!")
hit_chance=random.randint(1, 10)
if hit_chance==4:
player2.health-=(SwordSlash1.damage-weaken2)
print(player1.name+"'s sword met its destination! "+player2.name+"'s health is now "+str(player2.health)+"!")
else:
print("What a miss!")
elif move=="jumpjab" or move=="jump jab":
print(player1.name+" used Jump Jab!")
hit_chance=random.randint(1, 10)
if hit_chance==7:
player2.health-=(JumpJab1.damage-weaken2)
print(player1.name+"'s sword met its destination! "+player2.name+"'s health is now "+str(player2.health)+"!")
else:
print("Blindness caused a miss! Such a shame!")
elif move=="fireball" or move=="fire ball":
print(player1.name+" used Fireball!")
hit_chance=random.randint(1, 10)
if hit_chance==6:
player2.health-=(Fireball1.damage-weaken2)
print(player1.name+"'s Fireball hit "+player2.name+"! "+player2.name+"'s health is at "+str(player2.health)+"!")
else:
print("Miss!")
elif move=="lightningbolt" or move=="lightning bolt":
chance=random.randint(1, 10)
if unconscious2==False:
print(player1.name+" used Lightningbolt!")
print("Lightningbolt knocks out the opponent for 2 turns, but doesn't do any damage.")
if chance==5:
print("The lightningbolt hit! "+player2.name+"'s health is at "+str(player2.health)+"!")
unconscious2=True
else:
print("Oh no, the lightningbolt missed! "+player2.name+"'s health is at "+str(player2.health)+"!")
else:
print("You are not alowed to use this move if the enemy is still unconscious.")
elif move=="weaken":
print(player1.name+" used Weaken!")
print("Weaken weakens the opponents attacks.")
chance=random.randint(1,10)
Weaken1=weakenweaken
if chance==3:
player2.health-=(Weaken1.damage-weaken2)
print("The Weaken also did damage! "+player2.name+"'s health is now at "+str(player2.health)+"!")
else:
print("The Weaken didn't do any additional damage!")
elif move=="blindinglight" or move=="blinding light":
chance=random.randint(1,10)
print(player1.name+" used Blinding Light!")
print("Blinding Light makes your opponent very blind and have a 10% chance of hitting you.")
Blind2=True
if chance==4:
player2.health-=(BlindingLight1.damage-weaken2)
print("The Blinding Light also did damage! "+player2.name+"'s health is now "+str(player2.health)+".")
else:
print("The Blinding Light didn't do any damage!")
elif move=="heal":
if HealCount1<3:
chance=random.randint(1,10)
print(player1.name+" used Heal!")
print("Note: You can only heal 3 times in each Battle regardless of wheather the heal works or not.")
HealCount1+=1
if chance==7:
player1.health+=(Heal1.damage-weaken2)
print("The Heal worked! "+player1.name+"'s health is now at "+str(player1.health)+"!")
else:
print("The Heal didn't work at all! "+player1.name+"'s health is at "+str(player1.health)+"!")
else:
print("You can't use heal more than 3 times. You turn has been skipped.")
else:
print("That is not a valid attack choice. Skipping your turn.")
else:
unconsciousturncount1+=1
if unconsciousturncount1==lightningboltturns:
unconsciousturncount1=0
unconscious1=False
print(player1.name+" will wake up after the next turn!")
else:
print(player1.name+" is unconscious!")
weaken2=0
Blind1=False
if player2.health<=0:
print(player1.name+" has won!")
yesno=input("Rematch?")
if yesno=="yes":
print("Here we go!")
elif yesno=="no":
print("Okay!")
break
else:
print("I didn't understand you! To the menu we go!")
break
elif player1.health<=0:
print(player2.name+" has won!")
yesno=input("Rematch?")
if yesno=="yes":
print("Here we go!")
elif yesno=="no":
print("Okay!")
break
else:
print("I didn't understand you! To the menu we go!")
break
if not unconscious2: #Player2 Attacks HERE
if not Blind2:
print("It's "+player2.name+"'s turn!")
move=input("Here are your attacks:"+str(Attacks)+" Please choose one!").lower()
if move=="swordslash" or move=="sword slash":
print(player2.name+" used Sword Slash!")
hit_chance=random.randint(1, 10)
if hit_chance<4:
player1.health-=(SwordSlash2.damage-weaken1)
print(player2.name+"'s sword met its destination! "+player1.name+"'s health is now "+str(player1.health)+"!")
elif hit_chance>7 and not unconscious1:
print(player1.name+" dodged your attack at the last second. Better luck next time!")
print(player1.name+"'s health is at "+str(player1.health)+"!")
else:
player1.health-=(SwordSlash2.critical_damage-weaken1)
print("WOW! A critical hit! "+player1.name+"'s health is now at"+str(player1.health)+"!")
elif move=="jumpjab" or move=="jump jab":
print(player2.name+" used Jump Jab!")
hit_chance=random.randint(1, 10)
if hit_chance<4:
player1.health-=(JumpJab2.damage-weaken1)
print(player2.name+"'s sword met its destination! "+player1.name+"'s health is now "+str(player1.health)+"!")
elif hit_chance>8 and not unconscious1:
print(player1.name+" dodged your attack at the last second. Better luck next time!")
print(player1.name+"'s health is at "+str(player1.health)+"!")
else:
player1.health-=(JumpJab2.critical_damage-weaken1)
print("WOW! A critical hit! "+player1.name+"'s health is now "+str(player1.health)+"!")
elif move=="fireball" or move=="fire ball":
print(player2.name+" used Fireball!")
hit_chance=random.randint(1, 10)
if hit_chance<6:
player1.health-=(Fireball2.damage-weaken1)
print(player2.name+"'s Fireball hit "+player1.name+"! "+player1.name+"'s health is at "+str(player1.health)+"!")
elif hit_chance>=6 and hit_chance<8 and not unconscious1:
print(player1.name+" was to fast!")
else:
player1.health-=(Fireball2.critical_damage-weaken1)
print("Critical hit! Good job! "+player1.name+"'s health is now "+str(player1.health)+"!")
elif move=="lightningbolt" or move=="lightning bolt":
chance=random.randint(1, 10)
if unconscious1==False:
print(player2.name+" used Lightningbolt!")
print("Lightningbolt knocks out the opponent for 2 turns, but doesn't do any damage.")
if chance>5:
print("The lightningbolt hit! "+player1.name+"'s health is at "+str(player1.health)+"!")
unconscious1=True
else:
print("Oh no, the lightningbolt missed! "+player1.name+"'s health is at "+str(player1.health)+"!")
else:
print("You are not alowed to use this move if the enemy is still unconscious.")
elif move=="weaken":
print(player2.name+" used Weaken!")
print("Weaken weakens the opponents attacks.")
chance=random.randint(1,10)
if chance<3:
print("Uh oh! The Weaken didn't work! "+player1.name+"'s health is at "+str(player1.health)+"!")
else:
weaken2=weakenweaken
chance=random.randint(1,10)
if chance<7:
player1.health-=(Weaken2.damage-weaken1)
print("The Weaken also did damage! "+player1.name+"'s health is now at "+str(player1.health)+"!")
else:
player1.health-=(Weaken2.critical_damage-weaken1)
print("The Weaken also did critical damage! "+player1.name+"'s health is at "+str(player1.health)+"!")
elif move=="blindinglight" or move=="blinding light":
chance=random.randint(1,10)
print(player2.name+" used Blinding Light!")
print("Blinding Light makes your opponent very blind and have a 10% chance of hitting you.")
Blind1=True
if chance<4:
player1.health-=(BlindingLight2.damage-weaken1)
print("The Blinding Light also did damage! "+player1.name+"'s health is now "+str(player1.health)+".")
elif chance>=4 and chance<8:
player1.health-=(BlindingLight2.damage-weaken1)
print("The Blinding Light also did critical damage! "+player1.name+"'s health is now "+str(player1.health)+".")
else:
print("The Blinding Light didn't do any damage!")
elif move=="heal":
if HealCount2<3:
chance=random.randint(1,10)
print(player2.name+" used Heal!")
print("Note: You can only heal 3 times in each Battle regardless of wheather the heal works or not.")
HealCount2+=1
if chance<5:
player2.health+=(Heal2.damage-weaken1)
print("The Heal worked! "+player2.name+"'s health is now at "+str(player2.health)+"!")
elif chance>=5 and chance<8:
player2.health+=(Heal2.critical_damage-weaken1)
print("The Heal worked extra well! "+player2.name+"'s health is now at "+str(player2.health)+"!")
else:
print("The Heal didn't work at all! "+player2.name+"'s health is at "+str(player2.health)+"!")
else:
print("You can't use heal more than 3 times. You turn has been skipped.")
else:
print("That is not a valid attack choice. Skipping your turn.")
elif Blind2:
print("It's "+player2.name+"'s turn!")
print(player2.name+" is blind!")
move=input("Here are your attacks:"+str(Attacks)+" Please choose one!").lower()
if move=="swordslash" or move=="sword slash":
print(player2.name+" used Sword Slash!")
hit_chance=random.randint(1, 10)
if hit_chance==4:
player1.health-=(SwordSlash2.damage-weaken1)
print(player2.name+"'s sword met its destination! "+player1.name+"'s health is now "+str(player1.health)+"!")
else:
print("What a miss!")
elif move=="jumpjab" or move=="jump jab":
print(player2.name+" used Jump Jab!")
hit_chance=random.randint(1, 10)
if hit_chance==7:
player1.health-=(JumpJab2.damage-weaken1)
print(player2.name+"'s sword met its destination! "+player1.name+"'s health is now "+str(player1.health)+"!")
else:
print("Blindness caused a miss! Such a shame!")
elif move=="fireball" or move=="fire ball":
print(player2.name+" used Fireball!")
hit_chance=random.randint(1, 10)
if hit_chance==6:
player1.health-=(Fireball2.damage-weaken1)
print(player2.name+"'s Fireball hit "+player1.name+"! "+player1.name+"'s health is at "+str(player1.health)+"!")
else:
print("Miss!")
elif move=="lightningbolt" or move=="lightning bolt":
chance=random.randint(1, 10)
if unconscious1==False:
print(player2.name+" used Lightningbolt!")
print("Lightningbolt knocks out the opponent for 2 turns, but doesn't do any damage.")
if chance==5:
print("The lightningbolt hit! "+player1.name+"'s health is at "+str(player1.health)+"!")
unconscious1=True
else:
print("Oh no, the lightningbolt missed! "+player1.name+"'s health is at "+str(player1.health)+"!")
else:
print("You are not alowed to use this move if the enemy is still unconscious.")
elif move=="weaken":
print(player2.name+" used Weaken!")
print("Weaken weakens the opponents attacks.")
chance=random.randint(1,10)
if chance==3:
player1.health-=(Weaken2.damage-weaken1)
print("The Weaken also did damage! "+player1.name+"'s health is now at "+str(player1.health)+"!")
else:
print("The Weaken didn't do any additional damage!")
elif move=="blindinglight" or move=="blinding light":
chance=random.randint(1,10)
print(player2.name+" used Blinding Light!")
print("Blinding Light makes your opponent very blind and have a 10% chance of hitting you.")
Blind1=True
if chance==4:
player1.health-=(BlindingLight2.damage-weaken1)
print("The Blinding Light also did damage! "+player1.name+"'s health is now "+str(player1.health)+".")
else:
print("The Blinding Light didn't do any damage!")
elif move=="heal":
if HealCount2<3:
chance=random.randint(1,10)
print(player2.name+" used Heal!")
print("Note: You can only heal 3 times in each Battle regardless of wheather the heal works or not.")
HealCount2+=1
if chance==7:
player2.health+=(Heal2.damage-weaken1)
print("The Heal worked! "+player2.name+"'s health is now at "+str(player2.health)+"!")
else:
print("The Heal didn't work at all! "+player2.name+"'s health is at "+str(player2.health)+"!")
else:
print("You can't use heal more than 3 times. You turn has been skipped.")
else:
print("That is not a valid attack choice. Skipping your turn.")
else:
unconsciousturncount2+=1
if unconsciousturncount2==lightningboltturns:
unconsciousturncount2=0
unconscious2=False
print(player2.name+" will wake up after the next turn!")
else:
print(player2.name+" is unconscious!")
Blind2=False
weaken1=0
if player2.health<=0:
print(player1.name+" has won!")
yesno=input("Rematch?")
if yesno=="yes":
print("Here we go!")
elif yesno=="no":
print("Okay!")
break
else:
print("I didn't understand you! To the menu we go!")
break
elif player1.health<=0:
print(player2.name+" has won!")
yesno=input("Rematch?")
if yesno=="yes":
print("Here we go!")
elif yesno=="no":
print("Okay!")
break
else:
print("I didn't understand you! To the menu we go!")
break
def Battle1():
class Character:
def __init__(self, name, health):
self.health=health
self.name=name
class Attack:
def __init__(self, name, damage, critical_damage):
self.name=name
self.damage=random.randint((damage-5), (damage+5))
self.critical_damage=critical_damage
class EnemyAttack:
def __init__(self, name, damage, critical_damage):
self.name=name
self.damage=random.randint((damage-5),(damage+5))
self.critical_damage=critical_damage
Attacks=["Sword Slash", "Jump Jab"]
SwordSlash=Attack("swordslash", 10, 23)
JumpJab=Attack("jumpjab", 15, 24)
player=Character(PlayerName, 50)
Enemy1=Character("Swordsman", 50)
Stab=EnemyAttack("stab", 12, 21)
Uppercut=EnemyAttack("uppercut", 20, 22)
print("Battle 1! Welcome "+player.name+" to the battle! He will be fighting "+Enemy1.name+"!")
print("You have "+str(player.health)+" health. The Swordsman has "+str(Enemy1.health)+" health.")
Battle1=True
while Battle1:
move=input("Here are your attacks:"+str(Attacks)+" Please choose one!").lower()
if move=="swordslash" or move=="sword slash":
print("You used Sword Slash!")
hit_chance=random.randint(0, 10)
if hit_chance<4:
Enemy1.health-=SwordSlash.damage
print("Your sword met its destination! The "+Enemy1.name+"'s health is now "+str(Enemy1.health)+"!")
elif hit_chance>7:
print("The "+Enemy1.name+" dodged your attack at the last second. Better luck next time!")
print("The "+Enemy1.name+"'s health is at "+str(Enemy1.health)+"!")
else:
Enemy1.health-=SwordSlash.critical_damage
print("WOW! A critical hit! The "+Enemy1.name+"'s health is now "+str(Enemy1.health)+"!")
elif move=="jumpjab" or move=="jump jab":
print("You used Jump Jab!")
hit_chance=random.randint(0, 10)
if hit_chance<4:
Enemy1.health-=JumpJab.damage
print("Your sword met its destination! The "+Enemy1.name+"'s health is now "+str(Enemy1.health)+"!")
elif hit_chance>8:
print("The "+Enemy1.name+" dodged your attack at the last second. Better luck next time!")
print("The "+Enemy1.name+"'s health is at "+str(Enemy1.health)+"!")
else:
Enemy1.health-=JumpJab.critical_damage
print("WOW! A critical hit! The "+Enemy1.name+"'s health is now "+str(Enemy1.health)+"!")
else:
print("That is not a valid attack choice. Skipping your turn.")
if player.health<=0:
print("You died! Restarting the game...")
start()
break
elif Enemy1.health<=0:
print("You defeated the "+Enemy1.name+"! Good job! Getting Battle 2 ready...")
Battle2()
break
enemychance=random.randint(0, 10)
if enemychance<4:
print("The "+Enemy1.name+" used Uppercut!")
enemy_critical_chance=random.randint(0, 10)
if enemy_critical_chance<5:
player.health-=Uppercut.damage
print("The uppercut hit you. Your health is now "+str(player.health)+".")
elif enemy_critical_chance>=5 and enemy_critical_chance<9:
print("Wow! You dodged the uppercut! Good job! Your health is at "+str(player.health)+".")
else:
player.health-=Uppercut.critical_damage
print("Oooh! That uppercut hit you hard! Your health is now "+str(player.health)+".")
else:
print("The "+Enemy1.name+" used Stab!")
enemy_critical_chance=random.randint(0, 10)
if enemy_critical_chance<5:
player.health-=Stab.damage
print("The "+Enemy1.name+" stabbed you. Your health is at "+str(player.health)+".")
elif enemy_critical_chance>=5 and enemy_critical_chance<8:
print("Nice dodging skills you have there! Your health is at "+str(player.health)+".")
else:
player.health-=Stab.critical_damage
print("Are you okay there? That stab was critical! Your health is at "+str(player.health)+".")
if player.health<=0:
print("You died! Restarting the game...")
start()
break
elif Enemy1.health<=0:
print("You defeated the "+Enemy1.name+"! Good job! Getting Battle 2 ready...")
Battle2()
break
def Battle2(): #Battle 2!!!!
class Character:
def __init__(self, name, health):
self.health=health
self.name=name
class Attack:
def __init__(self, name, damage, critical_damage):
self.name=name
self.damage=random.randint((damage-3), (damage+7))
self.critical_damage=critical_damage
class EnemyAttack:
def __init__(self, name, damage, critical_damage):
self.name=name
self.damage=random.randint((damage-4),(damage+6))
self.critical_damage=critical_damage
Attacks=["Sword Slash", "Jump Jab", "Fireball"]
SwordSlash=Attack("swordslash", 20, 23)
JumpJab=Attack("jumpjab", 25, 24)
Fireball=Attack("fireball", 30, 22)
player=Character(PlayerName, 110)
Enemy2=Character("Witchlock", 100)
PoisonCount=0
PoisonSwitch=False
PoisonTurnCount=0
Poison=EnemyAttack("poison", 10, 0)
Heal=EnemyAttack("heal", 20, 27)
Harmful=EnemyAttack("harmful", 25, 32)
print("Battle 2! Welcome "+player.name+" to the battle! He will be fighting "+Enemy2.name+"!")
print("You have "+str(player.health)+" health. The "+Enemy2.name+" has "+str(Enemy2.health)+" health.")
print("You spent days training for this battle. You even learned how to shoot a fireball! You are ready.")
print("Your attack damage has even increased!")
Battle2=True
while Battle2:
move=input("Here are your attacks:"+str(Attacks)+" Please choose one!").lower()
if move=="swordslash" or move=="sword slash":
print("You used Sword Slash!")
hit_chance=random.randint(0, 10)
if hit_chance<4:
Enemy2.health-=SwordSlash.damage
print("Your sword met its destination! The "+Enemy2.name+"'s health is now "+str(Enemy2.health)+"!")
elif hit_chance>7:
print("The "+Enemy2.name+" dodged your attack at the last second. Better luck next time!")
print("The "+Enemy2.name+"'s health is at "+str(Enemy2.health)+"!")
else:
Enemy2.health-=SwordSlash.critical_damage
print("WOW! A critical hit! The "+Enemy2.name+"'s health is now "+str(Enemy2.health)+"!")
elif move=="jumpjab" or move=="jump jab":
print("You used Jump Jab!")
hit_chance=random.randint(0, 10)
if hit_chance<4:
Enemy2.health-=JumpJab.damage
print("Your sword met its destination! The "+Enemy2.name+"'s health is now "+str(Enemy2.health)+"!")
elif hit_chance>8:
print("The "+Enemy2.name+" dodged your attack at the last second. Better luck next time!")
print("The "+Enemy2.name+"'s health is at "+str(Enemy2.health)+"!")
else:
Enemy2.health-=JumpJab.critical_damage
print("WOW! A critical hit! The "+Enemy2.name+"'s health is now "+str(Enemy2.health)+"!")
elif move=="fireball" or move=="fire ball":
print("You used Fireball!")
hit_chance=random.randint(0, 10)
if hit_chance<6:
Enemy2.health-=Fireball.damage
print("Your Fireball hit the "+Enemy2.name+"! The "+Enemy2.name+" health is at "+str(Enemy2.health)+"!")
elif hit_chance>=6 and hit_chance<8:
print("The "+Enemy2.name+" was to fast!")
else:
Enemy2.health-=Fireball.critical_damage
print("Critical hit! Good job! The "+Enemy2.name+"'s health is now "+str(Enemy2.health)+"!")
else:
print("That is not a valid attack choice. Skipping your turn.")
if player.health<=0:
print("You died! Restarting the game...")
start()
break
elif Enemy2.health<=0:
print("You defeated the "+Enemy2.name+"! Good job! Getting Battle 3 ready...")
Battle3()
break
enemy_critical_chance=random.randint(0, 10)
if PoisonSwitch and PoisonTurnCount<4:
player.health-=Poison.damage
PoisonTurnCount+=1
print("You are still being poisoned. Your health is now "+str(player.health)+".")
if PoisonTurnCount==3:
PoisonSwitch=False
PoisonTurnCount=0
if enemy_critical_chance<3 and PoisonCount<3 and PoisonSwitch==False:
PoisonCount+=1
PoisonSwitch=True
player.health-=Poison.damage
print("The "+Enemy2.name+" used poison!")
print("Poison decreases your health every turn for 3 turns! Your health is now "+str(player.health)+".")
elif enemy_critical_chance>=3 and enemy_critical_chance<6:
print("The "+Enemy2.name+" used Heal!")
hit_chance=random.randint(0, 10)
if hit_chance<4:
Enemy.health+=Heal.damage
print("The Heal worked fine! The "+Enemy2.name+"'s health is now "+str(Enemy2.health)+"!")
elif hit_chance>=4 and hit_chance<7:
Enemy.health+=Heal.critical_damage
print("The Heal worked awesomely! The "+Enemy2.name+"'s health is now "+str(Enemy2.health)+"!")
else:
print("The Heal didn't work at ALL! The "+Enemy2.name+"'s health is "+str(Enemy2.health)+"!")
else:
print("The "+Enemy2.name+" used Harmful!")
enemy_critical_chance=random.randint(0, 10)
if enemy_critical_chance<5:
player.health-=Harmful.damage
print("The Harmful Potion hit you! Your health is now at "+str(player.health)+"!")
elif enemy_critical_chance>=5 and enemy_critical_chance<8:
print("You stepped out of the way of the Harmful Potion! Your health is at "+str(player.health)+".")
else:
player.health-=Harmful.critical_damage
print("That Harmful Potion hit you right in the head! Your health is at "+str(player.health)+".")
if player.health<=0:
print("You died! Restarting the game...")
start()
break
elif Enemy2.health<=0:
print("You defeated the "+Enemy2.name+"! Good job! Getting Battle 3 ready...")
Battle3()
break
def Battle3(): #Battle 2!!!!
class Character:
def __init__(self, name, health):
self.health=health
self.name=name
class Attack:
def __init__(self, name, damage, critical_damage):
self.name=name
self.damage=random.randint((damage-2), (damage+8))
self.critical_damage=critical_damage
class EnemyAttack:
def __init__(self, name, damage, critical_damage):
self.name=name
self.damage=random.randint((damage-3),(damage+7))
self.critical_damage=critical_damage
Attacks=["Sword Slash", "Jump Jab", "Fireball", "Lightningbolt", "Weaken"]
SwordSlash=Attack("swordslash", 40, 50)
JumpJab=Attack("jumpjab", 43, 53)
Fireball=Attack("fireball", 50, 60)
Lightningbolt=Attack("lightningbolt", 0, 0)
Weaken=Attack("weaken", 20, 30)
unconcious=False
unconciousturncount=0
weaken=0
player=Character(PlayerName, 180)
Enemy=Character("Fire Dragon", 210)
Firebreath=Attack("firebreath", 55, 65)
MeteorShower=EnemyAttack("meteorshower", 8, 0)
VolcanoEruption=Attack("volcano", 70, 90)
VolcanoBoiling=False
VolcanoTurnTimer=0
Firefist=Attack("firefist", 60, 80)
print("Battle 3! Welcome "+player.name+" to the battle! He will be fighting "+Enemy.name+"!")
print("You have "+str(player.health)+" health. The "+Enemy.name+" has "+str(Enemy.health)+" health.")
print("You trained and trained and trained, and now you are sure that you can survive the "+Enemy.name+".")
Battle3=True
while Battle3:
move=input("Here are your attacks:"+str(Attacks)+" Please choose one!").lower()
if move=="swordslash" or move=="sword slash":
print("You used Sword Slash!")
hit_chance=random.randint(0, 10)
if hit_chance<4:
Enemy.health-=SwordSlash.damage
print("Your sword met its destination! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif hit_chance>7:
print("The "+Enemy.name+" dodged your attack at the last second. Better luck next time!")
print("The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
Enemy.health-=SwordSlash.critical_damage
print("WOW! A critical hit! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif move=="jumpjab" or move=="jump jab":
print("You used Jump Jab!")
hit_chance=random.randint(0, 10)
if hit_chance<4:
Enemy.health-=JumpJab.damage
print("Your sword met its destination! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif hit_chance>8:
print("The "+Enemy.name+" dodged your attack at the last second. Better luck next time!")
print("The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
Enemy.health-=JumpJab.critical_damage
print("WOW! A critical hit! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif move=="fireball" or move=="fire ball":
print("You used Fireball!")
hit_chance=random.randint(0, 10)
if hit_chance<6:
Enemy.health-=Fireball.damage
print("Your Fireball hit the "+Enemy.name+"! The "+Enemy.name+" health is at "+str(Enemy.health)+"!")
elif hit_chance>=6 and hit_chance<8:
print("The "+Enemy.name+" was to fast!")
else:
Enemy.health-=Fireball.critical_damage
print("Critical hit! Good job! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif move=="lightningbolt" or move=="lightning bolt":
chance=random.randint(0, 10)
if unconcious==False:
print("You used Lightningbolt!")
print("Lightningbolt knocks out the opponent for 2 turns, but doesn't do any damage.")
if chance>6:
print("The lightningbolt hit! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
unconcious=True
else:
print("Oh no, the lightningbolt missed! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
print("You are not alowed to use this move if the enemy is still unconcious.")
elif move=="weaken":
print("You used Weaken!")
print("Weaken weakens the opponents attacks for this turn by 15 damage.")
chance=random.randint(0,10)
if chance<3:
print("Uh oh! The Weaken didn't work! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
weaken=15
chance=random.randint(0,10)
if chance<7:
Enemy.health-=Weaken.damage
print("The Weaken also did damage! The "+Enemy.name+"'s health is now at "+str(Enemy.health)+"!")
else:
Enemy.health-=Weaken.critical_damage
print("The Weaken also did critical damage! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
print("That is not a valid attack choice. Skipping your turn.")
if player.health<=0:
print("You died! Restarting the game...")
start()
break
elif Enemy.health<=0:
print("You defeated the "+Enemy.name+"! Good job! Getting Battle 4 ready...")
once=True
Battle4()
break
if not unconcious:
choose_attack=random.randint(1,8) #Enemy Attacks start here
if choose_attack==1 or choose_attack==2:
print("The "+Enemy.name+" used Firebreath!")
chance=random.randint(0,10)
if chance<6:
player.health-=(Firebreath.damage-weaken)
print("The Firebreath hit you in the chest! Your health is now at "+str(player.health)+"!")
elif chance>=6 and chance<8:
player.health-=(Firebreath.critical_damage-weaken)
print("The Firebreath hit you in the face! Your health is now at "+str(player.health)+"!")
else:
print("You dodged the Firebreath! Your health is at "+str(player.health)+".")
elif choose_attack==3 or choose_attack==4:
print("The "+Enemy.name+" chose MeteorShower!")
chance=random.randint(0,10)
Damage=chance*MeteorShower.damage
player.health-=(Damage-weaken)
print("You got hit by "+str(chance)+" meteors out of 10! Your health is now at "+str(player.health)+"!")
elif choose_attack==5 or choose_attack==6 and VolcanoBoiling==False:
print("The "+Enemy.name+" chose Volcano Eruption!")
VolcanoChance=random.randint(1,2)
if VolcanoChance==1:
VolcanoBoiling=True
VolcanoCritical=True
print("The Volcano will erupt in three turns! The lava is EXTRA HOT!")
if VolcanoChance==2:
VolcanoBoiling=True
VolcanoCritical=False
print("The Volcano will erupt in three turns!")
else:
print("The "+Enemy.name+" used Firefist!")
chance=random.randint(1,3)
if chance==1:
player.health-=(Firefist.damage-weaken)
print("The Firefist hit you in the arm! Your health is now at "+str(player.health)+"!")
elif chance==2:
player.health-=(Firefist.critical_damage-weaken)
print("The Firefist hit you in the gut! Your health is now at "+str(player.health)+"!")
else:
print("You dodged the Firefist! Your health is at "+str(player.health)+"!")
else:
unconciousturncount+=1
if unconciousturncount==2:
unconciousturncount=0
unconcious=False
print("The "+Enemy.name+" will wake up after your next turn!")
else:
print("The "+Enemy.name+" is unconcious!")
if VolcanoBoiling:
VolcanoTurnTimer+=1
if VolcanoTurnTimer==4:
VolcanoTurnTimer=0
VolcanoBoiling=False
VolcanoChance=random.randint(1,2)
if VolcanoChance==1:
if VolcanoCritical:
player.health-=(VolcanoEruption.critical_damage-weaken)
print("The volano erupted, soaking you in extra hot lava! Your health is now "+str(player.health)+"!")
elif not VolcanoCritical:
player.health-=(VolcanoEruption.damage-weaken)
print("The volano erupted, soaking you in lava! Your health is now "+str(player.health)+"!")
elif VolcanoChance==2:
print("You managed to find cover right before the lava from the volcano soaked everything! Your health is at "+str(player.health)+"!")
else:
print("The lava in the volcano is still rising.")
weaken=0
if player.health<=0:
print("You died! Restarting the game...")
start()
break
elif Enemy.health<=0:
print("You defeated the "+Enemy.name+"! Good job! Getting Battle 4 ready...")
Battle4()
break
def Battle4(): #Battle 2!!!!
class Character:
def __init__(self, name, health):
self.health=health
self.name=name
class Attack:
def __init__(self, name, damage, critical_damage):
self.name=name
self.damage=random.randint((damage-1), (damage+9))
self.critical_damage=critical_damage
class EnemyAttack:
def __init__(self, name, damage, critical_damage):
self.name=name
self.damage=random.randint((damage-2),(damage+8))
self.critical_damage=critical_damage
Attacks=["Sword Slash", "Jump Jab", "Fireball", "Lightningbolt", "Weaken", "Blinding Light"]
SwordSlash=Attack("swordslash",60, 70)
JumpJab=Attack("jumpjab", 65, 75)
Fireball=Attack("fireball", 70, 80)
Lightningbolt=Attack("lightningbolt", 0, 0)
Weaken=Attack("weaken", 40, 50)
BlindingLight=Attack("blindinglight", 60, 70)
Blind=False
unconcious=False
unconciousturncount=0
weaken=0
player=Character(PlayerName, 400)
Enemy=Character("Lava Beast", 550)
HotLava=Attack("hotlava", 67, 80)
LavaRock=Attack("lavarock", 112, 0)
LavaFlood=Attack("lavaflood", 30, 0)
Bomb=Attack("bomb", 100, 120)
LavaFlooding=False
print("Battle 4! Welcome "+player.name+" to the battle! He will be fighting "+Enemy.name+"!")
print("You have "+str(player.health)+" health. The "+Enemy.name+" has "+str(Enemy.health)+" health.")
print("After months of all-nighters in the training room, you are finally sure you can beat this monster.")
Battle4=True
while Battle4:
move=input("Here are your attacks:"+str(Attacks)+" Please choose one!").lower()
if move=="swordslash" or move=="sword slash":
print("You used Sword Slash!")
hit_chance=random.randint(1, 10)
if hit_chance<4:
Enemy.health-=SwordSlash.damage
print("Your sword met its destination! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif hit_chance>7 and not unconcious:
print("The "+Enemy.name+" dodged your attack at the last second. Better luck next time!")
print("The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
Enemy.health-=SwordSlash.critical_damage
print("WOW! A critical hit! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif move=="jumpjab" or move=="jump jab":
print("You used Jump Jab!")
hit_chance=random.randint(1, 10)
if hit_chance<4:
Enemy.health-=JumpJab.damage
print("Your sword met its destination! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif hit_chance>8 and not unconcious:
print("The "+Enemy.name+" dodged your attack at the last second. Better luck next time!")
print("The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
Enemy.health-=JumpJab.critical_damage
print("WOW! A critical hit! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif move=="fireball" or move=="fire ball":
print("You used Fireball!")
hit_chance=random.randint(1, 10)
if hit_chance<6:
Enemy.health-=Fireball.damage
print("Your Fireball hit the "+Enemy.name+"! The "+Enemy.name+" health is at "+str(Enemy.health)+"!")
elif hit_chance>=6 and hit_chance<8 and not unconcious:
print("The "+Enemy.name+" was to fast!")
else:
Enemy.health-=Fireball.critical_damage
print("Critical hit! Good job! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif move=="lightningbolt" or move=="lightning bolt":
chance=random.randint(1, 10)
if unconcious==False:
print("You used Lightningbolt!")
print("Lightningbolt knocks out the opponent for 2 turns, but doesn't do any damage.")
if chance>5:
print("The lightningbolt hit! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
unconcious=True
else:
print("Oh no, the lightningbolt missed! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
print("You are not alowed to use this move if the enemy is still unconcious.")
elif move=="weaken":
print("You used Weaken!")
print("Weaken weakens the opponents attacks for this turn by 35 damage.")
chance=random.randint(1,10)
if chance<3:
print("Uh oh! The Weaken didn't work! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
weaken=35
chance=random.randint(1,10)
if chance<7:
Enemy.health-=Weaken.damage
print("The Weaken also did damage! The "+Enemy.name+"'s health is now at "+str(Enemy.health)+"!")
else:
Enemy.health-=Weaken.critical_damage
print("The Weaken also did critical damage! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
elif move=="blindinglight" or move=="blinding light":
chance=random.randint(1,10)
print("You used Blinding Light!")
print("Blinding Light makes your opponent very blind and have a 10% chance of hitting you.")
Blind=True
if chance<4:
Enemy.health-=BlindingLight.damage
print("The Blinding Light also did damage! The "+Enemy.name+"'s health is now "+str(Enemy.health)+".")
elif chance>=4 and chance<8:
Enemy.health-=BlindingLight.damage
print("The Blinding Light also did critical damage! The "+Enemy.name+"'s health is now "+str(Enemy.health)+".")
else:
print("The Blinding Light didn't do any damage!")
else:
print("That is not a valid attack choice. Skipping your turn.")
if player.health<=0:
print("You died! Restarting the game...")
start()
break
elif player.health<=0 and Enemy.health<=0:
print("Tie game! You have both died!")
start()
break
elif Enemy.health<=0:
print("You defeated the "+Enemy.name+"! Good job! Getting Battle edcjkn ready...")
print("I see you have beat the creation I had made many years ago...")
print("Nobody has EVER beat it...")
print("What was that? Who am I? Well, WHO I am isn't relevent. It's whether you think you're ready to fight me or not...")
while True:
case=input("Yes, or no.").lower()
if case=="yes":
print("...")
print("...")
print("Beat my friend Rocky and I will tell you the code.")
break
elif case=="no":
print("The voice went away.")
break
else:
print("I didn't understand you.")
Battle5()
break
if not unconcious:
choose_attack=random.randint(1,4) #Enemy Attacks start here
if not Blind:
if choose_attack==1:
print("The "+Enemy.name+" chose Hot Lava!")
chance=random.randint(1,3)
if chance==1:
player.health-=(HotLava.damage-weaken)
print("The Hot Lava landed on your foot! Your health is now at "+str(player.health)+"!")
elif chance==2:
player.health-=(HotLava.critical_damage-weaken)
print("The Hot Lava landed on your face! Your health is now at "+str(player.health)+"!")
else:
print("Good job dodging that Hot Lava! Your health is at "+str(player.health)+"!")
elif choose_attack==2:
print("The "+Enemy.name+" used Lava Rock!")
while True:
guess=input("Guess a number between 1 and 3!")
ran=random.randint(1,3)
try:
if int(guess)==ran:
print("WOW! You sure are lucky! That Lava Rock completly missed you!")
break
else:
player.health-=(LavaRock.damage-weaken)
print("Wrong. The number was "+str(ran)+"! Your health is now at "+str(player.health)+"!")
break
except:
print("That isn't a number! Try again!")
elif choose_attack==3 and not LavaFlooding:
print("The "+Enemy.name+" used Lava Flood!")
print("Lava Flood floods the whole arena with lava and does "+str(LavaFlood.damage)+" damage every round to you for the rest of the game!")
print("Note: Weaken doesn't weaken the lava!")
LavaWeaken=0
LavaFlooding=True
elif choose_attack==4:
print("The "+Enemy.name+" used bomb!")
chance=random.randint(1,10)
if chance<4:
dm=(Bomb.damage-weaken)
player.health-=dm
Enemy.health-=dm
print("The Bomb did "+str(dm)+"to both you and the "+Enemy.name+"! Your health is now "+str(player.health)+".")
print("The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif chance>=4 and chance<6:
dm=(Bomb.critical_damage-weaken)
player.health-=dm
Enemy.health-=dm
print("The Bomb did "+str(dm)+"to both you and the "+Enemy.name+"! Your health is now "+str(player.health)+".")
print("The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
else:
print("The Bomb malfunctioned!")
elif Blind:
print("The Enemy is still blind!")
if choose_attack==1:
print("The "+Enemy.name+" chose Hot Lava!")
chance=random.randint(1,10)
if chance==6:
player.health-=(HotLava.damage-weaken)
print("The Hot Lava landed on your foot! Your health is now at "+str(player.health)+"!")
else:
print("The "+Enemy.name+" is so blind, it missed!")
elif choose_attack==2:
print("The "+Enemy.name+" used Lava Rock!")
while True:
guess=input("Guess a number between 1 and 10!")
ran=random.randint(1,10)
try:
if int(guess)!=ran:
print("WOW! You sure are lucky that you didn't guess the right number! That Lava Rock completly missed you!")
break
else:
player.health-=(LavaRock.damage-weaken)
print("How did you guess the right number?! That Lava Rock hit you! Your health is now at "+str(player.health)+"!")
break
except:
print("That isn't a number! Try again!")
elif choose_attack==3 and not LavaFlooding:
print("The "+Enemy.name+" used LavaFlood while it was blind!")
print("It didn't know how hot the Lava was when it spewed out!")
print("The lava does 15 damage because the "+Enemy.name+" was blind when it spewed out the lava,")
print("So the lava is cooler than normal!")
LavaFlooding=True
LavaWeaken=15
elif choose_attack==4:
print("The "+Enemy.name+" used Bomb!")
chance=random.randint(1,10)
if chance==3:
dm=(Bomb.damage-weaken)
player.health-dm
Enemy.health-=dm
print("The Bomb did "+str(dm)+"to both you and the "+Enemy.name+"! Your health is now "+str(player.health)+".")
print("The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
else:
print("The bomb missed!")
else:
unconciousturncount+=1
if unconciousturncount==2:
unconciousturncount=0
unconcious=False
print("The "+Enemy.name+" will wake up after your next turn!")
else:
print("The "+Enemy.name+" is unconscious!")
if LavaFlooding:
player.health-=(LavaFlood.damage-LavaWeaken)
print("The lava is still there. Your health is now "+str(player.health)+"!")
weaken=0
Blind=False
if player.health<=0:
print("You died! Restarting the game...")
start()
break
elif player.health<=0 and Enemy.health<=0:
print("Tie game! You have both died!")
start()
break
elif Enemy.health<=0:
print("You defeated the "+Enemy.name+"! Good job! Getting Battle edcjkn ready...")
print("I see you have beat the creation I had made many years ago...")
print("Nobody has EVER beat it...")
print("What was that? Who am I? Well, WHO I am isn't relevent. It's whether you think you're ready to fight me or not...")
while True:
case=input("Yes, or no.").lower()
if case=="yes":
print("...")
print("...")
print("Beat my friend Rocky and I will tell you the code.")
break
elif case=="no":
print("The voice went away.")
break
else:
print("I didn't understand you.")
Battle5()
break
def Battle5():
class Character:
def __init__(self, name, health):
self.health=health
self.name=name
class Attack:
def __init__(self, name, damage, critical_damage):
self.name=name
self.damage=random.randint((damage-0), (damage+10))
self.critical_damage=critical_damage
class EnemyAttack:
def __init__(self, name, damage, critical_damage):
self.name=name
self.damage=random.randint((damage-1),(damage+9))
self.critical_damage=critical_damage
Attacks=["Sword Slash", "Jump Jab", "Fireball", "Lightningbolt", "Weaken", "Blinding Light", "Heal"]
SwordSlash=Attack("swordslash", 80, 90)
JumpJab=Attack("jumpjab", 90, 100)
Fireball=Attack("fireball", 110, 120)
Lightningbolt=Attack("lightningbolt", 0, 0)
Weaken=Attack("weaken", 60, 70)
BlindingLight=Attack("blindinglight", 70, 80)
Heal=Attack("heal", 100, 120)
HealCount=0
Blind=False
unconscious=False
unconsciousturncount=0
weaken=0
player=Character(PlayerName, 750)
Enemy=Character("Rocky", 800)
RockSlam=Attack("rockslam", 120, 140)
Earthquake=Attack("earthquake", 80, 95)
EarthquakeOn=False
RockPunch=Attack("rockpunch", 90, 0)
playerunconsciousturncount=0
player_unconscious=False
Boulder=Attack("boulder", 100, 110)
print("Battle 5! Welcome "+player.name+" to the battle! He will be fighting "+Enemy.name+"!")
print("You have "+str(player.health)+" health. The "+Enemy.name+" has "+str(Enemy.health)+" health.")
print("You trained again. You did lots of all-nighters. You are ready.")
Battle5=True
while Battle5:
if not player_unconscious:
move=input("Here are your attacks:"+str(Attacks)+" Please choose one!").lower()
if move=="swordslash" or move=="sword slash":
print("You used Sword Slash!")
hit_chance=random.randint(1, 10)
if hit_chance<4:
Enemy.health-=SwordSlash.damage
print("Your sword met its destination! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif hit_chance>7 and not unconscious:
print("The "+Enemy.name+" dodged your attack at the last second. Better luck next time!")
print("The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
Enemy.health-=SwordSlash.critical_damage
print("WOW! A critical hit! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif move=="jumpjab" or move=="jump jab":
print("You used Jump Jab!")
hit_chance=random.randint(1, 10)
if hit_chance<4:
Enemy.health-=JumpJab.damage
print("Your sword met its destination! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif hit_chance>8 and not unconscious:
print("The "+Enemy.name+" dodged your attack at the last second. Better luck next time!")
print("The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
Enemy.health-=JumpJab.critical_damage
print("WOW! A critical hit! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif move=="fireball" or move=="fire ball":
print("You used Fireball!")
hit_chance=random.randint(1, 10)
if hit_chance<6:
Enemy.health-=Fireball.damage
print("Your Fireball hit the "+Enemy.name+"! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
elif hit_chance>=6 and hit_chance<8 and not unconscious:
print("The "+Enemy.name+" was to fast!")
else:
Enemy.health-=Fireball.critical_damage
print("Critical hit! Good job! The "+Enemy.name+"'s health is now "+str(Enemy.health)+"!")
elif move=="lightningbolt" or move=="lightning bolt":
chance=random.randint(1, 10)
if unconscious==False:
print("You used Lightningbolt!")
print("Lightningbolt knocks out the opponent for 2 turns, but doesn't do any damage.")
if chance>5:
print("The lightningbolt hit! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
unconscious=True
else:
print("Oh no, the lightningbolt missed! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
print("You are not alowed to use this move if the enemy is still unconscious.")
elif move=="weaken":
print("You used Weaken!")
print("Weaken weakens the opponents attacks for this turn by 35 damage.")
chance=random.randint(1,10)
if chance<3:
print("Uh oh! The Weaken didn't work! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
else:
weaken=35
chance=random.randint(1,10)
if chance<7:
Enemy.health-=Weaken.damage
print("The Weaken also did damage! The "+Enemy.name+"'s health is now at "+str(Enemy.health)+"!")
else:
Enemy.health-=Weaken.critical_damage
print("The Weaken also did critical damage! The "+Enemy.name+"'s health is at "+str(Enemy.health)+"!")
elif move=="blindinglight" or move=="blinding light":
chance=random.randint(1,10)
print("You used Blinding Light!")
print("Blinding Light makes your opponent very blind and have a 10% chance of hitting you.")
Blind=True
if chance<4:
Enemy.health-=BlindingLight.damage
print("The Blinding Light also did damage! The "+Enemy.name+"'s health is now "+str(Enemy.health)+".")
elif chance>=4 and chance<8:
Enemy.health-=BlindingLight.damage
print("The Blinding Light also did critical damage! The "+Enemy.name+"'s health is now "+str(Enemy.health)+".")
else:
print("The Blinding Light didn't do any damage!")
elif move=="heal":
if HealCount<3:
chance=random.randint(1,10)
print("You used Heal!")
print("Note: You can only heal 3 times in each Battle regardless of wheather the heal works or not.")
HealCount+=1
if chance<5:
player.health+=Heal.damage
print("The Heal worked! Your health is now at "+str(player.health)+"!")
elif chance>=5 and chance<8:
player.health+=Heal.critical_damage
print("The Heal worked extra well! Your health is now at "+str(Enemy.health)+"!")
else:
print("The Heal didn't work at all! Your health is at "+str(Enemy.health)+"!")
else:
print("You can't use heal more than 3 times. You turn has been skipped.")
else:
print("That is not a valid attack choice. Skipping your turn.")
if player.health<=0:
print("You died! Restarting the game...")
start()
break
elif player.health<=0 and Enemy.health<=0:
print("Tie game! You have both died!")
start()
break
elif Enemy.health<=0:
print("You defeated the "+Enemy.name+"! Good job! Getting Battle 6 ready...")
print("Again, you have defeated my freind Rocky. You are ready to fight me, arn't you?")
print("Well, I-")
print("...")
print("...")
print("You are ready. The code is 666.")
Battle6()
break
if not unconscious:
choose_attack=random.randint(1,4) #Enemy Attacks start here
if not Blind:
if choose_attack==1:
print("The "+Enemy.name+" chose Rock Slam!")
chance=random.randint(1,3)
if chance==1:
player.health-=(RockSlam.damage-weaken)
print("The Rock Slam landed directly! Your health is now at "+str(player.health)+"!")
elif chance==2 and not player_unconscious:
print("The Rock Slam flew over your shoulder! Your health is at "+str(player.health)+"!")
else:
player.health-=(RockSlam.critical_damage-weaken)
print("The Rock Slam landed directly on your face! Your health is now at "+str(player.health)+"!")
elif choose_attack==2 and not EarthquakeOn:
print("The "+Enemy.name+" used Earthquake!")
print("Every round you have a chance of getting hit by falling rocks!")
EarthquakeOn=True
elif choose_attack==3 and not player_unconscious:
print("The "+Enemy.name+" used Rock Punch!")
chance=random.randint(1,10)
if chance<5:
player.health-=(RockPunch.damage-weaken)
print("The Rock Punch met its destination! Your health is now "+str(player.health)+"!")
print("You are now knocked out!")
player_unconscious=True
elif chance>=5 and chance<9:
player.health-=(RockPunch.critical_damage-weaken)
print("The Rock Punch landed on your face! Your health is now "+str(player.health)+"!")
print("You are now knocked out!")
player_unconscious=True
else:
print("The Rock Punch missed!")
else:
print("The "+Enemy.name+" chose Boulder!")
chance=random.randint(1,3)
if chance==1:
player.health-=(Boulder.damage-weaken)
print("The Boulder knocked you over! Your health is now at "+str(player.health)+"!")
elif chance==2:
print("The Boulder flew high above you! Your health is at "+str(player.health)+"!")
else:
player.health-=(Boulder.critical_damage-weaken)
print("The boulder gained speed and hit you hard! Your health is now at "+str(player.health)+"!")
elif Blind:
print("The Enemy is still blind!")
if choose_attack==1:
print("The "+Enemy.name+" chose Hot Lava!")
chance=random.randint(1,10)
if chance==2:
player.health-=(RockSlam.damage-weaken)
print("The Rock Slam landed on your foot! Your health is now at "+str(player.health)+"!")
else:
print("The Rock Slam missed!")
elif choose_attack==2 and not EarthquakeOn:
print("The "+Enemy.name+" used Earthquake!")
print("Every round you have a chance of getting hit by falling rocks!")
print("Note: The Blindness doesn't effect the Earthquake!")
EarthquakeOn=True
elif choose_attack==3:
print("The "+Enemy.name+" used Rock Punch while it was blind!")
chance=(1,10)
if chance==9:
player.health-=(RockPunch.damage-weaken)
print("The Rock Punch still hit you! Your health is now at"+str(player.health)+"!")
print("You are now unconscious!")
player_unconscious=True
else:
print("It missed!")
elif choose_attack==4:
print("The "+Enemy.name+" used Boulder!")
chance=random.randint(1,10)
if chance==9:
print("The Boulder knocked you down! Your health is now at "+str(player.health)+"!")
else:
print("The Boulder missed completely!")
else:
unconsciousturncount+=1
if unconsciousturncount==2:
unconsciousturncount=0
unconscious=False
print("The "+Enemy.name+" will wake up after your next turn!")
else:
print("The "+Enemy.name+" is unconscious!")
if player_unconscious:
playerunconsciousturncount+=1
if playerunconsciousturncount==2:
print("You have woken up!")
player_unconscious=False
playerunconsciousturncount=0
else:
print("You will wake up in one turn!")
if EarthquakeOn:
chance=random.randint(1,3)
if chance==1:
player.health-=(Earthquake.damage-weaken)
print("A medium sized rock fell on you! Your health is now at "+str(player.health)+"!")
elif chance==2:
player.health-=(Earthquake.critical_damage-weaken)
print("A large rock fell on you! Your health is now at "+str(player.health)+".")
else:
print("No rocks landed on you.")
weaken=0
Blind=False
if player.health<=0:
print("You died! Restarting the game...")
start()
break
elif player.health<=0 and Enemy.health<=0:
print("Tie game! You have both died!")
print("Try again.")
start()
break
elif Enemy.health<=0:
print("You defeated the "+Enemy.name+"! Good job! Getting Battle 6 ready...")
print("Again, you have defeated my freind Rocky. You are ready to fight me, arn't you?")
print("Well, I-")
print("...")
print("...")
print("You are ready. The code is 666.")
Battle6()
break
def Battle6():
print("Battle 6 isn't ready yet.")
def Battle666():
print("I have to set up my arena first! Shoo! Begone you foul creature!")
if BattleChoice=="1" or BattleChoice.lower()=="battle 1":
print("You chose Battle 1!")
Battle1()
elif BattleChoice=="2" or BattleChoice.lower()=="battle 2":
print("You chose Battle 2!")
Battle2()
elif BattleChoice=="3" or BattleChoice.lower()=="battle 3":
print("You chose Battle 3!")
Battle3()
elif BattleChoice=="4" or BattleChoice.lower()=="battle 4":
print("You chose Battle 4!")
Battle4()
elif BattleChoice=="5" or BattleChoice.lower()=="battle 5":
print("You chose Battle 5!")
Battle5()
elif BattleChoice=="6" or BattleChoice.lower()=="battle 6":
print("You chose Battle 6!")
Battle6()
elif BattleChoice.lower()=="local":
print("You have selected Local Battle!")
LocalBattle()
elif BattleChoice=="666":
sure=input("Are you sure you want to do this?").lower()
if sure=="yes":
print("I'll probably never see you again.")
Battle666()
elif sure=="no":
print("Didn't think so.")
start()
else:
print("Sorry, that isn't a valid choice. Please type 1, 2, 3, 4, 5, or local!.")
start()
start()
print("Yes, I know, the game isn't done yet. I'm still working on it!")
print("Thanks for playing!")
|
#!/usr/bin/python
import os
import sys
import json
import argparse
import re
from tax.receipt import Receipt
from tax.item import Item
RECEIPT_REG = r'(?P<quantity>\d+) (?P<imported>(imported )*)(?P<name>[\w ]+) at (?P<price>\d+.\d+)'
def parse_items(items, exempt_dict):
"Read input receipt and returns its corresponding object"
prog = re.compile(RECEIPT_REG)
item_lst = []
for line in items:
item = prog.match(line).groupdict()
item_lst.append(Item.from_dict(item,
exempt=True if item['name'] in exempt_dict else False))
print(item_lst)
return item_lst
def read_receipt(f_name):
"Read input receipt and returns its corresponding object"
item_lst = []
with open(f_name, 'r') as f:
for line in f:
item_lst.append(line)
return item_lst
def read_exempt(exempt_f_name='exempt.json'):
"Read Json file listing tax-exempt products, and returns its dict"
exmp_dict = {}
with open(exempt_f_name, 'r') as f:
categories = json.load(f)
for c in categories['categories']:
for p in c['products']:
exmp_dict[p] = c['name']
return exmp_dict
def main():
"This application purpose is to compute tax on a given item list"
parser = argparse.ArgumentParser()
parser.add_argument('receipt', help='Input Receipt Text file name')
parser.add_argument('--exempt', help='Tax exempt goods Json file name')
args = parser.parse_args()
exempt_dict = read_exempt()
items = read_receipt(args.receipt)
recpt = Receipt(parse_items(items, exempt_dict))
print(recpt)
if __name__ == '__main__':
sys.exit(main())
|
import random
def what_drink():
questions = {
"strong": "Do ye like yer drinks strong?",
"salty": "Do ye like it with a salty tang?",
"bitter": "Are ye a lubber who likes it bitter?",
"sweet": "Would ye like a bit of sweetness with yer poison?",
"fruity": "Are ye one for a fruity finish?",
}
answers = {
"strong":"",
"salty":"",
"bitter":"",
"sweet":"",
"fruity":"",
}
customers = {}
name = input("What is your name? ")
if name in customers:
return customers[name] #not sure why this isn't working...
print(customers)
else:
for c in questions:
n = input(questions[c] + ' Enter Y/N. ')
if n.lower() == 'y' or n.lower() == 'yes':
answers[c] = True
else:
answers[c] = False
customers[name] = answers
return answers
def mix_drink(answers):
ingredients = {
"strong": ["glug of rum", "slug of whisky", "splash of gin"],
"salty": ["olive on a stick", "salt-dusted rim", "rasher of bacon"],
"bitter": ["shake of bitters", "splash of tonic", "twist of lemon peel"],
"sweet": ["sugar cube", "spoonful of honey", "spash of cola"],
"fruity": ["slice of orange", "dash of cassis", "cherry on top"],
}
drink = []
for c in answers:
if answers[c] == True:
drink.append(random.choice(ingredients[c]))
return drink
def drink_name():
adjectives = ["noble","fiery","insane","numbing","Wondrous"]
nouns = ["witch brew","Sailor Flask","hug","hair of dog","liquid courage"]
drinkname = random.choice(adjectives)+" "+random.choice(nouns)
return drinkname
if __name__ == '__main__':
print("Your drink is {}, which contains {}".format(drink_name(), mix_drink(what_drink())))
n = input("Would you like another drink? Enter Y/N. ")
while n.lower() == 'y' or n.lower() == 'yes':
print(mix_drink(what_drink()))
n = input("Would you like another drink? Enter Y/N. ")
else:
print("Hope you enjoyed your drink!")
|
""" Uses scraped data to conjugate and declenate German verbs, nouns
and adjectives """
import dataset
from german_anki.verbix import scrape_verbix
DB = dataset.connect('sqlite:///.local/share/Anki2/addons21/german_anki/german.db')
VERBS = DB.get_table('verb')
NOUNS = DB.get_table('noun')
ADJVS = DB.get_table('adjective')
def conjugate_verb(verb):
data = VERBS.find_one(word=verb)
if data is None:
return {}
return scrape_verbix(verb)
def declenations_noun(noun):
return NOUNS.find_one(word=noun)
def declenations_adj(adj):
return ADJVS.find_one(word=adj)
|
from math import floor
def binIsPal(n):
collector = []
while(not n == 0):
collector.append(str(n % 2))
n = floor(n / 2)
return collector == collector[::-1]
def isPal(pal):
return pal == pal[::-1]
palSum = 0
for n in range(1, 1000000, 2):
if(isPal(str(n)) and binIsPal(n)):
print(n)
palSum += n
print(palSum)
|
from math import floor
from math import sqrt
def genPrimes(n):
#http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""" Input n>=6, Returns a list of primes, 2 <= p < n """
correction = (n%6>1)
n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6]
sieve = [True] * (n/3)
sieve[0] = False
for i in xrange(int(n**0.5)/3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1)
sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1)
return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]
def isPrime(n):
if n == 2 or n == 3:
return True
if n < 2 or n % 2 == 0:
return False
if n < 9:
return True
if n % 3 == 0:
return False
factor, lim = 5, int(sqrt(n))
while factor < lim:
if n % factor == 0:
return False
if n % (factor + 2) == 0:
return False
factor +=6
return True
def numDivs(x):
#http://en.wikipedia.org/wiki/Formula_for_primes
divs = 0
for s in range(1, int(sqrt(x))):
divs += floor(x / s) - floor((x - 1) / s)
return int(2 * divs)
def isPandigital(n, l = 9):
n = str(n)
return len(n) == l and not '1234567890'[:l].strip(n)
def digitsToNum(nums):
return int(''.join(map(str, nums)))
def polygonArea(pts):
s = 0
for i in range(len(pts) - 1):
s += pts[i][0] * pts[i + 1][1] - pts[i+1][0] * pts[i][1]
return abs(s) / 2
|
'''a,b,c=[int(x) for x in input("Enter three integer numbers").split()]
average = (a+b+c)/3
print("Average of the three numbers is:",average)
studentid = int(input("Enter Student Id"))
name = input("Enter Student Name")
marks = float(input("Enter marks scored"))
print("ID:",studentid,"Name:",name,"Marks:",marks)'''
import math
r=float(input("Enter the radius"))
area=math.pi*r**2
print(area)'''
Student="Ashsisj"
student="hdhd"
|
x,y='12'
y,z='32'
print(x+y+z)
'''charlist="asdfghhkjluotuwrmpbicnbc"
password="passw"
for current in range(5):
a=[i for i in charlist]
for x in range(current):
a= [y+i for i in charlist for y in a]
if password in a:
print(f'password is: {a[a.index(password)]'})
exit()'''
#hack
#import webbrowser
#webbrowser.open('https://facebook.in')
#9784075758 dhruv shukla
x,y = '12'
y,z = '34'
print(x+y+z)
class student:
def __init__(self):
print("the first constructor")
def __init__(self):
print("The second constructor")
def __init__(self):
print("The third constructor")
def __init__(self):
print("The fourth constructor")
def __init__(self):
print("The fifth constructor")
print("does not mean")
print("how many constructor are there")
print("object always calls the last constructor")
st=student
st()
#opening website with python
import webbrowser
url = 'https://www.facebook.com'
webbrowser.open(url)
|
#Write a Python program to convert a byte string to a list of integers.
x = b'ABC'
print( )
print(list(x))
#Write a Python program to list the special variables used within the language.
s_var_names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))
print()
print( '\n'.join(' '.join(s_var_names[i:i+8]) for i in range(0, len(s_var_names), 8)) )
print()
#Write a Python program to get the system time.
import time
print(time.ctime())
print()
#Write a Python program to clear the screen or terminal.
import os
import time
# for windows
# os.system('cls')
os.system("ls")
time.sleep(6)
# Ubuntu version 10.10
os.system('clear')
#Write a Python program to get the name of the host on which the routine is running.
import socket
host_name = socket.gethostname()
print()
print("Host name:",host_name)
print()
#Write a Python program to access and print a URL's content to the console.
from http.client import HTTPConnection
conn = HTTPConnection("example.com")
conn.request("GET", "/")
result = conn.getresponse()
# retrieves the entire contents.
contents = result.read()
print(contents)
|
#Write a python programe to print the calander of using month and year
import calendar
x = int(input("Enter the year : "))
y = int(input("Enter the month : "))
print(calendar.month(x,y))
#Write a Python program to print the following here document
print('''i am ashish
i am in b.tech.
3red yera student''')
#Write a Python program to calculate number of days between two dates
from datetime import date
f_d1 = date(2015,12,30)
f_d2 = date(2015,10,30)
dal = f_d1-f_d2
print("Total numbers of days :",dal.days)
#Write a Python program to get the the volume of a sphere with radius 6.
r=float(input("Enter the radious is : "))
pi=3.14
v=4.0/3.0*pi*r**3
print("volume of sphere is :",v)
#Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.
def difference(n):
if n <= 17:
return 17 - n
else:
return (n - 17) * 2
print(difference(22))
print(difference(14))
#Write a Python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum.
def sum_thrice(x, y, z):
sum = x + y + z
if x == y == z:
sum = sum * 3
return sum
print(sum_thrice(1, 2, 3))
print(sum_thrice(3, 3, 3))
|
lst=[30,40,50,60,70,80]
#rempove
lst.remove(40)
#append
lst.append(20)
print(lst)
#del
del(lst[2:])
print(lst)
#max
print(max(lst))
print(min(lst))
#insert
lst.insert(4,30)
print(lst)
#sort
lst.sort()
print(lst)
lst.sort(reverse=True)
print(lst)
|
def display(name):
def message():
return "Wel come to: "
result = message()+name
return result
print(display("Ashish"))
#Parameto to another function
'''def display(fun):
return "hello "+ fun
def name():
return "Ashish"
print(display(name))
#returning function
def display():
def message():
return "hello "
return message
fun=display()
print(fun())
#pass
def fun(lst):
for i in lst:
print(i)
fun([2,3,4,5])
fun([32,34,56,78,89])
#recursion
def factorial(n):
if n==0:
return 1
else:
return=n*factorial(n-1)'''
#cube
def cube(n):
return n**3
print(cube(5))
#lambda
f=lambda n:n**3
print(f(3))
#Even or odd
l=lambda x:'yes' if x%2==0 else 'no'
print(l(10))
#sum
def add(a,b):
return a+b
print(add(10,20))
#lambda
l=lambda a,b:a+b
print(l(20,30))
#filter
lst=[10,20,30,40,11,23,32]
result=list(filter(lambda x:x%2==0, lst))
print(result)
for i in result:print(i)
#maping
l=[2,3,4,5]
result=list(map(lambda n:n*2,l))
print(result)
#reduced function
from functools import reduce
lst=[4,5,6,20,15]
result=reduce(lambda x,y: x+y,lst)
print(result)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.