blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
545k
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
545k
|
---|---|---|---|---|---|---|
ef045cb0440d1fe1466a7fda39915e68db973872 | mwnickerson/python-crash-course | /chapter_9/cars_vers4.py | 930 | 4.1875 | 4 | # Cars version 4
# Chapter 9
# modifying an attributes vales through a method
class Car:
"""a simple attempt to simulate a car"""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""return a descriptive name of a car"""
long_name =f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""reads odometer"""
print(f"This car has {self.odometer_reading}")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value
"""
self.odometer_reading = mileage
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23)
my_new_car.read_odometer() |
7e79127380cc86a94a1c4c5e836b8e00158481dc | mwnickerson/python-crash-course | /chapter_7/pizza_toppings.py | 321 | 4.28125 | 4 | # pizza toppings
# chapter 7 exercise 4
# a conditional loop that prompts user to enter toppings
prompt ="\nWhat topping would you like on your pizza?"
message = ""
while message != 'quit':
message = input(prompt)
topping = message
if message != 'quit':
print(f"I will add {topping} to your pizza!") |
8b5ff94d3edf0eca7b35b1c67ea764816fe236aa | mwnickerson/python-crash-course | /chapter_6/cities.py | 623 | 4.125 | 4 | # Cities
# dictionaries inside of dictionaries
cities = {
'miami': {
'state': 'florida',
'sports team': 'hurricanes',
'attraction' : 'south beach'
},
'philadelphia': {
'state': 'pennsylvania',
'sports team': 'eagles',
'attraction': 'liberty bell'
},
'new york city': {
'state': 'new york',
'sports team': 'yankees',
'attraction': 'times square'
}
}
for city, city_info in cities.items():
print(f"\nCITY: {city.title()}")
state = city_info['state'].title()
sports_team = city_info['sports team'].title()
attraction = city_info['attraction'].title()
print(state)
print(sports_team)
print(attraction)
|
1520778db31a0b825694362dea70bd80327640d9 | mwnickerson/python-crash-course | /chapter_6/rivers.py | 605 | 4.5 | 4 | # a dictionary containing rivers and their country
# prints a sentence about each one
# prints river name and river country from a loop
rivers_0 = {
'nile' : 'egypt',
'amazon' : 'brazil',
'mississippi' : 'united states',
'yangtze' : 'china',
'rhine' : 'germany'
}
for river, country in rivers_0.items():
print(f"The {river.title()} river runs through {country.title()}")
print(f"\nThe rivers that I thought of:")
for river in rivers_0.keys():
print(river.title())
print(f"\nThe countries with rivers are:")
for country in rivers_0.values():
print(country.title())
|
beb9bfc94e248c1b718c2ce8f01610f1e3456460 | mwnickerson/python-crash-course | /chapter_12/keys/keys.py | 1,385 | 3.984375 | 4 | # Keys
# chapter 12 exercise 5
# takes a keydown event
# prints the event.key attribute
import sys
import pygame
from settings import Settings
class KeyConverter:
"""overall class to manage program assets and behavior"""
def __init__(self):
"""initialize the program and create the resources"""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode(
(self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Event.key Dictionary")
def run_program(self):
"""Starts the program loop"""
while True:
self._check_events()
self._update_screen()
def _check_events(self):
"""responds to keypresses and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
def _check_keydown_events(self, event):
"""Respond to keypresses"""
# show the key that was pressed
print(event.key)
if event.key == pygame.K_ESCAPE:
sys.exit()
def _update_screen(self):
self.screen.fill(self.settings.bg_color)
pygame.display.flip()
if __name__ == '__main__':
kc = KeyConverter()
kc.run_program() |
3fb67a13e7194cdddc76ed12ffc867579dec68f3 | mwnickerson/python-crash-course | /chapter_10/number_writer.py | 240 | 3.828125 | 4 | # Number Writer
# Chapter 10: Storing Data
# using json.dump() and json.load()
# stores a list in a json
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'jsons/numbers.json'
with open(filename, 'w') as f:
json.dump(numbers, f)
|
94b3e3fff962a1311e9e02f1f653ddc75bea9ebb | mwnickerson/python-crash-course | /chapter_5/voting.py | 126 | 3.9375 | 4 | # if statement voting programs
age = 19
if age >= 18:
print("You are able to vote!")
print("Have you registered to vote?")
|
cb948a45e656ffd376acf055c8c5e58d50251f2e | mwnickerson/python-crash-course | /chapter_3/guest_changes.py | 582 | 3.53125 | 4 | # one of the guests cant make it, program removes them and invites someone else
guest = ['alexander the great', 'genghis khan', 'kevin mitnick', 'J.R.R Tolkien', 'John F. Kennedy']
print(f"Unfortunately, {guest[4].title()} can't make it to the party.")
guest[4] = 'babe ruth'
print(f"Dear {guest[0].title()}, \nPlease join me for a great feast")
print(f"Dear {guest[1].title()}, \nCome talk of your conquests.")
print(f"Dear {guest[2].title()}, \nJoin us and tell your stories")
print(f"Dear {guest[3].title()}, \nCome and chronicle our feast.")
print(f"Dear {guest[4].title()}, \nJoin us for dinner, it will be a homerun!")
|
fea3809ec2bf488d0867160cf88fbd57d67f3e15 | mwnickerson/python-crash-course | /chapter_11/city_functions.py | 342 | 3.9375 | 4 | # City Functions
# Chapter 11 Exercise 2
# added a population function
def get_city_country(city, country, population=''):
"""Generate city country formatted"""
if population:
city_country = f"{city}, {country} - population {population}"
else:
city_country = f"{city}, {country}"
return city_country.title()
|
02d3bcd27304830c1c4b1c11ef10139b2f0dcaf9 | mwnickerson/python-crash-course | /chapter_10/greet_user.py | 212 | 3.703125 | 4 | # Greet User
# Chapter 10: Storing Data
# reading user generated data
import json
filename = 'jsons/username.json'
with open(filename) as f:
username = json.load(f)
print(f"Welcome back, {username}!")
|
22bdf928b3a3d79e5dccd1361536f8fb7f0136f1 | mwnickerson/python-crash-course | /chapter_5/voting_vers2.py | 218 | 4.25 | 4 | # if and else statement
age = 17
if age >= 18:
print("You are able to vote!")
print("Have you registered to vote?")
else:
print("Sorry you are too young to vote.")
print("Please register to vote as you turn 18!")
|
cbe4ce4d644fcda766dfd72b095879a5ca2d2590 | mwnickerson/python-crash-course | /chapter_7/counting.py | 147 | 3.796875 | 4 | # Counting
# chapter 7
# the while loop in action
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
|
acefd9c2e8ff40edf60320a9ea1b18b5477b0afb | mwnickerson/python-crash-course | /chapter_6/alien_vers5.py | 184 | 4.25 | 4 | # Modifying values in a dictionary
alien_0 = {'color': 'green'}
print(f"The alien is {alien_0['color']}.")
alien_0 = {'color' : 'yellow'}
print(f"The alien is {alien_0['color']}.")
|
a934663927b79f54e0169eea362ad4e85ac9cbdf | mwnickerson/python-crash-course | /chapter_8/cities.py | 333 | 4.09375 | 4 | # Cities
# Chapter 8 exercise 5
# a function that take name and city and retruns a statement
# has a default city and country
def describe_city(city='Miami', country='U.S.A'):
print(f"{city.title()} is in {country.title()}")
describe_city()
describe_city('paris','france')
describe_city('philadelphia')
describe_city('Austin')
|
d44d5e2f17ffcb2e7966299ded7d054d7d05de7b | mwnickerson/python-crash-course | /chapter_8/t_shirt_vers2.py | 473 | 3.96875 | 4 | # T-Shirt Version 2
# Chapter 8 exercise 4
# take size and message and returns a statement
# large is the default size
def make_shirt(shirt_size='large', shirt_message='I love python'):
"""Takes a shrit size and message and printsmessage"""
"""default size is large"""
print(f"The shirt is {shirt_size} and says {shirt_message}")
make_shirt()
make_shirt('medium')
make_shirt('small', 'SGFja1RoZVBsYW5ldA==' )
make_shirt(shirt_message='SGFja1RoZVBsYW5ldA==')
|
9c94f5cb44b8a60ad3e9fe66a58546b624b2739f | mwnickerson/python-crash-course | /chapter_5/videogame_condtional.py | 1,486 | 3.6875 | 4 | # a series of conditional tests regarding video games
video_game = 'elden ring'
print("Is the video game Elden Ring?")
print( video_game == 'elden ring')
print("Is the video game Call of Duty?")
print( video_game == 'Call of Duty')
good_game = 'parkitect'
print("\nIs the good video game parkitect?")
print(good_game == 'parkitect')
print("Is the good video game Escape from Tarkov?")
print(good_game == 'Escape from Tarkov')
bad_game = 'last of us'
print("\nIs the bad game fortnite?")
print(bad_game == 'fortnite')
print("Is the bad game last of us?")
print(bad_game == 'last of us')
strat_game = 'humankind'
print("\nIs the 4X game Age of Empires?")
print(strat_game == 'age of empires')
print("Is the 4x game humankind?")
print(strat_game == 'humankind')
board_game = 'monopoly'
print("\nIs the board game stratego?")
print(board_game == 'stratego')
print("Is the board game monopoly")
print(board_game == 'monopoly')
owned_games = ['parkitect', 'humankind', 'sea of thieves',\
'escape from tarkov']
sale_game = 'elden ring'
print(f"\n{sale_game.title()} is on sale!")
if sale_game not in owned_games:
print(f"You do not own {sale_game.title()},\
buy it now!")
if len(owned_games) >= 2:
print(f"\nMaybe you own too many games to play")
print(f"Do not buy {sale_game}")
sale_game2 = 'parkitect'
print(f"\n{sale_game2.title()} is on sale!")
print(f"Do you own {sale_game2}?")
if sale_game2 in owned_games:
print(f"You own {sale_game2.title()},\
do not buy it!")
|
6fcb027e818ed15791490d49ffcfd6ffc9b146d7 | mwnickerson/python-crash-course | /chapter_5/alien_colors3.py | 658 | 3.75 | 4 | # If, elif, else alien color scoring
#round 1
alien_color = 'red' # 15 point score
if alien_color == 'green':
print('You scored 5 points')
elif alien_color == 'yellow':
print('You scored 10 points')
else:
print('You scored 15 points')
# round 2
alien_color = 'yellow' # 10 point score
if alien_color == 'green':
print('You scored 5 points')
elif alien_color == 'yellow':
print('You scored 10 points')
else:
print('You scored 15 points')
# round 3
alien_color = 'green' # 15 point score
if alien_color == 'green':
print('You scored 5 points')
elif alien_color == 'yellow':
print('You scored 10 points')
else:
print('You scored 15 points')
|
0db4acabc7715624030d1d0a257a4ae90c2034c7 | hangnguyen81/HY-data-analysis-with-python | /part02-e09_rational/rational.py | 1,097 | 4.03125 | 4 | #!/usr/bin/env python3
class Rational(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"{self.x}/{self.y}"
def __mul__(num1, num2):
return Rational(num1.x*num2.x, num1.y*num2.y)
def __truediv__(num1, num2):
return Rational(num1.x*num2.y, num1.y*num2.x)
def __add__(num1, num2):
return Rational(num1.x*num2.y + num2.x*num1.y, num1.y*num2.y)
def __sub__(num1, num2):
return Rational(num1.x*num2.y - num2.x*num1.y, num1.y*num2.y)
def __eq__(num1, num2):
return num1.x == num2.x and num1.y == num2.y
def __gt__(num1, num2):
return num1.x*num2.y > num2.x*num1.y
def __lt__(num1, num2):
return num1.x*num2.y < num2.x*num1.y
def main():
r1=Rational(1,4)
r2=Rational(2,3)
print(r1)
print(r2)
print(r1*r2)
print(r1/r2)
print(r1+r2)
print(r1-r2)
print(Rational(1,2) == Rational(2,4))
print(Rational(1,2) > Rational(2,4))
print(Rational(1,2) < Rational(2,4))
if __name__ == "__main__":
main()
|
7393500c1f9e8b7d3e3ceafce7f4e923d9111ae1 | hangnguyen81/HY-data-analysis-with-python | /part02-e13_diamond/diamond.py | 703 | 4.3125 | 4 | #!/usr/bin/env python3
'''
Create a function diamond that returns a two dimensional integer array where the 1s form a diamond shape.
Rest of the numbers are 0. The function should get a parameter that tells the length of a side of the diamond.
Do this using the eye and concatenate functions of NumPy and array slicing.
'''
import numpy as np
from numpy.core.records import array
def diamond(n):
inital_array = np.eye(n, dtype=int)
half_diamond = np.concatenate((inital_array[::-1],inital_array[:,1:]), axis=1)
full_diamond = np.concatenate((half_diamond[:-1],half_diamond[::-1]), axis=0)
return full_diamond
def main():
print(diamond(4))
if __name__ == "__main__":
main()
|
13b2ad577d87bdb7efff93a084208f42f71a359b | hangnguyen81/HY-data-analysis-with-python | /part01-e06_triple_square/triple_square.py | 432 | 4.09375 | 4 | #!/usr/bin/env python3
def triple(x):
#multiplies its parameter by three
x = x*3
return x
def square(x):
#raises its parameter to the power of two
x = x**2
return x
def main():
for i in range(1,11):
t = triple(i)
s = square(i)
if s>t:
break
print('triple({})=={}'.format(i,t),'square({})=={}'.format(i,s))
if __name__ == "__main__":
main()
|
14f3fd6898259a53461de709e7dc409a28ba829f | hangnguyen81/HY-data-analysis-with-python | /part01-e07_areas_of_shapes/areas_of_shapes.py | 902 | 4.15625 | 4 | #!/usr/bin/env python3
import math
def main():
while 1:
chosen = input('Choose a shape (triangle, rectangle, circle):')
chosen = chosen.lower()
if chosen == '':
break
elif chosen == 'triangle':
b=int(input('Give base of the triangle:'))
h=int(input('Give height of the triangle:'))
area = (b * h)/2
print(f"The area is {area}")
elif chosen == 'rectangle':
w = int(input('Give width of the rectangle:'))
h = int(input('Give height of the rectangle'))
area = w * h
print(f"The area is {area}")
elif chosen == 'circle':
r = int(input('Give radius of the circle:'))
area = math.pi * r**2
print(f"The area is {area}")
else:
print('Unknown shape!')
if __name__ == "__main__":
main()
|
81cc900e00edcbc8992a0f73fc3332b1e007b7bf | Iain-Forbes/static_dynamic | /part_2_code/specs/card_game_tests.py | 743 | 3.828125 | 4 | import unittest
from src.card import Card
from src.card_game import CardGame
class TestCardGame(unittest.TestCase):
def setUp(self):
self.ace = Card("Spades", 1)
self.card = Card("Clubs", 3)
self.card1 = Card("Hearts", 10 )
self.hand = [self.ace, self.card, self.card1]
self.card_game = CardGame()
def test_check_for_ace(self):
self.assertTrue(self.card_game.check_for_ace(self.ace))
def test_check_highest_card(self):
self.highest_card = self.card_game.highest_card(self.card1, self.card)
self.assertEqual(self.highest_card.value, 10)
def test_total_cards(self):
self.assertEqual(self.card_game.cards_total(self.hand),"You have a total of 14")
|
554a21528be4e8dc0ecdd9635196766071c0e4a0 | Julian-Arturo/FundamentosTaller-JH | /EjercicioN9.py | 1,323 | 4.59375 | 5 | """Mostrar en pantalla el promedio
de un alumno que ha cursado 5 materias
(Español, Matemáticas, Economía, Programación, Ingles)"""
#Programa que calcula el promedio de un estudiantes que cursa 5 materias
print ("Programa que calcula el promedio de un estudiantes que cursa 5 materias")
matematicas = 45
español = 39
economía = 40
programación = 50
ingles = 50
Promedio = matematicas + español + economía + programación + ingles
Resultado = Promedio/5
print ("El promedio del estudiante es de: ",Resultado)
#Julian Hernandez
#Profe, el ejercicio no estuvo muy claro, no decia a que se le sacaba promedio,
# por que me di a la tarea de hacer dos ejercicio de este.
# Quitarle la comillas al segundo para ser ejecutado. Muchas gracias
"""
print ("Programa que calcula el promedio de un estudiantes que cursa 5 materias")
matematicas1=float(input("Ingrese la nota final de matematicas: "))
español1=float(input("Ingrese la nota final de español: "))
economía1=float(input("Ingrese la nota final de economía: "))
programación1=float(input("Ingrese la nota final de programación: "))
ingles1=float(input("Ingrese la nota final de ingles: "))
Promedio = matematicas1 + español1 + economía1 + programación1 + ingles1
Resultado = Promedio/5
print ("El promedio del estudiante es de: ",Resultado)"""
#Julian Hernandez .. |
a5df0217059401b9de8e2663b6034a7bb31bb220 | sage-kanishq/PythonFiles | /Advanced/Async/theory.py | 266 | 3.5 | 4 | class Employee:
def __init__(self,firstname,lastname):
self.firstname = firstname
self.lastname = lastname
self.email = firstname+"."+lastname+"@company.com"
def fullname(self):
return self.firstname+" "+self.lastname
|
dba05501c8942049adee9f14b93332c6c67147b2 | wangjiancheng-123/datascience | /数据分析/day01/demo06_stack.py | 360 | 3.5 | 4 | #demo06_stack.py 组合与拆分
import numpy as np
a = np.arange(1, 7).reshape(2, 3)
b = np.arange(7, 13).reshape(2, 3)
print(a)
print(b)
c = np.hstack((a, b))
print(c)
a, b = np.hsplit(c, 2)
print(a)
print(b)
c = np.vstack((a, b))
print(c)
a, b = np.vsplit(c, 2)
print(a)
print(b)
c = np.dstack((a, b))
print(c)
a, b = np.dsplit(c, 2)
print(a)
print(b)
|
6e41091d728a2a31ad0a425c5ce928aac4f6810a | saran1211/rev-num | /swapbit.py | 77 | 3.6875 | 4 | a=int(input('enter the num1'))
b=int(input('enter the num2'))
a^b
print(b,a)
|
c020ad42e860dfa378b7fde09f82f4867b71b3c2 | mari756h/The_unemployed_cells | /model/cnn.py | 4,129 | 3.625 | 4 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class TextCNN(nn.Module):
""" PyTorch implementation of a convolutional neural network for sentence classification [1].
Implementation is adapted from the following repository https://github.com/Shawn1993/cnn-text-classification-pytorch
Attributes
----------
num_embed: int
number of embeddings
dim_embed: int
dimension of embedding layer
num_class: int
number of classes
p_dropout: float
probability of dropout
in_channels: int
number of in channels
out_channels: int
number of out channels
kernel_sizes: list
sizes of kernels (filter)
strides: int
what stride to use
Methods
----------
load_embeddings(matrix, non_trainable)
load previously trained word embeddings
forward(x)
feed data through network
References
----------
1. Kim Y. Convolutional neural networks for sentence classification. arXiv Prepr arXiv14085882. 2014:1746–1751. https://arxiv.org/pdf/1408.5882.pdf
"""
def __init__(self, num_embed, dim_embed, num_class, p_dropout, in_channels, out_channels, kernel_sizes, strides):
super(TextCNN, self).__init__()
self.num_embed = num_embed #Vocab size, V
self.dim_embed = dim_embed # Emb dim, D
self.num_class = num_class # C
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_sizes = kernel_sizes
self.strides = strides
# embedding layer from skip-gram or cbow
self.embed = nn.Embedding(
num_embeddings=self.num_embed, embedding_dim=self.dim_embed)
# convolutional part of the neural network
# allows for the possibility of multiple filters
self.convs = nn.ModuleList([
nn.Conv2d(in_channels=self.in_channels,
out_channels=self.out_channels,
kernel_size=(self.kernel_sizes[i], self.dim_embed),
stride=self.strides)
for i in range(len(self.kernel_sizes))
])
# regularization
self.dropout = nn.Dropout(p=p_dropout)
# linear output layer
self.fc1 = nn.Linear(in_features=len(self.kernel_sizes)*self.out_channels, out_features=self.num_class)
def load_embeddings(self, matrix, trainable=False):
"""Load pretrained word embeddings to the embedding module
Inspired by the following blog post: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76
Attributes
----------
Matrix: array or tensor
pretrained word embedding matrix
non_trainable: boolean, default: False
do not train the embeddings if true
"""
self.embed.weight.data.copy_(matrix)
if not trainable:
self.embed.weight.requires_grad = False
def forward(self, x):
"""Run data through network.
Attributes
----------
x: tensor
input to network
Returns
----------
out: tensor
output of network
"""
# get embeddings
x = self.embed(x)
x = torch.unsqueeze(x, 1)
# # run x through the different filters
# xs = [F.relu(conv(x)).squeeze(3) for conv in self.convs]
# # max-over-time pooling
# xs = [F.max_pool1d(x, x.size(2)).squeeze(2) for x in xs]
xs = []
for conv in self.convs:
x2 = F.relu(conv(x))
x2 = torch.squeeze(x2, -1)
x2 = F.max_pool1d(x2, x2.size(2))
xs.append(x2)
# concatenate
out = torch.cat(xs, 2)
out = out.view(out.size(0), -1)
# dropout
out = self.dropout(out)
# and output linear layer
out = self.fc1(out)
return out
|
992707cb6fb0382334ec407204943e25577470e7 | lukeencinas/EjerciciosExtraPython | /Bucles.py | 95 | 3.65625 | 4 | contador = 10
while contador != 0:
print(contador)
contador -= 1
print("Lanzamiento")
|
040c7d6fa77e6a2677b713229a9db9cef7f93b83 | johnzhoudev/python-citations-helper | /citations/auto_table.py | 6,817 | 3.78125 | 4 | #! /opt/anaconda3/bin/python
import pyperclip
# Open file containing input and read
table_data_file = open('./table_data_file.txt', 'r')
table_data = table_data_file.readlines()
def append_heading_row(arr_words):
return_str = "\t\t<tr>\n\t\t\t"
for j in range(len(arr_words)):
arr_words[j] = arr_words[j].replace("°C", "℃")
for i in range (len(arr_words) - 1):
return_str += ("<th>" + arr_words[i].strip(' \n') + "</th>\n\t\t\t")
return_str += "<th>" + arr_words[(len(arr_words) - 1)].strip(' \n') + "</th>\n\t\t</tr>\n"
return return_str
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def append_data_row(arr_words):
return_str = "\t\t<tr>\n\t\t\t"
for j in range(len(arr_words)):
arr_words[j] = arr_words[j].replace("°C", "℃")
#Append first word, as 1 thing until number detected
i = 0
first_str = ""
while(not is_number(arr_words[i].strip(" \n"))):
first_str += (arr_words[i].strip(' \n') + " ")
i += 1
return_str += "<td>" + first_str.strip(' \n') + "</td>\n\t\t\t"
#append groups of 3 items as 1 elt, plus check for degree celsius
for j in range (i, len(arr_words) - 3, 3):
return_str += ("<td>" + arr_words[j].strip(' \n') + " " + arr_words[j + 1].strip(' \n') + " " + arr_words[j + 2].strip(' \n') + "</td>\n\t\t\t")
return_str += "<td>" + arr_words[len(arr_words) - 3].strip(' \n') + " " + arr_words[len(arr_words) - 2].strip(' \n') + " " + arr_words[len(arr_words) - 1].strip(' \n') + "</td>\n"
return_str += "\t\t</tr>\n"
return return_str
#For first line, generate the title with a colspan
first_row = table_data[0].split(" ")
first_line = ""
second_line = ""
for j in range(len(first_row)):
first_row[j] = first_row[j].replace("°C", "℃")
for i in range(len(first_row)):
if (first_row[i] == "Global"):
for j in range (i, len(first_row)):
second_line += (first_row[j] + " ")
second_line = second_line.strip(" \n")
first_line = first_line.strip(" \n")
break
else:
first_line += first_row[i] + " "
line1 = "<table class='wb-table table table-bordered'>\n\t<thead>\n\t\t<tr>\n\t\t\t<th>"
line1 += first_line
line1 += "</th>\n\t\t\t<th colspan='3'>"
line1 += second_line
line1 += "</th>\n\t\t</tr>\n"
line2 = append_heading_row(table_data[1].split(" "))
#Get all data
master_table_text = line1 + line2 + "\t</thead>\n\t<tbody>\n"
del table_data[0:2]
for line in table_data:
master_table_text += append_data_row(line.split(" "))
master_table_text += "\t</tbody>\n</table>\n"
print("copying")
pyperclip.copy(master_table_text)
table_data_file.close()
# <table class='wb-table table table-bordered'>
# <thead>
# <tr>
# <th>Change in Degree Days Below 18℃ [℃ days]</th>
# <th colspan='3'>Global warming level</th>
# </tr>
# <tr>
# <th>Region</th>
# <th>+1℃</th>
# <th>+2⅝</th>
# <th>+3⅝</th>
# </tr>
# </thead>
# <tbody>
# <tr>
# <td>British Columbia</td>
# <td>-403 (-447, -363)</td>
# <td>-757 (-808, -722)</td>
# <td>-1088 (-1128, -1057)</td>
# </tr>
# <tr>
# <td>Prairies</td>
# <td>-461 (-515, -428)</td>
# <td>-891 (-938, -845)</td>
# <td>-1274 (-1332, -1235)</td>
# </tr>
# <tr>
# <td>Ontario</td>
# <td>-424 (-461, -393)</td>
# <td>-781 (-820, -746)</td>
# <td>-1127 (-1178, -1068)</td>
# </tr>
# <tr>
# <td>Quebec</td>
# <td>-466 (-494, -430)</td>
# <td>-874 (-917, -825)</td>
# <td>-1252 (-1321, -1183)</td>
# </tr>
# <tr>
# <td>Atlantic</td>
# <td>-456 (-489, -420)</td>
# <td>-834 (-861, -795)</td>
# <td>-1194 (-1258, -1127)</td>
# </tr>
# <tr>
# <td>North</td>
# <td>-692 (-740, -629)</td>
# <td>-1328 (-1328, -1274)</td>
# <td>-1917 (-1947, -1835)</td>
# </tr>
# </tbody>
# <tfoot>
# <tr>
# <td>Canada</td>
# <td>-449 (-487, -411)</td>
# <td>-836 (-887, -794)</td>
# <td>-1196 (-1257, -1139)</td>
# </tr>
# </tfoot>
# </table>
# <p>
# <strong>Table 3.1</strong>: Projected changes in heating degree days below 18°C for locations approximating Table C-2 locations in six Canadian regions and Canada as a whole for +1°C, +2°C, and +3°C global warming levels with respect to the 1986-2016 baseline period. Values represent the ensemble projection (25th percentile, 75th percentile) calculated from bias corrected CanRCM4 LE simulations.
# </p>
def make_table_row():
print('nrd: new row data, nrh: new row heading, dr: done row, dt: done table')
while(True):
input_str = input('Command: ')
input_str = input_str.strip(' \n')
if (input_str == 'nrd'):
row_html = '<tr>\n'
while(True):
input_data = input('Data: ')
input_data = input_data.strip(' \n')
if (input_data == 'dr'):
break
else:
row_html = row_html + '\t<td>' + input_data + '</td>\n'
row_html += '</tr>\n'
print('copying row to clipboard')
pyperclip.copy(row_html)
elif (input_str == 'nrh'):
row_html = '<tr>\n'
while(True):
input_data = input('Heading: ')
input_data = input_data.strip(' \n')
if (input_data == 'dr'):
break
else:
row_html = row_html + '\t<th>' + input_data + '</th>\n'
row_html += '</tr>\n'
print('copying row to clipboard')
pyperclip.copy(row_html)
else:
print('exiting table constructor')
break
# Change in July 2.5% Dry Design Temp. [°C] Global warming level
# Region +1°C +2°C +3°C
# British Columbia 2.2 (1.8, 2.6) 4.2 (3.7, 4.8) 6.8 (6.2, 7.4)
# Prairies 2.3 (1.6, 2.7) 4.0 (3.4, 4.7) 6.0 (5.4, 6.5)
# Ontario 1.6 (1.3, 1.9) 3.0 (2.5, 3.4) 4.1 (3.8, 4.5)
# Quebec 1.4 (1.1, 1.7) 3.0 (2.7, 3.3) 4.1 (3.9, 4.5)
# Atlantic 1.3 (1.1, 1.6) 2.8 (2.6, 3.0) 4.1 (3.9, 4.4)
# North 1.7 (1.3, 2.2) 3.2 (2.7, 3.8) 4.7 (4.3, 5.3)
# Canada 1.6 (1.3, 1.9) 3.0 (2.7, 3.5) 4.3 (4.0, 4.6)
# Change in July 2.5% Wet Design Temp. [°C] Global warming level
# Region +1°C +2°C +3°C
# British Columbia 1.8 (1.5, 2.1) 3.5 (3.2, 3.8) 5.3 (5.0, 5.8)
# Prairies 1.8 (1.3, 2.0) 3.1 (2.8, 3.4) 4.6 (4.3, 4.9)
# Ontario 1.2 (1.0, 1.4) 2.3 (2.1, 2.6) 3.2 (3.1, 3.4)
# Quebec 1.1 (0.9, 1.4) 2.4 (2.2, 2.5) 3.3 (3.1, 3.5)
# Atlantic 1.3 (1.2, 1.4) 2.6 (2.4, 2.7) 3.8 (3.6, 3.9)
# North 1.6 (1.3, 1.9) 2.8 (2.5, 3.3) 4.3 (4.0, 4.8)
# Canada 1.3 (1.1, 1.5) 2.5 (2.2, 2.7) 3.6 (3.3, 3.8) |
980fc1829d7f099fdf1cdf3aa5050352fac455f4 | raphael-abrantes/exercises-python | /ex006.py | 141 | 3.84375 | 4 | x = int(input('Digite um valor: '))
print(f'O dobro de {x} é {2*x}\nO triplo de {x} é {3*x}\nA raíz quadrada de {x} é {x**(1/2):.2f}')
|
a97bf3bcc27ccbcbed0e6d8f66e202dbcddcceac | raphael-abrantes/exercises-python | /ex066.py | 222 | 3.671875 | 4 | soma = i = 0
while True:
num = int(input('Insira um valor [Digite 999 para parar!]: '))
if num == 999:
break
i = i + 1
soma = soma + num
print(f'A soma dos {i} valores digitados é {soma}')
|
dce0664a1145c05112586aad520ec2b1bd094884 | raphael-abrantes/exercises-python | /ex067.py | 291 | 3.890625 | 4 | print('Para encerrar, digite um valor negativo')
while True:
n = int(input('Quer a tabuada de qual valor? '))
if n < 0:
print('\nFim do programa!')
break
print('-' * 32)
for i in range(1, 11):
print(f'{n} x {i} = {n*i}')
print('-' * 32)
|
70cac53d7cccc7778a1f5edd7daa26a480d5b48a | raphael-abrantes/exercises-python | /ex065.py | 650 | 3.78125 | 4 | answer = 'S'
i = s = maior = menor = 0
while answer in 'YySs':
i = i + 1
n = int(input('Digite um valor: '))
answer = str(input('Deseja cotinuar [Y/N]? ')).upper().strip()[0]
if answer not in 'YySsNn':
while answer not in 'YySsNn':
answer = str(input('Opção inválida. Deseja cotinuar [Y/N]? ')).upper().strip()[0]
if i == 1:
maior = menor = n
else:
if n > maior:
maior = n
if n < menor:
menor = n
s = s + n
print(f'A média dos {i} valores digitados é {s/i:.2f}')
print(f'O menor valor digitado foi {menor} e o maior foi {maior}')
|
90b1968bdccb773d613e89043145608b84027dac | raphael-abrantes/exercises-python | /ex096.py | 249 | 3.625 | 4 | def area(larg, comp):
a = larg * comp
print('-='*15)
print(f'A area de um terreno {larg}x{comp} é = {a:.1f}m²')
print('Área de Terreno')
print('-'*20)
area(float(input('Largura (m): ')),
float(input('Comprimento (m): ')))
|
e40488d5e910c6af7f852a5087b48f8b87bf9c82 | raphael-abrantes/exercises-python | /ex086.py | 296 | 3.71875 | 4 | aMatriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(0, 3):
for j in range (0, 3):
aMatriz[i][j] = int(input(f'Digite um valor para [{i}, {j}]: '))
print('-'*32)
for i in range(0, 3):
for j in range(0, 3):
print(f'[{aMatriz[i][j]:^7}]', end='')
print()
|
3f201f40b3d5ddc8dec9c8665271cf5a0b0c5723 | raphael-abrantes/exercises-python | /ex007.py | 161 | 3.71875 | 4 | n1 = float(input('Digite sua primeira nota: '))
n2 = float(input('Digite sua segunda nota: '))
print(f'A média de {n1} e {n2} é igual a {(n1 + n2)/2:.2f}')
|
d6ec64b000ca85a21b982dd995597837b6a70972 | raphael-abrantes/exercises-python | /ex085.py | 360 | 3.53125 | 4 | n = [[], []]
vValor = 0
for i in range (1, 8):
vValor = int(input(f'Digite o {i}° valor: '))
if vValor % 2 == 0:
n[0].append(vValor)
else:
n[1].append(vValor)
n[0].sort()
n[1].sort()
print('-'*50)
print(f'Todos os valores: {n}')
print(f'Os valores pares são: {n[0]}')
print(f'Os valores impares são: {n[1]}')
|
3dd0f77e6d97d184cb22c0be364c8e3197138088 | raphael-abrantes/exercises-python | /ex012.py | 116 | 3.59375 | 4 | preco = float(input('Qual o preço do produto? '))
print(f'O produto com 5% de desconto vale R${preco*0.95:.2f}')
|
dcb25dddc2d849f6d545c93328cc9ee2cb502d79 | raphael-abrantes/exercises-python | /ex016.py | 168 | 3.671875 | 4 | from math import trunc
#import math || from math import trunc
x = float(input('Digite um número Real: '))
print(f'A parcela inteira do número {x} é {trunc(x)}')
|
5633cff71b6fdfb99308df89b1be3fea2ad2c5ff | raphael-abrantes/exercises-python | /ex033.py | 454 | 4.0625 | 4 | n1 = int(input('Insira um valor: '))
n2 = int(input('Insira outro valor: '))
n3 = int(input('Insira o último valor: '))
menor = n1
maior = n1
#Verifica o menor
if n2 < n1 and n2 < n3:
menor = n2
elif n3 < n1 and n3 < n2:
menor = n3
#Verifica o maior
if n2 > n1 and n2 > n3:
maior = n2
elif n3 > n1 and n3 > n2:
maior = n3
print (f'O menor valor inserido foi: {menor}')
print (f'O maior valor inserido foi: {maior}')
|
9850e5de361b1f208eda6e0779e9db33ed8db7fb | raphael-abrantes/exercises-python | /ex008.py | 350 | 3.90625 | 4 | medida = float(input('Digite um valor em metros: '))
print(f'Para o valor de {medida}m, têm-se as seguintes conversões: ')
print('='*56)
print(f'{medida/1000:.2f}km')
print(f'{medida/100:.2f}hm')
print(f'{medida/10:.2f}dam')
print(f'{medida*1:.2f}m')
print(f'{medida*10:.2f}dm')
print(f'{medida*100:.2f}cm')
print(f'{medida*1000:.2f}mm')
|
ae386e8a7a2c0fa4d4178a374c08b0d2faa09468 | TimothyPolizzi/CMPT435 | /Assignments/AssignmentTwo/HashTable.py | 5,099 | 4.46875 | 4 | # An implementation of a hash table for CMPT435.
__author__ = 'Tim Polizzi'
__email__ = '[email protected]'
from typing import List
class HashTable(object):
"""Creates a table with quick insertion and removal using a calculated value.
Calculates a hash value for every item added to the table. The hash value determines where the item is inserted into
the list, and allows a large amount of items to be inserted with relative ease into a smaller list. If any insertion
would cause two items to go into the same place in the list, take the item already in the list and link it to the
new item.
"""
class __HashTableItem(object):
"""Creates an item for inside the hash table.
An item to store things in the hash table.
"""
def __init__(self, value: str):
self.val = value
self.next = None
def __init__(self):
self.table_size = 250
self.internal_table = [None] * self.table_size
self.size = 0
self.comparisons = 0
def insert(self, to_add: str):
"""Adds an item to the hash table.
Takes the given string to_add and calculates its hash value to add it to the table. If the hash value is already
taken by another item, sets the previous item to have a pointer to the new item.
Args:
to_add(str): The string value that is to be added to the hash table.
"""
hash_val = self.calculate_hash(to_add)
if self.internal_table[hash_val] is None:
self.internal_table[hash_val] = self.__HashTableItem(to_add)
else:
current_chain = self.internal_table[hash_val]
while current_chain.next is not None and current_chain.val is not to_add:
current_chain = current_chain.next
current_chain.next = self.__HashTableItem(to_add)
self.size = self.size + 1
def remove(self, to_remove: str) -> str:
"""Removes a item from the hash table.
Removes a given string item from the hash table.
Args:
to_remove(str): The item that is to be removed from the hash table.
Returns:
The string that is removed from the hash table.
"""
self.comparisons = 0
self.comparisons = self.comparisons + 1
hash_val = self.calculate_hash(to_remove)
to_return = None
if self.internal_table[hash_val] is not None:
previous = None
current = self.internal_table[hash_val]
while current.next is not None and current.val is not to_remove:
self.comparisons = self.comparisons + 1
previous = current
current = current.next
if current.val is to_remove:
self.comparisons = self.comparisons + 1
if previous is None:
to_return = current
self.internal_table[hash_val] = current.next
else:
to_return = current
previous.next = current.next
print(self.comparisons)
return to_return
def get_list(self, to_find: int) -> List[str]:
"""Gets the internal list of items at a given hash value.
Gets the list of items at the hash value specified.
Args:
to_find(int): The integer hash value of the position in the hash table that you are trying to find.
Returns:
The list of items stored at that hash value.
"""
current = self.internal_table[to_find]
return_list = None
if current is not None:
return_list = [current.val]
while current.next is not None:
current = current.next
return_list.append(current.val)
return return_list
def empty(self):
"""Cleans out the hash table of all values.
Completely empties the hash table.
"""
self.internal_table = []
def calculate_hash(self, to_calculate: str) -> int:
"""Calculate the hash value for a string.
Calculates the specific hash value for a string in this hash table.
Args:
to_calculate(str): The string who's hash value needs to be calculated.
Returns:
The integer hash value of to_calculate for this hash table.
"""
to_calculate = to_calculate.upper()
letter_total = 0
# Iterate over all letters in the string, totalling their ASCII values.
for i in to_calculate:
this_value = ord(i)
letter_total = letter_total + this_value
# Test: print the char and the hash.
# (if you're using pycharm, command + / can comment out highlighted sections)
# print(" [")
# print(i)
# print(this_value)
# print("] ")
# Scale letter_total to fit in table_size.
hash_code = (letter_total * 1) % self.table_size
# TODO: Experiment with letterTotal * 2, 3, 5, 50, etc.
return hash_code
|
77a523e48e004fe5885af5d61916c4066f44f096 | TimothyPolizzi/CMPT435 | /Assignments/AssignmentThree/LinkedGraph.py | 4,209 | 4.25 | 4 | # A graph made of linked objects for Alan's CMPT435.
__author__ = 'Tim Polizzi'
__email__ = '[email protected]'
from typing import List
class LinkedGraph(object):
class __Node(object):
""" An internal Node for the Linked Object model of the Graph
"""
def __init__(self, set_id, *init_value):
if 2 > len(init_value) > 0:
self.value = init_value
else:
self.value = None
self.connected_nodes = []
self.id = set_id
def connect(self, node):
self.connected_nodes.append(node)
def set_value(self, value: int):
self.value = value
def __init__(self):
self.vertex_list = []
def add_vertex(self, to_add):
""" Adds a vertex to the graph.
Args:
to_add: The value of the vertex to add.
Returns:
A boolean value that returns True if it worked, False otherwise.
"""
to_return = True
self.vertex_list.append(self.__Node(len(self.vertex_list), to_add))
return to_return
def find_node(self, to_find) -> __Node:
""" Finds a node in the graph based on it's value.
Args:
to_find: The integer value of the node that is being searched for.
Returns:
The node who's value corresponds to the integer value queried, or None if the node could not be found.
"""
to_return = None
for node in self.vertex_list:
if node.value[0] is to_find:
to_return = node
return to_return
def add_edge(self, vertex_1, vertex_2):
""" Adds an edge between two vertices to the graph.
Args:
vertex_1: The first vertex to be connected.
vertex_2: The second vertex to be connected.
Returns:
A boolean value that is True if the edge is created, False otherwise.
"""
to_return = True
temp1 = self.find_node(vertex_1)
temp2 = self.find_node(vertex_2)
temp1.connected_nodes.append(temp2)
temp2.connected_nodes.append(temp1)
return to_return
def breadth_first_traversal(self, start: int):
""" A breadth first traversal through the graph.
A way to traverse the graph, by moving from one node to all adjacent nodes, before moving on to do the process
again.
Args:
start: The node to start the traversal on.
Returns:
The list of traversed nodes in breadth first order.
"""
visited = [False] * len(self.vertex_list)
begin = self.find_node(start)
queue = [begin]
visited[begin.id] = True
traverse_list = [begin]
while queue:
begin = queue.pop(0)
print(begin.value[0], end=" ")
for i in begin.connected_nodes:
if not visited[i.id]:
queue.append(i)
visited[i.id] = True
traverse_list.append(i)
print()
return traverse_list
def depth_first_traversal(self, start: int):
""" A depth first traversal through the graph.
A way to traverse the graph, by moving from one node to the next child node, until there are no further children
when it goes back up a step to continue in the other direction for child nodes.
Args:
start: The index of the node to start the traversal on.
Returns:
The list of items that have been traversed.
"""
visited = [False] * len(self.vertex_list)
traverse_list = []
self.__depth_first_traversal_helper(start - 1, visited, traverse_list)
print()
return traverse_list
def __depth_first_traversal_helper(self, start: int, visited: List[bool], traverse_list: List[int]):
visited[start-1] = True
traverse_list.append(start)
print(start + 1, end=" ")
start_node = self.vertex_list[start]
for i in start_node.connected_nodes:
if not visited[i.id - 1]:
self.__depth_first_traversal_helper(i.id, visited, traverse_list)
|
c0152d8c48c1b81c2e2fc72e12d200c60f90b3b9 | keerthisreedeep/LuminarPythonNOV | /Flow_controls/all prime no between low limit to upper limit.py | 378 | 3.828125 | 4 | # print all prime nos between lower limit to upper limit
low = int(input("enter the lower limit"))
upp = int(input("enter the upper limit"))
for Number in range (low, (upp+1)):
flag = 0
for i in range(2, (Number // 2 + 1)):
if (Number % i == 0):
flag = flag + 1
break
if (flag == 0 and Number != 1):
print( Number, end=' ')
|
bc54b72db672fdc80f71246a06f295a97c9efa18 | keerthisreedeep/LuminarPythonNOV | /Flow_controls/temp.py | 126 | 3.875 | 4 | temperature=int(input("enter the current temperature"))
if(temperature>30):
print("hot here")
else:
print("cool here") |
a97aa88d77825b5b9425c336aab72cd67b424b7e | keerthisreedeep/LuminarPythonNOV | /Flow_controls/sum_of_cubes of a number.py | 133 | 3.96875 | 4 | num=int(input("enter a number"))
result=0
while(num!=0):
temp=num%10
result=(result)+(temp**3)
num=num//10
print(result)
|
f86510558d0e668d9fc15fd0a3ff277ac93ec656 | keerthisreedeep/LuminarPythonNOV | /Functionsandmodules/function pgm one.py | 1,125 | 4.46875 | 4 | #function
#functions are used to perform a specific task
print() # print msg int the console
input() # to read value through console
int() # type cast to int
# user defined function
# syntax
# def functionname(arg1,arg2,arg3,.................argn):
# function defnition
#---------------------------------------------------------
# function for adding two numbers
def add(n1,n2):
res=n1+n2
print(res)
#calling function by using function name
add(50,60)
#------------------------------------------------------
# function for subtracting two numbers
def sub(n1,n2):
res=n1-n2
print(res)
#calling function by using function name
sub(50,60)
#--------------------------------------------------------
# function for multiply two numbers
def mul(n1,n2):
res=n1*n2
print(product)
#calling function by using function name
product(50,60)
#--------------------------------------------------------
# function for divide two numbers
def div(n1,n2):
res=n1/n2
print(quotioent)
#calling function by using function name
quotient(50,60)
#--------------------------------------------------------- |
c633e32b95ff636fd81833377687758e712d33a5 | keerthisreedeep/LuminarPythonNOV | /Flow_controls/pgm_to_check_prime no.py | 250 | 4.09375 | 4 | number=int(input("enter a number"))
flag=0
for i in range(2,number):
if(number%i==0):
flag=1
break
else:
flag=0
if(flag>0):
print("number is not a prime number")
else:
print("number is prime number")
|
ea9ce7533e3f40c0078f83d82f40fa98fd915417 | keerthisreedeep/LuminarPythonNOV | /List_demo/pairs.py | 670 | 3.609375 | 4 | #lst=[1,2,3,4] #6 (2,4) , #7 (3,4)
# lst=[1,2,3,4]
# pair = input("enter the element ")
# for item in lst:
#
# for i in lst:
# sum=0
# if(item!=i):
# sum=item+i
# if(pair==sum):
# print(item,',',i)
# break
#------------------------------------------------------
lst=[1,2,3,4] #7 (3,4)
element=int(input("enter element"))
lst.sort()
low=0
upp=len(lst)-1
while(low<upp):
total=lst[low]+lst[upp]
if(total==element):
print("pairs",lst[low],",",lst[upp])
break
elif(total>element):
upp=upp-1
elif(total<element):
low+=1
|
e6a1ca5bfc03dd172f80ee3f24acc9d128db8588 | lenamv/Car_Price_Prediction | /feature_transformation.py | 3,961 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
from sklearn.base import TransformerMixin, BaseEstimator
import pandas as pd
import numpy as np
# Create a class to perform feature engineering
class FeatureEngineering(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
return self
def transform(self, X, y=None):
df = X
# Convert boolean values to integer
df['engine_has_gas']=df['engine_has_gas'].astype(int)
df['has_warranty']=df['has_warranty'].astype(int)
# Create a feature that represents mileage per year
df['odometer_value']=df['odometer_value'].apply(lambda x: round(x, -2))
df['odometer_value/year'] = round(df['odometer_value']/(2020 - df['year_produced']),-2)
# Create a feature how old is a car
df['year'] = 2020 - df['year_produced']
################################# Reduce a number of categories ######################################
# Combine manufacturer and model names
df['name'] = df['manufacturer_name'].apply(lambda x: x.strip()) + ' ' + df['model_name'].apply(lambda x: x.strip())
# Reduce the number of car model names
# Set a limit of rare car occurrence
car_total = 10
# Count a number of car names and convert the result to a dataframe
car_models = pd.DataFrame(df['manufacturer_name'].value_counts())
# Get a list of rare car names
car_models_list = car_models[car_models['manufacturer_name'] < car_total].index
# create a new category'other' for rare car model names
df['manufacturer_name'] = df['manufacturer_name'].apply(lambda x: 'other' if x in car_models_list else x)
# Reduce the number of car model names
# Set a limit of rare car occurrence
car_total = 10
# Count a number of car names and convert the result to a dataframe
car_models = pd.DataFrame(df['model_name'].value_counts())
# Get a list of rare car names
car_models_list = car_models[car_models['model_name'] < car_total].index
# create a new category'other' for rare car model names
df['model_name'] = df['model_name'].apply(lambda x: 'other' if x in car_models_list else x)
"""
# Reduce the number of car model names
# Set a limit of rare car occurrence
car_total = 20
# Count a number of car names and convert the result to a dataframe
car_models = pd.DataFrame(df['name'].value_counts())
# Get a list of rare car names
car_models_list = car_models[car_models['name'] < car_total].index
# create a new category'other' for rare car model names
df['name'] = df['name'].apply(lambda x: 'other' if x in car_models_list else x)
# Reduce the number of colors
df['color']=df['color'].replace({'violet':'other','yellow':'other','orange':'other', 'brown':'other'})
# Reduce the number of body tipes
df['body_type']=df['body_type'].replace({'pickup':'other','cabriolet':'other','limousine':'other'})
# Add 'hybrid-diesel' to 'diesel' category
df['engine_fuel']=df['engine_fuel'].replace({'hybrid-diesel':'diesel'})
"""
################################# End Reduce a number of categories ######################################
# Create a list of unnamed features
features_list = ['feature_0','feature_1', 'feature_2', 'feature_3', 'feature_4', 'feature_5', 'feature_6', 'feature_7', 'feature_8', 'feature_9']
for feature in features_list:
df[feature]=df[feature].astype(int)
# Count a total number of unnamed features for a car
df['other_features']=df[features_list].sum(axis=1).astype(int)
global feats
feats = ['name', 'odometer_value/year', 'year', 'other_features']
X=df
return X
|
5ca2fa162d8fb0045e3677fdb92199fa0b453365 | dariagus/Homework | /task_02_01.py | 154 | 3.96875 | 4 | def is_palindrome(x):
x = str(x)
x = x.lower()
x = x.replace(' ', '')
if x == x[::-1]:
return True
else:
return False
|
550f9940e0d3646142ce07babd0cd9eff743ea7e | Venka97/Python-programs-15IT322E | /Prog 2.py | 133 | 3.8125 | 4 | def fact(x):
if x == 0:
return 1
else:
return x * fact(x - 1)
x = int(input())
print(fact(x),sep='',end='') |
0f9c55296b28a4cf6530a4e55921ffa02527961b | Venka97/Python-programs-15IT322E | /Ex 1.py | 207 | 3.53125 | 4 | z = [int(x) for x in input().split()]
def bubble(a):
for i in len((a - 1):
if a[i] > a[i+1]:
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
print (a)
bubble(z) |
9af8a5a49a6878545c60df7b679b9f6b87ba9145 | vivek4svan/adventofcode2016 | /day_02_02.py | 1,271 | 3.53125 | 4 | # Day 2: Bathroom Security
# Part 2
def get_security_digit(code_line, i, j):
print line.strip()
for char in code_line:
if char == "R" and lock_panel[i][j+1] != "0":
j += 1
elif char == "L" and lock_panel[i][j-1] != "0":
j -= 1
elif char == "U" and lock_panel[i-1][j] != "0":
i -= 1
elif char == "D" and lock_panel[i+1][j] != "0":
i += 1
return [i, j]
def create_lock_panel(size):
lock_panel.append(["0", "0", "0", "0", "0", "0", "0"])
lock_panel.append(["0", "0", "0", "1", "0", "0", "0"])
lock_panel.append(["0", "0", "2", "3", "4", "0", "0"])
lock_panel.append(["0", "5", "6", "7", "8", "9", "0"])
lock_panel.append(["0", "0", "A", "B", "C", "0", "0"])
lock_panel.append(["0", "0", "0", "D", "0", "0", "0"])
lock_panel.append(["0", "0", "0", "0", "0", "0", "0"])
lock_panel = []
with open("day_02_01.txt") as f:
i_pos = 3
j_pos = 1
lock_panel_size = 3
create_lock_panel(lock_panel_size)
for line in f:
new_security_digit = get_security_digit(line.strip(), i_pos, j_pos)
i_pos = new_security_digit[0]
j_pos = new_security_digit[1]
print "Security Code Digit : " + str(lock_panel[i_pos][j_pos])
|
148b2404d2b3736a91e5a46a63fb43f69e175d69 | sethgoolsby/Lab03-sethgoolsby | /tcp_client.py | 1,077 | 3.765625 | 4 | """
Server receiver buffer is char[256]
If correct, the server will send a message back to you saying "I got your message"
Write your socket client code here in python
Establish a socket connection -> send a short message -> get a message back -> ternimate
use python "input->" function, enter a line of a few letters, such as "abcd"
Developer: Seth Goolsby
Student ID: 8504036914
GitHub Repository Link: https://github.com/sethgoolsby/Lab03-sethgoolsby.git
"""
import socket
def main():
HOST = '18.191.85.112'
PORT = 5005
# TODO: Create a socket and connect it to the server at the designated IP and port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as mySocket:
mySocket.connect((HOST,PORT))
# TODO: Get user input and send it to the server using your TCP socket
userData = bytes(input("Enter what you want to send to the server"), 'utf-8')
mySocket.sendall(userData)
# TODO: Receive a response from the server and close the TCP connection
serverData = mySocket.recv(1024)
print("Recieved",repr(serverData))
if __name__ == '__main__':
main()
|
a68904d3ec21021c485dea62a89588bd8bb68078 | eomcaleb/RateMyStocks | /.problems/strategy_tammy.py | 2,834 | 3.6875 | 4 | from os import close
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
def main():
#-----------------------------------
#1 - Get basic stock pricing on day-to-day basis
#-----------------------------------
startdate = dt.datetime(2021,1,1)
enddate = dt.datetime(2021,7,1)
df = web.DataReader('VIPS', 'yahoo', startdate, enddate)
df.reset_index(inplace=True,drop=False)
df['Date']
# Print first couple data entries to make sure data is correct
print(df.head())
# 1a - Save to CSV
#df.to_csv('tesla.csv', )
# Read from CSV
#df = pd.read_csv('tesla.csv')
print(df)
# 1b - Find Average
#Print average for 'High' column
print(df["High"].mean())
#Print average for 'Low' column using dot notation
print(df.Low.mean())
#Print mean of multiple columns
print(df[["Open", "Close"]].mean())
#General description of dataframe
print(df.describe())
#-----------------------------------
# 3
# Tammy's circumstances:
# - She has $12,000 worth of money to be invested
# - Only invests $1,000 if and only if the stock drops 5% from previous day
# How much is her investment worth at the end of 2020?
#-----------------------------------
#Tammy's initial savings
savingsTammy = 12000
#Number to be updated later
updateSavings = 0
#The amount Tammy will invest each time
invAmt = 1000
#array to hold the values for the times Tammy invested in TSLA stock
tslaValue = []
#Total amount she has at the end of 2020
resultTammy = 0
#how much TSLA stock is worth on the last day of 2020
lastDayVal = closeCol[len(closeCol)-1]
#loop through, starting from the second day --> need to be able to look at the day before in order to calculate a percent diff
for i in range(1,len(openCol)):
#if the percent gain is less than or equal to -5%
if((openCol[i] - closeCol[i-1])/closeCol[i-1] <= -0.05):
#add the value of the TSLA at that moment to our array
tslaValue.append(openCol[i])
#reduce how much Tammy has in her savings
savingsTammy = savingsTammy - invAmt
#add to variable how much has been invested so far
updateSavings += invAmt
#if her savings amount reaches 0, break from the loop
if(savingsTammy == 0):
break
#calculate how much each seperate investment has grown and add to the total
for val in tslaValue:
resultTammy += (lastDayVal - val)*invAmt/val
#add how much Tammy has invested to reflect proper amount in her account
resultTammy += updateSavings
print("Tammy's initial investment grew to ${:,.2f}".format(resultTammy))
if __name__ == "__main__":
main() |
89b5ceeca6934f590d58043ac74aa3b210a976c9 | charlie447/tech_development_interview | /data_structure_and_algorithm/scripts/tree.py | 13,959 | 3.953125 | 4 | import functools
import collections
def is_empty_tree(func):
@functools.wraps(func)
def wrapper(self):
if not self.root or self.root.data is None:
return []
else:
return func(self)
return wrapper
class Node(object):
def __init__(self, data=None, key=None, value=None, left_child=None, right_child=None) -> None:
self.data = data
self.left_child = left_child
self.right_child = right_child
# used in AVL
self.depth = 0
self.parent = None
# bs as Balance Factor
self.bf = 0
self.key = key
self.value = value
# for leetcode
self.left = None
self.right = None
self.val = data
def bst_insert(self, data):
if self.data is None:
self.data = data
return
if data < self.data:
if self.left_child is None:
self.left_child = Node(data)
else:
# recursive
self.left_child.bst_insert(data)
else:
if self.right_child is None:
self.right_child = Node(data)
else:
self.right_child.bst_insert(data)
def depth(child_tree: Node):
if not child_tree:
return 0
return 1 + max(depth(child_tree.left_child), depth(child_tree.right_child))
def node_bf(child_tree: Node):
if not child_tree or not child_tree.data:
return 0
bf = abs(depth(child_tree.left_child) - depth(child_tree.right_child))
return bf
def is_balance(child_tree: Node):
# O(N^2)
bf = node_bf(child_tree)
if bf > 1:
return False
else:
return is_balance(child_tree.left_child) and is_balance(child_tree.right_child)
class BinaryTree(object):
def __init__(self, node=None) -> None:
self.root = node
def add(self, item):
node = Node(item)
# if the current tree is a empty tree
if not self.root or self.root.data is None:
self.root = node
else:
# add nodes by left to right
node_queue = []
node_queue.append(self.root)
while True:
current_node = node_queue.pop(0)
if current_node.data is None:
# placeholder for root.
continue
if not current_node.left_child:
# add a left child
current_node.left_child = node
return
elif not current_node.right_child:
current_node.right_child = node
return
else:
node_queue.append(current_node.left_child)
node_queue.append(current_node.right_child)
@is_empty_tree
def floor_travel(self):
# BFS Broad first
tmp_queue = []
return_queue = []
tmp_queue.append(self.root)
while tmp_queue:
current_node = tmp_queue.pop(0)
return_queue.append(current_node)
if current_node.left_child:
tmp_queue.append(current_node.left_child)
if current_node.right_child:
tmp_queue.append(current_node.right_child)
return return_queue
@is_empty_tree
def levelOrderBottom(self):
# leetcode 107
if not self.root:
return []
level_list = []
stack = collections.deque([self.root])
while stack:
level = list()
for _ in range(len(stack)):
node = stack.popleft()
level.append(node.data)
if node.left_child:
stack.append(node.left_child)
if node.right_child:
stack.append(node.right_child)
level_list.append(level)
return level_list[::-1]
@is_empty_tree
def front_travel(self):
'''
Using stack, which is a better way than using loop
root -> left -> right
'''
stack = []
queue = []
stack.append(self.root)
while stack:
current_node = stack.pop()
queue.append(current_node)
# The differences to BFS
if current_node.right_child:
stack.append(current_node.right_child)
if current_node.left_child:
stack.append(current_node.left_child)
return queue
def front_travel_with_loop_1(self, root):
if root == None:
return []
print(root.data, end=' ')
self.front_travel_with_loop_1(root.left_child)
self.front_travel_with_loop_1(root.right_child)
@is_empty_tree
def front_travel_with_loop_2(self):
queue = []
def loop(root):
if not root:
return
queue.append(root)
loop(root.left_child)
loop(root.right_child)
loop(self.root)
return queue
@is_empty_tree
def middle_travel(self):
'''
left -> root -> right
'''
stack = []
queue = []
tmp_list = []
stack.append(self.root)
while stack:
current_node = stack.pop()
if current_node.right_child and current_node.right_child not in stack:
stack.append(current_node.right_child)
if current_node.left_child:
if current_node not in tmp_list:
tmp_list.append(current_node)
stack.append(current_node)
else:
tmp_list.remove(current_node)
queue.append(current_node)
continue
stack.append(current_node.left_child)
else:
queue.append(current_node)
return queue
@is_empty_tree
def back_travel(self):
'''
left -> right -> root
'''
stack = []
queue = []
tmp_list = []
stack.append(self.root)
while stack:
current_node = stack[-1]
if current_node.right_child and current_node not in tmp_list:
stack.append(current_node.right_child)
if current_node.left_child and current_node not in tmp_list:
stack.append(current_node.left_child)
if current_node in tmp_list or (current_node.left_child is None and current_node.right_child is None):
queue.append(stack.pop())
if current_node in tmp_list:
tmp_list.remove(current_node)
tmp_list.append(current_node)
return queue
def depth(self, child_root):
if not child_root:
return 0
return 1 + max(self.depth(child_root.left_child), self.depth(child_root.right_child))
class BalancedBinaryTree(object):
def __init__(self, node=None) -> None:
self.root = node
def add(self, **item):
"""插入数据
1 寻找插入点,并记录下距离该插入点的最小非平衡子树及其父子树
2 修改最小非平衡子树到插入点的bf
3 进行调整
Args:
item (any): the data of a node
"""
node = Node(**item)
if self.root is None or self.root.data is None:
self.root = node
return
# the least unbalanced node
non_balance_node = self.root
insert_to_node = self.root
non_balance_node_parent = None
insert_node_parent = None
while insert_to_node:
if node.data == insert_to_node.data:
return
# if the insertion node is non-balanced
if insert_to_node.bf != 0:
non_balance_node_parent, non_balance_node = insert_node_parent, insert_to_node
insert_node_parent = insert_to_node
if node.data > insert_to_node.data:
insert_to_node = insert_to_node.right_child
else:
insert_to_node = insert_to_node.left_child
# loop until the insert_to_node is None,
# which means that the final insertion position has been found.
if node.data > insert_node_parent.data:
# insert to the right
insert_node_parent.right_child = node
else:
insert_node_parent.left_child = node
# update bf
tmp_non_balance = non_balance_node
while tmp_non_balance:
if node.data == tmp_non_balance.data:
break
if node.data > tmp_non_balance.data:
tmp_non_balance.bf -= 1
tmp_non_balance = tmp_non_balance.right_child
else:
tmp_non_balance.bf += 1
tmp_non_balance = tmp_non_balance.left_child
# get what side of non_balance_node that the the new point inserted to.
# True repr the left, False repr the right.
if non_balance_node.data > node.data:
insert_position = non_balance_node.left_child.data > node.data
else:
insert_position = non_balance_node.right_child.data > node.data
# Rotate to maintain balance
if non_balance_node.bf > 1:
if insert_position:
non_balance_node = BalancedBinaryTree.right_rotate(non_balance_node)
else:
non_balance_node = BalancedBinaryTree.right_left_rotate(non_balance_node)
elif non_balance_node.bf < -1:
if insert_position:
non_balance_node = BalancedBinaryTree.left_right_rotate(non_balance_node)
else:
non_balance_node = BalancedBinaryTree.left_rotate(non_balance_node)
# assign the non_balance_node to the parent or root which depends on the node data.
if non_balance_node_parent:
if non_balance_node_parent.data > non_balance_node.data:
non_balance_node_parent.left_child = non_balance_node
else:
non_balance_node_parent.right_child = non_balance_node
else:
self.root = non_balance_node
@staticmethod
def left_rotate(node):
node.bf = node.right_child.bf = 0
node_right = node.right_child
node.right_child = node.right_child.left_child
node_right.left_child = node
return node_right
@staticmethod
def right_rotate(node):
node.bf = node.left_child.bf = 0
node_left = node.left_child
node.left_child = node.left_child.right_child
node_left.right_child = node
return node_left
@staticmethod
def left_right_rotate(node):
node_b = node.left_child
node_c = node_b.right_child
node.left_child = node_c.right_child
node_b.right_child = node_c.left_child
node_c.left_child = node_b
node_c.right_child = node
# update bf
if node_c.bf == 0:
node.bf = node_b.bf = 0
elif node_c.bf == 1:
node.bf = -1
node_b.bf = 0
else:
node.bf = 0
node_b.bf = 1
node_c.bf = 0
return node_c
@staticmethod
def right_left_rotate(node):
node_b = node.right_child
node_c = node_b.left_child
node_b.left_child = node_c.right_child
node.right_child = node_c.left_child
node_c.right_child = node_b
node_c.left_child = node
if node_c.bf == 0:
node.bf = node_b.bf = 0
elif node_c.bf == 1:
node.bf = 0
node_b.bf = -1
else:
node.bf = 1
node_b.bf = 0
node_c.bf = 0
return node_c
class BinarySortTree(object):
def __init__(self, node=None) -> None:
self.root = node
def add(self, item):
"""插入数据
Args:
item (any): the data of a node
"""
node = Node(item)
if self.root is None or self.root.data is None:
self.root = node
return
node_queue = []
node_queue.append(self.root)
while node_queue:
current_node = node_queue.pop()
if node.data >= current_node.data:
if current_node.right_child:
node_queue.append(current_node.right_child)
else:
current_node.right_child = node
else:
if current_node.left_child:
node_queue.append(current_node.left_child)
else:
current_node.left_child = node
class RedBlackTree(object):
def __init__(self, node=None) -> None:
self.root = node
def add(self, **item):
pass
if __name__ == "__main__":
#创建一个二叉树对象
node_list = [3,9,20,None,None,15,7]
tree = BinaryTree()
#以此向树中添加节点,i == 3的情况表示,一个空节点,看完后面就明白了
for i in node_list:
tree.add(i)
print(tree.levelOrderBottom())
#广度优先的层次遍历算法
# print([i.data for i in tree.floor_travel()])
#前,中,后序 遍历算法(栈实现)
# print([i.data for i in tree.front_travel()])
# tree.front_travel_with_loop_1(tree.root)
# print([i.data for i in tree.front_travel_with_loop_2()])
# print([i.data for i in tree.middle_travel()])
# print([i.data for i in tree.back_travel()])
print('------------------------------------')
#前,中,后序 遍历算法(堆栈实现)
# print([i.data for i in tree.front_stank_travel()])
# print([i.data for i in tree.middle_stank_travel()])
# print([i.data for i in tree.back_stank_travel()])
|
2750021796bb19068080d52a34e64182587bdbce | ze-dev/applied_programming | /maketxt.py | 775 | 3.65625 | 4 | def maketxt(filename):
'''Создает текстовый файл в директории запуска скрипта.
В консоли вызывать maketxt.py НужноеИмяФайла (БЕЗ пробелов)'''
import time, os
with open('%s.txt' % filename, 'w') as ff:
dirPath=os.getcwd()
fullPath = '%s\%s' % (dirPath, filename)
print('\nДиректория назначения вызова > %s ' % dirPath)
print('\nФайл %s.txt создан...' % filename)
time.sleep(2)
if __name__ == '__main__':
import sys
if len (sys.argv) > 1:
parameter = sys.argv[1]
else:
parameter = input('Введите имя файла > ')
maketxt(parameter)
|
4b6d03ff869820950c0d36c0a4edd8fbfec3c4f7 | Cvig/MyCodes | /Python/Practice_Problems/Array/Two Sum III - Data Structure Design.py | 1,606 | 4.09375 | 4 | '''
Design and implement a TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers whose sum is equal to the value.
'''
class TwoSum(object):
def __init__(self):
"""
initialize your data structure here
"""
self.numsCount = {}
def add(self, number):
"""
Add the number to an internal data structure.
:rtype: nothing
"""
# there could be duplicates in this array so better to use hashmap consisting of value and its count instead of storing each element separately because we are not interested in indices of twoSum, but just whether two elements sum to value or not.
if number in self.numsCount:
self.numsCount[number] +=1
else:
self.numsCount[number] = 1
def find(self, value):
"""
Find if there exists any pair of numbers whose sum is equal to the value.
:type value: int
:rtype: bool
"""
for key in self.numsCount:
first = key
second = value - first
if first == second: #if they are equal, that will be checked earlier
if self.numsCount[key] >1:
return True
elif second in self.numsCount: #else if they are not equal, do use else if and not just if
return True
return False
# Your TwoSum object will be instantiated and called as such:
# twoSum = TwoSum()
# twoSum.add(number)
# twoSum.find(value) |
68b3480708b70de1b8bb576e73aaf642e18cec93 | Cvig/MyCodes | /Python/Practice_Problems/Array/Intersection.py | 1,197 | 3.984375 | 4 | #find intersection of two lists of integers
#Cases: lists could be empty
#there could be duplicates in the list
#length may be different, in that case my list could not be bigger than that
class Solution(object):
def intersection(self, l1, l2):
"""
:type l1: list of integers
:type l2: list of integers
:rtype : list of integers
"""
l3 =[] #This is initialization of intersection list
dic_l3 = {} #We will keep a hashmap
if l1 == None or l2 == None: #if either of them is empty
return l3 #no element in intersection
#if both have elements
#iterate first list
for i in range(len(l1)):
if l1[i] in dic_l3:
dic_l3[l1[i]] +=1 #add 1 to the count
else:
dic_l3[l1[i]] = 1 #add the element as the key
#Now iterate the next list
for j in range(len(l2)):
if l2[j] in dic_l3: #if this is a key already
l3.append(l2[j]) #add the element to the result
dic_l3[l2[j]] -= 1 #decrement 1
return l3
#Test
'''
l1 =[5,8]
l2 =[8,0]
s = Solution()
r = s.intersection(l1,l2)
print r
''' |
b3cff1fe173d6371ab8a265716ebc47aac78e107 | Cvig/MyCodes | /Python/Practice_Problems/Lists/NestedListWeightSum.py | 734 | 3.8125 | 4 | #Given a nested list of integers, return the sum of all integers in the list weighted by their depth
#Each element is either an integer, or a list whose elements may also be integers or other lists
class Solution(object):
def depthSum(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
return self.findsum(nestedList, 1)
def findsum(self, eachlist, depth):
sum = 0
for i in range(len(eachlist)):
if type(eachlist[i]) == int:
sum += eachlist[i]*depth
else:
sum += self.findsum(eachlist[i], depth+1)
return sum
#Test
'''
s = Solution()
a = s.depthSum([1,[2,3,4],4])
print a
'''
|
29e6db95f9449ec3665a57762bf3d8e32aa0926c | sarnaizgarcia/Master-en-Programacion-con-Python_ed2 | /silvia/katas/pitagorasclases.py | 618 | 3.921875 | 4 | import math
class RightTriangle():
def __init__(self, leg_one, leg_two):
self.leg_one = leg_one
self.leg_two = leg_two
@property
def hypotenuse(self):
h = round(math.sqrt(pow(self.leg_one, 2) + pow(self.leg_two, 2)), 0)
return h
def __repr__(self):
return f'El primer cateto es {self.leg_one}, el otro cateto es {self.leg_two} y la hipotenusa es {self.hypotenuse}'
first_leg = int(input('Dime cuanto mide el primer cateto: '))
second_leg = int(input('Dime cuanto mide el segundo cateto: '))
triangle = RightTriangle(first_leg, second_leg)
print(triangle)
|
cb1e9921d2f54d3bc3e3cb8bf67ca3e2af019197 | mgeorgic/Python-Challenge | /PyBank/main.py | 2,471 | 4.25 | 4 | # Import os module to create file paths across operating systems
# Import csv module for reading CSV files
import csv
import os
# Set a path to collect the CSV data from the Resources folder
PyBankcsv = os.path.join('Resources', 'budget_data.csv')
# Open the CSV in reader mode using the path above PyBankiv
with open (PyBankcsv, newline="") as csvfile:
# Specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
# Create header row first
header = next(csvreader)
monthly_count = []
# Empty lists to store the data
profit = []
profit_change = []
# Read through each row of data after the header
for row in csvreader:
# populate the dates in column "monthly_count"
monthly_count.append(row[0])
# Append the profit information
profit.append(int(row[1]))
#Deleted unneccesary calculations bc I'll do them in print functions
#Calculate the changes in Profit over the entire period
for i in range(len(profit)):
# Calculate the average change in profits.
if i < 85:
profit_change.append(profit[i+1]-profit[i])
#Average of changes in Profit
avg_change = sum(profit_change)/len(profit_change)
# Greatest increase in profit (date and amount)
greatest_increase = max(profit_change)
greatest_index = profit_change.index(greatest_increase)
greatest_date = monthly_count[greatest_index+1]
# Greatest decrease in profit (date and amount)
greatest_decrease = min(profit_change)
lowest_index = profit_change.index(greatest_decrease)
lowest_date = monthly_count[lowest_index+1]
# Print the summary table in display
# Use f-string to accept all data types without conversion
# len counts the total amount of months in column "Monthly_Count"
# sum adds up all the profits in column "Profit"
# Round the average change to two decimals
report = f"""Financial Analysis
-----------------------
Total Months:{len(monthly_count)}
Total: ${sum(profit)}
Average Change: ${str(round(avg_change,2))}
Greatest Increase in Profits: {greatest_date} (${str(greatest_increase)})
Greatest Decrease in Profits: {lowest_date} (${str(greatest_decrease)})"""
print (report)
# Export the file to write
output_path = os.path.join('analysis','Simplified_budget_data.txt')
# Open the file using write mode while holding the contents in the file
with open(output_path, 'w') as txtfile:
# Write in this order
txtfile.write(report)
|
dc56e7a5a4fa8422088b3e0cba4b78d2a86a1be3 | roctbb/GoTo-Summer-17 | /day 1/6_words.py | 425 | 4.15625 | 4 | word = input("введи слово:")
words = []
words.append(word)
while True:
last_char = word[-1]
new_word = input("тебе на {0}:".format(last_char.upper())).lower()
while not new_word.startswith(last_char) or new_word in words:
print("Неверно!")
new_word = input("тебе на {0}:".format(last_char.upper())).lower()
word = new_word
print("Следующий ход!")
|
672c5c943f6b90605cf98d7ac4672316df20773a | vittal666/Python-Assignments | /Third Assignment/Question-9.py | 399 | 4.28125 | 4 | word = input("Enter a string : ")
lowerCaseCount = 0
upperCaseCount = 0
for char in word:
print(char)
if char.islower() :
lowerCaseCount = lowerCaseCount+1
if char.isupper() :
upperCaseCount = upperCaseCount+1
print("Number of Uppercase characters in the string is :", lowerCaseCount)
print("Number of Lowercase characters in the string is :", upperCaseCount)
|
168192647db4ab5dc7184877963cd38b43702527 | vittal666/Python-Assignments | /Third Assignment/Question-2.py | 500 | 3.84375 | 4 | input_list = []
n = int(input("Enter the list size : "))
print("\n")
for i in range(0, n):
print("Enter number", i+1, " : ")
item = int(input())
input_list.append(item)
print("\nEntered List is : ", input_list)
freq_dict = {}
for item in input_list:
if (item in freq_dict):
freq_dict[item] += 1
else:
freq_dict[item] = 1
print("\nPrinting count of each item : ")
for key, value in freq_dict.items():
print(key, " : ", freq_dict[key], " times")
|
e64285d27bcf8652203793248a17089754a465d6 | naijnauj/FAQ | /DTFT/day3/class.py | 1,035 | 3.625 | 4 | class MyClass(object):
message = 'Hello, Developer'
def show(self):
print self.message
print 'Here is %s in %s!' % (self.name, self.color)
@staticmethod
def printMessage():
print 'printMessage is called'
print MyClass.message
@classmethod
def createObj(cls, name, color):
print 'Object will be created: %s(%s, %s)'% (cls.__name__, name, color)
return cls(name, color)
def __init__(self, name = 'unset', color = 'black'):
print 'Constructor is called with params: ', name, ' ', color
self.name = name
self.color = color
def __del__(self):
print 'Destructor is called for %s' % self.name
MyClass.printMessage()
inst = MyClass.createObj('Toby', 'Red')
print inst.message
del inst
class BaseA(object):
def move(self):
print 'AAAAAAAAAAAAAA'
class BaseB(object):
def move(self):
print 'BBBBBBBBBBBB'
class BaseC(BaseA):
def moveC(self):
print 'CCCCCCCCCCCCCCCCC'
class D(BaseC, BaseB):
def moveD(self):
print 'DDDDDDDDDDDDDDDD'
inst = D()
inst.move() |
39237343d21c26559dea1979e1cea5a87c4227ba | shashankp/projecteuler | /45.py | 626 | 3.515625 | 4 | #Triangular, pentagonal, and hexagonal
import math
def isperfsq(i):
sq = math.sqrt(i)
if sq == int(sq): return True
return False
n = 533
c = 0
while True:
h = n*(2*n-1)
if isperfsq(8*h+1) and isperfsq(24*h+1):
t = (-1+math.sqrt(8*h+1))
p = (1+math.sqrt(24*h+1))
if t%2!=0 or p%6!=0:
n += 1
continue
t /= 2
p /= 6
#print 'found', h
if (p*(3*p-1))/2 == (t*(t+1))/2:
#print 't', t, (t*(t+1))/2
#print 'p', p, (p*(3*p-1))/2
print int((t*(t+1))/2)
exit()
n += 1
|
6ae38ce4d29e307187be215b56b45d59c0dd2615 | shashankp/projecteuler | /5.py | 201 | 3.75 | 4 | #lcm
n = 20
def lcm(a,b):
c = a*b
while b>0:
a,b = b,a%b
return c/a
l = set()
for i in xrange(2, n):
if i%2 != 0: l.add(2*i)
else: l.add(i)
c = 1
for i in l:
c = lcm(c,i)
print c
|
d6aa1d2839b1d49189238e7d52233cd7bf6c1a88 | ywtail/Aha-Algorithms | /2_5.py | 555 | 3.515625 | 4 | # coding:utf-8
# 数组模拟链表,输入一个数插入正确的位置
# data存数据,right存(下一个数的)索引
data=map(int,raw_input().split())
right=[i for i in range(1,len(data))]+[0]
#print data
#print right
inpt=int(raw_input())
data.append(inpt)
def func():
for i in xrange(len(data)):
if data[i]>inpt:
break
i-=1
right.append(right[i])
right[i]=len(data)-1
#print data,right
temp=0
while right[temp]!=0:
print data[temp],
temp=right[temp]
print data[temp]
func()
# 输入:2 3 5 8 9 10 18 26 32
# 输入:6
|
9840d8d6e3e2aab4ed89cfd405839f78b9d7d16e | ywtail/Aha-Algorithms | /2_2.py | 482 | 3.90625 | 4 | # coding:utf-8
# 桟(判断回文:先求中间,然后前半部分压入栈,弹出与后半部分对比。)
s=raw_input()
n=len(s)
def func():
if s==s[::-1]:
print "YES"
else:
print "NO"
#func()
if n==1:
print "YES"
else:
mid=n/2
mids=""
for i in xrange(mid):
mids+=(s[i])
if n%2==0:
nex=mid
else:
nex=mid+1
for j in xrange(nex,n):
if mids[i]!=s[j]:
break
i-=1
if i==-1:
print "YES"
else:
print "NO"
# 输入:ahaha
# 输出:YES |
bf4eae907ed3fae20b59aeb828bee713bcf2b111 | ywtail/Aha-Algorithms | /7_4.py | 676 | 3.625 | 4 | # coding:utf-8
# 并查集:求一共有几个犯罪团伙
def getf(v):
if f[v]==v:
return v
else:
f[v]=getf(f[v]) #路径压缩,顺带把经过的节点改为祖先的值
return f[v]
def merge(v,u):
t1=getf(v)
t2=getf(u)
if t1!=t2:
f[t2]=t1
n,m=map(int,raw_input().split())
f=[i for i in range(n+1)]
for i in range(m):
x,y=map(int,raw_input().split())
merge(x,y)
ans=0
#扫描有多少个犯罪团伙
for i in range(1,n+1):
if f[i]==i:
ans+=1
print ans
'''
input:
10 9
1 2
3 4
5 2
4 6
2 6
8 7
9 7
1 6
2 4
output:
3
分析:
每次找到祖先,修改祖先对应值。路径中节点对应值通过下一次经过时路径压缩改变。
''' |
fd53e99695c452678c1af7f5e31a5f1d4fa0f91b | pyjones/python | /campaignWorking.py | 1,553 | 3.640625 | 4 | # A script to work out campaign values and metrics
from __future__ import division
prompt = ">>>"
def cost_per_unique(campaign_value, campaign_uniques):
cost_per_unique = campaign_value / campaign_uniques
return cost_per_unique
def cost_per_minute(campaign_value,dwell_time):
cost_per_minute = campaign_value / dwell_time
return cost_per_minute
def cpm(campaign_value,impressions):
cpm = (campaign_value / impressions) * 1000
return cpm
def cpc(campaign_value,clicks):
cpc = campaign_value / clicks
return cpc
print "Campaign Name"
campaign_name = raw_input(prompt)
print "Campaign Value"
campaign_value = float(raw_input(prompt))
print "Campaign Uniques"
campaign_uniques = float(raw_input(prompt))
print "Total Dwell Time"
dwell_time = float(raw_input(prompt))
print "Total Impressions"
impressions = float(raw_input(prompt))
print "Total Clicks"
clicks = float(raw_input(prompt))
print "======"
print "For the campaign: ", campaign_name
print "The value of this campaign was: $ %.0f" % campaign_value
print "Number of impressions delivered: %.0f" % impressions
print "Number of clicks delivered: %.0f" % clicks
print "Total dwell time: %.0f" % dwell_time, "minutes"
print "The cost per unique was: $", "%.2f" % cost_per_unique(campaign_value, campaign_uniques)
print "The cost per minute was: $", "%.2f" % cost_per_minute(campaign_value,dwell_time)
print "The CPM of this campaign was: $", "%.2f" % cpm(campaign_value,impressions)
print "The CPC of this campaign was: $", "%.2f" % cpc(campaign_value,clicks)
print "======"
|
1c6f4c6df2921e90d2ab8b5d58b0bcd2f8b7927b | skunwarc/Adv-Stats | /emea.py | 883 | 3.671875 | 4 | #!/usr/bin/env python2.7
# initiate a few variables
i = 0
Id=[]
Gdp= []
Fertrate= []
# read csv file and store data in arrays x and y
import csv
with open('emea.csv','rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
i += 1
#print i
emea = row
Id.append(int(emea[0]))
Gdp.append(float(emea[1]))
Fertrate.append(float(emea[2]))
#print x
#print y
print ("Id")
print Id
print ("Gdp")
print Gdp
print ("Fertility rate")
print Fertrate
# now use arrays x and y to run linear regression
import scipy.stats as stats
lr = stats.linregress
slope, intercept, rvalue, pvalue, stderr,= lr(Gdp,Fertrate)
# print results to screen
print 'slope',slope
print 'intercept',intercept
print 'rvalue',rvalue
print 'pvalue',pvalue
print 'stand error',stderr
print 'Y=',slope,'*X+',intercept
print (" sagar kunwar")
print
|
8d3835871bc36c5af378d6136b25ffc8bd0f2f1b | cseoy73/Covid19-R-Web | /분석 및 시각화/graph3.py | 483 | 3.734375 | 4 | from matplotlib import pyplot as plt
month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Employment = [26800, 27991, 26609, 26562, 26930, 27055, 27106, 27085, 27012, 27088, 27241]
Unemployment = [1153, 26838, 1180, 1172, 1278, 1228, 1138, 864, 1000, 1028, 967]
plt.plot(month, Employment, marker="o")
plt.plot(month, Unemployment, marker="o")
plt.xlabel('Month')
plt.ylabel('단위: 천(명)')
plt.title('Employment And Unemployment')
plt.legend(['Employment', 'Unemployment'])
plt.show() |
87989d135315dad70da7904a74791609c713276b | TahsinaSnow/TahsinaSnow | /5th.py | 123 | 4.25 | 4 | import math
degree = float(input("Enter an angle in degree:"))
radian = (degree*math.pi)/180
print(math.sin(radian))
|
a19f190af9c07707915d425973f295a7254a6811 | marcofrn23/Python | /Design of Computer Programs/floorpuzzle.py | 1,019 | 3.984375 | 4 | # Exercise 1 for lesson 2 in 'Design of Computer Program' course
from itertools import permutations
def is_adjacent(p1, p2):
if abs(p1-p2) == 1:
return True
return False
def floor_puzzle():
"""Resolves the given puzzle with the given constraints."""
residences = list(permutations([1,2,3,4,5], 5))
# Expressing all the constraints with a generator expression
return list(next((Hopper, Kay, Liskov, Perlis, Ritchie)
for (Hopper, Kay, Liskov, Perlis, Ritchie) in residences
if Hopper is not 5 and
Kay is not 1 and
Liskov is not 1 and
Liskov is not 5 and
Perlis > Kay and
not is_adjacent(Ritchie, Liskov) and
not is_adjacent(Liskov, Kay)))
#MAIN
f = floor_puzzle()
p = ('Hopper', 'Kay', 'Liskov', 'Perlis', 'Ritchie')
res = [person + ' lives in the floor no. ' for person in p]
floors = [str(number) for number in f]
for i in range(5):
print '\n' + res[i] + floors[i]
print '\n......Puzzle resolved correctly.'
|
1feae052372eba7dd2597ed2d06d191195687a02 | abhayparikh99/Practice_Programs | /helly_3_in_1_game_merge.py | 13,057 | 4.34375 | 4 | # Game zone....
import random
# Write a program for Rock_Paper_Scissors game.
# user/computer will get 1 point for winning, Play game until user/computer score=3 point.
class RPS():
user_score=0
computer_score=0
def __init__(self):
print("Welcome to 'Rock Paper Scissors'".center(130)) ;print()
print("Instruction :\nRock smashes scissors, so in this case Rock get 1 point.\nPaper covers rock, so in this case Paper get 1 point.\nScissors cut paper, so in this case Scissor get 1 point.")
print("Use notation:\n'r' for 'rock' \n'p' for 'paper' \n's' for 'scissor'\n")
def play_RPS(self,user_score,computer_score):
status=True
while status: #loop will continue until any of user score becomes 3. # or score==3 then break.
print("---> Enter Your Choice")
user_choice=input("User Choice is:")
tickets=['r','s','p']
computer_choice=random.choice(tickets)
print("Computer Choice is:",computer_choice);print()
if user_choice in ["r","s","p"]:
if user_choice!=computer_choice:
if user_choice=='r':
if computer_choice=='s':
print("User Won!! Rock smashes scissor.")
user_score+=1
print("User Current Score is:",user_score) #or user_choice=='s' and computer_choice=='p':
print("Computer Current Score is:",computer_score);print()
else:
print("Computer Won!! Paper covers rock.")
computer_score+=1
print("User Current Score is:",user_score)
print("Computer Current Score is:",computer_score);print()
if user_choice=='s':
if computer_choice=='p':
print("User Won!! Scissor cut paper.")
user_score+=1
print("User Current Score is:",user_score)
print("Computer Current Score is:",computer_score);print()
else:
print("Computer Won!! Rock smashes scissor.")
computer_score+=1
print("User Current Score is:",user_score)
print("Computer Current Score is:",computer_score);print()
if user_choice=='p':
if computer_choice=='r':
print("User Won!! Paper covers rock.")
user_score+=1
print("User Current Score is:",user_score)
print("Computer Current Score is:",computer_score);print()
else:
print("Computer Won!! Scissor cut paper.")
computer_score+=1
print("User Current Score is:",user_score)
print("Computer Current Score is:",computer_score);print()
else:
print("Tie!!!");print()
else:
print("Invalid Choice");print()
if user_score==3 or computer_score==3:
status=False
print("Total Score of User is:",user_score)
print("Total Score of Computer is:",computer_score)
if user_score>computer_score:
print("User Won the Game!!")
else:
print("Computer Won the Game!!")
# WAP to create Housie Game.
class HG():
main_ticket=[]
user_ticket=[]
computer_ticket=[]
def play_housie(self):
self.n=int(input("Enter Number from which you want genertae tickets :"))
#Code for Generate main_ticket.
print("Tickets are :",end=" ")
status=True
while status:
ran=random.randint(1,99)
if ran not in self.main_ticket:
self.main_ticket.append(ran)
if len(self.main_ticket)==12:
status=False
for i in self.main_ticket:
print(i,end=" ")
print();print()
#Code for Generate user_ticket.
print("User's Tickets are :",end=" ")
for i in self.main_ticket:
u_ran=random.choice(self.main_ticket)
if u_ran not in self.user_ticket:
self.user_ticket.append(u_ran)
if len(self.user_ticket)==6:
break
for i in self.user_ticket:
print(i,end=" ")
print();print()
#Code for Generate computer_ticket/
print("Computer's Tickets are :",end=" ")
for k in self.main_ticket:
if k not in self.user_ticket:
self.computer_ticket.append(k)
for i in self.computer_ticket:
print(i,end=" ")
print();print()
#Code for Open one by one tickets and check in which those ticket is present and
# then remove from those list and print new list.
for i in self.main_ticket:
print("Entered Value is :",i)
if i in self.user_ticket:
self.user_ticket.remove(i)
print("Removed value from user's Ticket is :",i)
print("Remaining Values in user's Ticket are :",self.user_ticket)
self.element=input()
if len(self.user_ticket)==0:
print("User is win this Game!!!")
break
elif i in self.computer_ticket:
self.computer_ticket.remove(i)
print("Removed value from computer's Ticket is :",i)
print("Remaining values in computer's Ticket are :",self.computer_ticket)
self.element=input()
if len(self.computer_ticket)==0:
print("Computer is win this Game!!!")
break
# Write a Program to make quiz for Kaun Banega Crorepati.
class KBC():
def __init__(self):
print("Hello!!!Namaste".center(100));print()
print("Welcome to KBC".center(100)) ;print()
score=0
correct_count=0
correct_ans={}
incorrect_ans={}
def que_bank(self):
Q1="Que-1) Where is an ocean with no water?"
Q2="Que-2) What is always coming,but never arrives?"
Q3="Que-3) If you have a bowl with six apples and you take away four, how many do you have?"
Q4="Que-4) Some months have 31 days, others have 30 days, but how many have 28 days?"
Q5="Que-5) What is it that goes up, but never comes down?"
Q6="Que-6) The present age of Aradhana and Aadrika is in the ratio 3:4. 5 years back,the ratio of their ages was 2:3. What is the present age of Aradhana?"
Q7="Que-7) A train running at the speed of 15.55 m/s crosses a pole in 18 seconds. What is the length of the train?"
Q8="Que-8) Introducing Neeta, Anil said, ‘She is the wife of my mother’s only son.’ How is Neeta related to Anil?"
Q9="Que-9) A father is twice as old as his daughter. If 20 years ago, the age of the father was 10 times the age of the daughter, what is the present age of the father?"
Q10="Que-10) If you divide 30 by half and add ten, what do you get?"
self.que_option={
Q1:("A) On Map","B) Dessert","C) On Earth","D) None"),
Q2:("A) Today","B) Tomorrow","C) Next Day","D) Yesterday"),
Q3:("A) 2","B) 3","C) 4","D) 6"),
Q4:("A) 11","B) 5","C) 1","D) 12"),
Q5:("A) Age","B) Stairs","C) Kite","D) Birds"),
Q6:("A) 20","B) 15","C) 5","D) 10"),
Q7:("A) 200","B) 250","C) 180","D) 150"),
Q8:("A) Mother","B) Sister","C) Daughter-in-law","D) Wife"),
Q9:("A) 45","B) 22","C) 42","D) 24"),
Q10:("A) 35","B) 70","C) 50","D) None")
}
#dictionaries of correct options and their answer
self.ans_bank_value={Q1:"A) On Map",Q2:"B) Tomorrow",Q3:"C) 4",Q4:"D) 12",Q5:"A) Age",Q6:"B) 15",Q7:"C) 180",Q8:"D) Wife",Q9:"A) 45",Q10:"B) 70"}
self.ans_bank={Q1:"A",Q2:"B",Q3:"C",Q4:"D",Q5:"A",Q6:"B",Q7:"C",Q8:"D",Q9:"A",Q10:"B"}
for question in self.que_option:
print(question) #prints questions
for option in self.que_option[question]: #prints options
print(option)
print()
KBC.answer_validation(self)
def answer_validation(self):
for k in self.ans_bank:
self.answer=self.ans_bank[k]
self.ans_bank.pop(k) #to remove dict item one by one,.pop() is used with break in for loop
break
user_ans=input("Enter Correct option: A/B/C/D: ").upper() #to convert user ans into uppercase,str upper() method is used.
if self.answer==user_ans:
print("-->Correct Answer.")
self.score+=50
self.correct_count+=1
KBC.list_correct(self)
else:
print("Incorrect Answer.")
self.score-=20
KBC.list_incorrect(self)
print("Your Current Score is:",self.score)
print("-----------------------------")
def list_correct(self):
for i in self.ans_bank_value:
self.correct_ans[i]=self.ans_bank_value[i]
self.ans_bank_value.pop(i)
break
def list_incorrect(self):
for i in self.ans_bank_value:
self.incorrect_ans[i]=self.ans_bank_value[i]
self.ans_bank_value.pop(i)
break
def view_list(self):
status=True
while status:
print("Press 1 to view Correct answer List.\nPress 2 for Incorrect answer list.\nPress 3 for correct and incorrect both lists.")
list_choice=int(input("Enter your choice:"));print();print()
if list_choice==1:
print("list of correct questions and answers are :")
for i in self.correct_ans:
print(i,"\nCorrect Answer--->",self.correct_ans[i])
print()
elif list_choice==2:
print("list of incorrect questions are:")
for i in self.incorrect_ans:
print(i,"\ninCorrect Answer--->",self.incorrect_ans[i])
print()
elif list_choice==3:
print("list of correct questions are:")
for i in self.correct_ans:
print(i,"\nCorrect Answer--->",self.correct_ans[i]);print()
print()
print("list of incorrect questions are:");print()
for i in self.incorrect_ans:
print(i,"\nCorrect Answer--->",self.incorrect_ans[i])
print()
view_list_choice=(input("Press 'y' to continue and 'n' for exit: ")).lower()
if view_list_choice=='n':
status=False
break
def menu(self):
print("Press 1 for Play the Game.\n Press 2 for quit the game.")
choice=int(input("Enter your choice:"));print()
if choice==1:
print("**Instruction: You will get +50 points for each correct answer and -20 points for each wrong answer");print();input()
KBC.que_bank(self)
print("Correct Answer=",self.correct_count,"out of 10")
print("Quiz completed! Your Total Score out of 500 is:",self.score);print();print()
KBC.view_list(self)
elif choice==2:
print("You have choosed to Quit Quiz.")
else:
print("Invalid choice")
class menu():
def __init__(self):
print("Welcome to game zone.".center(100))
print("There are three games available in this game zone.\n1) Rock Paper Scissors\n2) Housie Game\n3) KBC Quiz");print()
def display(self):
print("Press 1 for 'RPS'. \nPress 2 for 'HG'.\nPress 3 for 'KBC'.")
choice=int(input("Enter your choice :"))
if choice==1:
obj=RPS()
obj.play_RPS(0,0)
elif choice==2:
obj_HG=HG()
obj_HG.play_housie()
elif choice==3:
obj_KBC=KBC()
obj_KBC.menu()
# obj_KBC.question_bank()
# obj_KBC.answer_validation()
# obj_KBC.list_correct()
# obj_KBC.list_incorrect()
# obj_KBC.view_list()
else:
print("Invalid choice.")
status=True
obj_menu=menu()
while status:
choice=input("-->Now if you want to play game then press 'y' or 'yes' and press 'n' or 'no' for exit this game zone.:")
if choice=='y' or choice=='yes':
obj_menu.display()
elif choice=='n' or choice=='no':
print("Bye Bye!!")
status=False |
c15cb5b8683ddda1af31898a980e9badf67ddaac | Taylorbear3/Find-the-Murderer | /class animal.py | 264 | 3.546875 | 4 |
class Animal:
name = None
numoflegs = None
numofeyes = None
hasnose = False
#method can
def sayName()
print(self.name)
tiger = Animal()
tiger.name = "Pi"
tiger.numOflegs = 4
tiger.numofeyes = 2
tiger.nose = 1
print(self.name) |
537f13db14ebefff96b6ecb3308d1c3b4435a6cb | ziegs4life/pythonPractices | /Lists.py | 2,256 | 3.5625 | 4 | # a = range(10)
# b = sum(a)
# print b
#
#
# a = [1,2,3]
# print max(a)
#
# a = [1,2,3]
# print min(a)
#
# a = range(2,10,2)
# print a
# def pos_num():
# my_list = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#
# for i in range(len(my_list)):
# if my_list[i] > 0:
# print my_list[i]
#
# pos_num()
# def pos_num_2():
# my_list = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# new_list = []
#
# for i in range(len(my_list)):
# if my_list[i] > 0:
# new_list.insert(i, my_list[i])
#
# print new_list
#
# pos_num_2()
# def multiplyList():
# my_list = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# factor = 10
# new_list = []
#
# for i in range(len(my_list)):
# new_list.insert(i, my_list[i] * factor)
#
# print new_list
# multiplyList()
#
# def multVect():
#
# list_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# list_2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# new_list = []
#
# for i in range(len(list_1)):
# new_list.insert(i, list_1[i] * list_2[i])
#
# print "list one: "
# print list_1
# print "list two: "
# print list_2
# print "product: "
# print new_list
#
# multVect()
# def matAdd():
#
# list_1 = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
# [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]]
# list_2 = [[10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
# [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
# product = [[],[]]
#
# for i in range(len(list_1)):
# for x in range(len(list_1[i])):
# product[i].append(list_1[i][x] + list_2[i][x])
#
# print product
#
# list_1 = ['apples', 'apples', 'bananas', 'bananas', 'pears', 'bananas']
# list_2 = []
#
# for i in list_1:
# if i not in list_2:
# list_2.append(i)
#
# print list_1
# print list_2
# matAdd()
def matAddtwo():
matrix_1 = [[2, 3], [4, 5]]
matrix_2 = [[3, 4], [5, 6]]
rows_1 = [1] * 2
cols_2 = [1] * 2
result = [[], []]
for i in range(len(matrix_1)):
for x in range(len(matrix_1[i])):
rows_1[i] *= matrix_1[i][x]
cols_2[i] *= matrix_2[x][i]
for i in range(len(matrix_1)):
for x in range(len(matrix_1)):
result[i].append(rows_1[i] + cols_2[x])
print matrix_1
print matrix_2
print result
matAddtwo()
|
4d8345fb969ff1d9d544f0cc2027c9325eb42370 | josegonzah/PruebaTecnicaSofka | /ConsoleApp/Questions.py | 2,947 | 4.09375 | 4 | import random
import csv
class Questions:
def __init__(self):
##Questions object is basically a dictionary which keys are the rounds asociated to the bank of questions
#and the values are arrays that contains arrays, those inner arrays have, in order, the statement, the answer
#and the other 3 options. This object was created with the purpose of only loading once this file as it is
#the file that has the potential to be the largest and to handle the data more eaisily
self.bankOfQuestions = {}
self.nameOfQuestionDB = 'questionDB.csv'
##The bank of questions will be populated next
self.populateBankOfQuestions(self.nameOfQuestionDB)
def getRandomQuestion(self, round):
#Returns a random questionn from the dictionary given a level of difficulty
numberOfQuestions = len(self.bankOfQuestions[round])
randomQuestion = random.randint(0, numberOfQuestions-1)
return self.bankOfQuestions[round][randomQuestion]
def addNewQuestion(self, round, statement, answer, option1, option2, option3):
#Method designed for future developers to add a question via code and not access directly
#the csv file
if(round > 0 and round <= len(self.bankOfQuestions)+1):
newQuestion = [statement, answer, option1, option2, option3]
self.bankOfQuestions[round].append(newQuestion)
newQuestionDB = [str(round), statement, answer, option1, option2, option3]
with open(self.nameOfQuestionDB, 'a', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(newQuestionDB)
csv_file.close()
else:
print("Can´t add question check difficulty level")
def populateBankOfQuestions(self, nameOfDataBase):
#Method to populate the dictionary inside this object by loading the data of the csv
#file to the dictionary
with open(nameOfDataBase) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
line_count += 1
continue
else:
difficulty = int(row[0])
statement = row[1]
answer = row[2]
option1 = row[3]
option2 = row[4]
option3 = row[5]
currentQuestion = [statement, answer ,option1 , option2, option3]
if difficulty in self.bankOfQuestions:
self.bankOfQuestions[difficulty].append(currentQuestion)
else:
level = []
level.append(currentQuestion)
self.bankOfQuestions[difficulty] = level
line_count += 1
|
7d133060d3601fb988fe143f3fff058b54d47b0e | austinread/adventofcode2020 | /solutions/9.py | 1,356 | 3.71875 | 4 | import sys
from helpers import inputs
raw = inputs.import_input(9)
numbers = raw.split("\n")
numbers = [int(n) for n in numbers]
preamble_length = 25
def is_valid(index):
number = numbers[index]
options = numbers[index-preamble_length:index]
valid = False
for o1 in options:
if valid:
break
for o2 in options:
if o1 == o2:
continue
if o1 + o2 == number:
valid = True
break
return valid
invalid_number = -1
for n in range (preamble_length,len(numbers)):
if not is_valid(n):
invalid_number = numbers[n]
print(f"Invalid number detected: {invalid_number}")
break
if invalid_number == -1:
print("Error: invalid number not found")
sys.exit()
for i in range(len(numbers)):
n = numbers[i]
if n >= invalid_number:
print("Error: no contiguous sequence found")
sys.exit()
sequence = [n]
for p in range(i+1,len(numbers)):
n2 = numbers[p]
sequence.append(n2)
sequence_sum = sum(sequence)
if sequence_sum == invalid_number:
lower = min(sequence)
upper = max(sequence)
print(f"Encryption weakness found: {lower + upper}")
sys.exit()
if sequence_sum > invalid_number:
break |
f8e1ece2012af7ee8c2ac873064e12fd01136317 | butuye08/Python | /ex33.py | 232 | 3.875 | 4 | i = 0
numbers = []
while i < 6:
print "At the top i is %d " % i
numbers.append (i)
i = i + 1
print "Numbers now", numbers
print "At the buttom i is %d " % i
print "The numbers: "
for num in numbers:
print num |
ed9bbe37e0e154e8fe47c772331a9a0786d36da8 | alu-rwa-dsa/summative-dirac_wanji_fiona | /High-Fidelity/main.py | 2,890 | 3.5625 | 4 | import sys
from users.signup.sign_up import sign_up
from login.login_module import login
from questions.questions_answers import Quiz
from users.search.search_one_user import get_the_user
# this is a function to call our main menu
def main_menu():
print("=" * 100)
print("Welcome! What would you like to do today?")
print("Press 1: To Sign Up if you are a new user")
print("Press 2: To Login if you're an existing user")
print("Press 3: Exit")
# we create a student menu that is displayed after logging in
def student_menu():
print("=" * 100)
print("Welcome! What would you like to do today?")
print("Press 1: To Play our new Resume Prep Quiz")
print("Press 2: To See your Score")
print("Press 3: Logout")
# we create an administrator menu that is displayed after logging in
def admin_menu():
print("=" * 100)
print("Welcome! What would you like to do today?")
print("Press 1: To Add a new Question")
print("Press 2: To Add a new Administrator")
print("Press 3: To Remove a User")
print("Press 4: To Search for a particular user to see their progress")
print("Press 5: To rank students by scores")
print("Press 6: Logout")
print("=" * 100)
print("Welcome to the ALU Career Readiness App\nWe are excited to be part of your journey as you further your career!!")
print("=" * 100)
main_menu()
choice = input("What number do you choose?").lower()
if choice == "1" or choice == "one":
user = sign_up()
elif choice == "2" or choice == "two":
user = login()
else:
sys.exit()
while (user != None):
if user.userClassification == "student" or user.userClassification == "Student":
student_menu()
option = input("What number do you choose?").lower()
if option == "1" or option == "one":
newQuiz = Quiz()
newQuiz.root.mainloop()
user.update_student_score(newQuiz.score)
user.save_student_data({"score" : user.score})
elif option == "2" or option == "two":
print("Your score is: {}".format(user.score))
else:
break
else:
admin_menu()
option = input("What number do you choose?").lower()
if option == "1" or option == "one":
user.add_question()
elif option == "2" or option == "two":
user.add_new_administrator()
elif option == "3" or option == "three":
user.remove_user()
elif option == "4" or option == "four":
get_the_user()
elif option == "5" or option == "five":
from users.sort.sortingandranking import *
else:
print("Thank you!")
break
main_menu()
print("\n")
print("Thanks for checking in and working on your career readiness!")
print("=" * 100)
|
407873321bdfe992b7ff8a86b323e9ae837ff504 | akaprosy/Miscellaneous-Hydraulic-tools-using-Python | /listcomprehensions.py | 651 | 3.640625 | 4 |
#Horsepower using list comprehensions
'''pressure = [value for value in range(100,3000,100)]
flow = [value for value in range(5,100,10)]
for i in flow:
for j in pressure:
hp = round((i*j)/1714)
print(f'Flow: {i} gpm, Pressure: {j} psi, Horsepower: {hp}')'''
#Torque lbs-ft given rpm and horsepower
hp = [.25,.33,.5,.75,1,1.5,2,3,5,7.5,10,15,20,25,30,40,50,60,75,100,125,150,200,250]
rpm = [100,500,750,1000,1200,1500,1800,2400,3000,3600]
for i in hp:
for j in rpm:
torque = round((i*5252)/j,2)
print(f'Horsepower = {i} hp | rpm = {j} rpm | Torque = {torque} lbs-ft')
|
64d7d72990c223ea8a483120756a424195b2be54 | jolllof/bb_to_canvas_migration | /BlackboardLogin.py | 1,695 | 3.53125 | 4 | """time module is used to put pauses between each selenium action
as the website sometimes take a second to load"""
import time
from selenium import webdriver
class BlackboardLogin:
"""this class opens up firefox and logs into Blackboard Admin site"""
def __init__(self, username, password, site):
"""init method intializes all variables to be used in this class"""
self._username = username
self._password = password
self._urls = {'prod': 'https://learnadmin.liberty.edu',
'test': 'https://bbtestadmin.liberty.edu'}
self._site = self._urls[site]
self._browser = webdriver.Firefox()
self._cookies = None
def bblogin(self):
"""this is the actual method that performs the log in process"""
self._browser.get(self._site)
time.sleep(1)
self._browser.find_element_by_id("agree_button").click()
self._browser.find_element_by_id("user_id").send_keys(self._username)
self._browser.find_element_by_id("password").send_keys(self._password)
time.sleep(1)
self._browser.find_element_by_id("entry-login").click()
time.sleep(1)
def cookie_sesh(self):
"""this method stores cookie session in property for future usage"""
self._cookies = self._browser.get_cookies()
@property
def site(self):
"""this property is used to store the site url"""
return self._site
@property
def cookies(self):
"""this property is intended to be used to keep cookie
session open for other methods to implement"""
return self._cookies
|
14792c76f72fb72f811c3dfba25a4ce9953d3abb | tjshamhu/game-of-life | /game.py | 2,286 | 3.515625 | 4 | class Cell:
next_state = None
def __init__(self, state='-'):
self.state = state
def evolve(self):
if not self.next_state:
return
self.state = self.next_state
self.next_state = None
def start(coords, runs):
x_min = min([i[0] for i in coords])
x_max = max([i[0] for i in coords])
y_min = min([i[1] for i in coords])
y_max = max([i[1] for i in coords])
x_items = 10
y_items = 10
board = [[Cell() for _ in range(x_items)] for _ in range(y_items)]
def get_neighbours(x, y):
def get_neighbour(_x, _y):
try:
return board[_y][_x]
except IndexError:
return None
n = []
neighbour_positions = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1), (x + 1, y + 1), (x - 1, y + 1),
(x - 1, y - 1), (x + 1, y - 1)]
for position in neighbour_positions:
neighbour = get_neighbour(position[0], position[1])
if position[0] >= 0 and position[1] >= 0 and neighbour:
n.append(neighbour)
return n
def print_board():
for _row in board[::-1]:
print(' '.join([c.state for c in _row]))
print('==========================================')
for coord in coords:
board[coord[1]][coord[0]].state = '*'
print('INITIAL')
print_board()
for _ in range(runs):
for y_idx, row in enumerate(board):
for x_idx, cell in enumerate(row):
neighbours = get_neighbours(x_idx, y_idx)
live_neighbours = [n for n in neighbours if n.state == '*']
if cell.state == '*' and len(live_neighbours) < 2:
cell.next_state = '-'
if cell.state == '*' and (len(live_neighbours) == 2 or len(live_neighbours) == 3):
cell.next_state = '*'
if cell.state == '*' and len(live_neighbours) > 3:
cell.next_state = '-'
if cell.state == '-' and len(live_neighbours) == 3:
cell.next_state = '*'
for row in board:
for cell in row:
cell.evolve()
print_board()
start([(3, 3), (4, 3), (4, 2)], 10)
|
4b715877e24c3b1c5964625d40c54fcdad08d81c | sungjoonhh/leetcode | /7_reverse_integer.py | 682 | 3.890625 | 4 | # Definition for singly-linked list.
class Solution:
def reverse(self, x: int) -> int:
num = 0
if x>=0 :
while x > 0:
num = int(num*10) + int((x%10))
x = int(x/10)
return 0 if num > int(pow(2,31)) else num
else :
x = x*-1
while x > 0:
num = int(num*10) + int((x%10))
x = int(x/10)
return 0 if num <pow(2,31) else num*-1
def main():
sol = Solution()
print(sol.reverse(1534236469))
print(pow(2,31))
if __name__ == "__main__":
# execute only if run as a script
main() |
b9386f91d02719835878a87d51535fe3c2f57018 | akatkar/python-training-examples | /day3/Rational.py | 928 | 3.734375 | 4 | class Rational:
counter = 0
def __init__(self,a,b):
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
cd = gcd(a,b)
self.a = a // cd
self.b = b // cd
Rational.counter += 1
def __add__(self, other):
a = self.a * other.b + other.a * self.b
b = self.b * other.b
return Rational(a, b)
def __sub__(self, other):
a = self.a * other.b - other.a * self.b
b = self.b * other.b
return Rational(a, b)
def __mul__(self, other):
a = self.a * other.a
b = self.b * other.b
return Rational(a, b)
def __invert__(self):
return Rational(self.b, self.a)
def __truediv__(self, other):
return self * ~other
def __floordiv__(self, other):
return self / other
def __str__(self):
return '{}/{}'.format(self.a, self.b)
|
bdb5d75b1c10dc1c9101468bdff355f91b4a0196 | akatkar/python-training-examples | /day4/02_BeautifulSoup/ex01_simpletable.py | 496 | 3.546875 | 4 | from bs4 import BeautifulSoup
with open("simpletable.html") as fp:
bs = BeautifulSoup(fp,"html.parser")
print(bs.title)
print(bs.title.text)
table = bs.find('table', "Simple Table")
# using iteration
# data = []
# for row in table.find_all("tr"):
# for col in row.find_all("td"):
# data.append(col.string.strip())
# print(data)
# using list comprehension
data = [col.string.strip() for row in table.find_all("tr") for col in row.find_all("td")]
print('Simple Table:', data)
|
3886f317fe8006f8b66b1e4e938e3edb1aa07e82 | akatkar/python-training-examples | /day1/example_02.py | 462 | 3.796875 | 4 | def x(a):
return a ** 3
a = 3
b = x(3)
print(f"{a}^3 = {b}")
def isPrime(n):
if n < 2:
return False
for i in range(2,n):
if n % i == 0:
return False
return True
print(-2, isPrime(-2))
print(10, isPrime(10))
primes = []
for i in range(100):
if isPrime(i):
primes.append(i)
print(primes)
def isPalindrome(n):
s = str(n)
return s == s[::-1]
print(isPalindrome(1234))
print(isPalindrome(12321))
|
01bb8c5920bc90d5250543a0fddd34625c322181 | akatkar/python-training-examples | /day3/class1.py | 175 | 3.84375 | 4 | # why do we need a class?
# Let's assume that we have to calculate rational numbers
a = 1
b = 2
c = 1
d = 3
e = a * d + c * b
f = b * d
print(f'{a}/{b} + {c}/{d} = {e}/{f} ') |
5e8dd2be609a00bbc9b39db690a55528f11284b9 | Rishabh450/PythonAutomation | /convertWeight.py | 204 | 3.640625 | 4 | weight = input('Enter Weight')
choice = input('(k) for killgram (p) for pounds')
if choice == 'k':
print(f'Weight in Pounds : {float(weight)*10}\n')
else:
print(f'Weight in Kg :{float(weight)*3}') |
dab19715b792e3874a5468b4af6eb79184b673e8 | Rishabh450/PythonAutomation | /removedublicate.py | 150 | 3.828125 | 4 | numbers = set([4, 2, 6, 4, 6, 3, 2])
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)
|
c1b7ca7425fe164c693e91e5deec6811adb7941a | NITIN-ME/Python-Algorithms | /Stack.py | 1,273 | 3.796875 | 4 | class Empty(Exception):
def __init__(self, message):
print(message)
class ArrayStack:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, e):
self._data.append(e)
def top(self):
try:
if(self.is_empty()):
raise Empty("Stack is empty")
return self._data[-1]
except Empty as e:
pass
def pop(self):
try:
if(self.is_empty()):
raise Empty("Stack is empty")
return self._data.pop()
except Empty as e:
pass
S = ArrayStack( ) # contents: [ ]
print(S.top())
S.push(5) # contents: [5]
S.push(3) # contents: [5, 3]
print(len(S)) # contents: [5, 3]; outputs 2
print(S.pop( )) # contents: [5]; outputs 3
print(S.is_empty()) # contents: [5]; outputs False
print(S.pop( )) # contents: [ ]; outputs 5
print(S.is_empty()) # contents: [ ]; outputs True
S.push(7) # contents: [7]
S.push(9) # contents: [7, 9]
print(S.top( )) # contents: [7, 9]; outputs 9
S.push(4) # contents: [7, 9, 4]
print(len(S)) # contents: [7, 9, 4]; outputs 3
print(S.pop( )) # contents: [7, 9]; outputs 4
S.push(6) # contents: [7, 9, 6]
print(S.top()) # contents: [7, 9, 6]; outputs 6
S.push(7) # contents: [7, 9, 6, 7]
print(len(S)) # contents: [7, 9, 6, 7]; outputs 4
|
9ee9da2e9502457358d27482a9273d3ebd27ed71 | NITIN-ME/Python-Algorithms | /closest_points.py | 1,673 | 3.78125 | 4 | from math import sqrt
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(" + str(self.x)+", "+str(self.y)+")"
def compareX(a, b):
return a.x - b.x
def compareY(a, b):
return a.y - b.y
def distance(a, b):
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y) * (a.y - b.y))
def bruteForce(arr ,n):
min = 9999999
for k in range(n):
for j in range(k+1,n):
s = distance(arr[k], arr[j])
if s < min:
min = s
return min
def min(x, y):
if x < y:
return x
else:
return y
def stripClosest(strip, d):
min = d
size = len(strip)
sortbyY(strip)
for i in range(size):
for j in range(i+1, size):
if abs(strip[i].y - strip[j].y) < min:
if(distance(strip[i], strip[j]) < min):
min = distance(strip[i], strip[j])
return min
def closestUtil(p):
n = len(p)
if(n <= 3):
return bruteForce(p, n)
mid = n // 2
midpoint = p[mid]
dl = closestUtil(p[0:mid])
dr = closestUtil(p[mid+1:n+1])
d = min(dl, dr)
strip = []
for k in range(n):
if(abs(p[k].x - midpoint.x) < d):
strip.append(p[k])
return min(d, stripClosest(strip, d))
def closest(p):
sortbyX(p)
return closestUtil(p)
def getkeyX(item):
return item.x
def getkeyY(item):
return item.y
def sortbyX(p):
return sorted(p, key = getkeyX)
def sortbyY(p):
return sorted(p, key = getkeyY)
def show(p):
for k in p:
print(k, end = " ")
print()
a = Point(2,3)
b = Point(12,30)
c = Point(40,50)
d = Point(5,1)
e = Point(12,10)
f = Point(3,4)
g = Point(3,5)
arr = [a,b,c,g,d,e,f]
arr1 = [a,b,c,d,e,f]
print(closest(arr))
print(closest(arr1))
"""
print(bruteForce(arr, len(arr)))
print(distance(p, q))
print(abs(-5))
"""
|
bc97f24ba8f725bfc6f0003a3efaea20efdce5b0 | NITIN-ME/Python-Algorithms | /linked.py | 1,427 | 3.953125 | 4 | """
use __slots__
__init__
__len__
is_empty
push
top
pop
"""
class Empty(Exception):
def __init__(self, message):
print(message)
class LinkedStack:
class _Node:
__slots__ = '_element', '_next'
def __init__(self, element, next):
self._element = element
self._next = next
def __init__(self):
self._head = None
self._size = 0
def __len__(self):
return self._size
def is_empty(self):
return self._size == 0
def push(self, e):
self._head = self._Node(e, self._head)
self._size += 1
def top(self):
try:
if(self._size == 0):
raise Empty("Stack is empty")
result = self._head._element
return result
except Empty as e:
pass
def pop(self):
try:
if(self._size == 0):
raise Empty("Stack is empty")
answer = self._head._element
self._head = self._head._next
self._size -= 1
return answer
except Empty as e:
pass
l = LinkedStack()
print(l.top())
print(l.pop())
l.push(5)
l.push(7)
l.push(8)
l.push(9)
l.push(10)
print("Size is: ", end = "")
print(len(l))
print(l.top())
print(l.pop())
print("Size is: ", end = "")
print(len(l))
print(l.top())
print(l.pop())
print("Size is: ", end = "")
print(len(l))
print(l.top())
print(l.pop())
print("Size is: ", end = "")
print(len(l))
print(l.top())
print(l.pop())
print("Size is: ", end = "")
print(len(l))
print(l.top())
print(l.pop())
print("Size is: ", end = "")
print(len(l))
print(l.top())
print(l.pop())
|
863f2333082729f83a086ccbb135540df142d132 | DanisHack/stampify | /data_models/website.py | 1,781 | 3.96875 | 4 | """This script creates a class to store
information about to a website"""
from urllib.parse import urlparse
from utils import url_utils
class Website:
"""This class stores the information about a website"""
__LOGO_API = 'https://logo.clearbit.com/'
__LOGO_SIZE = 24
def __init__(self, url):
self.url = url_utils.valid_url(url)
self.is_valid = bool(self.url)
self.domain = urlparse(self.url)[1] if self.is_valid else None
self.logo_url = '{}{}?size={}'.format(self.__LOGO_API,
self.domain,
self.__LOGO_SIZE) \
if self.domain else None
self.contents = None
def set_contents(self, contents):
"""Sets the value for contents"""
self.contents = contents
def convert_to_dict(self):
"""This is custom method to convert the Website
object to dictionary"""
# It will store dictionary representation of Website object
formatted_website = dict()
for key, value in self.__dict__.items():
if key == 'contents':
# Using custom object to dict conversion method to convert
# the Contents object to dictionary
formatted_website[key] = value.convert_to_dict()
else:
formatted_website[key] = value
return formatted_website
def get_title(self):
"""Returns the title of the provided webpage"""
content_list = self.contents.content_list
if not (content_list
and content_list[0].content_type.name == 'TEXT'
and content_list[0].type == 'title'):
return ''
return content_list[0].text_string
|
c96f018296422b1a219700ee9511f5fa3ead8614 | shuchenliu/doch_backend | /resources/tweetify.py | 6,145 | 3.59375 | 4 | '''
note:
1, Query in the databse if we stored this user before
2.a, If not, we grab tweets from last 7 days as usual,
2.b, If so, we query the date of the last tweets we store.
- if it is still within 7 days, we used it as the since_id
- if it is beyond 7 days range, we go back to 2.a
side note:
1, Consider letting the server to grab Trump's tweets every 10 minutes
2, Front-end should by default be set to Trump's tweets
it's should be up to the front-end to decide whether to keep re-tweeted in rendering
'''
import tweepy
import urllib.request
from datetime import datetime
from datetime import date, timedelta
from pytz import timezone
class Tweetify:
#OAuth
#TODO use environmental variables to store tokens & secrets
consumer_key="bYY1Bao6iZtwfUYunWsmx8BZD"
consumer_secret="4vbM4TTSlpBRuo35vsxSWE7JAqlqbYTAm9oFsepzZO4fRBNVLs"
access_token="733766645676670976-vvutEKaHcXYKbul2aK9iqEXDPiog2Ek"
access_token_secret="da3m8JXpSYEwubwPwv2GKysfvZpB0OIa3R3YCcjMPi7Yf"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
def __init__(self, screen_name, end_date, sid, time_now):
'''
end date needs to be a datetime object
'''
self.user = None
self.screen_name = screen_name
self.end_date = end_date
self.sid = sid
self.new_sid = sid
self.mid = 0
self.user_id = self.get_user_id(screen_name)
if self.user_id == "-1":
self.result = {"error" : "user does not exist"}
else:
self.result = {
"error" : None,
"tweets" : self.tweets_json(),
"user" : [self.user_json(self.user, time_now)],
}
@classmethod
def get_status(self, id):
try:
return self.api.get_status(id)
except:
return -1
def get_user_id(self, screen_name):
try:
self.user = self.api.get_user(screen_name = screen_name)
if self.user.status:
self.mid = self.user.status.id
return self.user.id_str
except:
return str(-1)
def tweets_json(self):
statuses = self.grab_tweets()
if statuses:
self.new_sid = statuses[0].id_str
return statuses
'''
json_list = []
for status in statuses:
json_list.append(status._json)
if json_list:
self.new_sid = json_list[0]["id_str"]
return json_list
'''
def user_json(self, user, time_now):
json_dict = {}
json_dict["id"] = user.id_str
json_dict["screenName"] = user.screen_name
json_dict["insensitiveName"] = json_dict["screenName"].lower()
json_dict["name"] = user.name
json_dict["createdAt"] = timezone('UTC').localize(user.created_at).astimezone(tz = timezone("US/Eastern"))
json_dict["description"] = user.description
json_dict["followers"] = user.followers_count
json_dict["friends"] = user.friends_count
json_dict["statusCount"] = user.statuses_count
json_dict["favCount"] = user.favourites_count
json_dict["location"] = user.location
json_dict["isVerified"] = user.verified
avatarUrl = user.profile_image_url.replace('normal', '400x400')
#print(user.profile_image_url)
json_dict["avatarUrl"] = avatarUrl
try:
json_dict["bannerUrl"] = user.profile_banner_url
self.save_pic('banner', json_dict["id"], json_dict["bannerUrl"])
except:
json_dict["bannerUrl"] = None
try:
json_dict["webUrl"] = user.entities["url"]["urls"][0]["expanded_url"]
except:
try:
json_dict["webUrl"] = user.entities["url"]["urls"][0]["url"]
except:
json_dict["webUrl"] = None
self.save_pic('avatar', json_dict["id"], json_dict["avatarUrl"])
json_dict["lastCheckedTime"] = time_now
json_dict["lastUpdatedTime"] = time_now
json_dict["lastTweetId"] = self.new_sid
return json_dict
def save_pic(self, flag, id, url):
filename = "static/img/{}/{}.png".format(flag, id)
f = open(filename, "wb")
f.write(urllib.request.urlopen(url).read())
f.close()
def grab_tweets(self):
status_list = []
if not self.user.status or self.user.status == self.sid:
return status_list
max_id = self.mid
while True:
statuses = self.api.user_timeline(user_id = self.user_id, max_id = max_id, tweet_mode = "extended")
#print(len(statuses))
if statuses:
if self.judging(statuses[-1]):
status_list += statuses
max_id = status_list[-1].id - 1
else:
for s in statuses:
if self.judging(s):
status_list.append(s)
else:
break
break
else:
break
return status_list
def judging(self, status):
if self.sid == "-1":
create_time = timezone('UTC').localize(status.created_at).astimezone(tz = timezone("US/Eastern")).date()
return create_time >= self.end_date.date()
else:
return status.id > int(self.sid)
@classmethod
def update_list(self, user_id, since_id):
page = 0
tweets = []
while True:
current_page = self.api.user_timeline(id=user_id, since_id=since_id, page=page)
print('ok {}'.format(len(current_page)))
if len(current_page) == 0 :
break
tweets += current_page
page += 1
print('doki {}'.format(len(tweets)))
tweet_info = {}
for t in tweets:
id = t.id_str
tweet_info[id] = {
"fav": t.favorite_count,
"rt" : t.retweet_count,
}
return tweet_info
|
53a85cca879f97c96ac4e2bcbb0175ce6ef03894 | JohnTalamo/Python-training | /app.py | 163 | 3.75 | 4 | name = "John"
print(len(name))
len(name)
fname = "John"
lname = "Talamo"
full = fname + " " + lname
print(full)
print(len(full))
name = "bazinga"
print(name[2:6])
|
Subsets and Splits