blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1c44d808df7fc717f16ed5a27bf8c6104b8fc4c2 | thejacobhardman/Rock-Paper-Scissors | /Game.py | 11,519 | 3.84375 | 4 | # Jacob Hardman
# Intro To Programming
# Professor Marcus Longwell
# 3/27/19
# Python Version 3.7.3
# Look up Coding Colorado
# Importing pkgs
import os
import random
# Clears the screen
def cls():
os.system('cls' if os.name=='nt' else 'clear')
########################################################## GLOBAL VARIABLES ##############################################################
# Tracks if the program is still running
Is_Running = True
# Stores the User's input
User_Input = ""
# Tracks if the User has made a decision
User_Confirm = False
# Tracks if the Player is still playing the selected game mode
Still_Playing = False
# Stores what moves the players can choose from for the vanilla game
Choices = ["Rock", "Paper", "Scissors"]
# Stores what moves the players can choose from for the expanded game
Exp_Choices = ["Rock", "Paper", "Scissors", "Lizard", "Spock"]
# Stores what the player decides to play
Player_Choice = 0
# Stores what the Computer decides to play
Computer_Choice = 0
# Tracks the score of each player
Player_Score = 0
Computer_Score = 0
############################################################ PROGRAM LOGIC ###############################################################
### Standard Rock Paper Scissors
def Vanilla_Game():
# Importing global variables
global User_Input
global Choices
global Player_Choice
global Computer_Choice
global Player_Score
global Computer_Score
Still_Playing = True
while Still_Playing == True:
# The player chooses what to play
while User_Confirm == False:
# Clearing the screen for readability
cls()
User_Input = input("Enter '1' for Rock, '2' for Paper, or '3' for Scissors: ")
if str(User_Input) == "1":
Player_Choice = Choices[0]
break
elif str(User_Input) == "2":
Player_Choice = Choices[1]
break
elif str(User_Input) == "3":
Player_Choice = Choices[2]
break
else:
print("\nPlease enter a valid selection.")
# Generating the computer's move
Computer_Choice = Choices[random.randint(0,2)]
print("\nPlayer: " + Player_Choice + " <--- ---> " + Computer_Choice + " :Computer")
# Calculating who won the game
if Player_Choice.upper() == "ROCK" and Computer_Choice.upper() == "SCISSORS":
print("\nPlayer's " + Player_Choice + " beats Computer's " + Computer_Choice + "!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
elif Player_Choice.upper() == "SCISSORS" and Computer_Choice.upper() == "PAPER":
print("\nPlayer's " + Player_Choice + " beats Computer's " + Computer_Choice + "!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
elif Player_Choice.upper() == "PAPER" and Computer_Choice.upper() == "ROCK":
print("\nPlayer's " + Player_Choice + " beats Computer's " + Computer_Choice + "!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
elif Player_Choice == Computer_Choice:
print("Both the Player and the Computer played " + Player_Choice + "!")
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
else:
print("\nComputer's " + Computer_Choice + " beats Player's " + Player_Choice + "!")
Computer_Score = Computer_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
while User_Confirm == False:
User_Input = input("\nWould you like to play again? (y/n): ")
if User_Input.upper() == "Y":
break
elif User_Input.upper() == "N":
Player_Score = 0
Computer_Score = 0
Still_Playing = False
break
else:
print("Please enter a valid selection.")
# DEBUG
# print(Player_Choice)
# print(Computer_Choice)
# input("\nPress 'enter' to continue.")
### Rock Paper Scissors Lizard Spock
def Expanded_Game():
# Importing global variables
global User_Input
global Exp_Choices
global Player_Choice
global Computer_Choice
global Player_Score
global Computer_Score
Still_Playing = True
while Still_Playing == True:
# The player chooses what to play
while User_Confirm == False:
# Clearing the screen for readability
cls()
User_Input = input("Enter '1' for Rock, '2' for Paper, or '3' for Scissors, or '4' for Lizard, or '5' for Spock: ")
if str(User_Input) == "1":
Player_Choice = Exp_Choices[0]
break
elif str(User_Input) == "2":
Player_Choice = Exp_Choices[1]
break
elif str(User_Input) == "3":
Player_Choice = Exp_Choices[2]
break
elif str(User_Input) == "4":
Player_Choice = Exp_Choices[3]
break
elif str(User_Input) == "5":
Player_Choice = Exp_Choices[4]
break
else:
print("\nPlease enter a valid selection.")
# Generating the computer's move
Computer_Choice = Exp_Choices[random.randint(0,4)]
print("\nPlayer: " + Player_Choice + " <--- ---> " + Computer_Choice + " :Computer")
# Calculating who won the game
# Rock crushes scissors
if Player_Choice.upper() == "ROCK" and Computer_Choice.upper() == "SCISSORS":
print("\nPlayer's Rock crushes Computer's Scissors!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
# Scissors cuts paper
elif Player_Choice.upper() == "SCISSORS" and Computer_Choice.upper() == "PAPER":
print("\nPlayer's Scissors cuts Computer's Paper!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
# Paper covers rock
elif Player_Choice.upper() == "PAPER" and Computer_Choice.upper() == "ROCK":
print("\nPlayer's Paper covers Computer's Rock!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
# Rock crushes lizard
elif Player_Choice.upper() == "ROCK" and Computer_Choice.upper() == "LIZARD":
print("\nPlayer's Rock crushes Computer's Lizard!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
# Lizard poisons Spock
elif Player_Choice.upper() == "LIZARD" and Computer_Choice.upper() == "SPOCK":
print("\nPlayer's Lizard poisons Computer's Spock!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
# Spock smashes scissors
elif Player_Choice.upper() == "SPOCK" and Computer_Choice.upper() == "SCISSORS":
print("\nPlayer's Spock smashes Computer's Scissors!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
# Scissors decapitates lizard
elif Player_Choice.upper() == "Scissors" and Computer_Choice.upper() == "LIZARD":
print("\nPlayer's Scissors decapitates Computer's Lizard!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
# Lizard eats paper
elif Player_Choice.upper() == "LIZARD" and Computer_Choice.upper() == "PAPER":
print("\nPlayer's Lizard eats Computer's Paper!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
# Paper disproves Spock
elif Player_Choice.upper() == "PAPER" and Computer_Choice.upper() == "SPOCK":
print("\nPlayer's Paper disproves Computer's Spock!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
# Spock vaporizes Rock
elif Player_Choice.upper() == "SPOCK" and Computer_Choice.upper() == "ROCK":
print("\nPlayer's Spock vaporizes Computer's Rock!")
Player_Score = Player_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
# Tie game
elif Player_Choice == Computer_Choice:
print("Both the Player and the Computer played " + Player_Choice + "!")
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
# Computer wins
else:
print("\nComputer's " + Computer_Choice + " beats Player's " + Player_Choice + "!")
Computer_Score = Computer_Score + 1
print("Player's Score: " + str(Player_Score) + "\nComputer's Score: " + str(Computer_Score))
while User_Confirm == False:
User_Input = input("\nWould you like to play again? (y/n): ")
if User_Input.upper() == "Y":
break
elif User_Input.upper() == "N":
Player_Score = 0
Computer_Score = 0
Still_Playing = False
break
else:
print("Please enter a valid selection.")
# DEBUG
# print(Player_Choice)
# print(Computer_Choice)
# input("\nPress 'enter' to continue.")
############################################################ PROGRAM FLOW ################################################################
while Is_Running == True:
while User_Confirm == False:
# Clearing the screen for readability
cls()
print("ROCK! PAPER! SCISSORS!")
User_Input = input("""\nEnter '1' to play standard Rock Paper Scissors
Enter '2' to play Rock Paper Scissors Lizard Spock
Enter '3' to quit the game: """)
if str(User_Input) == "1":
Vanilla_Game()
elif str(User_Input) == "2":
Expanded_Game()
elif str(User_Input) == "3":
while User_Confirm == False:
User_Input = input("\nAre you sure you want to quit the game? (y/n): ")
if User_Input.upper() == "Y":
Is_Running = False
User_Confirm = True
break
elif User_Input.upper() == "N":
break
else:
print("\nPlease enter a valid selection.")
input("Press 'enter' to continue.")
else:
print("\nPlease enter a valid selection.")
input("Press 'enter' to continue.")
|
d157aec623b861fcdaa73445b12817575e7bbf9f | cbarillas/Python-Biology | /lab02/coordinateMathSoln.py | 2,550 | 4.25 | 4 | #/usr/bin/env python3
# Name: Carlos Barillas (cbarilla)
# Group Members: none
from math import *
class Triad:
"""
This class calculates angles and distances among a triad of points.
Points can be supplied in any dimensional space as long as they are
consistent.
Points are supplied as tupels in n-dimensions, and there should be
three
of those to make the triad. Each point is positionally named as p,q,r
and the corresponding angles are then angleP, angleQ and angleR.
Distances are given by dPQ(), dPR() and dQR()
Required Modules: math
initialized: 3 positional tuples representing Points in n-space
p1 = Triad( p=(1,0,0), q=(0,0,0), r=(0,1,0) )
attributes: p,q,r the 3 tuples representing points in N-space
methods: angleQ() angles measured in degrees
dPQ(), dQR() distances in the same units of p,q,r
"""
def __init__(self, p, q, r):
""" Construct a Triad.
p1 = Triad(p=(1,0,0), q=(0,0,0), r=(0,0,0)).
"""
self.p = p
self.q = q
self.r = r
# Private helper methods.
def d2(self, a, b):
"""Calculate squared distance of point a to b."""
return float(sum((ia-ib)*(ia-ib) for ia, ib in zip (a, b)))
def ndot(self, a, b, c):
"""Dot Product of vector a, c standardized to b."""
return float(sum((ia-ib)*(ic-ib) for ia, ib, ic in zip (a, b, c)))
# Calculate lengths(distances) of segments PQ and QR.
def dPQ(self):
"""Provides the distance between point p and point q."""
return sqrt(self.d2(self.p, self.q))
def dQR(self):
"""Provides the distance between point q and point r."""
return sqrt(self.d2(self.q, self.r))
# Calculates the angles in degrees for angleQ
def angleQ(self):
"""Provides the angle made at point q by segments qp and qr
(degrees).
"""
return acos(self.ndot(self.p, self.q, self.r) /
sqrt(self.d2(self.p, self.q)*self.d2(self.r, self.q))) * 180/pi
coordinates = input("Enter three sets of atomic coordinates: \n")
leftP = coordinates.replace('(', ',')
rightP = leftP.replace (')', ',')
myList = rightP.split (',')
p = (float(myList[1]), float(myList[2]), float(myList[3]))
q = (float(myList[5]), float(myList[6]), float(myList[7]))
r = (float(myList[9]), float(myList[10]), float(myList[11]))
triad = Triad(p, q, r)
print('N-C bond length = {0:.2f} \nN-Ca bond length = {1:.2f} \nC-N-Ca bond' \
' angle = {2:.1f}'.format(triad.dPQ(), triad.dQR(), triad.angleQ()))
|
2da68ad98a6a06111ce78866dcc3422e850b07b4 | Jeramir1/python_projects | /tktest.py | 1,508 | 3.59375 | 4 | from tkinter import *
import webbrowser
from pytube import YouTube
def download():
linkfordl = str(link_field.get())
print(linkfordl)
yt = YouTube(linkfordl)
#Showing details
button = Button(new, text='Downloading',fg='Black',bg='Blue',command=())
button.grid(row=6, column=1)
print("Title: ",yt.title)
print("Number of views: ",yt.views)
print("Length of video: ",yt.length)
print("Rating of video: ",yt.rating)
#Getting the highest resolution possible
ys = yt.streams.get_highest_resolution()
#Starting download
print("Downloading...")
ys.download()
print("Download completed!!")
button = Button(new, text='Download complete',fg='Black',bg='Blue',command=(download))
button.grid(row=6, column=1)
fileoutput = Label(new, text = yt.title, fg ='Blue', bg = 'gray', font=("times", 12), cursor="hand2")#archivo generado
fileoutput.grid(row=7, column=1) #file output generado por el downloader
if __name__=='__main__':
new = Tk()
new.config(background='grey')
new.title("Youtube Downloader")
new.geometry("350x240")
ytlink = Label(new, text="Youtube Downloader",bg='grey',font=("times", 28, "bold"))
#text box for year input
link_field=Entry(new)
button = Button(new, text='Download Video',fg='Black',bg='Blue',command=download)
#adjusting widgets in position
ytlink.grid(row=2, column=1) #nombre del programa
link_field.grid(row=3, column=1)
button.grid(row=6, column=1)
new.mainloop() |
79e608419942dba075b9305cb81b538ef54e0ac7 | wintermute-cds/round | /integrationtests/create.py | 230 | 3.75 | 4 | from decimal import *
min = Decimal('-10.0')
max = Decimal('10.0')
step = Decimal('0.0001')
places = 3
current = min
while current <= max:
print('{0} {1}'.format(current, round(current, places)))
current = current + step |
2e65fcb903a06c8909575d22b5943fe03ee7f2ec | ecmarsh/algorithms-py | /rob_max_money_2.py | 2,197 | 3.71875 | 4 | """
213. House Robber II
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed. All houses at this
place are arranged in a circle. That means the first house is the neighbor
of the last one. Meanwhile, adjacent houses have security system connected
and it will automatically contact the police if two adjacent houses were
broken into on the same night.
Given a list of non-negative integers representing the amount of money
of each house, determine the maximum amount of money you can rob tonight
without alerting the police.
Example 1:
Input: [2,3,2]
Output: 3
Explanation: House 0 and house 2 are adjacent, so cannot rob both.
Example 2:
Input: [1,2,3,1]
Output: 4
Explanation: Rob house 0 then house 2 for 1 + 3 = 4.
"""
class Solution:
def rob(self, nums: List[int]) -> int:
"""
Same as House Robbers I, solved here:
https://github.com/ecmarsh/algorithms/blob/master/exercises/robMaxMoney.js
Except now we are constrained on robbing house 1 based on house n.
That is, we must break the circle by assuming a house isn't robbed.
To find out which one, we must try NOT robbing first 2 houses:
1) skip house[0], allowing us to rob house[-1], or
2) skip house[1], allowing us to rob house[-2]
We can use the same solution in house robbers 1, but restrict our range
The answer is, of course, is which 2 skips leads to the greater money.
Let n = len(nums), then:
T(n) = (n-2) + (n-2) = 2n-4 = O(n)
S(n) = O(1)
"""
# can only rob 1 house since 3 houses are all adjacent
if len(nums) <= 3:
nums.append(0) # handle no houses
return max(nums)
op1, op2 = 0, 0
# op1: house[0]..house[n-2]
n1, n2 = 0, nums[0]
for i in range(1, len(nums)-1):
n1, n2 = n2, max(n1 + nums[i], n2)
op1 = n2
# op2: house[1]..house[n-1]
n1, n2 = 0, nums[1]
for i in range(2, len(nums)):
n1, n2 = n2, max(n1 + nums[i], n2)
op2 = n2
return max([op1, op2])
|
ff3cf51d67d83b70c42b5355873387bf97168400 | kareemgamalmahmoud/python-automate-logo-on-photo | /logo_adder.py | 1,228 | 4.21875 | 4 | import os
from PIL import Image
# first we will take the name of the logo
# that the user want to add .
# then , take the name of the folder the we
# will add the photos after adding the logo .
LOGO_NAME = 'face.png' #input('enter the logo name with extention : ')
FOLDER_NAME = 'with logo image' #input('enter the folder name : ')
# get the informations of the logo ==>(width , height)
logo_image = Image.open(LOGO_NAME)
logo_width , logo_height = logo_image.size
# create the folder if it does not exist
if not( os.path.exists(FOLDER_NAME) ):
os.mkdir(FOLDER_NAME)
# loop over the images
# counter
count = 0
for filename in os.listdir('.'):
# check that the file is not logo
if not(filename.endswith('.png') or filename.endswith('.jpg') or filename == logo_image):
continue
img = Image.open(filename)
width, height = img.size
# add logo to the image
# there is a method called (paste) in pillow
# that make us to add the photo
img.paste(logo_image, (width - logo_width, height - logo_height))
# know let's save the image
img.save(os.path.join(FOLDER_NAME, filename))
count += 1
print(f'done image : {filename}')
print(f' {count} photos has been DONE') |
fa76ed9400b59ec392eb79fb694bd242b77c6514 | fto0sh/100DaysOfCode | /Day6.py | 546 | 3.765625 | 4 | Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> x = int(1) # x will be 1
>>> y = int(2.8) #y will b 2
>>> z = int("3") # z will be 3
>>> print(x ,y ,z)
1 2 3
>>> x = float(1) #x will be 1.0
>>> y = float(2.8) # y will be 2.8
>>> z = float("3") #z will be 3
>>> print(x ,y ,z)
1.0 2.8 3.0
>>> x = str("sl")
>>> y= str(2)
>>> z= str(3.0)
>>> print(x ,y ,z)
sl 2 3.0
>>> print(x)
sl
>>> print(y)
2
>>> y = str(2)
>>> print(y)
2
>>>
|
1f75110ebdadb66ca2590518582f1a33b7fe8b77 | mongoz/itstep | /lesson4/analyze_number.py | 465 | 4.15625 | 4 | a: int = int(input("Enter the integer number\n\t"))
if a % 2 == 0 and a > 0:
smile_parity = "Even positive number"
print(a, "is the", smile_parity)
elif a % 2 != 0 and a > 0:
smile_parity = "Odd positive number"
print(a, "is the", smile_parity)
elif a % 2 == 0:
smile_parity = "Even negative number"
print(a, "is the", smile_parity)
elif a % 2 != 0:
smile_parity = "Odd negative number"
print(a, "is the", smile_parity)
|
9c1c8b2a714eabc2d3e8229c1709403d91045615 | nickyfoto/lc | /python/204.count-primes.py | 3,032 | 3.84375 | 4 | #
# @lc app=leetcode id=204 lang=python3
#
# [204] Count Primes
#
# https://leetcode.com/problems/count-primes/description/
#
# algorithms
# Easy (28.73%)
# Total Accepted: 235.3K
# Total Submissions: 813K
# Testcase Example: '10'
#
# Count the number of prime numbers less than a non-negative number, n.
#
# Example:
#
#
# Input: 10
# Output: 4
# Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
#
#
#
class Solution:
# def countPrimes(self, n: int) -> int:
# def countPrimes(self, n):
# count = 0
# import math
# def is_prime(n):
# for i in range(3, int(math.sqrt(n)) + 1, 2):
# if n % i == 0:
# return False
# return True
# if n < 3:
# return 0
# if n == 3:
# return 1
# else:
# count = 1
# for i in range(3, n, 2):
# if is_prime(i):
# count += 1
# return count
def countPrimes(self, n):
count = 0
import math
if n < 3:
return 0
if n == 3:
return 1
else:
count = 0
def gen_primes():
""" Generate an infinite sequence of prime numbers.
"""
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long as required by the current
# number being tested.
#
D = {}
# The running integer that's checked for primeness
q = 2
while True:
if q not in D:
# q is a new prime.
# Yield it and mark its first multiple that isn't
# already marked in previous iterations
#
yield q
D[q * q] = [q]
else:
# q is composite. D[q] is the list of primes that
# divide it. Since we've reached q, we no longer
# need it in the map, but we'll mark the next
# multiples of its witnesses to prepare for larger
# numbers
#
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
for i in gen_primes():
if i < n:
count += 1
else:
break
return count
# s = Solution()
# n = 10
# print(s.countPrimes(n))
# print(s.countPrimes(n) == s.countPrimes2(n))
# import time
# start = time.time()
# print(s.countPrimes(1500000))
# end = time.time()
# print(end - start)
|
bdd095d2646c562f68b0accfbbd651b596b89bd7 | IrisJohn/Floor-Regression-Model1 | /Floor-Regression Mode-M5A.py | 3,964 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import warnings
warnings.simplefilter('ignore')
#plt.style.use('dark_background')
# In[2]:
data = pd.read_csv('Transformed_Housing_Data2.csv')
data.head()
# # Task:
# 1. To create a mean regression model based on "No of Floors" column and call it "floor_mean"
# 2. To compare the residual plots of overall "mean_sales" and "floor_mean".
# 3. To calculate the R-Square value for "floor_mean" model manually without using sklearn.
# ## 1. To create "floor_mean" column
# In[20]:
data['mean_sales'] = data['Sale_Price'].mean()
data['mean_sales'].head()
# In[21]:
## To check the unique values in column "No of Floors"
###### Start code ######
###### End code ######
data['No of Floors'].unique()
# ### Expected Output
#
#
# ```
# array([1. , 2. , 1.5, 3. , 2.5, 3.5])
# ```
#
# In[22]:
## Using pandas.pivot_table() to calculate the "floor_mean"
### Start code ###
floors_mean = None
floors_mean=df.pivot_table(values='Sale_Price',columns='No of Floors',aggfunc=np.mean)
floors_mean
# ### Expected Output
# <img src="images/image1.png">
# In[23]:
# making new column
data['floor_mean'] = 0
# for every unique floor_mean, fill its mean price in new column "floor_mean"
for i in floor_mean.columns:
### start code ###
data['floor_mean'][data['No of Floors']== i]=floors_mean[i][0]
### end code ###
data['floor_mean'].head()
# ## 2. To Compare Residual plots
# ### Expected Output
# <img src="images/image2.png">
# In[24]:
data['mean_sales']
# In[26]:
## Calculating residuals floor_mean_difference and mean_difference
### start code###
mean_difference=0
floor_mean_difference=0
mean_difference = data['mean_sales']-data['Sale_Price']
floor_mean_difference = data['floor_mean']-data['Sale_Price']
### end code ###
mean_difference.size, floor_mean_difference.size
# ### Expected Outcome
# <img src="images/image3.png">
# In[29]:
## Plotting the Residuals for comparison
k = range(0, len(data)) # for x axis
l = [0 for i in range(len(data))] # for regression line in residual plot
plt.figure( figsize = (15,6), dpi =100)
################## plot for Overall Mean ####################
plt.subplot(1,2,1)
plt.scatter(k,mean_difference,color='red',label='Residuals',s=2)
plt.plot(k,l,color='green',label='mean Regression',linewidth=3)
plt.xlabel('Fitted points')
plt.ylabel('Residuals wrt floor mean')
#code to create the residual of mean regression model along with regression line
### start code ###
### end code ###
plt.title('Residuals with respect to no of floors')
################## plot for Overall Mean ####################
plt.subplot(1,2,2)
#code to create the residual of floor mean regression model along with regression line
### start code ###
plt.scatter(k,floor_mean_difference,color='red',label='Residuals',s=2)
plt.plot(k,l,color='green',label='mean Regression',linewidth=3)
plt.xlabel('Fitted points')
plt.ylabel("Residuals")
plt.title("Residuals with respect to overall mean")
plt.legend()
plt.show()
# ### Expected Outcome
# <img src="images/image4.png">
# ## 3. To calculate $R^2$ value of the "floor_mean" model manually
# <img src="images/image5.png">
# In[31]:
## Calculate mean square error for overall mean regression model and call it MSE 1
from sklearn.metrics import mean_squared_error
y=data['Sale_Price']
yhat1=data['mean_sales']
yhat2=data['floor_mean']
### start code ###
MSE1 = mean_squared_error(yhat1,y)
### end code ###
## Calculate mean square error for floor mean regression model and call it MSE 2
### start code ###
MSE2 = mean_squared_error(yhat2,y)
### end code ###
## calculate R-Square value using the formula and call it R2
### start code ###
R2 = 1-(MSE2/MSE1)
### end code ###
R2
# ### Expected Outcome
# <img src="images/image6.png">
# In[ ]:
|
10b73f06c48cded9a9b7c5a8afdae237faa4a173 | Rodin2333/Algorithm | /剑指offer/42和为S的两个数字.py | 889 | 3.546875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
输入一个递增排序的数组和一个数字S,在数组中查找两个数,
使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
"""
class Solution:
def FindNumbersWithSum(self, array, tsum):
"""
:param array: 有序数组
:param tsum: 和
:return:
"""
left = 0
right = len(array) - 1
result = []
while left < right:
if array[left] + array[right] == tsum:
if not result or result[0] * result[1] > array[left] * array[right]:
result = [array[left], array[right]]
left += 1
right -= 1
elif array[left] + array[right] < tsum:
left += 1
else:
right -= 1
return result
|
85369103c51dce6aeca3ef8a715a965f18fd781f | BulavkinV/GVD | /Point.py | 251 | 3.609375 | 4 | class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def getPointsTuple(self):
return (self.x, self.y)
@staticmethod
def distance(cls, p1, p2):
return ((p1.x - p2.x)**2 + (p1.y-p2.y)**2)**.5 |
4f2f9ad63fd3eabe0b879ba7e8ce6159eff66344 | shcherbinushka/6115-preparation-for-the-credit-Python-3-semester | /12. Поиск максимума и подсчёт количества элементов, равных максимальному .py | 793 | 4.28125 | 4 | def max_search(): ### Программа ищет максимальный элемент в последовательности за один проход
x = -1 ### Текущий считываемый элемент
max_element = float('-inf') ### Текущий максимальный элемент
equal = 0 ### Колво элементов, не равных данному
while x !=0: ### Считываение идет до момента, пока x не будет равен 0
x = int(input())
if x > max_element:
max_element = x
equal = 1
elif x == max_element:
equal += 1
print(max_element, equal)
max_search() |
7a062102077d245d0bc58fc342c3510d0c54bd44 | Atramekes/Algorithms | /Recursion/Baguenaudier.py | 1,140 | 3.78125 | 4 | # !/usr/bin/python
# Algorithms
# @Author: Kortez
# @Email: 595976736@qq.com
import sys
import test_Recursion
outputs = []
def flip(seq, func):
""" Process a one/zero sequence seq according to func.
@param seq (list[int]): the unprocessed sequence
@param func (int): to do which function
@returns ~ (designed by yourself)
"""
### TODO - calculate the processed_seq according to func
### YOUR CODE HERE (optional)
### END YOUR CODE
def Baguenaudier(n):
""" Solve Baguenaudier problem.
@params n (int): dimension of the problem
@returns solution (list[int]): the list of functions to solve the problem
"""
### TODO - finish the function to Baguenaudier Hanoi problem
### YOUR CODE HERE
### END YOUR CODE
return solution
def run():
### finish this function to see your outputs (optional)
### use flip() (optional)
return
if __name__ == '__main__':
args = sys.argv[1]
if args == "run":
run()
elif args == "test":
test_Recursion.test_Baguenaudier()
else:
raise RuntimeError('invalid run mode')
|
ae12ae8eb2eab5ce1fa11423f2e76e172a393d46 | brdayauon/interviewPreparation | /symmetricTreeRecursive.py | 689 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
return self.isMirror(root,root)
def isMirror(self, p: TreeNode, q: TreeNode):
if p == None and q == None:
return True
if p == None or q == None:
return False
if p.val != q.val:
return False
# if p.left != q.left or p.right != q.right:
# return False
return self.isMirror(p.right,q.left) and self.isMirror(p.left, q.right) |
ea4c04c7520923f10fc7dddb903e3539aff45466 | lantzmw/LeetCode-Practice | /p5/solution.py | 2,751 | 3.953125 | 4 | class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
longest = ''
adjuster = 0
#go in reverse order through a string
for ss in range(len(s),0,-1):
substring = s[0:ss]
palindrome = self.findPalindrome(substring)
print("ss: %d longest %s palindrome %s" % (ss, longest, palindrome))
#if there hasn't been a longest before, than this is automatically the longest
if longest == '':
longest = palindrome
#if the longest is the same as the original string passed in, then no need to look further
if longest == s:
break
#otherwise check if the found palindrome is the longest
elif len(palindrome) >= len(longest):
longest = palindrome
return longest
def findPalindrome(self, s):
slen = len(s)
mid = slen / 2
longest = ''
print("Testing %s" % s)
#base case, nothing to check
if slen <= 1:
return s
#is front a palindrome
if self.checkPalindrome(s):
#check if its the longest
if len(s) > len(longest):
longest = s
#if top string is not a palindrome,
else:
#cut in half and see if that is the longest palindrome
print("finding in front half")
front = self.findPalindrome(s[:mid])
back = ''
#and test the back half as well
print("finding in back half")
if(slen % 2 == 0):
back = self.findPalindrome(s[mid:])
else:
back = self.findPalindrome(s[mid+1:])
#determine which is the longer palindrome
print("Front %s vs back %s" % (front, back))
if(len(front) > len(back)):
longest = front
else:
longest = back
print("longest is %s" % longest)
return longest
def checkPalindrome(self, s):
"""
check if the first part of a string is == to the back
"""
l = len(s)
mid = l / 2
front = ''
back = ''
ret = False
front = s[:mid]
#if even
if(l%2 == 0):
back = s[mid:]
else:
back = s[mid+1:]
#check if the strings are the same
if front == back[::-1]:
ret = True
return ret
sol = Solution()
"""
string = "ababa"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest))
string = "abaaba"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest))
string = "abgvba"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest))
string = "abaqwerty"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest))
string = "babad"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest))
"""
string = "cbbd"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest)) |
10d13fc2d365ac5ed02d93ce14ed5f4cd3d3a08d | njpayne/pythagoras | /Archive/pickle_cellphone.py | 1,217 | 4.40625 | 4 | # The pickle module provides functions for serializing objects
# Serializing an object means converting it into a stream of bytes that can be saved to a file for later retrieval
# The pickle modules dump function serializes an object and writes it to a file
# The load function retrieves an object from a file and deserializes it (unpickles it)
import pickle
import cellphone
FILENAME = 'cellphones.dat' # This is the constant representing the file name
def main(): # Create the main function
again = 'y' # Initialize a variable to control the loop
output_file = open(FILENAME, 'wb') # Write back to the file that is open & which was created above
while again.lower() == 'y': # While the again = 'y'
man = input("Please enter the manufacturer: ")
mod = input("Please enter the model: ")
retail = float(input("Please enter the retail price: "))
phone = cellphone.CellPhone(man, mod, retail) # Create the cell phone object
pickle.dump(phone, output_file) # Pickle the object and send it to the output_file
again = input("Would you like to enter more phone data? (y/n): ")
output_file.close() # Close the file in question
print("The data was written to", FILENAME)
main() # Call the main function |
4a7031ab9fa6adfc7f301f41de0ddd578bea4758 | DrQuestion/PoCS2 | /Collections 7.py | 1,614 | 3.953125 | 4 | from collections import deque
if __name__=='__main__':
t=int(raw_input()) #number of testcases
for _ in xrange(t): #iterating over the test cases
n=raw_input()
l=map(int,(raw_input().split()))
d=deque(l) #created a deque containing all the values of the test case analyzed
for _ in xrange(len(d)): #iterating over the indexes of the elements of d, which will progressively reduce
a=d.popleft() #extracted first and last element of d
b=d.pop()
if len(d)==0: #at one step from the end of the cycle, if everything didn't respect the if statement on the bottom, if the number of elements in d is even, we'll end up with 2 elements, that are removed by pops() above, meaning that we can pile cubes
print 'Yes'
break
elif len(d)==1: #if instead the number is odd, we'll end up with one element,
if max(a,b)<d[0]: # that if it's bigger than the other two,
print 'No' #we can't pile it
break #and break the cycle
else:
print 'Yes' #otherwise we can, and after printing yes we break the cycle
break
if max(a,b)<d[0] or max(a,b)<d[-1]: #the nucleus of the code: when the max between the two removed extremities is less than one of the two actual extremities,
print 'No' #it means that we can't pile
break
#if none of the previous if statements is verified, everything is ok by far and the cycle begins again with the two new extremities |
5ce604bf3cf39181579cefddf903379f17a4bc6a | girishgupta211/algorithms | /python/betright_python.py | 4,577 | 3.859375 | 4 | # Lembda function
MU = 8
a = lambda x, y: (x * MU) / y
print(a(2, 3))
# 5.333333333333333
# # Shallow copy
import copy
class A(object):
pass
a = A()
a.lst = [1, 2, 3]
a.str = 'cats and dogs'
b = copy.copy(a) # Here string will be pointing to new location as this is immutable
# b = a # here both will point to same object
# a.lst = [1, 2, 3, 4]
a.lst.append(100)
a.str = 'cats and mice'
print(b.lst)
print(b.str)
# [1, 2, 3, 100]
# cats and dogs
class A(object):
def __repr__(self):
return 'instance of A'
pass
a = A()
b = a
del a
print(b)
# instance of A
import datetime
class Human(object):
name = None
gender = None
birthdate = None
def __getattr__(self, item):
if item == 'age':
return datetime.datetime.now() - self.birthdate
else:
return None
def __getattribute__(self, item):
return object.__getattribute__(self, item)
h = Human()
h.birthdate = datetime.datetime(2004, 8, 20)
print(h.__dict__)
# h.age = 28 # if you set age with this way then it will add age attribute to
# __dict__ and when you can h.age, then I will not call __getattr__
print(h.age)
# 28
print(h.__dict__)
# {'birthdate': datetime.datetime(1994, 8, 20, 0, 0), 'age': 28}
class Org(object):
__employees = []
_employees = []
# Org.__employees.append('Eric') # This will throw an exception 'AttributeError: type object 'Org'
# # has no attribute '__employees' but still accessible through Org._Org__employees
Org._Org__employees.append('Eric')
print(Org._Org__employees)
print(Org._employees)
print(dir(Org))
# ['Eric']
# []
# ['_Org__employees', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_employees']
class Gog(Org):
__employees = []
print(Org._Org__employees)
print(Org._employees)
print(dir(Gog))
# ['Eric']
# []
# ['_Gog__employees', '_Org__employees', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_employees']
import datetime
class Human(object):
name = None
g = None
bd = None
def __getattr__(self, item):
# self.__dict__['age'] = item
if item == 'age':
return datetime.datetime.now() - self.bd
else:
return None
def __getattribute__(self, item):
# This will cause infinite recursion
# return self.__dict__[item]
return super(Human, self).__getattribute__(item)
# return object.__getattribute__(self, item)
#
h = Human()
h.bd = datetime.datetime(1994, 8, 20)
h.age = 28
print(h.age)
print(h.__dict__)
class A:
brothers = []
def __init__(self, name):
self.name = name
a = A('Richard')
b = A('Elly')
a.brothers.append('John')
print(a.name, a.brothers, b.name, b.brothers)
# Richard ['John'] Elly ['John']
a = ['orange', 'apple', 'banana']
b = a
a = ['tomato', 'cucumber', 'carrot']
print(b)
# ['orange', 'apple', 'banana']
# https://stackoverflow.com/questions/51887076/infinite-recursion-when-overriding-setattr/51887126#51887126
# infinite recursion
class Human(object):
def __setattr__(self, name, value):
if name == 'gender':
if value in ('male', 'female'):
# it calls __setattr__ in an infinite loop
# self.gender = value
super().__setattr__(name, value)
else:
# super(Human, self).__setattr__(name, value)
raise AttributeError('Gender can only be "male" or "female"')
else:
super().__setattr__(name, value)
h = Human()
h.name = 'Sweety'
# This will cause infinite recursion
h.gender = 'female'
print(h.name)
print(h.gender)
# Sweety
# female
#
class A:
pass
class B:
pass
a = A()
b = B()
print(type(a) == type(b), type(a), type(b))
# False <class '__main__.A'> <class '__main__.B'>
lst = ['I', 'am', 'Python', 'programmer']
s1 = ""
for x in lst:
s1 += x
print(s1)
# IamPythonprogrammer
# More efficient
s2 = "".join(lst)
print(s2)
# IamPythonprogrammer
|
e469b8fbe24dbf153c592749933745343103182d | CatarinaBrendel/Lernen | /curso_em_video/Module 2/exer037.py | 682 | 3.71875 | 4 | print "\033[32m-=\033[m" * 25
print "\033[30m Calculadora Conversora\033[m"
print "\033[32m-=\033[m" * 25
numero = int(raw_input("Digite um numero inteiro: > "))
print '''Escolha agora sua opcao:
[1] converter para BINARIO
[2] converter para OCTAL
[3] converter para HEXADECIMAL'''
opcao = int(raw_input("Entre sua opcao: > "))
if opcao == 1:
binario = bin(numero)
print "Seu numero Binario e: {}".format(binario[2:])
elif opcao == 2:
octal = oct(numero)
print "Seu numero OCTAl e: {}".format(octal[1:])
elif opcao == 3:
hexa = hex(numero)
print "Seu numero em HEXADECIMAL e: {}".format(hexa[2:])
else:
print "Entre uma opcao valida!"
|
6aac0625e4acfcc80609d03706b4d3f43e488dc6 | benjaminhuanghuang/ben-leetcode | /0063_Unique_Paths_II/solution.py | 4,231 | 4.03125 | 4 | '''
63. Unique Paths II
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
Note: m and n will be at most 100.
'''
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
rows = len(obstacleGrid)
cols = len(obstacleGrid[0])
if obstacleGrid[0][0] == 1:
return 0
elif rows == 1 and cols == 1:
return 1
paths = [[0 for i in range(cols)] for j in range(rows)]
paths[0][0] = 1
for i in xrange(1, rows):
if obstacleGrid[i][0] != 1:
paths[i][0] = paths[i - 1][0]
for j in range(1, cols):
if obstacleGrid[0][j] != 1:
paths[0][j] = paths[0][j - 1]
for i in range(1, rows):
for j in range(1, cols):
if obstacleGrid[i][j] != 1:
paths[i][j] = paths[i][j - 1] + paths[i - 1][j]
return paths[-1][-1]
def uniquePathsWithObstacles_9(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
mp = obstacleGrid
for i in range(len(mp)):
for j in range(len(mp[i])):
if i == 0 and j == 0:
mp[i][j] = 1 - mp[i][j] # if mp[i][j] == 1, path =0
elif i == 0:
if mp[i][j] == 1:
mp[i][j] = 0
else:
mp[i][j] = mp[i][j - 1]
elif j == 0:
if mp[i][j] == 1:
mp[i][j] = 0
else:
mp[i][j] = mp[i - 1][j]
else:
if mp[i][j] == 1:
mp[i][j] = 0
else:
mp[i][j] = mp[i - 1][j] + mp[i][j - 1]
return mp[-1][-1]
def uniquePathsWithObstacles_2(self, obstacleGrid):
rows = len(obstacleGrid)
cols = len(obstacleGrid[0])
if obstacleGrid[0][0] == 1:
return 0
elif rows == 1 and cols == 1:
return 1
paths = [[] for i in range(rows)]
for i in range(rows):
if obstacleGrid[i][0] == 1:
while (i < rows):
paths[i].append(0)
i += 1
break
else:
paths[i].append(1)
for j in range(1, cols):
if obstacleGrid[0][j] == 1:
while (j < cols):
paths[0].append(0)
j += 1
break
else:
paths[0].append(1)
for i in range(1, rows):
for j in range(1, cols):
if obstacleGrid[i][j] == 1:
paths[i].append(0)
else:
paths[i].append(paths[i][j - 1] + paths[i - 1][j])
return paths[-1][-1]
def uniquePathsWithObstacles_3(self, obstacleGrid):
rows = len(obstacleGrid)
cols = len(obstacleGrid[0])
res = [[0 for i in range(cols)] for j in range(rows)]
for i in range(rows):
if obstacleGrid[i][0] == 0:
res[i][0] = 1
else:
res[i][0] == 0
break
for i in range(cols):
if obstacleGrid[0][i] == 0:
res[0][i] = 1
else:
res[0][i] = 0
break
for i in range(1, rows):
for j in range(1, cols):
if obstacleGrid[i][j] == 1:
res[i][j] = 0
else:
res[i][j] = res[i - 1][j] + res[i][j - 1]
return res[rows - 1][cols - 1]
grid = [
[0, 1, 0],
[0, 1, 0],
[0, 1, 0]
]
s = Solution()
res = s.uniquePathsWithObstacles(grid)
print res
|
9509ef1f28b7e75915cbb75b97ad472d9af81bab | anobhama/Intern-Pie-Infocomm-Pvt-Lmt | /OOPS concept/single_inheritance.py | 1,033 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 00:16:23 2020
@author: Anobhama
"""
#single inheritance
#single parent and child class
class rectangle:
def __init__(self,l,b):
self.length=l
self.breath=b
def arearect(self):
area = self.length * self.breath
print("The area of rectange is ",area)
class square(rectangle):
def __init__(self,l,b):
super().__init__(l,b)
def areasquare(self):
area= self.length * self.length
print("The area of square is ",area)
a=square(10,5)
a.areasquare()
a.arearect()
#user input
length= int(input("Enter the length : "))
breath = int(input("Enter the breath : "))
shape=square(length,breath)
#shape.arearect()
#shape.areasquare()
print("if you wanna find the area of ")
print("(1) Rectange Press 1")
print("(2) Square Press 2")
print("(3) Both Press 3")
n=int(input("Enter your choice: "))
if n == 1:
shape.arearect()
elif n == 2:
shape.areasquare()
else:
shape.arearect()
shape.areasquare()
|
3ea038cdf2e0efaf412c0625a57752c0df15b3b0 | wentingsu/Su_Wenting_spring2017 | /Final/codePY/Analysis3.py | 3,949 | 3.515625 | 4 |
# coding: utf-8
# # Analysis 3 : analyse the variable
# * merge the 2015 and 2016 rank country table and create a new column to show the change of the rank for each contry and out put to a new csv.
# In[1]:
import pandas as pd
# from pythainlp.segment import segment
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import math
get_ipython().magic('matplotlib inline')
# In[2]:
# define the function to calculate and create the total score of happiness.
def getTotalScore(str):
# load the data
data = pd.read_csv(str)
# get all the columns that to be added together
colums = data.ix[:,2:]
# add the new column named 'total score'
# data['total score'] = colums.sum(axis = 1).head()
data['total score'] = np.sum(colums,axis = 1)
# return the data frame
return data
# In[3]:
data2015=getTotalScore('data/2015.csv')
data2016=getTotalScore('data/2016.csv')
# In[4]:
#define the function to sort based on total score and add a new column named rank
def getRank(data):
newData = data.sort_values(by='total score',ascending=False)
newData['Rank'] = range(1,len(data) + 1)
newData.index = range(0,len(data))
return newData
# In[5]:
data1 = getRank(data2015)
data2 = getRank(data2016)
# In[6]:
data2.head()
# In[13]:
# extract the region, country and rank in year 2015
data3 = pd.concat([data1['Country'],data1['Region'],data1['Rank'],data1['total score']],axis=1)
# extract the region, country and rank in year 2016
data4 = pd.concat([data2['Country'],data2['Rank'],data2['total score']],axis=1)
# merge the data in year 2015 and 2016
data5 = data3.merge(data4, on = 'Country', how = 'inner')
# get the new column named 'change' means the change of the rank from year 2015 to year 2016
data5['change'] = data5['Rank_y'] - data5['Rank_x']
# In[14]:
data5.head(6)
# In[18]:
# sort the change according to the change of scores.
data6 = data5.sort_values(by='change',ascending=False)
# In[19]:
data6.head()
# In[20]:
data6['change'].value_counts().head()
# In[24]:
sns.set()
sns.swarmplot(x="Region", y="change", data=data5)
plt.xticks(rotation=45)
plt.savefig('3-2.png')
# In[27]:
# pointplot to compare the rank and total score change from year 2015 to 2016
f, axes = plt.subplots(2, 1, figsize=(16, 16), sharex=True)
axes = axes.flatten()
# The change of the mean
sns.pointplot(x="Region", y="total score_x", data=data5, color='r', ax = axes[0])
sns.pointplot(x="Region", y="total score_y", data=data5, color='g',ax = axes[0])
sns.pointplot(x="Region", y="Rank_x", data=data5, color='r',ax = axes[1])
sns.pointplot(x="Region", y="Rank_y", data=data5, color='g',ax = axes[1])
plt.xticks(rotation=45)
plt.savefig('3-3.png')
# In[15]:
increase = data5[data5.change>0]
neutral = data5[data5.change==0]
decrese = data5[data5.change<0]
increase['Trend'] = 'increase'
neutral['Trend'] = 'neutral'
decrese['Trend'] = 'decrese'
data7 = pd.concat([increase,neutral,decrese],axis=0)
# data7
# In[16]:
data7.head()
# In[192]:
data7['Trend'].value_counts()
# In[28]:
# Scatterplots
sns.lmplot('Rank_x', 'change', data=data6, fit_reg=False)
plt.savefig('3-4.png')
# In[29]:
# Additionally, these functions accept vectors of Pandas or numpy objects rather than variables in a
sns.violinplot(x=data7.Trend, y=data7.change);
plt.savefig('3-5.png')
# In[31]:
# using factorplot to find out the rank change for each region.
g = sns.factorplot("Trend", col="Region", col_wrap=3,
data=data7[data7.Region.notnull()],
kind="count", size=3.5, aspect=.8, palette="Set2")
plt.savefig('3-6.png')
# In[ ]:
# Analyse the value-counts of the change from 2015-2016
# In[69]:
y = pd.DataFrame(data5['change'].value_counts().index)
# In[70]:
x = pd.DataFrame(data5['change'].value_counts().values)
# In[71]:
changevalue = pd.concat([y,x],axis=1)
# In[74]:
changevalue.columns = ['change', 'values']
|
4637e9d335b2c1c971ca999d1e05ec9f14351602 | xz1082/assignment5 | /tw991/assignment5.py | 4,560 | 3.546875 | 4 | import string
class interval:
def __init__(self, string_raw):
string2 = string.replace(string_raw,' ','')
middle_place=string2.find(',')
if (string2[0] == '[') & (string2[len(string2)-1] == ']') & (int(string2[1:middle_place]) <= int(string2[middle_place+1:len(string2)-1])):
self.lower_bound = int(string2[1:middle_place])
self.lower_show = int(string2[1:middle_place])
self.lower_bound_type = '['
self.upper_bound = int(string2[middle_place+1:len(string2)-1])
self.upper_show = int(string2[middle_place+1:len(string2)-1])
self.upper_bound_type = ']'
elif (string2[0] == '(') & (string2[len(string2)-1] == ')') & (int(string2[1:middle_place])+1 <= int(string2[middle_place+1:len(string2)-1])-1):
self.lower_bound = int(string2[1:middle_place])+1
self.lower_show = int(string2[1:middle_place])
self.lower_bound_type = '('
self.upper_bound = int(string2[middle_place+1:len(string2)-1])-1
self.upper_show = int(string2[middle_place+1:len(string2)-1])
self.upper_bound_type = ')'
elif (string2[0] == '(') & (string2[len(string2)-1] == ']') & (int(string2[1:middle_place])+1 <= int(string2[middle_place+1:len(string2)-1])):
self.lower_bound = int(string2[1:middle_place])+1
self.lower_show = int(string2[1:middle_place])
self.lower_bound_type = '('
self.upper_bound = int(string2[middle_place+1:len(string2)-1])
self.upper_show = int(string2[middle_place+1:len(string2)-1])
self.upper_bound_type = ']'
elif (string2[0] == '[') & (string2[len(string2)-1] == ')') & (int(string2[1:middle_place]) <= int(string2[middle_place+1:len(string2)-1])-1):
self.lower_bound = int(string2[1:middle_place])
self.lower_show = int(string2[1:middle_place])
self.lower_bound_type = '['
self.upper_bound = int(string2[middle_place+1:len(string2)-1])-1
self.upper_show = int(string2[middle_place+1:len(string2)-1])
self.upper_bound_type = ')'
else:
raise Exception('Input Error')
def __repr__(self):
return self.lower_bound_type+'%d,%d' %(self.lower_show,self.upper_show)+self.upper_bound_type
def mergeIntervals(int1, int2):
lower_bound_1 = int1.lower_bound
lower_bound_2 = int2.lower_bound
upper_bound_1 = int1.upper_bound
upper_bound_2 = int2.upper_bound
if (upper_bound_1+1 < lower_bound_2) or (upper_bound_2+1 < lower_bound_1):
raise Exception('No overlapping')
if (upper_bound_1 == max(upper_bound_1,upper_bound_2)):
upper_bound = upper_bound_1
upper_bound_show = int1.upper_show
upper_bound_type = int1.upper_bound_type
if (upper_bound_2 == max(upper_bound_1,upper_bound_2)):
upper_bound = upper_bound_2
upper_bound_show = int2.upper_show
upper_bound_type = int2.upper_bound_type
if (lower_bound_1 == min(lower_bound_1,lower_bound_2)):
lower_bound = lower_bound_1
lower_bound_show = int1.lower_show
lower_bound_type = int1.lower_bound_type
if (lower_bound_2 == min(lower_bound_1,lower_bound_2)):
lower_bound = lower_bound_2
lower_bound_show = int2.lower_show
lower_bound_type = int2.lower_bound_type
string = lower_bound_type + '%d,%d' %(lower_bound_show, upper_bound_show) + upper_bound_type
return interval(string)
def interval_sort(a,b):
if a.lower_bound > b.lower_bound:
return 1
if b.lower_bound > a.lower_bound:
return -1
return 0
def mergeOverlapping(intlist):
A=intlist[:]
A.sort(interval_sort)
B=[]
answer=[]
while len(A)>0:
x0=A[0]
for x in A:
try:
x0=mergeIntervals(x0,x)
except:
B.append(x)
answer.append(x0)
A=B[:]
B=[]
return answer
def insert(intlist,newint):
input=intlist[:]
input.append(newint)
string=mergeOverlapping(input)
string.sort(interval_sort)
return string
def input():
input_list = raw_input('List of intervals?').split(', ')
list = [interval(x) for x in input_list]
while True:
add = raw_input('Intervals?')
if add=='quit':
break
try:
add_int=interval(add)
except:
print 'Invalid interval'
continue
list = insert(list,add_int)
print(list)
|
41813f38835bb12fb3f50727e66ee4e41cfeacde | YonelaSitokwe1811/intro_pyhthon | /Intro_python/printmonth.py | 739 | 4.21875 | 4 | name_of_month = (input("Enter the month('January',...,'December') :\n"))
first_weekday = input("Enter start day('Monday',...,'Sunday') :\n")
number_of_days=31
month={'January','February','March','April','May','June','July','August','September','October','November','December'}
weekdays = {'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6}
print('{:>3}{:>4}{:>4}{:>4}{:>4}{:>4}{:>4}'
.format( 'M', 'T', 'W', 'Th', 'F', 'Sa','Su'))
print (weekdays[first_weekday]*4*' ' + '{:>3}'.format(1), end=' ')
for current_day in range(1, number_of_days+1):
if (weekdays[first_weekday] + current_day) % 7 == 0:
print ()
print ('{:>3}'.format(current_day ), end=' ')
|
cde7809cb01e3484166fb6efd432c437d6c5f749 | jphiii/phabricator-tools | /py/phl/phlsys_timedqueue.py | 2,751 | 3.65625 | 4 | """Priority queue for objects with associated delays.
Usage example:
>>> tq = TimedQueue(); tq.push('a', datetime.timedelta()); tq.pop_expired()
['a']
"""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# phlsys_timedqueue
#
# Public Classes:
# TimedQueue
# .push
# .pop_expired
#
# -----------------------------------------------------------------------------
# (this contents block is generated, edits will be lost)
# =============================================================================
from __future__ import absolute_import
import datetime
import heapq
class TimedQueue(object):
def __init__(self):
self._items = []
self._counter = 0
def push(self, item, delay):
# here we use counter as a second item in the tuple to compare to make
# sure that heappush() never tries to compare two items, also to be
# sure that things come out in the same order they are pushed
heap_item = (datetime.datetime.now() + delay, self._counter, item)
self._counter += 1
heapq.heappush(self._items, heap_item)
def pop_expired(self):
expired = []
if self._items:
now = datetime.datetime.now()
while self._items and self._items[0][0] <= now:
expired.append(heapq.heappop(self._items)[2])
return expired
# -----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Bloomberg Finance L.P.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# ------------------------------ END-OF-FILE ----------------------------------
|
2fecb50cd5b96a72af407dae5fa9be0db7393340 | ibrahim-sma/eulers_project | /problem_9.py | 1,410 | 4.1875 | 4 | # @author : Ibrahim Sma
# @github_location: https://github.com/ibrahim-sma
# @email: ibrahim.sma1990@gmail.com
# @LinkedIn: www.linkedin.com/in/ibrahim-sma
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Problem 9 - Special Pythagorean triplet
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2 ; For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Solution: Starts from if __name__ == "__main__":
def pythagoras_product():
# Initial assignment
abc_prod = 0
# Sum of given a,b,c in the question is 1000.
abc_sum = 1000
# value of a,b,c has to be less than 1000; so that sum(a,b,c) will be 1000
# Hence looping through a range less than 1000 for a & b
for a in range(2,1000):
for b in range(3, 1000):
# Since we have a & b from loop c can be found by subtracting (a & b) with 1000
c = abc_sum - a - b
# condition to check if a,b,c is a pythagoras triplet; returns the product if it is a triplet
if (a**2 + b**2) == c**2:
abc_prod = a * b * c
return a, b, c, abc_prod
if __name__ == "__main__":
a, b, c, abc_prod = pythagoras_product()
print(f"The product of pythagoras triplet ({a},{b},{c}) whose sum is 1000 is, {abc_prod}")
|
36ca8beaa89545e13be0c755aaadbd7d069b3fd5 | gagewooldridge/python-fizzbuzz | /FizzBuzz.py | 777 | 4.1875 | 4 | # This program will take the numbers 1-50 and evaluate them for the following criteria:
# Number divisible by three and five: Output = FizzBuzz
# Number divisible by three but not five: Output = Fizz
# Number divisible by five but not three: Output = Buzz
# Number divisible by neither three or five: Output = number
# Programmed by Gage Wooldridge on 5/13/16
# Declare counter variable and assign initial value
i = 0
# Implement loop to evaluate and increment counter variable
while (i < 50):
# Increment count
i += 1
# Evaluate data and display output
if i % 3 == 0 and i % 5 == 0:
print "FizzBuzz"
elif i % 3 == 0:
print "Fizz"
elif i % 5 == 0:
print "Buzz"
else:
print str(i) |
04008ec747f430bc5b911d077f2a10771166ef94 | sam1017/pythonstudy | /matrix_test.py | 1,747 | 3.5625 | 4 | import time
class matrix():
def __init__(self, matrix_view):
self.matrix_view = matrix_view
self.row = len(matrix_view)
self.column = len(matrix_view[0])
def show(self):
print("this matrix is " + str(self.row) + " * " + str(self.column))
for rows in self.matrix_view:
print(rows)
def matrix_T(self):
matrix_view_T = []
for i in range(0, self.column):
rows = []
for j in range(0, self.row):
rows.append(matrix_view[j][i])
matrix_view_T.append(rows)
return matrix_view_T
def get_matrix(self):
return self.matrix_view
def get_matrix_row(self):
return self.row
def get_matrix_column(self):
return self.column
def multiply(matrix_A, matrix_B):
matrix_view = []
matrix_A_view = matrix_A.get_matrix();
matrix_B_view = matrix_B.get_matrix();
for i in range(0,matrix_A.get_matrix_row()):
rows = []
for j in range(0, matrix_B.get_matrix_column()):
value = 0
for k in range(0,matrix_A.get_matrix_column()):
value = value + matrix_A_view[i][k]*matrix_B_view[k][j]
rows.append(value)
matrix_view.append(rows)
return matrix(matrix_view)
matrix_view = [[0, 12, 19, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0],[-3, 0, 0, 0, 0, 14, 0],[0, 0, 24, 0, 0, 0, 0],[0, 18, 0, 0, 0, 0, 0],[15, 0, 0, -7, 0, 0, 0]]
my_matrix = matrix(matrix_view)
my_matrix.show()
matrix_view_T = my_matrix.matrix_T()
if matrix_view_T != None:
my_matrix_T = matrix(matrix_view_T)
my_matrix_T.show()
start = time.clock()
matrix_A = multiply(my_matrix, my_matrix_T)
t = time.clock() - start
print(t)
matrix_A.show() |
f3598dc6f4ce9911382ad94038511b26c0578c2f | Anirban2404/LeetCodePractice | /409_longestPalindrome.py | 1,592 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 10:57:00 2019
@author: anirban-mac
"""
"""
409. Longest Palindrome
Given a string which consists of lowercase or uppercase letters, find the length
of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
"""
import collections
class Solution:
def longestPalindrome(self, s):
if len(s) < 1:
return 0
letterCounter = {}
for letter in s:
if letter in letterCounter:
letterCounter[letter] += 1
else:
letterCounter[letter] = 1
#print(letterCounter)
sum = 0
ones = False
for key, value in letterCounter.items():
#print (key, value)
if value % 2 == 0:
sum = sum + value
elif value % 2 != 0:
sum = sum + value - 1
ones = True
if ones:
sum = sum + 1
return sum
"""
def longestPalindrome(self, s):
ans = 0
for v in collections.Counter(s).values():
ans += v // 2 * 2
if ans % 2 == 0 and v % 2 == 1:
ans += 1
return ans
"""
s = "abccccdd"
print(Solution().longestPalindrome(s)) |
4641422529eec41c1a0c8986b5a453b3769e1b9d | johnfelipe/progress | /courses/cs101/lesson02/quiz01/abbaiza.py | 368 | 3.71875 | 4 | # Define a procedure, abbaize, that takes
# two strings as its inputs, and returns
# a string that is the first input,
# followed by two repetitions of the second input,
# followed by the first input.
def abbaize(x, y):
# return x + y + y + x
return x + y * 2 + x
print(abbaize('a', 'b'))
#>>> abba
print(abbaize('dog', 'cat'))
#>>> dogcatcatdog |
ef04c38a04d7d36375230aede6d529f99cb76a90 | corentinloirs/python-eval | /huffman/codec.py | 4,226 | 3.6875 | 4 | #Codec va faire appel à la libraire heapq, pour gérer l'ordonnancement des noeuds selon leur valeur
#On pourrait s'en passer, en triant à chaque itération la liste de
#dictionnaire des noeuds selon les keys. heapq le fera pour nous
#Heapq.heappop pop le dico de key la plus basse
#Heapq.heappush ajoute le noeud au heap
#C'est juste une gestion de pile automatisée
import heapq
import os
class node:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other): #on va avoir besoin du comparateur < pour heapq (comme on en aurait besoin pour trier la pile)
if(other == None):
return -1
if(not isinstance(other,node)):
return -1
return self.freq < other.freq
class builder:
def __init__(self,text):
self.heap = [] #liste des nodes, qu'on gérera facilement grâce à heapq
self.text = text
def make_frequency_dict(self): #dictionnaire des fréquences des lettres
frequency = {}
for character in self.text:
if not character in frequency:
frequency[character] = 0
frequency[character] += 1
return frequency
def heap_maker(self, frequency): #on construit la liste des nodes
for key in frequency:
noeud = node(key, frequency[key])
print(noeud.freq, noeud.char)
heapq.heappush(self.heap, noeud)
def tree_maker(self): #maintenant on relie les noeuds entre eux
while(len(self.heap)> 1): #On traite les noeuds jusqu'à ce qu'il ne reste que le noeud du haut, i.e. l'arbre binaire
noeud1 = heapq.heappop(self.heap) #on sort le noeud de frequency la plus basse
noeud2 = heapq.heappop(self.heap) #on sort le noeud de frequency la plus basse encore
merged = node(None, noeud1.freq + noeud2.freq) #On relie les noeuds, l'info sur les chars sera dans les noeuds fils
merged.left = noeud1 #on met bien le plus petit à gauche
merged.right = noeud2 #et le plus grand à droite
print(merged.freq)
heapq.heappush(self.heap, merged) #et on remet ce noeud dans la liste des noeuds à traiter !
def tree(self):
frequency = self.make_frequency_dict()
self.heap_maker(frequency)
self.tree_maker()
print(frequency)
return self.heap[0]
def TreeBuilder(text):
return builder(text)
class codec:
def __init__(self, tree):
self.tree = tree
self.codes = {} #dico, à une lettre on associe un code
self.reversemapping = {} #dico inversé, à un code on associe une lettre
def codemaker(self):
root = self.tree
current_code = ""
self.codemaker_assist1(root, current_code)
def codemaker_assist1(self, root, current_code): #fonction d'assistance à codemaker
if root == None:
return
if root.char != None: #on est sur un noeud en bout de branche, qui est associé à un charactère
self.codes[root.char] = current_code #dictionnaire de codage
self.reversemapping[current_code] = root.char #dictionnaire de décodage
return
self.codemaker_assist1(root.left, current_code + "0")
self.codemaker_assist1(root.right, current_code + "1")
def get_encoded_text(self, text):
encoded_text = ""
for char in text:
encoded_text += self.codes[char]
return encoded_text
def encode(self,text):
self.codemaker()
encoded_text = self.get_encoded_text(text)
print(self.codes)
return encoded_text
def decode(self, encoded_text):
self.codemaker()
current_code = ""
decoded_text = ""
for bit in encoded_text:
current_code += bit
if(current_code in self.reversemapping):
character = self.reversemapping[current_code]
decoded_text += character
current_code = ""
return decoded_text
def Codec(tree):
return codec(tree)
|
012dd0c23fd57ad6dc859ccee21ae5ff2662f3ab | nn-nagar/test | /task2.py | 267 | 3.828125 | 4 | phrase = input("Type in : ")
phrase_splited = phrase.split(' ')
# to remove duplicated
word_list = []
for i in phrase_splited:
if i not in word_list:
word_list.append(i)
else:
continue
word_list.sort()
print((' ').join(word_list)) |
1a095c99dff7d886a6db9385f8ad5ed6977e46fe | davecomeau/movie-trailer-website | /media.py | 1,427 | 3.875 | 4 | import webbrowser
class Movie():
""" Movie class
Movie objects contain information about a movie, including description
and preview URLS. Each object can open its preview trailer in a webbrowser.
Attributes:
title: A text field containing the name of the movie
storyline: A Text field that stores a brief description
of the movie's story
poster_image_url: A text field that stores the image URL of the movies poster
trailer_youtube_url: A text field that stores the TouTube URL of the
movie's preview Trailer
related_clips: A list that stores dictionaries populated in the that stores data
(title, youtube url, thumbnail image url, youtube video_id) about YouTube videao clips related to the movie.
Ex:
movie_1.related_clips = [ {'title': title, 'url': url, 'thumbnail':thumbnail_url, 'video_id':youtube_video_id},
{'title': title, 'url': url, 'thumbnail':thumbnail_url, 'video_id':youtube_video_id},
{'title': title, 'url': url, 'thumbnail':thumbnail_url, 'video_id':youtube_video_id} ]
"""
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
self.related_clips = []
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
|
9056a1ac9d967dc481da7b2304a8388a13dcfb89 | wansook0316/problem_solving | /210701_백준_FBI.py | 306 | 3.515625 | 4 | import re
import sys
input = sys.stdin.readline
fbi = []
p = re.compile("FBI")
for i in range(5):
if p.search(input()) != None:
fbi.append(i + 1)
fbi.sort()
if not fbi:
print("HE GOT AWAY!")
else:
print(" ".join(list(map(str, fbi))))
# N-FBI1
# 9A-USKOK
# I-NTERPOL
# G-MI6
# RF-KGB1 |
8d7d7298d7686273c3d577f0a2b4800195cffec7 | fengjiaxin/prepare_work | /leetcode_tag/LinkedList/19.删除链表的倒数第 N 个结点.py | 758 | 3.890625 | 4 | # 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
#
# 进阶:你能尝试使用一趟扫描实现吗?
#
# 输入:head = [1,2,3,4,5], n = 2
# 输出:[1,2,3,5]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
prevNode = ListNode(0)
prevNode.next = head
slow = prevNode
fast = prevNode
for i in range(n):
fast = fast.next
while fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return prevNode.next |
ddcc737a7d8a8beac8743556829a9d81e05ee408 | madhab-p/py-code | /src/root/pyconcpets/factorial.py | 859 | 3.703125 | 4 | '''
Created on Apr 11, 2017
Synopsis:
This document exhibits how doctest module can be used
for testing of the module.
@author: pneela
'''
def factorial(x):
'''
>>> factorial(5)
120
This function should not be called with very a large number
>>> factorial(1329283)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded in comparison
No -ve number for factorial
>>> factorial(-4)
Traceback (most recent call last):
...
...
ValueError: n must be >= 0
'''
if x < 0:
raise ValueError('n must be >= 0')
if x ==1 or x == 0:
return 1
else:
return x * factorial(x-1)
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
print(factorial(10)) |
dad314976c4558d510d5b359628673c72864314b | vpistola/project_euler | /euler45.py | 865 | 3.796875 | 4 | '''
Project Euler 45: After 40755, what is the next triangle number that is also pentagonal and hexagonal?
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, …
Pentagonal Pn=n(3n-1)/2 1, 5, 12, 22, 35, …
Hexagonal Hn=n(2n-1) 1, 6, 15, 28, 45, …
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
Note: All hexagonal numbers must be triangular numbers as well; there is no need to check for triangularity.
'''
import time
t1 = time.time()
def is_pentagonal(n):
return (1+(1+24*n)**0.5)/6 == int((1+(1+24*n)**0.5)/6)
def hexagonal(n):
return n*(2*n - 1)
n = 144
while not is_pentagonal(hexagonal(n)):
n += 1
print(hexagonal(n))
t2 = time.time()
print("Time elapsed:", t2 - t1, "seconds") |
a89c3eeacce98261039ea21e5094528c92c3cbbf | yejiahaoderek/Email-Spam-Classification | /email_preprocessor.py | 9,300 | 3.734375 | 4 | '''email_preprocessor.py
Preprocess Enron email dataset into features for use in supervised learning algorithms
Jiahao (Derek) Ye
CS 251 Data Analysis Visualization, Spring 2020
'''
import re
import os
import numpy as np
def tokenize_words(text):
'''Transforms an email into a list of words.
Parameters:
-----------
text: str. Sentence of text.
Returns:
-----------
Python list of str. Words in the sentence `text`.
This method is pre-filled for you (shouldn't require modification).
'''
# Define words as lowercase text with at least one alphabetic letter
pattern = re.compile(r'[A-Za-z]+[\w^\']*|[\w^\']*[A-Za-z]+[\w^\']*')
return pattern.findall(text.lower())
def count_words(email_path='data/enron'):
'''Determine the count of each word in the entire dataset (across all emails)
Parameters:
-----------
email_path: str. Relative path to the email dataset base folder.
Returns:
-----------
word_freq: Python dictionary. Maps words (keys) to their counts (values) across the dataset.
num_emails: int. Total number of emails in the dataset.
TODO:
- Descend into the dataset base directory -> class folders -> individual emails.
- Read each email file as a string.
- Use `tokenize_words` to chunk it into a list of words.
- Update the counts of each words in the dictionary.
Hints:
- Check out Python functions in the os and os.path modules for walking the directory structure.
- When reading in email files, you might experience errors due to reading funky characters
(spam can contain weird things!). On this dataset, this can be fixed by telling Python to assume
each file is encoded using 'latin-1': encoding='latin-1'
'''
all_files = os.listdir(email_path)
listOfFiles = []
counts = {}
for (dirpath, dirnames, filenames) in os.walk(email_path):
listOfFiles += [os.path.join(dirpath, file) for file in filenames if file[-4:] == '.txt']
for i in range(len(listOfFiles)):
with open(listOfFiles[i], encoding='latin-1') as file:
content = file.read()
listOfWords = tokenize_words(content)
for i in listOfWords:
if i in counts:
counts[i] += 1
else:
counts[i] = 1
file.close()
return counts, len(listOfFiles)
pass
def find_top_words(word_freq, num_features=200):
'''Given the dictionary of the words that appear in the dataset and their respective counts,
compile a list of the top `num_features` words and their respective counts.
Parameters:
-----------
word_freq: Python dictionary. Maps words (keys) to their counts (values) across the dataset.
num_features: int. Number of top words to select.
Returns:
-----------
top_words: Python list. Top `num_features` words in high-to-low count order.
counts: Python list. Counts of the `num_features` words in high-to-low count order.
'''
top_words = np.array(sorted(word_freq.items(),key=lambda item:item[1], reverse=True))
words = top_words[:num_features, 0].tolist()
counts = top_words[:num_features, 1].tolist()
return words, counts
pass
def make_feature_vectors(top_words, num_emails, email_path='data/enron'):
'''Count the occurance of the top W (`num_features`) words in each individual email, turn into
a feature vector of counts.
Parameters:
-----------
top_words: Python list. Top `num_features` words in high-to-low count order.
num_emails: int. Total number of emails in the dataset.
email_path: str. Relative path to the email dataset base folder.
Returns:
-----------
feats. ndarray. shape=(num_emails, num_features).
Vector of word counts from the `top_words` list for each email.
y. ndarray of nonnegative ints. shape=(num_emails,).
Class index for each email (spam/ham)
TODO:
- Descend into the dataset base directory -> class folders -> individual emails.
- Read each email file as a string.
- Use `tokenize_words` to chunk it into a list of words.
- Count the occurance of each word, ONLY THOSE THAT APPEAR IN `top_words`.
HINTS:
- Start with your code in `count_words` and modify as needed.
'''
all_files = os.listdir(email_path)
listOfFiles = []
classes = np.zeros((num_emails))
counts = np.zeros((num_emails,len(top_words)))
for (dirpath, dirnames, filenames) in os.walk(email_path):
listOfFiles += [os.path.join(dirpath, file) for file in filenames if file[-4:] == '.txt']
for i in range(len(listOfFiles)):
if listOfFiles[i][11:15] != "spam":
classes[i] = 1
features = {}
with open(listOfFiles[i], encoding='latin-1') as file:
content = file.read()
listOfWords = tokenize_words(content)
for j in top_words:
features[j] = listOfWords.count(j)
file.close()
counts[i,:] = np.array(list(features.values()))
return counts, np.array(classes)
pass
def make_train_test_sets(features, y, test_prop=0.2, shuffle=True):
'''Divide up the dataset `features` into subsets ("splits") for training and testing. The size
of each split is determined by `test_prop`.
Parameters:
-----------
features. ndarray. shape=(num_emails, num_features).
Vector of word counts from the `top_words` list for each email.
y. ndarray of nonnegative ints. shape=(num_emails,).
Class index for each email (spam/ham)
test_prop: float. Value between 0 and 1. What proportion of the dataset samples should we use
for the test set? e.g. 0.2 means 20% of samples are used for the test set, the remaining
80% are used in training.
shuffle: boolean. Should we shuffle the data before splitting it into train/test sets?
Returns:
-----------
x_train: ndarray. shape=(num_train_samps, num_features).
Training dataset
y_train: ndarray. shape=(num_train_samps,).
Class values for the training set
inds_train: ndarray. shape=(num_train_samps,).
The index of each training set email in the original unshuffled dataset.
For example: if we have originally N=5 emails in the dataset, their indices are
[0, 1, 2, 3, 4]. Then we shuffle the data. The indices are now [4, 0, 3, 2, 1]
let's say we put the 1st 3 samples in the training set and the remaining
ones in the test set. inds_train = [4, 0, 3] and inds_test = [2, 1].
x_test: ndarray. shape=(num_test_samps, num_features).
Test dataset
y_test:ndarray. shape=(num_test_samps,).
Class values for the test set
inds_test: ndarray. shape=(num_test_samps,).
The index of each test set email in the original unshuffled dataset.
For example: if we have originally N=5 emails in the dataset, their indices are
[0, 1, 2, 3, 4]. Then we shuffle the data. The indices are now [4, 0, 3, 2, 1]
let's say we put the 1st 3 samples in the training set and the remaining
ones in the test set. inds_train = [4, 0, 3] and inds_test = [2, 1].
HINTS:
- If you're shuffling, work with indices rather than actual values.
'''
N = features.shape[0]
if shuffle == True:
inds = np.arange(N)
np.random.shuffle(inds)
temp_feature = features.copy()
temp_y = y.copy()
for i in range(N):
temp_feature[i] = features[inds[i]]
temp_y[i] = y[inds[i]]
features = temp_feature
y = temp_y
else:
inds = np.arange(N)
idx_bound_test = int(features.shape[0] * (1-test_prop))
x_split = np.split(features, [idx_bound_test + 1, N], axis = 0)
y_split = np.split(y, [idx_bound_test + 1, N], axis = 0)
idx_split = np.split(np.array(inds), [idx_bound_test + 1, N])
x_train = x_split[0]
y_train = y_split[0]
inds_train = idx_split[0]
x_test = x_split[1]
y_test = y_split[1]
inds_test = idx_split[1]
return x_train, y_train, inds_train, x_test, y_test, inds_test
pass
def retrieve_emails(inds, email_path='data/enron'):
'''Obtain the text of emails at the indices `inds` in the dataset.
Parameters:
-----------
inds: ndarray of nonnegative ints. shape=(num_inds,).
The number of ints is user-selected and indices are counted from 0 to num_emails-1
(counting does NOT reset when switching to emails of another class).
email_path: str. Relative path to the email dataset base folder.
Returns:
-----------
Python list of str. len = num_inds = len(inds).
Strings of entire raw emails at the indices in `inds`
'''
all_files = os.listdir(email_path)
listOfFiles = []
for (dirpath, dirnames, filenames) in os.walk(email_path):
listOfFiles += [os.path.join(dirpath, file) for file in filenames if file[-4:] == '.txt']
allcontent = []
for i in inds:
with open(listOfFiles[i], encoding='latin-1') as file:
content = file.read()
allcontent.append(content)
file.close()
return allcontent
pass
|
de7f4d3d1edba01bcf760dfd8b55e2822649ce05 | BinceAlocious/python | /DataStructures/linkedList.py | 1,121 | 3.921875 | 4 | class Node:
def __init__(self,data=None):
self.data=data
self.next=None
class Linked_list:
def __init__(self):
self.head=Node()
def append(self,data):
new_node=Node(data)
cur=self.head
while(cur.next!=None):
cur=cur.next
cur.next=new_node
def length(self):
cur=self.head
total=0
while(cur.next!=None):
total+=1
cur=cur.next
return total
def search(self,val):
cur_node=self.head
flag=0
while(cur_node.next!=None):
cur_node=cur_node.next
if(cur_node.data==val):
flag=1
break
if(flag==1):
return True
else:
return False
def display(self):
elems=[]
cur_node=self.head
while(cur_node.next!=None):
cur_node=cur_node.next
elems.append(cur_node.data)
print(elems)
obj=Linked_list()
obj.append(10)
obj.append(20)
obj.append(30)
print(obj.length())
obj.display()
print(obj.search(20))
print(obj.search(40)) |
48800ccf99842580ff9b17d144260e61aa50e0d7 | ramishtaha/Some_Basic_Programs_to_Better_Understand_PythonProgramming | /Life_In_Weeks.py | 588 | 4.03125 | 4 | # Greetings.
print("Welcome to the Life in Weeks Calculator")
# Below code Calculates How many years you have till you turn 90 and stores it in a variable.
age = int(input("Please Enter Your Current Age:\n"))
yrs_remaining = 90 - age
# Below code Calculates the number of Days, Weeks, Years from the above calculated variable.
days = yrs_remaining * 365
weeks = yrs_remaining * 52
months = yrs_remaining * 12
# Below code uses f-string to properly format all the above calculated Variables.
print(f"You have {days} days, {weeks} weeks, {months} months and {yrs_remaining} Years left.") |
cd4bdce361bda1dff7b0772022b1a2c168388f60 | lychunvira18/learning-python-bootcamp | /week01/ex/09_random_loop.py | 102 | 3.703125 | 4 | import random
N = input("Enter a number: ")
for x in range(int(N)):
print(random.randrange(100))
|
d4cbae1ce859d37d97d88e6975cf214542ef6d6a | ImranAvenger/uri-python | /1248.py | 838 | 3.578125 | 4 | n = input()
for nIndex in range(n):
alimentos = raw_input()
alimentosManha = raw_input()
alimentosAlmoco = raw_input()
cheat = False
alimentosRestantes = []
for alimento in alimentos:
alimentosRestantes.insert(len(alimentosRestantes), alimento)
for alimentoManha in alimentosManha:
try:
alimentosRestantes.remove(alimentoManha)
except ValueError:
cheat = True
for alimentoAlmoco in alimentosAlmoco:
try:
alimentosRestantes.remove(alimentoAlmoco)
except ValueError:
cheat = True
if cheat:
print "CHEATER"
continue
alimentosRestantes = sorted(alimentosRestantes)
texto = ""
for alimentoRestante in alimentosRestantes:
texto += alimentoRestante
print texto |
320f6bedfd5317a624404163bbb7c7e2a974ebb6 | SlyesKimo123/ComputadoraScience2 | /Object Oriented Programming/OOP_Chap16#2.py | 804 | 3.921875 | 4 | class Point:
def __init__(self, initX, initY):
""" Create a new point at the given coordinates. """
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
return self.y
def distanceFromOrigin(self):
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def __str__(self):
return "x=" + str(self.x) + ", y=" + str(self.y)
def halfway(self, target):
mx = (self.x + target.x) / 2
my = (self.y + target.y) / 2
return Point(mx, my)
def reflect_x(self):
getX = q.getX()
getY = q.getY()
reflection = getY * -1
print("The reflection of (", getX, ", ", getY, ") ", "is (", getX, ", ", reflection, ").")
p = Point(3, 4)
q = Point(5, 12)
p.reflect_x()
|
ecdc1884f2d586268d6443a26406ee0bd961a8a4 | Tonyhao96/LeetCode_EveryDay | /590_N-ary Tree Postorder Traversal.py | 925 | 3.671875 | 4 | #590_N-ary Tree Postorder Traversal
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
#Recursion
#Time complexity: O(n) Space complexity: O(n)
class Solution:
def postorder(self, root: 'Node') -> List[int]:
res = []
def recur(root):
if not root: return None
children = root.children
for i in children:
recur(i)
res.append(root.val)
recur(root)
return res
#Iteration
#Time complexity: O(n) Space complexity: O(n)
class Solution:
def postorder(self, root: 'Node') -> List[int]:
if not root: return None
stack, res =[root,], []
while stack:
node = stack.pop()
res.append(node.val)
for i in node.children:
stack.append(i)
return res[::-1] |
f70038eccce44b85c981b164bec29ffd605d00fd | int-invest/Lesson3 | /DZ3.py | 289 | 3.6875 | 4 | def my_func(var_1, var_2, var_3):
a = [var_1, var_2, var_3]
a.sort(reverse=True)
print(a[0] + a[1])
my_func(int(input('Введите первое число: ')), int(input('Введите второе число: ')), int(input('Введите третье число: ')))
|
7b45b338da13ed08d00c15fdad2fd3aa091dbcdd | avl-harshitha/WE-Programs | /assessment01/interweave.py | 504 | 3.90625 | 4 | import sys
def largest_str(str1, str2):
return max(str1, str2, key=lambda x: len(x))
def smallest_str(str1, str2):
return max(str1, str2, key=lambda x: -len(x))
def interweave_string():
str1 = sys.argv[1]
str2 = sys.argv[2]
large_str = largest_str(str1, str2)
small_str = smallest_str(str1, str2)
inter_string = "".join([str1[i] + str2[i] for i in range(len(small_str))])
inter_string += large_str[len(small_str):]
return inter_string
print(interweave_string()) |
6b1bbc10a853401491a2539790899f6af7dc402d | wengjinlin/Homework | /Day06/Course/core/School.py | 578 | 3.625 | 4 | import Course,C_class
class School(object):
#学校基类
def __init__(self,name,address):
#自有属性
self.NAME = name
self.ADDRESS = address
self.COURSES = []
self.C_CLASSES = []
def create_course(self,name,cycle,price):
#创建课程,并关联
course = Course.Course(name,cycle,price)
self.COURSES.append(course)
def create_c_class(self,name,teacher,course):
#创建班级,并关联
c_class = C_class.C_class(name,teacher,course)
self.C_CLASSES.append(c_class)
|
4a208806b221dbddf77e09711c91cf93d4aab2c4 | liorberi/WorldOfGames | /WorlfOfGames/MemoryGame.py | 982 | 3.828125 | 4 | import time
from random import randrange
import os
def generate_sequence(difficulty):
list = []
for num in range(difficulty):
list.append(randrange(1, 101))
print(list)
time.sleep(3)
cls()
return list
def get_list_from_user(difficulty):
list= []
for num in range(difficulty):
list.append(int(input("enter number between 1-101 \n")))
return list
def is_list_equal(randlist, userlist):
randlist.sort()
userlist.sort()
if randlist == userlist:
return True
else:
return False
def play(difficulty):
randlist = generate_sequence(difficulty)
userlist = get_list_from_user(difficulty)
print("the random list is: ")
print(randlist)
print("the user list is: ")
print(userlist)
if is_list_equal(randlist, userlist):
print("the user as won the game")
else:
print("the user as lost the game")
def cls():
os.system('cls' if os.name=='nt' else 'clear')
|
618afab33ac1f5e18d18042d3ed9fc6e4e9f538c | nataliegarate/python_ds | /lists/min_val_list.py | 276 | 3.71875 | 4 | def findMinimum(arr):
if len(arr) == 0:
return None
min_val = arr[0]
for num in arr:
if num < min_val:
min_val = num
return min_val
def findMinimum2(arr):
if len(arr) == 0:
return None
arr.sort()
return arr[0]
|
6ba4a74a78ceff20c5cad7810182879ccf74431d | yohuhu/robot-framework | /test_sample/util.py | 186 | 3.578125 | 4 | from datetime import datetime
def get_current_time():
now= datetime.now()
now_time=now.strftime("%Y-%m-%d-%H_%M_%S")
print(now_time)
return now_time
get_current_time() |
886fd88d18ecafef1779725f8749bfab7283840a | bmaltby/project-euler | /019.py | 784 | 3.796875 | 4 | # 1 Jan 1900 is Monday so 7th Jan 1900 is a sunday
days_in_month = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leap_years = {}
year = 1900
while year < 2001:
if (year % 4 == 0) and not (year % 100 == 0 and year % 400):
leap_years[year] = True
else:
leap_years[year] = False
year += 1
year = 1900
month = 1
day = 7
sundays = 0
while year < 2001:
day += 7
daysformonth = days_in_month[month]
if month == 2 and leap_years[year]:
daysformonth = 29
if day > daysformonth:
day -= daysformonth
month += 1
if month > 12:
month = 1
year += 1
if year == 2001:
print sundays
exit()
if day == 1 and year > 1900:
sundays += 1
|
10aa8696371bb97ca1376bb380055bebc88a128e | asxzhy/Leetcode | /leetcode/question_1556/solution_3.py | 812 | 4.0625 | 4 | """
Loop through the input, add every digit to the result string. If the digits
left in the input is divisible by three, then add a dot to the result string
"""
class Solution:
def thousandSeparator(self, n: int) -> str:
# initialize a string to store the result
res = ""
# convert the int to string
n = str(n)
# loop through the input
for i in range(len(n)):
# add the current digit to the result
res += n[i]
# calculate how many left digits there are in the input
size = len(n) - i - 1
# if the left digits can be exact divided by three, add a dot
# to the result
if size > 0 and size % 3 == 0:
res += "."
return res
|
1cb9b724990a47f8a2206f26bd6992cb13243cf9 | jespererik/sensor-module | /install.py | 3,389 | 3.53125 | 4 | from ConfigParser import RawConfigParser
"""
Example structure of the config file
#General information about the node
[NODE]
NAME = RaspberryPi3
SENSORS = DHT11-Temperature,DHT11-Humidity
LOCATION = Pannrum
#Defines the IP and port the server is hosted on
[NETWORK]
SERVER_IP = 192.168.0.121
SERVER_PORT = 3000
#Defines which pins a specific sensor is connected to
#The following two fields are bound to the name you give the sensors under the [NODE] tag
[SENSOR_PINS]
DHT11-Temperature = 11,4
DHT11-Humidity = 11,4
#Defines which types a specifik sensor supports
[READING_TYPES]
DHT11-Temperature = temperature
DHT11-Humidity = humidity
[AUTHORIZATION]
username = test
password = python
"""
def make_config_file():
config_init = RawConfigParser()
config_init.read("shared/node.conf")
config_init.add_section("NODE")
config_init.add_section("NETWORK")
config_init.add_section("SENSOR_PINS")
config_init.add_section("READING_TYPES")
config_init.add_section("AUTHORIZATION")
return config_init
def main():
sensor_pins = []
reading_types = []
config = make_config_file()
print "Welcome to the initial configuration of your sensor network"
node_name = raw_input("Enter the name you wish to use for the sensor node: ")
sensor_names = raw_input("Enter the names of the sensors you have connected: ")
node_location = raw_input("Enter the symbolic/physical location of your node: ")
server_ip = raw_input("Enter the ip your server module with be located at: ")
server_port = raw_input("Enter the port your server module will be located at:")
for sensor in sensor_names.split(","):
sensor_pins.append(raw_input("Enter the GPIO pins for {}:".format(sensor)))
reading_types.append(raw_input("Enter the type of reading for {}:".format(sensor)))
username = raw_input("Enter the username used for authorization to the server:")
password = raw_input("Enter the password used for authorization to the server:")
print "Generating config file with fields and values:"
print "[NODE] NAME = {}".format(node_name)
print "[NODE] SENSORS = {}".format(sensor_names)
print "[NODE] LOCATION = {}".format(node_location)
print "[NETWORK] SERVER_IP = {}".format(server_ip)
print "[NETWORK] SERVER PORT = {}".format(server_port)
for sensor, pins, reading_type in zip(sensor_names.split(","), sensor_pins, reading_types):
print "[SENSOR_PINS] {} = {}".format(sensor, pins)
print "[READING_TYPES] {} = {}".format(sensor, reading_type)
print "[AUTHORIZATION] USERNAME = {}".format(username)
print "[AUTHORIZATION] PASSWORD = {}".format(password)
config.set("NODE", "NAME", node_name)
config.set("NODE", "SENSORS", sensor_names)
config.set("NODE", "LOCATION", node_location)
config.set("NETWORK", "SERVER_IP", server_ip)
config.set("NETWORK", "SERVER_PORT", server_port)
for sensor, pins, reading_type in zip(sensor_names.split(","), sensor_pins, reading_types):
config.set("SENSOR_PINS", sensor, pins)
config.set("READING_TYPES", sensor, reading_type)
config.set("AUTHORIZATION", "USERNAME", username)
config.set("AUTHORIZATION", "PASSWORD", password)
with open("shared/node.conf", "w") as config_file:
config.write(config_file)
if __name__ == "__main__":
main()
|
9c5d6262ae9b22455159ab34a1c7d9fcb5809599 | monidan/shit-code-python-oop | /Pizzas.py | 2,808 | 3.734375 | 4 |
class Pizza:
def __init__(self, size):
self._size = size
self._price = 0
self.is_discounted = False
@property
def size(self):
return self._size
@property
def size_naming(self):
if self.size == 1:
return 'Маленька'
elif self.size == 2:
return 'Стандартна'
elif self.size == 3:
return'Велика'
@property
def price(self):
return self._price
@price.setter
def price(self, new_price):
if self.size_naming == 'Маленька':
self._price = round(new_price * 0.6 * 1.05)
elif self.size_naming == 'Стандартна':
self._price = round(new_price)
elif self.size_naming == 'Велика':
self._price = round(new_price * 1.4)
return self._price
def apply_discount(self, discount):
if self.is_discounted:
return None
self.price *= (1 - discount)
self.is_discounted = True
def __repr__(self):
raise Exception('Override __repr__ method')
class PizzaMeat10(Pizza):
def __init__(self, size):
super().__init__(size)
self.standart_price = 115
self.price = self.standart_price
def __repr__(self):
pizza_name = "Піцца 'чотири мʼяса'"
return '{name} (ціна: {price} грн, розмір: {size})'.format(name=pizza_name, price=str(self.price), size=self.size_naming)
class PizzaHunt14(Pizza):
def __init__(self, size):
super().__init__(size)
self.standart_price = 105
self.price = self.standart_price
def __repr__(self):
pizza_name = "Піцца 'Мисливська'"
return '{name} (ціна: {price} грн, розмір: {size})'.format(name=pizza_name, price=str(self.price), size=self.size_naming)
class PizzaSeafood8(Pizza):
def __init__(self, size):
super().__init__(size)
self.standart_price = 185
self.price = self.standart_price
def __repr__(self):
pizza_name = "Піцца з морепродуктами"
return '{name} (ціна: {price} грн, розмір: {size})'.format(name=pizza_name, price=str(self.price), size=self.size_naming)
class PizzaCaprichosis5(Pizza):
def __init__(self, size):
super().__init__(size)
self.standart_price = 145
self.price = self.standart_price
def __repr__(self):
pizza_name = "Капрічоза"
return '{name} (ціна: {price} грн, розмір: {size})'.format(name=pizza_name, price=str(self.price), size=self.size_naming)
class PizzaBBQ15(Pizza):
def __init__(self, size):
super().__init__(size)
self.standart_price = 150
self.price = self.standart_price
def __repr__(self):
pizza_name = "Курка BBQ"
return '{name} (ціна: {price} грн, розмір: {size})'.format(name=pizza_name, price=str(self.price), size=self.size_naming)
|
b94e793846b5e36fe42504ef8d0cea237a179421 | alesalsa10/pdf_to_voice | /pdf_reader.py | 907 | 3.796875 | 4 | #extract text from pdf and read it using google text to speech
import PyPDF2, os
from gtts import gTTS
from sys import argv
pdf_name = argv[1]
txt_name = argv[2]
mp3_name = argv[3]
def text_extractor():
with open(f'{pdf_name}.pdf','rb') as pdf_file, open(f'{txt_name}.txt', 'w',encoding='utf-8') as text_file:
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
all_pages = pdf_reader.getNumPages()
for page_number in range(all_pages):
page = pdf_reader.getPage(page_number)
content = page.extractText()
text_file.write(content)
def text_to_speech():
file_to_read = open(f'{txt_name}.txt', 'r')
text = file_to_read.read()
language = 'en'
output = gTTS(text = text, lang=language, slow=False)
output.save(f'{mp3_name}.mp3')
file_to_read.close()
os.system(f'start {mp3_name}.mp3')
text_extractor()
text_to_speech()
|
775e7d7f7fa2a1891ee598048dba9989a85baa90 | WXLyndon/Data-structures-and-algorithms-review | /array/merge_sorted_arrays.py | 865 | 3.953125 | 4 | # input:[0,3,4,31], [4,6,30]
# output: [0,3,4,4,6,30,31]
def merge(arr1, arr2):
mergeArr = []
# Check if arr1 or arr2 is empty
if len(arr1) == 0:
return arr2
if len(arr2) == 0:
return arr1
arr1_index = 0
arr2_index = 0
while (arr1_index < len(arr1)) or (arr2_index < len(arr2)): # any input arr is not entirely checked
# arr1 is not entirely checked; and arr2 is entirely checked, or current arr1 item is less than current arr2 item.
if (arr1_index < len(arr1)) and ((arr2_index >= len(arr2)) or (arr1[arr1_index] < arr2[arr2_index])):
mergeArr.append(arr1[arr1_index])
arr1_index += 1
else:
mergeArr.append(arr2[arr2_index])
arr2_index += 1
return mergeArr
# print(merge([0,3,4,31],[4,6,30]))
print(merge([4,6,30],[0,3,4,31])) |
d2d9c3df38af646d3c725297b0a023462a7dea6e | mcclosr5/Python-code | /birthday_021.py | 1,000 | 4.03125 | 4 | #!/usr/bin/env python3
import sys
import calendar
def days(y, m, d):
b = calendar.weekday(y, m, d)
if b == 0:
return "You were born on a Monday and Monday's child is fair of face."
elif b == 1:
return "You were born on a Tuesday and Tuesday's child is full of grace."
elif b == 2:
return "You were born on a Wednesday and Wednesday's child is full of woe."
elif b == 3:
return "You were born on a Thursday and Thursday's child has far to go."
elif b == 4:
return "You were born on a Friday and Friday's child is loving and giving."
elif b == 5:
return "You were born on a Saturday and Saturday's child works hard for a living."
elif b == 6:
return "You were born on a Sunday and Sunday's child is fair and wise and good in every way."
def main():
day = int(sys.argv[1])
month = int(sys.argv[2])
year = int(sys.argv[3])
print(days(year, month, day))
if __name__ == '__main__':
main()
|
a8349f6cbee5cdb6458375df35ed7d4414f5adc6 | TheElderMindseeker/pmldl-assignment-1 | /task_2.py | 6,461 | 3.75 | 4 | """Implementation of simulated annealing algorithm for travelling salesman"""
import os
from copy import copy
from math import exp
from random import random, randrange, shuffle
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from geopy.distance import geodesic
from matplotlib.animation import FuncAnimation
from tqdm import tqdm
def population_to_int(population):
"""Converts population to integer value ignoring malformed values"""
try:
return int(population)
except ValueError:
return np.nan
def extract_city_coordinates(city_data, city_name):
"""Extracts coordinates of the chosen city as a tuple of floats"""
coords_df = city_data[city_data.city == city_name][['geo_lat', 'geo_lon']]
return coords_df.iat[0, 0], coords_df.iat[0, 1]
def calculate_total_distance(city_names, distances):
"""Calculates the total distance travelling through the cities
The order of elements in ``city_names`` matters.
Returns:
Scalar - the total distance of travelling in kilometers.
"""
total_distance = 0
for i, city_a in enumerate(city_names):
next_i = (i + 1) % len(city_names)
city_b = city_names[next_i]
total_distance += distances[f'{city_a}-{city_b}']
return total_distance
def new_route_proposal(city_names):
"""Generates a new route proposal for the travel
The new route is generated by exchanging the positions of two cities in the
path.
"""
index_a = randrange(len(city_names))
index_b = randrange(len(city_names))
names_copy = copy(city_names)
names_copy[index_a], names_copy[index_b] = (names_copy[index_b],
names_copy[index_a])
return names_copy
def simulated_annealing(city_names,
distances,
max_iters: int,
initial_T: float = 2.0,
decay_constant: float = 1.0):
"""Use SA algorithm to find the shortest path around all the cities
Args:
city_names: List of cities to travel around.
distances: Object containing the distance between any pair of cities
present in ``city_names``. The object can be anything as long as
``calculate_total_distance`` helper knows how to handle it.
max_iters: Maximum iterations for the algorithm.
initial_T: Starting temperature factor.
decay_constant: lambda value in exponential decay formula.
"""
current_route = copy(city_names)
shuffle(current_route)
best_result = calculate_total_distance(current_route, distances)
current_distance = best_result
best_route = copy(current_route)
sample_routes = list()
T = initial_T
for i in tqdm(range(max_iters)):
route_proposal = new_route_proposal(current_route)
proposal_distance = calculate_total_distance(route_proposal, distances)
if proposal_distance < current_distance:
current_route = route_proposal
current_distance = proposal_distance
if current_distance < best_result:
best_result = current_distance
best_route = current_route
sample_routes.append(best_route)
else:
try:
acceptance_value = exp(
(current_distance - proposal_distance) / T)
except ZeroDivisionError:
break
if random() < acceptance_value:
current_route = route_proposal
current_distance = proposal_distance
T = initial_T * exp(-decay_constant * (i + 1))
return best_route, sample_routes
def draw_route(route, line, city_data):
"""Draw a line representing a route around the cities
Args:
route: Ordered list of cities in a route.
line: Object to use for line drawing.
city_data: City information containing coordinates.
Returns:
Line object used for drawing.
"""
xdata, ydata = list(), list()
for city_name in route:
city_y, city_x = extract_city_coordinates(city_data, city_name)
xdata.append(city_x)
ydata.append(city_y)
xdata.append(xdata[0])
ydata.append(ydata[0])
line.set_data(xdata, ydata)
return line,
def animate_annealing(sample_routes, city_data):
"""Create an animation object of annealing visualization
Args:
sample_routes: List of routes generated during annealing.
city_data: City information containing coordinates.
Returns:
Animation object.
"""
figure = plt.figure()
axes = plt.axes(xlim=(20, 145), ylim=(40, 65))
line, = axes.plot(list(), list(), lw=2)
animation = FuncAnimation(figure,
draw_route,
frames=sample_routes,
fargs=(line, city_data),
blit=True)
return animation
def main():
"""Driver method of the script"""
script_dir = os.path.dirname(os.path.abspath(__file__))
city_data: pd.DataFrame = pd.read_csv(
os.path.join(script_dir, 'cities.csv'),
converters={'population': population_to_int})
# Take 30 most populated cities
city_data.sort_values('population', ascending=False, inplace=True)
city_data = city_data[:30]
city_names = list(city_data['city'])
distances = dict()
for name_a in city_names:
for name_b in city_names:
coords_a = extract_city_coordinates(city_data, name_a)
coords_b = extract_city_coordinates(city_data, name_b)
distances[f'{name_a}-{name_b}'] = geodesic(coords_a, coords_b).km
best_route, sample_routes = simulated_annealing(city_names,
distances,
10000000,
initial_T=100,
decay_constant=1e-5)
best_distance = calculate_total_distance(best_route, distances)
best_route.append(best_route[0])
print('Best route found:')
print(' -> '.join(best_route))
print(f'Total distance: {best_distance:.3f} km')
animation = animate_annealing(sample_routes, city_data)
animation.save(os.path.join(script_dir, 'animation.mp4'))
if __name__ == '__main__':
main()
|
43d0cd15627781349397ae2815a71b787fe3b17d | lucioeduardo/competitive-codes | /2019/Jadson/CP3-CAP2/2.2.1/1.py | 162 | 3.8125 | 4 | lista = [3,1,2,3,4]
lista.sort()
for cont in range(len(lista) - 1):
if lista[cont] == lista[cont+1]:
print("Encontrou")
break
else:
print("Não encontrou") |
0d1aa16281716aa81127bc8595b548f2ef2ee6e0 | Foh-k/algorithm_lecture | /insertion_sort.py | 664 | 3.765625 | 4 | import random
# 0~100の値を持つ15要素配列を乱数で生成
def make_randlist(n=15):
return list(random.randrange(100) for _ in range(n))
# 挿入する.実装方法の関係上後ろから降順か比較をしている
def insertion_sort(lst):
for i in range(1, len(lst)):
idx = i
while(idx > 0 and lst[idx - 1] > lst[idx]):
tmp = lst[idx - 1]
lst[idx - 1] = lst[idx]
lst[idx] = tmp
idx -= 1
def main():
lst = make_randlist()
print("ソート前")
print(lst)
insertion_sort(lst)
print("ソート後")
print(lst)
if __name__ == "__main__":
main()
|
3ef6e2e28e71eddf1dbafa4525a2a9c917e8766d | wobushimotou/Daily | /python/day8.py | 799 | 3.890625 | 4 | #!/usr/bin/env python
# coding=utf-8
#定义类描述数字时钟
from time import sleep
import os
class Clock:
def __init__(self,hour=0,minute=0,second=0):
self.__hour = hour
self.__minute = minute
self.__second = second
def run(self):
self.__second += 1
if(self.__second == 60):
self.__minute += 1
self.__second = 0
if(self.__minute == 60):
self.__hour += 1
self.__minute = 0
if(self.__hour == 24):
self.hour = 0
def show(self):
return '%2d:%2d:%2d'%(self.__hour,self.__minute,self.__second)
def main():
c = Clock()
while True:
print(c.show())
sleep(1)
os.system('clear')
c.run()
if __name__ == '__main__':
main()
|
ef552d311969ad338074e638c19069c5f465c5fa | Simranbassi/python_grapees | /ex3a.py | 170 | 4.15625 | 4 | age=int(input("enter the age of the candidate"))
if age>=18:
print("candidate is eligible for the voting")
else :
print("candidate is not eligibble for the voting") |
1d017ea004d23e9bc087833165289e7aa9497c88 | zhangxinli/leetcode | /back/next_permutute.py | 918 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-11-18 16:24:36
# @Author : xinli (xinli.zxl@foxmail.com)
# @Link :
# @Version : $Id$
class Solution:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums :
return
if len(nums)==0 or len(nums)==1:
return
i = len(nums)-2
while i>=0 :
if nums[i] < nums[i+1]:
break
i-=1
if i ==-1:
nums.reverse()
return
j=i+1
while j < len(nums)-1:
if nums[j] > nums[i] and nums[j+1] <= nums[i]:
break
j+=1
print(i,j)
temp= nums[i]
nums[i] = nums[j]
nums[j]= temp
nums[i+1:len(nums)] = nums[len(nums)-1:i:-1]
|
a4907434978c2c20342f82eee54f10e644e05e79 | ArturasDo/Pamoka-Nr.9-Ciklai | /ArturasDo Homework 9.1.py | 578 | 4.0625 | 4 | # Converter: kilometers into miles
print(" ")
print ("It's a converter, that converts kilometers into miles")
while True:
print(" ")
km = input("Please enter number of kilometers: ")
km = float(km.replace(",", "."))
miles = km * 0.621371
print("Result: " + str(km) + " kilometers = " + str(miles) + " miles.")
#ka reiskia pavyzdyje sekantis print su{} skliausteliais:
print("{0} kilometers is {1} miles.".format(km, miles))
z = input("Would you like to continue (Y/N)?")
f = z.lower()
if f != "y":
print("End of job.")
break
|
5559bf0140430cc15024246df7ced04e0f614997 | DStheG/ctci | /01_Arrays_and_Strings/01_Is_Unique.py | 2,230 | 4.15625 | 4 | #!/usr/bin/python
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1.1 Is Unique
Implement an algorithm to determine if a string has all unique characters.
What if you cannot use additional data structures?
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
import string
import sys
sys.path.append("../")
from module.ctci import Exercise
from module.ctci import Solution
from module.sort import quick_sort
from module.sort import merge_sort
from module.str import string_gen
CHARS_SET = string.printable
class Ex_01_01(Exercise):
def setup(self):
self.param.append(string_gen(chars=CHARS_SET))
class Ex0101(Solution):
# O(N*N)
def Naive(self, param):
r_str = param[0]
for i in range(len(r_str)):
for j in range(i+1, len(r_str)):
if r_str[i] == r_str[j]:
return "NOT Unique"
return " Unique"
#O(NlogN)
def QuickSort(self, param):
r_str = param[0]
sorted_str = quick_sort(list(r_str))
for i in range(1, len(sorted_str)):
if sorted_str[i-1] == sorted_str[i]:
return "NOT Unique"
return " Unique"
#O(NlogN)
def MergeSort(self, param):
r_str = param[0]
sorted_str = merge_sort(list(r_str))
for i in range(1, len(sorted_str)):
if sorted_str[i-1] == sorted_str[i]:
return "NOT Unique"
return " Unique"
# O(??)
def libSort(self, param):
r_str = param[0]
sorted_str = ''.join(sorted(r_str))
for i in range(1, len(sorted_str)):
if sorted_str[i-1] == sorted_str[i]:
return "NOT Unique"
return " Unique"
# O(N)
def Bucket(self, param):
r_str = param[0]
# THERE ARE ONLY 128 ASCIIs
number_of_printable_chars = len(CHARS_SET)
bucket = [0] * 128
for i in range(len(r_str)):
if bucket[ord(r_str[i])] == 0:
bucket[ord(r_str[i])] = 1
else:
return "NOT Unique"
return " Unique"
def solve():
ex = Ex_01_01()
ex.add_solution(Ex0101("Naive"))
ex.add_solution(Ex0101("QuickSort"))
ex.add_solution(Ex0101("MergeSort"))
ex.add_solution(Ex0101("libSort"))
ex.add_solution(Ex0101("Bucket"))
ex.solve()
if __name__ == "__main__":
solve()
|
e439ec29ded67a1f183b765666cad6fe69850ac9 | rahuladream/Python-Exercise | /Edugrade/create_2d.py | 467 | 4.03125 | 4 | """
QUESTION 7:
Create a 2-D list from the given input. You will get 2 inputs 1st parameter is the no. of elements in the list and the 2nd parameter is the no. of lists.
the elements inside the list should start from 0 and end at n-1.
Example -
Input - 8 3
Output - [
[0,1,2,3,4,5,6,7],
[0,1,2,3,4,5,6,7],
[0,1,2,3,4,5,6,7],
]
"""
def main(i,j):
arry = []
for j in range(j):
arry.append([i for i in range(i)])
return arry
print(main(8,3)) |
cbd5e5b257a41e92ad04be1d615d50f06fe86956 | ungerw/class-work | /ch3ex2.py | 302 | 4.125 | 4 | try:
hours = float(input('Hours Worked: '))
rate = float(input('Rate of Pay: '))
if hours <= 40:
pay = hours * rate
print(pay)
elif hours > 40:
pay = (40 * rate) + ((hours - 40) * (rate * 1.5))
print(pay)
except:
print('Please enter a numeric input') |
0ef253599f0c72e5f2876997c0bf0ae7dc950da6 | TanakitInt/Python-Year1-Archive | /In Class/Week 5/username.py | 524 | 4.34375 | 4 | # username.py
# Simple string processing program to generate usernames:
# First initial + first seven characters of last name
def main():
print("This program generates computer usernames.\n")
# get user's first and last names
first = input("Please enter your first name: ")
last = input("Please enter your last name: ")
# concatenate first initial with 7 chars of the last name.
uname = first[0].upper() + last[:7].lower()
# output the username
print("Your username is:", uname)
main()
|
e3d04afeaf18ae4057eaf0c2a877473a93f06a43 | qmnguyenw/python_py4e | /geeksforgeeks/python/basic/2_11.py | 2,507 | 4.09375 | 4 | How to Get the Tkinter Label Text?
**Prerequisite:**Python GUI – Tkinter
Python offers multiple options for developing a GUI (Graphical User
Interface). Out of all the GUI methods, _tkinter_ is the most commonly used
method. It is a standard Python interface to the Tk GUI toolkit shipped with
Python. Python with _tkinter_ is the fastest and easiest way to create GUI
applications. Creating a GUI using tkinter is an easy task.
In this article, we are going to write a Python script to get the _tkinter_
label text. Below are the various methods discussed:
**Method #1:** Using _cget()_ method.
**Approach:**
* Importing the module.
* Create the main window (container).
* Add Label widgets to the main window.
* Apply the _cget()_ method and get label text.
**Implementation:**
## Python3
__
__
__
__
__
__
__
# import modules
import tkinter as tk
# object of tkinter
# and background set for light grey
master = tk.Tk()
master.configure(bg='light grey')
# create label
l = tk.Label(master,
text="Welcome to geeksforgeeks",
bg="red")
# apply cget()
print("Label text: ", l.cget("text"))
l.pack()
master.mainloop()
---
__
__
**Output:**

**Method #2:** Using Dictionary label object.
**Approach:**
* Importing the module.
* Create the main window (container).
* Add Label widgets to the main window.
* Use Dictionary label object and get label text.
## Python3
__
__
__
__
__
__
__
# import modules
import tkinter as tk
# object of tkinter
# and background set for light grey
master = tk.Tk()
master.configure(bg = 'light grey')
# create label
l = tk.Label(master,
text = "Welcome to geeksforgeeks",
bg = "red")
# using dictionary label object
print("Label text: ", l["text"])
l.pack()
tk.mainloop()
---
__
__
**Output:**

Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
cb8e50b6b433109f1fae871a26205f5041ffae9a | rjc89/LeetCode_medium | /jump_game.py | 558 | 3.71875 | 4 | # https://leetcode.com/problems/jump-game/discuss/774588/Python%3A-Easy!-Linear-Time-O(n)-and-Space-O(1)-oror-Explanation
from typing import List
class Solution:
def canJump(self, nums: List[int]) -> bool:
reachableIndex = 0
for curr in range(len(nums)):
if curr + nums[curr] >= reachableIndex:
reachableIndex = curr + nums[curr]
if curr == reachableIndex:
break
return reachableIndex >= len(nums) - 1
s = Solution()
print(s.canJump(nums = [2,3,1,1,4]))
|
7b16d5c1a3d135a627b29a9495179b3666c4059c | byAbaddon/Book-Introduction-to-Programming-with----JavaScript____and____Python | /Pyrhon - Introduction to Programming/4.2. Complex Conditions - Exam Problems/03. Operations.py | 538 | 4 | 4 | n_one, n_two, operator = int(input()), int(input()), input()
try:
result = eval(f'n_one {operator} n_two')
if operator == '+' or operator == '-' or operator == '*':
is_even = 'even' if result % 2 == 0 else 'odd'
print(f'{n_one} {operator} {n_two} = {result} - {is_even}')
elif operator == '/':
print(f'{n_one} {operator} {n_two} = {result:.2f}')
else:
print(f'{n_one} {operator} {n_two} = {result}')
except:
print(f'Cannot divide {n_one} by zero')
'''
7
3
*
#7 * 3 = 21 - odd
'''
|
f73473a4fafe47c0f65f2abc9a30da23a4d78d08 | Prateeek73/90PlusBasicPythonCodes | /Codes/14.py | 251 | 3.8125 | 4 | d={'UPPERCASE':0,
'LOWERCASE':0}
for c in input("Enter the sentence"):
if c.isupper():
d["UPPERCASE"]+=1
elif c.islower():
d["LOWERCASE"]+=1
else:
pass
for key,value in d.items():
print(key+" : "+str(value))
|
2c11614a14e3e3d2d5492d42fde3eb665f166f4a | alexandrebarbaruiva/UnBChatBot | /bot/chatbotDAO.py | 3,868 | 3.84375 | 4 | """
Modulo responsavel pela interacao com o banco de dados.
TODO: Melhorar a documentacao
"""
import os
import sqlite3
class DAO():
"""Objeto responsavel por manipular o banco de dados."""
def __init__(self, database_path="chatbot.db"):
self._database_path = database_path
self._is_connected = False
if not os.path.exists(database_path):
print('Banco de dados nao encontrado.')
print('Deseja (re)criar um novo banco?(y/n)')
ans = input().lower()
if ans.startswith('y'):
self.create_new_bank()
def __connect(self):
"""Faz a conexao com o db"""
if not self._is_connected:
self._conn = sqlite3.connect(self._database_path)
self._cursor = self._conn.cursor()
self._is_connected = True
def __close(self):
"""Commita novas mudancas e fecha conexao com o db"""
if self._is_connected:
self._conn.commit()
self._conn.close()
self._is_connected = False
def create_new_bank(self):
"""
Cria um novo banco de dados baseado
em um script passado pelo usuario
"""
script = input(
'Digite o nome do arquivo contendo o script de criacao do banco: ')
while not os.path.exists(script):
script = input('Arquivo nao encontrado, favor digitar novamente: ')
self._database_path = input('Digite o nome do arquivo do novo banco: ')
self.__connect()
with open(script, 'r') as f:
self._cursor.executescript(f.read())
self.__close()
print('Banco de dados criado com sucesso')
def execute(self, query, params=()):
"""
Executa uma query e retorna o resultado. Trata excecoes
causadas pelo sqlite imprimindo os erros para o console.
"""
self.__connect()
try:
self._cursor.execute(query, params)
except sqlite3.Error as e:
print('Ocorreu um erro durante a execucao da query', query)
print('Mensagem do erro:', e)
finally:
data = self._cursor.fetchall()
self.__close()
return data
class DataHandler():
"""Faz a interacao com o banco de dados de uma maneira mais especifica."""
def __init__(self):
self._bd = DAO()
def get_user_by_id(self, telegram_id):
"""Retorna os dados do usuario baseado no seu ID"""
data = self._bd.execute(
'SELECT * FROM USUARIO WHERE TELEGRAM_ID = ?;', (int(telegram_id),)
)
return data
def get_user_message_history(self, telegram_id):
"""Retorna uma lista contendo todas a mensagens de um usuario"""
data = self._bd.execute(
""" SELECT TEXTO FROM MENSAGEM JOIN USUARIO
ON USUARIO.TELEGRAM_ID = MENSAGEM.USUARIO WHERE TELEGRAM_ID = ?;
""", (int(telegram_id),)
)
return data
def store_new_user(self, telegram_id, name=''):
"""Guarda as informacoes de um novo usuario no BD"""
self._bd.execute(
"""INSERT INTO USUARIO(TELEGRAM_ID, NOME)
VALUES(?, ?)""", (int(telegram_id), str(name))
)
def store_new_message(self, telegram_id, text):
"""Guarda uma nova mensagem de texto de um usuario"""
self._bd.execute(
"""INSERT INTO MENSAGEM(NUMERO, TEXTO, USUARIO)
VALUES(NULL, ?, ?)""", (str(text), int(telegram_id))
)
# TODO: Pegar historia de mensagens a partir de uma certa data
if __name__ == '__main__':
"""Cria um novo banco de dados quando executado"""
print('Um novo banco de dados sera criado, deseja continuar? (y/n)')
ans = input().lower()
if ans.startswith('y'):
a = DAO()
a.create_new_bank() |
03ceee50ed6dd2d7c2c3d1024057dbc01de70c59 | juriadrian/KernelSimulator | /FileSys/File.py | 791 | 3.546875 | 4 | __author__ = 'adri'
class File():
def __init__(self, file_name, inode):
self.name = file_name
self.inode = inode
class INode():
def __init__(self, name):
self.name = name
self.pointer = []
def add_pointer(self, pointer):
self.pointer.append(pointer)
class Data():
def __init__(self, program_name, size):
self.program_name = program_name
self.actual_key = None
self.blocks = {} #Dictionary where the key is the sector in the hard disk and the value is in which block is allocated the instruction
self.size = size
def save_data(self, key, value):
if key != self.actual_key:
self.blocks[key] = []
self.actual_key = key
self.blocks[key].append(value)
|
4808a1b4e8e494715e07f9d3c8eae2c0cadca10b | zh0uquan/LeetcodePractice | /Leetcode238.py | 1,167 | 3.609375 | 4 | class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
size = len(nums)
res = [1] * size
def helper(output, list, start, end, step=1):
p = 1
for i in range(start, end, step):
output[i] *= p
p *= list[i]
return output
# left
res = helper(output=res, list=nums, start=0, end=size)
# right
res = helper(output=res, list=nums, start=size-1, end=-1, step=-1)
return res
# def productExceptSelf(self, nums):
# """
# :type nums: List[int]
# :rtype: List[int]
# """
# product = 1
# counter = 1
# for num in nums:
# if num != 0:
# product *= num
# else:
# counter -= 1
#
# if counter < 0:
# return [0] * len(nums)
# elif counter == 0:
# return [ product if num == 0 else 0 for num in nums]
# return [product/num for num in nums]
print(Solution().productExceptSelf([1, 2, 3, 4, 1]))
|
d61fd596bc639c3cfa5328871097d441e24b95aa | theTonyHo/armacode | /source/examples/List_GetNextItem.py | 668 | 4.125 | 4 | """
Example:
How to advance to the next item in a list by providing a direction.
The logic here applies to most scriptincg languages. However, ` % totalCount` is unneccessary in Python as it accept index greater than the length of the list.
"""
dataList = ['a','b','c','d','e']
totalCount = len(dataList)
print dataList
for curIndex in range(totalCount):
print "Current Item: ", dataList[curIndex]
nextIndex = (curIndex + 1) % totalCount
print "Advance to the next item:", dataList[nextIndex]
nextIndex = (curIndex - 1) % totalCount
print "Advance to the prev item:", dataList[nextIndex]
print ""
|
b618964112e46449b9be0909db6c8fe832785274 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/anagram/4e6c06c3a90f412ea74eb3ef49621621.py | 1,444 | 4.0625 | 4 | import collections
class Anagram(object):
def __init__(self, word):
# _word is the normalized version of word.
word = word or ""
self._word = word.lower()
# _char_count is a dict containing the count of each character in _word.
self._char_count = collections.Counter(self._word)
def match(self, strings):
# The following code works in Python 2 but not Python 3.
#
# return filter(self._is_anagram, strings)
#
# I don't perticularly like the syntax of list comprehension, but I guess
# it's one of those things you simple get used to after a while. Any other
# suggestions on a short version that works in both? :)
#
# return [string for string in strings if self._is_anagram(string)]
matches = []
for string in strings:
if self._is_anagram(string):
matches.append(string)
return matches
def _is_anagram(self, string):
if len(string) != len(self._word):
# Length differ, thus string cannot be an anagram.
return False
s = string.lower()
if s == self._word:
# Anagrams should differ from the original word.
return False
# char_count is a dict containing the count of each character in s.
char_count = collections.defaultdict(int)
for c in s:
if not c in self._char_count:
# If the character c isn't present in _char_count s cannot be
# an anagram of _word.
return False
char_count[c] += 1
if self._char_count == char_count:
return True
return False
|
7bae8a20bf6f694822e16294311f609792c5c2a5 | bharat-kadchha/tutorials | /core-python/Core_Python/regexpkg/Regex_As_2.py | 698 | 4.5 | 4 | ''' The check_time function checks for the time format of a 12-hour clock, as follows:
the hour is between 1 and 12, with no leading zero, followed by a colon, then
minutes between 00 and 59, then an optional space, and then AM or PM, in upper or
lower case. Fill in the regular expression to do that. How many of the concepts
that you just learned can you use here? '''
import re
def check_time(text):
pattern = r"([1-9]|1[012]):(0[0-9]|[12345][0-9])[\s|am|pm|PM|AM]"
result = re.search(pattern, text)
return result != None
print(check_time("12:45pm")) # True
print(check_time("9:59 AM")) # True
print(check_time("6:60am")) # False
print(check_time("five o'clock")) # False |
de1fd508febf44ff74224b82998f400d3e39dc7e | oliviadxm/python_work | /chapter_6/chapter_6.py | 3,775 | 3.984375 | 4 | #6-1
print("---------6/1---------")
person = {
'first_name': 'hyesung',
'last_name': 'shin',
'age': 39,
'city': 'seoul',
}
print(person['first_name'])
print(person['last_name'])
print(person['age'])
print(person['city'])
#6-2
print("---------6/2---------")
favorite_num = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5,
}
print("A's favorite number is " + str(favorite_num['A']))
print("B's favorite number is " + str(favorite_num['B']))
print("C's favorite number is " + str(favorite_num['C']))
print("D's favorite number is " + str(favorite_num['D']))
print("E's favorite number is " + str(favorite_num['E']))
#6-3
print("---------6/3---------")
glossary = {
'print': 'output the value',
'str': 'convert number to string',
'title': 'capitalize the first letter of the word',
'for': 'loop through each value in the list',
'if-else': 'check for condition',
}
print('print: ' + glossary['print'])
print('str: ' + glossary['str'])
print('title: ' + glossary['title'])
print('for: ' + glossary['for'])
print('if-else: ' + glossary['if-else'])
#6-4
print("---------6/4---------")
glossary['list'] = 'a list of values'
glossary['range'] = 'a list of numbers in the range given'
glossary['append'] = 'append the value to the end of the list'
glossary['insert'] = 'insert value to the position given'
glossary['del'] = 'delete a value'
for key, value in glossary.items():
print(key + ": " + value)
#6-5
print("---------6/5---------")
rivers = {
'nile': 'egypt',
'yellow-river': 'china',
'han-river': 'korea',
}
for key, value in rivers.items():
print("The " + key.title() + " runs through " + value.title())
for key in rivers.keys():
print(key)
for value in rivers.values():
print(value)
#6-6
print("---------6/6---------")
print("exercise is in favorite_languages.py")
#6-7
print("---------6/7---------")
person2 = {
'first_name': 'eric',
'last_name': 'mun',
'age': 39,
'city': 'seoul',
}
person3 = {
'first_name': 'andy',
'last_name': 'lee',
'age': 38,
'city': 'seoul',
}
people = [person, person2, person3]
for p in people:
print("First Name: " + p['first_name'].title())
print("Last Name: " + p['last_name'].title())
print("Age: " + str(p['age']))
print("City: " + p['city'].title())
print("---")
# 6-8
print("---------6/8---------")
pet1 = {
'kind': 'dog',
'owner': 'alex',
}
pet2 = {
'kind': 'cat',
'owner': 'ben',
}
pet3 = {
'kind': 'dog',
'owner': 'jeo',
}
pets = [pet1, pet2, pet3]
for pet in pets:
print("Pet Kind: " + pet['kind'] + " Owner: " + pet['owner'])
# 6-9
print("---------6/9---------")
favorite_places = {
'james': ['las vegas', 'boston'],
'lena': ['new york', 'seattle', 'beijing'],
'pat': ['london', 'paris']
}
for key, value in favorite_places.items():
print(key.title() + "'s favorite places are: ")
for v in value:
print(v.title())
# 6-10
print("---------6/10---------")
favorite_nums = {
'A': [1, 2],
'B': [2, 3],
'C': [3],
'D': [4, 8],
'E': [5, 6],
}
for key, value in favorite_nums.items():
print(key + "'s favorite numbers are(is):")
for v in value:
print(v)
# 6-11
print("---------6/11---------")
cities = {
'boston': {
'state': 'ma',
'place': 'boston common',
'zip': '01801',
},
'seattle': {
'state': 'wa',
'place': 'space needle',
'zip': '98119',
},
'new york': {
'state': 'ny',
'place': 'time square',
'zip': '10004',
},
}
for city, city_info in cities.items():
print(city.title())
for k, v in city_info.items():
print(k.title() + ": " + v.title())
|
0eeeabd6e181bfe320b9c5417042415cbc40dc4b | zZedeXx/My_1st_Game | /Unuse/3..py | 457 | 4.09375 | 4 | # Написать функцию,
# принимающую произвольное кол-во чисел и возвращающую кортеж всех целых чисел,
# т.е. все дробные значения отсеиваются функцией.
def Function(*args):
lst = list(args)
for s in lst[:]:
if type(s) == float:
lst.remove(s)
return tuple(lst)
print(Function(2.5, 6.2, 87, 0.5, 90.2, 7))
|
bc3d4c5ec5ff266683b7cfc387a3cd16c87e5865 | jdrestre/Online_courses | /Udemy/Python_sin_fronteras_HTML_CSS_Flask_MySQL/ejercicios.py | 984 | 4.03125 | 4 | # dato = input('Ingrese dato: ')
# lista = ['hola', 'mundo', 'chanchito', 'feliz', 'dragones']
# if lista.count(dato) > 0:
# print('El dato existe:', dato)
# else:
# print('El dato no existe :(', dato)
primero = input('Ingrese primer número: ')
try:
primero = int(primero)
except:
primero = 'chanchito feliz'
if primero == 'chanchito feliz':
print('El valor ingresado no es un entero')
exit()
segundo = input('Ingrese segundo número: ')
try:
segundo = int(segundo)
except:
segundo = 'chanchito feliz'
if segundo == 'chanchito feliz':
print('El valor ingresado no es un entero')
exit()
simbolo = input('ingrese operación: ')
if simbolo == '+':
print('Suma:', primero + segundo)
elif simbolo == '-':
print('Resta:', primero - segundo)
elif simbolo == '*':
print('Multiplicación:', primero * segundo)
elif simbolo == '/':
print('División:', primero / segundo)
else:
print('El símbolo ingresado no es válido')
|
81e38c89ddffcfc50842364278c38d5386c43123 | SaiPrathekGitam/MyPythonCode | /oop/account.py | 796 | 3.546875 | 4 | from oop import amount_error as er
class SavingsAccount:
def __init__(self, acno, name, bal):
self.acno = acno
self.name = name
self.bal = bal
def print_details(self):
print("Account Number : ", self.acno)
print("Name : ", self.name)
print("Balance : ", self.bal)
def deposit(self, amount):
self.bal += amount
def withdraw(self, amount):
try:
if amount > self.bal:
raise er.AmountError("Insufficient Balance")
except Exception as ex:
print(ex)
else:
self.bal -= amount
a = SavingsAccount(1, "Prathek", 1000)
a.withdraw(5000)
a.deposit(5000)
a.withdraw(2000)
a.print_details()
|
37824fc95aa1bb6f02b5242031e3939aa5494ef9 | sandeepkumar8713/pythonapps | /22_secondFolder/37_alphabet_board_path.py | 3,090 | 4.03125 | 4 | # https://leetcode.com/problems/alphabet-board-path/
# https://leetcode.com/problems/alphabet-board-path/discuss/414431/python-O(n)-z-explanation
# Question : On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].
# Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"],
# We may make the following moves:
#
# 'U' moves our position up one row, if the position exists on the board;
# 'D' moves our position down one row, if the position exists on the board;
# 'L' moves our position left one column, if the position exists on the board;
# 'R' moves our position right one column, if the position exists on the board;
# '!' adds the character board[r][c] at our current position (r, c) to the answer.
# (Here, the only positions that exist on the board are positions with letters on them.)
#
# Return a sequence of moves that makes our answer equal to target in the minimum number of moves.
# You may return any path that does so.
#
# Example : Input: target = "leet"
# Output: "DDR!UURRR!!DDD!"
#
# Question Type : Generic
# Used : Make a map : char : 2d index in the matrix.
# Now from current position, see the target character.
# Using coordinate system, find out how much we have to go up, down, left or right
# from current position.
# Logic : class Solution:
# def __init__(self):
# self.charHash = {}
# counter = 0
# for char in "abcdefghijklmnopqrstuvwxyz":
# self.charHash[char] = (counter // 5, counter % 5)
# counter += 1
# def alphabetBoardPath(self, target):
# currPos = (0, 0), output = ''
# for char in target:
# [x, y] = self.charHash[char]
# moveX = x - currPos[0]
# moveY = y - currPos[1]
# if moveY < 0:
# output += 'L' * abs(moveY)
# if moveX > 0:
# output += 'D' * moveX
# if moveX < 0:
# output += "U" * abs(moveX)
# if moveY > 0:
# output += 'R' * moveY
# output += '!'
# currPos = (x, y)
# return output
# Complexity : O(n)
class Solution:
def __init__(self):
self.charHash = {}
counter = 0
for char in "abcdefghijklmnopqrstuvwxyz":
self.charHash[char] = (counter // 5, counter % 5)
counter += 1
def alphabetBoardPath(self, target):
currPos = (0, 0)
output = ''
for char in target:
[x, y] = self.charHash[char]
moveX = x - currPos[0]
moveY = y - currPos[1]
if moveY < 0:
output += 'L' * abs(moveY)
if moveX > 0:
output += 'D' * moveX
if moveX < 0:
output += "U" * abs(moveX)
if moveY > 0:
output += 'R' * moveY
output += '!'
currPos = (x, y)
return output
if __name__ == "__main__":
inpStr = "leet"
solution = Solution()
print(solution.alphabetBoardPath(inpStr))
|
a19249f2838b5e596f7d30bd172c29ebc8fdbaab | Dechuan0629/LeetCodePractice | /validPalindrome-Python/validPalindrome.py | 748 | 3.734375 | 4 | class Solution:
def validPalindrome(self, s: str) -> bool:
if ''.join(reversed(s)) == s:
return True
i , j = 0, len(s)-1
temp = list(s)
while i < j:
if temp[i] == temp[j]: #两个指针从两边开始判别,当找到一个不同时,去掉这个如果是回文就返回True,否则返回False
i+=1
j-=1
continue
if temp[0:i]+temp[i+1:] == list(reversed(temp[0:i]+temp[i+1:])) or temp[0:j]+temp[j+1:] == list(reversed(temp[0:j]+temp[j+1:])):
return True
else:return False
def main():
test = Solution()
s = "abbam"
print(test.validPalindrome(s))
if __name__ == '__main__':
main() |
9f57830a4f2fbd2ffaa8d4c3ebd59b83a22fb64e | KHVIII/CS1114- | /hw1/ytc344_hw1_q5.py | 236 | 3.65625 | 4 | def fibs(n):
n0 = 1
yield n0
n1 = 1
yield n1
for i in range (n-2):
result = n0 +n1
n0 = n1
n1 = result
yield result;
def main():
for curr in fibs(1):
print(curr)
|
a4d9fecb830b99ee8cbd3831a07c41aca6fe4e62 | prathimacode-hub/Python-Tutorial | /Beginner_Level/Set.py | 1,078 | 3.5625 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> basket = {"apple","mango","orange","pear","banana","apple"}
>>> basket
{'apple', 'pear', 'banana', 'orange', 'mango'}
>>> a = set()
>>> a.add(11)
>>> a.add(22)
>>> a.add(33)
>>> a.add(44)
>>> a
{33, 11, 44, 22}
>>> # don't initialize empty set bcoz python consider it set dictionary
>>> b = {}
>>> type(b)
<class 'dict'>
>>> b = {'somrthing'}
>>> b
{'somrthing'}
>>> type(b)
<class 'set'>
>>> # since set is unordered that means you can't access using index
>>> basket[0]
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
basket[0]
TypeError: 'set' object is not subscriptable
>>>
>>>
>>>
>>>
>>> # creating set from list by passing list as argument in constructor of set
>>> numbers = [1,2,3,4,5,2,1,3,5]
>>> set_numbers = set(numbers)
>>> set_numbers
{1, 2, 3, 4, 5}
>>> set_numbers.add(6)
>>> set_numbers
{1, 2, 3, 4, 5, 6}
>>> |
383a2c4433018b29a9106cd1db321fa6bb8dc0fd | Sherlynchance/SherlynChance_ITP2017_Exercises | /4-6. Odd Numbers.py | 89 | 3.78125 | 4 | odd = []
for x in range(0,20):
if x % 2 != 0:
odd.append(x)
print(odd)
|
0b4bdaff589b0fbde5c2fcd093524cb041ea111f | pardeepsingal/python-learning | /expression.py | 320 | 4.03125 | 4 | #!/usr/bin/env python3
x=23
y=74
if(x<y):
print('x < y and the value of x = {}, value of y = {} '.format(x,y))
elif(x>y):
print('x > y and the value of x = {}, value of y = {} '.format(x,y))
elif(x==y):
print('x and y are equal and value of x = {} and value of y = {} '.format(x,y))
else:
print('something else') |
dbc75508320e00241242f137950cdbafb8ad977f | E-Wawrzynek/ECEN-2703_Final-Project | /sudoku_generator.py | 4,048 | 3.640625 | 4 | # Suduko Generator, Final Project ECEN 2703
# Ella Wawrzynek & XuTao Ho
import argparse
from z3 import *
import random as rd
import itertools
def generate_board():
number_list = [Int('n%i'%i) for i in range(0,81)]
s = Solver()
for x in number_list:
s.add(And(x >= 1, x <= 9))
for x in range(0,9):
row_number = [0+9*x for x in range(0,9)]
column_number = range(0,9)
square_number = [0,3,6,27,30,33,54,57,60]
rows = [[] for x in range(0,9)]
columns = [[] for y in range(0,9)]
squares = [[] for z in range(0,9)]
for x in column_number:
for y in range(0,9):
columns[x].append(number_list[x+9*y])
row = 0
for x in row_number:
for y in range(0,9):
rows[row].append(number_list[x+y])
row += 1
square = 0
for x in square_number:
for y in [0,9,18]:
squares[square].append(number_list[x + y])
squares[square].append(number_list[x + 1 + y])
squares[square].append(number_list[x + 2 + y])
square += 1
for x in range(0,9):
for y in range(0,9):
for z in range(0,9):
if z != y:
s.add(columns[x][z] != columns[x][y])
s.add(rows[x][z] != rows[x][y])
s.add(squares[x][z] != squares[x][y])
s.add(rows[0][0] == rd.randint(1,9))
results = s.check()
if results == sat:
print("Full Board")
m = s.model()
for x in range(0,9):
print(', '.join(str(m[rows[x][y]]) for y in range(0,9)))
board = [ [ m.evaluate(rows[i][j]) for j in range(9) ] for i in range(9) ]
elif results == unsat:
print("Constraints are unsatisfiable")
else:
print("Unable to Solve")
return board
def solve_sudoku(grid):
s = Solver()
solve_grid = []
solve_grid = [[Int('v%i%i' % (j, k)) for k in range(1,10)] for j in range(1,10)]
for r in range(9):
for c in range(9):
if type(grid[r][c]) != type(0):
s.add(solve_grid[r][c] == grid[r][c])
for r in range(9):
for c in range(9):
s.add(And(1 <= solve_grid[r][c], solve_grid[r][c] <= 9))
for r in range(9):
s.add(Distinct(solve_grid[r]))
for c in range(9):
s.add(Distinct([solve_grid[r][c] for r in range(9)]))
for x in range(0, 9, 3):
for y in range(0, 9, 3):
s.add(Distinct([solve_grid[j][k] for j, k in itertools.product(range(3), range(3))]))
cntr = 0
while s.check() == sat:
cntr += 1
m = s.model()
for j in range(9):
for k in range(9):
s.add(Not(And(solve_grid[j][k] == m[solve_grid[j][k]])))
return cntr
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Sudoku board generator',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-d', '--difficulty', help='level of board difficulty (0, 1, 2, or 3)',
default=1, type=int)
args = parser.parse_args()
level = args.difficulty
if level == 0:
num_remove = 0
if level == 1:
num_remove = 27
if level == 2:
num_remove = 36
if level == 3:
num_remove = 45
n = [Int('i') for i in range(10)]
rd.seed(None)
grid = generate_board()
grid_copy = []
for r in range(0,9):
grid_copy.append([])
for c in range(0,9):
grid_copy[r].append(grid[r][c])
while num_remove > 0:
num_remove -= 1
r = rd.randint(0,8)
c = rd.randint(0,8)
while grid_copy[r][c] == 0:
r = rd.randint(0,8)
c = rd.randint(0,8)
grid_copy[r][c] = 0
sols = solve_sudoku(grid_copy)
if sols != 1:
grid_copy[r][c] = grid[r][c]
num_remove += 1
for x in range(9):
for y in range(9):
if type(grid_copy[x][y]) == type(0):
grid_copy[x][y] = '_'
print("Player's Board")
for x in range(0,9):
print(', '.join(str(grid_copy[x][y]) for y in range(0,9))) |
acf2ef1a60eec2ba8d1f1cb9828ee07582dbb0d4 | DanielVitas/projektna-naloga-UVP | /physics/vector.py | 1,175 | 4.09375 | 4 | class Vector(object):
def __init__(self, x, y=None):
if y is not None:
self.x = x
self.y = y
else:
self.x = x.x
self.y = x.y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, other):
if type(other) == Vector:
return self.x * other.x + self.y * other.y
if type(other) == int or float:
return Vector(self.x * other, self.y * other)
def __repr__(self):
return 'Vector' + str((self.x, self.y))
def __abs__(self):
return (self * self) ** (1 / 2)
def __pow__(self, power, modulo=None):
return self.x * power.y - self.y * power.x
def right_angled(self):
return Vector(self.y, -self.x)
def normalize(self):
if self.x != 0 or self.y != 0:
return self * (1 / abs(self))
else:
return self
if __name__ == '__main__':
print(Vector(1, 2) * 3)
print(Vector(1, 2) * Vector(2, 2))
|
81c21c61a850c1cff1cc00968b13b50f80eec3ab | dr-aryone/BiblioPixel | /bibliopixel/layout/geometry/segment.py | 1,539 | 3.59375 | 4 | from . import strip
class Segment(strip.Strip):
"""Represents an offset, length segment within a strip."""
def __init__(self, strip, length, offset=0):
if offset < 0 or length < 0:
raise ValueError('Segment indices are non-negative.')
if offset + length > len(strip):
raise ValueError('Segment too long.')
self.strip = strip
self.offset = offset
self.length = length
def __getitem__(self, index):
return self.strip[self._fix_index(index)]
def __setitem__(self, index, value):
self.strip[self._fix_index(index)] = value
def __len__(self):
return self.length
def next(self, length):
"""Return a new segment starting right after self in the same buffer."""
return Segment(self.strip, length, self.offset + self.length)
def _fix_index(self, index):
if isinstance(index, slice):
raise ValueError('Slicing segments not implemented.')
if index < 0:
index += self.length
if index >= 0 and index < self.length:
return self.offset + index
raise IndexError('Index out of range')
def make_segments(strip, length):
"""Return a list of Segments that evenly split the strip."""
if len(strip) % length:
raise ValueError('The length of strip must be a multiple of length')
s = []
try:
while True:
s.append(s[-1].next(length) if s else Segment(strip, length))
except ValueError:
return s
|
f86d5e7eb8ae286ff1b8764cef7c88e9b5a69b54 | JojoPalambas/Klyxt | /src/string_utils.py | 199 | 3.78125 | 4 |
def isNumber(s):
if not s or s == "":
return False
for c in s:
if c not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.']:
return False
return True
|
53d0e6c3cd43c0439567152fadc0392c17bb8668 | cassantiago/520-python | /Aula1/sintaxeBasica.py | 710 | 4.21875 | 4 | #!/usr/bin/python3
#print('hello word')
#nome = str(input('digite seu nome: ')).upper()
# print (nome)
# print('seu nome é', nome)
# print(input('Digite seu nome: '),'Seja bem vindo')
# print(input('Digite sua idade: '),'idade')
#idade = input('digite sua idade: ')
#print(f'deu nome é {nome}, e sua idade é {idade} ')
#print (nome,idade,sep='.',end='\n')
#texto = '4linux' #string
#numero = 3 #int
#Print(texto.upper())
#Print(texto.title())
#Print(texto.strip())
#Print(texto.replace('l','p'))
#email = str(input('Digite o E-mail: ')).lower().strip()
#print(email)
#nome = str(input('digite seu nome: ')).upper()
#print(nome)
verdadeiro = True
Falso = False
print(not(Falso == True))
|
9087c608302cafb48297db5ef02e4203674519af | deepeshchaudhari/learnOOPython | /tut6b[filter].py | 196 | 3.6875 | 4 | '''
filter function
'''
def greater_than_2(n):
if n>2:
return True
else:
return False
l = [1,2,12,1,2,1,2,1,222,1,2,1,2]
gt = list(filter(greater_than_2,l))
print(gt)
|
a972b4781fdd651a1147a68dfaf04aaf50971642 | mercolino/monitoring | /lib/sqlite.py | 6,095 | 3.640625 | 4 | import sqlite3
import re
import datetime
class SQLite():
def __init__(self, db_name):
# Error Checks
if not isinstance(db_name, str):
raise TypeError("The name of the database should be a string")
if len(db_name) == 0:
raise ValueError("The database name should not be empty")
# Create the connection and the cursor
self.conn = sqlite3.connect(db_name)
self.c = self.conn.cursor()
self.tables = {}
def __valid_input(self, string):
'''Private function to validate input'''
for l in string:
if l in [';', '(', ')', ]:
raise ValueError("Forbidden character found on the string '%s'" % string)
return True
def __fields_not_primary_key(self, fields):
''' Private function to determine if the table have a Primary Key'''
new_fields = []
for f in fields:
if not re.match('.*primary key.*', f.lower()):
new_fields.append(f.split(" ")[0])
return new_fields
def __get_primary_key(self, fields):
''' Private function to determine the Primary Key field'''
for f in fields:
if re.match('.*primary key.*', f.lower()):
return f.split(" ")[0]
raise RuntimeError("No primary key on table")
def create_table(self, table_name, fields):
""" Create table"""
# Error Checks
if not isinstance(table_name, str):
raise TypeError("The name of the table on database should be a string")
if type(fields) is not tuple:
raise TypeError("The fields should be a tuple ('field_name data_type OPTION', ...)")
if len(table_name) == 0:
raise ValueError("The table name should not be empty")
if len(fields) == 0:
raise ValueError("You need at least one field to create a table")
for f in fields:
self.__valid_input(f)
try:
self.tables[table_name] = fields
sql = '''CREATE TABLE IF NOT EXISTS {tbl} ({flds})'''.format(tbl=table_name,
flds=",".join(f for f in fields))
self.c.execute(sql)
except Exception as e:
raise e
def insert(self, table_name, values):
""" Insert data into table """
# Error Checks
if not isinstance(table_name, str):
raise TypeError("The name of the table on database should be a string")
if type(values) is not tuple:
raise TypeError("The values should be a tuple containing the values to insert")
if len(table_name) == 0:
raise ValueError("The table name should not be empty")
if len(values) == 0:
raise ValueError("You need at least one value to insert on the table")
for v in values:
if isinstance(v, str):
self.__valid_input(v)
try:
fields = self.__fields_not_primary_key(self.tables[table_name])
sql = '''INSERT INTO {tbl}({flds}) VALUES({vals})'''.format(tbl=table_name,
flds=",".join(f for f in fields),
vals=",".join("?" for i in range(len(values))))
self.c.execute(sql, values)
self.conn.commit()
except Exception as e:
raise e
def get_last_n(self, table_name, n=1):
""" Get the last n values on table """
# Error Checks
if not isinstance(table_name, str):
raise TypeError("The name of the table on database should be a string")
if not isinstance(n, int):
raise TypeError("The number of records (n) asked should be an integer")
if len(table_name) == 0:
raise ValueError("The table name should not be empty")
if n <= 0:
raise ValueError("The number of records should be greater than or equal to 1")
try:
sql = '''SELECT * FROM {tbl} ORDER by {pk} DESC LIMIT {num}'''.format(tbl=table_name,
pk=self.__get_primary_key(
self.tables[table_name]),
num=n)
self.c.execute(sql)
return self.c.fetchall()
except Exception as e:
raise e
def query(self, query, values=None):
""" Query """
# Error Checks
if not isinstance(query, str):
raise TypeError("The query should be a string")
if len(query) == 0:
raise ValueError("The query can't be empty")
if values is not None:
if type(values) is not tuple:
raise ValueError("Values should be a tuple")
try:
if values is None:
self.c.execute(query)
return self.c.fetchall()
else:
self.c.execute(query, values)
return self.c.fetchall()
except Exception as e:
raise e
def get_columns_from_table(self, table_name):
""" Get columns from table """
# Error Checks
if not isinstance(table_name, str):
raise TypeError("The table name should be a string")
if len(table_name) == 0:
raise ValueError("The table name can't be empty")
for v in table_name:
if isinstance(v, str):
self.__valid_input(v)
try:
sql = "SELECT * from {tbl}".format(tbl=table_name)
self.c.execute(sql)
return list(map(lambda x: x[0], self.c.description))
except Exception as e:
raise e
def close(self):
""" Close connection"""
try:
self.conn.close()
except Exception as e:
raise e |
690f57357862c6abee4b98e2fd26961dd275c952 | prativadhikari/Bussi | /countvowelconsonant.py | 453 | 4.09375 | 4 | """
The given program asks a user for a word and
tells how many vowels and consonants the word contains.
"""
def main():
ask = input("Enter a word: ")
vowels = 0
consonants = 0
for i in ask:
if (i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u'):
vowels = vowels + 1
else:
consonants = consonants + 1
print("Word",(ask),"contains",(vowels),"vowels and",(consonants),"Consonants")
|
83725d63e34c648d84a53f6278ddf536d8bab737 | VinhMaiVy/learning-python | /src/Algorithms/00 Implementation/py_kangaroo.py | 498 | 3.734375 | 4 | #!/bin/python3
"""
0 2 5 3
NO
0 3 4 2
YES
43 2 70 2
NO
Modulo
"""
def kangaroo(x1, v1, x2, v2):
result = 'NO'
if (v1 != v2):
jumps = (x2-x1)/(v1-v2)
if jumps > 0 and jumps % 1 == 0:
result = 'YES'
return result
if __name__ == '__main__':
x1V1X2V2 = input().split()
x1 = int(x1V1X2V2[0])
v1 = int(x1V1X2V2[1])
x2 = int(x1V1X2V2[2])
v2 = int(x1V1X2V2[3])
result = kangaroo(x1, v1, x2, v2)
print(result + '\n')
|
9e616d0a72b1a2cca9d766972407e09fa9551076 | zzhyzzh/Leetcode | /leetcode-algorithms/706. Design HashMap/MyHashMap.py | 1,895 | 3.59375 | 4 | class MyHashMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 1000
self.buckets = [[] for _ in range(self.size)]
def put(self, key, value):
"""
value will always be non-negative.
:type key: int
:type value: int
:rtype: void
"""
bucket, index = self._index(key)
array = self.buckets[bucket]
if index < 0:
array.append((key, value))
else:
array[index] = (key, value)
def get(self, key):
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
:type key: int
:rtype: int
"""
bucket, index = self._index(key)
if index < 0:
return -1
array = self.buckets[bucket]
key, value = array[index]
return value
def remove(self, key):
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
:type key: int
:rtype: void
"""
bucket, index = self._index(key)
if index < 0:
return
array = self.buckets[bucket]
del array[index]
def _bucket(self, key):
return key % self.size
def _index(self, key):
bucket = self._bucket(key)
for i, (k, v) in enumerate(self.buckets[bucket]):
if k == key:
return bucket, i
return bucket, -1
hashMap = MyHashMap()
hashMap.put(1, 1)
hashMap.put(2, 2)
hashMap.get(1) # // returns 1
hashMap.get(3) # // returns -1 (not found)
hashMap.put(2, 1) # // update the existing value
hashMap.get(2) # // returns 1
hashMap.remove(2) # // remove the mapping for 2
hashMap.get(2) # |
4b53c836991db73d12be6310eb20bacd7d6aa45f | 11Q/openPY | /大数据开发语言(Python语言程序设计)-课件/Codes/第01章 程序设计基本方法/rose-1c.py | 1,547 | 3.625 | 4 | #turtle绘制玫瑰
from turtle import*
#global pen and speed
pencolor("black")
fillcolor("red")
speed(50)
s=0.15
#init poistion
penup()
goto(0,600*s)
pendown()
begin_fill()
circle(200*s,30)
for i in range(60):
lt(1)
circle(50*s,1)
circle(200*s,30)
for i in range(4):
lt(1)
circle(100*s,1)
circle(200*s,50)
for i in range(50):
lt(1)
circle(50*s,1)
circle(350*s,65)
for i in range(40):
lt(1)
circle(70*s,1)
circle(150*s,50)
for i in range(20):
rt(1)
circle(50*s,1)
circle(400*s,60)
for i in range(18):
lt(1)
circle(50*s,1)
fd(250*s)
rt(150)
circle(-500*s,12)
lt(140)
circle(550*s,110)
lt(27)
circle(650*s,100)
lt(130)
circle(-300*s,20)
rt(123)
circle(220*s,57)
end_fill()
lt(120)
fd(280*s)
lt(115)
circle(300*s,33)
lt(180)
circle(-300*s,33)
for i in range(70):
rt(1)
circle(225*s,1)
circle(350*s,104)
lt(90)
circle(200*s,105)
circle(-500*s,63)
penup()
goto(170*s,-330*s)
pendown()
lt(160)
for i in range(20):
lt(1)
circle(2500*s,1)
for i in range(220):
rt(1)
circle(250*s,1)
fillcolor('green')
penup()
goto(670*s,-480*s)
pendown()
rt(140)
begin_fill()
circle(300*s,120)
lt(60)
circle(300*s,120)
end_fill()
penup()
goto(180*s,-850*s)
pendown()
rt(85)
circle(600*s,40)
penup()
goto(-150*s,-1300*s)
pendown()
begin_fill()
rt(120)
circle(300*s,115)
lt(75)
circle(300*s,100)
end_fill()
penup()
goto(430*s,-1370*s)
pendown()
rt(30)
circle(-600*s,35)
done()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.