text stringlengths 37 1.41M |
|---|
import turtle
esquerda = int(input('Esquerda:'))
topo = int(input('Topo:'))
largura = int(input('Largura:'))
altura = int(input('Altura:'))
x = int(input('X:'))
y = int(input('Y:'))
if (x > esquerda) or x < esquerda and x < esquerda - largura:
print('Não colide')
elif x >= esquerda - largura and x <= esquerda:
print('Colide')
#retângulo
t = turtle.Turtle()
t.penup()
t.goto(esquerda,topo)
t.right(90)
t.pendown()
t.forward(altura)
t.right(90)
t.forward(largura)
t.right(90)
t.forward(altura)
t.right(90)
t.forward(largura)
#ponto
t.penup()
t.goto(x, y)
t.color('blue')
t.dot(size=5)
|
import string
def is_pangram(sentence):
for letter in string.ascii_lowercase:
if letter in sentence.lower():
pass
else:
return False
return True |
'''Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3'''
n=input()
l=0
d=0
for i in n:
if i.isalpha():
l+=1
elif i.isdigit():
d+=1
print(f'LETTERS {l}')
print(f'DIGITS {d}') |
'''Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console.
Example: If the following n is given as input to the program:
10
Then, the output of the program should be:
0,2,4,6,8,10
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints
Use yield to produce the next value in generator.'''
def gen(n):
for i in range(0,n+1):
if i%2==0:
yield i
l=[str(i) for i in gen(int(input()))]
print(','.join(l))
|
'''Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 _ C _ D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.For example Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24'''
import math
C=50
H=30
D=input("enter the value of D: ")
j=[]
for i in D.split(','):
j.append(str(int(math.sqrt((2*C*int(i))/H))))
print(','.join(j))
|
'''Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
'''
import random
n=random.sample([i for i in range(100,201) if i%2==0],5)
print(n) |
'''Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9'''
n=input()
u=0
l=0
for i in n:
if i.islower():
l+=1
elif i.isupper():
u+=1
print(f'UPPER CASE {u}\nLOWER CASE {l}') |
'''Define a function which can generate a dictionary where the keys are numbers
between 1 and 20 (both included) and the values are square of keys.
The function should just print the keys only.'''
def dict_print():
dict1={i:i**2 for i in range(1,21)}
for i in dict1:
print(i)
return dict1
dict_print() |
'''Please write a program which count and print the numbers of each character in a string input by console.
Example: If the following string is given as input to the program:
abcdefgabc
Then, the output of the program should be:
a,2
c,2
b,2
e,1
d,1
g,1
f,1'''
n=[i for i in input()]
dict1={i:n.count(i) for i in n}
for i in dict1:
print(f'{i},{dict1.get(i)}')
|
'''Please write a program to randomly print a integer number between 7 and 15 inclusive.'''
import random
n=random.randint(7,15)
print(n) |
'''Define a function that can accept two strings as input and concatenate them and then print it in console.'''
cnct=lambda s,s1:s+s1
print(cnct(input(),input())) |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 27 17:01:10 2019
@author: Vidya
Solution to Project Euler problem 2
https://projecteuler.net/problem=2
Problem Statement :
>>>>>>>>>>>
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
>>>>>>>>>>>
Assumptions :
1. The max value entered is an integer
Result :
Expected Answer for 4000000 - 4613732
"""
def fibonacci():
current_num, next_num = 0, 1
while True:
current_num, next_num = next_num, current_num + next_num
yield current_num
def sum_even_fibonnaci(max):
sum_even = 0
fib_gen = fibonacci()
fib_value = fib_gen.__next__()
while (fib_value <= max):
if (fib_value % 2) == 0:
sum_even += fib_value
fib_value = fib_gen.__next__()
print('Sum of even fibonnaci numbers upto {0} is {1}'.format(
max, sum_even))
max = int(input(
'Please enter max value upto which to sum even fibonacci numbers : ').strip())
sum_even_fibonnaci(max)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 13 16:47:02 2019
@author: Vidya
Solution to Project Euler problem 16
https://projecteuler.net/problem=16
Problem Statement :
>>>>>>>>>>> Power digit sum
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
>>>>>>>>>>>
Result :
Expected Answer - 1366
Notes :
1. We use python's built in support for big numbers
References :
From the link -
https://docs.python.org/3/c-api/long.html#integer-objects
All integers are implemented as “long” integer objects of arbitrary size.
And hence there is no need to store the required sum in a special number type
for big numbers. (Hard limit of memory accessible to python is applicable)
We do the regular power multiplication sum the digits.
"""
import time
def sum_digits(number, exponent):
exp_result = str(number**exponent)
sum_result = sum([int(i) for i in exp_result])
return sum_result
if __name__ == '__main__':
number = 2
power = 1000
start_time = time.time()
result = sum_digits(number, power)
end_time = time.time() - start_time
print('Sum of the digits of the number ', number,
'to the power ', power, 'is ', result)
print('Time taken is ', end_time)
|
#!/usr/local/bin/python
"""
tokenizer in python (albeit a (very) long one
outputs similar to shell script
"""
import os
import re
import subprocess
import sys
import tempfile
if len(sys.argv) < 2:
print("Error! No argument given. Need the filename for the command.")
sys.exit(1)
lines = open(sys.argv[1], 'r').readlines()
lines_str = '\n'.join(lines).lower()
lines_str = re.sub("[^a-zA-Z]", '\n', lines_str)
lines = lines_str.split('\n')
count_dict = {}
for line in lines:
line = line.strip()
if line not in count_dict:
count_dict[line] = 0
count_dict[line] += 1
count_dict.pop('', None)
output_str = ""
for w in sorted(count_dict, key=count_dict.get, reverse=True):
output_str += str(count_dict[w]) + " " + w + "\n"
temp_f = tempfile.NamedTemporaryFile()
temp_f.write(output_str)
# print(temp_f.name)
subprocess.Popen(['less', temp_f.name], stdin=subprocess.PIPE).communicate()
|
"""
Name:Matthew Coutts
Class: CMSPC 462 - FA 2020
Project 2 - Create a BT and a BST and implement functions
Date: October 15th, 2020
"""
from big_o import big_o
import time ##first we import the time function
BSTtime = [] # this will hold our time for the function BST
BT_Time = [] # this will hold our time for the function BT
class BT:
#this will be our constructor
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def buildTree(self, data):
if data == self.data:
return
# if the data inserted is less than cur value it'll
# go into the left node
if data < self.data:
if self.left:
self.left.buildTree(data)
else:
self.left = BT(data)
# if the data is greater than the value
# of the current node then it goes right
else:
if self.right:
self.right.buildTree(data)
else:
self.right = BT(data)
def findMinNode(self):
if self.left is None:
return self.data
return self.left.findMinNode()
def findMaxNode(self):
if self.right is None:
return self.data
return self.right.findMaxNode()
# this will first visit left node
# then the root node and finally
# the right node and display them in
# specific order
def inOrderTrav(self):
elements = []
if self.left:
elements += self.left.inOrderTrav()
elements.append(self.data)
if self.right:
elements += self.right.inOrderTrav()
return elements
'''
First it visits left node, right node, and then
root node
'''
def postOrderTrav(self):
elements = []
if self.left:
elements += self.left.postOrderTrav()
if self.right:
elements += self.right.postOrderTrav()
elements.append(self.data)
return elements
def preOrderTrav(self):
elements = [self.data]
if self.left:
elements += self.left.preOrderTrav()
if self.right:
elements += self.right.preOrderTrav()
return elements
listTree= [ 2, 4, 22, 34, 9, 6, 67, 42, 55, 70, 120, 99, 200]
listBT = BT(6) ## BT will not be created unless data is given as param
for e in listTree: #this puts all the elements in listTree into the tree
listBT.buildTree(e)
print("Binary Tree \n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("|||\t\tExample1\t\t|||")
print("Maximum node in BT: \n", listBT.findMaxNode())
print("Minimum node in BT: \n",listBT.findMinNode())
print("Post Order: \n", listBT.postOrderTrav())
print("Pre Order: \n", listBT.preOrderTrav())
print("In Order: \n", listBT.inOrderTrav())
listTree2= [ 5,6,7,8,9,10,22,600,2]
listBT2 = BT(3) ## BT will not be created unless data is given as param
for e in listTree2: #this puts all the elements in listTree into the tree
listBT2.buildTree(e)
print(" \n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("|||\t\tExample2\t\t|||")
print("Maximum node in BT: \n", listBT2.findMaxNode())
print("Minimum node in BT: \n",listBT2.findMinNode())
print("Post Order: \n", listBT2.postOrderTrav())
print("Pre Order: \n", listBT2.preOrderTrav())
print("In Order: \n", listBT2.inOrderTrav())
listTree3= [ 10,2,7,8,9,2,3,3,5,6,999]
listBT3 = BT(9) ## BT will not be created unless data is given as param
for e in listTree3: #this puts all the elements in listTree into the tree
listBT3.buildTree(e)
print(" \n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("|||\t\tExample3\t\t|||")
print("Maximum node in BT: \n", listBT3.findMaxNode())
print("Minimum node in BT: \n",listBT3.findMinNode())
print("Post Order: \n", listBT3.postOrderTrav())
print("Pre Order: \n", listBT3.preOrderTrav())
print("In Order: \n", listBT3.inOrderTrav())
class BST:
# this is our constructor
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# insert func to insert the data according to it's amount
def buildSTree(self, data):
if data == self.data:
return
# if the data inserted is less than cur value itll
# go into the left node
if data < self.data:
if self.left:
self.left.buildSTree(data)
else:
self.left = BST(data)
# if the data is greater than the value
# of the current node then it goes right
else:
if self.right:
self.right.buildSTree(data)
else:
self.right = BST(data)
# this will first visit left node
# then the root node and finally
# the right node and display them in
# specific order
def inOrderTrav(self):
elements = []
if self.left:
elements += self.left.inOrderTrav()
elements.append(self.data)
if self.right:
elements += self.right.inOrderTrav()
return elements
'''
First it visits left node, right node, and then
root node
'''
def postOrderTrav(self):
elements = []
if self.left:
elements += self.left.postOrderTrav()
if self.right:
elements += self.right.postOrderTrav()
elements.append(self.data)
return elements
def preOrderTrav(self):
elements = [self.data]
if self.left:
elements += self.left.preOrderTrav()
if self.right:
elements += self.right.preOrderTrav()
return elements
def findMinNode(self):
if self.left is None:
return self.data
return self.left.findMinNode()
def findMaxNode(self):
if self.right is None:
return self.data
return self.right.findMaxNode()
def deleteNode(self, data, val):
if self is None: ##none is left and right val
return self
if data < self.data: #if input is less than current
self.left = deleteNode(self.left, data) #go to the left node
elif (data > self.data): #if input is higher, go to right node
self.right = deleteNode(self.right, data)
else:
if self.left is None:
temp = self.right #if left is none then assign temp to right
self.left = None
return temp
elif self.right is None: #if right is none, assign temp to left
temp = self.left
self.left = None
return temp
temp = findMinNode(self.right) ##node with two children, get the smallest right subtree
self.data = temp.data ##copy the right small subtree
self.right = deleteNode(self.right, temp.data) #delete smallest right subtree
return self
def PrintTree(self): ##print to see what values are in the tree
if self.left:
self.left.PrintTree()
print(self.data)
if self.right:
self.right.PrintTree()
def addBST(self, tree2):
for e in tree2:
self.buildSTree(e)
return tree2
listBST1 = BST(2)
l2 = [6, 4, 22, 9, 6, 42, 34, 55, 70, 99, 67,200,120]
for e in l2:
listBST1.buildSTree(e)
print("\nBinary Search Tree \n ~~~~~~~~~~~~~~~~~~~~")
print("Post Order: \n", listBST1.postOrderTrav())
print("Pre Order: \n", listBST1.preOrderTrav())
print("In Order: \n", listBST1.inOrderTrav())
print("Max node in BST: \n", listBST1.findMaxNode())
print("Min node in BST: \n", listBST1.findMinNode())
listBST2 = BST(2)
l2 = [6, 4, 22, 9, 6, 42, 34, 55, 70, 99, 67,200,120]
for e in l2:
listBST2.buildSTree(e)
print("\nBinary Search Tree \n ~~~~~~~~~~~~~~~~~~~~")
print("Post Order: \n", listBST2.postOrderTrav())
print("Pre Order: \n", listBST2.preOrderTrav())
print("In Order: \n", listBST2.inOrderTrav())
print("Max node in BST: \n", listBST2.findMaxNode())
print("Min node in BST: \n", listBST2.findMinNode())
print("~~~~~~~~~~~~~~~~~~~~~~~\n")
print("|||\t\tExample3\t\t|||")
##creating a new tree
deleteTree = [2,3,4,5,6,7]
listBST3 = BST(1)
for e in deleteTree:
listBST3.buildSTree(e)
print("Maximum node in BT: \n", listBST3.findMaxNode())
print("Minimum node in BT: \n",listBST3.findMinNode())
print("Post Order: \n", listBST3.postOrderTrav())
print("Pre Order: \n", listBST3.preOrderTrav())
print("In Order: \n", listBST3.inOrderTrav())
listBST3.deleteNode(1)
print (listBST3.inOrderTrav())
listBST2.addBST(listBST3)
print("Tree combination: ", )
|
"""
*** BaSuZ3 ***
This problem was asked by Airbnb.
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
Follow-up: Can you do this in O(N) time and constant space?
"""
# Solución / Solution - class, function, etc.
def agrega_uwus(texto, uwu = 'uwu'):
"""
Acá se coloca la descripción de la función (lo que se muestra cuando colocas el maus por encima de ella), por ejemplo:\n
agrega_uwus(texto, uwu = 'uwu')\n
[texto -> string | uwu -> string | return -> string]
Toma un string "texto" y le añade el parámetro "uwu" al inicio y al final.
Por defecto el valor de la variable "uwu" es 'uwu'.
>>> agrega_uwus('Dr. Aven')
> 'uwu Dr. Aven uwu'
"""
return "uwu " + texto + " uwu"
dr_aven = "BaSuZ3"
uwus = agrega_uwus(dr_aven)
print(uwus) |
"""
*** BaSuZ3 ***
This problem was asked by Apple.
Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
"""
# Solución / Solution - class, function, etc.
def agrega_uwus(texto, uwu = 'uwu'):
"""
Acá se coloca la descripción de la función (lo que se muestra cuando colocas el maus por encima de ella), por ejemplo:\n
agrega_uwus(texto, uwu = 'uwu')\n
[texto -> string | uwu -> string | return -> string]
Toma un string "texto" y le añade el parámetro "uwu" al inicio y al final.
Por defecto el valor de la variable "uwu" es 'uwu'.
>>> agrega_uwus('Dr. Aven')
> 'uwu Dr. Aven uwu'
"""
return "uwu " + texto + " uwu"
dr_aven = "BaSuZ3"
uwus = agrega_uwus(dr_aven)
print(uwus) |
#!/usr/bin/env python3
if __name__ == '__main__':
# Text in Python is represented as things called strings. You can use single or double quotes to assign a string.
#
a = 'This is a string.'
b = "This is also a string."
c = "So's this, and it has an appostrophe."
d = str()
print(a, b, c)
# You can use strings with for loops, and get a character at a time.
for c in 'I am a string':
print(c)
# There are a number of things you can do to manipulate strings. Here are some of them.
print('This is a string'.split()) # Split into a list. You can choose what you split on as a parameter to split()
print('This is a string'.replace('string', 'line of text')) # You can replace things in the string.
print('string' in 'This is a string') # Checking if something is in there. |
import overload
print("===================")
print("print(overload.foo())")
print(overload.foo())
print("===================")
print("overload.foo(4, 3.0)")
overload.foo(4, 3.0)
print("===================")
print("print(overload.foo(0, 3.0, 56, 2.0))")
print(overload.foo(0, 3.0, 56, 2.0))
print("===================")
def a():
return 25
print("print(overload.foo(a))")
print(overload.foo(a))
|
from constants import *
color = [BLUE, RED, GREEN, WHITE, YELLOW, VIOLET, AQUA]
def text_objects(text, font, color):
"""
Sets up text format and returns it
:param str text: text to format
:param font: Font
:param color: Color of text
"""
text_surface = font.render(text, True, color)
return text_surface, text_surface.get_rect()
def button(text, x, y, w, h, ic, ac, surface):
"""
Creates button and returns False if clicked and True if not clicked
:param str text: text to display on the button
:param int x: x parameter of button's localization
:param int y: y parameter of button's localization
:param int w: width of the button
:param int h: height of the button
:param ic: inactive color of the button
:param ac: active color of the button
:param surface: surface for the button to be displayed on
"""
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(surface, ac, (x, y, w, h))
if click[0] == 1:
return False
else:
pygame.draw.rect(surface, ic, (x, y, w, h))
small_text = pygame.font.Font(None, BUTTON_FONT_SIZE)
text_surf, text_rect = text_objects(text, small_text, BLACK)
text_rect.center = ((x+(w/2)), (y+(h/2)))
surface.blit(text_surf, text_rect)
return True
def message_display(text, surface, font_size, color, localization):
"""
Displays text on screen.
:param str text: text to display
:param surface: surface for the text to be displayed on
:param font_size: font size of the text
:param color: color of the text
:param localization: localization of the text
"""
large_text = pygame.font.Font(None, font_size)
text_surf, text_rect = text_objects(text, large_text, color)
text_rect.center = localization
surface.blit(text_surf, text_rect)
class GameMenu:
"""Class that handles game menu"""
def __init__(self, game_display, settings):
self.__gameDisplay = game_display
self.__settings = settings
def game_intro(self):
"""Game intro screen."""
intro = True
while intro:
click = pygame.mouse.get_pressed()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN or click[0] == 1 or click[2] == 1:
intro = False
if event.type == pygame.QUIT:
pygame.quit()
quit()
self.__gameDisplay.surface.blit(self.__gameDisplay.get_background(), [0, 0])
message_display(GAME_NAME, self.__gameDisplay.surface, INTRO_FONT_SIZE, GAME_NAME_COLOR,
((self.__gameDisplay.WIDTH / 2), (self.__gameDisplay.HEIGHT / 6)))
message_display(PRESS_KEY, self.__gameDisplay.surface, int(INTRO_FONT_SIZE/2), PRESS_KEY_COLOR,
((self.__gameDisplay.WIDTH / 2), (self.__gameDisplay.HEIGHT / 1.3)))
pygame.display.update()
self.__gameDisplay.clock.tick(MENU_FPS)
def game_menu(self):
"""Game menu screen with buttons handling player actions."""
not_playing = True
about = False
settings = False
quit_st = False
while not_playing:
if about:
self.game_about()
if settings:
self.game_settings()
for event in pygame.event.get():
if event.type == pygame.QUIT or quit_st:
pygame.quit()
quit()
self.__gameDisplay.surface.blit(self.__gameDisplay.get_background(), [0, 0])
not_playing = button(PLAY, int((DISPLAY_WIDTH / 2) - 100),
int(DISPLAY_HEIGHT / 8), 200, 100, GREEN, LIGHT_GREEN, self.__gameDisplay.surface)
settings = not button(SETTINGS, ((DISPLAY_WIDTH / 2) - 100),
(DISPLAY_HEIGHT / 3), 200, 100, RED, LIGHT_RED, self.__gameDisplay.surface)
about = not button(ABOUT, ((DISPLAY_WIDTH / 2) - 100),
(DISPLAY_HEIGHT / 2), 200, 100, BLUE, LIGHT_BLUE, self.__gameDisplay.surface)
quit_st = not button(QUIT, ((DISPLAY_WIDTH / 2) - 100),
(DISPLAY_HEIGHT / 1.5), 200, 100, WHITE, GRAY, self.__gameDisplay.surface)
pygame.display.update()
self.__gameDisplay.clock.tick(MENU_FPS)
def game_about(self):
"""Screen with name of author and instructions to the game."""
about = True
click = (0, 0, 0)
while about:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
about = False
if click[0] == 1 or click[2] == 1:
about = False
if event.type == pygame.QUIT:
pygame.quit()
quit()
click = pygame.mouse.get_pressed()
self.__gameDisplay.surface.fill(BLACK)
message_display(GAME_ABOUT, self.__gameDisplay.surface, ABOUT_FONT_SIZE,
GAME_ABOUT_COLOR, ((DISPLAY_WIDTH/2), (DISPLAY_HEIGHT/8)))
message_display(PLAYER_CONTROLS, self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE+20,
AQUA, ((DISPLAY_WIDTH / 4.5), ((DISPLAY_HEIGHT / 8) + 130)))
message_display(PLAYER0_CONTROLS, self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE,
RED, ((DISPLAY_WIDTH / 4.5), ((DISPLAY_HEIGHT / 8)+200)))
message_display(PLAYER1_CONTROLS, self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE,
GREEN, ((DISPLAY_WIDTH / 4.5), ((DISPLAY_HEIGHT / 8)+250)))
message_display(PLAYER2_CONTROLS, self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE,
BLUE, ((DISPLAY_WIDTH / 4.5), ((DISPLAY_HEIGHT / 8)+300)))
message_display(PLAYER3_CONTROLS, self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE,
YELLOW, ((DISPLAY_WIDTH / 4.5), ((DISPLAY_HEIGHT / 8)+350)))
message_display(" - Clears map", self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE,
color[0], ((DISPLAY_WIDTH / 1.35), ((DISPLAY_HEIGHT / 8) + 150)))
pygame.draw.circle(self.__gameDisplay.surface, color[0], (int((DISPLAY_WIDTH / 1.35)-220),
int((DISPLAY_HEIGHT / 8) + 150)), POWERUP_SIZE)
message_display(" - Speeds up enemies", self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE,
color[1], ((DISPLAY_WIDTH / 1.35), ((DISPLAY_HEIGHT / 8) + 200)))
pygame.draw.circle(self.__gameDisplay.surface, color[1], (int((DISPLAY_WIDTH / 1.35) - 220),
int((DISPLAY_HEIGHT / 8) + 200)), POWERUP_SIZE)
message_display(" - Makes enemies' turn bigger", self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE,
color[2], ((DISPLAY_WIDTH / 1.35), ((DISPLAY_HEIGHT / 8) + 250)))
pygame.draw.circle(self.__gameDisplay.surface, color[2], (int((DISPLAY_WIDTH / 1.35) - 220),
int((DISPLAY_HEIGHT / 8) + 250)), POWERUP_SIZE)
message_display(" - Ghost mode", self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE,
color[3], ((DISPLAY_WIDTH / 1.35), ((DISPLAY_HEIGHT / 8) + 300)))
pygame.draw.circle(self.__gameDisplay.surface, color[3], (int((DISPLAY_WIDTH / 1.35) - 220),
int((DISPLAY_HEIGHT / 8) + 300)), POWERUP_SIZE)
message_display(" - Makes enemies bigger", self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE,
color[4], ((DISPLAY_WIDTH / 1.35), ((DISPLAY_HEIGHT / 8) + 350)))
pygame.draw.circle(self.__gameDisplay.surface, color[4], (int((DISPLAY_WIDTH / 1.35) - 220),
int((DISPLAY_HEIGHT / 8) + 350)), POWERUP_SIZE)
message_display(" - Reverses enemies' keys", self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE,
color[5], ((DISPLAY_WIDTH / 1.35), ((DISPLAY_HEIGHT / 8) + 400)))
pygame.draw.circle(self.__gameDisplay.surface, color[5], (int((DISPLAY_WIDTH / 1.35) - 220),
int((DISPLAY_HEIGHT / 8) + 400)), POWERUP_SIZE)
message_display(" - Enemies cannot pass walls", self.__gameDisplay.surface, PLAYER_CONTROLS_FONT_SIZE,
color[6], ((DISPLAY_WIDTH / 1.35), ((DISPLAY_HEIGHT / 8) + 450)))
pygame.draw.circle(self.__gameDisplay.surface, color[6], (int((DISPLAY_WIDTH / 1.35) - 220),
int((DISPLAY_HEIGHT / 8) + 450)), POWERUP_SIZE)
pygame.display.update()
self.__gameDisplay.clock.tick(MENU_FPS)
def game_settings(self):
"""Screen with settings of the game."""
settings = True
while settings:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
settings = False
if event.type == pygame.QUIT:
pygame.quit()
quit()
self.__gameDisplay.surface.fill(BLACK)
number_clicked = not button(NUMBER_OF_PLAYERS, ((DISPLAY_WIDTH / 2) - 150),
(DISPLAY_HEIGHT / 8), 300, 150, GREEN, LIGHT_GREEN, self.__gameDisplay.surface)
powerups = not button(GAME_MODE, ((DISPLAY_WIDTH / 2) - 150),
(DISPLAY_HEIGHT / 1.7), 300, 150, BLUE, LIGHT_BLUE, self.__gameDisplay.surface)
if number_clicked:
if self.__settings.get_number() == 4:
self.__settings.set_number(2)
else:
self.__settings.set_number(self.__settings.get_number() + 1)
if powerups:
self.__settings.set_mode(not self.__settings.get_mode())
message_display(str(self.__settings.get_number()), self.__gameDisplay.surface, int(NUMBER_FONT_SIZE / 2), GREEN,
((self.__gameDisplay.WIDTH / 1.3), ((self.__gameDisplay.HEIGHT / 8) + 75)))
message_display(str(self.__settings.get_mode()), self.__gameDisplay.surface, int(NUMBER_FONT_SIZE / 2), GREEN,
((self.__gameDisplay.WIDTH / 1.3), ((self.__gameDisplay.HEIGHT / 1.7) + 75)))
pygame.display.update()
self.__gameDisplay.clock.tick(13)
|
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
"""
@author: Henrique Igai Wang
Class that represents each item of customer's cart
"""
from classes.item_class import Item
class Cart:
def __init__(self):
self.productList = []
def __str__(self):
string = ""
productList = self.getProductList()
for i in range(len(productList)):
string += "Product:{}; Quantity:{} \n".format(productList[i].getName(), productList[i].getQuantity())
return string
def addProduct(self, item):
try:
productName = item.getName()
print(productName)
i = self.haveProduct(productName)
if (i >= 0):
self.productList[i].addQuantity(1)
else:
self.productList.append(item)
return True
except:
return False
def getProductList(self):
return self.productList
# Receive String productName
# Return int i >= 0 that represents the position of productName in the dataBase
# Return -1 if there is no product in the database with its name as productName
def haveProduct(self, productName):
productList = self.getProductList()
for i in range(len(productList)):
currProductName = productList[i].getName()
if (productName == currProductName):
return i
return -1
|
def login():
username = input("Enter username: ")
password = input("Enter password: ")
if username == "admin" and password == "1234":
return True
else:
return False
def showMenu():
print(15*"-" + "Menu" + 15*"-")
print("1. Vat Calculator")
print("2. Price Calculator")
print("Choose 1 or 2")
def menuSelect():
userSelected = input(">>")
if userSelected == "1":
print("Vat Price = ", vatCalculate(int(input("Price : "))), "Baht")
elif userSelected == "2":
print("Total Price = ", priceCalculate(), "Baht")
return
def vatCalculate(totalPrice):
vat = 7
result = totalPrice + (totalPrice * vat / 100)
return result
def priceCalculate():
price1 = int(input("First Product Price : "))
price2 = int(input("Second Product Price : "))
return vatCalculate(price1 + price2)
if login() == True:
showMenu()
menuSelect()
else:
print("Try again !!") |
__author__ = 'isaac'
"""
Written By: Gil Rael
The following program prints the A Friday - Fridays that are scheduled days off in 2017,
The program takes the hard coded first A Friday that is a scheduled day off in January 2017
and then calculates the other A Fridays in 2017 based on this initial date.
Planning
Modules Needed
from datetime import *
Classes
A_Friday
Attributes Methods
def_init__(self):
# hard coded def__str__
initial_a_friday_date -> str def calculate_a_friday(self):
a_friday = initial_a_friday_date + 14 days
"""
from datetime import *
class AFriday(object):
def __init__(self):
self.counter = 0
self.initial_a_friday_date = "1/6/17"
print("\nThe A Friday Dates In The Year 2017:\n")
self.initial_a_friday_date = datetime.strptime(self.initial_a_friday_date, "%m/%d/%y")
print(self.initial_a_friday_date)
# For testing purposes print(self.date_1.year)
# For testing purposes int(self.date_1.year)
self.next_a_friday_date = self.initial_a_friday_date + timedelta(days=14)
print(self.next_a_friday_date)
while (self.counter < 24):
self.counter = self.counter + 1
self.next_a_friday_date = self.next_a_friday_date + timedelta(days=14)
print(self.next_a_friday_date)
def main():
# creates and AFriday object
new_date = AFriday()
if __name__ == "__main__":
main()
|
server = []
while True:
sname = input("Please enter any server ")
if sname in server:
print(sname,"Server Exist in our inventory")
else:
print(sname,"Server not found")
print("to add --",sname,"enter 'y': or exit (press any other key:)")
i = input()
if i == 'y' :
server.append(sname)
print("\nCurrent server list:",server)
else :
print("Do come back again, thanks!!")
break
|
#my_list = [2,3,4,5,6,8,10]
my_list = input("ENTER YOUR LIST ")
my_list=list(my_list)
print(type(my_list))
print "MY ORIGINAL LIST IS" ,my_list
for i in range(len(my_list)):
if ((my_list[i] % 2) == 0 ):
print( str(my_list[i]) + " -->element is even")
print('TESTING')
else:
print( str(my_list[i])+" -->element is ODD")
|
import unittest
from domain.car import Car
class TestCar(unittest.TestCase):
def test_create(self):
car=Car("C1",2007,780)
self.assertEqual(car.get_fuel(),"C1")
self.assertEqual(car.get_year(),2007)
self.assertEqual(car.get_price(),780)
def test_set(self):
car=Car()
car.set_fuel("C1")
car.set_price(780)
car.set_year(2007)
self.assertEqual(car.get_fuel(),"C1")
self.assertEqual(car.get_year(),2007)
self.assertEqual(car.get_price(),780)
if __name__=="__main__":
unittest.main() |
#! python3
# incidentParser.py - parses incident data from the Boca Police Department and cleans it up.
import re
import csv
raw_incident_file = "bocaIncidents.csv"
headers = ['type', 'date', 'address'];
def main():
parse_rows();
write_new_file();
print(*parsed_rows, sep='\n')
parsed_rows = []
def parse_rows():
with open(raw_incident_file) as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
crime_type = row[0]
# Remove incident number with regex
if row[2] == '':
row[1] = re.sub('\d{10}', '', row[1]);
crime_date = row[1].split(',')[0];
crime_year = row[1].split()[2];
crime_address = re.sub('^.+?\d{4}', '', row[1]);
crime_address = crime_address.title().strip() + ', Boca Raton, Florida'
else:
row[1] = re.sub('\d{10}', '', row[1]);
crime_date = row[1].split(',')[0];
crime_year = row[1].split()[2];
crime_address = row[2];
crime_address = crime_address.title().strip() + ', Boca Raton, Florida'
parsed_rows.append([crime_type, crime_date + ', ' + crime_year, crime_address])
def write_new_file():
with open('boca-incidents-final.csv', 'w', newline='') as finalfile:
writer = csv.writer(finalfile)
writer.writerow(headers)
writer.writerows(parsed_rows)
if __name__ == "__main__":
print("Cleaning file now...");
main();
print("All done!");
|
def main():
num=0
print('Loop 1:')
while num < 6:
print(num)
num += 1
print('\nLoop 2:')
for num in range(6):
print(num)
print('\nLoop 3:')
for num in range(0,6):
print(num)
print('\nLoop 4:')
for num in range(1,11,2):
print(num)
print('\nLoop 5:')
for num in range(10,0,-1):
print(num)
print('\nLoop 6:')
nums = [0,1,2,3,4,5] #list
for num in nums:
print(num)
print('\nLoop 7:')
nums = (0,1,2,3,4,5) #tuple
for num in nums:
print(num)
grades = {'English':97, 'Math':93, 'Art':74, 'Music':86}
print('\nLoop 8:')
for course in grades:
print(course)
print('\nLoop 9:')
for course in grades.keys():
print(course)
print('\nLoop 10:')
for grade in grades.values():
print(grade)
print('\nLoop 11:')
for num in range(6):
print(num)
if num > 3:
break
print('\nLoop 12:')
for num in range(6):
if num==3:
continue
print(num)
main() |
import math
user_name = input("What is your name? ")
# old way with concatenation:
greeting = "Hello, " + user_name + "!"
# or with string formatting:
greeting = "Hello, {0}!".format(user_name)
# new way with f-string:
greeting = f"Hello, {user_name}!"
print (greeting)
# format specification is also available:
pi_statement = f"pi is {math.pi:.4f}"
print (pi_statement) |
import random
def get_rand_nums(low,high,num):
for number in range(num):
yield random.randint(low,high)
print('First time through:')
for num in get_rand_nums(1,100,5):
print(num)
print('Second time through:')
for num in get_rand_nums(1,100,5):
print(num) |
from random import randint
def roll_dice():
return (randint(1,6), randint(1,6), randint(1,6))
def play():
n=0
while True:
n+=1
r = roll_dice()
print('{}: {},{},{}'.format(n, r[0], r[1], r[2]))
if r[0] == r[1] == r[2]:
print('Wow! Triples!')
input()
def main():
input('Press ENTER to roll the dice. ')
play()
main() |
#problem 1
def initialLetterCount(wordList):
dict = {}
for word in wordList:
firstLetter = word[0]
if firstLetter not in dict:
dict[firstLetter] = 1
else:
dict[firstLetter] = dict[firstLetter] + 1
return dict
horton = ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
print(initialLetterCount(horton))
#problem2
def initialLetters(wordList):
mydictionary={}
for i in wordList:
if i[0] not in mydictionary:
mydictionary[i[0]]=[i]
elif i not in mydictionary[i[0]]:
mydictionary[i[0]].append(i)
return mydictionary
horton = ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say', 'with']
print(initialLetters(horton))
#problem3
def shareALetter(wordList):
mydictionary = {}
for word in wordList:
if word not in mydictionary:
mydictionary[word] = []
for i in mydictionary.keys():
for word in wordList:
checkmatch = False
for n in i:
if n in word:
checkmatch=True
break
if checkmatch:
mydictionary[i].append(word)
return mydictionary
print(shareALetter(horton))
{'I': ['I'], 'say': ['say', 'what', 'mean', 'and'], 'what': ['say', 'what', 'mean',
'and'], 'mean': ['say', 'what', 'mean', 'and'], 'and': ['say', 'what', 'mean', 'and']}
|
Sum = 0
#This Function calculates the sum of the square of each digitt of any number
def sumOfSquares(a):
global Sum
Sum =(a%10)**2 + Sum
if a == 0:
a = Sum
Sum = 0
return a
a = a/10
return sumOfSquares(a)
def isHappy(a):
if sumOfSquares(a) == 4:
return False
if sumOfSquares(a) == 1:
return True
else:
return isHappy(sumOfSquares(a))
nu =int( raw_input("Enter a number to check its happiness:"))
print isHappy(nu)
print('ahmaddoooo')
|
import random
min = 1
max = 6
roll_again = "y"
while roll_again is "y":
print("rolling the dices...")
print("the values are")
print(random.randint(min,max))
print(random.randint(1,6))
roll_again = input("roll the dices again? ")
|
# 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':
carry = 0
p = l1
q = l2
curr = dummy = ListNode(0)
while p or q:
if p:
x = p.val
else:
x = 0
if q:
y = q.val
else:
y = 0
total = carry + x + y
carry = total // 10
curr.next = ListNode(total % 10)
curr = curr.next
if p:
p = p.next
if q:
q = q.next
if carry > 0:
curr.next = ListNode(1)
return dummy.next
|
"""
===================================================
Introduction to Machine Learning (67577)
===================================================
Skeleton for the decision tree classifier with real-values features.
Training algorithm: CART
Author: Noga Zaslavsky
Edited: Yoav Wald, May 2018
"""
import numpy as np
import ex4_tools
class Node(object):
""" A node in a real-valued decision tree.
Set all the attributes properly for viewing the tree after training.
"""
def __init__(self, leaf = True, left = None, right = None, samples = 0,
feature = None, theta = 0.5, misclassification = 0,
label = None):
"""
Parameters
----------
leaf : True if the node is a leaf, False otherwise
left : left child
right : right child
samples : number of training samples that got to this node
feature : a coordinate j in [d], where d is the dimension of x (only for internal nodes)
theta : threshold over self.feature (only for internal nodes)
label : the label of the node, if it is a leaf
"""
self.leaf = leaf
self.left = left
self.right = right
self.samples = samples
self.feature = feature
self.theta = theta
self.label = label
class DecisionTree(object):
""" A decision tree for binary classification.
max_depth - the maximum depth allowed for a node in this tree.
Training method: CART
"""
def __init__(self,max_depth):
self.root = None
self.max_depth = max_depth
self.num_features = 0
def train(self, X, y):
"""
Train this classifier over the sample (X,y)
"""
if len(X) == 0:
raise Exception("number of train sample should be positive.")
if len(X) != len(y):
raise Exception("different num of samples")
self.CART(X,y,None,self.max_depth)
def train(self, X, y):
"""
Train this classifier over the sample (X,y)
"""
if len(X) == 0:
raise Exception("you can't train without examples.")
A = list()
for i in range(len(X[0])):
A.append(np.sort(np.unique(X[:,i])))
self.root = self.CART(X, y, np.array(A), 0)
def CART(self,X, y, A, depth):
"""
Gorw a decision tree with the CART method ()
Parameters
----------
X, y : sample
A : array of d*m real features, A[j,:] row corresponds to thresholds over x_j
depth : current depth of the tree
Returns
-------
node : an instance of the class Node (can be either a root of a subtree or a leaf)
"""
self.root = Node()
self.CART_helper(self.root,X,y,A,depth)
return self.root
def get_best_split(self, X,y,D = []):
m, d = X.shape
F, J, theta = [0]*2, [0]*2, [0]*2
D = np.array([1/m] * m)
for b in [0,1]:
s = 2*b - 1
F[b], theta[b], J[b] = D[y==s].sum(), X[:,0].min()-1, 0
for j in range(d): # go over all features
ind = np.argsort(X[:, j])
Xj = np.sort(X[:, j]) # sort by coordinate j
Xj = np.hstack([Xj,Xj.max()+1])
f = D[y==s].sum()
for i in range(m): # check thresholds over Xj for improvement
f -= s*y[ind[i]]*D[ind[i]]
if f < F[b] and Xj[i] != Xj[i+1]:
F[b], J[b], theta[b] = f, j, (Xj[i]+Xj[i+1])/2
b = np.argmin(F)
return theta[b], J[b], 2*b-1
def split_data(self, X, y, theta, j, s):
X_left,y_left,X_right,y_right = None,None,None,None
# if s == 1:
# X_left = X[X[:,j] >= theta]
# y_left = y[X[:,j] >= theta]
# X_right = X[X[:,j] < theta]
# y_right = y[X[:,j] < theta]
# else:
m, d = np.shape(X)
X_left = X[X[:, j] <= theta]
y_left = y[X[:, j] <= theta]
X_right = X[X[:, j] > theta]
y_right = y[X[:, j] > theta]
if np.shape(X_left) == (0,) or np.shape(X_left) == (m, d):
X_left = X[:int(m / 2), :]
y_left = y[:int(m / 2)]
X_right = X[int(m / 2):, :]
y_right = y[int(m / 2):]
return X_left,y_left,X_right,y_right
def check_for_zeros(self, label_left, label_right, feature, theta, X, y):
m, d = np.shape(X)
X_left = X[X[:, feature] <= theta]
y_left = y[X[:, feature] <= theta]
X_right = X[X[:, feature] > theta]
y_right = y[X[:, feature] > theta]
if np.shape(X_left) == (0,) or np.shape(X_left) == (m,d):
X_left = X[:int(m/2),:]
y_left = y[:int(m/2)]
X_right = X[int(m/2):,:]
y_right = y[int(m/2):]
if np.shape(X_left) == (0,):
label_left = label_right
if np.shape(X_left) == (m,d):
label_right = label_left
return X_left, y_left, X_right, y_right, label_left, \
label_right
def CART_helper(self, root, X, y, A, depth):
# find best split
if len(X) <= 1 :
root.leaf = True
return
theta,j,s = self.get_best_split(X,y)
X_left,y_left,X_right,y_right = self.split_data(X,y,theta,j,s)
# add the nodes
root.samples = len(X)
root.feature = j
root.theta = theta
root.leaf = False
root.left, root.right = Node(),Node()
root.left.leaf, root.right.leaf= False, False
root.left.label, root.right.label = s, (-1 * s)
if len(X) == len(X_left):
root.right.label = root.label.left
if len(X_left) == 0:
root.left.label = root.right.left
# split the data
# if we are in a good depth, continue recursively
if depth < self.max_depth:
self.CART_helper(root.left,X_left,y_left,A,depth+1)
self.CART_helper(root.right,X_right,y_right,A,depth+1)
else:
root.right,root.left,root.leaf = None, None, True
def predict(self, X):
"""
Returns
-------
y_hat : a prediction vector for X
"""
return np.array([self.predict_single(x) for x in X])
def predict_single(self,x):
# todo: to change
# if len(x) != self.num_features:
# raise Exception("different number of features")
cur = self.root
while cur.leaf == False:
if x[cur.feature] >= cur.theta:
cur = cur.right
else:
cur = cur.left
return cur.label
def error(self, X, y):
"""
Returns
-------
the error of this classifier over the sample (X,y)
"""
ans = self.predict(X)
return np.sum(np.logical_not(np.equal(ans, y))) / len(X) |
def play_quiz():
print("Determining your Patronus....")
print("When chosing your answer, please put the letter that is in brackets.")
print(" ")
print(" ")
print("You enter the woods, and see a small, shapeless light hovering before you.")
print("As you try to get closer to it, the shapeless light seems to move away from you.")
print("Curious, you follow the light to see where it goes.")
print(" ")
print("*_*_*_*_*_*_*_*_*_*_*_*_*")
print(" ")
print("A few feet into the woods, the light seems to stop.")
print("*...* Suddenly, you hear a quiet voice say:")
print("You are ready to begin your journey....")
print("You can only chose one, (b)lack or (w)hite?")
Spoints = 0
Opoints = 0
JRpoints = 0
Hpoints = 0
BW = (input("~,.~*,.~ "))
if BW=="b" or BW=="B":
Hpoints += 1
Opoints += 1
else:
if BW=="w" or BW=="W":
JRpoints += 1
Spoints += 1
print(" ")
print(" ")
print("Once answering the question, the light grows and becomes little brighter.")
print("*~,.,~* The light then seems to continue into the forest")
print("A few feet more, into the woods, the light stops again.")
print("*...* The quiet voice comes back and says:")
print("If you could be known for one thing what would you chose?")
print(" ")
print(" (L)eader, (H)ardworker, (F)earless, (U)nique")
Know = (input("~,.~*,.~ "))
if Know=="L" or Know=="l":
Spoints += 1
elif Know=="H" or Know=="h":
Opoints += 1
elif Know=="F" or Know=="f":
JRpoints += 1
else:
if Know =="U" or Know=="u":
Hpoints += 1
print(" ")
print(" ")
print("Once answering the question, the light grows and becomes little brighter.")
print("*~,.,~* The light then seems to continue into the forest")
print("A few feet more, into the woods, the light stops again.")
print("*...* The quiet voice comes back and says:")
print("Now you must face a monster who threatens the lives of you, your loved ones, and the world.")
print("Pick the best way to defeat the monster to save everyone:")
print("")
print("(A): The monster is only here for one person. I will get everyone to saftey before fighting the monster myself.")
print("(B): The monster is not a monster. In fact, I've read all about it and some chamomile tea will calm it down.")
print("(C): I will fight side by side with my friends to defeat the monster and save the world!")
print("(D): There is a potion that can temporarily paralyze the monster. I've already made it.")
Mon = (input("~,.~*,.~ "))
if Mon=="a" or Mon=="A":
Spoints += 1
elif Mon =="B" or Mon=="b":
Hpoints += 1
elif Mon=="C" or Mon=="c":
JRpoints += 1
else:
if Mon=="d" or Mon=="D":
Opoints += 1
print(" ")
print(" ")
print("Once answering the question, the light grows and becomes little brighter.")
print("*~,.,~* The light then seems to continue into the forest")
print("A few feet more, into the woods, the light stops again.")
print("*...* The quiet voice comes back and says:")
print("Just a few more questions, you'll know soon.")
print(" ")
print("Suddenly, the forest seems to get brighter.")
print("To your left is a stream. To your right is a small hut.")
print("In front of you but in the distance are mountains.")
print("Behind you is a path.")
print("*...* The quiet voice says:")
print("Make your choice as to how to proceed.")
print("To the (s)tream, to the (h)ut, to the (m)ountains, or take the (p)ath?")
Way = (input("~,.~*,.~ "))
if Way=="p" or Way=="P":
Spoints += 1
elif Way=="s" or Way=="S":
Opoints += 1
elif Way=="m" or Way=="M":
JRpoints += 1
else:
if Way=="h" or Way=="H":
Hpoints += 1
print(" ")
print(" ")
print("Once answering the question, the light grows and becomes little brighter.")
print("The stream, the hut, the mountains, and the path disappear. The forest is just a forest")
print("*~,.,~* The light then seems to continue into the forest")
print("A few feet more, into the woods, the light stops again.")
print("*...* The quiet voice comes back and says:")
print("Two more questions to go. What is your favorite class?")
print("(D)efense Against the Dark Arts, (H)erbology, (Q)uidditch practice, or (D)ivination?")
Class = (input("~,.~*,.~ "))
if Class=="D" or Class=="d":
Spoints += 1
elif Class=="H" or Class=="h":
Hpoints += 1
elif Class=="Q" or Class=="q":
JRpoints +=1
else:
if Class=="D" or Class=="d":
Opoints += 1
print(" ")
print(" ")
print("Once answering the question, the light grows and becomes little brighter.")
print("*~,.,~* The light then seems to continue into the forest")
print("A few feet more, into the woods, the light stops again.")
print("*...* The quiet voice comes back and says:")
print("This is your last and final question ~ answer to life the universe and everything")
print(" ")
print("What is your purpose in life?")
print("To (d)iscover, to (p)rotect, to (c)reate, to (a)chieve")
Ans = (input("~,.~*,.~ "))
if Ans=="d" or Ans=="D":
Opoints += 1
elif Ans=="P" or Ans=="p":
Spoints += 1
elif Ans=="C" or Ans=="c":
Hpoints += 1
elif Ans=="a" or Ans=="A":
JRpoints += 1
else:
if Ans=="42":
print("I see what you did there, but please put in a real answer.")
ns = (input("~,.~*,.~ "))
if ns=="d" or ns=="D":
Opoints += 1
elif ns=="P" or ns=="p":
Spoints += 1
elif ns=="C" or ns=="c":
Hpoints += 1
elif ns=="a" or ns=="A":
JRpoints += 1
print(" ")
print("^, .~* ^_ ,. *")
print(" ")
if Spoints>Opoints and Spoints>JRpoints and Spoints>Hpoints:
print("Your patronus is a Stag")
print("Traditionally seen as ‘King of the Forest’, the stag is the protector of the other animals.")
elif Opoints>Spoints and Opoints>JRpoints and Opoints>Hpoints:
print("Your patronus is an Otter")
print("An otter represents 'that which is hidden, unknown but necessary within the personality.'")
elif JRpoints>Spoints and JRpoints>Opoints and JRpoints>Hpoints:
print("Your patronus is a Jack Russel Terrier")
print("Jack Russels represent loyalty and blind fearlessness.")
elif Hpoints>Spoints and Hpoints>JRpoints and Hpoints>Opoints:
print("Your patronus is a Hare")
print("Hares represent being carefree and thoughts beyond imagination.")
else:
print("You are not ready to have a Patronus now. Thank you for taking the time to go on this journey.")
if __name__ == '__main__':
play_hangman()
|
#!/usr/bin/env python3
'''matriz é uma lista com três elementos,
onde cada elemento é uma linha da matriz. '''
matriz = [[1,2,3], [4,5,6], 6,7,8]
print(matriz[1])
'''O primeiro índice seleciona a linha,
e o segundo índice seleciona a coluna.'''
print(matriz[1][1]) |
#!/usr/bin/env python3
# Exemplo de composicao
import math
# from raio import area
# from calcula_distancia import distancia
def area(raio):
return math.pi * raio**2
def distancia(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dquadrado = dx**2 + dy**2
resultado = math.sqrt(dquadrado)
return resultado
def area2(xc, yc, xp, yp):
raio = distancia(xc, yc, xp, yp)
resultado= area(raio)
print(resultado)
area2(1,2,4,6) |
#!/usr/bin/env python3
def valorAbs(x):
if x == 0:
return 0
elif x < 0:
return -x
elif x > 0:
return x
print(valorAbs(2))
print(valorAbs(-1))
print(valorAbs(0)) |
#!/usr/bin/env python3
def imprime_dobrado(nome):
print (nome, nome)
def concatDupla(part1 , part2):
concat = part1 + part2
imprime_dobrado(concat)
#Esta função recebe dois argumentos, concatena-os, e então
# imprime o resultado duas vezes.
# Podemos chamar a função com duas strings:
canto1 = 'Pie Jesus domine'
canto2 = ' Dona eis requiem.'
concatDupla(canto1,canto2) |
#!/usr/bin/env python3
"""O Teorema de Pitágoras diz que: “a soma dos quadrados dos catetos é igual
ao quadrado da hipotenusa.”"""
import math
def calculaHipotenusa(x, y):
z = x**2 + y**2
hipo = math.sqrt(z)
return hipo
print(calculaHipotenusa(9,12)) |
#!/usr/bin/env python3
import string
fruta = 'banana'
indice = str.find(fruta, 'na', 3)
print(f'posicao: {indice}') |
#!/usr/bin/env python3
def imprimeMultiplos(n, altura): # altura refere-se a tabuada nesse caso.
i = 1
while i <= altura:
print (n, 'x', i, '=', n*i, '\t',)
i = i + 1
print()
# teste da funcao imprimeMultiplos
# imprimeMultiplos(3, 2)
def imprimeTabMult(altura): # altura nesse caso refere-se ao numero maximo
i = 1
while i <= altura:
imprimeMultiplos(i, altura) # chamda da funcao imprimeMultiplos
i = i + 1
# chamada da funcao imprimeTabMult
imprimeTabMult(6) |
#!/usr/bin/env python3
def compara(x, y):
if x > y:
return 1
elif x == y:
return 0
else:
return -1
print(compara(1,2))
print(compara(3,2))
print(compara(3,3)) |
""" Display url using the default browser.
by frost (passion-xbmc.org)
"""
# Modules General
import webbrowser
from traceback import print_exc
# Modules XBMC
import xbmc
def notification( header="", message="", sleep=5000, icon="DefaultIconInfo.png" ):
""" Will display a notification dialog with the specified header and message,
in addition you can set the length of time it displays in milliseconds and a icon image.
"""
xbmc.executebuiltin( "XBMC.Notification(%s,%s,%i,%s)" % ( header, message, sleep, icon ) )
def launchUrl( url ):
try: webbrowser.open( url )
except: print_exc()
def Main( url, Addon ):
try:
# notify user
notification( Addon.getAddonInfo( "name" ), url, icon=Addon.getAddonInfo( "icon" ) )
# launch url
launchUrl( url )
except:
print_exc()
if ( __name__ == "__main__" ):
import sys
#print sys.argv
from xbmcaddon import Addon
Main( sys.argv[ 3 ], Addon( sys.argv[ 2 ] ) )
|
# Import random library
import random as Random
# Create function that takes in a parameter for the fruits array and the number of fruits requested
def pick_fruits(fruits, num_fruits=3):
# Set the value of the fruits array to the value returned by the get avalible fruits functtion
fruits = get_avalible_fruits(fruits)
# Create an empty array
picked_fruits = []
# Check if there are more fruits in the array than the requested amount
if len(fruits) > num_fruits:
# If so:
# Create a while loop that runs while the length of the picked_fruits array is less than the number of fruits requested
while len(picked_fruits) < num_fruits:
# Chose a random fruit from the fruit array
fruit_choice = Random.choice(fruits)
# Remove the chosen fruit from the array
fruits.remove(fruit_choice)
# Append the picked_fruits array with the new chosen fruit
picked_fruits.append(fruit_choice)
# Return the picked fruits array
return picked_fruits
else:
return fruits
# Create function that takes in an array of fruits called get_avalible_fruits
def get_avalible_fruits(fruits):
# Create an empty array to store the avalible fruits
avalible_fruits = []
# Create a for loop that iterates through all of the fruits
for fruit in fruits:
# If the fruit does not start with a vowel:
if fruit[0].lower() not in ['a', 'e', 'i', 'o', 'u']:
# Append the avalible fruits array with the fruit
avalible_fruits.append(fruit)
# Return the avalible fruits array
return avalible_fruits
fruits = ["Banana", "Apple", "Mango", "Orange", "Pineapple", "Honeydew"]
print(pick_fruits(fruits, 3)) |
import numpy as np
import pandas as pd
# drop() method has inplace=False as default
def df_drop_column() :
old_data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Height': [5.1, 6.2, 5.1, 5.2],
'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
old_frame = pd.DataFrame(old_data)
address = ['Delhi', 'Bangalore', 'Chennai', 'Patna']
old_frame["Address"]= address
print(old_frame.index) #there is no index set
# Drop the column with label 'Qualification'
qualification = old_frame["Qualification"]
#axis = 0 indictaes rows, axis =1 indicates columns
#inplace= False (default value)does not drop the column
old_frame.drop('Qualification', axis=1, inplace=True)
print(old_frame)
print("Shape : ", old_frame.shape)
old_frame['Qualification'] = qualification # adds column
print(old_frame)
old_frame.drop(columns=['Height', 'Qualification'], axis=1, inplace=True)
print(old_frame) # 2 columns are dropped in one shot
def df_drop_row() :
data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'year': [2012, 2012, 2013, 2014, 2014],
'reports': [47, 24, 31, 23, 32]}
original = pd.DataFrame(data, index = ['1', '2', '3', '4', '5'])
original.drop('3',axis=0,inplace=True) #drop third row
print(original.index)
original.drop(original.head(1).index,inplace=True) #drop top 1 row
original.drop(original.tail(1).index,inplace=True) # drop bottom 1 row
print(original)
def df_display() :
data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'year': [2012, 2012, 2013, 2014, 2014],
'reports': [47, 24, 31, 23, 32]}
original = pd.DataFrame(data, index = ['1', '2', '3', '4', '5'])
print(original[:-1]) #display all rows expect last row
print(original[:-2]) #display all rows expect last 2 row2
print(original[:2]) #display first 2 rows
print(original.head(1)) #display top 1 row
print(original.tail(2)) #display bottom 1 row
def df_set_index() :
old_data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Height': [5.1, 6.2, 5.1, 5.2],
'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
old_frame = pd.DataFrame(old_data)
address = ['Delhi', 'Bangalore', 'Chennai', 'Patna']
old_frame["Address"]= address
print(old_frame.index) #there is no index set
old_frame.set_index('Name', inplace = True)
print(old_frame)
def df_reset_index():
original = pd.DataFrame(data=np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
index= [2.5, 12.6, 4.8],
columns=[48, 49, 50])
print(original)
new = original.reset_index(level=0, drop=True) # index has been dropped
print(new)
new1 = original.reset_index() #index remains as column, new index is in place
print(new1)
def main() :
#df_display()
#df_reset_index()
#df_set_index()
df_drop_column()
#df_drop_row()
# this means that if this script is executed, then
# main() will be executed
if __name__ == '__main__':
main() |
#Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
thistuple = ("apple", "banana", "cherry")
print(thistuple)
thattuple = tuple(("honda", "maruti", "hyundai"))
print("tuple created using constructor ", thattuple)
print("Count : ",len(thistuple))
for x in thistuple:
print(x)
if "cherry" in thistuple:
print("Yes, 'cherry' is in the fruits tuple")
index = 2
print ("Item at index 2 : ",thistuple[2])
try:
del(thistuple[1])
except:
print("You cannot delete from tuple \n")
try:
thistuple[1] = "blackcurrant"
print(thistuple)
except:
print("Exception shown as the program tried to modify tuple element")
try:
del thattuple
print(thattuple)
except:
print("You can delete tuple. Exception shown as the program printed deleted tuple")
def delete(tupleSample, element):
tempList = list(tupleSample)
tempList.remove(element)
tupleSample = tuple(tempList)
return tupleSample
animals = ['cat', 'dog', 'rabbit', 'guinea pig']
print("before deleting \n",animals)
deleted_rabbit = delete(animals,'rabbit')
print("after deleting rabbit using list conversion \n",deleted_rabbit)
|
global solved
AllPuzzles = []
with open ('sudoku.txt') as file:
for line in file:
if line[0] == "G":
AllPuzzles.append([])
else:
AllPuzzles[-1].append(line.strip())
class Square():
def __init__(self, number, row, column, box):
self.number = number
self.row = row
self.column = column
self.box = box
self.possibles = []
def __str__(self):
return("Number: " + str(self.number) + " Row: " + str(self.row) + " Column: " + str(self.column) + " Box: " + str(self.box) + " Pos: " + str(self.possibles))
def interpretPuzzle(Puzzle):
currentSquares = []
for row in range(len(Puzzle)):
currentBox = 1
if row > 2:
currentBox = 4
if row > 5:
currentBox = 7
for column in range(len(Puzzle[row])):
box = currentBox
if column > 2:
box += 1
if column > 5:
box += 1
currentSquares.append(Square(int(Puzzle[row][column]), row + 1, column + 1, box))
return currentSquares
def getRemainingNumbers(square):
numbers =[i + 1 for i in range(9)]
for i in currentSquares:
if i.row == square.row:
if i.number in numbers:
numbers.remove(i.number)
elif i.column == square.column:
if i.number in numbers:
numbers.remove(i.number)
elif i.box == square.box:
if i.number in numbers:
numbers.remove(i.number)
return numbers
def findCertains():
#this one clears out all squares that only have one option
#either because they only have on number to use
#or they have a number that no other square in one of their sections has
#I continue running this method until it goes through without finding any
#first recalculate possibilities for each square
for i in currentSquares:
if i.number == 0:
i.possibles = getRemainingNumbers(i)
#check if square only has on possible number
if len(i.possibles) == 1:
i.number = i.possibles[0]
i.possibles = []
return True
#then check if any squares have a unique possible number
for square in currentSquares:
if square.number == 0:
tempPossibles = []
for i in currentSquares:
if i != square:
if i.row == square.row:
for p in i.possibles:
if p not in tempPossibles:
tempPossibles.append(p)
elif i.column == square.column:
for p in i.possibles:
if p not in tempPossibles:
tempPossibles.append(p)
elif i.box == square.box:
for p in i.possibles:
if p not in tempPossibles:
tempPossibles.append(p)
possiblesLeft = []
for p in square.possibles:
if p not in tempPossibles:
possiblesLeft.append(p)
if len(possiblesLeft) == 1:
square.number = possiblesLeft[0]
square.possibles = []
return True
return False
"""
so if clearing out the certain ones doesn't solve the puzzle
I run this recurssive algorithm which just brute-forces the solution
looping through each square that still has possibles
for each square try the first possible
then check if that breaks anything
if it does try the next possible
if there are no more possibles then change the number back to zero
and return so that you go back to the previous number
if it works then go onto the next number
do this until the puzzle is solved
"""
def bruteForce(current):
global solved
for possible in currentSquares[current].possibles:
if solved == True:
return
currentSquares[current].number = 0
attempt = True
for i in currentSquares:
if i != currentSquares[current]:
if i.row == currentSquares[current].row:
if i.number == possible:
attempt = False
elif i.column == currentSquares[current].column:
if i.number == possible:
attempt = False
elif i.box == currentSquares[current].box:
if i.number == possible:
attempt = False
if attempt:
if current == len(currentSquares) - 1:
solved = True
currentSquares[current].number = possible
return
currentSquares[current].number = possible
for i in range(current + 1, len(currentSquares)):
if len(currentSquares[i].possibles) > 0:
bruteForce(i)
break
if i == len(currentSquares) - 1:
solved = True
currentSquares[current].number = possible
return
if current == len(currentSquares) - 1:
solved == True
if not solved:
currentSquares[current].number = 0
return
answer = 0
for i in range(len(AllPuzzles)):
if i == i:
currentSquares = interpretPuzzle(AllPuzzles[i])
while True:
if not findCertains():
break
for s in currentSquares:
if s.number == 0:
s.possibles = getRemainingNumbers(s)
solved = True
for square in currentSquares:
if square.number == 0:
solved = False
if not solved:
for square in range(0, len(currentSquares)):
if currentSquares[square].number == 0:
bruteForce(square)
break
for square in currentSquares:
if square.number == 0:
print("Problem: ", i)
print("solved: ", i)
sum= ''
for i in range(3):
sum += str(currentSquares[i].number)
answer += int(sum)
print(answer)
|
#PF-Exer-18
def get_count(num_list):
count=0
for i in range(0,len(num_list)-1):
if(num_list[i]==num_list[i+1]):
count=count+1
# Write your logic here
return count
#provide different values in list and test your program
num_list=[1,1,5,100,-20,-20,6,0,0]
print(get_count(num_list))
|
def find_common_characters(msg1,msg2):
a=''
for i in range(0,len(msg1)):
for j in range(0,len(msg2)):
if(msg1[i]==msg2[j]):
if(msg1[i]!=" "):
if msg1[i] not in str(a):
a=a+msg1[i]
if(a==''):
a=-1
return a
#Remove pass and write your logic here
#Provide different values for msg1,msg2 and test your program
msg1="python"
msg2="Python"
common_characters=find_common_characters(msg1,msg2)
print(common_characters)
|
#PF-Tryout
def generate_next_date(date,month,year):
#Start writing your code here
if(month==1 or month==3 or month ==5 or month ==7 or month==8 or month==10):
if(date>=1 and date<=30):
next_date=date+1
next_month=month
next_year=year
else:
next_date=1
month=month+1
next_year=year
if((month==4) or (month==6) or (month==9)or (month==11)):
if(date>=1 and date<=29):
next_date=date+1
next_month=month
next_year=year
else:
next_date=1
next_month=month+1
next_year=year
if(month==2):
if(date>=1 and date<=27):
next_date=date+1
next_month=month
next_year=year
else:
next_date=1
next_month=month+1
next_year=year
if((month==2) and (year%4==0)):
if(date>=1 and date<=28):
next_date=date+1
next_month=month
next_year=year
else:
next_date=1
next_month=month+1
next_year=year
if(month==12):
if(date>=1 and date<=30):
next_date=date+1
next_month=month
next_year=year
else:
next_date=1
month=1
next_year=year+1
print(next_date,"-",next_month,"-",next_year)
generate_next_date(22,3,2011)
|
#goal of this tryout is to create a function from scratch and invoke it for the given problem
def convert_temp(temp):
sign=temp[-1]
temp=int(temp[0:-1])
if(sign=="C" or sign=="c"):
tempval=(temp*(9/5)+32)
tempval=str(tempval)+"F"
elif(sign=="F" or sign=="f"):
tempval=((temp-32)*(5/9))
tempval=str(tempval)+"C"
return tempval
res=convert_temp('44F')
print(res)
|
# CSV = comma seperated variables
# very common output for spreadsheet programs
import csv
# Open the file
data = open('example.csv',encoding='utf-8')
# csv.reader
csv_data = csv.reader(data,delimiter=',',quotechar='"')
# reformat it into a python object list of lists
data_lines = list(csv_data)
# print(data_lines[0])
# for line in data_lines[:5]:
# print(line)
all_emails = []
one_line = data_lines[10]
# print(one_line)
# all emails
for line in data_lines[1:]:
all_emails.append(line[3])
# print(all_emails)
full_names = []
for line in data_lines[1:]:
full_names.append(line[1]+' '+line[2])
# print(full_names)
file_to_output = open('to_save_file.csv',mode='w',newline='')
csv_writer = csv.writer(file_to_output,delimiter=',')
csv_writer.writerow(['a','b','c'])
csv_writer.writerows([['1','2','3'],['4','5','6']])
file_to_output.close()
f = open('to_save_file.csv',mode='a',newline='')
csv_writer = csv.writer(f)
csv_writer.writerow(['1','2','3'])
f.close() |
class Player:
def display(self):
print('Name :', self.name)
print('Level:', self.level)
p1 = Player()
p1.name = 'Daikon'
p1.level = 1
p1.display()
p2 = Player()
p2.name = 'Ninjin'
p2.level = 2
p2.display()
|
def find(c):
if(d.__getitem__(c)==None):
return False
else:
d.__setattr__(c,(d.__getitem__(c)+1))
def Encrypt():
endata = ""
for i in range(len(data)):
c = chr((ord(data[i]) + int(key1)) % 128)
if (ord(c) <= 31 and ord(c) >= 0):
endata += chr(ord(c) + 32)
else:
endata += c
return endata
def Decrypt():
dedata = ""
for i in range(len(endata)):
if ((ord(endata[i]) - int(key2) <= 31) and (ord(endata[i]) - int(key2) >= 0)):
c1 = (ord(endata[i]) - int(key2) - 32)
dedata += chr(c1 % 128)
else:
dedata += chr((ord(endata[i]) - int(key2)) % 128)
return dedata
f = open("plaintext.txt", "r")
data = f.read()
f.close()
print("Enter key for encryption")
key1 = input()
endata = Encrypt()
en = open("encrypted.txt", "w")
en.write(endata)
en.close()
l=list(endata)
d={i:0 for i in l}
for c in l:
if c in d:
d[c]+=1
else:
d.__setitem__(c, 1)
temp=0
for c in d:
if(d[c]>temp):
temp=d[c]
val=c
key2=(ord(val)-ord(' '))%128
print(key2)
dedata=Decrypt()
de = open("decrypt.txt", "w")
de.write(dedata)
de.close() |
def Encrypt():
endata=""
for i in range(len(data)):
c=chr((ord(data[i])+int(key1)) %256)
if(ord(c) <=31 and ord(c) >=0):
endata+=chr(ord(c)+32)
else:
endata+=c
return endata
def Decrypt():
dedata=""
for i in range(len(endata)):
if(ord(endata[i])-int(key2) <=31 and ord(endata[i])-int(key2) >=0):
c1=ord(endata[i])-int(key2) -32
dedata+=chr(c1%256)
else:
dedata+=chr((ord(endata[i])-int(key2))%256)
return dedata
f=open("plaintext.txt","r")
data=f.read()
f.close()
print("Enter key for encryption")
key1=input()
print("Enter key for normal decryption")
key2=input()
endata=Encrypt()
en=open("encrypted.txt", "w")
en.write(endata)
en.close()
dedata=Decrypt()
de=open("decrypt.txt","w")
de.write(dedata)
de.close()
|
def solution(arr, divisor):
possible_divide = []
for i in arr:
if i % divisor == 0:
possible_divide.append(i)
if len(possible_divide) == 0:
possible_divide.append(-1)
return possible_divide
else:
possible_divide.sort()
return possible_divide
|
"""
Entradas
venta en galones--->float--->gal
precio por litro--->float--->precio
Salidas
venta en litros--->float--->lts
total venta--->float--->total
"""
print("COBRO GASOLINERIA")
gal=float(input ("Ingrese la venta en galones: "))
lts=(gal*3.785)
total=(lts*50000)
print("El total de la venta es: "+str(total)) |
"""
en una tienda efectúan un descuento a los clientes dependiendo del monto de la compra. El descuento se efectúa con base en el siguiente criterio:
a. Si el monto es inferior a $50.000 COP, no hay descuento.
b. Si está comprendido entre $50.000 COP y $100.000 COP inclusive, se hace un descuento del 5%
c. Si está comprendido entre $100.000 COP y $700.000 COP inclusive, se hace un descuento del 11%
d. Si está comprendido entre $700.000 COP y $1.500.000 COP inclusive, el descuento es del 18
e. Si el monto es mayor a $1500000, hay un 25% de descuento.
Calcule y muestre el nombre del cliente, el monto de la compra, monto a pagar y descuento recibido.
Entradas
nombre--->str--->name
monto compra--->float--->price
Salidas
monto a pagar--->float--->net
descuento--->float--->desc
"""
name=str(input("Nombre del cliente: "))
price=float(input("Monto de la compra: "))
if(price>0 and price<=50000):
net=(price-(price*0.05))
desc=(price-net)
print("Nombre: "+str(name)+(" Monto de la compra: "+str(price)+(" Descuento: ")+str(desc)+" Valor neto: "+str(net)))
elif(price>50000 and price<=100000):
net=(price-(price*0.11))
desc=(price-net)
print("Nombre: "+str(name)+(" Monto de la compra: "+str(price)+(" Descuento: ")+str(desc)+" Valor neto: "+str(net)))
elif(price>100000 and price<=700000):
net=(price-(price*0.18))
desc=(price-net)
print("Nombre: "+str(name)+(" Monto de la compra: "+str(price)+(" Descuento: ")+str(desc)+" Valor neto: "+str(net)))
elif(price>1500000):
net=(price-(price*0.25))
desc=(price-net)
print("Nombre: "+str(name)+(" Monto de la compra: "+str(price)+(" Descuento: ")+str(desc)+" Valor neto: "+str(net))) |
"""
Entradas
Capital
Salidas
Ganancia
La razon es un dato conocido, no se toma como entrada
"""
cap=int (input("Ingrese el valor del capital invertido: "))
ganancia=(cap*0.02)
print("La ganancia mensual es de: "+str(ganancia)) |
""""
entradas
lectura actual--->float--->lact
lectura anterior--->float--->lant
valor kw--->float--->kwh
salidas
consumo--->float--->cons
total factura-->float--->total
"""
print("FACTURA DE ENERGIA ELECTRICA")
lact=float(input ("Digite lectura actual: "))
lant=float(input ("Digite lectura anterior: "))
kwh=float(input ("Valor del kilowatio: "))
cons=(lact-lant)
total=(cons*kwh)
print("El valor a pagar es :"+str(total)) |
"""
Entradas
numero de estudiantes--->int--->est
numero de mujeres-->int--->numm
numero de hombres--->int--->numh
Salidas
Porcentaje de hombres--->float--->ph
porcentaje de mujeres--->float--->pm
"""
est=int(input("Introduzca el número de estudiantes: "))
numm=int(input("¿Cuantas mujeres hay en el grupo? "))
numh=int(est-numm)
ph=((numh/est)*100)
pm=((numm/est)*100)
print("El porcentaje de mujeres es: "+str(pm))
print("El porcentaje de hombres es: "+str(ph)) |
import random
class Cell:
"""A single cell in a maze"""
def __init__(self, row, col):
self.visited = False
self.left = True
self.right = True
self.up = True
self.down = True
self.row = row
self.col = col
def get_all_neighbors(self, maze):
"""Get a list of all the neighbors to this cell"""
neighbors = []
# top
if self.row - 1 > -1 and not self.up:
neighbors.append((self.row - 1, self.col))
# right
if self.col + 1 < len(maze[0]) and not self.right:
neighbors.append((self.row, self.col + 1))
# bottom
if self.row + 1 < len(maze) and not self.down:
neighbors.append((self.row + 1, self.col))
# left
if self.col - 1 > -1 and not self.left:
neighbors.append((self.row, self.col - 1))
# should always be at least 1 neighbor
assert neighbors
return neighbors
def get_all_unvisited_neighbors(self, maze):
"""Get a list of all the neighbors to this cell"""
neighbors = []
# top
if self.row - 1 > -1 and not maze[self.row - 1][self.col].visited:
neighbors.append((self.row - 1, self.col))
# right
if self.col + 1 < len(maze[0]) and not maze[self.row][self.col + 1].visited:
neighbors.append((self.row, self.col + 1))
# bottom
if self.row + 1 < len(maze) and not maze[self.row + 1][self.col].visited:
neighbors.append((self.row + 1, self.col))
# left
if self.col - 1 > -1 and not maze[self.row][self.col - 1].visited:
neighbors.append((self.row, self.col - 1))
return neighbors
def get_neighbor(self, maze):
"""Pick a random neighbor to return"""
neighbors = self.get_all_unvisited_neighbors(maze)
if not neighbors:
return None
else:
return random.choice(neighbors)
def get_visited_neighbor(self, maze):
"""Pick a random neighbor to return. Doesn't matter if it's been visited before."""
neighbors = []
# top
if self.row - 1 > -1:
neighbors.append((self.row - 1, self.col))
# right
if self.col + 1 < len(maze[0]):
neighbors.append((self.row, self.col + 1))
# bottom
if self.row + 1 < len(maze):
neighbors.append((self.row + 1, self.col))
# left
if self.col - 1 > -1:
neighbors.append((self.row, self.col - 1))
if not neighbors:
return None
else:
return random.choice(neighbors)
|
'''
Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки,
но каждое слово должно начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func().
'''
def int_func(str):
'''
Делает первые буквы каждого слова заглавными
:param str: исходная строка
:return: строка с первыми заглавными буквами
'''
return str.title()
while True:
str = input('\nEnter a string in lower case (Enter - to exit): ')
if str == '': # если пустая строка - выход
break
print(f'Modified string: {int_func(str)}')
print('\nProgram completed.') |
# usr/bin/env python
# -*- coding:utf-8 -*-
def quick(arr):
if len(arr) in (0,1):
return arr
p=arr[-1]
l=[x for x in arr[:-1] if x <= p]
r=[x for x in arr[:-1] if x > p]
return quick(l) + [p] + quick(r)
li=[9,1,6,4,9,2,7,4,5,3,8]
print(li)
print(quick(li))
# 名称 平均計算時間 最悪計算時間 メモリ使用量 安定性
# クイックソート O(nlogn) O(n^2) O(logn) 安定ではない
|
# usr/bin/env python
# -*- coding:utf-8 -*-
def insert(arr):
for i in range(1,len(arr)):
for j in range(i,0,-1):
if arr[j] >= arr[j-1]:
break
else:
arr[j],arr[j-1]=arr[j-1],arr[j]
return arr
li=[9,1,6,4,9,2,7,4,5,3,8]
print(li)
print(insert(li))
# 名称 平均計算時間 最悪計算時間 メモリ使用量 安定性
# 挿入ソート O(n^2) O(n^2) O(1) 安定
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 10 09:46:08 2019
@author: Lily Amsellem
"""
import math
import numpy as np
import numpy.random as random
import scipy.special as special
import matplotlib.pyplot as plt
"""
x is the stock
D is the demand
o is the order
v is the quantity sold at an instant t
V is the values of Bellman Function
"""
#data values
T=7
p=0.5
n=[0,15,12,10,10,10,40,40,0]
def f(x,o,d):
#v=min(d,x+o)
#return x+o-v
return(max(x+o-d,0))
def L(x,o,d):
v=min(d,x+o)
return 2*v-o
###########SOLVING THE PROBLEM#########
def dynamicProgram(K=lambda x:0):
V=np.zeros((51,8))
optimalOrders=np.zeros((51,7))
#Final Value
for x in range(51):
V[x,T]=K(x)
for t in range(T-1,-1,-1):
for x in range(51):
V[x,t]=-math.inf
maxOrder=min(50-x,10)
for o in range(maxOrder+1):
Vo=0
for k in range(n[t+1]+1):
#Vo=2*min(n[t+1]*p,x+o)-o
#Vo+=V[x+o-min(k,x+o),t+1]*special.binom(n[t+1],k)*(p**k)*(1-p)**(n[t+1]-k)
Vo+=(2*min(k,x+o)+V[f(x,o,k),t+1])*special.binom(n[t+1],k)*(p**k)*(1-p)**(n[t+1]-k)
Vo=Vo-o
if Vo>V[x,t]:
V[x,t]=Vo
optimalOrders[x,t]=o
return(V,optimalOrders)
#Plot the optimal values in function of S0
def DP_display(K=lambda x:0):
V,optimalOrders=dynamicProgram(K)
X=np.arange(51)
plt.plot(X,V[:,0])
#Question 5: Case where we buy an initial stock at price "buy_price" (0.75,1 or 1.25$)
def buy_initial_stock(V,buy_price):
return (np.argmax(V[:,0]-buy_price*np.arange(0,51)),np.max(V[:,0]-buy_price*np.arange(0,51)))
#########SIMULATING THE PROBLEM#############
#Question 6: Estimate optimal value through Monte-Carlo and plot in function of the orders u
def Monte_Carlo(nb_samples,order_strategy,x0=0):
demand=np.zeros((nb_samples,T+1))
orders=np.zeros((nb_samples,T+1))
stock=np.zeros((nb_samples,T+1))
stock[:,0]=x0*np.ones(nb_samples)
V=np.zeros(nb_samples)
meanMC=0
for t in range(T+1):
#draw binomial samples
demand[:,t]=np.random.binomial(n[t],p,size=nb_samples)
for i in range(nb_samples):
for t in range(T):
x=stock[i,t]
orders[i,t]=min(order_strategy,50-x)
o=orders[i,t]
stock[i,t+1]=f(x,o,demand[i,t+1])
V[i]+=L(x,o,demand[i,t+1])
meanMC+=V[i]/nb_samples
return(meanMC)
def MC_display(nb_samples,x0=0,compare=False):
orders=np.arange(11)
MC_results=np.zeros(11)
for i in range(11):
MC_results[i]=Monte_Carlo(nb_samples,orders[i],x0)
if (compare==False):
plt.plot(orders,MC_results)
plt.xlabel("order strategy")
plt.plot(orders,MC_results)
plt.title("Values through Monte-Carlo approach")
else:
V=dynamicProgram(K=lambda x:0)[0]
print("Expected value of the optimal policy : ",V[x0,0])
print("Value computed through Monte-Carlo : ",np.max(MC_results))
############INFORMATION STRUCTURE########@
#New info structure is hazard-decision--> decision is made with knowledge of d_{t+1}
def main():
#QUESTION 6 : Plot Monte Carlo computations in function of order u
plt.figure()
MC_display(1000,x0=20,compare=False)
plt.show()
#QUESTION 7: Check that optimal values through MC and Dynamic Programming coincide for s0=20
MC_display(1000,x0=20,compare=True)
#QUESTION 8 : Assume that final stock can be sold for 1$, and compare with the case
#where the final value function is 0
plt.figure()
DP_display()
DP_display(K=lambda x:x)
plt.title("Profit with and without selling the final stock")
plt.show()
|
while(True):
print("Press q to quit")
a = input("enter a number")
if a == "q":
break
try:
a =int(a)
if a > 6:
print("Enterd number is greater then 6")
except Exception as e:
print(e)
print("Thanks for playing this game") |
# def func(a):
# return a+5
'''
#Lambda Functions: is a function like we make function using "def" keyword.
Functions created using an expression using lambda keyword.
syntax : lambda arguments : expressions
--> Ek hi line m function define krte h
'''
func = lambda a: a+5
x = 566
print(func(x))
sequare = lambda a:a*a
print(sequare(5))
sum = lambda a,b,c : a+b+c
print(sum(7,3,5))
|
# This is an illustration of the random walk diffusion model of atoms.
# It is assumed that the atoms are diffusing upwards as shown in the output figure of this script.
# We consider 3 atoms viz. A, B and C.
import numpy as np
import matplotlib.pyplot as plt
import math
# For tracing a random path for atom 1.
series1_xvalues = [0]
series1_yvalues = [0]
dist = 2
i = 0
itr = 0
x1 = 0
y1 = 0
while (i < 120):
itr = itr + 1
x2 = np.random.uniform(0, 10)
y2 = np.random.uniform(0, 10)
dist = math.sqrt((y2 - y1)*(y2 - y1) + (x2 - x1)*(x2 - x1))
if (dist < 1):
i = i + 1
series1_xvalues.append(x2)
series1_yvalues.append(y2)
x1 = x2
y1 = y2
series1_xvalues.append(5)
series1_yvalues.append(10)
# For tracing a random path for atom 2.
series2_xvalues = [5]
series2_yvalues = [0]
dist = 2
i = 0
itr = 0
x1 = 5
y1 = 0
while (i < 120):
itr = itr + 1
x2 = np.random.uniform(0, 10)
y2 = np.random.uniform(0, 10)
dist = math.sqrt((y2 - y1)*(y2 - y1) + (x2 - x1)*(x2 - x1))
if (dist < 1):
i = i + 1
series2_xvalues.append(x2)
series2_yvalues.append(y2)
x1 = x2
y1 = y2
series2_xvalues.append(5)
series2_yvalues.append(10)
# For tracing a random path for atom 3.
series3_xvalues = [10]
series3_yvalues = [0]
dist = 2
i = 0
itr = 0
x1 = 10
y1 = 0
while (i < 120):
itr = itr + 1
x2 = np.random.uniform(0, 10)
y2 = np.random.uniform(0, 10)
dist = math.sqrt((y2 - y1)*(y2 - y1) + (x2 - x1)*(x2 - x1))
if (dist < 1):
i = i + 1
series3_xvalues.append(x2)
series3_yvalues.append(y2)
x1 = x2
y1 = y2
series3_xvalues.append(5)
series3_yvalues.append(10)
plt.scatter(series1_xvalues, series1_yvalues, color = ['red'])
plt.scatter(series2_xvalues, series2_yvalues, color = ['green'])
plt.scatter(series3_xvalues, series3_yvalues, color = ['orange'])
plt.xlim(0, 10)
plt.ylim(0, 10)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Atoms A, B and C diffusing upwards following random path.')
plt.text(0, 0, 'A', size = 10, bbox = dict(boxstyle = 'square'))
plt.text(5, 0, 'B', size = 10, bbox = dict(boxstyle = 'square'))
plt.text(10, 0, 'C', size = 10, bbox = dict(boxstyle = 'square'))
#plt.text(5, 10, 'D', size = 10, bbox = dict(boxstyle = 'square'))
plt.show()
|
def unique():
list=[]
n=int(input("Enter the length of the list : "))
while(n!=0):
num=int(input("Enter the number: "))
list.append(num)
n=n-1
print(set(x for x in list if list.count(x)==1))
unique()
|
class Character:
name = ''
power = 0
energy = 100
def eat(self, food=5):
while self.energy != 100:
if self.energy < 100:
print('\nУ вас сейчас меньше 100% энергии.')
eat_food = input('Вы можете подкрепиться(да или нет)')
if eat_food == 'да' and self.energy < 100:
self.energy += food
print('Стало', self.energy, 'энергии.')
else:
print('Это ваш выбор, но он может вам еще аукнуться...')
break
def do_exercise(self, hours=1):
while self.energy > 0 and self.power != 100:
if self.energy > 0:
print('Вы можете подкачаться и увеличить свою силу.')
do_exer = input('Хотите стать сильнее?(да или нет)')
if do_exer == 'да':
self.power += hours * 5
self.energy -= hours * 5
print('Теперь ваша сила равна', self.power)
print('И ваша энергия равна', self.energy)
else:
print('Вы выбрали быть бездельником... Что ж герой из вас так себе.')
break
peter = Character()
peter.name = 'Peter Parker'
print('Мы создали нового персонаж, его зовут -', peter.name)
peter.energy = 90
print('У него сейчас столько энергии:', peter.energy)
peter.alias = 'Spider-Man'
print('Этот герой всем известен под псевдонимом -', peter.alias)
peter.power = 70
print('Его сила равна', peter.power)
#peter.eat()
#peter.do_exercise()
def main():
while True:
choice = int(input('\nЕсли хотите увеличить энергию введите 1\nЕсли хотите увеличить силу введите 2\n'))
if choice == 1:
peter.eat()
elif choice == 2:
peter.do_exercise(int(input('Введите сколько часов вы хотите потренить: ')))
main()
# bruce = Character()
# bruce.name = 'Bruce Wayne'
# bruce.power = 75
# bruce.energy = 100
# bruce.alias = 'Batman'
# print('\nСоздан второй персонаж -', bruce.name)
# print('У него сейчас столько энергии:', bruce.energy)
# print('Этот герой всем известен под псевдонимом -', bruce.alias)
# print('Его сила равна', bruce.power) |
#Exercise 19
#Given a string return the odd characters of a string based on the index
def oddCharacters(word):
oddList = []
for i in range(1,len(word)):
if i%2 != 0:
oddList.append(word[i])
oddStr = ''.join(oddList)
return oddStr
print(oddCharacters('Hallo'))
|
#Exercise 13
#When using bottom down approach we start the the smallest deetails as we build to a bigger picture
#part one-->check if first letter is capital
def is1stcapital(string):
string_list = [i for i in string]
return string_list[0].isupper()
#part 2 -->We then capitalize each first letter
def capitalize1stletter(string):
string_list = [i for i in string]
if is1stcapital(string) == True:
return string
else:
string_list[0]= string_list[0].upper()
string = ''.join(string_list)
return string
#part 3 -->we then assembly each word to make a new sentence with first letter capitalized
def capitalized(sentence):
st = []
s_list = sentence.split(' ')
for word in s_list:
word = capitalize1stletter(word)
st.append(word)
st2 = ' '.join(st)
return st2
s= input('Enter a sentence >')
print (capitalized(s))
|
#Exercise 4
#Indicates the amount of change to give
#The change is divided in groups of twenties,ten, fives, ones, quarters, dimes, nickels and pennies
#user inputs cost of item
cost_of_item = 65.64#float(input('Enter the cost of item >'))
#user inputs amount given
amount_given = 100.00#float(input('How much did the person give you >'))
#change to be given
raw_change = amount_given - cost_of_item
#making change
twenties = int(raw_change // 20)
rem_no20 = raw_change % 20
tens = int(rem_no20 // 10)
rem_no10 = rem_no20 % 10
fives = int(rem_no10 // 5)
rem_no5 = rem_no10 % 5
ones = int(rem_no5 // 1)
rem_no1 = rem_no5 % 1
quarters = int(rem_no1 // 0.25)
rem_noqts = rem_no1 % 0.25
dimes = int(rem_noqts // 0.10)
rem_nodms = rem_noqts % 0.10
nickels = (rem_nodms // 0.05)
rem_nonks = rem_nodms % 0.05
pennies = rem_nonks // 0.01
#Using singular and omitting those with 0 values
#for twenties
if twenties == 1:
twenties_count = '{} twenty\n'.format(twenties)
elif twenties >1:
twenties_count = '{} twenties\n'.format(twenties)
else:
twenties_count = ''
#for tens
if tens == 1:
tens_count = '{} ten\n'.format(tens)
elif tens > 1:
tens_count = '{} tens\n'.format(tens)
else:
tens_count = ''
#for fives
if fives == 1:
fives_count = '{} five\n'.format(fives)
elif fives > 1:
fives_count = '{} fives\n'.format(fives)
else:
fives_count = ''
#for ones
if ones == 1:
ones_count = '{} one\n'.format(ones)
elif ones > 1:
ones_count = '{} ones\n'.format(ones)
else:
ones_count = ''
#for quarters
if quarters == 1:
quarters_count = '{} quarter\n'.format(quarters)
elif quarters > 1:
quarters_count = '{} quarters\n'.format(quarters)
else:
quarters_count = ''
#for dimes
if dimes == 1:
dimes_count = '{} dime\n'.format(dimes)
elif dimes > 1:
dimes_count = '{} dimes\n'.format(dimes)
else:
dimes_count = ''
#for nickels
if nickels == 1:
nickels_count = '{} nickel\n'.format(nickels)
elif nickels > 1:
nickels_count = '{} nickels\n'.format(nickels)
else:
nickels_count = ''
#for pennies
if pennies == 1:
pennies_count = '{}penny'.format(pennies)
elif pennies > 1:
pennies_count = '{}pennies'.format(pennies)
else:
pennies_count = ''
print(ones_count)
print('The bills of change should be:\n{}{}{}{}{}{}{}{}'.format(twenties_count,tens_count,fives_count,ones_count,quarters_count,dimes_count,nickels_count,pennies_count))
|
class Function:
def __init__(self,id,argList,compoundInstr):
self.compoundInstr=compoundInstr
self.id=id
self.argList=argList
class Memory:
def __init__(self, name): # memory name
self.name=name
self.map={}
def has_key(self, name): # variable name
return (name in self.map)
def get(self, name): # get from memory current value of variable <name>
return self.map[name]
def put(self, name, value): # puts into memory current value of variable <name>
self.map[name]=value
def printIt(self):
print "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
for key in self.map.iterkeys():
print str(key) + " " + str(self.map[key])
print "2222222222222222222222222222222222222222222222222222222"
class MemoryStack:
def __init__(self, memory=None): # initialize memory stack with memory <memory>
self.stack=[];
if memory:
self.stack.append(memory)
def get(self, name): # get from memory stack current value of variable <name>
#print "get " + str(name)
for i in range(len(self.stack)-1,-1,-1):
if self.stack[i].has_key(name):
#print " " + str(self.stack[i].get(name))
return self.stack[i].get(name)
#print " None"
return None
def insert(self, name, value): # inserts into memory stack variable <name> with value <value>
#print "insert " + str(name) + " " + str(value)
self.stack[-1].put(name, value)
def printIt(self):
self.stack[-1].printIt()
def set(self, name, value): # sets variable <name> to value <value>
#print "set " + str(name) + " " + str(value)
for i in range(len(self.stack)-1,-1,-1):
if self.stack[i].has_key(name):
self.stack[i].put(name,value)
return True
return False
def push(self, memory): # push memory <memory> onto the stack
self.stack.append(memory)
def pop(self): # pops the top memory from the stack
return self.stack.pop()
def addClassDef(self, dec, currClass, extension):
#print "ADD: " + str(dec) + " " + str(currClass) + " " + str(extension)
newExts = {}
if extension != None:
for i in range(len(self.stack)-1,-1,-1):
for key in self.stack[i].map.iterkeys():
if str(key).startswith(str(extension)):
#print str(key)
currDecSuff = str(key).split('.')[1]
currVal = self.stack[i].get(key)
newExts[str(dec) +"." + currDecSuff] = [i, currVal]
for key in newExts.iterkeys():
#print "111111111111111111"
#print str(newExts[key][0])
#print str(newExts[key][1])
#print str(key)
#print "111111111111111111"
self.stack[newExts[key][0]].put(key, newExts[key][1])
newClass = {}
for i in range(len(self.stack)-1,-1,-1):
for key in self.stack[i].map.iterkeys():
if str(key).startswith(str(currClass)):
#print str(key)
currDecSuff = str(key).split('.')[1]
currVal = self.stack[i].get(key)
currDec = str(dec) +"." + currDecSuff
newClass[currDec] = [i ,currVal]
for key in newClass.iterkeys():
#print "2222222222222222222222222"
#print str(newClass[key][0])
#print str(newClass[key][1])
#print str(key)
#print "2222222222222222222222222"
self.stack[newClass[key][0]].put(key, newClass[key][1]) |
'''
Created on May 7, 2015
https://www.hackerrank.com/contests/projecteuler/challenges/euler003
@author: Chocolate
'''
def prime(n):
i = 2
#print n;
while (n % i != 0 and i*i< n):
i += 1
#print "In While",i
if (i*i < n):
#print "In if",i;
return prime (n / i)
else:
print n
for _ in xrange(input()):
n = input()
prime(n)
|
#####Rules_variables
#* Cannot start with any number
#* #Cannot be used at the beginning of a variable name
#* !Cannot be used at the beginning of a variable name
#* There can be no symbol at the beginning of the variable
#* Variables must be one word, not two words
#* If two words _ it must be used
#* To know the position of any character inside the variable {print(variable name.find("The name of the letter"))}
#* There are characters in this position inside the variable {print(variable name[Numbers])}
#* Inside the variable to get from one character to another in the sting {print(variable name[From any number:Up to any number])}
#*
#*
#*
#*
|
a=int(input("Sayi giriniz:"))
if(a%2==0):
print("Sayi çifttir.")
else:
print("Sayi tektir.") |
#liste'den liste2'yi oluşturalım.
liste1 = [1,2,3,4,5]
liste2 = list() #veya liste2=[] ikiside boş liste oluşturur.
for i in liste1:
liste2.append(i) #liste2'ye liste1'in elemanlarını ekledik.
print(liste2) |
for i in range(1,100):
if(i%2==0):
print(i)
print("------")
for j in range(1,100):
if(j%2==1):#(j%2!=0)
print(j) |
liste=[1,2,3,4,5]
print(liste)
for i in range(6,25):
liste.append(i)
print(liste) |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import statsmodels.api as sm
loansData = pd.read_csv('https://spark-public.s3.amazonaws.com/dataanalysis/loansData.csv')
# FICO DATA
# loansData['FICO.Range'][0:5]
# Returns as follow:
# 81174 735-739
# 99592 715-719
# 80059 690-694
# 15825 695-699
# 33182 695-699
# Split into numbers - will return in form [###, ###]
# cleanFICORange = loansData['FICO.Range'].map(lambda x: x.split('-'))
cleanFICORange = [x.split('-') for x in loansData['FICO.Range'].tolist()]
# map(lambda x: x**2, xrange(10))
# or this?
# [x**2 for x in xrange(10)]
# Results:
# >>> cleanFICORange[0:5]
# 81174 [735, 739]
# 99592 [715, 719]
# 80059 [690, 694]
# 15825 [695, 699]
# 33182 [695, 699]
# Name: FICO.Range, dtype: object
# >>> cleanFICORange[0:5].values[0]
# ['735', '739']
# >>> type(cleanFICORange[0:5].values[0])
# <type 'list'>
# >>> cleanFICORange[0:5].values[0][0]
# '735'
# >>> type(cleanFICORange[0:5].values[0][0])
# <type 'str'>
# We have a string inside a list. Need to convert each string to integer
# To do this, we use a list comprehension
# The "[0]" at the end makes it so that we only choose the first element
# cleanFICOScore = cleanFICORange.map(lambda x: [int(n) for n in x][0])
cleanFICOScore = [[int(n) for n in x][0] for x in cleanFICORange]
# Results:
# print(cleanFICORange.head(5))
# 81174 735
# 99592 715
# 80059 690
# 15825 695
# 33182 695
# Name: FICO.Range, dtype: int64
# To understand better, check out: http://carlgroner.me/Python/2011/11/09/An-Introduction-to-List-Comprehensions-in-Python.html
# Assign cleaned score to new column called "FICO.Score"
loansData['FICO.Score'] = cleanFICOScore
# print(loansData['FICO.Score'].head(5))
# 81174 735
# 99592 715
# 80059 690
# 15825 695
# 33182 695
# Name: FICO.Score, dtype: int64
# Histogram
plt.figure()
p = loansData['FICO.Score'].hist()
plt.savefig('FicoScore_hist.png')
plt.close()
# Scatterplot matrix
a = pd.scatter_matrix(loansData, alpha=0.05, figsize=(10,10), diagonal='hist')
plt.savefig('FicoScore_ScatterMatrix.png')
plt.close()
# CLEAN INTEREST RATE DATA
# clean_ir = loansData["Interest.Rate"].map(lambda x: round(float(x.rstrip("%"))/100, 4))
clean_ir = [round(float(x.rstrip("%"))/100, 4) for x in loansData["Interest.Rate"]]loansData["Interest.Rate"] = clean_ir
# CLEAN LOAN LENGTH DATA
clean_loanLength = loansData["Loan.Length"].map(lambda x: float(x.rstrip("months")))
clean_loanLength = [float(x.rstrip("months") for x in loansData["Loan.Length"]]
loansData["Loan.Length"] = clean_loanLength
# LINEAR REGRESSION!
# Linear regression model:
# InterestRate = b + a1(FICOScore) + a2(LoanAmount)
intrate = loansData['Interest.Rate']
loanamt = loansData['Amount.Requested']
fico = loansData['FICO.Score']
# Create y and x variables
# The dependent variable
y = np.matrix(intrate).transpose()
# The independent variables shaped as columns
x1 = np.matrix(fico).transpose()
x2 = np.matrix(loanamt).transpose()
# put the two columns together to create an input matrix
x = np.column_stack([x1,x2])
# Create linear model
X = sm.add_constant(x)
model = sm.OLS(y,X)
f = model.fit()
# results summary
f.summary()
coeff = f.params
# plot:
line=[]
line2 = []
for j in fico:
line.append(coeff[0] + coeff[1]*j + coeff[2]*10000)
line2.append(coeff[0] + coeff[1]*j + coeff[2]*30000)
plt.close()
plt.scatter(fico,intrate)
plt.hold(True)
plt.plot(fico, line, label = '$10,000 Requested', color = 'blue')
plt.plot(fico, line2, label = '$30,000 Requested', color = 'green')
plt.legend(loc = 'upper right')
plt.ylabel('Interest Rate in %')
plt.xlabel('FICO Score')
plt.save('Fico_Scatter_10000&30000.png')
# Load to new CSV file
loansData.to_csv('loansData_clean.csv', header=True, index=False)
|
import requests
from bs4 import BeautifulSoup
import bs4
continent_links = ['https://en.wikipedia.org/wiki/List_of_airlines_of_Africa',
'https://en.wikipedia.org/wiki/List_of_airlines_of_the_Americas',
'https://en.wikipedia.org/wiki/List_of_airlines_of_Asia',
'https://en.wikipedia.org/wiki/List_of_airlines_of_Europe',
'https://en.wikipedia.org/wiki/List_of_airlines_of_Oceania']
links = []
airlines = set()
# Get all links that contain airline names.
for continent in continent_links:
html = requests.get(continent)
b = BeautifulSoup(html.text, 'lxml')
country_divs = b.find_all('div', {"role": "note"})
country_links = [each.contents[1].attrs['href'] for each in country_divs]
links.extend(country_links)
for link in links:
# Get the content of each link.
html = requests.get('https://en.wikipedia.org' + link)
b = BeautifulSoup(html.text, 'lxml')
# Airline names are stored in tables and sometimes there can be multiple tables. As a result of that, we get all the
# tables in the page.
# By using a lambda function here we can tell find_all to find all classes that include wikitable in them.
tables = b.find_all('table', {"class": lambda c: "wikitable" in c})
if len(tables) > 0:
for table in tables:
airline_trs = table.contents[1].contents
# Get the order of the column that contains the airline name.
table_column_names = table.contents[1].contents[0]
counter = 0
for column in table_column_names:
try:
column_text = column.text.strip().upper()
if 'AIRLINE' in column_text or 'NAME' in column_text:
break
except AttributeError:
pass
counter += 1
# For each row get the content of the column that has the airline name and put it in the airlines set.
for tr in airline_trs:
if isinstance(tr, bs4.element.Tag):
airline_column = tr.contents[counter]
if airline_column.name == 'td':
try:
airlines.add(airline_column.contents[0].text.strip())
except AttributeError:
airlines.add(airline_column.text.strip())
except Exception as e:
print(e)
# Turns our set to a list and sorts it. Finally, writes its contents in a text file.
airlines = list(airlines)
airlines.sort()
with open('airline_list.txt', 'w') as airline_list:
for airline in airlines:
try:
airline_list.write(airline.strip() + '\n')
except Exception as e:
print(e)
print(airline)
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 18:08:29 2018
@author: soojunghong
@about : Building POS tagger
@reference : https://nlpforhackers.io/training-pos-tagger/
"""
from nltk import word_tokenize, pos_tag
print pos_tag(word_tokenize("I am Soojung, I am learning NLP"))
#---------------------------------------------
# Picking a corpus to train the POS tagger
#---------------------------------------------
import nltk
tagged_sentences = nltk.corpus.treebank.tagged_sents()
print tagged_sentences[0]
print "Tagged sentences: ", len(tagged_sentences)
print "Tagged words: ", len(nltk.corpus.treebank.tagged_words())
#--------------------------------------------------
# Training your own POS Tagger using scikit-learn
#--------------------------------------------------
#define feature
# from following feature function take """ sentence: [w1, w2, ...], index: the index of the word """
def features(sentence, index):
return {
'word' : sentence[index],
'is_first': index == 0,
'is_last': index == len(sentence) - 1,
'is_capitalized': sentence[index][0].upper() == sentence[index][0],
'is_all_caps': sentence[index].upper() == sentence[index],
'is_all_lower': sentence[index].lower() == sentence[index],
'prefix-1': sentence[index][0],
'prefix-2': sentence[index][:2],
'prefix-3': sentence[index][:3],
'suffix-1': sentence[index][-1], # -1 means the index from the very right end
'suffix-2': sentence[index][-2:], ## second right end
'suffix-3': sentence[index][-3:],
'prev_word': '' if index == 0 else sentence[index-1],
'next_word': '' if index == len(sentence)-1 else sentence[index+1],
'has_hyphen': '-' in sentence[index],
'is_numeric': sentence[index].isdigit(),
'capitals_inside': sentence[index][1:].lower() != sentence[index][1:]
}
import pprint
pprint.pprint(features(['This', 'is', 'a', 'sentence'], 2))
def untag(tagged_sentence):
return [w for w, t in tagged_sentence]
# build training set
# Split the dataset for training and testing
cutoff = int(.75 * len(tagged_sentences))
training_sentences = tagged_sentences[:cutoff]
training_sentences
test_sentences = tagged_sentences[cutoff:]
test_sentences
print len(training_sentences)
print len(test_sentences)
def transform_to_dataset(tagged_sentences):
X, y = [],[]
for tagged in tagged_sentences:
for index in range(len(tagged)):
X.append(features(untag(tagged), index))
y.append(tagged[index][1])
return X, y
X, y = transform_to_dataset(training_sentences)
X
y
# train the classifier - Decision Tree
from sklearn.tree import DecisionTreeClassifier
from sklearn.feature_extraction import DictVectorizer
from sklearn.pipeline import Pipeline
clf = Pipeline([
('vectorizer', DictVectorizer(sparse=False)),
('classifier', DecisionTreeClassifier(criterion='entropy'))
])
clf.fit(X[:10000], y[:10000]) #use first 10k samples
print 'Training completed'
X_test, y_test = transform_to_dataset(test_sentences)
print "Accuracy: ", clf.score(X_test, y_test)
# let's use classifier
def pos_tag(sentence):
tagged_sentence = []
tags = clf.predict([features(sentence, index) for index in range(len(sentence))])
return zip(sentence, tags)
print pos_tag(word_tokenize('this is my friend John')) |
# 27 移除元素
# https://leetcode-cn.com/problems/remove-element/
def removeElement(nums, val):
k = 0 # 不等元素索引
for i in range(len(nums)):
if (nums[i] != val):
if (i != k): # 防止所有元素都是非零元素(特殊用例)-》自己与自己交换
nums[k], nums[i] = nums[i], nums[k]
k += 1
return k
# 优化-》
def removeElement2(nums, val):
i = 0
for j in range(len(nums)):
if nums[j] == val:
nums[i], nums[j] = nums[j], nums[i]
i += 1
del nums[:i]
return len(nums)
def removeElement3(nums, val):
while val in nums:
nums.remove(val)
return len(nums)
nums = [0,1,2,2,3,0,4,2]
val = 2
print(removeElement3(nums,val),nums) |
# Creator: Lusemar Oliveira
# Description: Project 4 - Grocery List
# Date: 10/27/2020
# Class: COP1000
# Variable declarations
test = None
# Logic
while True:
groceryList = open("grocery.dat", "r") # Open File for Reading data
print ("Here is your currently Grocery List: " + "\n")
for row in groceryList:
print (row)
print ("\n")
# Get user input
listItem = input("Please enter a new item to the Grocery List: ")
groceryList = open("grocery.dat", "a") # Open File for Append data
groceryList.write("\n")
groceryList.write(listItem) # Wriring data to the list
test = input("\n" + "Would you like to enter another Item to the Grocery List? Yes or No? ")
print ("\n")
if test == "No":
print ("Here is your Updated Grocery List: " + "\n")
# I had to Close and reopen the File in order to go through the loop again
groceryList.close()
groceryList = open("grocery.dat", "r")
for row in groceryList:
print (row)
groceryList.close() # Close File
break
else:
groceryList.close() # Close File
# Write while loop here
#while True:
# flowerData = flower.readline().strip()
# growData = flower.readline().strip()
# if (flowerData == ""):
# break
# Print flower name using the following format
# print(var + " grows in the " + var2)
# print(flowerData + " grows in the " + growData)
|
#Assignment 5.2
Numbers = []
while True :
sval = input('Enter a number: ')
if sval == 'done' :
break
try:
fval = float(sval)
except:
print('Invalid input')
continue
Numbers.append(fval)
Minimum = int(min(Numbers))
Maximum = int(max(Numbers))
print('Maximum is', Maximum)
print('Minimum is', Minimum) |
"""This is the player class"""
import pygame
import random
# Local imports
import resources
pygame.font.init()
COLORS = resources.COLORS
NAME_FONT = pygame.font.SysFont("comicsans", 20)
SCORE_FONT = pygame.font.SysFont("comicsans", 30)
WIN_WIDTH = 1400
WIN_HEIGHT = 800
class Player:
size = 20
thickness = 0
def __init__(self, x, y, name):
self.x = x
self.y = y
self.name = name
self.player_color = COLORS[random.randint(0, len(COLORS) - 1)]
def convert_coords_int(self):
"""
Converts player coords to int
@return:
"""
self.x = int(self.x)
self.y = int(self.y)
def move(self, x=0, y=0):
"""
Moves player, changes its coords
@param x: int
@param y: int
@return: None
"""
self.x += x
self.y += y
def draw(self, win):
"""
Draws the player and its name on screen
@param win: pygame.Window
@return: None
"""
pygame.draw.circle(win, self.player_color, (self.x, self.y), self.size, self.thickness)
text = NAME_FONT.render(self.name, 1, (0, 0, 0))
win.blit(text, (self.x - text.get_width() / 2, self.y - text.get_height() / 2))
def draw_score(self, win):
"""
Draws the player score
@param win: pygame.Window
@return:None
"""
text = SCORE_FONT.render("Score: " + str(int(self.size)), 1, (0, 0, 0))
win.blit(text, (10, WIN_HEIGHT - text.get_height() - 10))
|
def add_data(list_values):
with open('iris.csv','a') as f:
f.write(','.join(list_values)+'\n')
def delete_data(list_values):
import pandas as pd
iris=pd.read_csv('iris.csv',header=None)
data=iris.loc[(iris[0]==list_values[0]) & (iris[1]==list_values[1]) & (iris[2]==list_values[2]) & (iris[3]==list_values[3]) & (iris[4]==list_values[4])]
if data.empty:
return "Data is not in the dataset"
df = pd.merge(iris, data, on=[0,1,2,3,4], how='outer', indicator=True).query("_merge != 'both'").drop('_merge', axis=1).reset_index(drop=True)
#print len(df)
df.to_csv('iris.csv',index=False)
return "Deleta data successfully"
|
"""
Prediction File
------------
Author: Guilherme M. Toso
File: prediction.py
Date: Jul 16, 2021
Description:
This is the prediction page. Where the user can input data and it will return the house price prediction.
"""
# Dependencies
import os
import streamlit as st
from apps.domain.data_clean import Cleaner
from apps.data.database import database
from apps.domain.model import regressor
class Prediction():
def __init__(self):
super().__init__()
self.price = 0.0
self.input_data = {
'sqft_living': 0,
'sqft_lot':0,
'sqft_above':0,
'yr_built':1852,
'lat':47.1559,
'long':-122.519,
'sqft_living15':0,
'sqft_lot15':0,
'bedrooms':0,
'bathrooms':0,
'floors':1,
'waterfront':'Yes',
'renovated':'Yes',
'views':0,
'condition':'Poor',
'grade':0
}
self.cleaner = Cleaner()
def app(self):
st.title('Predict House Price')
st.markdown("""
----
With the help of Machine Learning models you can predict the house price
-------
----
""")
price = st.empty()
pred = st.empty()
update_data = st.empty()
pred_col_1, pred_col_2, pred_col_3 = st.beta_columns([2,1,1])
with pred_col_1:
price.title(f"Price: ${self.price:,.2f}")
with pred_col_2:
predicted = pred.button("Predict Price")
with pred_col_3:
updated = update_data.button("Update Data")
st.text("\n")
column_1, column_2, column_3 = st.beta_columns(3)
with column_1:
self.input_data['sqft_living'] = st.number_input(label="Living Area (in Square Feet)", min_value=0.0, step=0.01)
self.input_data['yr_built'] = st.number_input(label="Year Built", min_value=1852, step=1)
self.input_data['sqft_living15'] = st.number_input(label="Living Area of the 15 Closest Neighbors (in Square Feet)", min_value=0.0, step=0.01)
self.input_data['bathrooms'] = st.number_input(label="Bathrooms", min_value=0, step=1)
self.input_data['renovated'] = st.radio(label="The house were renovated? ",options=('Yes','No'))
self.input_data['grade'] = st.slider(label="Select the house grade",min_value=0, max_value=13,step=1)
with column_2:
self.input_data['sqft_lot'] = st.number_input(label="Land Area (in Square Feet)", min_value=0.0, step=0.01)
self.input_data['lat'] = st.number_input(label="Latitute (4 decimal digits)", min_value=47.1559, max_value=47.7776, step=0.0001)
self.input_data['sqft_lot15'] = st.number_input(label="Landing Area of the 15 Closest Neighbors (in Square Feet)", min_value=0.0, step=0.01)
self.input_data['floors'] = st.number_input(label="Floors", min_value=1, step=1)
self.input_data['views'] = st.slider(label="How is the house view",min_value=0, max_value=4,step=1)
with column_3:
self.input_data['sqft_above'] = st.number_input(label="House Area apart from basement (in Square Feet)", min_value=0.0, step=0.01)
self.input_data['long'] = st.number_input(label="Longitude (3 decimal digits)", min_value=-122.519, max_value=-121.315, step=0.001)
self.input_data['bedrooms'] = st.number_input(label="Bedrooms", min_value=0, step=1)
self.input_data['waterfront'] = st.radio(label="There is a water front? ",options=('Yes','No'))
self.input_data['condition'] = st.select_slider(label='Select the house overall condition',
options=['Poor', 'Fair-Badly', 'Average', 'Good', 'Very Good'])
cleaned_data = self.cleaner.model_input(self.input_data)
if predicted:
self.price = regressor.predict(cleaned_data)
price.title(f"Price: ${self.price[0]:,.2f}")
if updated:
database.update()
|
#!/usr/bin/env python
# encoding: utf-8
# the same as 1001, but I stuck in this for hours...
def get_number(n):
if n % 2 == 0:
return n / 2
else:
return (3 * n + 1) / 2
n = int(input())
number_list = [int(i) for i in input().split()]
data = number_list[:]
for i in data:
while not i == 1:
i = get_number(i)
if i in number_list:
number_list.remove(i)
number_list.sort(reverse=True)
print(' '.join([str(i) for i in number_list]))
|
def pares(dimension):
i=1
pares=0
while i<=dimension:
if i % 2==0:
print(i,end=" ")
if i % 2==0:
pares=pares+1
if i==dimension:
print("\n\n La cantidad de pares son " + str(pares))
break;#Sale del flujo de ejecución del ciclo
#Incrementar contador en el ciclo
i=i+1
rango=int(input("\n\n Ingrese hasta donde quiere saber los números pares >"))
#Llamar a la función
#Llamar al método
print( pares(rango))
|
from operaciones_mate_intermedio import menu2
#Menu de operaciones
def menu():
print("************************************************************")
print("* *")
print("* ELIJA UNA OPCIÓN *")
print("* 1)Suma *")
print("* 2)Resta *")
print("* 3)Multiplicación *")
print("* 4)División *")
menu2()
##Se llama al menu2 que esta dentro de otro modulo hacia este modulo
def suma(n1,n2):
print("\nLa suma de " + str(n1) + " + " + str(n2) + " = ", (n1+n2))
def resta(n1,n2):
print("\nLa resta de "+ str(n1) + " - " + str(n2) + " = ", (n1-n2) )
def multiplicacion(n1,n2):
print("\nLa multiplicación de "+ str(n1) + " * " + str(n2) + " = ", (n1*n2))
#Método para verificar si no ingresa un cero como segundo método para la division
def verificar(n2):
if n2==0:
return 0
else:
return 1
#Método de la división
def dividir(n1,n2):
print("\nLa división de "+ str(n1) + " / " + str(n2) + " = ", (n1/n2)) |
#Prueba con cadenas
while True:
nombreUsuario=input("\nIntroduce tu nombre de usuario >")
while nombreUsuario.isalpha()==False:
print("\n debe ingresar una cadena ")
nombreUsuario=input("\nIntroduce tu nombre de usuario >")
#Mostrar opciones de cadenas
print("\n El nombre es " + nombreUsuario.upper())#Convierte todo a mayuscula
print("\n El nombre es " + nombreUsuario.lower())#Convierte todo a minuscula
print("\n El nombre es " + nombreUsuario.capitalize())#Convierte la primer letra en mayuscula no importa si todas estan en mayuscula o minuscula
#count devuelve el número de veces que se encuentra una letra o valor en una cadena tambien se puede poner el valor inicial y final de busqueda
print("\n La letra a aparece " + str(nombreUsuario.count("a",1,55 )) + " Veces en el nombre " + nombreUsuario)
#print("\n El nombre es " + nombreUsuario.encode("a"))
print("\n El nombre contiene una F en el índice " + str(nombreUsuario.find("f")) + " De fabricio")#Devuleve el indice donde se encuentra la letra primera
#Index es igual que find a diferencia que si no encuentra nada lanza un error de valor ValueError
print("\n El nombre contiene una F en el indice " + str(nombreUsuario.index("f")))
print("\n El nombre es " + nombreUsuario.replace("a","j"))#remplaza la a por la j
continuar=input("Más operaciones 1)si 2)no >")
while continuar.isdigit()==False :
print("Ingrese un digito ")
continuar=input("Más operaciones 1)si 2)no >")
if int(continuar)==2:
break
|
#Uso del continue en un ciclo
nombre="Angel Fabricio González"
contador=0
for i in nombre:
if i==" ":
continue#El continue omite el resto de código desde que se aplica
contador+=1
print("\n La cantidad de letras de " + nombre + " son: " + str(contador))
|
#importar clase para la raiz cuadradra
import math
def menu2():
print("* 5)Raíz cuadrada *")
print("* 6)Potencia *")
print("* 7)Salir *")
print("************************************************************")
#metodo para sacar la raíz cuadrada
def raiz(num):
if num<=0:
print("\n La raíz cuadrada no es menor o igual a cero ")
else:
print("\n La raíz cuadrada de " + str(num) + " es " + str(math.sqrt(num)))
#Método para la potencia
def potencia(base,exponente):
if base==0:
print("\n La base nunca debe ser cero ")
else:
print("\n El resultado de " + str(base) + "^" + str(exponente) + " = " + str(base**exponente) )
|
def mensaje():
print("Estoy aprendiendo python")
print("esto es fácil")
def multiplicacion(n1,n2):
return n1*n2
#Llamar a la función
mensaje()
#Llamar otra ves a la función mensaje
mensaje()
#llamar a función multiplicación
numero1=5.5
numero2=3
print(multiplicacion(numero1,numero2))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.