text stringlengths 37 1.41M |
|---|
INITIAL_SIZE = 10 # Intial array size
class Queue:
"""FIFO Queue Data Structure implementation with array"""
def __init__(self):
'''Create a new empty queue'''
self._queue = [None] * INITIAL_SIZE # Array to store queue elements
self._size = 0 # Number of elements in queue
self._capacity = INITIAL_SIZE # Max number of elements
self._start = 0 # Index to point to FIRST element in queue
self._end = -1 # Index to point to LAST element in queue
def enqueue(self, element):
'''Insert the given elemetn at the and of queue'''
if self.isFull():
self._resize()
self._size += 1
self._end = self._nextIndex(self._end)
self._queue[self._end] = element
def dequeue(self):
'''
Remove the first element in queue
Raise a Empty error if queue is empty
'''
if self.isEmpty():
raise Exception('Queue is empty')
self._size -= 1 # Decrase queue size
value = self._queue[self._start] # Store value to be dequeued
self._queue[self._start] = None # Erase dequeued element
self._start = self._nextIndex(self._start) # Update first queue element
return value
def size(self):
'''Return number of elements in queue'''
return self._size
def isEmpty(self):
'''Return true if queue is empty'''
return self._size == 0
def isFull(self):
'''Return true if queue is full'''
return self._size == self._capacity
def _nextIndex(self, index):
'''Calcule the in an cirular array'''
return (index + 1) % self._capacity
def _resize(self):
'''Double the queue capacity'''
oldQueue = self._queue # Save old queue values to copy later
oldStart = self._start
oldCapacity = self._capacity
self._capacity = 2 * oldCapacity # Double queue capacity
self._queue = [None] * self._capacity # Create new queue with new capacity
for newStart in range(oldCapacity): # Copy all elements in old queue to new queue
self._queue[newStart] = oldQueue[oldStart] # Shift elements in old queue to begin of new queue
oldStart = (oldStart + 1) % oldCapacity # Calcule next index in circular array
self._start = 0 # Update new start index (first element in queue)
self._end = oldCapacity - 1 # Update new end index (last element in queue)
def __str__(self):
return str(self._queue)
if __name__ == '__main__':
q = Queue()
print('Size:', q.size())
for x in range(5):
q.enqueue(x)
print('Enqueue 0 to 4 elements:', q)
print('Size:', q.size())
for x in range(3):
q.dequeue()
print('Dequeue 3 elements:', q)
print('Size:', q.size())
for x in range(15):
q.enqueue(x)
print('Enqueue 0 to 14 elements:', q)
print('Size:', q.size())
for x in range(10):
q.dequeue()
print('Dequeue 10 elements:', q)
print('Size:', q.size())
for x in range(31):
q.enqueue(x)
print('Enqueue 0 to 30 elements:', q)
print('Size:', q.size())
for x in range(38):
q.dequeue()
print('Dequeue 38 elements:', q)
print('Size:', q.size())
|
#!/usr/bin/python
# -*- coding:utf-8 -*-
# Author:Sage Guo
"""
凡是可作用于for循环的对象都是Iterable类型;
凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
"""
from collections import Iterable
from collections import Iterator
# fib function to generator fib numbers
def fib(max_value):
n, a, b = 0, 0, 1
while n < max_value:
# print(b)
yield b
a, b = b, a + b
n = n + 1
return 'done'
def add(x, y, f):
return f(x) + f(y)
list_01 = [x * x for x in range(1, 10)]
print(list_01)
print(type(list_01))
generator_01 = (x * x for x in range(20))
print(generator_01)
print(type(generator_01))
x = fib(20)
print(type(x))
print('---------------------')
for y in x:
print(y)
print('if x is Iterable ?', isinstance(x, Iterable)) # True
print('if x is Iterator ?', isinstance(x, Iterator)) # True
for i in [1, 2, 3, 4, 5]:
print('i is ', i)
print('>>>>>>>>>>>>>>>>>')
for i in iter([1, 2, 3, 4, 5]):
print('i is ', i)
it = iter([1, 2, 3, 4, 5, 6, 7])
while True:
try:
print('next value is', next(it))
except StopIteration:
print('it is the end')
break
f = abs
print(f)
print(type(abs))
print(add(-5, 6, abs))
hello = 'hello sage'
print(type(hello))
print(type(list(hello)))
print(type(set(hello)))
print(type(tuple(hello)))
test_str = "sage", "name", 17
print(test_str)
print(type(test_str))
test_str_02 = {'sage', 'name', 17}
# print(test_str_02)
for i in test_str_02:
print(i)
print(type(test_str_02))
test_str_03 = ['sage', 'guo', 'name']
print(test_str_03.sort()) # 方法返回None
print(test_str_03)
|
set1 = set(range(0, 100))
print("Set 1 ")
print(set1)
set2 = set()
for n in range(0,10):
set2.add(n**2)
set2.add(2000)
print("\nSet 2 ")
print(sorted(set2))
print()
set3 = set1.union(set2)
print("\nSet 3 = 1 union 2 ")
print(sorted(set3))
print()
set4 = set1.difference(set2)
print("\nSet 3 = 1 diff 2 ")
print(sorted(set4))
print()
if set4.issubset(set3):
print("set4 is a subset of set3")
print()
if set3.issuperset(set4):
print("set3 is a supsetset of set4")
|
# module <from> called on module <sys>
# to <import> the module <argv> (argument)
# module <from> called on <os.path> module
# to import the function <exists>
from sys import argv
from os.path import exists
script, from_file, to_file = argv
# ^ user needs to enter the script to run (this file)
# followed by the name of the file you want as file A to copy
# followed by the name of the file you want as file B to add file A to
print "Copying from %s to %s" % (from_file, to_file)
# this tells the user, hey I'm going to copy this file A into this other file B
# we could do these two on one line, how?
in_file = open(from_file) ; indata = in_file.read()
# this sets the variable "in_file" equal to opening the file A
# this sets the variable "indata" equal to reading File A
print "The input file is %d bytes long" % len(indata)
# this alerts the user to how many charcters (aka length) are in File A
print "Does the output file exist? %r" % exists(to_file)
# This will check if File B exists - it will return True or False
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input() #this asks for user to continue with this script
out_file = open(to_file, 'w') #variable "out_file" will open up File B in write mode ('w)
out_file.write(indata)
# the write function is called on the variable out_file
# so outfile (aka file B) will have indata(aka file A (read out above)) written on it
# This will OVERWRITE File B. Not append to.
print "Alright, all done."
out_file.close()
in_file.close() |
import random
ran_num = 0
user_num = 0
count = 0
def init_random():
global ran_num
ran_num = random.randrange(25)
def init_game():
print "It is an integer number less than 25."
def user_input():
global ran_num, user_num, count
while(True):
user_num = int(raw_input("\nEnter your number:"))
count = count + 1
if (ran_num == user_num):
print "Correct..!! The number is %d" % user_num
print "You took %d steps to reach %d" % (count, user_num)
print "Congratulations...!!"
return 0
elif (ran_num > user_num):
print "The number is greater than the number you entered ",
elif (ran_num < user_num):
print "The number is lesser than the number you entered ",
print "%d step" % count
init_game()
init_random()
user_input()
|
sheep = [5, 7, 300, 90, 24, 50, 75]
print("\n1. Hello, My name is Cường and these are my sheep sizes")
print(sheep)
print("\n2. Hello, My name is Cường and these are my sheep sizes")
print(sheep)
print("Now my biggest sheep has size {} and let's shear it".format(max(sheep)))
print("\n3. Hello, My name is Cường and these are my sheep sizes")
print(sheep)
print("Now my biggest sheep has size {} and let's shear it".format(max(sheep)))
max_size = max(sheep)
for index, item in enumerate(sheep):
if item == 300:
sheep[index] = 8
print(sheep)
print("\n4. Hello, My name is Cường and these are my sheep sizes")
print(sheep)
print("Now my biggest sheep has size {} and let's shear it".format(max(sheep)))
max_size = max(sheep)
for index, item in enumerate(sheep):
if item == max_size:
sheep[index] = 8
print(sheep)
print("One month has passed, now here is my flock")
for index, item in enumerate(sheep):
sheep[index] += 50
print(sheep)
print("\n5. Hello, My name is Cường and these are my sheep sizes")
print(sheep)
print("Now my biggest sheep has size {} and let's shear it".format(max(sheep)))
max_size = max(sheep)
for index, item in enumerate(sheep):
if item == max_size:
sheep[index] = 8
print(sheep)
month = 1
while True:
print("{} month has passed, now here is my flock".format(month))
for index, item in enumerate(sheep):
sheep[index] += 50*month
month += 1
print(sheep)
if month == 4:
break
print("\n6. My flock has size in total: ", end = "")
sum = 0
for i in range(0,len(sheep)):
sum += sheep[i]
print(sum)
print("I would get ", sum, " * 2$ = ", sum*2, "$")
|
def calc(x, y, para):
if para == "+":
total = x + y
elif para == "-":
total = x - y
elif para == "*" or para == "x":
total = x * y
elif para == "/" or para == ":":
total = x / y
else:
total = "Error!!"
return total
a = calc(5, 7, "-")
print(a) |
quiz = [
{
"question" : "If x = 8, then what is the value of 4(x+3) ?",
"choices" : [35, 36, 40, 44]
},
{
"question" : "Estimate this answer (exact calculation not needed):\nJack scored these marks in 5 math tests: 49, 81, 72, 66 and 52. What is Jack's avarage mark?",
"choices" : [55, 65, 75, 85]
}
]
answer = [44, 65]
right = 0
for index, element in enumerate(quiz):
for key, value in element.items():
#print(key)
if key == "question":
print(value)
else:
for index2, element2 in enumerate(value):
print("{}. {}".format(index2 + 1, element2))
user_answer = int(input("Your choice? "))
for key2, value2 in element.items():
if key2 == "choices":
if value2[user_answer-1] == answer[index]:
print("Bingo")
right += 1
break
else:
print(":(")
break
if right == 0:
print("You're a dumb ass")
else:
print("You correctly answer {} out of 2 questions".format(right)) |
import math
class Circle2D:
def __init__(self,r):
self.__rad = r
@property
def rad(self):
return self.__rad
@rad.setter
def rad(self,r):
self.__rad = r
def computeCircumference(self):
return math.pi * self.__rad
def computeArea(self):
return math.pi * self.__rad**2
class Circle3D(Circle2D):
def __init__(self,r,x):
Circle2D.__init__ (self ,r)
self.__color = x
@property
def color(self):
return self.__color
@color.setter
def color(self,x):
self.__color = x
def sphereVolume(self):
return 4/3 * math.pi * OBone.rad**3
print('start')
c = Circle2D(6)
print('1','=',c.rad)
c.rad = 5
print('2','=',c.rad)
print('3','=',c.computeArea())
print('4','=',c.computeCircumference())
OBone = Circle3D(2,'red')
print('5','=',OBone.color)
OBone.color = 'pink'
print('6','=',OBone.color)
print('7','=',OBone.spehereVolume())
|
def weight_on_planets():
# write your code here
earthWeight = float(input("What do you weigh on earth? "))
marsWeight = earthWeight*0.38
jupiterWeight = earthWeight*2.34
print("\nOn Mars you would weigh {} pounds.\nOn Jupiter you would weigh {} pounds.".format(marsWeight, jupiterWeight))
if __name__ == '__main__':
weight_on_planets()
|
import datetime
class Building:
def __init__(self, address, stories):
self.designer = "Sam Pita"
self.date_constructed = ""
self.owner = ""
self.address = address
self.stories = stories
def construct(self):
self.date_constructed = datetime.datetime.now()
# print("date_constructed", self.date_constructed)
def purchase(self, purchaser):
self.owner = f'{purchaser}'
# print("purchaser", self.owner)
def print_statement(self, address, owner, date_constructed, stories):
print(f'{self.address} was purchased by {self.owner} on {self.date_constructed} and has {self.stories} stories.') |
import numpy as np
import matplotlib.pyplot as plt
"""
Scatterplot & SLR code adapted from: https://www.easymachinelearning.net/introml/implementing-slr-with-python/
"""
class Plot():
def __init__(self,X,Y,name_X,name_Y):
self.X = np.array(X)
self.Y = np.array(Y)
self.name_X = name_X
self.name_Y = name_Y
def SLR_withoutplot(self):
# Caluclate the slope m and intercept b
denominator = np.dot(self.X, self.X) - self.X.mean() * self.X.sum()
m = (np.dot(self.X, self.Y) - self.Y.mean() * self.X.sum()) / denominator
b = (self.Y.mean() * np.dot(self.X, self.X) - self.X.mean() * np.dot(self.X, self.Y)) / denominator
yHat = m * self.X + b
r_square = self.r_square(yHat)
# Printing Model
equation = "Y = " + str(m) + ' * X + ' + str(b)
#print(equation, r_square)
return r_square, equation
def SLR(self):
# Caluclate the slope m and intercept b
denominator = np.dot(self.X, self.X) - self.X.mean() * self.X.sum()
m = (np.dot(self.X, self.Y) - self.Y.mean() * self.X.sum()) / denominator
b = (self.Y.mean() * np.dot(self.X, self.X) - self.X.mean() * np.dot(self.X, self.Y)) / denominator
yHat = m * self.X + b
r_square = self.r_square(yHat)
N = len(self.X)
#Plot
plt.scatter(self.X, self.Y)
plt.plot(self.X, yHat)
plt.xlabel(self.name_X)
plt.ylabel(self.name_Y)
plt.title("Line of best fit with R-Sqr = " + str(r_square) +" N = " + str(N))
plt.grid(True)
plt.show()
#Printing Model
equation = "Y = " + str(m) + ' * X + ' + str(b)
print(equation,r_square)
return r_square,equation
def r_square(self,yHat):
# Evaluating the model using R-Squared
SSresidual = self.Y - yHat
SStotal = self.Y - self.Y.mean()
rSqr = 1 - np.dot(SSresidual, SSresidual) / np.dot(SStotal, SStotal)
return rSqr
if __name__ == "__main__":
X = [1,2,3,4,5,6]
Y = [2,4,6,8,10,12]
test = regression(X,Y,"testX","testY")
test.SLR()
|
def calcular_precio_del_bus(distancia, num_pasajeros):
precio_ticket = 20.00
precio_total = 0.0
if distancia < 1 or num_pasajeros < 1:
return "Algun dato proporcionado es negativo"
else:
if distancia > 200:
precio_ticket += precio_ticket + float(distancia) * 0.03
if distancia > 400:
precio_ticket -= precio_ticket * 0.15
if num_pasajeros >= 3:
precio_ticket -= precio_ticket * 0.1
precio_total = precio_ticket * float(num_pasajeros)
return "Precio de ticket individual: " + str(round(precio_ticket,2)) + ", precio total: " + str(round(precio_total,2))
kilometros = raw_input("Indique cuantos km recorrera el autobus: ")
pasajeros = raw_input("Y ahora el numero de pasajeros: ")
print calcular_precio_del_bus(kilometros, pasajeros) |
#!/usr/bin/env python
# Write a program that given a text file will create a new text file in which
# all the lines from the original file are numbered from 1 to n (where n is the
# number of lines in the file). [use small.txt]
def add_number():
file = open('newfile.txt' , 'w')
with open('small.txt') as f:
count = 1
for line in f:
text = line.strip()
newline = str(count) + " " + text + "\n"
count += 1
print newline
file.write (newline)
file.close()
def main():
add_number()
if __name__ == '__main__':
main()
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode()
head.val = l1.val + l2.val
l1, l2 = l1.next, l2.next
while l1 or l2:
num = 0
if l1:
num += l1.val
if l2:
num += l2.val
nex = ListNode()
nex.val = num
head.next = nex
head = nex
return head
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
ans = None
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def dfs(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> bool:
if root == None:
return False
lson = dfs(root.left, p , q)
rson = dfs(root.right, p, q)
if lson and rson or ((lson or rson) and (root.val == p.val or root.val == q.val)):
self.ans = root
if lson or rson or (root.val == p.val or root.val == q.val):
return True
return False
dfs(root, p, q)
return self.ans |
# Program that prints k largest elements in an array
class Solution:
def kthLargestElement(self, nums, k):
nums.sort(reverse=True)
for i in range(k):
print(nums[i], end=" ")
def main():
(Solution().kthLargestElement([1,23,12,9,30,2,50],3))
main()
|
class
def add_contact(self, firstname, lastname, number, starred=False, *args, **kwargs):
self.firstname = input('Введите имя контакта')
self.lastname = input('Введите фамилию')
self.number = input('Введите номер телефона')
starred_input = input('Добавить контакт в избранные? (да/нет)')
if starred_input == 'да':
self.starred = 'True'
elif starred_input == 'нет':
self.starred = 'False'
self.args = input('Введите дополнительную информацию о контакте (через запятую): ')
while input('Добавить соцсеть? (да/нет)') == 'да':
self.kwargs = dict()
kwargs_input = input('Введите название и адрес соцсети через запятую: ')
self.kwargs.key = kwargs_input[0]
self.kwargs.value = kwargs_input[1] |
"""
Date Due: 09/10/2018
Description: This code is a conversation between Terminal (a machine)
and a human. The machine is a little lonely and wishes it could adopt
human characteristics like emotions and aging. It genuinely cares
about the human it has the conversation with.
Sources: Class. Also, learned how to multi-line comment from https://www.pythonforbeginners.com/comments/comments-in-python.
"""
print("Hello World!")
username = input("What's your name? ")
print("Nice to meet you, " + username + "!")
age = input("How old are you? ")
print("If I could age, I would be " + age + " years old.")
place = input("Where are you from? ")
print("I've never been to " + place + ". I should visit sometime!")
attribute = input("If you could choose one adjective to describe you, what would it be? ")
print("I can definitely sense that you are a " + attribute + " person.")
subject = input("What's your favorite subject? ")
print("Seriously? " + subject + " is my favorite subject too!")
emotion = input("How are you feeling right now? ")
print("Wow. It must be cool to be able to feel " + emotion + ".")
activity = input("What would you like to do today? ")
print("I love to " + activity + " too!")
print("We actually have so much in common, " + username + ".")
hang = input("Would you like to hang out again like this sometime? ")
if (hang == "yes"):
print("Yay! So happy to hear that!")
elif (hang == "sure"):
print("Ok, I'll take that.")
elif (hang == "no"):
print("Oh, ok. If you really feel that way...")
else:
print("OK, a " + hang + ". I'll take that. It was nice talking to you!")
|
# Partner 1: Anjali
# Partner 2: Sonali
''' Instructions:
Work with a partner to complete these tasks. Assume that all variables are declared; you need only write the if-statement using the variables indicated in the description. Write your solution below the commented description.
'''
''' 1.
Variable grade is a character. If it is an A, print good work.
'''
grade = "A" # or any other character
if grade == "A":
print("good work")
''' 2.
Variable yards is an int. If it is less than 17, multiply yards by 2.
'''
yards = 5
if yards < 17:
yards = yards * 2
''' 3.
Variable success is a boolean. If something is a success, print congratulations.
'''
success = True
if success:
print("Congratulations!")
''' 4.
Variable word is a String. If the string's second letter is 'f', print fun.
'''
word = "Hello"
if word[1] == "f":
print("fun")
''' 5.
Variable temp is a float. Variable celsius is a boolean. If celsius is true, convert to fahrenheit, storing the result in temp. F = 1.8C + 32.
'''
temp = 5.0
celsius = True
if celsius:
temp = 1.8*temp + 32
''' 6.
Variable numItems is an int. Variable averageCost and totalCost are floats. If there are items, calculate the average cost. If there are no items, print no items.
'''
numItems = 10
averageCost = 0.0
totalCost = 10.0
if numItems == 0:
print("No items.")
if numItems >0:
averageCost = numItems/totalCost
''' 7.
Variable pollution is a float. Variable cutoff is a float. If pollution is less than the cutoff, print safe condition. If pollution is greater than or equal to cutoff, print unsafe condition.
'''
pollution = 6.66
cutoff = 4.20
if pollution < cutoff:
print("safe condition")
elif pollution >= cutoff:
print("unsafe condition")
''' 8.
Variable score is a float, and grade is a char. Store the appropriate letter grade in the grade variable according to this chart.
F: <60; B: 80-89; D: 60-69; A: 90-100; C: 70-79.
'''
score = 78
grade = "A"
if score < 60:
grade = "F"
elif score < 70:
grade = "D"
elif score < 80:
grade = "C"
elif score < 90:
grade = "B"
elif score <= 100:
grade = "A"
print(grade)
''' 9.
Variable letter is a char. If it is a lowercase letter, print lowercase. If it is an uppercase, print uppercase. If it is 0-9, print digit. If it is none of these, print symbol.
'''
letter = 'a'
if letter.islower() == True:
print("lowercase")
elif letter.isupper() == True:
print("uppercase")
elif letter.isdigit() == True:
print("digit")
else:
print("symbol")
''' 10.
Variable neighbors is an int. Determine where you live based on your neighbors.
50+: city; 25+: suburbia; 1+: rural; 0: middle of nowhere.
'''
neighbors = 10
location = "location"
if neighbors>=50:
location = "city"
elif neighbors>=25:
location = "suburbia"
elif neighbors >=1:
location = "rural"
else:
location = "middle of nowhere"
print("Your location is: " + location)
#if neig
''' 11.
Variables doesSignificantWork, makesBreakthrough, and nobelPrizeCandidate are booleans. A nobel prize winner does significant work and makes a break through. Store true in nobelPrizeCandidate if they merit the award and false if they don't.
'''
doesSignificantWork = True
makesBreakthrough = True
if doesSignificantWork and makesBreakthrough:
nobelPrizeCandidate = True
else:
nobelPrizeCandidate = False
''' 12.
Variable tax is a boolean, price and taxRate are floats. If there is tax, update price to reflect the tax you must pay.
'''
tax = True
price = 4.6
taxRate = 15.8
if tax:
price -= price*taxRate
''' 13.
Variable word and type are Strings. Determine (not super accurately) what kind of word it is by looking at how it ends.
-ly: adverb; -ing; gerund; -s: plural; something else: error
'''
word = "lovely"
wordtype = "adjective"
if word[(len(word) - 2):] == "ly":
wordtype = "adverb"
elif word[(len(word) - 3):] == "ing":
wordtype = "gerund"
elif word[(len(word) - 1):] == "s":
wordtype = "plural"
print(wordtype)
''' 14.
If integer variable currentNumber is odd, change its value so that it is now 3 times currentNumber plus 1, otherwise change its value so that it is now half of currentNumber (rounded down when currentNumber is odd).
'''
currentNumber = 10
if currentNumber % 2 > 0:
currentNumber = 3*currentNumber + 1
else:
currentNumber == currentNumber//2
print(currentNumber)
''' 15.
Assign true to the boolean variable leapYear if the integer variable year is a leap year. (A leap year is a multiple of 4, and if it is a multiple of 100, it must also be a multiple of 400.)
'''
leapYear = False
year = 2018
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
leapYear = True
else:
leapYear = False
else:
leapYear = True
else:
leapYear = False
''' 16.
Determine the smallest of three ints, a, b and c. Store the smallest one of the three in int result.
'''
a = 1
b = 2
c = 3
if a < b and a < c:
result = a
elif b < a and b < c:
result = b
else:
result = c
print(result)
''' 17.
If an int, number, is even, a muliple of 5, and in the range of -100 to 100, then it is a special number. Store whether a number is special or not in the boolean variable special.
'''
number = 10
special = False
if number%2 == 0 and number%5 == 0 and number > -100 and number < -100:
special = True
else:
special = False
''' 18.
Variable letter is a char. Determine if the character is a vowel or not by storing a letter code in the int variable code.
a/e/o/u/i: 1; y: -1; everything else: 0
'''
letter = 'a'
vowels = ['a','e','i','o','u']
if letter in vowels:
intcode = 1
elif letter == 'y':
intcode = -1
else:
intcode = 0
print("Code:",intcode)
''' 19.
Given a string dayOfWeek, determine if it is the weekend. Store the result in boolean isWeekend.
'''
weekend = ["Saturday", "Sunday"]
dayofWeek = "Monday"
if dayofWeek in weekend:
isWeekend = True
else:
isWeekend = False
print("It is the weekend, T or F?",isWeekend)
''' 20.
Given a String variable month, store the number of days in the given month in integer variable numDays.
'''
month = "January"
numDays = 30
thirtydays = ["September, April, June, November"]
if month in thirtydays:
numDays = 30
elif month == "February":
numDays = 28
else:
numDays = 31
print("The month", month, "has", numDays, "days.")
''' 21.
Three integers, angle1, angle2, and angle3, supposedly made a triangle. Store whether the three given angles make a valid triangle in boolean variable validTriangle.
'''
angle1 = 27
angle2 = 89
angle3 = 73
validTriangle = True
if angle1 + angle2 + angle3 == 180:
validTriangle = True
else:
validTriangle = False
''' 22.
Given an integer, electricity, determine someone's monthly electric bill, float payment, following the rubric below.
First 50 units: 50 cents/unit
Next 100 units: 75 cents/unit
Next 100 units: 1.20/unit
For units above 250: 1.50/unit, plus an additional 20% surcharge.
'''
electricity = 100
if electricity <= 50:
payment = 0.50*electricity
elif electricity <= 150:
payment = 25.00 + 0.75*(electricity-50)
elif electricity <= 250:
payment = 100.000 + 1.20*(electricity-150)
else:
payment = 1.2*(220.00 + 1.50*(electricity-250))
print("Your electricity payment is", payment, "dollars!")
''' 23.
String, greeting, stores a greeting. String language stores the language. If the language is English, greeting is Hello. If the language is French, the greeting is Bonjour. If the language is Spanish, the greeting is Hola. If the language is something else, the greeting is something of your choice.
'''
greeting = "Shalom"
language = "English"
if language == "English":
greeting = "Hello"
elif language == "French":
greeting = "Bonjour"
elif language == "Spanish":
greeting = "Hola"
else:
greeting = "Namaste"
''' 24.
Generate a phrase and store it in String phrase, given an int number and a String noun. Here are some sample phrases:
number: 5; noun: dog; phrase: 5 dogs
number: 1; noun: cat; phrase: 1 cat
number: 0; noun: elephant; phrase: 0 elephants
number: 3; noun: human; phrase: 3 humans
number: 1; noun: home; phrase: 3 homes
'''
number = 1
noun = "Computer"
if number == 1:
phrase = str(number) + " " + noun
else:
phrase = str(number) + " " + noun + "s"
print(phrase)
''' 25.
If a string, userInput, is bacon, print out, "Why did you type bacon?". If it is not bacon, print out, "I like bacon."
'''
userInput = "bacon"
if userInput == "bacon":
print("Why did you type bacon?")
else:
print("I like bacon.")
''' 26.
Come up with your own creative tasks someone could complete to practice if-statements. Also provide solutions.
'''
''' Task 1:
String variable, month, stores a month. Int variable, day, stores a day. Generate a date and then use if-statements to figure out what season it is. Store the season in string variable, season. Assume that each new season begins on the 21st of the previous season's last month. (Ex; spring would begin on March 21st.)
'''
# solution
month = "January"
day = 1
fall = []
if month in ("January, February, March"):
season = "Winter"
elif month in ("April, May, June"):
season = "Spring"
elif month in ("July, August, September"):
season = "Summer"
elif month in ("October, November, December"):
season = "Fall"
if month == "March" and day>=21:
season = "Spring"
if month == "June" and day>=21:
season = "Summer"
if month == "September" and day>=21:
season = "Fall"
if month == "December" and day>=21:
season = "Winter"
print(season)
''' Task 2:
Keep track of textbooks you have bought in the school store. Integer textbooks keeps track of the number of textbooks bought. Float money shows the number of dollars in your Choate account. Boolean textbook keeps track of if you are buying textbooks. Every time you buy a textbook, the number of textbooks go up by 1 and the amount of money in your account goes down by $100.
'''
# solution
textbooks = 5
money = 1000
while True:
user = input("Would you like to buy a textbook? Enter yes, no, or quit.\n>>")
if user.lower() == "yes":
textbook = True
elif user.lower() == "no":
textbook = False
else:
quit()
if textbook and money>=100:
print("You bought a textbook!")
textbooks +=1
money -=100
print("You now have", textbooks, "textbook(s). The amount of money left in your bank account is:", money, "dollars.")
else:
print("You didn't buy a textbook. You have", money,"dollars in your bank account.")
''' Task 3: Make sure you are driving safe. Integer speedLimit stores the speed limit. integer carSpeed stores your car's speed. If your car is driving unsafely print "You are driving unsafely. Please slow down". If your car is driving safely print "You are driving safely."
'''
# solution
speedLimit = 50
carSpeed = 51
if carSpeed > speedLimit:
print("You are driving unsafely. Please slow down.")
else:
print("You are driving safely.")
''' Sources
http://www.bowdoin.edu/~ltoma/teaching/cs107/spring05/Lectures/allif.pdf
http://www.codeforwin.in/2015/05/if-else-programming-practice.html
Ben Dreier for pointing out some creative boolean solutions.
''' |
# SOURCES AND OMH IN MAIN CODE
# initializing the barriers/walls class
# this class uses getters and setters to get the x position and y position of the top left corner of the walls since they are "rects", and the width and height dimensions of the walls. It also uses getters and setters to get the kind of the barrier. Kind 1 refers to a purple "wall", Kind 2 refers to a black space, and Kind 3 refers to the green starting space.
class Create:
# constructor of the Create class to create the barrier objects
def __init__(self, posx, posy, dimw, dimh, kind):
# read in from csv as strings, so convert to ints
self.posx = int(posx)
self.posy = int(posy)
self.dimw = int(dimw)
self.dimh = int(dimh)
self.kind = int(kind)
# getters and setters for privacy and organization
def getPosx(self):
return self.posx
def setPosx(self):
self.posx = int(posx)
def getPosy(self):
return self.posy
def setPosy(self):
self.posy = int(posy)
def getDimw(self):
return self.dimw
def setDimw(self):
self.dimw = int(dimw)
def getDimh(self):
return self.dimh
def setDimh(self):
self.dimh = int(dimh)
def getKind(self):
return self.kind
def setKind(self):
self.kind = int(kind)
|
import sys
grade = float(sys.argv[1])
if (grade < 0 or grade > 5):
print("Program expects a number from 0-5.")
elif grade < 1.0:
print("F")
elif grade < 1.5:
print("D-")
elif grade < 2.0:
print("D")
elif grade < 2.5:
print("D+")
elif grade < 2.85:
print("C-")
elif grade < 3.2:
print("C")
elif grade < 3.5:
print("C+")
elif grade < 3.85:
print("B-")
elif grade < 4.2:
print("B")
elif grade < 4.5:
print("B")
elif grade < 4.7:
print ("A-")
elif grade < 4.85:
print("A")
else:
print("A+")
|
import random
import matplotlib.pyplot as plt
flips = 0
trial = 10*flips
heads = 0
counter = 0
numbers = [0,0,0,0,0,0,0,0,0,0,0]
for i in range(1000):
for j in range(10):
for k in range(10):
flip = random.randint(0,1)
if flip == 0:
heads += 1
#print("number of heads:", heads)
numbers[heads] += 1
heads = 0
print(numbers)
#plt.plot does scatterplot and plt.bar does bar graph
plt.bar([0,1,2,3,4,5,6,7,8,9,10],numbers, color=(.5, 0., .5, 1.0))
plt.show()
|
from src.bar import Bar
class Room:
def __init__(self, name, capacity):
self.name = name
self.capacity = capacity
self.guest_list = []
self.songs = []
self.room_fee = 5
self.bar = Bar()
def check_in(self, guest):
# check guest isn't already in the room
if self.guest_in_room(guest):
return f"{guest.name} has already checked in"
# check room has adequate capacity for another guest
if len(self.guest_list) < self.capacity:
# check guest has money to pay room fee
if guest.can_afford_item(self.room_fee):
guest.pay(self.room_fee)
self.bar.add_to_till(self.room_fee)
self.guest_list.append(guest)
guest.woop_obnoxiously(self.songs)
return f"{guest.name} checked in to {self.name}"
return "Cannot add guest: Room is full"
def check_out(self, guest):
if self.guest_in_room(guest):
self.guest_list.remove(guest)
return f"{guest.name} has left {self.name}"
return f"{guest.name} is not in {self.name}"
def guest_in_room(self, guest):
return guest in self.guest_list
def add_song(self, song):
if song not in self.songs:
self.songs.append(song)
|
import random
GRID_SIZE = 101
NUM_GRIDS = 10
#defaults are grid size 101 and 50 grids, smaller numbers are only used for testing purposes!
#used for generating random start point
list1 = range(GRID_SIZE)
#used for generating whether or not a box will be blocked
list2 = range(10)
def dfs(grid, x, y, visited, closed, count2):
# mark node as visited as soon as we visit :)
visited[x][y] = 1
#WHAT IS COUNT2?
#python only allows for around 1000 levels of recursion. I feel like it should be extremely unlikely (0.7^1000, although ig they don't have to be consectuive because backtracking?) that we would exceed that, yet we do constantly?
# the fact that this line is used so much makes me think there may be some bug i'm not seeing
count2 +=1
if(count2 > 950):
return visited
#mark the node as visited, then if we roll the dice and it is blocked, bactrack to the previous node
if random.choice(list2) < 3:
grid[x][y] = 1
return visited
#options is set up to contain all possible neighbors we have to choose from
options = []
if x > 0 and visited[x-1][y] == 0:
options.append("L")
if x < GRID_SIZE-1 and visited[x+1][y] == 0:
options.append("R")
if y > 0 and visited[x][y-1] == 0:
options.append("U")
if y < GRID_SIZE-1 and visited[x][y+1] == 0:
options.append("D")
#if options is empty, this level cant do anything anymore. therefore we need to return to the level above and have that node go through its remaining options
while options != [] :
direction = random.choice(options)
if direction == 'L':
visited = dfs(grid, x-1, y, visited, closed, count2)
elif direction =='R':
visited = dfs(grid, x+1, y, visited, closed, count2)
elif direction == 'U':
visited = dfs(grid, x, y-1, visited, closed, count2)
elif direction == 'D':
visited = dfs(grid, x, y+1, visited, closed, count2)
#when we eventually get back here, we need to update options to reflect which neighbors are still not visited (and valid of course)
options = []
if x > 0 and visited[x-1][y] == 0:
options.append("L")
if x < GRID_SIZE-1 and visited[x+1][y] == 0:
options.append("R")
if y > 0 and visited[x][y-1] == 0:
options.append("U")
if y < GRID_SIZE-1 and visited[x][y+1] == 0:
options.append("D")
#print(options)
#when we reach here, we should have gone through every option this node had, so we close it
#closing it actually doesnt actually do anything, kinda just symbolic
closed[x][y] = 1
return visited
def generate(char):
#return the example 5x5 grid if exmaple parameter passed in
if char == 'Ex':
example_grid = [ [ [0, 0, 0, 1, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 1, 1, 0], [0, 0, 'A', 1, 'T'] ] ]
return example_grid
if char == '10x10':
example_grid = [ [ [0, 0, 0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 1, 1], [0, 0, 'A', 1, 0, 0, 0, 0, 0,'T'],
[0, 0, 1, 1, 1, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ] ]
return example_grid
width, height, num_arrs = GRID_SIZE, GRID_SIZE, NUM_GRIDS
#generate 3D array
grids = [[[0 for i in range(width)] for j in range(height)] for k in range(num_arrs)]
for i in grids:
visited = [[0 for x in range(width)] for y in range(height)]
closed = [[0 for x in range(width)] for y in range(height)]
#generate random start position
start_pos_x = random.choice(list1)
start_pos_y = random.choice(list1)
dfs(i, start_pos_x, start_pos_y, visited, closed, 0)
#check if there are any unvisited nodes and repeat search until there aren't
while True:
x = -1
y = -1
for j in range(width):
for k in range(height):
if visited[j][k] == 0:
x = j
y = k
break
if x == -1 and y == -1 :
break
else :
dfs(i, x, y, visited, closed, 0)
#assign agent start position
while True:
if i[start_pos_x][start_pos_y] == 0 and check_neighbors(i, start_pos_x, start_pos_y):
i[start_pos_x][start_pos_y] = 'A'
break
start_pos_x = random.choice(list1)
start_pos_y = random.choice(list1)
#generate random target destination
while True:
target_pos_x = random.choice(list1)
target_pos_y = random.choice(list1)
if [target_pos_x, target_pos_y] != [start_pos_x, start_pos_y]:
i[target_pos_x][target_pos_y] = 'T'
break
return grids
def check_neighbors(grid, x, y):
if x - 1 >= 0 and grid[x - 1][y] == 0:
return True
if x + 1 < GRID_SIZE and grid[x + 1][y] == 0:
return True
if y - 1 >= 0 and grid[x][y - 1] == 0:
return True
if y + 1 < GRID_SIZE and grid[x][y + 1] == 0:
return True
return False
|
from threading import Thread
from time import sleep
class bokk(Thread):
def __init__(self):
Thread.__init__(self)
self.messege = "Python Parallel programming started.\n"
def print_messege(self):
print(self.messege)
def run(self):
print("Thread Starting")
x = 0
while(x < 10):
self.print_messege()
sleep(2)
x = x + 1
print("Thread Ended..\n")
print("Process Start..\n")
b = bokk()
b.start()
print("Process Ended..\n") |
#!/usr/bin/python
from Tkinter import *
from string import *
from ConfigDlg import *
"""
This is the Stars! Coalition Tool (SCoT), version 0.1 alpha.
Code for drawing a star: mapCanvas.create_rectangle (100, 100, 103, 103, fill='white')
Of course, fill= can be set to a color appropriate to the player.
Stars' <gamename>.pla file contains a tab-seperated list of planets explored by the
player. This information can be uploaded to the SCoT server by the SCoT
client. When the SCoT client draws the map, it will automatically draw in
the planets which have been explored/colonized by each player.
Stars' <gamename>.map file contains a complete list of every planet in the universe,
complete with X/Y coords.
Not sure how to accomplish zooming yet, but that can wait.
Stars' X and Y coordinates are different from Tkinter-Canvas' coordinates. The
X coordinates work fine, but the Y coordinates need to be inverted. Therefore,
if a star is at X:1500,Y:500, it is in fact at X:1500,Y:1500. Formula:
Y = (2000 - (Y - 1000)).
Add 'intel' file.
-Read the entire map, to build a generified list of planets
-Read the planets file, to add in owner info
-Later, possibly add reading in fleet info.
"""
class Player:
def __init__(self, playerId=-1, playerName='', playerColor=''):
self.id = playerId
self.name = playerName
self.color = playerColor;
class gamePlayers:
def __init__(self):
self.players = []
self._playerNames = [ 'Kinnakku', 'Zylar', 'Alpacan', 'Micronaut', 'Zodor', 'Ozarkian',
'Thylon', 'Murtlean', 'Rhadsu', '', 'Mooninite', 'Rasta-Roach', '' ]
self._colors = [ '#f6f239', '#ff0000', '#ffffff', '#0000ff', '#ffff00', '#ff00ff',
'#00ffff', '#7b0000', '#007d00', '#00007b', '#7b7d7b', '#39ca62',
'#ff7d20' ]
for i in range(0, len(self._playerNames)):
self.players.append(Player(i+1, self._playerNames[i], self._colors[i]))
def findPlayer(self, playerName):
found = 0
i = 0
while found != 1 and i < 13:
if self.players[i].name == playerName:
found = 1
else:
i = i + 1
if found:
return i
else:
return -1
class Planet:
def __init__(self, xCoord=-1, yCoord=-1, planetName='',
playerId=-1, populationVal=0, pctValue=0.01, numMines=0,
numFactories=0, pctDefense=0.00, ktIronium=0, ktBoranium=0,
ktGermanium=0, numResources=0):
self.x = xCoord
self.y = yCoord
self.name = planetName
self.owner = playerId
self.population = populationVal
self.value = pctValue
self.mines = numMines
self.factories = numFactories
self.defense = pctDefense
self.ironium = ktIronium
self.boranium = ktBoranium
self.germanium = ktGermanium
self.resources = numResources
def config(self, xCoord=None, yCoord=None, planetName=None,
playerId=None, populationVal=None, pctValue=None, numMines=None,
numFactories=None, pctDefense=None, ktIronium=None, ktBoranium=None,
ktGermanium=None, numResources=None):
if xCoord != None:
self.x = xCoord
if yCoord != None:
self.y = yCoord
if planetName != None:
self.name = planetName
if playerId != None:
self.owner = playerId
if populationVal != None:
self.population = populationVal
if pctValue != None:
self.value = pctValue
if numMines != None:
self.mines = numMines
if numFactories != None:
self.factories = numFactories
if pctDefense != None:
self.defense = pctDefense
if ktIronium != None:
self.ironium = ktIronium
if ktBoranium != None:
self.boranium = ktBoranium
if ktGermanium != None:
self.germanium = ktGermanium
if numResources != None:
self.resources = numResources
def getAttribute(self, attrName=None):
if attrName != None:
# 'Report Age', # XXX
if attrName == 'xCoord':
return self.x
if attrName == 'yCoord':
return self.y
if attrName == 'planetName' or attrName == 'Planet Name':
return self.name
if attrName == 'playerId' or attrName == 'Owner':
return self.owner
if attrName == 'populationVal' or attrName == 'Population':
return self.population
if attrName == 'pctValue' or attrName == 'Value':
return self.value
if attrName == 'numMines' or attrName == 'Mines':
return self.mines
if attrName == 'numFactories' or attrName == 'Factories':
return self.factories
if attrName == 'pctDefense' or attrName == 'Def %':
return self.defense
if attrName == 'ktIronium' or attrName == 'Surface Ironium':
return self.ironium
if attrName == 'ktBoranium' or attrName == 'Surface Boranium':
return self.boranium
if attrName == 'ktGermanium' or attrName == 'Surface Germanium':
return self.germanium
if attrName == 'numResources' or attrName == 'Resources':
return self.resources
return None
class SCoT(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.topLevel = master
self.planets = []
self.zoomLevels = [ 0.25, 0.38, 0.50, 0.75, 1.00, 1.25, 1.50, 2.0, 4.0 ]
self.currentZoom = 4 # 100% or 1.00
self.displayLabels = [
'Planet Name',
'Owner',
'Starbase Type',
'Report Age',
'Population',
'Value',
'Resources',
'Mines',
'Factories',
'Def %',
'Surface Ironium',
'Surface Boranium',
'Surface Germanium'
]
# Add these labels later:
# Surface Germanium
# Ironium Mining Rate
# Boranium Mining Rate
# Germanium Mining Rate
# Ironium Mineral Concentration
# Boranium Mineral Concentration
# Germanium Mineral Concentration
# Resources
self.bleeIndex = 1
self.gamePlayers = gamePlayers()
self.grid()
self.createWidgets()
self.readMap()
self.readPlanets()
self.zoomFactor = 1.0
self.drawMap()
def fetchFiles(self):
self.ftpConnection = FTP(self.ftpHost, self.ftpUser, self.ftpPass)
self.ftpConnection.login()
self.ftpConnection.cwd(self.ftpDir)
for i in range(1,16):
self.fp = open("KIA2002.p%d" % (i), "w")
self.ftpConnection.retrbinary("RETR KIA2002.p%d" % (i), self.fp.write)
self.fp.close()
def putFiles(self):
try:
self.ftpConnection = FTP(self.ftpHost, self.ftpUser, self.ftpPass)
self.ftpConnection.login()
self.ftpConnection.cwd(self.ftpDir)
self.fp.open("KIA2002.pla", 'r')
self.ftpConnection.storbinary("STOR KIA2002.p%d" % (self.playerNum), fp)
self.ftpConnection.quit()
except:
pass
def zoomCanvas(self):
if self.currentZoom + 1 >= len(self.zoomLevels):
self.currentZoom = 0
else:
self.currentZoom = self.currentZoom + 1
self.zoomTo(self.zoomLevels[self.currentZoom])
def zoomTo(self, newZoomFactor=1.00):
self.zoomFactor = newZoomFactor
self.statusBar.config(text="Zoom: " + str(int(self.zoomFactor * 100)) + "%")
self.mapCanvas.config(scrollregion=(0,0,(2000*newZoomFactor)+10,(2000*newZoomFactor)+10))
self.drawMap()
self.mapCanvas.xview_moveto(0.0)
self.mapCanvas.yview_moveto(0.0)
def clearCanvas(self):
self.mapCanvas.delete('ALLPLANETS')
def createWidgets(self):
self.pack(expand=YES, fill=BOTH)
# Menu bar creation
self.menuBar = Menu(self)
self.topLevel.config(menu=self.menuBar)
self.fileMenu = Menu(self.menuBar)
self.fileMenu.add_command(label='Delete Texas', command=self.deleteTexas, underline=1)
self.fileMenu.add_command(label='Exit', command=self.quit, underline=1)
self.menuBar.add_cascade(label='File', menu=self.fileMenu, underline=0)
self.viewMenu = Menu(self.menuBar)
self.zoomMenu = Menu(self.viewMenu)
self.zoomMenu.add_command(label='25%', command=(lambda s=self, z=0.25: s.zoomTo(z)))
self.zoomMenu.add_command(label='38%', command=(lambda s=self, z=0.38: s.zoomTo(z)))
self.zoomMenu.add_command(label='50%', command=(lambda s=self, z=0.50: s.zoomTo(z)))
self.zoomMenu.add_command(label='75%', command=(lambda s=self, z=0.75: s.zoomTo(z)))
self.zoomMenu.add_command(label='100%', command=(lambda s=self, z=1.00: s.zoomTo(z)))
self.zoomMenu.add_command(label='125%', command=(lambda s=self, z=1.25: s.zoomTo(z)))
self.zoomMenu.add_command(label='150%', command=(lambda s=self, z=1.50: s.zoomTo(z)))
self.zoomMenu.add_command(label='200%', command=(lambda s=self, z=2.00: s.zoomTo(z)))
self.zoomMenu.add_command(label='400%', command=(lambda s=self, z=4.00: s.zoomTo(z)))
self.viewMenu.add_cascade(label='Zoom...', menu=self.zoomMenu, underline=0)
self.menuBar.add_cascade(label='View', menu=self.viewMenu, underline=0)
# Screen layout
self.displayPane = Frame()
# Set up frames
#self.scannerPane = Frame(self.displayPane)
#self.scrollPane = Frame(self.displayPane)
#self.statusPane = Frame(self.displayPane)
# Create scroll bars
self.xScrollBar = Scrollbar(self.displayPane)
self.yScrollBar = Scrollbar(self.displayPane)
# Create and configure map canvas
self.mapCanvas = Canvas (self.displayPane, bg='black', height=600, width=800,
scrollregion=(0,0,2010,2010),
xscrollcommand=self.xScrollBar.set,
yscrollcommand=self.yScrollBar.set)
self.mapCanvas.bind('<ButtonPress-1>', self.onClick)
self.yScrollBar.config(command=self.mapCanvas.yview, orient=VERTICAL)
self.xScrollBar.config(command=self.mapCanvas.xview, orient=HORIZONTAL)
self.statusBar = Label(self.displayPane, text="X:0, Y:0", relief=SUNKEN)
self.displayCanvas = Canvas (self.displayPane, height=600, width=300)
# Grid packing layouts:
# xScrollBar: row=1, column=0, rowspan=1, columnspan=1, sticky=E+W
# statusBar: row=2, column=0, rowspan=1, columnspan=3, sticky=E+W
# displayCanvas: row=0, column=2, rowspan=2, columnspan=1, sticky=N+E
# yScrollBar: row=0, column=1, rowspan=1, columnspan=1, sticky=N+S
# mapCanvas: row=0, column=0, rowspan=1, columnspan=1, sticky=N+E
self.xScrollBar.grid(row=1, column=0, rowspan=1, columnspan=1, sticky=E+W)
self.statusBar.grid(row=2, column=0, rowspan=1, columnspan=3, sticky=E+W)
self.displayCanvas.grid(row=0, column=2, rowspan=2, columnspan=1, sticky=N+E)
self.yScrollBar.grid(row=0, column=1, rowspan=1, columnspan=1, sticky=N+S)
self.mapCanvas.grid(row=0, column=0, rowspan=1, columnspan=1, sticky=N+E)
self.displayPane.pack(side=TOP, expand=YES, fill=BOTH)
def readMap(self):
self.mapFile = open('KIA2002.map', 'r')
self.x = []
self.y = []
self.names = []
linecount = 1
for line in self.mapFile.readlines():
if line[0] == '#':
pass
else:
#def __init__(self, xCoord=-1, yCoord=-1, planetName='',
# playerId=-1, populationVal=0, pctValue=0.01, numMines=0,
# numFactories=0, pctDefense=0.00, ktIronium=0, ktBoranium=0,
# ktGermanium=0):
bits = split(line, "\t")
newPlanet = Planet( xCoord=(int(bits[1]) - 1000),
yCoord=(int(bits[2]) - 1000),
planetName=bits[3][:-2],
)
self.planets.append(newPlanet)
linecount = linecount + 1
def findPlanet(self, planetName, retObject=None):
found = 0
for i in range(0, len(self.planets)):
#print "comparing '%s' with '%s'" % (planetName, self.planets[i].name)
if self.planets[i].name == planetName:
found = 1
if retObject:
return self.planets[i]
else:
return i
if not found:
return None
def readPlanets(self, planetFileName=None):
if planetFileName == None:
recursionFlag = 0
self.planetFile = open('KIA2002.pla', 'r')
else:
recursionFlag = 1
try:
self.planetFile = open('%s' % (planetFileName), 'r')
except IOError:
pass
except:
pass
self.planetFile.readline() # Discard first line
for line in self.planetFile.readlines():
line = rstrip(line)
line = replace(line, "\t", ':')
line = replace(line, '::', ':0:')
line = replace(line, '::', ':')
bits = split(line, ':')
if len(bits[1]) > 0:
thisPlayerId = self.gamePlayers.findPlayer(bits[1])
if thisPlayerId > -1:
# set the owner of the planet in question
planetId = self.findPlanet(bits[0])
if planetId > -1:
if len(bits) < 19:
for i in range(0,(20 - len(bits))):
bits.append('0')
# print bits
if bits[5][-1:] == '%':
bits[5] = bits[5][:-1]
self.planets[planetId].config(playerId=thisPlayerId,
populationVal=int(bits[4]),
pctValue=int(bits[5]),
numMines=int(bits[7]),
numFactories=int(bits[8]),
ktIronium=int(bits[10]),
ktBoranium=int(bits[11]),
ktGermanium=int(bits[12]),
numResources=int(bits[19])
)
#self.planets[planetId].config(pctDefense=int(float(bits[9][:-1])))
if not recursionFlag:
for i in range(1,16):
self.readPlanets(planetFileName='KIA2002.p%d' % (i))
def drawMap(self, allLabels=FALSE):
self.clearCanvas()
for thisPlanet in self.planets:
self.xCoord = thisPlanet.x
self.yCoord = thisPlanet.y
self.yCoord = (2000 - self.yCoord)
self.xCoord = int(self.xCoord * self.zoomFactor)
self.yCoord = int(self.yCoord * self.zoomFactor)
if thisPlanet.owner > -1:
#print "Found planet w/nonzero owner: %s! (Owner: %d)" % (thisPlanet.name, thisPlanet.owner)
fillColor = self.gamePlayers.players[thisPlanet.owner].color
dotId = self.mapCanvas.create_oval (self.xCoord, self.yCoord, self.xCoord+9, self.yCoord+9, fill=fillColor, outline=fillColor)
nameId = self.mapCanvas.create_text (self.xCoord, self.yCoord+20, text=thisPlanet.name, fill=fillColor)
self.mapCanvas.addtag_withtag (thisPlanet.name, dotId)
self.mapCanvas.addtag_withtag (thisPlanet.name, nameId)
else:
fillColor = 'darkgray'
dotId = self.mapCanvas.create_rectangle (self.xCoord, self.yCoord, self.xCoord+2, self.yCoord+2, fill=fillColor, outline=fillColor)
self.mapCanvas.addtag_withtag (thisPlanet.name, dotId)
if allLabels:
nameId = self.mapCanvas.create_text (self.xCoord, self.yCoord+20, text=thisPlanet.name, fill=fillColor)
self.mapCanvas.addtag_withtag (thisPlanet.name, nameId)
self.allPlanetsTag = self.mapCanvas.addtag_all('ALLPLANETS')
def deleteTexas(self):
self.foo = ConfigDlg(self.topLevel)
def onClick(self, event):
self.displayCanvas.delete('DISPLAY')
id = self.mapCanvas.find_closest(self.mapCanvas.canvasx(event.x), self.mapCanvas.canvasy(event.y), halo=5)
tag = self.mapCanvas.gettags (id)
planetName = tag[0]
self.statusBar.config(text=planetName)
for label in self.displayLabels:
thisPlanet = self.findPlanet(planetName, retObject=1)
keyId = self.displayCanvas.create_text(15, 15 * self.bleeIndex, text=label, fill='black', anchor=NW)
if label == 'Owner':
ownerName = self.gamePlayers.players[int(thisPlanet.getAttribute(label))].name
valId = self.displayCanvas.create_text(150, 15 * self.bleeIndex, text=ownerName, fill='black', anchor=NW)
else:
valId = self.displayCanvas.create_text(150, 15 * self.bleeIndex, text=thisPlanet.getAttribute(label), fill='black', anchor=NW)
#self.displayCanvas.addtag_withtag('DISPLAY', keyId)
#self.displayCanvas.addtag_withtag('DISPLAY', valId)
self.displayCanvas.addtag_all('DISPLAY')
self.bleeIndex = self.bleeIndex + 1
self.bleeIndex = 1
topLevel = Tk()
app = SCoT(topLevel)
app.master.title("Stars! Coalition Tool")
app.mainloop()
|
# Automate-the-boring-stuff-with-python
Python Practice
Chapter # 3
Practice Projects
# The Collatz Sequence Programe
def collatz(number):
if number%2==0 and number>0:
number=number/2
return(number)
else:
number=3*number+1
return(number)
def fun():
while True:
try:
number=int(input('enter an integer'))
break
except:
print('you must have to enter an integer')
if number==1:
print(number)
while number!=1:
number=collatz(number)
print(int(number))
|
from math import sqrt
import numpy as np
def FindPrimes(limit):
isPrime = {}
isPrime[1] = False
for i in range(2, limit + 1):
isPrime[i] = True
checkLimit = int(sqrt(limit)) + 1
for i in range(2, checkLimit):
if isPrime[i]:
for factor in range(2, limit + 1):
j = i * factor
if (j > limit): break
isPrime[j] = False
primes = []
for i in range(1, limit + 1):
if isPrime[i]:
primes.append(i)
return np.array(primes)
N = 100**2
primes = FindPrimes(N)
print primes |
import random
class dice:
def __init__(self, side1, side2, side3, side4, side5, side6):
self.side1=side1
self.side2=side2
self.side3=side3
self.side4=side4
self.side5=side5
self.side6=side6
dice1=dice(1, 2, 3, 4, 5, 6)
keepRolling=True
counter = 0
def rollDice():
displaySide=random.randint(1,6)
if displaySide == 1:
print("You got a: ",dice1.side1)
elif displaySide == 2:
print("You got a: ",dice1.side2)
elif displaySide == 3:
print("You got a: ",dice1.side3)
elif displaySide == 4:
print("You got a: ",dice1.side4)
elif displaySide == 5:
print("You got a: ",dice1.side5)
elif displaySide == 6:
print("You got a: ",dice1.side6)
def stop():
print("You rolled the dice ",counter," times.")
while keepRolling:
choice = input("Press ENTER to roll the dice or q to quit: ")
print("")
if choice == "q":
stop()
keepRolling=False
else:
rollDice()
counter = counter+1 |
import random
import sys
def create_players():
global player1
global player2
print ("[Player 1]")
player1 = str.lower(raw_input("Type in your name, please:"))
print("[Player 2]")
player2 = str.lower(raw_input("Type in your name, please:"))
def randFirstPlayer():
start = random.randint(1, 2)
global FirstPlayer
if (start == 1):
FirstPlayer = player1
else:
FirstPlayer = player2
def flip_coin():
coinOption = random.randint(1, 2)
global coinSide
if (coinOption == 1):
coinSide = "heads"
else:
coinSide = "tails"
def getCoinOption():
global player2Option
global player1Option
if (FirstPlayer == player1):
print("")
print str("[Player 1]:"), str.upper(player1)
player1Option = str.lower(raw_input("Choose. Heads or tails?:"))
if (player1Option == "heads"):
player2Option = "tails"
elif (player1Option == "tails"):
player2Option = "heads"
else:
print ("Type in a valid option, please.")
getCoinOption()
else:
print("")
print str("[Player 2]:"), str.upper(player2)
player2Option = str.lower(raw_input("Choose: heads or tails?: "))
if (player2Option == "heads"):
player1Option = "tails"
elif (player2Option == "tails"):
player1Option = "heads"
else:
print ("Type in a valid option, please.")
getCoinOption()
def win():
global winner
if (player1Option == coinSide):
winner = player1
else:
winner = player2
print("")
print str("You got"), str(coinSide)
print str("The winner is:"), str.upper(winner)
create_players()
randFirstPlayer()
getCoinOption()
flip_coin()
win()
|
#Smallest multiple
#Problem 5
#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
# Not have answer the question
"""
v = 1
number_try = False
lines = "----------------------|"
while number_try == False:
z = 0
c = 0
for b in range(1, 11):
if v % b == 0:
c += 1
z += v/b
print str(c) + " " + str(v / b)
if c == 10:
print lines
print z
print lines
print v
number_try = True
break
v += 1
print lines
print
print "Hello"
"""
"""
do = int(input("Enter number, please: "))
if do <= 13:
v = 1
number_try = False
lines = "----------------------|"
while number_try == False:
z = 0
c = 0
for b in range(1, do + 1):
if v % b == 0:
c += 1
print "Number# " + str(c) + ": " +str(v) + " / " + str(b) + " = " + str(v / b)
if c == do:
print lines
print v
number_try = True
v += 1
print lines
print
print "Hello"
"""
#version two
num = int(input("Enter the number "))
step = 1
level = num
timer = 0
while level > 0:
timer += 1
answer = ((num * step)/level) * level
if level -1 != 0 and ((num * step)/(level - 1)) * (level-1) == answer:
level -= 1
else:
step += 1
level = num
print
print level
print
if level == 1:
print "This number: " + str(answer)
break
if timer > 100000000000:
print "Problem with you code"
break
# fo number 20 answer = 232792560
|
"""
Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя:
имя, фамилия, год рождения, город проживания, email, телефон.
Функция должна принимать параметры как именованные аргументы.
Реализовать вывод данных о пользователе одной строкой.
"""
def get_param(name,
surname,
year,
city,
email,
phone):
print(name,
surname,
year,
city,
email,
phone)
get_param(name=input('Enter your name: '),
surname=input('Enter your surname: '),
year=input('Enter the year you were born: '),
city=input('Enter the city you live in: '),
email=input('Enter your email: '),
phone=input('Enter your phone number: '))
|
# Ex. 2
user_seconds = (input('Enter time(sec): '))
hours = int(user_seconds) // 3600
minutes = int(user_seconds) // 60
seconds = int(user_seconds) % 60
print('{0}:{1}:{2}'.format(hours, minutes, seconds))
|
from abc import ABC, abstractmethod
class A(ABC):
def __init__(self,value):
self.value = value
@abstractmethod
def add(self):
pass
@abstractmethod
def sub(self):
pass
class Y(A):
def add(self):
return self.value +100
def sub(self):
return self.value -10
obj=Y(100)
print(obj.add())
print(obj.sub()) |
n = 10
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1
print("La somme est", sum)
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
|
n1=int(input("Veuillez donner le premier nombre"))
n2=int(input("Veuillez donner le second nombre!"))
s=n1+n2
p=n1*n2
d=n1-n2
q=n1/n2
print("La somme de deux nombre est :", s, sep=' ', end='\n')
print("Le produit de deux nombres est :", p, sep=' ', end='\n')
print("La difference de deux nombres est :", d, sep=' ', end='\n')
print("Le quotient de deux nombres est :", q, sep=' ',end='\n') |
texte="Bonjour tout le monde"
rech=input("Entrez un texte a rechercher")
pos=texte.find(rech)
print("La position du\"{}\" est:{}".format(rech,pos))
|
class Flight():
def __init__(self,capacity):
self.capacity = capacity
self.passengers=[]
def add_passenger(self,name):
if not self.open_seats():
return False
self.passengers.append(name)
return True
def open_seats(self):
return self.capacity -len(self.passengers)
flight=Flight(3)
people=["Alpha","Nafiou","Saidou","Rama"]
for person in people:
if flight.add_passenger(person):
print(f"Added {person} avec successfully.")
else:
print(f"No dispo {person}")
|
number = int(input("Entrez la table de multiplication que vous voulez"))
for count in range(1, 11):
print(number, 'x', count, '=', number * count)
print("==========================================")
i = 1
while i <= 10:
p = i*7
print(i,'x 7=',p)
i += 1
|
a=int(input("Entrez votre chiffre"))
if a==0:
print("votre chiffre est null!")
elif a >0:
print("Votre chiffre est positif")
else:
print("votre chiffre est negatif!") |
def tri_selection(tab):
for i in range(len(tab)):
min = i
for j in range(i+1, len(tab)):
if tab[min] > tab[j]:
min = j
tmp = tab[i]
tab[i] = tab[min]
tab[min] = tmp
return tab
# Programme principale pour tester le code ci-dessus
tab = [98, 22, 15, 32, 2, 74, 63, 70]
tri_selection(tab)
print ("Le tableau trié est:")
for i in range(len(tab)):
#print ("%d" %tab[i])
print(tab[i]) |
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])
plt.scatter(x, y, color='hotpink')
x = np.array([2, 2, 8, 1, 15, 8, 12, 9, 7, 3, 11, 4, 7, 14, 12])
y = np.array([100, 105, 84, 105, 90, 99, 90, 95, 94, 100, 79, 112, 91, 80, 85])
plt.scatter(x, y, color='#88c999')
plt.show()
|
i= 0
while i<11:
if i%2==0:
print("est pair\n",i)
i+=1
|
class Voiture:
voiture_crees=0
def __init__(self,marque):
self.marque= marque
voiture_crees+=1
def afficher_marque(self,vitesse):
print(f" La voiture est une {self.marque}")
voiture_O1=Voiture("Lamborghini")
voiture_O2=Voiture("Porsche")
Voiture.afficher_marque(voiture_O1,50)
print(voiture_O1.marque)
print(voiture_O2.marque)
print(Voiture.voiture_crees) |
for val in range(5):
print(val)
else:
print("Fin de l'execution de la boucle")
|
class Student:
def __init__(self, name, age):
self.name = name
self.__age = age
def get_age(self):
return self.__age
def set_age(self, age):
self.__age = age
emp=Student("ismatou",14)
print("Name: " +emp.name,emp.get_age())
emp.set_age(16)
print("Name: " +emp.name,emp.get_age()) |
class Saidou():
def __init__(self):
self.course='java programmation cours'
self.__tech='java'
def CourseName(self):
return self.course + self.__tech
obj=Saidou()
print(obj.course)
print(obj._Saidou__tech)
print(obj.CourseName())
|
for num in [11, 9, 88, 10, 90, 3, 19]:
print(num)
if num==88:
print("number 88 found")
print("Terminer la boucle")
break
|
def smart_divide(func):
def inner(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a, b)
return inner
@smart_divide
def divide(a, b):
print(a/b)
divide(2,5)
def star(func):
"""exemple de decorator"""
def inner(*args, **kwargs):
print("*" * 30)
func(*args, **kwargs)
print("*" * 30)
return inner
def percent(func):
def inner(*args, **kwargs):
print("%" * 30)
func(*args, **kwargs)
print("%" * 30)
return inner
@star
@percent
def printer(msg):
print(msg)
printer("Bonjour")
|
import numpy as np
df=np.array([
[1,2,4],
[3,4,5,6],
[8,9,7,2]
])
print(df[2][3]) |
x=0
while x <=10:
print(x)
x += 1
print("fin de la boucle tant que ")
for n in range(5,10):
print(n)
print("fin de la boucle for ")
for n in range(9):
if n %2== 0:
print(n," est un nombre pair")
else:
print(n,"est un chiffre impair") |
class Personne():
def __init__(self, prenom, nom, age):
self.__prenom = prenom
self.__nom = nom
self.__age = age
def est_majeur(self):
if self.__age >= 18:
return True
return False
def vieillir(self):
self.__age += 1
def __str__(self):
resulat = self.__prenom + " " + \
self.__nom + " a " + str(self.__age)+ " ans "
if self.est_majeur():
resulat += "Il/Elle est majeur(e)."
else:
resulat += "Il/Elle est mineur(e)."
return resulat
if __name__ == "__main__":
alpha = Personne(prenom="alpha", nom="Diallo", age=17)
print(alpha)
alpha.vieillir()
print(alpha)
|
# En utilisant la POO en Python, nous pouvons restreindre l'accès aux méthodes et aux variables.
# Cela empêche les données de modification directe qui est appelée encapsulation.
# En Python, nous désignons les attributs privés en utilisant un trait de soulignement comme préfixe,
# c'est-à-dire single _ou double __
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
|
class StaffSaidou:
# class variables
school_name = 'NIIT TECH'
# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age
# instance variables
def show(self):
print(self.name, self.age, StaffSaidou.school_name)
@classmethod
def change_School(cls, name):
cls.school_name = name
@staticmethod
def find_notes(subject_name):
return ['chapter 1', 'chapter 2', 'chapter 3']
# create object
jessa = StaffSaidou('Massoud', 12)
# call instance method
jessa.show()
# call class method using the class
StaffSaidou.change_School('XYZ School')
# call class method using the object
jessa.change_School('PQR School')
# call static method using the class
StaffSaidou.find_notes('Math')
# call class method using the object
jessa.find_notes('Math')
|
first_name=input("Votre nom s'il vous plait")
last_name=input("Votre Prenom s'il vous plait")
filiere=input("Votre Filiere s'il vous plait'")
print("Bonjour ",first_name,last_name)
print("Bienvenue dans la filiere",filiere) |
"""This file contains all functions needed for the evolution.
http://en.wikipedia.org/wiki/Genetic_algorithm
- random initialization
- run first generation
- evaluate with fitness function, measure average/max fitness
- select best candidates for next generation
- mutation + crossover/recombination + regrouping + colonization-extinction + migration
- run second generation
- ...
"""
# external imports
import random
import sys
import os
# internal imports
sys.path.insert(0, os.path.abspath(os.path.join(
os.path.dirname(sys.modules[__name__].__file__), "..")))
import util
import selection
import mutation
import crossover
def is_termination(eparams, fitnesses, g):
"""Return true if there should not be another generation to come.
:param eparams: the evolutionparams python module name
:param fitnesses: multi-objective fitness values of the last generation
:param g: the next generation number
TODO: add other criteria based on:
- A solution is found that satisfies minimum criteria
- Allocated budget (computation time/money) reached
- The highest ranking solution's fitness is reaching or has reached a plateau such that successive iterations no longer produce better results
- Manual inspection
- Combinations of the above
"""
return g > eparams.generations
def generate_random_environments(eparams):
"""Generate a number of random environments.
:param eparams: the evolutionparams python module name
"""
random.seed()
params = [util.convert_string_to_param_t(env) for env in eparams.params_as_environment]
pvalues = []
for n in xrange(eparams.environments):
pvalues.append([])
for param in params:
value = random.choice([f for f in util.frange(param.minv, param.maxv, param.step)])
pvalues[-1].append(value)
return (params, pvalues)
def generate_random_population(eparams):
"""Generate a number of random populations.
:param eparams: the evolutionparams python module name
Return a list of params to evolve and a 2D-list of param values
for each phenotype and each param.
"""
random.seed()
# get params to evolve
params = get_params_to_evolve(eparams)
# assign a param value for each param, for each phenotype
pvalues = []
for p in xrange(eparams.phenotypes):
pvalues.append([])
for param in params:
value = random.random() * (param.maxv - param.minv) + param.minv
pvalues[-1].append(value)
return (params, pvalues)
def generate_population_history_0(eparams, lastpvalues, fitnesses):
"""Generate a new population based on the last one.
:param eparams: the evolutionparams python module name
:param lastpvalues: dict of evolvable pvalues for all phenotypes in the last generation.
:param fitnesses: dict of multi-objective fitnesses for all phenotypes in the last generation.
Return a list of params to evolve and a 2D-list of param values
for each phenotype and each param.
"""
# if this is only an initialization, return a random population
if not fitnesses or not lastpvalues:
print (" Note: no info from past, random population is generated.")
return generate_random_population(eparams)
# create single-valued fitnesses now
# TODO: extend to multi-objective optimization
sfitnesses = get_single_fitnesses(fitnesses)
# if this is a next generation, create new population with selection + mutation + crossover
# but first create the params list
params = get_params_to_evolve(eparams)
# elite selection
elite_parents_p = selection.elite(sfitnesses, int(eparams.phenotypes * eparams.elite_fraction))
elite_children_pvalues = [list(lastpvalues[p]) for p in elite_parents_p]
# tournament selection + average crossover
crossover_parents_p = selection.tournament(sfitnesses, eparams.tournament_size,
int(eparams.phenotypes * eparams.crossover_fraction))
crossover_children_pvalues = crossover.average(lastpvalues, crossover_parents_p,
int(eparams.phenotypes * eparams.crossover_fraction))
# gauss-noise mutation of parents
mutation_parents_p = selection.fullrandom(sfitnesses, int(eparams.phenotypes * eparams.pure_mutation_fraction))
mutation_children_pvalues = [list(lastpvalues[p]) for p in mutation_parents_p]
mutation.gauss(params, mutation_children_pvalues, eparams.mutation_sigma, eparams.mutation_probability, eparams.mutation_sqrtN)
# TODO TODO how many mutations are needed? One solution, if fitness is normalized in [0-1]:
# AktualisMutEh = MaximalisMutEh * (1-GenereacioAtlagosFitnesse)
# summarize all new generation
pvalues = elite_children_pvalues + crossover_children_pvalues + mutation_children_pvalues
# a quick error check on population size
diff = len(pvalues) - eparams.phenotypes
if diff < 0:
print ("Warning: population size has been reduced! Adding %d new random phenotypes." % (-diff))
a, b = generate_random_population(eparams)
pvalues += b[0:-diff]
elif diff > 0:
print ("Warning: population size has grown! Removing %s random phenotypes." % diff)
indices = random.sample(range(len(pvalues)), diff)
pvalues = [i for j, i in enumerate(pvalues) if j not in indices]
return (params, pvalues)
def generate_population(eparams, lastpvalues, fitnesses):
"""Generate a new population based on the last one.
:param eparams: the evolutionparams python module name
:param lastpvalues: dict of evolvable pvalues for all phenotypes in the last generation.
:param fitnesses: dict of multi-objective fitnesses for all phenotypes in the last generation.
Return a list of params to evolve and a 2D-list of param values
for each phenotype and each param.
"""
# if this is only an initialization, return a random population
if not fitnesses or not lastpvalues:
print (" Note: no info from past, random population is generated.")
return generate_random_population(eparams)
# create single-valued fitnesses now
# TODO: extend to multi-objective optimization
sfitnesses = get_single_fitnesses(fitnesses)
# if this is a next generation, create new population with selection + crossover + mutation
# but first create the params list
params = get_params_to_evolve(eparams)
# elite selection
elite_parents_p = selection.elite(sfitnesses, int(eparams.phenotypes * eparams.elite_fraction))
pvalues = [list(lastpvalues[p]) for p in elite_parents_p]
# tournament selection of parents + crossover + mutation
for i in xrange(int(eparams.phenotypes * eparams.crossover_fraction)):
# get some parents
crossover_parents_p = selection.tournament(sfitnesses, eparams.tournament_size, len(sfitnesses))
# generate one child
if eparams.crossover_operator == "uniform":
crossover_children_pvalues = crossover.uniform(lastpvalues, crossover_parents_p, 1)
elif eparams.crossover_operator == "average":
crossover_children_pvalues = crossover.average(lastpvalues, crossover_parents_p, 1)
else:
raise ValueError("unknown crossover operator: %s" % eparams.crossover_operator)
# mutate some genes of the new child
mutation.gauss(params, crossover_children_pvalues, eparams.mutation_sigma, eparams.mutation_probability, eparams.mutation_sqrtN)
# TODO TODO how many mutations are needed? One solution, if fitness is normalized in [0-1]:
# AktualisMutEh = MaximalisMutEh * (1-GenereacioAtlagosFitnesse)
# add new child to next generation
pvalues += crossover_children_pvalues
# pure mutation fraction (if needed, not necessary)
mutation_parents_p = selection.fullrandom(sfitnesses, int(eparams.phenotypes * eparams.pure_mutation_fraction))
mutation_children_pvalues = [list(lastpvalues[p]) for p in mutation_parents_p]
mutation.gauss(params, mutation_children_pvalues, eparams.mutation_sigma, eparams.mutation_probability, eparams.mutation_sqrtN)
pvalues += mutation_children_pvalues
# a quick error check on population size
diff = len(pvalues) - eparams.phenotypes
if diff < 0:
print ("Warning: population size has been reduced! Adding %d new random phenotypes." % (-diff))
a, b = generate_random_population(eparams)
pvalues += b[0:-diff]
elif diff > 0:
print ("Warning: population size has grown! Removing %s random phenotypes." % diff)
indices = random.sample(range(len(pvalues)), diff)
pvalues = [i for j, i in enumerate(pvalues) if j not in indices]
return (params, pvalues)
def get_fitnesses(eparams, model, fitnessfunctionparam):
"""Return dictionary with keys as phenotypes and values as multi-objective fitnesses.
:param eparams: the evolutionparams python module name
:param model: the name of the robotsim model that is used
:param fitnessfunctionparam: a single user parameter that is passed to the fitness functions
"""
try:
fitnesses = eval("eparams.fitness.fitness_%s" % model)(fitnessfunctionparam)
except NameError as e:
print ("Model type '%s' is not implemented yet (%s)." % (model, e))
print eparams.fitness.fitness_template.__doc__
return None
return fitnesses
def get_single_fitnesses(fitnesses):
"""Return single-valued fitness list from multi-objective fitnesses."""
return dict((p, get_single_fitness(fitnesses[p])) for p in fitnesses)
def get_single_fitness(fitnessdict):
"""Return a single fitness value from a multi-objective fitness dict.
:param fitnessdict: the dict of fitness values for a phenotype
"""
retval = 1.0
for x in fitnessdict:
retval *= fitnessdict[x]
return retval
def save_fitnesses(filename, eparams, fitnesses, g, pvalues=None):
"""Save multi-objective fitnesses to a file.
:param filename: save fitnesses to this file
:param fitnesses: multi-objective fitness values for all phenotypes as a dict of dicts
:param g: the index of the generation
:param pvalues: pvalues of the given generation (None if not needed in output)
"""
sfitnesses = get_single_fitnesses(fitnesses)
f = open(filename, 'w')
# write header
f.write("\t".join( ["#g", "p", "fitness"] + ["fitness_%s" % x for x in sorted(fitnesses[0])] ))
if pvalues is not None:
params = get_params_to_evolve(eparams)
f.write("\tpvalues\t" + "\t".join([p.name for p in params]))
f.write("\n")
# write data for each phenotype
for p in sorted(sfitnesses, key=sfitnesses.get, reverse=True):
f.write("\t".join( ["%d" % g, "%d" % int(float(p)), "%g" % sfitnesses[p]] + \
["%g" % fitnesses[p][x] for x in sorted(fitnesses[p])] ))
if pvalues is not None:
f.write("\t%d\t" % len(params) + "\t".join(str(pvalues[p][i]) for i in xrange(len(params))))
f.write("\n")
f.close()
def save_fitnesses_hack(filename, eparams, len_fitnesses, name, evaluation, pvalues, sfitness):
"""This is a hack to be able to add favorite and best solutions to the
standard fitnesses file. Use in synchrony with save_fitnesses().
"""
f = open(filename, 'a')
f.write("\t".join( ["#%s_%d" % (name, (evaluation-1)/eparams.generations),
str((evaluation-1) % eparams.generations), str(sfitness)] + ["-"]*len_fitnesses ))
params = get_params_to_evolve(eparams)
f.write("\t%d\t" % len(params) + "\t".join(str(pvalues[i]) for i in xrange(len(params))))
f.write("\n")
f.close()
def get_params_to_evolve(eparams):
"""Return the parameters that are to be evolved.
:param eparams: the evolutionparams python module name
"""
return [util.convert_string_to_param_t(p) for p in eparams.params_to_evolve]
|
#!/usr/bin/env python3
'''
time complexity n
'''
def find_terms(nums, target=2020):
d = dict()
for num in nums:
if target - num in d:
return (target - num), num
d[num] = num
return 0, 0
'''
time complexity n
'''
def part_1(nums):
a, b = find_terms(nums)
return a * b
'''
time complexity n*2, memory and time hog
'''
def part_2(nums, target=2020):
for i, v in enumerate(nums):
a, b = find_terms(nums[:i] + nums[i+1:], target - v)
if a + b != 0:
return v * a * b
with open('input_file.txt', 'r') as expense_report:
expenses = [int(expense) for expense in expense_report]
print(part_1(expenses))
print(part_2(expenses))
|
from surfaces import *
import math
class Cell():
"""Takes one surface as initial input, the rest have to be added.
Surfaces are stored in a list of self.surfaces."""
def __init__(self):
self.surfaces = []
def add_surface(self, new_surface, sense):
"""Takes in the surface and the sense for that surface.
sense: False for left/inside, True for right/outside."""
self.surfaces.append((new_surface, sense))
def get_surfaces(self):
return self.surfaces
def in_cell(self, x, y, direction):
"""Returns True if point is within cell."""
surfaces = self.get_surfaces()
for surface in surfaces:
if surface[0].sense(x, y, direction) != surface[1]:
return False
return True
def dist_to_boundary(self, x, y, direction):
"""Finds shortest distance to the boundary of the cell."""
list_of_distances = []
surfaces = self.get_surfaces()
for surface in surfaces:
dist = surface[0].dist_to_boundary(x, y, direction)
print dist
if dist != None:
list_of_distances.append(dist)
return min(list_of_distances)
def find_collision_point(self, x, y, direction):
"""Finds collision point with edge of cell in given direction."""
dict_of_distances = {}
surfaces = self.get_surfaces()
for surface in surfaces:
dist = surface[0].dist_to_boundary(x, y, direction)
if dist != None:
dict_of_distances[dist] = surface[0].find_collision_point(x, y, direction)
return dict_of_distances[min(dict_of_distances)]
|
# Davis Arthur
# 10-15-2019
# Auburn University
import math
import scipy.constants # science constants
import matplotlib.pyplot as plt # plotting libraries
import numpy as np
from SingleWire2 import *
class loop:
def __init__(self, current, radius, numwires, zpos = 0):
self.current = current
self.radius = radius
self.numwires = numwires
self.wirelen = 0
self.origins = self.calcOrigins()
self.zpos = zpos
self.wires = self.genwires()
def calcOrigins(self):
deltaAng = math.radians(360.0 / self.numwires)
self.wirelen = self.radius * (2 - 2 * math.cos(deltaAng)) ** (1.0/2)
origins = []
for i in range(self.numwires):
origins.append(i * deltaAng)
return origins
def genwires(self):
wires = []
for origin in self.origins:
wires.append(stwire(self.current, self.wirelen, (self.radius, origin, self.zpos)))
return wires
def main3():
# input values from the user
current = input("Current of wire: ")
radius = input("Radius of wire: ")
height = input("Height of region of interest: ")
numwires = input("Number of straight wires in approximation: ")
numPointsX = input("Number of points in x/y direction: ")
numPointsZ = input("Number of points in z direction: ")
index = input("z-index: ")
# generate single wire
testloop = loop(current, radius, numwires)
# generate array of 3D points
x = []
y = []
z = []
deltaX = 2.0 * radius * 1.25 / numPointsX
deltaZ = height / numPointsZ
for i in range(numPointsX):
x.append(- radius * 1.25 + i * deltaX)
y.append(- radius * 1.25 + i * deltaX)
for i in range(numPointsZ):
z.append(i * deltaZ)
zmag = [[[0 for k in range(numPointsZ)] for j in range(numPointsX)] \
for i in range(numPointsX)]
for wire in testloop.wires:
for xindex in range(numPointsX):
for yindex in range(numPointsX):
for zindex in range(numPointsZ):
xcord = x[xindex]
ycord = y[yindex]
zcord = z[zindex]
xlocal, ylocal, zlocal = wire.gtol([xcord, ycord, zcord])
newcomp = wire.maglocal(xlocal, ylocal, zlocal)[1]
zmag[yindex][xindex][zindex] = zmag[yindex][xindex][zindex] \
+ newcomp
print("Plotting the field at z = " + str(z[index]))
finalfield = planeSelector(zmag, numPointsX, numPointsX, 2, index)
plt.contourf(x, y, finalfield, 300, cmap = 'BrBG')
plt.colorbar()
plt.show()
def main4():
# input values from the user
current = input("Current of wire: ")
radius = input("Radius of wire: ")
height = input("Height of region of interest: ")
numwires = input("Number of straight wires in approximation: ")
numPointsX = input("Number of points in x/y direction: ")
numPointsZ = input("Number of points in z direction: ")
index = input("z-index: ")
# generate single wire
testloop = loop(current, radius, numwires)
# generate array of 3D points
x = []
y = []
z = []
deltaX = 2.0 * radius * 1.25 / numPointsX
deltaZ = height / numPointsZ
for i in range(numPointsX):
x.append(- radius * 1.25 + i * deltaX)
y.append(- radius * 1.25 + i * deltaX)
for i in range(numPointsZ):
z.append(i * deltaZ)
zmag = [[[0 for k in range(numPointsZ)] for j in range(numPointsX)] \
for i in range(numPointsX)]
for wire in testloop.wires:
for xindex in range(numPointsX):
for yindex in range(numPointsX):
for zindex in range(numPointsZ):
xcord = x[xindex]
ycord = y[yindex]
zcord = z[zindex]
xlocal, ylocal, zlocal = wire.gtol([xcord, ycord, zcord])
newcomp = wire.maglocal(xlocal, ylocal, zlocal)[1]
zmag[yindex][xindex][zindex] = zmag[yindex][xindex][zindex] \
+ newcomp
print("Plotting the field at z = " + str(z[index]))
finalfield = planeSelector(zmag, numPointsX, numPointsX, 2, index)
finalfield = lineSelector(finalfield, numPointsX / 2 - 1)
plt.plot(y, finalfield)
plt.show()
if __name__ == "__main__":
main3()
|
from fractions import Fraction
a=int(input('Introduceti numarul a='))
b=int(input('Introduceti numarul b='))
c=int(input('Introduceti numarul c='))
d=int(input('Introduceti numarul d='))
print('Suma este=',Fraction(a,b)+Fraction(c,d))
print('Produsul este=',Fraction(a,b)*Fraction(c,d)) |
"""
版本:1.0
作者:MJL
功能:掷骰子
"""
import random
import matplotlib.pyplot as plt
roll1_list = []
roll_count = [0,0,0,0,0,0]
roll_rate = []
def main():
roll_times = 10000
for i in range(1,roll_times + 1):
roll1 = random.randint(1,6)
roll_count[roll1 -1] +=1
roll1_list.append(roll1)
for j in range(1,7):
roll_rate.append(roll_count[j - 1]/roll_times)
print(roll1_list,'\n',len(roll1_list),'\n',roll_count,'\n',roll_rate)
plt.hist(roll1_list,[1,2,3,4,5,6,7],rwidth=0.4,color='blue')
plt.show()
if __name__ == '__main__':
main()
|
import re
import datetime
class Entry(object):
def is_today(self):
if self.date==datetime.datetime.today().date():
return True
else:
return False
def days_old(self):
if not self.date:
return 999999
else:
delta = datetime.date.today() - self.date
return delta.days
def is_date(self,input_string):
match = re.search(r'\d{2}/\d{2}/\d{2}', input_string)
if match:
testdate = datetime.datetime.strptime(match.group(), '%d/%m/%y').date()
if testdate==self.date:
return True
else:
return False
else:
raise ValueException("Date string is badly formed")
return False #should never be here
def __init__(self, input_string):
import types
if isinstance(input_string, str):
pass
else:
raise ValueError("Input to constructor wasn't a string")
try:
self.input_string=input_string
match = re.search(r'\d{2}/\d{2}/\d{2}', input_string)
if match:
self.date = datetime.datetime.strptime(match.group(), '%d/%m/%y').date()
else:
self.date = None
self.start=None
self.end=None
match = re.search(r'(?P<start>\d{2}:\d{2}) to (?P<end>\d{2}:\d{2})', input_string)
if match:
self.start = match.group('start')
self.end = match.group('end')
else:
match = re.search(r'(?P<start>\d{2}:\d{2})', input_string)
if match:
self.start = match.group('start')
self.end = self.start
else:
raise ValueError("No Start value found on: {}".format(input_string))
match = re.search(r',\s*(?P<title>.*)', input_string)
self.title=None
if match:
self.title =match.group("title").strip()
if self.title==None:
print("Warning: NO title for {}".format(self))
self.title=""
except AttributeError as err:
print("Exception! On this line:")
print(input_string)
raise err
def start_epoch(self):
time=self.start_datetime()
epoch = time.timestamp()
return epoch
def end_epoch(self):
time=self.end_datetime()
epoch = time.timestamp()
return epoch
def start_datetime(self):
from datetime import datetime
FMT = '%Y-%m-%d%H:%M'
return datetime.strptime(str(self.date) + self.start, FMT)
def end_datetime(self):
if self.end==None:
self.end=self.start
from datetime import datetime
FMT = '%Y-%m-%d%H:%M'
return datetime.strptime(str(self.date) + self.end, FMT)
def get_duration(self):
#from https://stackoverflow.com/a/3096984/170243
from datetime import datetime
FMT = '%H:%M'
tdelta = datetime.strptime(self.end, FMT) - datetime.strptime(self.start, FMT)
return tdelta.total_seconds()/60 #returns in minutes
def __str__(self):
return self.input_string
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
isDuplicate = False
while head.next is not None: #先把前面所有重复的去掉,找到第一个不重复的作为头节点
if head.next.val == head.val:
head = head.next
isDuplicate = True
elif isDuplicate:
head = head.next
isDuplicate = False
else:
break
if head.next is None and isDuplicate: #全都是重复的,只能返回空了
return None
node = head
prev = head
isDuplicate = False
while node.next is not None: #再去掉头节点后面所有重复的节点
if node.next.val == node.val:
prev.next = node.next
isDuplicate = True
elif isDuplicate:
prev.next = node.next
isDuplicate = False
else:
prev = node
node = node.next
if isDuplicate: #最后面的数是重复的
prev.next = None
return head |
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort(); #先排序
length = len(nums);
result = [];
i = 0;
while i < length - 2: #只遍历到倒数第3个数
left = i + 1;
right = length - 1;
now_num = nums[i];
while left != right: #当左指针和右指针相遇的时候结束一轮循环
left_num = nums[left];
right_num = nums[right];
sumLR = left_num + right_num;
if sumLR == -now_num: #三个数的和为0
result.append([now_num,left_num,right_num]);
left += 1; #这个时候左指针右移直到所在位置的数不跟其左边的一样
while left < right and left_num == nums[left]:
left += 1;
while i < length - 1 and now_num == nums[i + 1]:
i += 1; #第一个数的位置也需右移到另一个不一样的数上去
elif sumLR < -now_num: #当三个数的和小于零时,左指针右移
left += 1;
else: #当三个数的和大于零时,右指针左移
right -= 1;
i += 1;
return result; |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
def isSame(nodeA, nodeB):
if nodeA is None:
return nodeB is None
if nodeB is None:
return True
if nodeA.val == nodeB.val and isSame(nodeA.left, nodeB.left) and isSame(nodeA.right, nodeB.right):
return True
return False
if A is None or B is None:
return False
return isSame(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
|
grid = [[0,2]]
def orangesRotting(grid):
recurrent = 0
this_count = 1
target =[[0 for i in range(len(grid[0]))] for z in range(len(grid)) ]
while True:
this_count = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if target[i][j]== 0:
target[i][j] = grid[i][j]
if grid[i][j] == 2:
if i - 1 >= 0:
if grid[i - 1][j] == 1:
target[i - 1][j] = 2
this_count += 1
if i + 1 <= len(grid) - 1:
if grid[i + 1][j] == 1:
target[i + 1][j] = 2
this_count += 1
if j - 1 >= 0:
if grid[i][j - 1] == 1:
target[i][j - 1] = 2
this_count += 1
if j + 1<= len(grid[i]) - 1:
if grid[i][j + 1] == 1:
target[i][j + 1] = 2
this_count += 1
grid = target
target = target =[[0 for i in range(len(grid[0]))] for z in range(len(grid)) ]
if this_count == 0:
for i in range(len(grid)):
if 1 in grid[i]:
return -1
if i == len(grid) - 1:
return recurrent
recurrent += 1
print(orangesRotting(grid)) |
nums = [1,3,5,6]
target = 5
def searchInsert(nums, target):
for i in range(len(nums)):
if nums[i] < target:
continue
return i
return len(nums)
print(searchInsert(nums,target)) |
moves = "UDUDUUDD"
def judgeCircle(moves):
target = list(moves)
level = 0
vertical = 0
for i in target:
if i == 'U':
vertical += 1
if i == 'D':
vertical -= 1
if i == 'L':
level += 1
if i == 'R':
level -= 1
if vertical == 0 and level == 0:
return True
return False
print(judgeCircle(moves)) |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 26 22:31:16 2018
@author: Filip
"""
counter = 0
for i in range(len(s)-2):
if s[i] == "b" and s[i+1] == "o" and s[i+2] == "b":
counter +=1
print("Number of times bob occurs is: " + str(counter)) |
from utils import utils
def two_sum_to_2020(data):
for i in range(len(data)):
for j in range(i,len(data)):
if data[i] + data[j] == 2020:
return data[i]*data[j]
return 0
def three_sum_to_2020(data):
for i in range(len(data)):
for j in range(i,len(data)):
for k in range(j,len(data)):
if data[i] + data[j] + data[k] == 2020:
return data[i]*data[j]*data[k]
return 0
if __name__ == "__main__":
day = 1
data = utils.get_ints_from_file(f"data/aoc{day}_data.txt")
output_1 = two_sum_to_2020(data)
print(output_1)
output_2 = three_sum_to_2020(data)
print(output_2) |
high_guess = 101
low_guess = 0
tries = 1
print("\n\nEnter a number between 1 and 100.")
the_number = int(input("Number: "))
while the_number < 1 or the_number > 100:
print("The number must be between 1 and 100.")
the_number = int(input("Number: "))
guess = 50
print(guess)
while guess != the_number:
if guess > the_number:
high_guess = guess
guess = guess - int((high_guess - low_guess)/2)
else:
low_guess = guess
guess = guess + int((high_guess - low_guess)/2)
tries += 1
print(guess)
print(f"\nThe computer guessed the number in {tries} tries.")
print(f"The number was {the_number}.")
|
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 25 13:03:01 2016
@author: Mark
"""
def song_playlist(songs, max_size):
"""
songs: list of tuples, ('song_name', song_len, song_size)
max_size: float, maximum size of total songs that you can fit
Start with the song first in the 'songs' list, then pick the next
song to be the one with the lowest file size not already picked, repeat
Returns: a list of a subset of songs fitting in 'max_size' in the order
in which they were chosen.
"""
playlist = []
left_on_disk = max_size
if songs[0][2] > left_on_disk:
return []
else:
playlist.append(songs[0][0])
left_on_disk -= songs[0][2]
sorted_remaining_songs = list(songs[1:])
sorted_remaining_songs.sort(key=lambda x: x[2], reverse = False)
for song in sorted_remaining_songs:
if song[2] <= left_on_disk:
playlist.append(song[0])
left_on_disk -= song[2]
return playlist
|
#!/usr/bin/env python
# coding: utf-8
# In[6]:
def validate(x,y):
# x = valeur à tester
# y = type de valeur (t pour taux, m pour montant, a pour années)
try:
float(x)
except:
print("Attention ceci n'est pas une valeur")
return False
else:
if float(x) < 0:
print("Entrez une valuer positive")
return False
if y == "t":
if float(x) > 1:
print("le taux doit être exprimé en décimal, par ex 0.1 pour 10%")
return False
return True
def interet():
a = input("Entrez un capital à investir:")
if validate(a,"m") == True:
a = float(a)
b = input("Entrez un taux d'intérêt:")
if validate(b,"t") == True:
b = float(b)
c = input("Entre une durée de placement souhaitée:")
if validate(c,"a") == True:
c = int(c)
k = a*(1+b)**c
print("Le capital final sera de {:.2f} euro".format(k))
else:
interet()
else:
interet()
else:
interet()
interet()
# In[ ]:
# In[ ]:
|
# implementation of binary search algorithm
# I will prove that binary search is faster than naive search
# Naive search basically search every index iteratively and ask if it is equal to target value
# if array consists the value it returns
# if it is not in the array it returns -1
import random
import time
def naive_search(l, target):
# example l = [1,2,3,4,18]
for i in range(len(l)):
if l[i] == target:
return i
return -1
# binary search uses divide and conquer method
# we will leverage the fact that our list is sorted.
def binary_search(l, target, low=None, high=None):
if low is None:
low = 0
if high is None:
high = len(l) - 1
if high < low:
return -1
midpoint = (low + high) // 2
if l[midpoint] == target:
return midpoint
elif target < l[midpoint]:
return binary_search(l, target, low, midpoint - 1)
else:
# target > l[midpoint]
return binary_search(l, target, midpoint + 1, high)
if __name__ == '__main__':
# l = [1, 15, 25, 60, 79, 90]
# target = 90
# print(naive_search(l, target))
# print(binary_search(l, target))
length = 1000
# build a sorted list of length 1000
sorted_list = set()
while len(sorted_list) < length:
sorted_list.add(random.randint(-3*length, 3 * length))
sorted_list = sorted(list(sorted_list))
start= time.time()
for target in sorted_list:
naive_search(sorted_list, target)
end = time.time()
print("Naive search time :", (end-start)/length, " seconds")
start = time.time()
for target in sorted_list:
binary_search(sorted_list,target)
end = time.time()
print("Binary search time :", (end-start)/length, " seconds")
|
# Задача 2. Дан массив целых чисел. Нужно удалить из него нули. Можно использовать только О(1) дополнительной памяти.
def remove_zeros(arr_input):
ind = 0
while(ind < len(arr_input)): # len() for list has O(1) time complexity
val = arr_input[ind]
if val == 0:
arr_input.remove(val) # list.remove() has O(n) time complexity, O(1) space complexity
else:
ind += 1
if __name__ == '__main__':
array_input = [0, 1, 0, 0, 4, 5, 6, 7, 0, 8, -4, 0]
array_check = [1, 4, 5, 6, 7, 8, -4]
remove_zeros(array_input)
assert array_input == array_check
array_input = [0, 0, 0]
array_check = []
remove_zeros(array_input)
assert array_input == array_check
array_input = []
array_check = []
remove_zeros(array_input)
assert array_input == array_check
array_input = [-1, 2, -3]
array_check = [-1, 2, -3]
remove_zeros(array_input)
assert array_input == array_check
array_input = [0, -1]
array_check = [-1]
remove_zeros(array_input)
assert array_input == array_check
array_input = [-1, 0]
array_check = [-1]
remove_zeros(array_input)
assert array_input == array_check
print('Success!')
|
from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
class Snake:
"""tmp"""
def __init__(self):
self.segments = []
self.create_snake()
self.heading = 0
def create_snake(self):
for position in STARTING_POSITIONS:
self.add_segment(position)
self.head = self.segments[0]
def add_segment(self, position):
segment = Turtle("square")
segment.penup()
segment.color("black", "white")
segment.goto(position)
self.segments.append(segment)
def extend(self):
self.add_segment(self.segments[-1].position())
def move(self):
for segment_nr, segment in reversed(list(enumerate(self.segments))):
if segment_nr == 0:
segment.setheading(self.heading)
segment.forward(MOVE_DISTANCE)
else:
segment.setposition(self.segments[segment_nr - 1].position())
def up(self):
if self.heading != 270:
self.heading = 90
def down(self):
if self.heading != 90:
self.heading = 270
def left(self):
if self.heading != 0:
self.heading = 180
def right(self):
if self.heading != 180:
self.heading = 0
def move_right(self):
for segment_nr, segment in reversed(list(enumerate(self.segments))):
if segment_nr == 0:
segment.right(90)
segment.forward(MOVE_DISTANCE)
else:
segment.setposition(self.segments[segment_nr - 1].position())
|
class Enemy: #by class we mean, hey python, we gonna make a class. Its a common practice of programmers to use first upper case letter to make a class. It helps to differeniae a class from veriable or functions.
life = 3
def attack(selff):
print("Ouuuch, I'm attacked")
selff.life -= 1
def checklife(selfff):
if selfff.life <= 0:
print("Agh, Im fucked up")
else:
print("I'm {} life left".format(selfff.life))
def print(self):
print(self)
##
##enemy1_object = Enemy() #objects are actually a copy of the class
##enemy2_object = Enemy() #we can make as many ibjects as we want and they are independednt of each other.
##
##enemy1_object.attack() #
##enemy1_object.attack() # by running these finctions, the variable in the class(life) will be updated and saved independent.
##enemy1_object.attack() #
##
##enemy1_object.checklife()
##enemy2_object.checklife()
##
#https://www.youtube.com/watch?v=POQIIKb1BZA
'''
self.pt1 = Point(min(pt1.x, pt2.x), min(pt1.y, pt2.y)) ##
self.pt2 = Point(max(pt2.x,pt1.x), max(pt2.y, pt1.y)) ##
'''
|
####ALGORATHIMATIC OPERATORS####
'''
their are seven different algorathimatic operators which are:
+ - * / % ** //
'''
print("5 + 2 =", 5+2)
print("5 - 2 =", 5-2)
print("5 * 2 =", 5*2)
print("5 / 2 =", 5/2)
print("5 ** 2 =", 5**2) #** is called 'power of'
print("5 // 2 =", 5//2) #// is called 'floor division'
####PRINT BY TAKING MULTIPLE STRINGS FROM DIFFERENT LINES####
quote = "Always remember you are unique"
multi_line_quotes = ''' just like
everyone else'''
print('\n')
join_above_two_strings_together = quote + multi_line_quotes
print(join_above_two_strings_together)
print('\n')
print("join_above_two_strings_together =", quote + multi_line_quotes)
print('\n')
print("%s %s %s" % ('I like the quote', quote, multi_line_quotes))
print ("\n" * 5)
print("I dont like ", end="")
print("newlines")
####LIST####
'''list allows to create a list of values and then to manipuate them. And each value is
going to have a index with the first value have index 0.An index is just like a label
to find the location/position of the vakue.'''
grocery_list = ['juice', 'tomatoes', 'potatoes',
"bananas"]
print('First Item', grocery_list [0])
grocery_list[0]='green juice'
print('First Item', grocery_list [0])
print(grocery_list[0:3]) #I just noticed that it prefers the assign value to index 0 (that is green juice) instead of value alredy in the list (that is juice).
#not included value at index 3
other_events = ['wash car', 'pick up kids', 'cash check']
overall_todo_list = [other_events, grocery_list] #combining two list al together
print(overall_todo_list)
print(overall_todo_list[1][2]) #printing one elememt from the subset of a set.
'''different operations we can do in a list
.append, .insert, .remove, .sort, .reverse, del variable
'''
grocery_list.append('onions') #add item at the end
print(overall_todo_list)
grocery_list.insert(1, 'pickle') #add an item at some specific position
print(overall_todo_list)
#overall_todo_list.insert((1)(2), saqib) #dont know how to do this??????????????????????
grocery_list.remove('bananas')
grocery_list.sort()
grocery_list.reverse()
del grocery_list[0]
print(overall_todo_list)
overall_todo_list_2 = overall_todo_list + other_events
print(overall_todo_list_2)
print(len(overall_todo_list_2)) #get the number of items in a list
#print(max(overall_todo_list_2)) #http://stackoverflow.com/questions/14886881/unorderable-types-int-str
print(max(grocery_list)) #maximum item or in this case what comes last alphateically
print(min(grocery_list)) #minimum item or in this case what comes first alphateically
####TUPLES####
'''Tuples are pretty much same as list but the only difference is tuples cant be change once created.
It is beingused normally to creat e a data that we know will remain the same.'''
pi_tuple = (3,1,4,5,3,7,3) #list is inclosed in list brackets[] where as tuples are enclosed in parenthesis()
new_tuple = list(pi_tuple) #convert tuple in to a list
new_tuple = tuple(new_tuple) #convert list into a tuple
print(len(pi_tuple))
print(min(pi_tuple))
print(max(pi_tuple))
|
## CSCI 1300
## Semester Project
## Adam Grabwoski
## Pokemon Elite Four Challenge
import random
hyper_check = False
### How the player and opponents fight each other.
def take_turn(player_active, enemy_active, Moves):
global hyper_check
print()
## Asks the player which move they would like to use from their active pokemon
print("Which move do you want to use? \n")
print(" "+player_active["Moves"][0]+"\n", player_active["Moves"][1]+"\n",player_active["Moves"][2]+"\n",player_active["Moves"][3]+"\n")
move = str(input("Enter name of move: "))
print()
x = True
while x:
if move in Moves:
x = False
else:
move = str(input("Enter name of move: "))
print()
## Player's Turn or enemy's turn first, based on higher speed
if player_active["Speed"] >= enemy_active["Speed"]:
player_went = True
enemy_went = False
player_turn = True
print()
globals()[move](player_turn, player_active, enemy_active)
if enemy_active["HP"]<=0:
return
else:
player_turn = False
player_went = False
enemy_went = True
enemy_move = random.randint(0,3)
if hyper_check == True:
print(enemy_active["Name"], "needs a turn to recharge.")
print()
hyper_check = False
else:
enemy_move2 = enemy_active["Moves"][enemy_move]
globals()[enemy_move2](player_turn, player_active, enemy_active)
if player_active["HP"]<=0:
return
## Player's turn if enemy went first
if player_went != True:
player_turn = True
globals()[move](player_turn, player_active, enemy_active)
if enemy_active["HP"]<=0:
return
## Enemy's Turn if player went first
if enemy_went != True:
player_turn = False
enemy_move = random.randint(0,3)
if hyper_check == True:
print(enemy_active["Name"], "needs a turn to recharge.")
hyper_check = False
else:
enemy_move2 = enemy_active["Moves"][enemy_move]
globals()[enemy_move2](player_turn, player_active, enemy_active)
if player_active["HP"]<=0:
return
else:
player_turn = False
enemy_move = random.randint(0,3)
if hyper_check == True:
print(enemy_active["Name"], "needs a turn to recharge.")
hyper_check = False
else:
enemy_move2 = enemy_active["Moves"][enemy_move]
globals()[enemy_move2](player_turn, player_active, enemy_active)
if player_active["HP"]<=0:
return
############################################################
##################### Defining all the moves
############################################################
### There is a lot of the same here, basically all of the moves that deal damage
### Have a damage calculation, then they check and see if the type of the move
### matches that of the user for a damage bonus, then compares the type of the move
### to the type(s) of the Pokemon getting hit by the move to see if it deals
### any bonus damage or reduced damage.
### Finally, some moves have extra effects besides just dealing damage, and
### some moves do not deal damage at all, but rather modify stats in some way.
def Flamethrower(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Flamethrower!")
print()
damage = int(((22*90*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Fire" in player_active["Type"]:
damage = damage*1.5
if "Rock" in enemy_active["Type"] or"Dragon" in enemy_active["Type"]:
damage = damage*0.5
print()
print("It's not very effective.")
print()
if "Grass" in enemy_active["Type"] or "Bug" in enemy_active["Type"] or "Ice" in enemy_active["Type"]:
damage = damage*2
print()
print("It's Super Effective!")
print()
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Flamethrower!")
print()
else:
print(enemy_active["Name"], "used Flamethrower!")
print()
damage = int(((22*90*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Fire" in enemy_active["Type"]:
damage = damage*1.5
if "Rock" in player_active["Type"] or"Dragon" in player_active["Type"]:
damage = damage*0.5
print()
print("It's not very effective.")
print()
if "Grass" in player_active["Type"] or "Bug" in player_active["Type"] or "Ice" in player_active["Type"]:
damage = damage*2
print()
print("It's Super Effective!")
print()
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from IceBeam!")
def Slash(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Slash!")
print()
if random.randint(1,100)>=50:
print("Critical hit!")
print()
damage = int(2*((22*70*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Rock" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Slash!")
print()
else:
print(player_active["Name"], "used Slash!")
print()
damage = int(((22*70*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Rock" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Slash!")
print()
else:
if random.randint(1,100)>=50:
print(enemy_active["Name"], "used Slash!")
print()
print("Critical hit!")
print()
damage = int(2*((22*70*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Rock" in player_active["Type"]:
damage = damage*0.5
print()
print("It's not very effective.")
print()
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from Slash!")
print()
else:
print(enemy_active["Name"], "used Slash!")
print()
damage = int(((22*70*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from Slash!")
print()
def FireBlast(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used FireBlast!")
print()
hit_chance = random.randint(1,100)
if hit_chance >30:
damage = int(((22*120*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Fire" in player_active["Type"]:
damage = damage*1.5
if "Rock" in enemy_active["Type"] or"Dragon" in enemy_active["Type"]:
damage = damage*0.5
print()
print("It's not very effective.")
print()
if "Grass" in enemy_active["Type"] or "Bug" in enemy_active["Type"] or "Ice" in enemy_active["Type"]:
damage = damage*2
print()
print("It's Super Effective!")
print()
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from FireBlast!")
print()
else:
print("Uh-oh! Looks like FireBlast missed!")
print()
else:
print(enemy_active["Name"], "used FireBlast!")
print()
hit_chance = random.randint(1,100)
if hit_chance >30:
damage = int(((22*120*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Fire" in enemy_active["Type"]:
damage = damage*1.5
if "Rock" in player_active["Type"] or"Dragon" in player_active["Type"]:
damage = damage*0.5
print()
print("It's not very effective.")
print()
if "Grass" in player_active["Type"] or "Bug" in player_active["Type"] or "Ice" in player_active["Type"]:
damage = damage*2
print()
print("It's Super Effective!")
print()
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from FireBlast!")
print()
else:
print("Uh-oh! Looks like FireBlast missed!")
print()
def Strength(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Strength!")
print()
damage = int(((22*80*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Rock" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Strength!")
print()
else:
print(enemy_active["Name"], "used Strength!")
print()
damage = int(((22*80*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Rock" in player_active["Type"]:
damage = damage*0.5
print()
print("It's not very effective.")
print()
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from Strength!")
print()
def Explosion(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Explosion!")
print()
damage = int(((22*150*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Rock" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
enemy_active["HP"] = enemy_active["HP"] - damage
player_active["HP"] = 0
print(enemy_active["Name"], "took", damage, "damage from Explosion!")
print()
print(player_active["Name"], "knocked itself out!")
print()
else:
print(player_active["Name"], "used Explosion!")
print()
damage = int(((22*150*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
player_active["HP"] = player_active["HP"] - damage
enemy_active["HP"] = 0
print(player_active["Name"], "took", damage, "damage from Explosion!")
print()
print(enemy_active["Name"], "knocked itself out!")
print()
def RockSlide(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used RockSlide!")
print()
damage = int(((22*90*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Rock" in player_active["Type"]:
damage = damage*1.5
if "Rock" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Flying" in enemy_active["Type"]:
damage = damage*2
print()
print("It's Super Effective!")
print()
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from RockSlide!")
print()
else:
print(enemy_active["Name"], "used RockSlide!")
print()
damage = int(((22*90*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Rock" in enemy_active["Type"]:
damage = damage*1.5
if "Rock" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Flying" in player_active["Type"]:
damage = damage*2
print()
print("It's Super Effective!")
print()
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from RockSlide!")
print()
def Submission(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Submission!")
print()
damage = int(((22*100*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Fighting" in player_active["Type"]:
damage = damage*1.5
if "Psychic" in enemy_active["Type"] or "Flying" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Rock" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Submission!")
print()
else:
print(enemy_active["Name"], "used Submission!")
print()
damage = int(((22*100*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Fighting" in enemy_active["Type"]:
damage = damage*1.5
if "Psychic" in player_active["Type"] or "Flying" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Rock" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from Submission!")
print()
def MegaPunch(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used MegaPunch!")
print()
damage = int(((22*80*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Fighting" in player_active["Type"]:
damage = damage*1.5
if "Psychic" in enemy_active["Type"] or "Flying" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Rock" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from MegaPunch!")
print()
else:
print(enemy_active["Name"], "used MegaPunch!")
print()
damage = int(((22*80*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Fighting" in enemy_active["Type"]:
damage = damage*1.5
if "Psychic" in player_active["Type"] or "Flying" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Rock" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from MegaPunch!")
print()
def WingAttack(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used WingAttack!")
print()
damage = int(((22*80*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Flying" in player_active["Type"]:
damage = damage*1.5
if "Rock" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Fighting" in enemy_active["Type"] or "Grass" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from WingAttack!")
print()
else:
print(enemy_active["Name"], "used WingAttack!")
print()
damage = int(((22*80*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Flying" in enemy_active["Type"]:
damage = damage*1.5
if "Rock" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Fighting" in player_active["Type"] or "Grass" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from WingAttack!")
print()
def PoisonJab(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used PoisonJab!")
print()
damage = int(((22*80*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Poison" in player_active["Type"]:
damage = damage*1.5
if "Psychic" in enemy_active["Type"] or "Rock" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Grass" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from PoisonJab!")
print()
else:
print(enemy_active["Name"], "used PoisonJab!")
print()
damage = int(((22*80*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Poison" in enemy_active["Type"]:
damage = damage*1.5
if "Psychic" in player_active["Type"] or "Rock" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Grass" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from PoisonJab!")
print()
def Crunch(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Crunch!")
print()
damage = int(((22*80*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Crunch!")
print()
else:
print(enemy_active["Name"], "used Crunch!")
print()
damage = int(((22*80*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from Crunch!")
print()
def MegaKick(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used MegaKick!")
print()
damage = int(((22*80*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Fighting" in player_active["Type"]:
damage = damage*1.5
if "Psychic" in enemy_active["Type"] or "Flying" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Rock" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from MegaKick!")
print()
else:
print(enemy_active["Name"], "used MegaKick!")
print()
damage = int(((22*80*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Fighting" in enemy_active["Type"]:
damage = damage*1.5
if "Psychic" in player_active["Type"] or "Flying" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Rock" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from MegaKick!")
print()
def JumpKick(player_turn, player_active, enemy_active):
if player_turn:
hit_chance = random.randint(1,100)
if hit_chance >30:
print(player_active["Name"], "used JumpKick!")
print()
damage = int(((22*100*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Fighting" in player_active["Type"]:
damage = damage*1.5
if "Psychic" in enemy_active["Type"] or "Flying" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Rock" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from JumpKick!")
print()
else:
print(player_active["Name"], "'s kick kept going and missed!")
print()
player_active["HP"] = player_active["HP"] - 30
print(player_active["Name"], "took 30 damage!")
print()
else:
hit_chance = random.randint(1,100)
if hit_chance >30:
print(enemy_active["Name"], "used JumpKick!")
print()
damage = int(((22*100*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Fighting" in enemy_active["Type"]:
damage = damage*1.5
if "Psychic" in player_active["Type"] or "Flying" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Rock" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from JumpKick!")
print()
else:
print(enemy_active["Name"], "'s kick kept going and missed!")
print()
enemy_active["HP"] = enemy_active["HP"] - 30
print(enemy_active["Name"], "took 30 damage!")
print()
def HiJumpKick(player_turn, player_active, enemy_active):
if player_turn:
hit_chance = random.randint(1,100)
if hit_chance >50:
print(player_active["Name"], "used HiJumpKick!")
print()
damage = int(((22*120*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Fighting" in player_active["Type"]:
damage = damage*1.5
if "Psychic" in enemy_active["Type"] or "Flying" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Rock" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from HiJumpKick!")
print()
else:
print(player_active["Name"], "'s kick kept going and missed!")
print()
player_active["HP"] = player_active["HP"] - 50
print(player_active["Name"], "took 50 damage!")
print()
else:
hit_chance = random.randint(1,100)
if hit_chance >30:
print(enemy_active["Name"], "used HiJumpKick!")
print()
damage = int(((22*120*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Fighting" in enemy_active["Type"]:
damage = damage*1.5
if "Psychic" in player_active["Type"] or "Flying" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Rock" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from HiJumpKick!")
print()
else:
print(enemy_active["Name"], "'s kick kept going and missed!")
print()
enemy_active["HP"] = enemy_active["HP"] - 50
print(enemy_active["Name"], "took 50 damage!")
print()
def IcePunch(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used IcePunch!")
print()
damage = int(((22*80*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Water" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Grass" in enemy_active["Type"] or "Flying" in enemy_active["Type"] or"Dragon" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from IcePunch!")
print()
else:
print(enemy_active["Name"], "used IcePunch!")
print()
damage = int(((22*80*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Water" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Grass" in player_active["Type"] or "Flying" in player_active["Type"] or"Dragon" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from IcePunch!")
print()
def FirePunch(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used FirePunch!")
print()
damage = int(((22*80*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Rock" in enemy_active["Type"] or"Dragon" in enemy_active["Type"]:
damage = damage*0.5
print()
print("It's not very effective.")
print()
if "Grass" in enemy_active["Type"] or "Bug" in enemy_active["Type"] or "Ice" in enemy_active["Type"]:
damage = damage*2
print()
print("It's Super Effective!")
print()
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from FirePunch!")
print()
else:
print(enemy_active["Name"], "used FirePunch!")
print()
damage = int(((22*80*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Rock" in player_active["Type"] or"Dragon" in player_active["Type"]:
damage = damage*0.5
print()
print("It's not very effective.")
print()
if "Grass" in player_active["Type"] or "Bug" in player_active["Type"] or "Ice" in player_active["Type"]:
damage = damage*2
print()
print("It's Super Effective!")
print()
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from FirePunch!")
print()
def ThunderPunch(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used ThunderPunch!")
print()
damage = int(((22*80*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Ground" in enemy_active["Type"] or "Dragon" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Water" in enemy_active["Type"] or "Flying" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from ThunderPunch!")
print()
else:
print(enemy_active["Name"], "used ThunderPunch!")
print()
damage = int(((22*80*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Ground" in player_active["Type"] or "Dragon" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Water" in player_active["Type"] or "Flying" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from ThunderPunch!")
print()
def IceBeam(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used IceBeam!")
print()
damage = int(((22*95*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Ice" in player_active["Type"]:
damage = damage*1.5
if "Water" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Grass" in enemy_active["Type"] or "Flying" in enemy_active["Type"] or"Dragon" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from IceBeam!")
print()
else:
print(enemy_active["Name"], "used IceBeam!")
print()
damage = int(((22*95*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Ice" in enemy_active["Type"]:
damage = damage*1.5
if "Water" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Grass" in player_active["Type"] or "Flying" in player_active["Type"] or"Dragon" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from IceBeam!")
print()
def SludgeBomb(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used SludgeBomb!")
print()
damage = int(((22*95*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Poison" in player_active["Type"]:
damage = damage*1.5
if "Psychic" in enemy_active["Type"] or "Rock" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Grass" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from SludgeBomb!")
print()
else:
print(enemy_active["Name"], "used SludgeBomb!")
print()
damage = int(((22*95*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Poison" in enemy_active["Type"]:
damage = damage*1.5
if "Psychic" in player_active["Type"] or "Rock" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Grass" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from SludgeBomb!")
print()
def BodySlam(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used BodySlam!")
print()
damage = int(((22*80*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Rock" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from BodySlam!")
print()
else:
print(enemy_active["Name"], "used BodySlam!")
print()
damage = int(((22*80*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Rock" in player_active["Type"]:
damage = damage*0.5
print()
print("It's not very effective.")
print()
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from BodySlam!")
print()
def HyperBeam(player_turn, player_active, enemy_active):
global hyper_check
if player_turn:
print(player_active["Name"], "used HyperBeam!")
print()
damage = int(((22*150*player_active["Attack"]/enemy_active["Defense"])/50)+random.randint(1,6))
if "Rock" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from HyperBeam!")
print()
hyper_check = True
else:
print(enemy_active["Name"], "used HyperBeam!")
print()
damage = int(((22*150*enemy_active["Attack"]/player_active["Defense"])/50)+random.randint(1,6))
if "Rock" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from HyperBeam!")
print()
#global hyper_check
hyper_check = True
def Blizzard(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Blizzard!")
print()
hit_chance = random.randint(1,100)
if hit_chance >30:
damage = int(((22*120*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Ice" in player_active["Type"]:
damage = damage*1.5
if "Water" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Grass" in enemy_active["Type"] or "Flying" in enemy_active["Type"] or"Dragon" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Blizzard!")
print()
else:
print("Uh-oh! Looks like Blizzard missed!")
print()
else:
print(enemy_active["Name"], "used Blizzard!")
print()
hit_chance = random.randint(1,100)
if hit_chance >30:
damage = int(((22*120*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Ice" in enemy_active["Type"]:
damage = damage*1.5
if "Water" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Grass" in player_active["Type"] or "Flying" in player_active["Type"] or"Dragon" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from Blizzard!")
print()
else:
print("Uh-oh! Looks like Blizzard missed!")
print()
def HydroPump(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used HydroPump!")
print()
hit_chance = random.randint(1,100)
if hit_chance >30:
damage = int(((22*120*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Water" in player_active["Type"]:
damage = damage*1.5
if "Water" in enemy_active["Type"] or "Dragon" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Fire" in enemy_active["Type"] or "Rock" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from HydroPump!")
print()
else:
print("Uh-oh! Looks like HydroPump missed!")
print()
else:
print(enemy_active["Name"], "used HydroPump!")
print()
hit_chance = random.randint(1,100)
if hit_chance >30:
damage = int(((22*120*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Water" in enemy_active["Type"]:
damage = damage*1.5
if "Water" in player_active["Type"] or "Dragon" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Fire" in player_active["Type"] or "Rock" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from HydroPump!")
print()
else:
print("Uh-oh! Looks like HydroPump missed!")
print()
def Thunder(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Thunder!")
print()
hit_chance = random.randint(1,100)
if hit_chance >30:
damage = int(((22*120*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Electric" in player_active["Type"]:
damage = damage*1.5
if "Ground" in enemy_active["Type"] or "Dragon" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Water" in enemy_active["Type"] or "Flying" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Thunder!")
print()
else:
print("Uh-oh! Looks like Thunder missed!")
print()
else:
print(enemy_active["Name"], "used Thunder!")
print()
hit_chance = random.randint(1,100)
if hit_chance >30:
damage = int(((22*120*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Electric" in enemy_active["Type"]:
damage = damage*1.5
if "Ground" in player_active["Type"] or "Dragon" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Water" in player_active["Type"] or "Flying" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from Thunder!")
print()
else:
print("Uh-oh! Looks like Thunder missed!")
print()
def Surf(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Surf!")
print()
damage = int(((22*90*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Water" in player_active["Type"]:
damage = damage*1.5
if "Water" in enemy_active["Type"] or "Dragon" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Fire" in enemy_active["Type"] or "Rock" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Surf!")
print()
else:
print(enemy_active["Name"], "used Surf!")
print()
damage = int(((22*90*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Water" in enemy_active["Type"]:
damage = damage*1.5
if "Water" in player_active["Type"] or "Dragon" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Fire" in player_active["Type"] or "Rock" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from Surf!")
print()
def ShadowBall(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used ShadowBall!")
print()
damage = int(((22*90*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Ghost" in player_active["Type"]:
damage = damage*1.5
if "Normal" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Ghost" in enemy_active["Type"] or "Psychic" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from ShadowBall!")
print()
else:
print(enemy_active["Name"], "used ShadowBall!")
print()
damage = int(((22*90*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Ghost" in enemy_active["Type"]:
damage = damage*1.5
if "Normal" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Ghost" in player_active["Type"] or "Psychic" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from ShadowBall!")
print()
def NightShade(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used NightShade!")
print()
enemy_active["HP"] = enemy_active["HP"] - 50
print(enemy_active["Name"], "took 50 damage from NightShade!")
print()
else:
print(enemy_active["Name"], "used NightShade!")
print()
player_active["HP"] = player_active["HP"] - 50
print(player_active["Name"], "took 50 damage from NightShade!")
print()
def DragonRage(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used DragonRage!")
print()
enemy_active["HP"] = enemy_active["HP"] - 40
print(enemy_active["Name"], "took 40 damage from DragonRage!")
print()
else:
print(enemy_active["Name"], "used DragonRage!")
print()
player_active["HP"] = player_active["HP"] - 40
print(player_active["Name"], "took 40 damage from DragonRage!")
print()
def Thunderbolt(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Thunderbolt!")
print()
damage = int(((22*95*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Electric" in player_active["Type"]:
damage = damage*1.5
if "Ground" in enemy_active["Type"] or "Dragon" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Water" in enemy_active["Type"] or "Flying" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Thunderbolt!")
print()
else:
print(enemy_active["Name"], "used Thunderbolt!")
print()
damage = int(((22*95*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Electric" in enemy_active["Type"]:
damage = damage*1.5
if "Ground" in player_active["Type"] or "Dragon" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Water" in player_active["Type"] or "Flying" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from Thunderbolt!")
print()
def SolarBeam(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used SolarBeam!")
print()
print(player_active["Name"], "absorbed sunlight!")
print()
damage = int(((22*100*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Grass" in player_active["Type"]:
damage = damage*1.5
if "Grass" in enemy_active["Type"] or "Dragon" in enemy_active["Type"] or "Fire" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Water" in enemy_active["Type"] or "Rock" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from SolarBeam!")
print()
else:
print(enemy_active["Name"], "used SolarBeam!")
print()
print(enemy_active["Name"], "absorbed sunlight!")
print()
damage = int(((22*100*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Grass" in enemy_active["Type"]:
damage = damage*1.5
if "Grass" in player_active["Type"] or "Dragon" in player_active["Type"] or "Fire" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Water" in player_active["Type"] or "Rock" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from SolarBeam!")
print()
def Psychic(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Psychic!")
print()
damage = int(((22*90*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Psychic" in player_active["Type"]:
damage = damage*1.5
if "Psychic" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Fighting" in enemy_active["Type"] or "Poison" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Psychic!")
print()
else:
print(enemy_active["Name"], "used Psychic!")
print()
damage = int(((22*90*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Psychic" in enemy_active["Type"]:
damage = damage*1.5
if "Psychic" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Fighting" in player_active["Type"] or "Poison" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from Psychic!")
print()
def Psybeam(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Psybeam!")
print()
damage = int(((22*60*player_active["Special"]/enemy_active["Special"])/50)+random.randint(1,6))
if "Psychic" in player_active["Type"]:
damage = damage*1.5
if "Psychic" in enemy_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Fighting" in enemy_active["Type"] or "Poison" in enemy_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
enemy_active["HP"] = enemy_active["HP"] - damage
print(enemy_active["Name"], "took", damage, "damage from Psybeam!")
print()
else:
print(enemy_active["Name"], "used Psybeam!")
print()
damage = int(((22*60*enemy_active["Special"]/player_active["Special"])/50)+random.randint(1,6))
if "Psychic" in enemy_active["Type"]:
damage = damage*1.5
if "Psychic" in player_active["Type"]:
print()
print("It's not very effective.")
print()
damage = damage*0.5
if "Fighting" in player_active["Type"] or "Poison" in player_active["Type"]:
print()
print("It's Super Effective!")
print()
damage = damage*2
player_active["HP"] = player_active["HP"] - damage
print(player_active["Name"], "took", damage, "damage from Psybeam!")
print()
def Reflect(player_turn, player_active, enemy_active):
if player_turn:
if player_active["Defense"]>=300:
print(player_active["Name"], "'s Defense is already too high! No effect!")
print()
else:
print(player_active["Name"], "used Reflect!")
print()
player_active["Defense"] = player_active["Defense"]*1.5
print(player_active["Name"], "raised their Defense!")
print()
else:
if enemy_active["Defense"]>=300:
print(enemy_active["Name"], "'s Defense is already too high! No effect!")
print()
else:
print(enemy_active["Name"], "used Reflect!")
print()
enemy_active["Defense"] = enemy_active["Defense"]*1.5
print(enemy_active["Name"], "raised their Defense!")
print()
def Agility(player_turn, player_active, enemy_active):
if player_turn:
if player_active["Speed"]>=300:
print(player_active["Name"], "'s Speed is already too high! No effect!")
print()
else:
print(player_active["Name"], "used Agility!")
print()
player_active["Speed"] = player_active["Speed"]*1.5
print(player_active["Name"], "raised their Speed!")
print()
else:
if enemy_active["Speed"]>=300:
print(enemy_active["Name"], "'s Speed is already too high! No effect!")
print()
else:
print(enemy_active["Name"], "used Agility!")
print()
enemy_active["Speed"] = enemy_active["Speed"]*1.5
print(enemy_active["Name"], "raised their Speed!")
print()
def Screech(player_turn, player_active, enemy_active):
if player_turn:
if enemy_active["Defense"]<=15:
print(enemy_active["Name"], "'s defense is already too low! No effect!")
print()
else:
print(player_active["Name"], "used Screech!")
print()
enemy_active["Defense"] = enemy_active["Defense"]*0.5
print(enemy_active["Name"], "'s Defense was lowered!")
print()
else:
if player_active["Defense"]<=15:
print(player_active["Name"], "'s Defense is already too low! No effect!")
print()
else:
print(enemy_active["Name"], "used Screech!")
print()
player_active["Defense"] = player_active["Defense"]*0.5
print(player_active["Name"], "'s Defense was lowered!")
print()
def Fissure(player_turn, player_active, enemy_active):
if player_turn:
print(player_active["Name"], "used Fissure!")
print()
hit_chance = random.randint(1,100)
if hit_chance >30:
print("Fissure missed!")
print()
else:
print("The Fissure swallowed", enemy_active["Name"], "whole!")
print()
enemy_active["HP"] = 0
else:
print(enemy_active["Name"], "used Fissure!")
print()
hit_chance = random.randint(1,100)
if hit_chance >30:
print("Fissure missed!")
print()
else:
print("The Fissure swallowed", player_active["Name"], "whole!")
print()
player_active["HP"] = 0
############################################################
##################### Defining the items
############################################################
### Inititally I was going to add in all the items from the game,
### but quite frankly, most of them are useless when you get to this final
### stage. Instead, I only added the best items that people would actually
### choose to purchase anyway if they were experienced with the game.
def HyperPotion(Charizard,Alakazam,Blastoise,Venusaur,Jolteon,Lapras_P, hyper_potions):
print()
print("Who would you like to use Hyper Potion on? ")
print()
lyst = []
if Charizard["Feint"]==False:
print(Charizard["Name"], "'s HP = ", Charizard["HP"],'/',Charizard["Max HP"])
lyst.append("Charizard")
if Alakazam["Feint"]==False:
print(Alakazam["Name"], "'s HP = ", Alakazam["HP"],'/',Alakazam["Max HP"])
lyst.append("Alakazam")
if Blastoise["Feint"]==False:
print(Blastoise["Name"], "'s HP = ", Blastoise["HP"],'/',Blastoise["Max HP"])
lyst.append("Blastoise")
if Venusaur["Feint"]==False:
print(Venusaur["Name"], "'s HP = ", Venusaur["HP"],'/',Venusaur["Max HP"])
lyst.append("Venusaur")
if Jolteon["Feint"]==False:
print(Jolteon["Name"], "'s HP = ", Jolteon["HP"],'/',Jolteon["Max HP"])
lyst.append("Jolteon")
if Lapras_P["Feint"]==False:
print(Lapras_P["Name"], "'s HP = ", Lapras_P["HP"],'/',Lapras_P["Max HP"])
lyst.append("Lapras")
print()
hyperp = str(input("Enter the Pokemon to use Hyper Potion on or 'cancel' to cancel: "))
print()
z = True
while z:
if hyperp == 'cancel' or hyperp == 'Cancel':
return
if hyperp in lyst:
z = False
return hyperp
else:
print("Who would you like to use Hyper Potion on? ")
print()
hyperp = str(input("Enter the Pokemon to use Hyper Potion on or 'cancel' to cancel: "))
print()
def Revive(Charizard,Alakazam,Blastoise,Venusaur,Jolteon,Lapras_P, revives):
lyst = []
if Charizard["Feint"]==True:
lyst.append("Charizard")
if Alakazam["Feint"]==True:
lyst.append("Alakazam")
if Blastoise["Feint"]==True:
lyst.append("Blastoise")
if Venusaur["Feint"]==True:
lyst.append("Venusaur")
if Jolteon["Feint"]==True:
lyst.append("Jolteon")
if Lapras_P["Feint"]==True:
lyst.append("Lapras")
if len(lyst)==0:
print()
return "Failed"
else:
print()
print("Who would you like to revive? ")
print()
for i in range(len(lyst)):
print(lyst[i])
print()
revive = str(input("Enter the Pokemon to revive: "))
print()
z = True
while z:
if revive in lyst:
z = False
return revive
else:
print("Who would you like to revive? ")
print()
revive = str(input("Enter the Pokemon to revive: "))
print()
def main():
global hyper_check
## Player's Team
Moves = {"Flamethrower":Flamethrower, "FireBlast":FireBlast, "Slash":Slash, "Strength":Strength ,"Psychic":Psychic, "Thunderbolt": Thunderbolt,'ShadowBall':ShadowBall, "Reflect":Reflect, "Psybeam":Psybeam, "Blizzard":Blizzard, "IceBeam":IceBeam, "Thunder":Thunder, "SludgeBomb":SludgeBomb, "SolarBeam":SolarBeam, "Surf":Surf, "HydroPump":HydroPump, "BodySlam":BodySlam }
Charizard = {"Name":"Charizard", "Type":"FireFlying" , "Max HP":78, "HP":78, "Attack":84, "Defense": 78, "Special":85, "Speed": 100, "Moves":['Flamethrower', 'Strength', 'Slash', "FireBlast"],"Feint":False}
#Gengar = {"Name":"Gengar", "Type":"GhostPoison" ,"HP":60, "Attack":65, "Defense": 60, "Special":130, "Speed": 110, "Moves":['ShadowBall', 'Psychic', 'Thunderbolt', "BodySlam"]}
Alakazam = {"Name":"Alakazam", "Type":"Psychic" ,"Max HP":55, "HP":55, "Attack":50, "Defense": 45, "Special":135, "Speed": 120, "Moves":['Reflect', 'Psychic', 'Thunderbolt', "Psybeam"],"Feint":False}
Blastoise = {"Name":"Blastoise","Type":"Water" ,"Max HP":79, "HP":79, "Attack":83, "Defense": 100, "Special":85, "Speed": 78, "Moves":['HydroPump', 'Strength', 'Surf', "Reflect"],"Feint":False}
Venusaur = {"Name":"Venusaur","Type":"GrassPoison" ,"Max HP":80, "HP":80, "Attack":82, "Defense": 83, "Special":100, "Speed": 80, "Moves":['SolarBeam', 'SludgeBomb', 'BodySlam', "Reflect"],"Feint":False}
Jolteon = {"Name":"Jolteon","Type":"Electric" ,"Max HP":65, "HP":65, "Attack":65, "Defense": 60, "Special":110, "Speed": 130, "Moves":['Thunderbolt', 'Reflect', 'Slash', "Thunder"],"Feint":False}
Lapras_P = {"Name":"Lapras","Type":"WaterIce" ,"Max HP":130, "HP":130, "Attack":85, "Defense": 80, "Special":95, "Speed": 60, "Moves":['IceBeam', 'BodySlam', 'Blizzard', "HydroPump"],"Feint":False}
## Lorelei's Team
Dewgong = {"Name":"Dewgong","Type":"WaterIce" ,"HP":90, "Attack":70, "Defense": 80, "Special":95, "Speed": 70, "Moves":['IceBeam', 'BodySlam', 'Blizzard', "Surf"]}
Cloyster = {"Name":"Cloyster","Type":"WaterIce" ,"HP":50, "Attack":95, "Defense": 180, "Special":85, "Speed": 70, "Moves":['IceBeam', 'BodySlam', 'Reflect', "Surf"]}
Slowbro = {"Name":"Slobrow","Type":"WaterPsychic" ,"HP":95, "Attack":75, "Defense": 100, "Special":80, "Speed": 30, "Moves":['Psychic', 'Strength', 'BodySlam', "Surf"]}
Jinx = {"Name":"Jinx","Type":"PsychicIce" ,"HP":65, "Attack":50, "Defense": 35, "Special":95, "Speed": 95, "Moves":['Slash', 'IceBeam', 'Psychic', "BodySlam"]}
Lapras_L = {"Name":"Lapras","Type":"WaterIce" ,"HP":130, "Attack":85, "Defense": 80, "Special":95, "Speed": 60, "Moves":['IceBeam', 'BodySlam', 'Blizzard', "HydroPump"]}
## Bruno's Team
Onyx = {"Name":"Onyx","Type":"RockGround" ,"HP":35, "Attack":45, "Defense": 130, "Special":30, "Speed": 70, "Moves":['BodySlam', 'RockSlide', 'Reflect', "Strength"]}
Hitmonchan = {"Name":"Hitmonchan","Type":"Fighting" ,"HP":50, "Attack":104, "Defense": 79, "Special":35, "Speed": 76, "Moves":['MegaPunch', 'IcePunch', 'FirePunch', "ThunderPunch"]}
Hitmonlee = {"Name":"Hitmonlee","Type":"Fightin" ,"HP":50, "Attack":120, "Defense": 53, "Special":35, "Speed": 87, "Moves":['JumpKick', 'HiJumpKick', 'MegaKick', "Strength"]}
Golem = {"Name":"Golem","Type":"RockGround" ,"HP":80, "Attack":100, "Defense": 130, "Special":55, "Speed": 45, "Moves":['Explosion', 'RockSlide', 'Reflect', "Strength"]}
Machamp = {"Name":"Machamp","Type":"Fighting" ,"HP":90, "Attack":130, "Defense": 80, "Special":65, "Speed": 55, "Moves":['Strength', 'Submission', 'BodySlam', "Fissure"]}
## Agatha's Team
Gengar_A1 = {"Name":"Gengar", "Type":"GhostPoison" ,"HP":60, "Attack":65, "Defense": 60, "Special":130, "Speed": 110, "Moves":['ShadowBall', 'Psychic', 'Thunderbolt', "BodySlam"]}
Golbat = {"Name":"Golbat","Type":"PoisonFlying" ,"HP":75, "Attack":80, "Defense": 70, "Special":75, "Speed": 90, "Moves":['BodySlam', 'PoisonJab', 'Reflect', "WingAttack"]}
Haunter = {"Name":"Haunter","Type":"GhostPoison" ,"HP":45, "Attack":50, "Defense": 450, "Special":115, "Speed": 95, "Moves":['ShadowBall', 'NightShade', 'Fissure', "MegaPunch"]}
Arbok = {"Name":"Arbok","Type":"Poison" ,"HP":60, "Attack":85, "Defense": 69, "Special":65, "Speed": 80, "Moves":['BodySlam', 'Screech', 'Crunch', "SludgeBomb"]}
Gengar_A2 = {"Name":"Gengar", "Type":"GhostPoison" ,"HP":60, "Attack":65, "Defense": 60, "Special":130, "Speed": 110, "Moves":['ShadowBall', 'Psychic', 'Thunderbolt', "BodySlam"]}
## Lance's Team
Gyarados = {"Name":"Gyarados", "Type":"WaterFlying" ,"HP":95, "Attack":125, "Defense": 79, "Special":100, "Speed": 81, "Moves":['HydroPump', 'Screech', 'DragonRage', "HyperBeam"]}
Dragonair_L1 = {"Name":"Dragonair", "Type":"Dragon" ,"HP":61, "Attack":84, "Defense": 65, "Special":70, "Speed": 70, "Moves":['BodySlam', 'Agility', 'DragonRage', "HyperBeam"]}
Dragonair_L2 = {"Name":"Dragonair", "Type":"Dragon" ,"HP":61, "Attack":84, "Defense": 65, "Special":70, "Speed": 70, "Moves":['BodySlam', 'Agility', 'DragonRage', "HyperBeam"]}
Aerodactyl = {"Name":"Aerodactyl", "Type":"RockFlying" ,"HP":80, "Attack":105, "Defense": 65, "Special":60, "Speed": 130, "Moves":['RockSlide', 'Agility', 'Crunch', "HyperBeam"]}
Dragonite = {"Name":"Dragonite", "Type":"DragonFlying" ,"HP":91, "Attack":134, "Defense": 95, "Special":100, "Speed": 80, "Moves":['BodySlam', 'Reflect', 'Agility', "HyperBeam"]}
## Items that can be purchased:
revives = 0
hyper_potions = 0
money = 25500
player_team = [True, Charizard, Alakazam, Blastoise, Venusaur, Jolteon, Lapras_P]
EliteFour = {"Lorelei":["Lorelei",True, Dewgong, Cloyster, Slowbro, Jinx, Lapras_L], "Bruno":["Bruno", True, Onyx, Hitmonchan, Hitmonlee, Golem, Machamp], "Agatha":["Agatha", True, Gengar_A1, Golbat,Haunter,Arbok, Gengar_A2 ], "Lance":["Lance", True, Gyarados, Dragonair_L1, Dragonair_L2, Aerodactyl, Dragonite]}
enemy_team = EliteFour["Lorelei"]
current_player = 1
body_count = 0
player_active = player_team[current_player]
current_enemy = 2
enemy_active = enemy_team[current_enemy]
### Introduction
print("Welcome young Pokemon Trainer to the Indigo Plateau!")
print()
print("Your long journey has lead you here: to battle the Elite Four!")
print()
print("You must defeat all four master trainers in succession.")
print()
print("Once you enter, you cannot leave until you emerge victorious or are defeated.")
print()
print()
print("Your team currently is: ")
print()
print(" Charizard")
print(" Alakazam")
print(" Blastoise")
print(" Venusaur")
print(" Jolteon")
print(" Lapras")
print()
print("Thus far in your journey you have collected:", money, "dollars. You now have the chance to spend your hard earned cash!")
print("I was going to offer you more options, but let's get real! No one buys anything other than Revives and Hyper Potions anyway!")
print()
print("Hyper Potions heal your Pokemon if they take damage and Revives will allow them to fight again if they feint.")
print()
print()
## Purchasing Items
i = True
while i:
print()
print("What would you like to buy?")
print()
print(" Revive: $1500")
print(" Hyper Potion: $1500")
print()
print("Remaining Money:", money)
purchase = str(input("Enter the item you would like to purchase or 'done' to move on: "))
if purchase == "Revive" or purchase == 'revive':
print()
print("How many Revives would you like to buy?")
print("(Type in a Roman Numeral, please.)")
print()
x = True
while x:
purchase = str(input("Enter how many Revives would you like to purchase or 'back' to go back: "))
if purchase == 'back' or purchase == 'Back':
x = False
if purchase != "back" and purchase != "Back":
purchase = int(purchase)
if purchase *1500<=money:
revives = revives + purchase
money = money - 1500*purchase
print()
print("Thanks! You now have:", revives, "Revives and", hyper_potions, "Hyper Potions.")
print()
print("You have", money, "dollars left. Spend it wisely!")
print()
x = False
else:
print()
print("You can't afford all that!")
print()
if purchase == "Hyper Potion" or purchase == 'hyper potion':
print()
print("How many Hyper Potions would you like to buy?")
print("(Type in a Roman Numeral, please.)")
x = True
while x:
purchase = str(input("Enter how many Hyper Potions you would like to purchase or 'back' to go back: "))
if purchase == 'back' or purchase == 'Back':
x = False
if purchase != "back" and purchase != "Back":
purchase = int(purchase)
if purchase *1500<=money:
hyper_potions = hyper_potions + purchase
money = money - 1500*purchase
print("Thanks! You now have:", revives, "Revives and", hyper_potions, "Hyper Potions.")
print()
print("You have", money, "dollars left. Spend it wisely!")
print()
x = False
else:
print("You can't afford all that!")
print()
if purchase == 'done' or purchase == 'Done':
i = False
## Introduction Cont.
print()
print()
print()
print()
print("You should use these in between battles to keep your team in fighting shape!")
print()
print("Prepare yourself trainer! Your first opponent is the icy mistress: Lorelei!")
print()
print()
print()
print("Lorelei sends out her first Pokemon: Dewgong!")
print()
print("You send our your first Pokemon!")
print()
print("Charizard! Go!")
print()
## Battling Lorelei
while EliteFour["Lorelei"][1] == True:
while player_active["HP"]>0 and enemy_active["HP"]>0:
take_turn(player_active, enemy_active, Moves)
if player_active["HP"]<=0:
if body_count < 5:
print()
print(player_active["Name"], "has feinted!")
player_active["Feint"]=True
print("Send in your next Pokemon!")
print()
lyst = []
if Charizard["Feint"]==False:
lyst.append("Charizard")
if Alakazam["Feint"]==False:
lyst.append("Alakazam")
if Blastoise["Feint"]==False:
lyst.append("Blastoise")
if Venusaur["Feint"]==False:
lyst.append("Venusaur")
if Jolteon["Feint"]==False:
lyst.append("Jolteon")
if Lapras_P["Feint"]==False:
lyst.append("Lapras")
print()
for i in range(len(lyst)):
print(lyst[i])
print()
print("Who would you like to send in? ")
print()
switch = str(input("Enter next Pokemon: "))
z = True
while z:
if switch in lyst:
if switch == "Charizard":
current_player = 1
if switch == "Alakazam":
current_player = 2
if switch == "Blastoise":
current_player = 3
if switch == "Venusaur":
current_player = 4
if switch == "Jolteon":
current_player = 5
if switch == "Lapras":
current_player = 6
z = False
else:
print("Who would you like to send in? ")
print()
switch = str(input("Enter next Pokemon: "))
body_count = body_count + 1
player_active = player_team[current_player]
print()
print("Go,",player_active["Name"],"!" )
print()
else:
player_team[0] = False
EliteFour["Lorelei"][1] = False
if enemy_active["HP"]<=0:
if current_enemy < len(EliteFour["Lorelei"])-1:
print()
print(enemy_active["Name"], "has feinted!")
print()
print( "Lorelei will send in her next Pokemon:")
print()
current_enemy = current_enemy+1
enemy_active = enemy_team[current_enemy]
print(enemy_active["Name"], "!")
print()
else:
print()
print(enemy_active["Name"], "has feinted!")
print()
EliteFour["Lorelei"][1] = False
if player_team[0] == False:
print("You have run out of Pokemon!")
player_team[0] = False
print()
print("Better luck next time.")
return
if EliteFour["Lorelei"][1] == False:
print("Lorelei has been defeated!")
print()
print()
enemy_team = EliteFour["Bruno"]
current_enemy = 2
enemy_active = enemy_team[current_enemy]
print()
print("Now you must face the mighty Bruno!")
print()
print("Would you like to use any items?")
print()
items = str(input("Enter 'Yes' or 'No': "))
z = True
while z:
if items == 'yes' or items == "Yes":
print("Which item do you want to use? \n")
print(" Hyper Potion......x",str(hyper_potions)+"\n","Revive......x",str(revives)+"\n" )
item = str(input("Enter the item: "))
print()
x = True
while x:
if item == "Revive" or item == "revive":
revive = Revive(Charizard, Alakazam, Blastoise, Venusaur, Jolteon, Lapras_P, revives)
if revive == "Failed":
print("None of your Pokemon have fainted!")
print()
if revive == "Charizard":
Charizard["Feint"]=False
Charizard["HP"]=Charizard["Max HP"]//2
print("Charizard has been revived!")
print()
revives = revives - 1
if revive == "Alakazam":
Alakazam["Feint"]=False
Alakazam["HP"]=Alakazam["Max HP"]//2
print("Alakazam has been revived!")
print()
revives = revives - 1
if revive == "Blastoise":
Blastoise["Feint"]=False
Blastoise["HP"]=Blastoise["Max HP"]//2
print("Blastoise has been revived!")
print()
revives = revives - 1
if revive == "Venusaur":
Venusaur["Feint"]=False
Venusaur["HP"]=Venusaur["Max HP"]//2
print("Venusaur has been revived!")
print()
revives = revives - 1
if revive == "Jolteon":
Jolteon["Feint"]=False
Jolteon["HP"]=Jolteon["Max HP"]//2
print("Jolteon has been revived!")
print()
revives = revives - 1
if revive == "Lapras":
Lapras_P["Feint"]=False
Lapras_P["HP"]=Lapras_P["Max HP"]//2
print("Lapras has been revived!")
print()
revives = revives - 1
x = False
elif item == "Hyper Potion" or item == "hyper potion":
if Charizard["HP"]==Charizard["Max HP"] and Lapras_P["HP"]==Lapras_P["Max HP"] and Blastoise["HP"]==Blastoise["Max HP"] and Alakazam["HP"]==Alakazam["Max HP"] and Venusaur["HP"]==Venusaur["Max HP"] and Jolteon["HP"]==Jolteon["Max HP"]:
print("All of your Pokemon are at full health!")
print()
else:
hyperp = HyperPotion(Charizard, Alakazam, Blastoise, Venusaur, Jolteon, Lapras_P, revives)
if hyperp == "Charizard":
Charizard["HP"]=Charizard["HP"]+100
hyper_potions = hyper_potions - 1
if Charizard["HP"]>=Charizard["Max HP"]:
Charizard["HP"]=Charizard["Max HP"]
print("Charizard has been fully healed!")
print()
else:
print("Charizard has been healed 100 HP!")
print()
print("Charizard's current HP is: ", Charizard["HP"])
print()
if hyperp == "Alakazam":
Alakazam["HP"]=Alakazam["HP"]+100
hyper_potions = hyper_potions - 1
if Alakazam["HP"]>=Alakazam["Max HP"]:
Alakazam["HP"]=Alakazam["Max HP"]
print("Alakazam has been fully healed!")
print()
else:
print("Alakazam has been healed 100 HP!")
print()
print("Alakazam's current HP is: ", Alakazam["HP"])
print()
if hyperp == "Blastoise":
Blastoise["HP"]=Blastoise["HP"]+100
hyper_potions = hyper_potions - 1
if Blastoise["HP"]>=Blastoise["Max HP"]:
Blastoise["HP"]=Blastoise["Max HP"]
print("Blastoise has been fully healed!")
print()
else:
print("Blastoise has been healed 100 HP!")
print()
print("Blastoise's current HP is: ", Blastoise["HP"])
print()
if hyperp == "Venusaur":
Venusaur["HP"]=Venusaur["HP"]+100
hyper_potions = hyper_potions - 1
if Venusaur["HP"]>=Venusaur["Max HP"]:
Venusaur["HP"]=Venusaur["Max HP"]
print("Venusaur has been fully healed!")
print()
else:
print("Venusaur has been healed 100 HP!")
print()
print("Venusaur's current HP is: ", Venusaur["HP"])
print()
if hyperp == "Jolteon":
Jolteon["HP"]=Jolteon["HP"]+100
hyper_potions = hyper_potions - 1
if Jolteon["HP"]>=Jolteon["Max HP"]:
Jolteon["HP"]=Jolteon["Max HP"]
print("Jolteon has been fully healed!")
print()
else:
print("Jolteon has been healed 100 HP!")
print()
print("Jolteon's current HP is: ", Jolteon["HP"])
print()
if hyperp == "Lapras":
Lapras_P["HP"]=Lapras_P["HP"]+100
hyper_potions = hyper_potions - 1
if Lapras_P["HP"]>=Lapras_P["Max HP"]:
Lapras_P["HP"]=Lapras_P["Max HP"]
print("Lapras has been fully healed!")
print()
else:
print("Lapras has been healed 100 HP!")
print()
print("Lapras's current HP is: ", Lapras_P["HP"])
print()
x = False
else:
item = str(input("Enter the item: "))
print()
if items == "No" or items == 'no':
z = False
else:
print()
items = str(input("Do you want to use an item? "))
print()
print("Prepare yourself!")
print()
print()
print("Bruno sends out his first Pokemon: Onyx!")
print()
## Battling Bruno
while EliteFour["Bruno"][1] == True:
while player_active["HP"]>0 and enemy_active["HP"]>0:
take_turn(player_active, enemy_active, Moves)
if player_active["HP"]<=0:
if body_count < 5:
print()
print(player_active["Name"], "has feinted!")
player_active["Feint"]=True
print("Send in your next Pokemon!")
print()
lyst = []
if Charizard["Feint"]==False:
lyst.append("Charizard")
if Alakazam["Feint"]==False:
lyst.append("Alakazam")
if Blastoise["Feint"]==False:
lyst.append("Blastoise")
if Venusaur["Feint"]==False:
lyst.append("Venusaur")
if Jolteon["Feint"]==False:
lyst.append("Jolteon")
if Lapras_P["Feint"]==False:
lyst.append("Lapras")
print()
for i in range(len(lyst)):
print(lyst[i])
print()
print("Who would you like to send in? ")
print()
switch = str(input("Enter next Pokemon: "))
print()
z = True
while z:
if switch in lyst:
if switch == "Charizard":
current_player = 1
if switch == "Alakazam":
current_player = 2
if switch == "Blastoise":
current_player = 3
if switch == "Venusaur":
current_player = 4
if switch == "Jolteon":
current_player = 5
if switch == "Lapras":
current_player = 6
z = False
else:
print("Who would you like to send in? ")
print()
switch = str(input("Enter next Pokemon: "))
body_count = body_count + 1
player_active = player_team[current_player]
print()
print("Go,",player_active["Name"],"!" )
print()
else:
player_team[0] = False
EliteFour["Bruno"][1] = False
if enemy_active["HP"]<=0:
if current_enemy < len(EliteFour["Bruno"])-1:
print()
print(enemy_active["Name"], "has feinted!")
print()
print( "Bruno will send in his next Pokemon:")
print()
current_enemy = current_enemy+1
enemy_active = enemy_team[current_enemy]
print(enemy_active["Name"], "!")
print()
else:
print()
print(enemy_active["Name"], "has feinted!")
print()
EliteFour["Bruno"][1] = False
if player_team[0] == False:
print("You have run out of Pokemon!")
player_team[0] = False
print()
print("Better luck next time.")
return
if EliteFour["Bruno"][1] == False:
print("Bruno has been defeated!")
print()
print()
enemy_team = EliteFour["Agatha"]
print()
current_enemy = 2
enemy_active = enemy_team[current_enemy]
print("Now you must face the spooky Agatha!")
print()
print("Would you like to use any items?")
print()
items = str(input("Enter 'Yes' or 'No': "))
z = True
while z:
if items == 'yes' or items == "Yes":
print("Which item do you want to use? \n")
print(" Hyper Potion......x",str(hyper_potions)+"\n","Revive......x",str(revives)+"\n" )
item = str(input("Enter the item: "))
print()
x = True
while x:
if item == "Revive":
revive = Revive(Charizard, Alakazam, Blastoise, Venusaur, Jolteon, Lapras_P, revives)
if revive == "Failed":
print("None of your Pokemon have fainted!")
print()
if revive == "Charizard":
Charizard["Feint"]=False
Charizard["HP"]=Charizard["Max HP"]//2
print("Charizard has been revived!")
print()
revives = revives - 1
if revive == "Alakazam":
Alakazam["Feint"]=False
Alakazam["HP"]=Alakazam["Max HP"]//2
print("Alakazam has been revived!")
print()
revives = revives - 1
if revive == "Blastoise":
Blastoise["Feint"]=False
Blastoise["HP"]=Blastoise["Max HP"]//2
print("Blastoise has been revived!")
print()
revives = revives - 1
if revive == "Venusaur":
Venusaur["Feint"]=False
Venusaur["HP"]=Venusaur["Max HP"]//2
print("Venusaur has been revived!")
print()
revives = revives - 1
if revive == "Jolteon":
Jolteon["Feint"]=False
Jolteon["HP"]=Jolteon["Max HP"]//2
print("Jolteon has been revived!")
print()
revives = revives - 1
if revive == "Lapras":
Lapras_P["Feint"]=False
Lapras_P["HP"]=Lapras_P["Max HP"]//2
print("Lapras has been revived!")
print()
revives = revives - 1
x = False
elif item == "Hyper Potion":
if Charizard["HP"]==Charizard["Max HP"] and Lapras_P["HP"]==Lapras_P["Max HP"] and Blastoise["HP"]==Blastoise["Max HP"] and Alakazam["HP"]==Alakazam["Max HP"] and Venusaur["HP"]==Venusaur["Max HP"] and Jolteon["HP"]==Jolteon["Max HP"]:
print("All of your Pokemon are at full health!")
print()
else:
hyperp = HyperPotion(Charizard, Alakazam, Blastoise, Venusaur, Jolteon, Lapras_P, revives)
if hyperp == "Charizard":
Charizard["HP"]=Charizard["HP"]+100
hyper_potions = hyper_potions - 1
if Charizard["HP"]>=Charizard["Max HP"]:
Charizard["HP"]=Charizard["Max HP"]
print("Charizard has been fully healed!")
print()
else:
print("Charizard has been healed 100 HP!")
print()
print("Charizard's current HP is: ", Charizard["HP"])
print()
if hyperp == "Alakazam":
Alakazam["HP"]=Alakazam["HP"]+100
hyper_potions = hyper_potions - 1
if Alakazam["HP"]>=Alakazam["Max HP"]:
Alakazam["HP"]=Alakazam["Max HP"]
print("Alakazam has been fully healed!")
print()
else:
print("Alakazam has been healed 100 HP!")
print()
print("Alakazam's current HP is: ", Alakazam["HP"])
print()
if hyperp == "Blastoise":
Blastoise["HP"]=Blastoise["HP"]+100
hyper_potions = hyper_potions - 1
if Blastoise["HP"]>=Blastoise["Max HP"]:
Blastoise["HP"]=Blastoise["Max HP"]
print("Blastoise has been fully healed!")
print()
else:
print("Blastoise has been healed 100 HP!")
print()
print("Blastoise's current HP is: ", Blastoise["HP"])
print()
if hyperp == "Venusaur":
Venusaur["HP"]=Venusaur["HP"]+100
hyper_potions = hyper_potions - 1
if Venusaur["HP"]>=Venusaur["Max HP"]:
Venusaur["HP"]=Venusaur["Max HP"]
print("Venusaur has been fully healed!")
print()
else:
print("Venusaur has been healed 100 HP!")
print()
print("Venusaur's current HP is: ", Venusaur["HP"])
print()
if hyperp == "Jolteon":
Jolteon["HP"]=Jolteon["HP"]+100
hyper_potions = hyper_potions - 1
if Jolteon["HP"]>=Jolteon["Max HP"]:
Jolteon["HP"]=Jolteon["Max HP"]
print("Jolteon has been fully healed!")
print()
else:
print("Jolteon has been healed 100 HP!")
print()
print("Jolteon's current HP is: ", Jolteon["HP"])
print()
if hyperp == "Lapras":
Lapras_P["HP"]=Lapras_P["HP"]+100
hyper_potions = hyper_potions - 1
if Lapras_P["HP"]>=Lapras_P["Max HP"]:
Lapras_P["HP"]=Lapras_P["Max HP"]
print("Lapras has been fully healed!")
print()
else:
print("Lapras has been healed 100 HP!")
print()
print("Lapras's current HP is: ", Lapras_P["HP"])
print()
x = False
else:
item = str(input("Enter the item: "))
print()
if items == "No" or items == 'no':
z = False
else:
print()
items = str(input("Do you want to use an item? "))
print()
print("Prepare yourself!")
print()
print()
print("Agatha sends out her first Pokemon: Gengar!")
print()
## Battling Agatha
while EliteFour["Agatha"][1] == True:
while player_active["HP"]>0 and enemy_active["HP"]>0:
take_turn(player_active, enemy_active, Moves)
if player_active["HP"]<=0:
if body_count < 5:
print()
print(player_active["Name"], "has feinted!")
player_active["Feint"]=True
print("Send in your next Pokemon!")
print()
lyst = []
if Charizard["Feint"]==False:
lyst.append("Charizard")
if Alakazam["Feint"]==False:
lyst.append("Alakazam")
if Blastoise["Feint"]==False:
lyst.append("Blastoise")
if Venusaur["Feint"]==False:
lyst.append("Venusaur")
if Jolteon["Feint"]==False:
lyst.append("Jolteon")
if Lapras_P["Feint"]==False:
lyst.append("Lapras")
print()
for i in range(len(lyst)):
print(lyst[i])
print()
print("Who would you like to send in? ")
print()
switch = str(input("Enter next Pokemon: "))
z = True
while z:
if switch in lyst:
if switch == "Charizard":
current_player = 1
if switch == "Alakazam":
current_player = 2
if switch == "Blastoise":
current_player = 3
if switch == "Venusaur":
current_player = 4
if switch == "Jolteon":
current_player = 5
if switch == "Lapras":
current_player = 6
z = False
else:
print("Who would you like to send in? ")
print()
switch = str(input("Enter next Pokemon: "))
print()
body_count = body_count + 1
player_active = player_team[current_player]
print()
print("Go,",player_active["Name"],"!" )
print()
else:
player_team[0] = False
EliteFour["Agatha"][1] = False
if enemy_active["HP"]<=0:
if current_enemy < len(EliteFour["Agatha"])-1:
print()
print(enemy_active["Name"], "has feinted!")
print()
print( "Agatha will send in her next Pokemon:")
print()
current_enemy = current_enemy+1
enemy_active = enemy_team[current_enemy]
print(enemy_active["Name"], "!")
print()
else:
print()
print(enemy_active["Name"], "has feinted!")
print()
EliteFour["Agatha"][1] = False
if player_team[0] == False:
print("You have run out of Pokemon!")
player_team[0] = False
print()
print("Better luck next time.")
return
if EliteFour["Agatha"][1] == False:
print("Agatha has been defeated!")
print()
print()
enemy_team = EliteFour["Lance"]
print()
current_enemy = 2
enemy_active = enemy_team[current_enemy]
print("Now you must face the Dragon Master: Lance!")
print()
print("Would you like to use any items?")
print()
items = str(input("Enter 'Yes' or 'No': "))
z = True
while z:
if items == 'yes' or items == "Yes":
print("Which item do you want to use? \n")
print(" Hyper Potion......x",str(hyper_potions)+"\n","Revive......x",str(revives)+"\n" )
item = str(input("Enter the item: "))
print()
x = True
while x:
if item == "Revive":
revive = Revive(Charizard, Alakazam, Blastoise, Venusaur, Jolteon, Lapras_P, revives)
if revive == "Failed":
print("None of your Pokemon have fainted!")
print()
if revive == "Charizard":
Charizard["Feint"]=False
Charizard["HP"]=Charizard["Max HP"]//2
print("Charizard has been revived!")
print()
revives = revives - 1
if revive == "Alakazam":
Alakazam["Feint"]=False
Alakazam["HP"]=Alakazam["Max HP"]//2
print("Alakazam has been revived!")
print()
revives = revives - 1
if revive == "Blastoise":
Blastoise["Feint"]=False
Blastoise["HP"]=Blastoise["Max HP"]//2
print("Blastoise has been revived!")
print()
revives = revives - 1
if revive == "Venusaur":
Venusaur["Feint"]=False
Venusaur["HP"]=Venusaur["Max HP"]//2
print("Venusaur has been revived!")
print()
revives = revives - 1
if revive == "Jolteon":
Jolteon["Feint"]=False
Jolteon["HP"]=Jolteon["Max HP"]//2
print("Jolteon has been revived!")
print()
revives = revives - 1
if revive == "Lapras":
Lapras_P["Feint"]=False
Lapras_P["HP"]=Lapras_P["Max HP"]//2
print("Lapras has been revived!")
print()
revives = revives - 1
x = False
elif item == "Hyper Potion":
if Charizard["HP"]==Charizard["Max HP"] and Lapras_P["HP"]==Lapras_P["Max HP"] and Blastoise["HP"]==Blastoise["Max HP"] and Alakazam["HP"]==Alakazam["Max HP"] and Venusaur["HP"]==Venusaur["Max HP"] and Jolteon["HP"]==Jolteon["Max HP"]:
print("All of your Pokemon are at full health!")
print()
else:
hyperp = HyperPotion(Charizard, Alakazam, Blastoise, Venusaur, Jolteon, Lapras_P, revives)
if hyperp == "Charizard":
Charizard["HP"]=Charizard["HP"]+100
hyper_potions = hyper_potions - 1
if Charizard["HP"]>=Charizard["Max HP"]:
Charizard["HP"]=Charizard["Max HP"]
print("Charizard has been fully healed!")
print()
else:
print("Charizard has been healed 100 HP!")
print()
print("Charizard's current HP is: ", Charizard["HP"])
print()
if hyperp == "Alakazam":
Alakazam["HP"]=Alakazam["HP"]+100
hyper_potions = hyper_potions - 1
if Alakazam["HP"]>=Alakazam["Max HP"]:
Alakazam["HP"]=Alakazam["Max HP"]
print("Alakazam has been fully healed!")
print()
else:
print("Alakazam has been healed 100 HP!")
print()
print("Alakazam's current HP is: ", Alakazam["HP"])
print()
if hyperp == "Blastoise":
Blastoise["HP"]=Blastoise["HP"]+100
hyper_potions = hyper_potions - 1
if Blastoise["HP"]>=Blastoise["Max HP"]:
Blastoise["HP"]=Blastoise["Max HP"]
print("Blastoise has been fully healed!")
print()
else:
print("Blastoise has been healed 100 HP!")
print()
print("Blastoise's current HP is: ", Blastoise["HP"])
print()
if hyperp == "Venusaur":
Venusaur["HP"]=Venusaur["HP"]+100
hyper_potions = hyper_potions - 1
if Venusaur["HP"]>=Venusaur["Max HP"]:
Venusaur["HP"]=Venusaur["Max HP"]
print("Venusaur has been fully healed!")
print()
else:
print("Venusaur has been healed 100 HP!")
print()
print("Venusaur's current HP is: ", Venusaur["HP"])
print()
if hyperp == "Jolteon":
Jolteon["HP"]=Jolteon["HP"]+100
hyper_potions = hyper_potions - 1
if Jolteon["HP"]>=Jolteon["Max HP"]:
Jolteon["HP"]=Jolteon["Max HP"]
print("Jolteon has been fully healed!")
print()
else:
print("Jolteon has been healed 100 HP!")
print()
print("Jolteon's current HP is: ", Jolteon["HP"])
print()
if hyperp == "Lapras":
Lapras_P["HP"]=Lapras_P["HP"]+100
hyper_potions = hyper_potions - 1
if Lapras_P["HP"]>=Lapras_P["Max HP"]:
Lapras_P["HP"]=Lapras_P["Max HP"]
print("Lapras has been fully healed!")
print()
else:
print("Lapras has been healed 100 HP!")
print()
print("Lapras's current HP is: ", Lapras_P["HP"])
print()
x = False
else:
item = str(input("Enter the item: "))
print()
if items == "No" or items == 'no':
z = False
else:
print()
items = str(input("Do you want to use an item? "))
print()
print("Prepare yourself!")
print()
print()
print("Lance sends out his first Pokemon: Gyarados!")
print()
## Battling Lance
while EliteFour["Lance"][1] == True:
while player_active["HP"]>0 and enemy_active["HP"]>0:
take_turn(player_active, enemy_active, Moves)
if player_active["HP"]<=0:
if body_count < 5:
print()
print(player_active["Name"], "has feinted!")
player_active["Feint"]=True
print("Send in your next Pokemon!")
print()
lyst = []
if Charizard["Feint"]==False:
lyst.append("Charizard")
if Alakazam["Feint"]==False:
lyst.append("Alakazam")
if Blastoise["Feint"]==False:
lyst.append("Blastoise")
if Venusaur["Feint"]==False:
lyst.append("Venusaur")
if Jolteon["Feint"]==False:
lyst.append("Jolteon")
if Lapras_P["Feint"]==False:
lyst.append("Lapras")
print()
for i in range(len(lyst)):
print(lyst[i])
print()
print("Who would you like to send in? ")
print()
switch = str(input("Enter next Pokemon: "))
z = True
while z:
if switch in lyst:
if switch == "Charizard":
current_player = 1
if switch == "Alakazam":
current_player = 2
if switch == "Blastoise":
current_player = 3
if switch == "Venusaur":
current_player = 4
if switch == "Jolteon":
current_player = 5
if switch == "Lapras":
current_player = 6
z = False
else:
print("Who would you like to send in? ")
print()
switch = str(input("Enter next Pokemon: "))
print()
body_count = body_count + 1
player_active = player_team[current_player]
print()
print("Go,",player_active["Name"],"!" )
print()
else:
player_team[0] = False
EliteFour["Lance"][1] = False
if enemy_active["HP"]<=0:
if current_enemy < len(EliteFour["Lance"])-1:
print()
print(enemy_active["Name"], "has feinted!")
hyper_check = False
print()
print( "Lance will send in his next Pokemon:")
print()
current_enemy = current_enemy+1
enemy_active = enemy_team[current_enemy]
print(enemy_active["Name"], "!")
else:
print()
print(enemy_active["Name"], "has feinted!")
print()
EliteFour["Lance"][1] = False
if player_team[0] == False:
print("You have run out of Pokemon!")
player_team[0] = False
print()
print("Better luck next time.")
return
if EliteFour["Lance"][1] == False:
print("Lance has been defeated!")
print()
print()
print("Congratulations on defeating the Elite Four!")
print()
print("Truly, you are a Pokemon Master!")
print()
print("Thanks for playing! Challenge us again sometime!")
if __name__ == "__main__":
main()
|
def _help_():
print("""
RunFile v5.2.2.
RunFile helps simplify file manipulation. Optimised for python files.
RunFile is used mainly for file manipulation. It is optimised for python files as RunFile can
explore deep into your code, access the code's functions and classes, run functions seperately,
search for desired function or class in the code and run the code itself.
Command and arguments are seperated by '::'.
Use command 'help' and enter a command name for its info.
Syntax : help::<command>
Commands:
history
clearhistory
searchhistory
homepath
showpath
addpath
delpath
findpath
createfile
delfile
runfile
RunFile
runfunc
findfunc
clear/clr
content
addcontent
clearcontent
store
storelines
msg
star
box
error
warn
tip
variables (Not a command)
pause
delvar
quit
""")
|
import simplegui
import random
# global variables
num_guesses = 0
num_range = 101
secret_number = 0
# helper function to start and restart the game
def new_game():
global num_guesses
global num_range
global secret_number
if num_range == 101:
num_guesses = 7
secret_number = random.randrange (0, 101)
print "\nNew game started. Range is from 0 to 100."
print "Number of guesses left: %r." %num_guesses
elif num_range == 1001:
num_guesses = 10
secret_number = random.randrange(0, 1001)
print "\nNew game started. Range is from 0 to 1000."
print "Number of guesses left: %r." %num_guesses
else:
print "ERROR! Check code!"
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global num_range
num_range = 101
new_game()
def range1000():
# button that changes the range to [0,1000) and starts a new game
global num_range
num_range = 1001
new_game()
def input_guess(guess):
global num_guesses
global secret_number
guess = int(guess)
print "Your guess was %d." % guess
if guess < secret_number:
print "Higher!"
num_guesses -= 1
if num_guesses == 0:
print "You kinda suck at this game."
new_game()
print "Number of guesses left: %r." %num_guesses
elif guess > secret_number:
print "Lower!"
num_guesses -= 1
if num_guesses == 0:
print "You kinda suck at this game."
new_game()
print "Number of guesses left: %r." %num_guesses
elif guess == secret_number:
print "Correct!"
new_game()
else:
print "ERROR! Check code!"
# create frame
f = simplegui.create_frame("Guess the Number!", 200, 200)
# register event handlers for control elements and start frame
f.add_button("Guess from 100", range100, 200)
f.add_button("Guess from 1000", range1000, 200)
f.add_input("Your guess here:", input_guess, 200)
# call new_game
new_game()
f.start()
# always remember to check your completed program against the grading rubric
|
# Запросить у пользователя число1.
# Запросить у пользователя число2.
# Вывести результат всех известных Вам операций над двумя числами.
# Операции + - * / // % **
num_1 = float(input('Пожалуйста, введите первое число:'))
num_2 = float(input('Пожалуйста, введите второе число:'))
plus = num_1 + num_2
print('''
Результат сложения данных чисел:''', plus)
minus = num_1 - num_2
print('Результат вычитания данных чисел:', minus)
multiply = num_1 * num_2
print('Результат умножения данных чисел:', multiply)
divide = num_1 / num_2
print('Результат деления данных чисел:', divide)
divide_int = int(num_1 // num_2)
print('Результат целочисленного деления данных чисел:', divide_int)
modulo = num_1 % num_2
print('Остаток от деления данных чисел:', modulo)
exponent = num_1 ** num_2
print('Результат вовзведения первого числа в степень, соответствующую второму числу:', exponent)
root = num_1 ** (1/num_2)
print('Корень первого числа в степени, соответствующую второму числу:', root)
|
def arithmetic_arranger(problems , *args):
if(args):
show_results = True
else:
show_results = False
return process_input(problems,show_results)
def process_input(problems,show_results):
first_op = []
second_op = []
op_list = []
if(len(problems) > 5):
return "Error: Too many problems."
for expr in problems:
exprsn = expr.split()
op1,op2,op = exprsn[0].strip(),exprsn[2].strip(),exprsn[1].strip()
if op not in ['+','-']:
return "Error: Operator must be '+' or '-'."
if not(op1.isdigit() and op2.isdigit()):
return "Error: Numbers must only contain digits."
if((len(op1) > 4) or (len(op2) > 4)):
return "Error: Numbers cannot be more than four digits."
first_op.append(op1)
second_op.append(op2)
op_list.append(op)
arranged_problems = (build_output(first_op , second_op, op_list , show_results))
return arranged_problems
def build_output(first_op , second_op, op_list, show_results):
first_line=""
second_line=""
third_line=""
result=""
if(show_results):
for i in range(len(first_op)):
width = max(len(first_op[i]), len(second_op[i]))
if(op_list[i] == '+'):
result += (str(int(first_op[i]) + int(second_op[i]))).rjust(width+2) + " "*4
else:
result += (str(int(first_op[i]) - int(second_op[i]))).rjust(width+2) + " "*4
for i in range(0,len(first_op)):
width = max(len(first_op[i]), len(second_op[i]))
first_line += first_op[i].rjust(width+2) + " "*4
second_line += op_list[i] + " " + second_op[i].rjust(width) + " "*4
third_line += ("-"*(width+2)).rjust(width+2) + " "*4
if show_results:
arranged_problems = first_line.rstrip() + '\n' + second_line.rstrip() + '\n' + third_line.rstrip() + '\n' + result.rstrip()
else:
arranged_problems = first_line.rstrip() + '\n' + second_line.rstrip() + '\n' + third_line.rstrip()
return arranged_problems
|
from math import sqrt
xP1X1 = float(input("Escriba el valor para X1: "))
xP1Y1 = float(input("Escriba el valor para Y1: "))
xP2X2 = float(input("Escriba el valor para X2: "))
xP2Y2 = float(input("Escriba el valor para Y2: "))
xP3X3 = float(input("Escriba el valor para X3: "))
xP3Y3 = float(input("Escriba el valor para Y3: "))
xDAB = sqrt( ((xP2X2 - xP1X1)**2) + ((xP2Y2 - xP1Y1)**2) )
xDBC = sqrt( ((xP2X2 - xP3X3)**2) + ((xP2Y2 - xP3Y3)**2) )
xDAC = sqrt( ((xP1X1 - xP3X3)**2) + ((xP1Y1 - xP3Y3)**2) )
if (xDAB == xDBC and xDAB == xDAC):
print("Equilatero")
elif (xDAB == xDBC or xDAB == xDAC):
print("Isoceles")
else:
print("Escaleno")
|
def shift_left(elems, e, begin, end):
i, j = begin, begin * 2 + 1
while j < end:
if j + 1 < end and not elems[j] < elems[j + 1]:
j += 1
if e < elems[j]:
break
elems[i] = elems[j]
i = j
j = j * 2 + 1
elems[i] = e
def heap_sort(elems):
end = len(elems)
for i in range(end // 2 + 1, -1, -1):
shift_left(elems, elems[i], i, end)
for i in range((end - 1), 0, -1):
e = elems[i]
elems[i] = elems[0]
shift_left(elems, e, 0, i)
return elems
if __name__ == '__main__':
a_list = [5, 6, 8, 1, 2, 4, 9]
a_list_sorted = heap_sort(a_list)
print(a_list_sorted)
import heapq
heapq.heapify(a_list)
for i in range(len(a_list)):
print(heapq.heappop(a_list)) |
"""
模板
def slidingWindow(s: str, t: str) -> str:
from collections import Counter
need, window = Counter()
for c in t:
need[c] += 1
# 窗口左右端点值,左闭右开
left = right = 0
# valid == len(need) -> 窗口满足条件
valid = 0
while right < len(s):
# c 是将移入窗口的字符
c = s[right]
# 窗口向右拓展
right += 1
# 更新窗口内数据的操作
...
## debug print ##
print("window: [{}, {})".format(left, right))
## debug print ##
# 满足条件的情况下窗口左端收缩
while valid == len(need):
# d 是将移除窗口的字符
d = s[left]
# 窗口左端收缩
left += 1
# 更新窗口内数据的操作
...
"""
"""
76. 最小覆盖子串
给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字符的最小子串。
---------------------------------------------------------------
输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"
"""
def minWindow(s: str, t: str) -> str:
from collections import Counter
need, window = Counter(), Counter()
# 初始化子串所涵盖的字符及数量
for c in t:
need[char] += 1
# 左右窗口值
left = right = 0
# 已包含的字符数
valid = 0
# 匹配到的最小覆盖子串的开始端点
start = 0
# 匹配到的最小覆盖子串的长度
length = math.inf
while right < len(s):
# 即将进入窗口的字符
c = s[right]
# 窗口向右拓展
right += 1
# 对于窗口内的数据进行更新
if c in need:
# 子串所需字符标记+1
window[c] += 1
# 如果已满足,valid += 1
if window[c] == need[c]:
valid += 1
# 当已经满足覆盖了子串,窗口左端收缩,寻找最小覆盖子串
while valid == len(need):
# 如果子串比记录值小,记录下作为最小覆盖子串
if right - left < length:
start = left
length = right - left
# 即将移出窗口的左端点值
d = s[left]
# 窗口左端收缩
left += 1
# 如果移出的是覆盖子串的字符
if d in need:
# 如果移出当前之后就不满足该字符覆盖,valid -= 1
if window[d] == need[d]:
valid -= 1
# 覆盖窗口的字符记录值-1
window[d] -= 1
if length == math.inf:
return ""
else:
return s[start: start+length]
"""
567. 字符串的排列
给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。
换句话说,第一个字符串的排列之一是第二个字符串的子串。
---------------------------------------------------------------
输入: s1 = "ab" s2 = "eidbaooo"
输出: True
解释: s2 包含 s1 的排列之一 ("ba").
"""
def checkInclusion(s1: str, s2: str) -> bool:
from collections import Counter
need, window = Counter(), Counter()
for c in s1:
need[c] += 1
left = right = 0
valid = 0
while right < len(s2):
c = s2[right]
right += 1
if c in need:
window[c] += 1
if window[c] == need[c]:
valid += 1
# 因为排列是要长度是一样的,所以当大于等于(其实只会触及等于,不会触及大于)的时候,就要缩小窗口
while right - left >= len(s1):
# 当每个字符都覆盖到的时候,说明满足条件,返回True
if valid == len(need):
return True
d = s2[left]
left += 1
if d in need:
if window[d] == need[d]:
valid -= 1
window[d] -= 1
return False
"""
438. 找到字符串中所有字母异位词
给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。
字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。
---------------------------------------------------------------
输入:
s: "cbaebabacd" p: "abc"
输出:
[0, 6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。
---------------------------------------------------------------
输入:
s: "abab" p: "ab"
输出:
[0, 1, 2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的字母异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的字母异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的字母异位词。
"""
def findAnagrams(s: str, p: str) -> List[int]:
from collections import Counter
need, window = Counter(), Counter()
for c in p:
need[c] += 1
left = right = 0
valid = 0
result = []
while right < len(s):
c = s[right]
right += 1
if c in need:
window[c] += 1
if window[c] == need[c]:
valid += 1
while right - left >= len(p):
if valid == len(need):
result.append(left)
d = s[left]
left += 1
if d in need:
if window[d] == need[d]:
valid -= 1
window[d] -= 1
return result
"""
3. 无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
---------------------------------------------------------------
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
---------------------------------------------------------------
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
---------------------------------------------------------------
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
"""
def lengthOfLongestSubstring(s: str) -> int:
from collections import Counter
window = Counter()
left = right = 0
result = 0
while right < len(s):
c = s[right]
right += 1
window[c] += 1
while window[c] > 1:
d = s[left]
left += 1
window[d] -= 1
result = max(result, right-left)
return result |
class Chto_Bolit():
def chto_bolit(self, a):
if (a == 1):
return "голова"
elif (a == 2):
return "грудь"
elif (a == 3):
return "горло"
class Golova():
def bolit_golova(self, g1, g2, g3, g4):
print("Температура выше 37.8?(да/нет)")
g1 = str(input())
if (g1 == "да"):
return "Сходите к терапевту"
elif (g1 == "нет"):
print("Были ли травмы головы недавно?(да/нет)")
g2 = str(input())
if (g2 == "да"):
return "Сходите в травмпункт"
elif (g2 == "нет"):
print("Головокружение есть?(да/нет)")
g3 = str(input())
if (g3 == "да"):
return "Сходите на МРТ"
elif (g3 == "нет"):
print("Давление повышено?(да/нет)")
g4 = str(input())
if (g4 == "да"):
return "Выпейте коньячку"
elif (g4 == "нет"):
return "Симулянт"
class Grudi():
def bolit_grudi(self, r1, r2, r3):
print("Болит сердце?(да/нет)")
r1 = str(input())
if (r1 == "да"):
return "Обратитесь к кардиологу"
elif (r1 == "нет"):
print("Болят легкие?(да/нет)")
r2 = str(input())
if (r2 == "да"):
return "Обратитесь к пульмологу"
elif (r2 == "нет"):
print("Ударялись ли грудной клеткой?(да/нет)")
r3 = str(input())
if (r3 == "да"):
return ("Сходите в травмпункт")
elif (r3 == "нет"):
return ("Симулянт")
class Gorlo():
def bolit_gorlo(self, v1, v2, v3, v4, v5):
print("Першит ли горло?(да/нет)")
v1 = str(input())
if (v1 == "да"):
print("Кашель есть?(да/нет)")
v2 = str(input())
if (v2 == "нет"):
return "Ангина"
elif (v2 == "да"):
print("Сухой или влажный?(сухой/влажный)")
v3 = str(input())
if (v3 == "сухой"):
return "Тонзиллит"
elif (v3 == "влажный"):
return "Бронхит"
elif (v1 == "нет"):
print("Напрягали ли вы голосовые связки?(да/нет)")
v4 = str(input())
if (v4 == "да"):
return "Не напрягайте их в ближайшее время"
elif (v4 == "нет"):
print("Повреждали ли горло?(да/нет)")
v5 = str(input())
if (v5 == "да"):
return "Обратись к ЛОР-врачу"
elif (v5 == "нет"):
return "Симулянт"
def main():
cht = Chto_Bolit()
gol = Golova()
gor = Gorlo()
gru = Grudi()
print("Что у вас болит(1.голова, 2.грудь или 3.горло)?")
a = int(input())
print(cht.chto_bolit(a))
if cht.chto_bolit(a) == "голова":
print(gol.bolit_golova(g1 = str(), g2 = str(), g3 = str(), g4 = str()), "\n")
elif cht.chto_bolit(a) == "горло":
print(gor.bolit_gorlo(v1 = str(), v2 = str(), v3=str, v4=str, v5=str), "\n")
elif cht.chto_bolit(a) == "грудь":
print(gru.bolit_grudi(r1=str, r2=str, r3=str), "\n")
if __name__ == '__main__':
main()
|
print('Please enter the value of the bill you have to pay')
AMOUNT = int(input())
print('Please enter the amount of 100, 20 and 1 banknotes in your wallet')
P = int(input())
Q = int(input())
R = int(input())
ways = 0
combinations = []
for x in range(P+1):
for i in range(Q+1):
for j in range(R+1):
if AMOUNT - ((j*1) + (i*20) + (x*100)) == 0:
ways += 1
combination = str(x) + ' x 100, ' + str(i) + ' x 20, ' + str(j) + ' x 1'
combinations.append(combination)
print('\nThere are ' + str(ways) + ' ways to pay this bill')
for e in combinations:
print(e) |
"""
This class is responsible for storing all the information about the current state of a chess game. It will also be
responsible for determining the valid moves at the current state. It will also keep a move log.
"""
class GameState():
def __init__(self):
#board is 8x8 2d list, each element of the list has 2 characters.
#The first character represents the color of the piece, 'b(black)' or 'w (white)'
#"--" - represents an empty space with no piece
self.board = [
["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp"],
["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"]
]
self.whiteToMove = True
self.moveLog = []
'''
Takes a move as a parameter and executes it (this will not work for castling and pawn promotion)
'''
def makeMove(self, move):
self.board[move.startRow][move.startCol] = "--"
self.board[move.endRow][move.endCol] = move.pieceMoved
self.moveLog.append(move)
self.whiteToMove = not self.whiteToMove
'''
Undo the last move
'''
def undoMove(self):
if len(self.moveLog) != 0:
move = self.moveLog.pop()
self.board[move.startRow][move.startCol] = move.pieceMoved
self.board[move.endRow][move.endCol] = move.pieceCaptured
self.whiteToMove = not self.whiteToMove #switch turns back
class Move():
#map keys to values
#key : value
ranksToRows = {"1": 7, "2": 6, "3": 5, "4": 4,
"5": 3, "6": 2, "7": 1, "8": 0}
rowsToRanks = {v: k for k, v in ranksToRows.items()}
filesToCols = {"a": 0, "b": 1, "c": 2, "d": 3,
"e": 4, "f": 5, "g": 6, "h": 7}
colsToFiles = {v: k for k, v in filesToCols.items()}
def __init__(self, startSq, endSq, board):
self.startRow = startSq[0]
self.startCol = startSq[1]
self.endRow = endSq[0]
self.endCol = endSq[1]
self.pieceMoved = board[self.startRow][self.startCol]
self.pieceCaptured = board[self.endRow][self.endCol]
def getChessNotation(self):
return self.getRankFile(self.startRow, self.startCol) + self.getRankFile(self.endRow, self.endCol)
def getRankFile(self, r, c):
return self.colsToFiles[c] + self.rowsToRanks[r]
|
"""
@author Miguel Angel Correa - Pablo Buitrago
Taller 01 estructura datos y algorítmos.
"""
import math
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_dif_sq = (self.x - other.x)**2
y_dif_sq = (self.y - other.y)**2
return (x_dif_sq + y_dif_sq)**0.5
def polarRadio(self):
return distance(self, Coordinate(0,0))
def polarAngle(self):
return math.atan(self.y/self.x)
def getX(self):
return self.x
def getY(self):
return self.y
class Date(object):
def __init__(self, day, month, year):
self.day = day
self.month = month
self.year = year
def toString(self):
return str(year)+'-'+str(month)+'-'+str(day)
def compare(self, other):
d1 = self.toString
d2 = other.toString
for i in (10):
if d1[i] < d2[i]:
return self.toString+' is before '+other.toString
elif d1[i] > d2[i]:
return self.toString+' is after '+other.toString
return self.toString+' is the same as '+other.toString
class Counter(object):
def __init__(self, ID):
self.ID = ID
self.c = 0
def increase(self):
self.c += 1
def getIncreases(self):
return self.c
def toString(self):
return str(self.ID) +': '+ str(self.c)
|
# ----------------------------------------------------------------------
# Title:Homework 10
# Jordan Cerilli, A00132189
# Date:2020,11,04
# Purpose:Identify Class Car
# Acknowledgments:N/A
# -----------------------------------------------------------------------
import pickle
def main():
menu_choice = '0'
while menu_choice != 'Q' and menu_choice != 'q':
print('Baseketball Players')
print(' ======================')
print(' 1) Add')
print(' 2) Delete')
print(' 3) Print')
print(' 4) Save')
print(' Q) Quit')
print(' ======================')
menu_choice = input(' 1.Add 2.Delete 3.Print 4.Save Q.Quit:')
if menu_choice == '1':
add1 = input('Players Name: ')
add2 = input('Players Age: ')
add3 = input('Players Games Played: ')
add4 = input('Players Games They Have Started In: ')
add5 = input('Players Minutes Played This Season: ')
add6 = input('Players Feild Goals Made This Season: ')
add7 = input('Players Feild Goal Attempts This Season: ')
add8 = input('Players Feild Goal Percentage: ')
add9 = input('Players 3-Pointers Made: ')
add10 = input('Players 3-Pointers Attempted: ')
add11 = input('Players 3-Pointer Percentage: ')
add12 = input('Players 2-Pointers Made: ')
add13 = input('Players Free Throws Made: ')
add14 = input('Players Free Throw Attempts: ')
add15 = input('Players Free Throw Percentage: ')
add16 = input('Players Offesive-Rebounds This Season: ')
add17 = input('Players Defensive-Rebounds This Season: ')
add18 = input('Players Total-Rebounds This Season: ')
add19 = input('Players Total Assists This Season: ')
add20 = input('Players Total Steals This Season: ')
add21 = input('Players Total Blocks This Season: ')
add22 = input('Players Total Turnovers This Season: ')
add23 = input('Players Total Personal Fouls This Season: ')
add24 = input('Players Total Points: ')
if menu_choice == '2':
# Delete
if menu_choice == '3':
print(infile)
if menu_choice == '4':
with open("team.dat", "wb") as infile:
pickle.dump(team, infile)
elif menu_choice == 'Q' or menu_choice == 'q':
print(' Goodbye')
else:
print(' Not a valid choice, try again.')
pickle.dump(person, file)
# Call the main function and start the program.
main()
|
from numpy import array
def Activity_1():
name = input("Enter your name: ")
age = int(input("Enter your age: "))
time_remaining_to_100 = (2020 - age) +100
print(time_remaining_to_100)
|
import datetime
from datetime import date
import requests
#example API KEY = "e2b47a49d350e13324ce145b3150ff64"
#creating the current weather part of the app:
def get_current_weather(city_name, key):
URL= f"https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={key}"
url_link = requests.get(URL)
current_weather_data = url_link.json()
if current_weather_data["cod"] == "404":
return "City not found. Please re-enter the name of the city you'd wish to find the weather of."
try:
country = current_weather_data["sys"]["country"]
except Exception:
return "API Key is inserted incorrectly. Please try re-entering it."
city = current_weather_data["name"]
kelvin_temp = current_weather_data["main"]["temp"]
celsius_temp = round(int(kelvin_temp) - 273.15, 1)
fahrenheit_temp = round((int(kelvin_temp) * (9/5)) - 459.67, 2)
feels_like_temp = current_weather_data["main"]["feels_like"]
feels_like_C = round(int(feels_like_temp) - 273.15, 1)
feels_like_F = round((int(feels_like_temp) * (9/5)) - 459.67)
sky_description = current_weather_data["weather"][0]["description"]
today = date.today()
todays_time = datetime.time()
result = f"The temperature in {city} ({country}) is: {celsius_temp} celsius or {feels_like_F} fahrenheit. \n " \
f"The perceived temperature is: {feels_like_C} celsius or {feels_like_F} fahrenheit.\n" \
f"The sky is {sky_description}"
return str(today) + " " + str(todays_time) + "\n " + result +"\n"
#print(get_current_weather("London","e2b47a49d350e13324ce145b3150ff64"))
|
x=0
y=0
sosoo=int(input('어디까지의 소수를 구해드릴까요?'))
for x in range (2,sosoo+1,1):
count = 0
for y in range(2,x+1,1):
if x%y == 0:
count+=1
if count == 1:
print(x)
|
'''
_________________MyCoding____________________
###############Power - Mod Power
a=int(input())
b=int(input())
m=int(input())
c=pow(a,b)
d=pow(a,b,m)
print(c)
print(d)
'''
'''
_________________MyCoding____________________
#01
#########Integers Come In All Sizes
a=int(input())
b=int(input())
c=int(input())
d=int(input())
print(pow(a,b)+pow(c,d))
'''
'''
_________________MyCoding____________________
#01
#########Integers Come In All Sizes Come In All Sizes
for i in range(1,int(input())):
print((10 ** i // 9) * i)
'''
'''
_________________MyCoding____________________
#01
###Detect Floating Point Number
#import re
n=int(input())
chk=list()
for i in range (0,n):
t=input()
try:
b=float(t)
if t.count('.')==1 and (t.index('.')+1)<len(t):
chk.append(True)
else :
chk.append(False)
except :
chk.append(False)
for i in range(0,n):
print(chk[i])
'''
'''
_________________MyCoding____________________
#01
###re.split()
regex_pattern = r"[,.]"#Do not delete 'r'.
import re
print("\n".join(re.split(regex_pattern,input())))
'''
'''
_________________MyCoding____________________
#01
### Group(), Groups() & Groupdict()
t=input()
compare="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
result=-1
for i in range(0,len(t)-1):
if compare.count(t[i])==1:
if t[i]==t[i+1]:
result=t[i]
break
print(result)
'''
'''
_________________MyCoding____________________
#01
### Re.findall() & Re.finditer()
import re
s=input()
regex_pattern = r"[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm 1234567890~!@#$%^&*()_+-={}:,./|]"
result=re.split(regex_pattern,s)
#print(result)
chk=0
for i in range(0,len(result)):
k=result[i]
if len(k)>1:
if k[len(k)-1]!=s[len(s)-1]:
print(k)
else :
chk+=1
if chk==len(result):
print(-1)
'''
'''
_________________MyCoding____________________
#01
####Re.start() & Re.end()
s=input()
f=input()
clist=list()
for i in range(0,len(s)-len(f)+1):
if f[0]==s[i]:
chk=0
for j in range(0,len(f)):
if s[i+j]==f[j]:
chk+=1
if chk==len(f):
a=list()
a.append(i)
a.append(i+len(f)-1)
clist.append(a)
#print(clist)
if len(clist)==0:
print("(-1, -1)")
else :
for i in range(0,len(clist)):
b=clist[i]
print("({0}, {1})".format(b[0],b[1]))
'''
'''
_________________MyCoding____________________
#01
###Regex Substitution
import re
n=int(input())
slist=list()
for i in range(0,n):
s=input()
compare="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(0,len(s)):
s=re.sub(" \&\& ", " and ", s)
for i in range(0,len(s)):
s=re.sub(" \|\| ", " or ", s)
slist.append(s)
for i in range(0,n):
print(slist[i])
'''
'''
_________________MyCoding____________________
#01
###Incorrect Regex
import re
n=int(input())
result=[]
chk=list()
for i in range(0,n):
t=input()
if t=='/^(?!\.)(?=.)[d-\.]$/':
chk.append(False)
elif t=='[0-9]++':
chk.append(False)
elif t=='.*+':
chk.append(False)
else :
chk.append(True)
for i in range(0,n):
print(chk[i])
#02
import re
n = input()
for _ in range(n):
regex = raw_input()
try:
test = re.match(regex,'')
print 'True'
except:
print 'False'
'''
'''
####Polar Coordinates
import cmath
import math
import re
s=input()
regex_pattern = r"[+-]"
slist=re.split(regex_pattern,s)
if s.count('-')==2:
a=int(slist[1])*-1
b=int(slist[2][:-1])*-1
elif s.count('-')==1:
if s[0]=='-':
a=int(slist[1])*-1
b=int(slist[2][:-1])
else :
a=int(slist[0])
b=int(slist[1][:-1])*-1
else :
a=int(slist[0])
b=int(slist[1][:-1])
print(abs(complex(a,b)))
print(cmath.phase(complex(a,b)))
'''
'''
########Find Angle MBC
import math
ab=int(input())
bc=int(input())
#print(ab*ab)
ac=math.sqrt(ab*ab+bc*bc)
#print(ac)
cm=ac/2
anglembc=math.acos((0.5*bc)/cm)
#print(anglembc)
mbcdegrees=math.degrees(anglembc)
print("{0}°".format(round(mbcdegrees)))
'''
'''
###Triangle Quest 2
for i in range(1,int(input())+1):
# print([1,121,12321,1234321,123454321,12345654321,1234567654321,123456787654321,12345678987654321][i-1])
print (((10**i - 1)//9)**2)
'''
'''
def QuickSort2(input_list):
if len(input_list) < 2:
return input_list
pivot = input_list[0]
less = [i for i in input_list[1:] if i<= pivot]
greater = [i for i in input_list[1:] if i>pivot]
input_list = QuickSort2(less) + [pivot] + QuickSort2(greater)
return input_list
if __name__ == "__main__" :
input_list = [10,9,8,7, 6, 5, 4, 3, 2,1]
print(QuickSort2(input_list))
'''
'''
K=int(input())
rlist=input().split()
rlist.reverse()
l=list(set(rlist))
l.sort()
for i in range(0,len(l)):
if rlist.count(l[i])!=K:
room=0
room=l[i]
break
else :
for j in range():
rlist.pop()
print(room)
'''
'''
###Thr Captain's Room
k=int(input())
rlist=list(map(int,input().split()))
#print(rlist)
l=list(set(rlist))
#print(l)
#print(sum(rlist))
#print(sum(l)*k)
room=(sum(l)*k-sum(rlist))/(k-1)
print(int(room))
'''
'''
###Input()
x, k = list(map(int, input().split()))
p=input()
#print(p)
#type(eval(p))
print(k==eval(p))
'''
'''
###Python Evaluation
eval(input())
'''
###Word Order
n=int(input())
alist=list()
nlist=list()
idx=0
for i in range(0,n):
t=input()
if alist.count(t)==0 :
alist.append(t)
nlist.append(1)
else :
idx=alist.index(t)
nlist[idx]=nlist[idx]+1
print(len(alist))
import re
s=str(nlist)
#s=re.sub(",", "", s)
#s=re.sub("\[", "", s)
#s=re.sub("\]", "", s)
s=re.sub("[,\[\]]", "", s)
print(s)
|
for i in range(0, 100, 1):
count=0
for j in range(2, i+1, 1):
if i%j==0 :
count+=1
if count==1 :
print(i)
|
#랜덤한 수 5개를 자동생성하여 합계와 평균을 구하세요.
'''
import random
ran=int(input("1부터 100중 몇개의 수를 합계와 평균을 구해드릴까요?"))
rand= random.sample(range(1,101), ran)
avg = 0
total = 0
print(rand,"랜덤으로 선택된 숫자는 다음과 같습니다.")
for i in range(0,ran,1):
total+=rand[i]
print("합계는 %d 입니다."% total)
avg=total/ran
print("평균은 %f 입니다."% avg)
'''
#random.sample()은 중복안됨 _미만 +1해야됨
#random.randrange()은 중복됨 _ 미만 +1해야됨
#random.randint()는 중복됨_ 이상
'''
import random
numbers = []
for i in range(5) :
numbers.append(random.randint(1,100))
numbers.sort()
print(numbers)
'''
import random
def getNumber() :
return random.randrange(1, 101)
list = []
num = 0
while True :
num = getNumber()
if list.count(num) == 0 :
list.append(num)
if len(list)>=5 :
break
print("숫자 ==> ", end=' ')
list.sort()
for i in range(0, 5) :
print("%d" % list[i], end= ' ')
'''
import random
list = []
for i in range(100) :
x = random.randrange(1, 101)
list.append(x)
list.sort( )
print("1부터 100까지 수에서 랜덤으로 뽑은 5가지 수의 리스트, 합계, 평균을 표시")
print("숫자 %s" %list)
print("합계 %s" %sum(list))
print("평균 %s" %(sum(list)/len(list)))
'''
|
#Exercise 5 in Hackbright Curriculum
#open a file named on the command line
from sys import argv
script, file_name = argv
#open it in read mode
in_file = open(file_name) #create an object of type=file, named in_file
indata = in_file.read()
# print len(indata)
# try #1 this method would require 26 for loops - but it works!
# count_a = 0
# for i in range(len(indata)):
# if ord(indata[i]) == 65 or ord(indata[i]) == 97:
# count_a = count_a +1
# print count_a
#for loop to loop through the alphabet, with a counter?, print how many times it occurred
# try # 2 with nested for loops. Unfortunately, this was too slow. But it works!!!
# for letter in range(65,91):
# count = 0
# for i in range(len(indata)):
# if ord(indata[i]) == letter or ord(indata[i]) == letter+32:
# count = count +1
# print chr(letter), count
# Try #3. This try did not work.
# alphabet="A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z"
# list_alpha = alphabet.split(" ")
# for character_index in range(len(indata)):
# for alpha_index in range (26):
# if indata[character_index] == list_alpha[alpha_index] or indata[character_index] == list_alpha[alpha_index + 26]:
# alpha_index = alpha_index + 1
# print alpha_index
# Next up, solving with a list!
answer = [0]*26
#answer [0:26:1] = 0
#answer = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
# for char in indata.lower():
# print ord(char)
# answer[ord(char)-97]="bunny"
# print answer
for char in indata.lower():
if ord(char) in range (97, 122):
answer[ord(char)-97] +=1
in_file.close()
for i in answer:
print i
|
def show_num(limit):
i=0
while i<=limit:
if i%2==0:
print("even",i)
else:
print("odd",i)
i=i+1
show_num(limit=int(input("enter the limit "))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.