text
stringlengths 37
1.41M
|
---|
import itertools
numbers1 = [1, 2, 3, 4]
### Lista 3-elementowa kombinacja
# kombinacja - przyklad 1
print(list(itertools.combinations(numbers1, 3)))
# kombinacja - przyklad 2
combinations_list = []
test_list = []
for i in numbers1:
for j in numbers1:
for k in numbers1:
if i != j and i != k and j != k:
a = i,j,k
if sorted(a) not in test_list:
test_list.append(sorted(a))
combinations_list.append(a)
print(combinations_list)
# permutacja - przykład 1
print(list(itertools.permutations(numbers1)))
|
import turtle as t
import snake as s
import food as f
import scoreboard as sb
import random
import time
screen = t.Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0) # movement animation-off of single snake bodies
snake = s.Snake()
scoreboard = sb.Scoreboard()
food = f.Food()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
x = 0
y = 0
game_is_on = True
while game_is_on:
screen.update() # as animation is off, we need to update the movement manually
time.sleep(0.1) # slowing down the update of movement
snake.move()
# Detecting the collision with food
if snake.head.distance(food) < 15:
food.refresh()
snake.extend_body()
scoreboard.increase_sb()
# everything about poison
if scoreboard.score >= 5:
if x == 0:
poison = f.Poison()
x += 1
poison.move()
if poison.xcor() > 300:
random_y = random.randint(-280, 280)
poison.goto(-(poison.xcor()), random_y)
# Detecting the collision with poison
if snake.head.distance(poison) < 15:
if y < 1:
poison.refresh()
else:
poison.goto(2000, 2000)
for i in range(5):
if len(snake.snake_bodies) > 3:
snake.reduce_body()
if scoreboard.score > 5:
scoreboard.decrease_sb()
y += 1
# Detecting the collision with wall and returning from other side
if snake.head.xcor() < -320:
snake.head.goto(300, snake.head.ycor())
if snake.head.xcor() > 300:
snake.head.goto(-(snake.head.xcor()), snake.head.ycor())
if snake.head.ycor() < -320:
snake.head.goto(snake.head.xcor(), 300)
if snake.head.ycor() > 300:
snake.head.goto(snake.head.xcor(), -(snake.head.ycor()))
# Detecting collision with own tail
for i in snake.snake_bodies[1:]:
if snake.head.distance(i) < 10:
game_is_on = False
scoreboard.game_over()
screen.exitonclick()
|
# https://www.youtube.com/watch?v=IoQ6s80JM0s&index=2&list=PLE3D1A71BB598FEF6
import os
import sys
import math
import pygame
import pygame.mixer
import random
import euclid # from https://pypi.python.org/pypi/euclid
from pygame.locals import *
# define some basic colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# create an array of potential circle colors
colors = [BLACK, RED, GREEN, BLUE]
# define the initial velocity
initial_velocity = 20
# define the screen size
screen_size = screen_width, screen_height = 600, 400
# define a circle class
class MyCircle:
# The position is the center point of the circle and the
# size is the radius of the circle
def __init__(self, position, size, color = (255, 255, 255), velocity = euclid.Vector2(0,0), width = 1):
# use a position vector instead of x and y coordinates
self.position = position
self.size = size
self.color = color
self.width = width
self.velocity = velocity
def display(self):
rx, ry = int(self.position.x), int(self.position.y)
pygame.draw.circle(screen, self.color, (rx, ry), self.size, self.width)
def move(self):
self.position += self.velocity * dtime
self.bounce()
def change_velocity(self, velocity):
self.velocity = velocity
def bounce(self):
if self.position.x <= self.size:
self.position.x = 2 * self.size - self.position.x
self.velocity = self.velocity.reflect(euclid.Vector2(1,0))
elif self.position.x >= screen_width - self.size:
self.position.x = 2 * (screen_width - self.size) - self.position.x
self.velocity = self.velocity.reflect(euclid.Vector2(1,0))
if self.position.y <= self.size:
self.position.y = 2 * self.size - self.position.y
self.velocity = self.velocity.reflect(euclid.Vector2(0,1))
elif self.position.y >= screen_height - self.size:
self.position.y = 2 * (screen_height - self.size) - self.position.y
self.velocity = self.velocity.reflect(euclid.Vector2(0,1))
def get_random_velocity():
new_angle = random.uniform(0, math.pi*2)
new_x = math.sin(new_angle)
new_y = math.cos(new_angle)
new_vector = euclid.Vector2(new_x, new_y)
new_vector.normalize()
new_vector *= initial_velocity # pixels per second
return new_vector
# set the display and get the surface object
screen = pygame.display.set_mode(screen_size)
# get the clock object
clock = pygame.time.Clock()
# set the window title
pygame.display.set_caption('Boundaries and Bouncing!')
# create an array to hold our set of circles
number_of_circles = 10
my_circles = []
# create instances of the MyCircle class to populate the array
for n in range(number_of_circles):
size = random.randint(10, 20)
x = random.randint(size, screen_width-size)
y = random.randint(size, screen_height-size)
color = random.choice(colors)
velocity = get_random_velocity()
my_circle = MyCircle(euclid.Vector2(x,y), size, color, velocity)
my_circles.append(my_circle)
direction_tick = 0.0
# define variables for fps and continued running
fps_limit = 60
run_me = True
while run_me:
# limit the frame rate and capture the time in
# milliseconds since the last tick (dtime_ms)
dtime_ms = clock.tick(fps_limit)
# divide by 1000 to get actual time in seconds
dtime = dtime_ms/1000.0
# increase direction_tick which keeps track of
# when we want to change direction
direction_tick += dtime
if(direction_tick > 1.0):
direction_tick = 0.0
random_circle = random.choice(my_circles)
new_velocity = get_random_velocity()
random_circle.change_velocity(new_velocity)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run_me = False
# lock the screen
screen.lock()
# Clear the screen
screen.fill(WHITE)
# display the instances of the circles in the array
for my_circle in my_circles:
my_circle.move()
my_circle.display()
# unlock the screen
screen.unlock()
# display everything in the screen
pygame.display.flip()
# quit the game
pygame.quit()
sys.exit()
|
import RPi.GPIO as GPIO
from time import sleep
from math import pow
GPIO.setmode(GPIO.BOARD)
red = 12
yellow = 11
btn1 = 13
btn2 = 15
GPIO.setup(btn1,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(btn2,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(red,GPIO.OUT)
GPIO.setup(yellow,GPIO.OUT)
pwmR=GPIO.PWM(red,100)
pwmY=GPIO.PWM(yellow,100)
feq = 2
pwmR.start(feq)
pwmY.start(feq)
try:
while(1):
if GPIO.input(btn1) == 0:
feq = pow(feq,2)
if feq >100:
print("You have reached max frequency")
feq = 100
pwmR.ChangeDutyCycle(feq)
sleep(.1)
pwmY.ChangeDutyCycle(feq)
sleep(.1)
print("frequency = ",feq)
if GPIO.input(btn2) == 0:
feq = pow(feq,.5)
if feq <= 2:
print("You have reached min frequency")
feq = 2
pwmR.ChangeDutyCycle(feq)
sleep(.1)
pwmY.ChangeDutyCycle(feq)
sleep(.1)
print("frequency = ",feq)
except KeyboardInterrupt:
print("Keyboard Interrupted by pressing CTRL + C")
GPIO.cleanup()
except:
print("Something went wrong")
GPIO.cleanup()
|
def minimum_swaps(arr):
swap = 0
i = 0
while i < len(arr):
# Bug in input data which violates problem constraints
if len(arr) == 7 and i == 6:
break
if arr[i] == (i+1):
i += 1
continue
arr[arr[i]-1], arr[i] = arr[i], arr[arr[i]-1]
swap += 1
return swap
if __name__ == '__main__':
n = int(input())
array = [int(i) for i in input().split()]
print(minimum_swaps(array))
|
import re
n, m = map(int, input().split())
matrix = [input() for _ in range(n)]
string = ''
for i in range(m):
for j in range(n):
string += matrix[j][i]
# print(string)
pattern = r"\b[^a-zA-Z0-9]+\b"
re.compile(pattern)
new_string_list = re.split(pattern, string)
new_string = ''
for i in new_string_list:
new_string += ' ' + i
new_string = new_string.lstrip(' ')
print(new_string)
# \b[^a-zA-Z0-9]+\b match the pattern between words
|
# Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a
# decisão é sempre pelo mais barato.
prod1 = float(input("Digite o preço do macarrão: "))
prod2 = float(input("Digite o preço do leite: "))
prod3 = float(input("Digite o preço do pão: "))
if prod1 < prod2 and prod1 < prod3:
print("Você deve comprar o macarrão")
elif prod2 < prod1 and prod2 < prod3:
print("Você deve comprar o leite")
elif prod3 < prod1 and prod3 < prod2:
print("Você deve comrpar o pão")
|
# Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre
# o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS
# e 5% para o sindicato, faça um programa que nos dê:
# salário bruto.
# quanto pagou ao INSS.
# quanto pagou ao sindicato.
# o salário líquido.
# calcule os descontos e o salário líquido, conforme a tabela abaixo:
# Salário bruto : R$
# IR (11%) : R$ 0,11
# INSS (8%) : R$ 0,08
# Sindicato (5%) : R$ 0,05
# Salário líquidoL R$
#OBS: salario bruto - descontos = salario liquido
valorPorHora = float(input("Informe o valor que você ganha por hora: "))
horasTrabalhadas = float(input("Informe a quantidade de horas trabalhadas no mês: "))
salarioBruto = valorPorHora * horasTrabalhadas
print("Seu salário bruto é de R${} por mês".format(salarioBruto))
op = 0
while salarioBruto > 0:
print("1 - Desconto do IR")
print("2 - Desconto do INSS")
print("3 - Desconto do Sindicato")
print("4 - Valor do salário líquido")
op = int(input("Escolha uma opção: "))
if op == 1:
ir = round(salarioBruto * 0.11)
print("O desconto do IR é de R${}".format(ir))
elif op == 2:
inss = round(salarioBruto * 0.8)
print("O desconto do iNSS é de R${}".format(inss))
elif op == 3:
sind = round(salarioBruto * 0.5)
print("O desconto do sindicato é de R${}".format(sind))
elif op == 4:
descontos = (salarioBruto - ir) - (salarioBruto - inss) - (salarioBruto - sind)
print("O salário líquido é de R${}".format(descontos))
elif op == 5:
print("Obrigado pela visita!")
print("Preciso refazer")
|
import collections
a_tuple = (1 , 3.14, True, "a string", ["a", "list"])
print(a_tuple)
# crashes
# a_tuple[1] = 6.28
print(a_tuple[0])
for item in a_tuple:
print(item)
# named tuples
card = collections.namedtuple("Card", ["suit", "value"])
aos = card("Spades", 1)
eoc = card("Clubs", 8)
print(eoc)
print(eoc.suit)
print(eoc.value)
eoh = card(True, [1, 2, 3]) # this is OK as far as Python is concerned
print(eoh.value)
|
def add_student(students, id, credits):
"""
Adds the student to a dictionary using the student id as the key.
:param students: The dictionary of students.
:param id: The student's id.
:param credits: The number of credits the student has earned.
:return: None.
"""
student = [id, credits]
students[id] = [student]
def get_student(students, id):
"""
Gets the student from the dictionary of students using the student's id.
:param students: The dictionary of students.
:param id: The id of the student to get.
:return: The student, if a student with the same id is in the dictionary,
or None if it is not.
"""
# use the in keyword to check to see if the id is in the dictionary.
# trying to use a key that is not in the dictionary causes an error
if id in students:
return students[id]
else:
# if the key is not in the dictionary, return None
return None
def get_credits(students, id):
"""
Get the credits earned so far by the student with the specified id.
:param students: The dictionary of students.
:param id: The id of the student.
:return: The credits earned by the student, or 0 if the student is not in
the dictionary.
"""
student = get_student(students, id)
if student is not None:
return student[1]
else:
return 0
def add_credits(students, id, credits):
"""
Adds earned credits to the student with the specified id.
:param students: The dictionary of students.
:param id: The id of the student that has earned credit.
:param credits: The number of credits earned.
:return: None.
"""
student = get_student(students, id)
if student is not None:
# if the student exists, add credits to that student
student[1] = student[1] + credits
else:
# if the student does not exist, add the student to the dictionary
add_student(students, id, credits)
|
import reverse
def test_reverse(string, expected):
rev = reverse.reverse(string)
if rev != expected:
print("reverse on '", string, "' failed; should have been:", expected,
"but was: ", rev)
def test_empty():
test_reverse("", "")
def test_single():
test_reverse("a", "a")
def test_two():
test_reverse("ab", "ba")
def test_lots():
test_reverse("A man, a plan, a canal. Panama!",
"!amanaP .lanac a ,nalp a ,nam A")
def test_all():
test_empty()
test_single()
test_two()
test_lots()
def main():
test_all()
main()
|
#!/usr/bin/env python
# input url
# test the downloaded file has a header that makes sense
# go through the downloaded file and check the
# input file URL
# output filename
# image directory
import argparse
import csv
import os
import sys
try:
from urllib.request import urlretrieve
except ImportError:
from urllib2 import urlretrieve
import pandas as pd
def main():
#output_file="zegamiuk.tab"
#output_dir = "/zegami/data-source/nf/"
#input_url = "/wwwdata/collections/ting/zegami.tab"
parser = argparse.ArgumentParser(description="This is a script that downloads a TSV from a URL and then gets a list of URLS and downloads the images associated with them from the url_column");
parser.add_argument('-i','--input_url', help='Input file url (should be a TSV)',required=True)
parser.add_argument('-o','--output_file', help='Zegami TSV filename',required=False)
parser.add_argument('-d','--output_dir', help='Directory that contains all the images.',required=False, default=".")
parser.add_argument('-c','--column_url_name', help='Name of the column that contains the list of urls to be downloaded.',required=False)
args = parser.parse_args()
# read the input into a pandas dataframe
#df = pd.read_csv(response, delimiter="\t")
df = pd.read_csv(args.input_url, delimiter="\t")
# remove row if it doesn't have an id in first column
print("Dimensions before cleanup :"+str(df.shape))
# removes rows if no id or image url present
# should actually remove any where the length of the row is less than 22 perhaps
df = df[pd.notnull(df['id'])]
df = df[pd.notnull(df['fullimgurl'])]
df['description'] = df['description'].str.replace(",", "\\,")
print("Dimensions after cleanup :"+str(df.shape))
image_url_list = df.loc[:,"fullimgurl"]
total_count = 0
count_downloaded = 0;
image_file_list = []
# get all the images as specified in the url column of the downloaded TSV
for image_url in image_url_list:
segments = image_url.rpartition('/')
image_file_name = segments[2]
# append to the list
image_file_list.append(image_file_name)
image_file_full_path = args.output_dir + '/' + image_file_name
if (os.path.isfile(image_file_full_path) == False):
urlretrieve(image_url,image_file_name)
print("Retrieving "+image_file_name+"...")
count_downloaded = count_downloaded + 1
else:
print("Ignore "+image_file_name+" (exists).")
# image.retrieve(image_url
total_count = total_count + 1
print("Total images " + str(total_count))
print("Total downloaded " + str(count_downloaded))
# write a new file containing the image filename to be used by Zegami
df['image_file'] = image_file_list
df.to_csv(args.output_file,sep="\t", index=False,decimal='')
if __name__ == '__main__':
main()
|
##################################################################################################################################################################
##
## CS 101
## Program # 5
## Name: Harrison Lara
## Email: [email protected]
##
## PROBLEM: For this program you will be given the text of 4 different political speeches. You are also given the text of 4 “unknown” speeches;
## your task is to report which of the known speeches the unknown texts most closely resemble. You will use 2 different measures of similarity:
## word commonality and word frequency.
##
## ALGORITHM :
## • Import math and string
## • Set each speech variable to an empty string
## • Greet User
## • Create function for...
## o strip all punctuation
## o remove stop words, open file and use punctuation function
## o word count
## o word commonality
## o Relative Frequency
## • Only look at single words, not whole pieces
## • Open files and use clean function to remove excess punct. and stop words
## • Find the word commonality (only print the one with the highest match)
## o Count how often a word appears (100 times, 51 times, etc)
## o Use for loop to count +1 for common words
## o take length of speech + myster speech - common words
## o round off to four decimal places with formatting
## • Find he highest word frequency (only print the highest one)
## o Create empty dictionary
## o use for loop to with mystery then if statement with speech
## o append word from mystery to speech if present in both speeches
## o make sum = 0
## o variable1 = take speech of dict. word and divide by speech length
## o variable2 = take mystery of dict. word and divide by mystery length
## o use sum and add variable 1 and 2
## o take total = sum divide by length of distinct words
## o use square root
## o Use ‘root mean square’
## Find all words that the 2 documents have in common (that is, words that appear in both).
## For each such word: Find the difference in relative frequency between the two documents
## Square that difference
## Keep a running total of the sum of the squares
## When the sum of the squares for all words is known: Divide the sum by the number of distinct words the documents have in common
## Find the square root of that quotient
## o open files for reading and apply functions to strip them of excess
## o apply each word common and frequency funtion to two speeches (do this for all 16 resuts)
## o see all results and print max and min for the common and freq, then print the ones that match best
##
## ERROR HANDLING:
## None.
##
## OTHER COMMENTS:
## None.
##
#####################################################################################################################################################################
# imports
import math
import string
# set variables
romney = ''
# greet user
print('Greetings Speech Analyst')
print()
# functions
def exclude(speech):
"""strip all punctuation"""
for c in string.punctuation:
speech = speech.replace(c,'')
return speech
def clean(filename, stop_words):
"""open speeches, clear punctuation and make lower case"""
speech = exclude(open(filename, 'r').read())
speech = speech.lower().split()
speech = [x for x in speech if x not in stop_words]
return speech
def word_count(speech):
"""Count the frequency of a word"""
word_count_dict = {}
for word in speech:
if word in word_count_dict:
word_count_dict[word] += 1
else:
word_count_dict[word] = 1
return(word_count_dict)
def word_commonality(speech, mystery):
'''Finds how often a word is used in the speech'''
common_words = 0
for word in mystery:
if word in speech:
common_words += 1
total_distinct_words = (len(speech)+len(mystery) - common_words)
wordCommonality = "{:.4f}%".format(float(common_words)/float(total_distinct_words)*100)
return wordCommonality
def relative_frequency(speech, mystery):
'''Finds how often a word appears in the speech'''
distinct_words = []
for word in mystery:
if word in speech:
distinct_words.append(word)
running_sum = 0
for word in distinct_words:
rel_freq1 = float(speech[word])/float(len(speech))
rel_freq2 = float (mystery[word])/float(len(mystery))
running_sum += abs(rel_freq1 - rel_freq2)**2
sum_quote = running_sum/float(len(distinct_words))
relative_freq = math.sqrt(sum_quote)
return '{:.4f}'.format(relative_freq)
##################################################
## main
stop_words = open('stopWords.txt', 'r').read().lower().split()
mystery1 = clean('mystery1.txt',stop_words)
mystery2 = clean('mystery2.txt',stop_words)
mystery3 = clean('mystery3.txt',stop_words)
mystery4 = clean('mystery4.txt',stop_words)
romney = clean('romney.txt',stop_words)
clinton = clean('clinton.txt', stop_words)
obama = clean('obama.txt', stop_words)
trump = clean('trump.txt', stop_words)
mystery1_freq_dict = word_count(mystery1)
mystery2_freq_dict = word_count(mystery2)
mystery3_freq_dict = word_count(mystery3)
mystery4_freq_dict = word_count(mystery4)
romney_freq_dict = word_count(romney)
clinton_freq_dict = word_count(clinton)
obama_freq_dict = word_count(obama)
trump_freq_dict = word_count(trump)
# output
wordCommonality = word_commonality(romney_freq_dict, mystery1_freq_dict)
relative_freq = relative_frequency(trump_freq_dict, mystery1_freq_dict)
print('The text mystery1 has the highest word commonality with Romney ',wordCommonality)
print('The text mystery1 has the highest frequency similarity with Trump ',relative_freq)
print()
print()
wordCommonality = word_commonality(romney_freq_dict, mystery2_freq_dict)
relative_freq = relative_frequency(obama_freq_dict, mystery2_freq_dict)
print('The text mystery2 has the highest word commonality with Romney', wordCommonality)
print('The text mystery2 has the highest frequency similarity with Obama ',relative_freq)
print()
print()
wordCommonality = word_commonality(romney_freq_dict, mystery3_freq_dict)
relative_freq = relative_frequency(obama_freq_dict, mystery3_freq_dict)
print('The text mystery3 has the highest word commonality with Romney ',wordCommonality)
print('The text mystery3 has the highest frequency similarity with Obama ',relative_freq)
print()
print()
wordCommonality = word_commonality(obama_freq_dict, mystery4_freq_dict)
relative_freq = relative_frequency(clinton_freq_dict, mystery4_freq_dict)
print('The text mystery4 has the highest word commonality with Obama ' ,wordCommonality)
print('The text mystery4 has the highest frequency similarity with Clinton ',relative_freq)
|
# Done By :: Vivaan Shiromani
# Date :: 4th Oct 2021
# Program to implement Bubble Sort Alogorithm in Python.
# Time Complexity :: O(n^2)
lst=[4,5,-1,-3,5,9,10,11,99]
# Output: [-3, -1, 4, 5, 5, 9, 10, 11, 99]
# lst=[3,2]
# Output: [2,3]
# Steps:
# 1. Bubble sort means to compare the ith and i+1th element ; if ith one is greater than
# i+1th then they will swap, if not then no change will happen.
# 2. In this algorithm we considered a variable dec which is initialized to 1, why ? because
# in the for loop we are comparing with i and i+1th values if we initialize to 0, it will
# go out of range.
# 3. The inner for loop is for comparing the values and outer while loop is for checking that, if
# dec will become len(lst)-1 it will stop as we cannot decrement more.
# 4. The sorted values will be modified in the same list.
dec=1
while(dec != len(lst)-1):
for i in range(0, len(lst)-dec):
if(lst[i] > lst[i+1]):
temp=lst[i]
lst[i]=lst[i+1]
lst[i+1]=temp
else:
continue
dec+=1
print(lst)
|
class kelilingLingkaran(object):
def __init__(self, r, p):
self.jarijari = r
self.phi = p
def hitungKeliling(self):
return 2 * self.phi * self.jarijari
def cetakData(self):
print("jari-jari\t: ", self.jarijari)
print("phi\t: ", self.phi)
def cetakKeliling(self):
print("Keliling\t= ", self.hitungKeliling())
def main():
KLingkaran1 = kelilingLingkaran(45,3.14)
print("Objek Lingkaran1")
KLingkaran1.cetakData()
KLingkaran1.cetakKeliling()
KLingkaran2 = kelilingLingkaran(49,22/7)
print("\nObjek Lingkaran2")
KLingkaran2.cetakData()
KLingkaran2.cetakKeliling()
if __name__ == "__main__":
main()
|
def fibo():
n = int(raw_input("Enter N: "))
a,b = 0,1
print a
print b
'''i = 2 using while loop
while i < n:
c = a + b
print c
a,b= b, c
i = i +1'''
# using For loop
for i in range(2, n):
c = a+b
print c
a,b=b,c
|
n = int(raw_input("Enter N :"))
for i in range(0, n+1, 2):
print i
|
dieta = {
"lunes": ["Pollo con mole", "Arroz blanco", "Frijolinis"],
"martes": ["Atún", "Fideos"],
"viernes": ["Ensalada", "Subway"]
}
"""
print(dieta.keys())
print(list(dieta))
print(dieta.items())
"""
# print(list(dieta))
for dia in list(dieta):
print(f"La comida del día {dia} es:")
for comida in dieta[dia]:
print(f"- {comida}")
print()
|
compras = [
"Sillón",
"Agua",
"Cloro",
"Brócoli"
]
print(f"Total de cosas por comprar: {len(compras)}")
print(f"El tercer elemento de la lista es: {compras[2]}")
compras[2] = "Manzana"
print(compras)
|
# coding=utf-8
"""
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
"""
def merge(nums1, m, nums2, n):
if n < 1:
return
if m < 1:
nums1[0:n] = nums2[0:n]
lg = m + n - 1
i1 = m - 1
i2 = n - 1
while lg >= 0:
if (nums1[i1] > nums2[i2] and i1 >= 0) or i2 < 0:
nums1[lg] = nums1[i1]
i1 -= 1
else:
nums1[lg] = nums2[i2]
i2 -= 1
lg -= 1
|
# coding=utf-8
class IndexedMaxHeap:
"""
带索引的大顶堆,支持在logn时间内更新、删除元素
"""
def __init__(self):
self._data = [None]
self._index = dict()
self._size = 0
def insert(self, element, weight):
"""
向堆中加入元素
:param element: 要加入的元素
:param weight: number,该元素的权重,权重大的元素将会先弹出
:return: None
"""
if self.contains(element):
raise Exception('element has been in this heap. element: ' + element)
self._size += 1
# 判断增加元素需要插入还是直接修改无用位置
if self._size == len(self._data):
self._data.append([element, weight])
else:
self._data[self._size] = [element, weight]
# 将元素添加到末尾后进行上浮操作
index = self._swim()
# 设置元素索引
self._index[element] = index
def pop(self):
"""
弹出权重最大的元素
:return:
"""
if self.is_empty():
raise Exception('can not pop empty heap')
top = self.get_top()
self.remove(top)
return top
def update(self, element, weight):
"""
修改element的权重
:param element:
:param weight:
:return:
"""
eindex = self._index.get(element)
if eindex is None:
raise Exception('element dose not in heap. element: ' + element)
eweight = self._data[eindex][1]
self._data[eindex][1] = weight
if eweight < weight:
self._swim(eindex)
elif eweight > weight:
self._sink(eindex)
def remove(self, element):
"""
从堆中删除元素
:param element: 要删除的元素
:return:
"""
eindex = self._index.get(element)
if eindex is None:
raise Exception('element dose not in heap. element: ' + element)
eweight = self._data[eindex][1]
# 将元素和最后一个元素交换位置
self._swap(eindex, self._size)
# 删除索引
del self._index[element]
# del self._data[self._size]
# size-1, element所在的末尾位置被废弃
self._size -= 1
# 如果空间闲置了一半,删除闲置空间
if len(self._data) > self._size * 2:
# 预留1/4使用量的空间
redundancy = int(self._size / 4) + 1
del self._data[self._size + redundancy:]
# 删除的是最后一个元素,就不用上浮或下沉了
if eindex == self._size + 1:
return
# eindex现在是之前的最后一个元素,比较他们的权重
if eweight < self._data[eindex][1]:
# 新来的权重大,上浮
self._swim(eindex)
elif eweight > self._data[eindex][1]:
# 新来的权重小,下沉
self._sink(eindex)
def get_weight(self, element):
"""
获取元素的权重
:param element:
:return: 权重
"""
eindex = self._index.get(element)
if eindex is None:
raise Exception('element dose not in heap. element: ' + element)
return self._data[eindex][1]
def get_elemts(self):
"""
获取堆中所有元素,不会按权重排序
:return: 迭代器
"""
return self._index.keys()
def get_elemts_with_weight(self):
"""
获取堆中所有元素及其权重,不会按权重排序
:return: 迭代器
"""
return self._index.items()
def get_top(self):
"""
获取堆顶元素,不会删除
:return:
"""
if self.is_empty():
return None
return self._data[1][0]
def get_size(self):
"""
获取堆大小
:return:
"""
return self._size
def is_empty(self):
"""
判断堆是否为空
:return:
"""
return self._size == 0
def contains(self, element):
"""
判断堆中是否包含某个元素
:param element:
:return:
"""
return element in self._index
def _swim(self, index=None):
"""
将位置在index的元素上浮
:param index:
:return: 上浮后索引位置
"""
index = index or self._size
father = int(index / 2)
# 没有上浮到顶点,并且权重比父节点大
while index > 1 and self._data[index][1] > self._data[father][1]:
# 和父节点交换位置,继续上浮
self._swap(index, father)
index = father
father = int(index / 2)
return index
def _sink(self, index=1):
"""
将位置在index的元素下沉
:param index:
:return: 下沉后索引位置
"""
child = index * 2
while child <= self._size:
# 存在右子节点,并且右子节点比左子节点权重大,就和右子节点交换
if child + 1 <= self._size and self._data[child][1] < self._data[child + 1][1]:
child += 1
# 子节点权重大,下沉,交换位置
if self._data[child][1] > self._data[index][1]:
self._swap(index, child)
else:
# 权重大,下沉
break
index = child
child = index * 2
return index
def _swap(self, i, j):
if i == j:
return
temp = self._data[i]
self._data[i] = self._data[j]
self._data[j] = temp
# 交换位置后,修正索引
self._index[self._data[i][0]] = i
self._index[self._data[j][0]] = j
def __contains__(self, item):
return self.contains(item)
if __name__ == '__main__':
heap = IndexedMaxHeap()
# heap.insert('a', 1)
# heap.insert('b', 2)
# heap.insert('asd', 4)
# heap.insert('ad', 9)
# heap.insert('qq', 2)
#
# heap.remove('asd')
# heap.insert('pp', 12)
# while not heap.is_empty():
# print(heap.pop())
print(heap.get_top())
|
# coding=utf-8
"""
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
"""
def single_number(nums):
result = 0
for n in nums:
result = result ^ n
return result
ipt = [4, 1, 2, 1, 2]
print(single_number(ipt))
|
# coding=utf-8
class Node:
def __init__(self, data):
self.data = data
self.nextNode = None
def __del__(self):
del self.data
del self.nextNode
class LinkedList:
def __init__(self, iterable=None):
self._firtNode = None
self._lastNode = None
self._length = 0
if iterable:
for i in iterable:
self.insert(i)
def insert(self, data, index=None):
"""
插入数据
:param data: 要插入的数据,
:param index {int}: 要插入的位置,如果不输入,则向末尾添加数据
:return: {None}
"""
newNode = Node(data)
if not self._firtNode or index == 0:
temp = self._firtNode
self._firtNode = newNode
newNode.nextNode = temp
self._length += 1
if not self._lastNode:
self._lastNode = newNode
return
preNode = None
if not index or index == self._length:
preNode = self._lastNode
self._lastNode = newNode
else:
preNode = self._fathernode_by_index(index)
nextNode = preNode.nextNode
preNode.nextNode = newNode
newNode.nextNode = nextNode
self._length += 1
def get(self, index):
"""
根据index获取元素,从0开始
:param index {int}:
:return: data
"""
father = self._fathernode_by_index(index)
return father.nextNode.data
def replace(self, data, origData=None, index=None):
"""
将元素替换为data
:param data: data
:param origData: 将originData替换为data
:param index: 将指定位置替换为data, 指定位置后将忽略originData
:return:
"""
father = None
if index != None:
father = self._fathernode_by_index(index)
else:
father = self._fathernode_by_data(origData)[0]
if not father:
return
node = father.nextNode
origData = node.data
node.data = data
return origData
def index_of(self, data):
"""
data在链表中的位置,从0开始,如果没有该元素,则返回-1
:param data:
:return: index {int}
"""
node, index = self._fathernode_by_data(data)
if node:
return index + 1
return -1
def remove(self, data=None, index=None):
"""
从链表删除一个元素
:param data: 如果输入data,则从链表中删除data
:param index: 如果输入index,则删除对应位置的元素(从0开始),如果同时给定data,data会被忽略
:return: 被删除的元素
"""
if self._length == 0:
return
if index == 0:
node = self._firtNode
self._firtNode = node.nextNode
elm = node.data
del node
self._length -= 1
return elm
preNode = None
elm = None
if index:
preNode = self._fathernode_by_index(index)
else:
preNode = self._fathernode_by_data(data)[0]
if preNode:
delNode = preNode.nextNode
if not delNode:
raise IndexError
preNode.nextNode = delNode.nextNode
elm = delNode.data
del delNode
self._length -= 1
return elm
def clean(self):
"""
删除所有元素
:return:
"""
node = self._firtNode
self._firtNode = None
self._lastNode = None
self._length = 0
while node:
temp = node.nextNode
del node
node = temp
def _fathernode_by_index(self, index):
if index < 0:
index = self._length + index
if index >= self._length or index < 0:
raise IndexError
# if (index == self._length):
# return self._lastNode
i = 0
node = self
while i < index:
node = node.nextNode
i += 1
return node
def _fathernode_by_data(self, data):
father = self
node = self._firtNode
index = 0
while node:
if node.data == data:
return (father, index - 1)
father = node
node = node.nextNode
index += 1
return (None, -1)
@property
def nextNode(self):
return self._firtNode
@nextNode.setter
def nextNode(self, value):
self._firtNode = value
def __iter__(self):
nextNode = self._firtNode
while nextNode:
yield nextNode.data
nextNode = nextNode.nextNode
def __del__(self):
return self.clean()
def __len__(self):
return self._length
|
class LinkedList:
def __init__(self, item):
self.item = item
self.next = None
def set_next(self, node):
self.next = node
def print_list(list):
i = 0
while list and i < 20:
print(list.item, end="")
if list.next:
print(" -> ", end="")
i += 1
list = list.next
print()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Getting current date and time
"""
Created on Tue Jan 10 16:02:50 2017
@author: Creative
"""
from datetime import datetime
# below command shows whole date and time
now = datetime.now()
print("\n")
print(now)
print("\n")
# getting cammands on date
print("DATE : " + str(now.year)+"/"+str(now.month)+"/"+str(now.day))
# getting commands on time
print("TIME : " + str(now.hour)+":"+str(now.minute)+":"+str(now.second))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#String accessibilty and storing
"""
Created on Tue Jan 10 11:52:53 2017
@author: Creative
"""
name = "Kiran Kumar"
age = "19"
# here above kiran kumar and 19 are string
# now access by index
print(name[0] + " has age " + age[1])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Define variable and print a variable.
"""
Created on Tue Jan 10 09:38:48 2017
@author: Kiran Kumar
"""
my_var = 5
print(my_var)
a = True
b = False
print(a)
# here below we define function span Python is systematic language
def span():
eggs = 12
return eggs
print(span())
|
#!/bin/python3
# Multiples of 3 and 5
# If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
import sys
def calc_sum(k):
n3 = (k-1) // 3
n5 = (k-1) // 5
n15 = (k-1) // 15
sum = (3 * (n3 + 1) * n3 // 2) + (5 * (n5 + 1) * n5 // 2) - (15 * (n15 + 1) * n15 // 2)
return sum
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
sum = calc_sum(n)
# sum = 0
# for i in range(1, n, 1):
# if (i % 3 == 0 or i % 5 == 0):
# sum += i
print(sum)
|
num_01 = int(input("Please input 1 integer number : "))
num_02 = int(input("Please input 2 integer number : "))
print("add two numbers with using sum() function")
print("you can see the result at the next line")
print("sum of 2 numbers ({}, {})'s sum result = {}".format(num_01, num_02, sum(num_01, num_02)))
|
import sys
def sqr(x):
return x * x
def main(n):
x = 1
for i in range(1, n):
y = sqr(x) + 1
print("sqr(%d) + 1 = %d" % (x, y))
x = y
if __name__ == '__main__':
n = int(sys.argv[1])
main(n)
|
import queue
import time
class Node:
def __init__( self, state, parent, direction, depth, cost ):
# Contains the state of the node
self.state = state
# Contains the node that generated this node
self.parent = parent
# Contains the operation that generated this node from the parent
self.direction = direction
# Contains the depth of this node (parent.depth +1)
self.depth = depth
# Contains the path cost of this node from depth 0. Not used for depth/breadth first.
self.cost = cost
def __hash__(self):
return self.state.__hash__
def __str__(self):
return (self.state,self.direction,self.depth,self.cost)
def createNode(state, parent, direction, depth, cost):
return Node(state, parent, direction, depth, cost)
def expandNode(parentnode) :
#Expand the current node as the parent. Create an empty list and append children into the list.
expanded_nodes = []
upNode = up(parentnode.state)
downNode = down(parentnode.state)
leftNode = left(parentnode.state)
rightNode = right(parentnode.state)
#If a child node is returned None from createNode() method, do not append to the expanded nodes list.
if upNode != None:
expanded_nodes.append(createNode(upNode, parentnode, "u", parentnode.depth + 1, parentnode.cost+1 ) )
if downNode != None:
expanded_nodes.append( createNode(downNode, parentnode, "d", parentnode.depth + 1, parentnode.cost+1 ) )
if leftNode != None:
expanded_nodes.append( createNode(leftNode, parentnode, "l", parentnode.depth + 1, parentnode.cost+1 ) )
if rightNode != None:
expanded_nodes.append( createNode(rightNode, parentnode, "r", parentnode.depth + 1, parentnode.cost+1 ) )
return expanded_nodes
def up(state):
new_state = state[:]
index = new_state.index(0)
if index not in [0,1,2]:
temp = new_state[index-3]
new_state[index-3] = new_state[index]
new_state[index] = temp
return new_state
else:
return None
def down(state):
new_state = state[:]
index = new_state.index(0)
if index not in [6,7,8]:
temp = new_state[index+3]
new_state[index+3] = new_state[index]
new_state[index] = temp
return new_state
else:
return None
def left(state):
new_state = state[:]
index = new_state.index(0)
if index not in [0,3,6]:
temp = new_state[index-1]
new_state[index-1] = new_state[index]
new_state[index] = temp
return new_state
else:
return None
def right(state):
new_state = state[:]
index = new_state.index(0)
if index not in [2,5,8]:
temp = new_state[index+1]
new_state[index+1] = new_state[index]
new_state[index] = temp
return new_state
else:
return None
def printParent(nodeToExplore):
if nodeToExplore.parent == None:
return
else:
printParent(nodeToExplore.parent)
print(nodeToExplore.direction, ' ,' , end = " ")
def checkRepeat(expandedNodeList,exploredStates,frontierStates):
temp = []
for x in expandedNodeList:
temp.append(x)
for expN in temp:
if expN.state in exploredStates or expN.state in frontierStates:
expandedNodeList.remove(expN)
for n in expandedNodeList:
frontierStates.append(n.state)
def goalFound(nodeToExplore,explored,end,start):
directionList = []
directionList.insert(0,nodeToExplore.direction)
parentNode = nodeToExplore.parent
print('path_to_goal : ', end = " ")
printParent(nodeToExplore.parent)
print(nodeToExplore.direction)
print('cost_of_path: ', nodeToExplore.cost)
print('nodes_expanded: ', len(explored))
print('max_search_depth: ', nodeToExplore.depth+1)
print('time_elapsed: ', end-start)
def BFSexplore(initialState, goalState):
# Initialize lists, start timer
start = time.time()
# frontier - List of nodes in the frontier (to be explored)
frontier = []
# explored - List of nodes that have been explored/expanded
explored = []
# exploredStates - List of states that correlate to the explored list
exploredStates = []
# frontierStates - List of states that correlate to the frontier list
frontierStates = []
# Append starting node
startingnode = (createNode(initialState, None, None, 0, 0))
frontier.append(startingnode)
frontierStates.append(startingnode.state)
# Loop until frontier is empty or goalState is found
while(len(frontier) != 0):
# Dequeue from frontier and state list
nodeToExplore = frontier.pop(0)
frontierStates.pop(0)
# Check if goal is been found
if nodeToExplore.state == goalState:
# Stop timer
end = time.time()
# goalFound method to print information/statistics
goalFound(nodeToExplore,explored,end,start)
return nodeToExplore
else:
# If goal not found, explore/expand the node
explored.append(nodeToExplore)
exploredStates.append(nodeToExplore.state)
expandedNodeList = expandNode(nodeToExplore)
# checkRepeat method used to check if list of expanded node states are already in the respective frontier/explored lists
checkRepeat(expandedNodeList,exploredStates,frontierStates)
# Add expanded nodes to the frontier
frontier = frontier + expandedNodeList
return None
def DfsExplore(initialState,goalState):
start = time.time()
frontier = []
explored = []
exploredStates = []
frontierStates = []
startingnode = (createNode(initialState, None, None, 0, 0))
frontier.append(startingnode)
frontierStates.append(startingnode.state)
while(len(frontier) != 0):
nodeToExplore = frontier.pop(0)
frontierStates.pop(0)
explored.append(nodeToExplore)
exploredStates.append(nodeToExplore.state)
if nodeToExplore.state == goalState:
end = time.time()
directionList = []
directionList.insert(0,nodeToExplore.direction)
parentNode = nodeToExplore.parent
print('path_to_goal : ', end = " ")
printParent(nodeToExplore.parent)
print(nodeToExplore.direction)
print('cost_of_path: ', nodeToExplore.cost)
print('nodes_expanded: ', len(explored))
print('max_search_depth: ', nodeToExplore.depth+1)
print('time_elapsed: ', end-start)
return nodeToExplore
else:
expandedNodeList = expandNode(nodeToExplore)
temp = []
for x in expandedNodeList:
temp.append(x)
for expN in temp:
if expN.state in exploredStates or expN.state in frontierStates:
expandedNodeList.remove(expN)
for n in expandedNodeList:
frontierStates.append(n.state)
frontier = expandedNodeList + frontier
return None
def main():
initialState = [6,1,8,4,0,2,7,3,5]
goalState = [0,1,2,3,4,5,6,7,8]
resultNode = BFSexplore(initialState,goalState)
# resultNode2 = DfsExplore(initialState,goalState)
if __name__ == '__main__':
main()
|
#while和else结合使用简单介绍
a=1
while a == 1:
print("a==1")
a = a + 1
else:
print("a != 1")
print(a)
#简单语句组(若while循环体中只有一个语句,则可和while写在同一行)
a=1
while a == 1:a = a + 1
else:
print("a != 1")
print(a)
#break:跳出整个循环体
for i in range(1,10):
if i == 5:
break
print(i)
#continu:跳出当前循环而费整个循环体
for i in range(1,10):
if i == 5:
continue
print(i)
|
"""
分段函数求值
3x-5 (x>1)
f(x) = x+2 (-1<=x<=1)
5x +3 (x<-1)
"""
#分支结构
#x = -2
#if x > 1:
# y = 3*x-5
#elif x < -1:
# y = 5*x+3
#else:
# y = x+2
#print(y)
def calculate(x):
if x > 1:
y = 3*x-5
elif x < -1:
y = 5*x+3
else:
y = x+2
print(y)
calculate(2)
|
# for i in range(2,5):
# print(i)
def fib(n):
if n ==1:
return [0]
if n == 2:
return [0,1]
if n >= 3:
fibs = [0,1]
print(fibs[-1])
print(fibs[-2])
for i in range(3,n):
fibs = fibs.append(fibs[-2]+fibs[-1])
return fibs
print(fib(3))
|
"""
unnitest测试框架
--单元测试覆盖类型:
--语句覆盖
--条件覆盖
--判断覆盖
--路径覆盖
--框架介绍
--编写规范
--测试模块首先import unittest
--测试类必须继承 unittest.TestCase
--测试方法必须以“test_”
"""
import unittest
#定义测试类并继承unittest测试类
class TestStringMethods(unittest.TestCase):
#setUp 和 tearDown 方法是在每条测试用例的前后分别进行调用的方法
def setUp(self) -> None:#默认返回值是None
print("setup")
def tearDown(self) -> None:
print("teardown")
# setUpCalss 和 tearDownClass 方法是在整个类的前后分别调用的方法
#类级别的方法需要加一个装饰器:@classmethod
@classmethod
def setUpClass(cls) -> None:
print('set up class')
@classmethod
def tearDownClass(cls) -> None:
print('tear down class')
def test_play(self):
print('test abc')
def test_upper(self):
print('test_upper')
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
print('test_isupper')
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
print('test_split')
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
#环境准备的测试方法 不应该写在测试用例中
|
def fibonacci_generator(n=None):
if n is not None and n <= 0:
raise ValueError("parameter 'n' must be positive")
first = 0
second = 1
if n == 1:
yield first
yield first
yield second
if n is not None:
counter = 3
while counter <= n:
result = first + second
first, second = second, result
counter += 1
yield result
else:
while True:
result = first + second
first, second = second, result
yield result
if __name__ == "__main__":
for number in fibonacci_generator():
print(number)
|
months_array = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
}
def get_month_name(month):
return months_array[month]
def get_elem(arr, el):
for elem in arr:
key, val = elem
if key == el:
return True
return False
def get_index(arr, el):
index = 0
for elem in arr:
fst, snd = elem
if fst == el:
return index
index += 1
return None
def get_annual(arr, el):
res = []
for elem in arr:
year, months = elem
if year == el:
res = months
return res
def transform_data(variables, acc=None):
if len(variables) == 0:
return acc
else:
year, month, total, count = variables.pop(-1)
if acc is None:
acc = [[year, [[get_month_name(month), total]]]]
else:
if get_elem(acc, year):
months = get_annual(acc, year)
if not get_elem(months, get_month_name(month)):
acc[get_index(acc, year)][1].append([get_month_name(month), total])
else:
acc.append([year, [[get_month_name(month), total]]])
return transform_data(variables, acc)
def transform_data_to_hist(variables, acc=None):
if len(variables) == 0:
return acc
else:
year, month, total, count = variables.pop(-1)
if acc is None:
acc = [[year, [[get_month_name(month), count]]]]
else:
if get_elem(acc, year):
months = get_annual(acc, year)
if not get_elem(months, get_month_name(month)):
acc[get_index(acc, year)][1].append([get_month_name(month), count])
else:
acc.append([year, [[get_month_name(month), count]]])
return transform_data_to_hist(variables, acc)
|
#Topic:Logistic Regression - Simulated Data
#-----------------------------
#libraries
from sklearn.datasets import make_classification
from matplotlib import pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pandas as pd
# Generate and dataset for Logistic Regression
x, y = make_classification( n_samples=100, n_features=1, n_classes=2, n_clusters_per_class=1, flip_y=0.03, n_informative=1, n_redundant=0, n_repeated=0 )
x
x.mean()
y
np.bincount(y)
np.array(np.unique(y, return_counts=True)).T
# Create a scatter plot
plt.scatter(x, y, c=y, cmap='rainbow')
plt.title('Scatter Plot of Logistic Regression')
plt.show();
# Split the dataset into training and test dataset
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)
x_train, x_test
# Create a Logistic Regression Object, perform Logistic Regression
log_reg = LogisticRegression()
log_reg.fit(x_train, y_train)
# Show to Coeficient and Intercept
print(log_reg.coef_)
print(log_reg.intercept_)
# Perform prediction using the test dataset
y_pred = log_reg.predict(x_test)
y_pred
#Show the Confusion Matrix
confusion_matrix(y_test, y_pred)
|
#Missing Data
#-----------------------------
#%Imputation
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sleep1 = pd.read_csv('sleep.csv')
sleep1.head()
sleep2 = pd.read_csv('https://raw.githubusercontent.com/dupadhyaya/sipPython/master/data/sleep.csv')
sleep2
sleep = sleep2.copy()
#select to drop the rows only if all of the values in the row are missing.
sleep.dropna(how='all',inplace=False).shape
sleep.isna().sum(axis=1)
sleep.isna().sum(axis=0)
#just want to drop a column (variable) that has some missing values.
sleep.head()
sleep.dropna(axis=1,inplace=False).head()
sleep.dropna(axis=0,inplace=False).head()
sleep.shape
#keep only the rows with at least 4 non-na values:
sleep.dropna(thresh=9, axis=0, inplace=False).shape
sleep.dropna(thresh=55, axis=1, inplace=False).shape
s1= np.int(.6 * len(sleep)) ; s1
#t1=55
len(sleep)
sleep.shape #using dynamically : not working
sleep.dropna(thresh= t1 , axis=1, inplace=False ).shape
#https://towardsdatascience.com/the-tale-of-missing-values-in-python-c96beb0e8a9d
#negative values
sleep.fillna(value=-99999,inplace=False).head()
list1 = sleep['NonD'].dropna()
list1
import numpy.random
#numpy.random.choice(a, size=None, replace=True, p=None)
#https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html
np.random.choice(list1, 3, replace=False)
np.asscalar(np.random.choice(list1, 1, replace=False))
sleep['NonD'].fillna(value=np.asscalar(np.random.choice(list1, 1, replace=False)), inplace=False)
random_replace = np.vectorize(lambda x: np.random.randint(2) if np.isnan(x) else x)
sleep.head(10)
sleep5 = random_replace(sleep)
sleep5[1:5, 1:5]
nan_mask = np.isnan(sleep)
nan_mask
sleep.loc[[True, False,True],]
sleep[nan_mask] = np.random.randint(0, 2, size=np.count_nonzero(nan_mask) )
np.count_nonzero( np.isnan(sleep))
np.count_nonzero(np.isnan(sleep))
size=np.count_nonzero(nan_mask)
size
#%%% not working
from sklearn.preprocessing import Imputer
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
imp.fit(train)
train= imp.transform(train)
|
f#Matplot Lib -Features
#-----------------------------
#%
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,1000)
x
#just the plot
plt.plot(x, np.sin(x))
#Axis - manual
plt.plot(x, np.sin(x))
plt.xlim(-1, 15)
plt.ylim(-1.5, 1.5)
#Axis - Reverse
plt.plot(x, np.sin(x))
plt.xlim(-1, 11)
plt.ylim(1.5, -1.5)
#%%%
#Axis - Together -spelling AXIS
plt.plot(x, np.sin(x))
plt.axis([-1, 11,-2, 2])
#[xmin xmax ymin ymax]
#%%%
#Axis - tight
plt.plot(x, np.sin(x))
plt.axis('tight')
#Axis - equal aspect ratio
plt.plot(x, np.sin(x))
plt.axis('equal')
#%%%Label Plots
#titles & axis
plt.plot(x, np.sin(x))
plt.title('Sine Curve')
plt.xlabel('X Label')
plt.ylabel('Y Label')
#Multiple Curves, single line label
plt.plot(x, np.sin(x), label='X Curve')
plt.plot(x, np.cos(x), label='Y Curve')
plt.title('Sine and Cos Curve')
plt.ylabel("dhiraj Upadhyaya")
plt.xlabel("Anil Jadon")
plt.axis('equal')
plt.legend()
#axis plot
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,1000)
ax= plt.axes()
ax.plot(x, np.sin(x))
ax.set( xlim=(0,10) , ylim = (-2, 2), xlabel = 'X Label', ylabel = 'Y Label', title = ' Plot with Sin and Cos Curve');
|
# -*- coding: utf-8 -*-
#binomial distribution
#The binomial distribution model deals with finding the probability of success of an event which has only two possible outcomes in a series of experiments. For example, tossing of a coin always gives a head or a tail. The probability of finding exactly 3 heads in tossing a coin repeatedly for 10 times is estimated during the binomial distribution.
#We use the seaborn python library which has in-built functions to create such probability distribution graphs. Also, the scipy package helps is creating the binomial distribution.
#Eg1
from scipy.stats import binom
import seaborn as sb
binom.rvs(size=10,n=20,p=0.8)
data_binom = binom.rvs(n=20,p=0.8,loc=0,size=1000)
ax = sb.distplot(data_binom, kde=True, color='blue', hist_kws= {"linewidth": 25,'alpha':1})
ax.set(xlabel='Binomial', ylabel='Frequency')
#import libraries
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
#assuming value
total_sample=10
p_value=0.4
n=np.arange(0,20)
#import binomial function
binomial=stats.binom.pmf
(n,total_sample,p_value)
#plot the binomial distribution
plt.plot(n,binomial,'o-')
plt.title('Binomial distribution')
plt.xlabel('number of success')
plt.ylabel('probability of success')
plt.show()
|
#Dates - Range
#-----------------------------
#https://towardsdatascience.com/playing-with-time-series-data-in-python-959e2485bff8
import pandas as pd
import numpy as np
dtrange1D = pd.date_range('2019-1-1', '2019-7-11', freq='D')
dtrange1D
dtrange1D.min()
#The resulting DatetimeIndex has an attribute freq with a value of 'D', indicating daily frequency.#Available frequencies in pandas include
#hourly ('H'),
#calendar daily ('D'),
#business daily ('B'),
#weekly ('W'),
#monthly ('M'),
#quarterly ('Q'),
#annual ('A'), and many others.
#Frequencies can also be specified as multiples of any of the base frequencies, for example '5D' for every five days.
dtrange3D = pd.date_range('2019-1-1', '2019-7-11', freq='3D')
dtrange3D
dtrange1M = pd.date_range('2019-1-1', '2019-7-11', freq='1M')
dtrange1M
#date range at hourly frequency, specifying the start date and number of periods, instead of the start date and end date.
pd.date_range('2019-7-11', periods=8, freq='H')
pd.date_range('2019-7-11 09:00', periods=8, freq='H')
#https://www.dataquest.io/blog/tutorial-time-series-analysis-with-pandas/
#convert to different freq
#create data frame - weekly freq with some data
classStrength = np.random.randint(25,60, size=100)
weekdates = pd.date_range('2019-5-1', periods=100, freq='B')
weekdates
attendance = pd.DataFrame({'classStr':classStrength, 'wdates':weekdates})
attendance.head(10).append(attendance.tail(10))
#
attendance.set_index('wdates', inplace=True)
attendance
#create another column with daily freq
attendance.asfreq('D') #some missing values Sat/ Sun
attendance.head(10)
#temporarily creates dates for Sat/ Sun, fill with NA
#del dailyAttendance
attendance.asfreq('D', method='ffill')
attendance.head()
daily1 = attendance.asfreq('D', method='bfill')
daily1.head(10)
#replace permanently
daily1.rename(columns= {'classStr':'Dattnd'}, inplace=True)
newAttendance2 = pd.concat([attendance, daily1], axis=1)
newAttendance2.head()
#a.to_frame().join(b)#with same index
#resample
newAttendance2.resample('W').sum()
newAttendance2.resample('M').sum()
newAttendance2.classStr
newAttendance2.Dattnd
#
# Start and end of the date range to extract
start, end = '2019-05', '2019-06'
# Plot daily and weekly resampled time series together
#run together upto plt.show
fig, ax = plt.subplots()
ax.plot(newAttendance2.loc[start:end, 'Dattnd'], marker='.', linestyle='-', linewidth=0.5, label='Daily')
ax.plot(newAttendance2.loc[start:end, 'classStr'], marker='o', markersize=8, linestyle='-', label='Weekly Mean Resample')
ax.set_ylabel('Class Strength')
plt.xticks(rotation=90)
ax.legend()
plt.show();
#------------------------------------
#
newAttendance2['Dattnd'].resample('M').sum()
newAttendance2['Dattnd'].resample('M').sum(min_count=5)
#min rows=5
#----------
fig, ax = plt.subplots()
ax.plot(newAttendance2['Dattnd'], color='black', label='Daily Attendance')
newAttendance2[['classStr','Dattnd']].plot.area(ax=ax, linewidth=0)
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.legend()
ax.set_ylabel('Student Strength')
plt.show();
#https://www.dataquest.io/blog/tutorial-time-series-analysis-with-pandas/
#resample() method, which splits the DatetimeIndex into time bins and groups the data by time bin
|
#Topic:
#-----------------------------
# Import the modules
import sys
import random
ans = True
#This generates a random number and prints a different value every time
#exit when value entere
while ans:
question = input("Enter a number (1-8): (press enter to quit) ")
answers = random.randint(1,8)
ans = True
print
if (question == "" or question == 'q'): break
elif answers == 1: print("It is certain")
elif answers == 2: print("Outlook good")
elif answers == 3: print("You may rely on it")
elif answers == 4: print("Ask again later")
elif answers == 5: print("Concentrate and ask again")
elif answers == 6: print("Reply hazy, try again")
elif answers == 7: print("My reply is no")
elif answers == 8: print("My sources say no")
# if (question == "" or question == 'q'): sys.exit() or break
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 08:00:01 2019 @author: du
"""
"""
Test for an education/gender interaction in wages
==================================================
Wages depend mostly on education. Here we investigate how this dependence
is related to gender: not only does gender create an offset in wages, it
also seems that wages increase more with education for males than
females.
Does our data support this last hypothesis? We will test this using
statsmodels' formulas
(http://statsmodels.sourceforge.net/stable/example_formulas.html).
"""
##############################################################################
# Load and massage the data
import pandas
import urllib
import os
if not os.path.exists('wages.txt'):
# Download the file if it is not present
urllib.urlretrieve('http://lib.stat.cmu.edu/datasets/CPS_85_Wages',
'wages.txt')
# EDUCATION: Number of years of education
# SEX: 1=Female, 0=Male
# WAGE: Wage (dollars per hour)
data = pandas.read_csv('wages.txt', skiprows=27, skipfooter=6, sep=None,
header=None, names=['education', 'gender', 'wage'],
usecols=[0, 2, 5],
)
# Convert genders to strings (this is particulary useful so that the
# statsmodels formulas detects that gender is a categorical variable)
import numpy as np
data['gender'] = np.choose(data.gender, ['male', 'female'])
# Log-transform the wages, because they typically are increased with
# multiplicative factors
data['wage'] = np.log10(data['wage'])
##############################################################################
# simple plotting
import seaborn
# Plot 2 linear fits for male and female.
seaborn.lmplot(y='wage', x='education', hue='gender', data=data)
##############################################################################
# statistical analysis
import statsmodels.formula.api as sm
# Note that this model is not the plot displayed above: it is one
# joined model for male and female, not separate models for male and
# female. The reason is that a single model enables statistical testing
result = sm.ols(formula='wage ~ education + gender', data=data).fit()
print(result.summary())
##############################################################################
# The plots above highlight that there is not only a different offset in
# wage but also a different slope
#
# We need to model this using an interaction
result = sm.ols(formula='wage ~ education + gender + education * gender',
data=data).fit()
print(result.summary())
##############################################################################
# Looking at the p-value of the interaction of gender and education, the
# data does not support the hypothesis that education benefits males
# more than female (p-value > 0.05).
import matplotlib.pyplot as plt
plt.show()
|
#Seaborn Heatmap
#-----------------------------
#%https://seaborn.pydata.org/generated/seaborn.heatmap.html
import numpy as np
np.random.seed(0)
import seaborn as sns
sns.set()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)
#Change the limits of the colormap:
ax = sns.heatmap(uniform_data, vmin=0, vmax=1)
#Plot a heatmap for data centered on 0 with a diverging colormap:
normal_data = np.random.randn(10, 12)
ax = sns.heatmap(normal_data, center=0)
#Plot a dataframe with meaningful row and column labels:
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
flights
ax = sns.heatmap(flights)
#Annotate each cell with the numeric value using integer formatting:
ax = sns.heatmap(flights, annot=True, fmt="d")
#Add lines between each cell:
ax = sns.heatmap(flights, linewidths=.5)
#Use a different colormap:
ax = sns.heatmap(flights, cmap="YlGnBu")
#Center the colormap at a specific value:
ax = sns.heatmap(flights, center=flights.loc["January", 1955])
#Plot every other column label and don’t plot row labels:
data = np.random.randn(50, 20)
ax = sns.heatmap(data, xticklabels=2, yticklabels=False)
#Don’t draw a colorbar:
ax = sns.heatmap(flights, cbar=False)
|
#Topic: Association Rule Analysis
#-----------------------------
#libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#creating sample data
TID =[1,2,3,4,6,7,8,9]
items = [['I1,I2,I5'], ['I2,I4'], ['I2,I3'], ['I1,I2,I4'], ['I1,I3'], ['I2,I3'],['I1,I2,I3,I5'], ['I1,I2,I3']]
items
item1 = 'I1,I2,I5'
item1.split(',')
type(items)
for i in items: print(i)
newlist.append([i.split(',')[0])
itemSale = pd.DataFrame({'TID':TID, 'items':items})
itemSale
#data
#data = pd.read_csv('data/bookstore.csv')
data = itemSale
data.head()
#split transaction strings into lists
transactions = data['items'].apply(lambda t: [t.split() for x in t])
#convert DF to List of Strings
transactionsList = list(transactions)
transacationsList
transacationsList[0]
transactionsList.count([I1','I2'])
|
#Seaborn - CountPlot
#-----------------------------
#%https://seaborn.pydata.org/generated/seaborn.countplot.html
import seaborn as sns
sns.set(style="darkgrid")
titanic = sns.load_dataset("titanic")
ax = sns.countplot(x="class", data=titanic)
#values
ax = sns.countplot(x="class", hue="who", data=titanic)
#horiz
ax = sns.countplot(y="class", hue="who", data=titanic)
#Use a different color palette:
ax = sns.countplot(x="who", data=titanic, palette="Set3")
titanic.head()
#plt.bar keyword arguments for a different look:
ax = sns.countplot(x="who", data=titanic, facecolor=(0, 0, 0, 0), linewidth=5, edgecolor=sns.color_palette("dark", 3))
#Facet
#Use catplot() to combine a countplot() and a FacetGrid. This allows grouping within additional categorical variables. Using catplot() is safer than using FacetGrid directly, as it ensures synchronization of variable order across facets
g = sns.catplot(x="class", hue="who", col="survived", data=titanic, kind="count", height=4, aspect=.7);
#seaborn.countplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, dodge=True, ax=None, **kwargs)¶
|
# -*- coding: utf-8 -*-
#Frozen Set
#-----------------------------
#%
#The frozenset() method returns an immutable frozenset object initialized with elements from the given iterable. While elements of a set can be modified at any time, elements of frozen set remains the same after creation.
#Due to this, frozen sets can be used as key in Dictionary or as element of another set. But like sets, it is not ordered (the elements can be set at any index)
#frozenset([iterable])
#The frozenset() method optionally takes a single parameter:
#iterable (Optional) - the iterable which contains elements to initialize the frozenset with.
#Iterable can be set, dictionary, tuple, etc.
#The frozenset() method returns an immutable frozenset initialized with elements from the given iterable.
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
type(vowels)
vowels
fSet = frozenset(vowels)
type(fSet)
print('The frozen set is:', fSet)
fSet
print('The empty frozen set is:', frozenset())
#Dictionary : only takes keys
# random dictionary
person = {"name": "John", "age": 23, "sex": "male"}
person
type(person)
fSet2 = frozenset(person)
print('The frozen set is:', fSet2) #only keys
#Like normal sets, frozenset can also perform different operations like union, intersection, etc
#
s = [1,2,3,"hi",1,2,3,5,8,"hi","hello","google"]
s
output = frozenset(s)
print(output)
# Output: frozenset({1, 2, 3, 'google', 5, 8, 'hi', 'hello'})
#Frozenset is an immutable unordered collection of unique elements. It holds collection of element but it does not guarantee the order of the elements in it. As it is immutable we cannot able to update the data once created. when we need to get a unique elements out of group of the repeated elements then we can simply use built-in function "frozenset". we can also use the set but we should only use it when we want to update it afterwards. Because it consumes more memory than frozenset.
#https://learnbatta.com/blog/python-working-with-frozenset-data-type-50/
|
# -*- coding: utf-8 -*-
#Tuples - collection, ordered, unchangeable/ unmutatble, like list, round bracket
tuple1 = (1,2, 'SIP', 'Dhiraj', True)
tuple1
#everying like list except changes
tuple1[0] = 99
#access
tuple1[0]
for i in tuple1 : print(i)
if 'Dhiraj' in tuple1 : print('Dhiraj is present in tuple')
if 'Kounal' in tuple1 : print('Kounal is present in tuple')
tuple1.append('kounal') #error, cannot add
len(tuple1)
#methods in tuple
#count, index, ...
tuple1
tuple1.remove() #cannot remove also
#single value
tuple2a = 'a'
type(tuple2a) #error incorrect way
tuple2b = 'a',
type(tuple2)
#end of tuple
#where do we used it - list type of object where no changes are required
#list of gender, courses, categories, countries, list of values
#https://learnbatta.com/blog/python-working-with-tuple-data-type-41/
|
# -*- coding: utf-8 -*-
#
#-----------------------------
#%
# -*- coding: utf-8 -*-
#Python has excellent libraries for data visualization. A combination of Pandas, numpy and matplotlib can help in creating in nearly all types of visualizations charts. In this chapter we will get started with looking at some simple chart and the various properties of the chart.
##Creating a Chart
#We use numpy library to create the required numbers to be mapped for creating the chart and the pyplot method in matplotlib to draws the actual chart.
#import libraries
import numpy as np
import matplotlib.pyplot as plt
#create sample data
x = np.arange(0,10)
x
y = x ^ 2
y
#Simple Plot
plt.plot(x,y)
#line plot by default for numerical values
#Labling the Axes: we can apply labels to the axes as well as a title for the chart using appropriate methods from the library as shown below.
import numpy as np
import matplotlib.pyplot as plt
#%%%
x = np.arange(0,10)
y = x ^ 2
x,y
#Labeling the Axes and Title
#run these 4 lines together
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
plt.plot(x,y)
#see label values: title, x&y label
|
#Boxplots and paired differences
import matplotlib.pyplot as plt
#data
from pydataset import data
mtcars = data('mtcars')
mtcars.head()
#Example 1
plt.figure()
mtcars.boxplot(column=['mpg'])
plt.yticks(5)
plt.show();
plt.figure()
mtcars.boxplot(column=['mpg','wt'])
plt.yticks(5)
plt.show();
#Different dataset
import pandas as pd
data = pd.read_csv('data/brain_size.csv', sep=';', na_values='.')
# Box plot of FSIQ and PIQ (different measures od IQ)
plt.figure(figsize=(4, 3))
data.boxplot(column=['FSIQ', 'PIQ'])
plt.show();
# Boxplot of the difference
plt.figure(figsize=(4, 3))
plt.boxplot(data['FSIQ'] - data['PIQ'])
plt.xticks((1, ), ('FSIQ - PIQ', ))
plt.show();
#end
#boxplot category wise
#https://towardsdatascience.com/understanding-boxplots-5e2df7bcbd51
|
#Topic: Clustering - Simple and Data Camp Site
#-----------------------------
#https://www.datacamp.com/community/tutorials/k-means-clustering-python
#https://scikit-learn.org/stable/modules/clustering.html
X = [1,1,1,2,1,2,1,2]
Y = [4,2,4,1,1,4,1,1]
Z = [1,2,2,2,1,2,2,1]
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import metrics
from scipy.spatial.distance import cdist
df = pd.DataFrame({'X':X, 'Y':Y, 'Z':Z})
df
from sklearn.cluster import KMeans
#https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html
i=3;
km3 = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)
km3
#KMeans(n_clusters=8, init=’k-means++’, n_init=10, max_iter=300, tol=0.0001, precompute_distances=’auto’, verbose=0, random_state=None, copy_x=True, n_jobs=None, algorithm=’auto’)
dir(km3)
km3.fit_predict(df)
km3.cluster_centers_
km3.inertia_
km3.labels_ #which row has goes to which cluster no
km3.get_params
km3.n_clusters
df
pd.concat([df, pd.Series(km3.labels_)], axis=1)
#not change i = 2
i=2;
km2 = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)
km2
km2.fit_predict(df)
km2.cluster_centers_
km2.labels_ #which row has goes to which cluster no
km2.inertia_
km3.inertia_ # less
df
pd.concat([df, pd.Series(km2.labels_)], axis=1)
#%%% #How to selected i ? - optimal number of clusters
wcss = []
#run these together
for i in range(1, 5):
kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)
kmeans.fit(df)
wcss.append(kmeans.inertia_)
wcss #this is approx value of i ~ 2
plt.plot(wcss)
#%%%
km1 = KMeans(n_clusters = 1, init = 'k-means++', random_state = 42)
km1.fit(df)
km1.inertia_
km2 = KMeans(n_clusters = 2, init = 'k-means++', random_state = 42)
km2.fit(df)
km2.inertia_
km3 = KMeans(n_clusters = 3, init = 'k-means++', random_state = 42)
km3.fit(df)
km3.inertia_
km4 = KMeans(n_clusters = 4, init = 'k-means++', random_state = 42)
km4.fit(df)
km4.inertia_
km1.inertia_, km2.inertia_, km3.inertia_, km4.inertia_
#https://www.datanovia.com/en/lessons/determining-the-optimal-number-of-clusters-3-must-know-methods/
#%%% k means determine k
distortions = []
K = range(1,5)
for k in K:
kmeanModel = KMeans(n_clusters=k).fit(df)
kmeanModel.fit(df)
distortions.append(sum(np.min(cdist(df, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / df.shape[0])
distortions
# Plot the elbow
plt.plot(K, distortions, 'bx-')
plt.xlabel('k')
plt.ylabel('Distortion')
plt.title('The Elbow Method showing the optimal k')
plt.show();
#%%%%
#Plot clusters %%%%
km3b = KMeans(n_clusters = 3, init = 'k-means++', random_state = 42)
X2 = np.random.randint(50,100, size=100)
Y2 = np.random.randint(60,90, size=100)
df2 = pd.DataFrame({'X':X2, 'Y':Y2})
km3b.fit(df2)
km3b.inertia_
centers = np.array(km3b.cluster_centers_)
centers
plt.scatter(x=df2.X, y=df2.Y)
plt.scatter(centers[:,0], centers[:,1], marker="x", color='r')
plt.show();
#end here...
|
#Topic:US Crime
#-----------------------------
#libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
url = "https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/US_Crime_Rates/US_Crime_Rates_1960_2014.csv"
crime = pd.read_csv(url)
crime.head()
crime.info()
# pd.to_datetime(crime)
crime.Year = pd.to_datetime(crime.Year, format='%Y')
crime.info()
crime = crime.set_index('Year', drop = True)
crime.head()
del crime['Total']
crime.head()
# Uses resample to sum each decade
crimes = crime.resample('10AS').sum()
# Uses resample to get the max value only for the "Population" column
population = crime['Population'].resample('10AS').max()
# Updating the "Population" column
crimes['Population'] = population
crimes
#dangerous decade to live
# apparently the 90s was a pretty dangerous time in the US
crime.idxmax(0)
#year in which max of each column had
|
# -*- coding: utf-8 -*-
#Matplot Styling
#-----------------------------
#Python - Chart Styling
#The charts created in python can have further styling by using some appropriate methods from the libraries used for charting. In this lesson we will see the implementation of Annotation, legends and chart background.
#Adding Annotations - Many times, we need to annotate the chart by highlighting the specific locations of the chart. In the below example we indicate the sharp change in values in the chart by adding annotations at those points.
#libraries
import numpy as np
#from matplotlib import pyplot as plt
import matploylib.pyplot as plt
#generate data
x = np.arange(0,10)
y = x ^ 2
z = x ^ 3
t = x ^ 4
#check
x,y,z,t
# Labeling the Axes and Title : run next 4 lines together
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
plt.plot(x,y)
#Annotate - next 3 lines together
plt.annotate(xy=[2,1], s='Second Entry')
plt.annotate(xy=[4,6], s='Third Entry')
plt.plot(x,y)
#Adding Legends
#We sometimes need a chart with multiple lines being plotted. Use of legend represents the meaning associated with each line. In the below chart we have 3 lines with appropriate legends.
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0,10)
y = x ^ 2
z = x ^ 3
t = x ^ 4
# Labeling the Axes and Title : run all these lines together
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
plt.annotate(xy=[2,1], s='Second Entry')
plt.annotate(xy=[4,6], s='Third Entry')
plt.plot(x,y)
plt.plot(x,z)
plt.plot(x,t)
plt.legend(['Race1', 'Race2','Race3'], loc=4) # Adding Legends
#Chart presentation Style
#We can modify the presentation style of the chart by using different methods from the style package.
plt.style.available #available styles
#Style the background
plt.style.use('fast')
plt.plot(x,z)
#other styles
plt.style.use('classic')
plt.plot(x,z)
#
plt.style.use('bmh')
plt.plot(x,z)
#https://matplotlib.org/3.1.0/gallery/style_sheets/style_sheets_reference.html
plt.style.use('ggplot')
plt.plot(x,z)
#https://matplotlib.org/3.1.0/gallery/style_sheets/ggplot.html#sphx-glr-gallery-style-sheets-ggplot-py
plt.style.use('dark_background')
plt.plot(x,z)
#
plt.style.use('seaborn')
plt.plot(x,z)
#Presentation
plt.style.use('presentation')
plt.plot(x,z)
#you can define your style
#https://matplotlib.org/users/style_sheets.html#defining-your-own-style
|
#Label in Scatter Plot
#-----------------------------
#%
import matplotlib.pyplot as plt
import numpy as np
plt.clf()
# using some dummy data for this example
xs = np.random.normal(loc=4, scale=2.0, size=10)
ys = np.random.normal(loc=2.0, scale=0.8, size=10)
plt.scatter(xs,ys)
# zip joins x and y coordinates in pairs
for x,y in zip(xs,ys):
label = "{:.2f}".format(y)
plt.annotate(label, # this is the text
(x,y), # this is the point to label
textcoords="offset points", # how to position the text
xytext=(0,10), # distance from text to points (x,y)
ha='center') # horizontal alignment can be left, right or center
plt.xticks(np.arange(0,10,1))
plt.yticks(np.arange(0,5,0.5))
plt.show();
|
#Topic: Apple Data
#-----------------------------
#libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/09_Time_Series/Apple_Stock/appl_1980_2014.csv'
apple = pd.read_csv(url)
apple.head()
apple.dtypes
apple.Date = pd.to_datetime(apple.Date)
apple['Date'].head()
apple = apple.set_index('Date')
apple.head()
# NO! All are unique
apple.index.is_unique
apple.sort_index(ascending = True).head()
apple_month = apple.resample('BM').mean()
apple_month.head()
#diff btw first and last dt
(apple.index.max() - apple.index.min()).days
#data of months
apple_months = apple.resample('BM').mean()
len(apple_months.index)
#plot
# makes the plot and assign it to a variable
appl_open = apple['Adj Close'].plot(title = "Apple Stock")
# changes the size of the graph
fig = appl_open.get_figure()
fig.set_size_inches(13.5, 9)
|
# -*- coding: utf-8 -*-
#Different ways of importing libraries
Z#Python comes with built in functions like
x=[1, 4.5, 9]
print(x)
abs(x)
int(x[1]) #takes only 1 value
len(x)
#they are limited in functionality
#need more functions - this comes from libraries or modules
#Modules define functions, classes, variables that can be referenced
import math
print(math.pi)
#if gives an error that no module found, they you have install it from anaconda prompt (as admin)
#pip install xxxxxxx : xxxx - module name
#modules have to be imported to be used
#method 1 - import : functions have to be used with prefix of module name
#list imported libraries
import random
for i in range(10): print(random.randint(1,25), end =' ')
#method 2
#from xxxxx import
#functions can be referred by name rather than dot notation
from random import randint
for i in range(10) : print(randint(1,25), end=' ')
#no dot used
#use comma to import more functions from modules
#from module import function1, function2
#Method3 : Alias
# import [module] as [another_name]
import random as rn
for i in range(10) : print(rn.randint(1,25), end=' ')
#Installing modules
#multiple modules
import math, re
import sys, pprint
pprint.pprint(sys.modules) #loaded modules
#anaconda prompt
#pip install [module]
#Loaded Modules List
import sys
sys.modules.keys()
#2
import math,re
print(dir())
del math, random
#removing imported module
#del [module]
#Checking
before = [str(m) for m in sys.modules]
print(before)
##how to import libraries in python
import math
from math import pi
from math import *
#
import pandas
#alias
import pandas as pd
#import [module] as [anothername]
#existing name already used, use shorter verion of library name
import math as m
print(m.pi)
import matplotlib as plt
plt.show()
#for OS related commands
import os
print(os.name)
os.getcwd()
#import any python files also
#links
https://leemendelowitz.github.io/blog/how-does-python-find-packages.html
|
#Topic: Linear Regression Stock Market Prediction
#-----------------------------
#libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Stock_Market = {'Year': [2017,2017,2017, 2017,2017,2017,2017,2017, 2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016, 2016,2016,2016], 'Month': [12, 11,10,9,8,7,6, 5,4,3, 2,1,12,11, 10,9,8,7,6,5,4,3,2,1], 'Interest_Rate': [2.75,2.5,2.5,2.5,2.5, 2.5,2.5,2.25,2.25, 2.25,2,2,2,1.75,1.75, 1.75,1.75, 1.75,1.75,1.75,1.75,1.75,1.75,1.75], 'Unemployment_Rate': [5.3,5.3, 5.3,5.3,5.4,5.6,5.5, 5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1, 5.9,6.2,6.2, 6.1],'Stock_Index_Price':[1464,1394,1357,1293,1256,1254,1234,1195, 1159,1167,1130,1075,1047,965, 943,958,971,949,884,866,876,822,704,719] } #dictionary format
type(Stock_Market)
Stock_Market
#height(IV) vs weight (DV)
df = pd.DataFrame(Stock_Market, columns=['Year','Month','Interest_Rate', 'Unemployment_Rate', 'Stock_Index_Price' ])
df.head(n=5)
print (df)
df.shape
#check that a linear relationship exists between the:
#Stock_Index_Price (dependent variable) and Interest_Rate (independent variable)
#Stock_Index_Price (dependent variable) and Unemployment_Rate (independent variable)
#run these lines together
%matplotlib inline
plt.scatter(df['Interest_Rate'], df['Stock_Index_Price'], color='red')
plt.title('Stock Index Price Vs Interest Rate', fontsize=14)
plt.xlabel('Interest Rate', fontsize=14)
plt.ylabel('Stock Index Price', fontsize=14)
plt.grid(True)
plt.show();
# linear relationship exists between the Stock_Index_Price and the Interest_Rate. Specifically, when interest rates go up, the stock index price also goes up:
plt.scatter(df['Unemployment_Rate'], df['Stock_Index_Price'], color='green')
plt.title('Stock Index Price Vs Unemployment Rate', fontsize=14)
plt.xlabel('Unemployment Rate', fontsize=14)
plt.ylabel('Stock Index Price', fontsize=14)
plt.grid(True)
plt.show() ;
#linear relationship also exists between the Stock_Index_Price and the Unemployment_Rate – when the unemployment rates go up, the stock index price goes down (here we still have a linear relationship, but with a negative slope):
#Multiple Linear Regression
from sklearn import linear_model #1st method
import statsmodels.api as sm #2nd method
df.head(5)
df.shape
X = df[['Interest_Rate','Unemployment_Rate']] # here we have 2 variables for multiple regression. If you just want to use one variable for simple linear regression, then use X = df['Interest_Rate'] for example. Alternatively, you may add additional variables within the brackets
Y = df['Stock_Index_Price']
X
Y
# with sklearn : from sklearn import linear_model
regr = linear_model.LinearRegression()
regr.fit(X, Y)
regr.score(X, Y) #R2
#89% of the variation in Stock Prices is due to Unemployment Rate & Interest Rate
print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)
df.head()
#Stock_Index_Price = (Intercept) + (Interest_Rate coef)*X1 + (Unemployment_Rate coef)*X2
#Stock_Index_Price = (1798.4040) + (345.5401)*X1 + (-250.1466)*X2
dir(regr)
help(regr)
# prediction with sklearn
New_Interest_Rate = 2.75
New_Unemployment_Rate = 5.3
print ('Predicted Stock Index Price: \n', regr.predict([[New_Interest_Rate ,New_Unemployment_Rate]]))
#Interest Rate = 2.75 (i.e., X1= 2.75)
#Unemployment Rate = 5.3 (i.e., X2= 5.3)
Stock_Index_Price = (1798.4040) + (345.5401)*(2.75) + (-250.1466)*(5.3) #1422.86
Stock_Index_Price
# with statsmodels
import statsmodels.api as sm #2nd method
X = sm.add_constant(X) # adding a constant
X.head()
model = sm.OLS(Y, X).fit() #create model
predictions = model.predict(X)
predictions
print_model = model.summary()
print(print_model)
#coefficients captured in this table match with the coefficients generated by sklearn.
print('R2 ', round(regr.score(X, Y),3) , 'Intercept: \n', np.round(regr.intercept_,3), ' Coefficients', np.round(regr.coef_,3))
#we got consistent results by applying both sklearn and statsmodels.
#ref
#https://datatofish.com/multiple-linear-regression-python/
#end here
from sklearn.linear_model import LinearRegression
X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
# y = 1 * x_0 + 2 * x_1 + 3
y = np.dot(X, np.array([1, 2])) + 3
reg = LinearRegression().fit(X, y)
reg.score(X, y)
|
#Topic: Statistics - Covariance
#-----------------------------
#Covariance provides the a measure of strength of correlation between two variable or more set of variables. The covariance matrix element Cij is the covariance of xi and xj. The element Cii is the variance of xi.
#If COV(xi, xj) = 0 then variables are uncorrelated
#If COV(xi, xj) > 0 then variables positively correlated
#If COV(xi, xj) > < 0 then variables negatively correlated
#numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)
#Parameters:
#m : [array_like] A 1D or 2D variables. variables are columns
#y : [array_like] It has the same form as that of m.
#rowvar : [bool, optional] If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed:
#bias : Default normalization is False. If bias is True it normalize the data points.
import numpy as np
x = np.array([[0, 3, 4], [1, 2, 4], [3, 4, 5]])
x
print("Shape of array:\n", np.shape(x))
print("Covarianace matrix of x:\n", np.cov(x))
#%%
x = [1.23, 2.12, 3.34, 4.5]
y = [2.56, 2.89, 3.76, 3.95]
# find out covariance with respect columns
cov_mat = np.stack((x, y), axis = 0)
cov_mat
print(np.cov(cov_mat))
#%%https://www.geeksforgeeks.org/python-numpy-cov-function/
#%% Pandas - Covariance
Series.cov(other, min_periods=None)
#https://www.geeksforgeeks.org/python-pandas-series-cov-to-find-covariance/
|
# -*- coding: utf-8 -*-
# Interfaces in the plots
#-----------------------------
#%
#library
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
fig = plt.figure() #plot Figure
#MATLAB interface
#create 1st panel
#(row, column, panel)
plt.subplot(2, 1, 1)
plt.plot(x, np.sin(x))
#create 2nd panel
#(row, column, panel)
plt.subplot(2, 1, 2)
plt.plot(x, np.cos(x))
#%%%
#how to add something into the first one, overlap
#first create grid of plots
fig1, ax1 = plt.subplots(2)
#call plot() method on the appropriate object
ax1[0].plot(x, np.sin(x))
ax1[1].plot(x, np.cos(x))
# switching between
plt.plot() and ax.plot()
#for best visualisation
|
#Topic: Correlation, Covariance,
#-----------------------------
#libraries
#The difference between variance, covariance, and correlation is:
#Variance is a measure of variability from the mean
#Covariance is a measure of relationship between the variability of 2 variables - covariance is scale dependent because it is not standardized
#Correlation is a of relationship between the variability of of 2 variables - correlation is standardized making it not scale dependent
import pandas as pd
import numpy as np
# Setting a seed so the example is reproducible
np.random.seed(4272018)
df = pd.DataFrame(np.random.randint(low= 0, high= 20, size= (5, 2)), columns= ['Commercials Watched', 'Product Purchases'])
df
df.agg(["mean", "std"])
df.cov()
df.corr()
#skewness & Kurtosis
#%matplotlib inline
import numpy as np
import pandas as pd
from scipy.stats import kurtosis
from scipy.stats import skew
import matplotlib.pyplot as plt
plt.style.use('ggplot')
data = np.random.normal(0, 1, 10000000)
data
len(data)
np.var(data)
plt.hist(data, bins=60)
print("mean : ", np.mean(data))
print("var : ", np.var(data)) #sq of sd
print("skew : ", skew(data))
print("kurt : ", kurtosis(data))
#https://www.spcforexcel.com/knowledge/basic-statistics/are-skewness-and-kurtosis-useful-statistics
#https://www.researchgate.net/post/What_is_the_acceptable_range_of_skewness_and_kurtosis_for_normal_distribution_of_data distribution
#If the skewness is between -0.5 and 0.5, the data are fairly symmetrical
#If the skewness is between -1 and – 0.5 or between 0.5 and 1, the data are moderately skewed
#If the skewness is less than -1 or greater than 1, the data are highly skewed
import numpy as np
from scipy.stats import kurtosis, skew
x_random = np.random.normal(0, 2, 10000)
x = np.linspace( -5, 5, 10000 )
y = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x)**2 ) # normal distribution
np.skewness(y)
skew(y)
import matplotlib.pyplot as plt
f, (ax1, ax2) = plt.subplots(1, 2)
ax1.hist(x_random, bins='auto')
ax1.set_title('probability density (random)')
ax2.hist(y, bins='auto')
ax2.set_title('(your dataset)')
plt.tight_layout()
#find skewness and kurtosis of mtcars columns
mtcars
skew(mtcars.mpg)
plt.hist(mtcars.mpg, bins=5)
kurtosis(mtcars.mpg)
#find columns normal distributed, skewed and kurtosis
|
#Topic: Frozen Sets
#-----------------------------
#The frozenset() method returns an immutable frozenset object initialized with elements from the given iterable.
#syntax : frozenset([iterable])
#Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of frozen set remains the same after creation.
#Due to this, frozen sets can be used as key in Dictionary or as element of another set. But like sets, it is not ordered (the elements can be set at any index)
#Sets are mutable, and may therefore not be used, for example, as keys in dictionaries.
#Another problem is that sets themselves may only contain immutable (hashable) values, and thus may not contain other sets.
#Because sets of sets often occur in practice, there is the frozenset type, which represents immutable (and, therefore, hashable) sets
fzs1 = frozenset([1, 2, 3])
fzs1
type(fzs1)
fzs2 = frozenset([2, 3, 4])
fzs1.union(fzs2) #all numbers
fzs1.intersection(fzs2) #common
#Sets may only contain immutable (hashable) values, and thus may not contain other sets, in which case frozensets can be useful. Consider the following example:
a = set([1, 2, 3])
b = set([2, 3, 4])
a.add(b)
a.add(frozenset(b))
a
#--
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
fSet = frozenset(vowels)
print('The frozen set is:', fSet)
#used in dictionary # random dictionary
person = {"name": "John", "age": 23, "sex": "male"}
fSet = frozenset(person)
print('The frozen set is:', fSet)
#Like normal sets, frozenset can also perform different operations like union, intersection, etc.
#links
#https://www.python-course.eu/python3_sets_frozensets.php
|
#Topic: Join
#-----------------------------
#libraries
numList = ['1', '2', '3', '4']
seperator = ', '
print(seperator.join(numList))
numTuple = ('1', '2', '3', '4')
print(seperator.join(numTuple))
s1 = 'abc'
s2 = '123'
""" Each character of s2 is concatenated to the front of s1"""
print('s1.join(s2):', s1.join(s2))
""" Each character of s1 is concatenated to the front of s2"""
print('s2.join(s1):', s2.join(s1))
#sets
test = {'2', '1', '3'}
s = ', '
print(s.join(test))
test = {'Python', 'Java', 'Ruby'}
s = '->->'
print(s.join(test))
#dictionaries
test = {'mat': 1, 'that': 2}
s = '->'
print(s.join(test))
test = {1:'mat', 2:'that'}
s = ', '
# this gives error
print(s.join(test))
# The join() method tries to concatenate the key (not value) of the dictionary to the string. If the key of the string is not a string, it raises TypeError exception.
#https://www.programiz.com/python-programming/methods/string/join
#%%
list1 = ['1','2','3','4']
s = "-"
# joins elements of list1 by '-' # and stores in sting s
s = s.join(list1)
# join use to join a list of # strings to a separator s
print(s)
#
"asd%d" % 9
"asd" + str(9)
"abc" + str(9)
'abc{0}'.format(9)
#%%
s = ' this is my string '
s.split()
s.split(maxsplit=1)
'a' + 'b' + 'c'
'do' * 2
'Hello' + 2 #error
strings = ['do', 're', 'mi']
','.join(strings)
#%%%
str = ""
str1 = ( "geeks", "for", "geeks" )
str.join(str1)
def convert(s):
str1 = ""
return(str1.join(s))
s = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']
print(convert(s))
#%%
str?
result = ""
for i in range(1, 11): result += str(i) + " "
print(result)
#%%%
import pandas as pd
my_list = [1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0]
''.join([str(item) for item in my_list])
string1 = "student"
string1
for i in range(1, 11): print(string1 + str(i))
slist1 = [string1 + str(i) for i in range(1,11)]
slist1
#----
rollno = pd.Series(range(1,11))
rollno
name = pd.Series(["student" + str(i) for i in range(1,11)])
name
|
#Topic: Numpy Histogram
#-----------------------------
#Compute the histogram of a set of data.
#https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
#NumPy has a numpy.histogram() function that is a graphical representation of the frequency distribution of data. Rectangles of equal horizontal size corresponding to class interval called bin and variable height corresponding to frequency
import numpy as np
#numpy.histogram() function takes the input array and bins as two parameters. The successive elements in bin array act as the boundary of each bin.
#All but the last (righthand-most) bin is half-open. In other words, if bins is:
[1, 2, 3, 4]
#then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4.
x = [1,1,1,1,2,2,2]
np.histogram(x, bins=2)
#count 1s=4, 2s-3 : [1 to 1.5]-4, [1.6 to 2.0]-3
x = [1,2,1,1,6,7,8]
np.histogram(x, bins=2)
#1 to 4.5 : 4, 4.6 to 8 : 3
x = np.arange(1,11)
x
np.histogram(x, bins=2)
#1 to 5.5 : 5, 5.6 to 10 : 5
x
np.histogram(x, bins=[0,4,10])
#0 to 3.9 : 4, 4.01 to 10 : 6
#[include] (donot include): default [1,4):[4,10]
np.histogram(x, bins=[0,4.1,10])
np.histogram(x, bins=[0,3,9,10])
#%%
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
np.histogram(a,bins = [0,20,40,60,80,100])
hist,bins = np.histogram(a,bins = [0,20,40,60,80,100])
print(hist) #0-20:3, 20-40:4, 40-60:5, 60-80:2, 80-100:1
print(bins)
#%%%
from matplotlib import pyplot as plt
import numpy as np
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
np.histogram(a,bins = [0,20,40,60,80,100])
plt.hist(a, bins = [0,20,40,60,80,100])
plt.title("histogram")
plt.show();
#Links
#https://www.datacamp.com/community/tutorials/histograms-matplotlib
#https://datatofish.com/plot-histogram-python/
#https://matplotlib.org/3.1.1/gallery/statistics/histogram_multihist.html
|
#String Operations
# Sets
S1 = {1,2,3}
type(S1)
S1
S2 = set()
type(S2)
S2.add(4)
S2.add(5)
S2
#Empty Set
S0=set() # {} creates empty dict, not a set
S0
type(S0)
#Simple Set
S1={'apple','banana',1,2}
S1
type(S1)
#convert to List ???
L1=set(S1)
type(L1)
L1
# Set Comprehensions
import string
s = set(string.ascii_lowercase)
print(s,end=' ')
from string import ascii_uppercase, ascii_lowercase
sl=set(ascii_lowercase)
sL=list(ascii_lowercase)
su=list(ascii_uppercase)
print(sl,su, sep='-', end=' ')
sl.sort() # error
sL.sort()
sL
#cannot sort sets
alphabet = []
for letter in range(97,123):
alphabet.append(chr(letter))
print(alphabet, end='')
ALPHABET = []
for letter in range(65, 91):
ALPHABET.append(chr(letter))
print(ALPHABET, end='')
# Use map to create lowercase alphabet
alphabet1 = map(chr, range(97, 123))
print(list(alphabet1))
for ch in map(chr, range(97, 123)):
print(ch, end='')
L2= [chr(x) for x in [66,53,0,94]]
L2
L2= [chr(x) for x in range(97,123)]
print(L2, end=' ')
[*map(chr, [66, 53, 0, 94])]
[*map(chr, range(97,123))]
|
class Vehiculos():
def __init__(self, marca, modelo):
self.marca=marca
self.modelo=modelo
self.enMarcha=False
self.acelera=False
self.frena=False
def arrancar(self):
self.enMarcha=True
def acelerar(self):
self.acelera=True
def frenar(self):
self.frena=True
def estado(self):
print(f"Marca: {self.marca}.\nModelo: {self.modelo}",
f"\nEn marcha: {self.enMarcha}. \nAcelerando: {self.acelera}.",
f"\nFrenando: {self.frena}")
class Furgoneta(Vehiculos):
def carga(self, cargar):
self.cargado=cargar
if(self.cargado):
return "La furgoneta esta cargada"
else:
return "La furgoneta no esta cargada"
class Moto(Vehiculos):
hcaballito="no estoy haciendo caballito"
# esta funcion cambia el valor de la variable
def caballito(self):
self.hcaballito="Voy haciendo el caballito"
# al tener el mismo nombre que el metodo de la clase padre
# este sobreescribe el anterior
# en el caso de esta clase tener un hijo
# el heredaria el estado de esta clase y no de vehiculos
def estado(self):
print(f"Marca: {self.marca}.\nModelo: {self.modelo}",
f"\nEn marcha: {self.enMarcha}. \nAcelerando: {self.acelera}.",
f"\nFrenando: {self.frena}. \n{self.hcaballito}")
class VElectricos():
def __init__(self):
self.autonomia=100
def cargarEnergia(self):
self.cargando=True
# Cuando hay herencia multiple
# se le da preferencia al primero que se usa
# como parametro
class BicicletaElectrica(VElectricos, Vehiculos):
pass
miBici=BicicletaElectrica()
print("\n----Otro vehiculo----\n")
miMoto=Moto("Honda","CBR")
miMoto.caballito()
miMoto.estado()
print("\n----Otro vehiculo----\n")
miFurgoneta=Furgoneta("Renault", "Kangoo")
miFurgoneta.arrancar()
miFurgoneta.estado()
print(miFurgoneta.carga(True))
|
miTupla=("juan", 13, 1, 1995)
#imprime 1
print(miTupla[2])
miLista=list(miTupla)
# imprime ['juan', 13, 1, 1995]
# los corchetes son de lista
print(miLista)
miTupla2=tuple(miLista)
# imprime ('juan', 13, 1, 1995)
# los parentecis son de tupla
print(miTupla2)
#me da true por que existe en la tupla
print("juan" in miTupla2)
#me devolvera 1 por que solo existe 1 vez
print(miTupla2.count(13))
#devuelve la cantidad de elementos
#de la tuplas 4
print(len(miTupla2))
#empaquetado de tupla
miTupla3= "Hernesto", 14, 9, 1995
#me devuelve <class 'tuple'>
print(type(miTupla3))
#desempaquetado de tupla
nombre, dia, mes, agno =miTupla3
print("el nombre es:", nombre)
print("el dia es:", dia)
print("el mes es:", mes)
print("el ano es:", agno)
|
def suma( op1, op2 ):
print("El resultado de la suma es:", str( op1 + op2 ))
def restar( op1, op2 ):
print("El resultado de la resta es:", str( op1 - op2 ))
def multiplicar( op1, op2 ):
print("El resultado de la multiplicacion es:", str( op1 * op2 ))
def dividir( op1, op2 ):
print("El resultado de la division es:", str( op1 / op2 ))
def potenciar( op1, op2 ):
print("El resultado de la potenciacion es:", str( op1 ** op2 ))
def redondear( op1 ):
print("El redondeado es:", str(round( op1 )))
|
from tkinter import *
raiz=Tk()
miFrame=Frame(raiz, width=1200, height=600)
miFrame.pack()
#aca estoy posicionando los elementos
cuadroNombre=Entry(miFrame)
cuadroNombre.grid(row=0, column=1)
cuadroApellido=Entry(miFrame)
cuadroApellido.grid(row=1, column=1)
cuadroDireccón=Entry(miFrame)
cuadroDireccón.grid(row=2, column=1)
cuadroPass=Entry(miFrame)
cuadroPass.grid(row=3, column=1)
# esto se utiliza para tapar la contraseña
cuadroPass.config(show="*")
nombreLabel=Label(miFrame, text="Nombre:")
nombreLabel.grid(row=0, column=0, sticky="w", padx=10, pady=10)
apellidoLabel=Label(miFrame, text="Apellido:")
apellidoLabel.grid(row=1, column=0, sticky="w", padx=10, pady=10)
direccionLabel=Label(miFrame, text="Dirección:")
direccionLabel.grid(row=2, column=0, sticky="w", padx=10, pady=10)
passLabel=Label(miFrame, text="Contraseña:")
passLabel.grid(row=3, column=0, sticky="w", padx=10, pady=10)
# con .config(fg="red", justify="center")
# en los Entry podria poner los textos en rojo
# y centrados cuando se escriben
# el pading es la distancia que hay entre el contenedor
# y el contenido esa se puede modificar como pady y padx
#sticky permite posicionar el texto del label n,s,e,w
# y combinaciones ne nw ejemplo
raiz.mainloop()
|
import pickle
class Persona():
def __init__(self, nombre, genero, edad):
self.nombre = nombre
self.genero = genero
self.edad = edad
print(f"Se ha creado una persona nueva con el nombre de {self.nombre}")
# sirve para convertir en cadena de texto
# la informacion de un objeto
def __str__(self):
return "{} {} {}".format(self.nombre, self.genero, self.edad)
class ListaPersonas():
personas=[]
def __init__(self):# para agregar informacion binaria
listaDePersonas=open("ficheroExternoPersonas", "ab+")
listaDePersonas.seek(0)
# aca le digo que diga la cantidad de personas que guardo
# pero si no guardo a nadie que pase a la execpcion
try:
self.personas=pickle.load(listaDePersonas)
print("Se cargaron {} personas del fichero correspondiente".format(len(self.personas)))
except:
print("El fichero esta vacio")
finally:
listaDePersonas.close()
del (listaDePersonas)
def agregarPersonas(self, persona):
# con esto agrego personas a la lista
self.personas.append(persona)
def mostrarPersonas(self):
for persona in self.personas:
print(persona)
def guardarPersonasEnFicheroExterno(self):
listaDePersonas=open("ficheroExternoPersonas", "wb")
pickle.dump(self.personas, listaDePersonas)
listaDePersonas.close()
del (listaDePersonas)
def mostrarInfoFicheroExterno(self):
print("La informacion del fichero externo es la siguiente:")
for persona in self.personas:
print(persona)
miLista=ListaPersonas()
p=Persona("Sandra", "Femenino", 29)
p2=Persona("Antonio", "Masculino", 39)
p3=Persona("Ana", "Femenino", 19)
miLista.agregarPersonas(p)
miLista.agregarPersonas(p2)
miLista.agregarPersonas(p3)
miLista.guardarPersonasEnFicheroExterno()
miLista.mostrarInfoFicheroExterno()
|
import sqlite3
# inicio la conexion
miConexion=sqlite3.connect("PrimeraBase")
# creo el cursor
miCursor=miConexion.cursor()
# aca se mete la intruccion sql de crear tabla
#-miCursor.execute("CREATE TABLE PRODUCTOS (NOMBRE_ARTICULO VARCHAR(50), PRECIO INTEGER, SECCION VARCHAR(20))")
# aca inserto valores en la tabla creada
#-miCursor.execute("INSERT INTO PRODUCTOS VALUES('BALON', 15, 'DEPORTES')")
# esto es para decir que aceptamos los cambios
# que se le hicieron a la tabla
variosProductos=[
("Camiseta", 10, "Deportes"),
("Jarrón", 90, "Cerámica"),
("Camión", 20, "Jueguetería")
]
# aca le pido al servidor todos los productos
# de la tabla PRODUCTOS
miCursor.execute("SELECT * FROM PRODUCTOS")
# este metodo devuelve una lista con todos los registros
# de la intruccion sql
variableProductos=miCursor.fetchall()
# aca imprime la respuesta
for producto in variableProductos:
print("Nombre Articulo:", producto[0],
"\nPrecio:", producto[1],
"\nCategoria:", producto[2])
# esto es para ingresar varios valores
# al mismo tiempo
# se tiene que poner tantos interrogantes
# como valores de tablas se quieran poner
#-miCursor.executemany("INSERT INTO PRODUCTOS VALUES (?,?,?)", variosProductos)
miConexion.commit()
# cierro la conexion
miConexion.close()
# para ver la base de datos se puede descargar el visor sqlite
|
class Coche():
# constructor de clase
def __init__(self):
# encapsulo las variables
self.__largoChasis=250
self.__anchoChasis=120
self.__enMarcha=False
self.__ruedas=4
def arrancar(self,arrancar):
# le cambio para lo que le pase por parametro
# se lo va a insertar como valor en arrancar
self.__enMarcha=arrancar
# y aca que devuelva un mensaje si el auto da
# true o no
if(self.__enMarcha):
return "El coche esta en marcha"
else:
return "El coche esta parado"
def estado(self):
print(f"El coche tiene {self.__ruedas} ruedas, un ancho de {self.__anchoChasis} y un largo de {self.__largoChasis}.")
miCoche=Coche()
print(miCoche.arrancar(True))
miCoche.estado()
print("\n----A continuacion creamos el segundo objeto----\n")
miCoche2=Coche()
print(miCoche.arrancar(False))
miCoche2.estado()
|
from bs4 import BeautifulSoup
import urllib.request
from sys import argv
print(""" .|'''.|
||.. ' .... ... .. .... ... ... .... ... ..
''|||. .| '' ||' '' '' .|| ||' || .|...|| ||' ''
. '|| || || .|' || || | || ||
|'....|' '|...' .||. '|..'|' ||...' '|...' .||.
||
'''' """)
class Scraper:
def __init__(self,file):
self.file = file
def scrapelinks(self):
#Fast parser to parse HTML websites
parser = "lxml"
soup = BeautifulSoup(self.file,parser)
#It locates all the anchor elements it sotres them in variable
contain_links = soup.find_all("a")
#it looks for a tag called href which is the link in every element then prints the links
for tag in contain_links:
link = tag.get("href")
print(link+"\n")
def scrapetitles(self):
#Fast parser to parse HTML websites
parser = "lxml"
soup = BeautifulSoup(self.file,parser)
#finds the H1 html elements then prints them
titles = soup.find_all("h1")
print(titles)
def scrapep(self):
#Fast parser to parse HTML websites
parser = "lxml"
soup = BeautifulSoup(self.file,parser)
#finds paragraphs in html
paragraphs = soup.find_all("p")
#counter to count the paragraphs
count = 0
#print every paragraph sepreatly
for paragraph in paragraphs:
count += 1
print("Paragraph"+ str(count)+ "\n" + str(paragraph)+ "\n")
def downloadhtml(self):
parser = "lxml"
soup = BeautifulSoup(self.file,parser)
#downloads a html file of the site given
with open("Downlodedhtml.html", "a") as download_file:
download_file.write(soup.prettify())
args = argv[1:]
if len(argv)==3:
url = str(args[0])
if url == None:
url = str(input("Enter the site you want to scrape : \n"))
user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"
r = urllib.request.Request(url,headers={'User-Agent': user_agent})
with urllib.request.urlopen(r) as response:
the_page = response.read()
if str(args[1]) == "links":
Scraper(the_page).scrapelinks()
elif str(args[1]) == "titles":
Scraper(the_page).scrapetitles()
elif str(args[1]) == "paragraphs":
Scraper(the_page).scrapep()
elif str(args[1]) == "downloadhtml":
Scraper(the_page).downloadhtml()
else:
url = str(input("Enter the site you want to scrape : \n"))
user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"
r = urllib.request.Request(url,headers={'User-Agent': user_agent})
with urllib.request.urlopen(r) as response:
the_page = response.read()
scrapetype = str(input("What you want to scrap ? "))
if scrapetype == "links":
Scraper(the_page).scrapelinks()
elif scrapetype == "titles":
Scraper(the_page).scrapetitles()
elif scrapetype == "paragraphs":
Scraper(the_page).scrapep()
elif scrapetype == "downloadhtml":
Scraper(the_page).downloadhtml()
|
from utils import *
assignments = []
def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
# Don't waste memory appending actions that don't actually change any values
if values[box] == value:
return values
values[box] = value
if len(value) == 1:
assignments.append(values.copy())
return values
def naked_twins(values):
"""Eliminate values using the naked twins strategy.
Args:
values(dict): a dictionary of the form {'box_name': '123456789', ...}
Returns:
the values dictionary with the naked twins eliminated from peers.
"""
# Find all instances of naked twins
# Eliminate the naked twins as possibilities for their peers
naked_twin_map = {}
pair_map = {}
for box in boxes:
if len(values[box]) == 2:
if values[box] in pair_map:
pair_map[values[box]].append(box)
else:
pair_map[values[box]] = [box]
for key in pair_map:
if len(pair_map[key]) >= 2:
naked_twin_map[key] = pair_map[key]
for key, value in naked_twin_map.items():
for v in value:
row_item = [row for row in row_unit if v in row]
col_item = [col for col in col_unit if v in col]
sq_item = [sq for sq in square_unit if v in sq]
if row_item[0]:
for cell in row_item[0]:
if cell != v and values[cell] == key:
digits = list(key)
for cell in row_item[0]:
if cell not in value:
values[cell] = values[cell].replace(digits[0], "")
values[cell] = values[cell].replace(digits[1], "")
if col_item[0]:
for cell in col_item[0]:
if cell != v and values[cell] == key:
digits = list(key)
#print (digits)
for cell in col_item[0]:
if cell not in value:
values[cell] = values[cell].replace(digits[0], "")
values[cell] = values[cell].replace(digits[1], "")
if sq_item[0]:
for cell in sq_item[0]:
if cell != v and values[cell] == key:
digits = list(key)
#print (digits)
for cell in sq_item[0]:
if cell not in value:
values[cell] = values[cell].replace(digits[0], "")
values[cell] = values[cell].replace(digits[1], "")
return values
def grid_values(grid):
"""
Convert grid into a dict of {square: char} with '123456789' for empties.
Args:
grid(string) - A grid in string form.
Returns:
A grid in dictionary form
Keys: The boxes, e.g., 'A1'
Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.
"""
assert len(grid) == 81
all_values = '123456789'
new_values = dict(zip(boxes, grid))
for k in new_values.keys():
if new_values[k] == '.':
new_values[k] = all_values
return new_values
def eliminate(values):
"""
If a box has a single value assigned, then none of the peers of this box can have this value.
:param values:
The dictionary of the sudoku
:return values:
The values dictionary with the values eliminated
"""
values = naked_twins(values)
solved_values = [b for b in boxes if len(values[b]) == 1]
for box in solved_values:
digit = values[box]
for peer in peers[box]:
values[peer] = values[peer].replace(digit, '')
return values
def only_choice(values):
"""
If there is only one box in a unit which would allow a certain digit,
then that box must be assigned that digit.
:param values:
The dictionary of the sudoku
:return values:
The values dictionary with values after applying the only choice constraint
"""
nums = '123456789'
for unit in unit_list:
for digit in nums:
dplaces = [box for box in unit if digit in values[box]]
if len(dplaces) == 1:
values[dplaces[0]] = digit
return values
def reduce_puzzle(values):
"""
Combining functions eliminate and only choice to keep reducing and
simplifying the sudoku until no more reduction is possible
:param values:
The dictionary of the sudoku that needs reduction
:return values:
The sudoku dictionary after reduction after applying eliminate and only choice
"""
stalled = False
while not stalled:
before_solved_number = 0
after_solved_number = 0
for box in boxes:
if (len(values[box]) == 1):
before_solved_number = before_solved_number + 1
values = eliminate(values)
values = only_choice(values)
for box in boxes:
if (len(values[box]) == 1):
after_solved_number = after_solved_number + 1
if (before_solved_number == after_solved_number):
stalled = True
if len([box for box in values.keys() if len(values[box]) == 0]):
return False
return values
def search(values):
"Using depth-first search and propagation, try all possible values."
# First, reduce the puzzle using the previous function
values = reduce_puzzle(values)
if values is False:
return False
if all(len(values[s]) == 1 for s in boxes):
return values
# Choose one of the unfilled squares with the fewest possibilities
n,s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1)
# Now use recurrence to solve each one of the resulting sudokus, and
for value in values[s]:
new_sudoku = values.copy()
new_sudoku[s] = value
attempt = search(new_sudoku)
if attempt:
return attempt
def solve(grid):
"""
Find the solution to a Sudoku grid.
Args:
grid(string): a string representing a sudoku grid.
Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
Returns:
The dictionary representation of the final sudoku grid. False if no solution exists.
"""
temp_values = grid_values(grid)
result = eliminate(temp_values)
result2 = only_choice(result)
result3 = reduce_puzzle(result2)
result4 = search(result3)
return result4
if __name__ == '__main__':
try:
from visualize import visualize_assignments
visualize_assignments(assignments)
except SystemExit:
pass
except:
print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')
|
#1
def fatorial(n):
if(n < 0):
raise Exception('Menor que zero')
if(n == 0 or n == 1):
return 1
return n * fatorial(n - 1)
#2
def somatorio(n):
if(n == 0):
return 0
if(n > 0):
return n + somatorio(n-1)
if(n < 0):
return n + somatorio(n+1)
#3
def fibonacci(n):
if(n < 1):
raise Exception('Menor que um')
if(n == 1):
return 0
if(n == 2):
return 1
return fibonacci(n -1) + fibonacci(n -2)
#4
def somatorioKJ(k, j):
if (j < k):
return somatorioKJ(j, k)
if (j == k):
return k
return j + somatorioKJ(k, j - 1)
#5
def palindrome(s):
if(len(s) <= 1):
return True
if(s[0] != s[len(s)-1]):
return False
palindrome(s[1:-1])
#6
def convBase2(n):
if (n < 1):
return ''
return str(n % 2) + str(convBase2(n / 2))
#7
def somatorioArray(list):
if len(list) == 0:
return 0
list.pop() + somatorio(list)
#8
def maiorElemento(list):
if(len(list) == 1):
return list.pop()
auxA = list.pop()
auxB = maiorElemento(list)
if(auxA >= auxB):
return auxA
else:
return auxB
#10
def nroDigit(n):
if (n/10 < 1 and n/10 > -1):
return 1
return 1 + nroDigit(n / 10)
print(nroDigit(-99999))
|
# All in-game items
class Weapon:
def __init__(self):
raise NotImplementedError("Do not create raw Weapon objects.")
def __str__(self): return self.name
class Rock(Weapon):
def __init__(self):
self.name = "Rock"
self.description = "A fist-sized rock, best used against heads."
self.damage = 5
self.value = 1
class Laptop(Weapon):
def __init__(self):
self.name = "Laptop"
self.description = "A good ol' Dell laptop. " \
"Heavy and nice to smack people with."
self.damage = 10
self.value = 50
class Fists(Weapon):
def __init__(self):
self.name = "Fists"
self.description = "Bare knuckles."
self.damage = 1
self.value = 0
# Had to create this class to easily determine if drone is in inventory (with isinstance)
class Special:
def __str__(self):
return self.name
class Drone(Special):
def __init__(self):
self.name = "The Holy Drone"
self.description = "A drone. You can feel its spirit humming within."
def __str__(self):
return self.name
# Future plans, add effects for getting drunk
class Consumables:
def __str__(self):
return self.name
class Beer(Consumables):
def __init__(self):
self.name = "Carlsberg Beer"
self.description = "A can of Carlsberg, cold and wet from condensation."
self.value = 10
# Also had to create this class for easy searching with isinstance
class Poison:
def __str__(self):
return self.name
class Mee(Poison):
def __init__(self):
self.name = "Mee Goreng Extra Spicy"
self.description = "It's a plate of mee goreng, and even the smell makes your eyes water."
self.value = 1
|
def product(a, b):
if a < 0:
a *= -1
elif b < 0:
b *= -1
result = a * b
print("Product of", a, "and", b, "equals", result)
return result
def pre_product(a, b):
product_result = product(a,b)
if a < 0 and b < 0:
product_result *= -1
return product_result
|
'''
Given an undirected graph with n nodes labeled 1..n. Some of the nodes are already connected. The i-th edge connects nodes edges[i][0] and edges[i][1] together. Your task is to augment this set of edges with additional edges to connect all the nodes. Find the minimum cost to add new edges between the nodes such that all the nodes are accessible from each other.
Input:
n, an int representing the total number of nodes.
edges, a list of integer pair representing the nodes already connected by an edge.
newEdges, a list where each element is a triplet representing the pair of nodes between which an edge can be added and the cost of addition, respectively (e.g. [1, 2, 5] means to add an edge between node 1 and 2, the cost would be 5).
Example 1:
Input: n = 6, edges = [[1, 4], [4, 5], [2, 3]], newEdges = [[1, 2, 5], [1, 3, 10], [1, 6, 2], [5, 6, 5]]
Output: 7
Explanation:
There are 3 connected components [1, 4, 5], [2, 3] and [6].
We can connect these components into a single component by connecting node 1 to node 2 and node 1 to node 6 at a minimum cost of 5 + 2 = 7.
'''
def compute_min_cost(num_nodes, base_mst, poss_mst):
uf = {}
# create union find for the initial edges given
def find(edge):
uf.setdefault(edge, edge)
if uf[edge] != edge:
uf[edge] = find(uf[edge])
return uf[edge]
def union(edge1, edge2):
uf[find(edge1)] = find(edge2)
for e1, e2 in base_mst:
if find(e1) != find(e2):
union(e1, e2)
# sort the new edges by cost
# if an edge is not part of the minimum spanning tree, then include it, else continue
cost_ret = 0
for c1, c2, cost in sorted(poss_mst, key=lambda x : x[2]):
if find(c1) != find(c2):
union(c1, c2)
cost_ret += cost
if len({find(c) for c in uf}) == 1 and len(uf) == num_nodes:
return cost_ret
else:
return -1
if __name__ == '__main__':
n = 6
edges = [[1, 4], [4, 5], [2, 3]]
new_edges = [[1, 2, 5], [1, 3, 10], [1, 6, 2], [5, 6, 5]]
print(compute_min_cost(n, edges, new_edges))
|
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
seen = {}
for i in range(len(nums)):
if target - nums[i] in seen:
return [i, seen[target-nums[i]]]
else:
seen[nums[i]] = i
return 0
nums = [2, 7, 11, 15]
target = 9
print(twoSum(nums, target))
|
def containsDuplicate(nums):
"""
:type nums: List[int]
:rtype: bool
"""
unique = set(nums)
return len(unique) != len(nums)
array = [1,1,1,3,3,4,3,2,4,2]
print(containsDuplicate(array))
|
'''
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Example 1:
Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}
Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself.
'''
# # @param head, a RandomListNode
# # @return a RandomListNode
# def copyRandomList(head):
# copy = collections.defaultdict(lambda:RandomListNode(0))
# copy[None] = None
# node = head
# while node:
# copy[node].label = node.label
# copy[node].next = copy[node.next]
# copy[node].random = copy[node.random]
# node = node.next
# return copy[head]
"""
# Definition for a Node.
class Node:
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
"""dict with old Nodes as keys and new Nodes as values. Doing so allows us to create node's next and random as we iterate through the list from head to tail. Otherwise, we need to go through the list backwards.
defaultdict() is an efficient way of handling missing keys """
map_new = collections.defaultdict(lambda: Node(None, None, None))
map_new[None] = None # if a node's next or random is None, their value will be None but not a new Node, doing so removes the if-else check in the while loop
nd_old = head
while nd_old:
map_new[nd_old].val = nd_old.val
map_new[nd_old].next = map_new[nd_old.next]
map_new[nd_old].random = map_new[nd_old.random]
nd_old = nd_old.next
return map_new[head]
|
def gradingStudents(grades):
newgrade=[]
for i in range(len(grades)):
if grades[i] > 40 and grades[i] <=100:
if ((((grades[i]//5)+1)*5)-grades[i]< 3 ):
newgrade.append(((grades[i]//5)+1)*5)
else:
newgrade.append(grades[i])
else:
if grades[i]>=38 and grades[i] < 40:
newgrade.append(40)
else:
newgrade.append(grades[i])
return newgrade
|
#!/usr/bin/env python
"""
Data wrangling tool for quickly selecting a winner from Habitica Challenge CSV
data.
"""
# Ensure backwards compatibility with Python 2
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals)
from builtins import *
import numpy as np
import os
import pandas as pd
import sys
from .configuration import get_options
def print_scores(header, scores):
""" Simple Leaderboard print function. """
print(header)
print('-' * len(header))
print(scores.to_string(header=False, float_format='%0.2f'))
print()
def pick_winner():
"""Habitica Challenge Data Wrangler"""
print('pick_winner - Version 2.0.0')
print('===========================')
print()
options = get_options()
# Load the raw challenge CSV data
try:
challenge_data = pd.read_csv(options.input_file, index_col='name')
except IndexError as e:
print("Error opening input data file")
exit(-1)
# Rename the score columns to the task name. It makes things a lot easier!
# First, build a list of matching task,value pairs...
kv_pairs = []
for i in range(int((len(challenge_data.columns) - 1) / 3)):
k = 'Task'
v = 'Value'
if i == 0:
kv_pairs.append((k,v))
else:
kv_pairs.append((k + '.' + str(i), v + '.' + str(i)))
# Next, remap the value column names to the matching task name...
new_columns = {}
for k,v in kv_pairs:
new_columns[v] = challenge_data[k][0]
challenge_data.rename(columns=new_columns, inplace=True)
# Now reshape the data into a more tractable layout
values = pd.DataFrame(data=challenge_data, columns=new_columns.values())
# take a copy of the values for spreadsheet output
if options.to_excel:
original_values = values.copy(deep=True)
# Set incomplete Todos to have a value of None
for idx, name in enumerate(values.columns):
if 'todo:' in name:
values.iloc[:,idx][values.iloc[:,idx] < 1] = None
# rank the scores
ranked = values.rank(axis=0, method='max', ascending=False)
# after ranking, each completed todo will have a value equal to the number of
# participants that completed the todo. This gives todos a variable value.
# Setting them to a consistent value is more fair.
incomplete_todo_score = len(values)
completed_todo_score = 1
for idx, name in enumerate(ranked.columns):
if 'todo:' in name:
null_mask = pd.isnull(ranked.iloc[:,idx])
not_null_mask = pd.notnull(ranked.iloc[:,idx])
ranked.iloc[:,idx][null_mask] = incomplete_todo_score
ranked.iloc[:,idx][not_null_mask] = completed_todo_score
# Sum the scores for each participant, and sort into ascending order
sorted_scores = ranked.mean(axis=1).sort_values(ascending=True)
# sorted_scores.to_csv('sorted.csv')
if options.to_excel:
basename = os.path.splitext(os.path.basename(options.input_file))[0]
excelname = basename + '_data.xls'
with pd.ExcelWriter(excelname) as writer:
challenge_data.to_excel(writer, sheet_name='raw')
original_values.to_excel(writer, sheet_name='reshaped')
ranked.to_excel(writer, sheet_name='placings')
pd.DataFrame(data=sorted_scores).to_excel(
writer,
sheet_name='final scores')
# Display the leaderboard
n = options.leaderboard_rows
print_scores('Leaderboard - average placing in all challenge tasks - lower is better', sorted_scores[:n])
# rank the sorted scores to detect a tie for first place
ranked_sorted = sorted_scores.rank(axis=0, method='min', ascending=True)
first_place = ranked_sorted[ranked_sorted == 1].index.values
if len(first_place) > 1:
print('You have a tie for first place, between:')
print(' ' + ', '.join(first_place))
print()
print('The randomly selected winner is: {0}'.format(
np.random.choice(first_place)))
print()
exit(0)
if __name__ == '__main__':
start()
|
# a*3 each 1 year
# b*2 each 1 year
args = input().split(' ')
a = int(args[0])
b = int(args[1])
years = 0
while a <= b:
a *= 3
b *= 2
years +=1
print(years)
|
# -*- coding: utf-8 -*-
"""
A = {1, 8, 2,4}
B = {4, 9, 2, 7}
print(A)
print(B)
print(A|B)
print(A&B)
print(A-B)
print(A^B)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict['model'])
import numpy as np
out_arr_1 = np.random.randint(2, 10, 8)
print(out_arr_1);
out_arr_2 = np.random.randint(2, 10, (2, 3))
print(out_arr_2);
out_arr_3 = np.random.randint(2, 10, (2, 3, 4))
print(out_arr_3);
"""
import numpy as np
from scipy import stats
data = np.random.randint(1, 11, 5)
print(data);
print(np.mean(data))
print(np.median(data))
print(stats.mode(data))
speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]
x = stats.mode(speed)
print(x)
print(data);
print(np.mean(data))
print(np.var(data))
print(np.std(data))
|
def make_album(artist_name, album_title, number=None):
album = {
"artist".title(): artist_name.title(),
"album".title(): album_title.title()
}
if number:
album['number'.title()] = number
return album
one = make_album('koko', 'wheels on the bus')
two = make_album('bobo', 'I losh you')
three = make_album('chu chu', 'handa', number=4)
print(one)
print(two)
print(three)
|
class User:
def __init__(self, first_name, last_name, email, title, age, city):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.title = title
self.age = age
self.city = city
self.login_attempts = 0
def describe_user(self):
print(f"\n{self.first_name} {self.last_name} is a {self.age} years old {self.title} who lives in {self.city}")
def greet_user(self):
print(f"\nHello {self.first_name} {self.last_name}")
def increment_login_attempts(self):
self.login_attempts +=1
def reset_login_attempts(self):
self.login_attempts = 0
ammar = User('Ammar', 'Alim', '[email protected]', 'Devops eng', 33, 'Seattle')
osman = User('Osman', 'Alim', '[email protected]', 'SRE eng', 55, 'khartoum')
ali = User('Ali', 'Alim', '[email protected]', 'Sec eng', 2, 'Seattle')
ammar.increment_login_attempts()
ammar.increment_login_attempts()
ammar.increment_login_attempts()
ammar.increment_login_attempts()
ammar.describe_user()
print(ammar.login_attempts)
ammar.reset_login_attempts()
ammar.describe_user()
print(ammar.login_attempts)
|
#D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.
test1 = [1, 2, 2, 3]
test2 = [2, 2, 3, 3, 3]
test3 = []
def remove_adjacent(lists):
n=0
while n+1 < len(lists):
if lists[n] == lists[n+1]:
lists.pop(n+1)
else:
n=n+1
print(lists)
def main():
remove_adjacent(test1)
remove_adjacent(test2)
remove_adjacent(test3)
if __name__ == '__main__':
main()
|
#Import and dependencies
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
#Here the process of automation is achieved by using the framework Selenium.
#Selenium is a portable framework for testing and automating web applications web applications
#Path to chromedriver.exe
chrome_path = r"C:\Users\giril\AppData\Local\Programs\Python\Python36-32\chromedriver.exe"
#Initiating and setting up the driver
driver = webdriver.Chrome(chrome_path)
URL = "https://www.linkedin.com/"
driver.get(URL)
#The script is made to wait, to ensure that the page is loaded
time.sleep(2)
driver.find_element_by_xpath("/html/body/main/section[1]/div[2]/form/div[2]/div[1]/input").click()
name = input("Enter your username ")
time.sleep(3)
driver.find_element_by_xpath("/html/body/main/section[1]/div[2]/form/div[2]/div[1]/input").send_keys(name)
time.sleep(2)
driver.find_element_by_xpath("/html/body/main/section[1]/div[2]/form/div[2]/div[2]/input").click()
time.sleep(2)
passwd = input("Enter your password ")
driver.find_element_by_xpath("/html/body/main/section[1]/div[2]/form/div[2]/div[2]/input").send_keys(passwd)
time.sleep(2)
driver.find_element_by_xpath("/html/body/main/section[1]/div[2]/form/button").click()
time.sleep(2)
driver.find_element_by_xpath("/html/body/header/div/form/div/div/div/div/div[1]").click()
time.sleep(1)
ppl = input("Enter the name of the contact ")
driver.find_element_by_xpath("/html/body/header/div/form/div/div/div/div/div[1]/div/input").send_keys(ppl)
time.sleep(1)
driver.find_element_by_xpath("/html/body/header/div/form/div/div/div/div/div[2]/button").click()
time.sleep(3)
driver.find_element_by_xpath("/html/body/div[7]/div[3]/div/div[2]/div/div[2]/div/div/div/div/ul/li[1]/div/div/div[3]/div/button").click()
time.sleep(2)
driver.find_element_by_xpath("/html/body/div[4]/div/div/div[3]/button[1]").click()
message = input("Enter the note u want to connect with ")
driver.find_element_by_xpath("/html/body/div[4]/div/div/div[2]/div[1]/textarea").send_keys(message)
time.sleep(1)
driver.find_element_by_xpath("/html/body/div[4]/div/div/div[3]/button[2]").click()
time.sleep(1)
driver.find_element_by_xpath("/html/body/header/div/nav/ul/li[1]/a/span[1]").click()
|
# Initializes people set to 69
people = 69
# Initializes cars set to 70
cars = 70
# Initializes buses set to 71
buses = 71
# If cars > people (i.e., if cars > people evaluates to true)
if cars > people:
# Print the string
print "We should take the cars."
# Otherwise (if cars > people evaluates to false), if cars < people (i.e., if cars < people evaluates to true)
elif cars < people:
# Print the string
print "We should not take cars."
# Otherwise, if cars < people evaluates to false and if cars > people evaluates to false
else:
# Print the string
print "We can't decide."
# Evaluates the statement buses > cars
if buses > cars:
# If buses > cars evalutes to true, print the string
print "That's too many buses."
# If buses > cars evalutes to false, evalute the statement buses < cars
elif buses < cars:
# If buses < cars evaluates to true print the string
print "Maybe we could take the buses."
# If neither buses > cars nor buses < cars evalutes to true
else:
# Print the string
print "We still can't decide."
# Evaluates the statement people > buses
if people > buses:
# If the statement is true, print the string
print "Alright, let's just take the buses."
# If people > buses evaluates to false
else:
# Print the string
print "Fine, let's stay home then."
|
# Imports argv module from sys
from sys import argv
# Sets argv to script and filename (i.e. these must be passed when the script is run)
script, filename = argv
# Prints the string with the raw data fromatter and filename taken from argv inserted
print "We're going to erase %r." % filename
# Prints the string
print "If you don't wnat that hit CTRL-C (^C)."
# Prints the string
print "If you do want that, hit RETURN."
# Calls raw input with "?" passed as a parameter, allowing the user to choose between CTRL-C and RETURN
raw_input("?")
# Prints the string
print "Opening the file..."
# Sets target to open called on filename with the write option passed as a parameter
target = open(filename, 'w')
# Prints the string
print "Truncating the file. Goodbye!"
# Calls truncate on target
target.truncate()
# Prints the string
print "Now I'm going to ask you for three lines."
# Sets line1, line2, line3 to raw_input with the string passed allowing the user to input three lines
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
# Prints the string
print "I'm going to write these lines to the file."
# Calls write on target (i.e. open(filename)) and passes these six arguments
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
# Prints the string
print "And finally, we close it."
# Calls close on target
target.close()
|
# Defines constructor Parent
class Parent(object):
# Defines function override taking parameter self (i.e., Parent)
def override(self):
# Prints string when called
print "PARENT override()"
# Defines constructor Child which inherits from Parent
class Child(Parent):
# Defines function override for Child taking parameter self (i.e. Child)
# Overrides inheritance in this case (separate function)
def override(self):
# Prints string when called
print "CHILD override()"
# Initializes dad as an instance of Parent
dad = Parent()
# Initializes son as an instance of Child
son = Child()
# Calls override on dad, i.e. prints "PARENT Override()"
dad.override()
# Calls override on son, i.e. prints "CHILD override()"
# This is an override
son.override()
|
# Defines constructor Parent
class Parent(object):
# Defines parent.override()
def override(self):
# Prints string when called
print "PARENT override()"
# Defines parent.implicit()
def implicit(self):
# Prints string when called
print "PARENT implicit()"
# Defines parent.altered()
def altered(self):
# Prints string when called
print "PARENT altered()"
# Defines Child constructor that inherets from Parent
class Child(Parent):
# Defines child.override()
def override(self):
# Prints string when called
print "CHILD override()"
# Defines child.altered()
def altered(self):
# Prints string when called
print "CHILD, BEFORE PARENT altered()"
# Calls super altered (i.e. child.altered = parent.altered())
super(Child, self).altered()
# Prints string
print "CHILD, AFTER PARENT altered()"
# Initializes dad to new instance of Parent
dad = Parent()
# Initializes son to new instance of Child
son = Child()
# Calls parent.implicit()
dad.implicit()
# Calls child.implicit() == parent.implicit() (no child.implicit)
# defined but Child inherits parent.implicit implicitly
son.implicit()
# Calls parent.override()
dad.override()
# Calls child.override()
son.override()
# Calls parent.altered
dad.altered()
# Calls child.altered == call super to parent.altered()
son.altered()
|
import pickle
from heapq import heappush, heappop
from time import sleep
# import numpy as np
# --------------------------------------
# --------------------------------------
# SLIDING PUZZLE IMPORTS (REPEATED CODE)
# --------------------------------------
# --------------------------------------
def tuple_puzzle_to_list(puzzle):
'''Converts a board matrix from a tuple of tuples to a list of lists'''
return list(list(row) for row in puzzle)
def list_puzzle_to_tuple(puzzle):
'''Converts a board matrix from a list of lists to a tuple of tuples'''
return tuple(tuple(row) for row in puzzle)
def is_solved(puzzle):
'''Returns a boolean indicating whether a board is solved or not'''
# if the zero isnt in the bottom left corner dont search the whole board
if puzzle[-1][-1] != 0:
return False
for x in range(len(puzzle)):
for y in range(len(puzzle[-1])):
if x == len(puzzle) - 1 and y == len(puzzle[-1]) - 1:
continue
if puzzle[x][y] != (x*len(puzzle[-1])) + (y + 1):
return False
return True
def find_zero(puzzle):
'''Given a board, returns a tuple with the x,y coordinates of the zero.
NOTE: This can be improved by keeping track of the 0 instead of searching
for it every time'''
for x in range(len(puzzle)):
for y in range(len(puzzle[-1])):
if puzzle[x][y] == 0:
return x, y
def find_next_moves(puzzle):
'''Given a puzzle this will find the coordinates of the 0 and return
a tuple with x,y coordinates and a list of four new x,y coordinates or
None if the 0 is in a corner or on an edge'''
x, y = find_zero(puzzle)
left = (x - 1, y) if x > 0 else None
right = (x + 1, y) if x < len(puzzle) - 1 else None
up = (x, y - 1) if y > 0 else None
down = (x, y + 1) if y < len(puzzle[-1]) - 1 else None
return (x, y), [left, right, up, down]
def swap(puzzle, start, next_move):
'''Given a puzzle, a tuple with x,y 0 (start) coordinates, and the x,y
coordinates of the next move, '''
lst_pzl = tuple_puzzle_to_list(puzzle)
sx, sy, nx, ny = *start, *next_move
lst_pzl[sx][sy], lst_pzl[nx][ny] = lst_pzl[nx][ny], lst_pzl[sx][sy]
return list_puzzle_to_tuple(lst_pzl)
def moves(puzzle):
'''Given a puzzle this will find the next 2-4 possible moves, create
2-4 new game boards, then returns a list of them. '''
start, next_moves = find_next_moves(puzzle)
new_boards = []
for move in next_moves:
if move is not None:
new_board = swap(puzzle, start, move)
new_boards.append((new_board, move))
return new_boards
def manhattan_dist(puzzle):
'''returns the manhattan distance of a board to its solved state
This is the sum of the manhattan distances (aka l1 distance/ taxicab
distance) from each number to its desired location.
'''
# return num_inversions(puzzle)[0]
dist = 0
for x in range(len(puzzle)):
for y in range(len(puzzle[0])):
if puzzle[x][y] != 0:
val = puzzle[x][y]
des_x, des_y = divmod(val - 1, len(puzzle[0]))
dist += abs(x - des_x) + abs(y - des_y)
return dist
def display_solution(board, all_moves, sleep_len=1):
'''prints the solution with fancy colors and dramatic pauses'''
BLUE = '\033[94m'
GREEN = '\033[92m'
END = '\033[0m'
RED = '\033[91m'
# YELLOW = '\033[93m'
print('Start:')
for row in board:
print(f'\t{row}')
print()
num_moves = len(all_moves)
zero_loc = find_zero(board)
for itr, move in zip(range(1, num_moves + 1), all_moves):
sleep(sleep_len)
print(f'Move {itr}: {BLUE}{zero_loc}{END} <-> {RED}{move}{END}')
board_str = ''
for i, row in enumerate(board):
board_str += '\t('
for j, col in enumerate(row):
if j != 0:
board_str += ', '
if zero_loc == (i, j):
board_str += f'{BLUE}{col}{END}'
elif move == (i, j):
board_str += f'{RED}{col}{END}'
else:
board_str += f'{col}'
board_str += ')\n'
board = swap(board, zero_loc, move)
print(board_str)
zero_loc = move
sleep(sleep_len)
print(f'Done in {num_moves} moves:{GREEN}')
for row in board:
print(f'\t{row}')
print(END)
# --------------------------------------
# --------------------------------------
# --------------DONE--------------------
# --------------------------------------
# --------------------------------------
# the model will predict the number of moves required from a starting position
model = pickle.load(open('best_states.pkl', 'rb'))
def flatten(board):
flat = []
for row in board:
for item in row:
flat.append(item)
return flat
def predict_num_moves(board):
man_dist = manhattan_dist(board)
if man_dist <= 3:
return man_dist
# flat_board = np.array(board).flatten()
flat_board = flatten(board)
return model.predict([flat_board])[0]
def solve(original_puzzle):
'''Uses A* method with an heuristic for how solved a given puzzle state
is. Uses manhattan distance as the heuristic.'''
if type(original_puzzle) == list:
original_puzzle = list_puzzle_to_tuple(original_puzzle)
# if not is_solveable(original_puzzle):
# return -1, None
if is_solved(original_puzzle):
return 0, []
# TODO: Plot what the min heap's min is every time
min_heap = []
dist = predict_num_moves(original_puzzle)
min_heap.append((dist, original_puzzle, []))
# create a set of seen boards to make sure we dont follow the same path
# more than once
seen = set()
seen.add(original_puzzle)
while len(min_heap) > 0:
# remove the next board from the queue, alone w num moves, and allmoves
_, curr_board, all_moves = heappop(min_heap)
# find the next possible board moves
next_board_moves = moves(curr_board)
# loop through the new boards
for board, move in next_board_moves:
# ensure the board has not been seen
if board not in seen:
# if so check if the board is solved
if is_solved(board):
# if it is return the board and the moves
return all_moves + [move]
# add the board, num_moves + 1, and all_moves +[move] to the q
dist = predict_num_moves(board) + len(all_moves) + 1
board_obj = dist, board, all_moves + [move]
heappush(min_heap, board_obj)
# add the board to seen
seen.add(board)
# if the queue is empty it means all possible perms have been seen and none
# were solved. no solution, return -1
return None
# def display_solution(moves):
# for iteration, board in enumerate(moves):
# print(f'Move no. {iteration}')
# for row in board:
# print(f'\t{row}')
puzzle = (
(0, 2, 3),
(1, 4, 6),
(7, 5, 8)
)
puzzle = (
(4, 1, 0),
(2, 6, 3),
(7, 5, 8)
)
puzzle = (
(0, 8, 1),
(5, 4, 7),
(3, 2, 6)
)
puzzle = (
(7, 6, 8),
(2, 0, 1),
(3, 5, 4)
)
if __name__ == '__main__':
all_moves = solve(puzzle)
display_solution(puzzle, all_moves, 0.3)
|
class Node(object):
def __init__(self, value):
self.children = [None]*2
self.val = value
def getValue(self):
return self.val
def getLeft(self):
return self.children[0]
def getRight(self):
return self.children[1]
def setLeft(self, n):
self.children[0] = n
def setRight(self, n):
self.children[1] = n
class BinaryTree(object):
def __init__(self):
self.head = None
def Preorder(self):
nodes=[]
recurse=self.PreorderR(nodes,self.head)
return recurse
def PreorderR(self,nodes,curr):
if curr is None:
return
nodes.append(curr.getValue())
self.PreorderR(nodes,curr.getLeft())
self.PreorderR(nodes,curr.getRight())
return nodes
def Postorder(self):
nodes=[]
return self.PostorderR(nodes, self.head)
def PostorderR(self,nodes,curr):
if curr is None:
return
self.PostorderR(nodes,curr.getLeft())
self.PostorderR(nodes,curr.getRight())
nodes.append(curr.getValue())
return nodes
def inorder(self):
return self.inorderR([],self.head)
def inorderR(self,nodes,curr):
if curr is None:
return
self.inorderR(nodes,curr.getLeft())
nodes.append(curr.getValue())
self.inorderR(nodes,curr.getRight())
return nodes
def treeHeight(self):
return self.TreeHeight(self.head)
def TreeHeight(self, node):
if node is None:
return 0
return max(self.TreeHeight(node.getLeft()),self.TreeHeight(node.getRight()))+1
def Add(self, val):
if self.head == None:
self.head = Node(val)
else:
self.AddR(self.head, val)
def AddR(self, root, val):
if root is None:
return None
else:
current = root.getValue()
if val < current:
if root.getLeft() is None:
root.setLeft(Node(val))
else:
self.AddR(root.getLeft(), val)
if val > current:
if root.getRight() is None:
root.setRight(Node(val))
else:
self.AddR(root.getRight(), val)
def Find(self, val):
return self.FindR(self.head, val)
def FindR(self, root, val):
if root is None:
return None
else:
current = root.getValue()
if current == val:
return root
if current < val:
return self.FindR(root.getRight(), val)
elif current > val:
return self.FindR(root.getLeft(), val)
def Remove(self, val):
return self.RemoveR(self.head, val, None)
def RemoveR(self, root, val, parent):
if parent is None:
self.head = None
else:
current = root.getValue()
if current == val:
if current == parent.getLeft():
parent.setLeft(current.getLeft())
elif current == parent.getRight():
parent.setRight(current.getRight())
else:
if current < val:
self.RemoveR(current.getRight(), val, current)
elif current > val:
self.RemoveR(current.getLeft(), val, current)
|
#!/usr/bin/python
import RPi.GPIO as GPIO
import os # needed for system callback
import Queue
import time
SWITCH1 = 17
SWITCH2 = 27
LED1 = 22
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(27, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(22, GPIO.OUT)
## The Queue module provides a FIFO implementation suitable for multi-threaded programming.
eventQueue = Queue.Queue()
# Define function for button press
def SWITCH1(channel): eventQueue.put('SWITCH1')
def SWITCH2(channel): eventQueue.put('SWITCH2')
# Set the interrupt - call ledSwitch function on button press - set debounce
GPIO.add_event_detect(17, GPIO.FALLING, callback = SWITCH1, bouncetime = 250)
GPIO.add_event_detect(27, GPIO.FALLING, callback = SWITCH2, bouncetime = 250)
try:
while True:
try:
event = eventQueue.get(True, 0.1)
except Queue.Empty:
continue
if event == 'SWITCH1':
print "The SWITCH1 event is registered."
## The thing to note is that the result of GPIO.input() is a boolean value.
## If the input is high, it returns True and if the input is low, it returns False.
## There is no middle.
value = GPIO.input(LED1) ## Read input from port
if value == GPIO.HIGH: ## If port is released (True or 1)
GPIO.output(LED1, GPIO.LOW) ## Turn off
else: ## Else port is off
GPIO.output(LED1, GPIO.HIGH) ## Turn on
if event == 'SWITCH2':
print "The SWITCH2 event is registered."
except KeyboardInterrupt:
GPIO.cleanup()
|
inp = """ I'm sure that the shells are seashore shells.
So if she sells seashells on the seashore,
The shells that she sells are seashells I'm sure.
She sells seashells on the seashore;"""
#print(len(inp))
coni = inp.split("\n")
#print(coni)
length = []
for i in coni:
length.append(len(i))
justlen = max(length)
for j in coni:
print("{}".format(j).rjust(justlen-len(j)))
|
file_name = open('she.txt','r')
lines = file_name.readlines()
new = []
for l in lines:
new.append(l.split(" "))
sl = []
for i in range(len(new)):
for j in range(len(new[i])):
o = new[i].pop()
print(o)
new[i].insert(j,o)
print(new)
|
from pymysql import connect
import os
connection = connect(
host = os.getenv('MYSQL_HOST'),
user = os.getenv('MYSQL_USER'),
password = os.getenv('MYSQL_PASSWORD'),
db = os.getenv('MYSQL_DATABASE'),
charset = 'utf8mb4'
)
loop = 0
loop1 = 0
loop2 = 0
while loop == 0:
try:
menu = int(input("Enter 1 to create an account, 2 to deposit money, 3 to withdraw money, 4 to show your account details and 5 to exit: "))
if menu == 1:
name = input("Enter name: ")
password = input("Enter password: ")
try:
with connection.cursor() as cursor:
query = 'insert into account (name, password) values("' + name + '", "' + password +'");'
cursor.execute(query)
connection.commit()
finally:
pass
print("Thank you for creating your account with us.")
elif menu == 2:
while loop1 == 0:
try:
deposit = float(input("Enter amount of money to be deposited: "))
except ValueError:
print("Please enter a valid number.")
continue
while loop2 == 0:
sure = input("Are you sure?(Y/N)")
if sure == 'Y':
try:
with connection.cursor() as cursor:
query = 'insert into money (deposit) values("' + str(deposit) + '")'
cursor.execute(query)
connection.commit()
finally:
pass
print("Thank you. Your money has been deposited.")
break
elif sure == 'N':
break
else:
print("Please enter a valid response.")
continue
if sure == 'Y':
break
elif menu == 3:
while loop1 == 0:
try:
withdrawal = float(input("Enter amount of money to be withdrawn: "))
except ValueError:
print("Please enter a valid number.")
continue
while loop2 ==0:
sure = input("Are you sure?(Y/N)")
if sure == 'Y':
try:
with connection.cursor() as cursor:
query = 'insert into money (withdrawal) values("' + str(withdrawal) + '")'
cursor.execute(query)
connection.commit()
finally:
pass
print("Thank you. Your money has been withdrawn.")
break
elif sure == 'N':
break
else:
print("Please enter a valid response.")
continue
if sure == 'Y':
break
elif menu == 4:
print("Here are your account details: ")
try:
with connection.cursor() as cursor:
query = 'select * from account;'
cursor.execute(query)
result = cursor.fetchall()
print(result)
finally:
pass
elif menu == 5:
connection.close()
break
else:
print("Please enter a valid number.")
except ValueError:
print("Please enter a valid number.")
|
import itertools
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return itertools.chain.from_iterable(
itertools.combinations(s, r)
for r in range(len(s)+1)
)
def baseline(list_):
p = powerset(list_)
next(p)
return max(p, key=lambda s: -abs(sum(s)))
def sum0(list_):
if 0 in list_:
return [0]
p = itertools.groupby(sorted(list_), key=lambda x: x > 0)
negative = list(next(p)[1])
positive = list(next(p)[1])
# print(list(powerset(negative)))
# print(list(powerset(positive)))
# print(baseline([2, 3, 100, -99]))
# print(baseline([100, -89, -8, 11]))
print(sum0([2, 3, 100, -99]))
print(sum0([100, -89, -8, 11]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.