blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
b643e9a0d72242ed831b4e20b8edcc08258d50ad | summergirl21/Advent-of-Code-2016 | /Day03/Day3.py | 1,209 | 3.90625 | 4 | def main():
print("Hello")
input = open("Day3_input.txt", "r")
#input = open("Day3_input_test.txt", "r")
newinput = {0:[], 1:[], 2:[]}
for line in input:
line = [int(x) for x in line.split()]
for i in range(0, 3):
newinput[i].append(line[i])
print(newinput[0])
print(newinput[1])
print(newinput[2])
count = 0
for i in range(0, 3):
input = newinput[i]
index = 0
while index < len(input):
sides = [input[index], input[index+1], input[index+2]]
sides.sort()
if sides[0] + sides[1] > sides[2]:
print ("is valid triangle " + str(sides[0]) + " " + str(sides[1]) + " " + str(sides[2]))
count += 1
else:
print("is not valid triangle " + str(sides[0]) + " " + str(sides[1]) + " " + str(sides[2]))
index += 3
print(count)
# count = 0
# for line in input:
# sides = [0, 0, 0]
# #line = [int(x) for x in line.split()]
# line.sort()
# #print(line)
# if line[0] + line[1] > line[2]:
# count += 1
# print(count)
if __name__ == "__main__":
main() |
f85f89d07de9f394d7f95646c0a490232bc3b7bc | whoismaruf/usermanager | /app.py | 2,605 | 4.15625 | 4 | from scripts.user import User
print('\nWelcome to user management CLI application')
user_list = {}
def create_account():
name = input('\nSay your name: ')
while True:
email = input('\nEnter email: ')
if '@' in email:
temp = [i for i in email[email.find('@'):]]
if '.' in temp:
user = User(name, email)
break
else:
print("\nInvalid Email address! Please enter the correct one.")
continue
else:
print("\nInvalid Email address! Please enter the correct one.")
continue
uname = user.set_username()
current_user = {
'name': name,
'email': email
}
while True:
if uname in user_list:
new_uname = input(f'\nSorry your username "{uname}" has been taken, choose another one: ')
uname = new_uname.replace(" ", '')
else:
break
user_list[f'{uname}'] = current_user
print(f"\nHello, {name}! Your account has been created as {uname}.\n\nChoose what to do next - ")
while True:
user_input = input('''
A --> Create account
S --> Show account info
Q --> Quit
''')
if user_input == 'A' or user_input == 'a':
create_account()
elif user_input == 'S' or user_input == 's':
if len(user_list) == 0:
print("\nThere is no account, please create one")
continue
else:
while True:
search = input('\nEnter username: ')
if search not in user_list:
print(f"\nYour searched '{search}' user not found.")
pop = input('''
S --> Search again
M --> Back to main menu
''')
if pop == 'S' or pop == 's':
continue
elif pop == 'M' or pop == 'm':
break
else:
print('Bad input')
break
else:
res = user_list[search]
print(f'''
Account information for {search}
Name: {res['name']}
Email: {res['email']}
''')
break
elif user_input == 'Q' or user_input == 'q':
break
elif user_input == '':
print('Please input something')
continue
else:
print('\nBad input, try again\n') |
59406c79354db2ff825e18a503fa35a4883ca51d | avadesh02/fml-project | /srcpy/robot_env/two_dof_manipulator.py | 10,894 | 3.96875 | 4 | ## This is the implementation of a 2 degree of manipulator
## Author: Avadesh Meduri
## Date : 9/11/2020
import numpy as np
from matplotlib import pyplot as plt
# these packages for animating the robot env
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation
class TwoDOFManipulator:
def __init__(self, l1, l2, m1, m2):
self.dt = 0.001 # discretization step in seconds
self.g = 9.81 # gravity vector
self.l1 = l1
self.l2 = l2
self.m1 = m1
self.m2 = m2
self.Il1 = self.m1*(self.l1**2)/12.0 #inertia of link 1 around the center of mass axis
self.Il2 = self.m2*(self.l2**2)/12.0 #inertia of link 2 around the center of mass axis
self.Im1 = 4*self.Il1 #inertia of link 1 around the rotor axis
self.Im2 = 4*self.Il2 #inertia of link 2 around the rotor axis
def dynamics(self, th1, th2, thd1, thd2, tau1, tau2):
'''
This function computes the dynamics (dy/dt = f(y,t)) given the current state of the robot
(Joint Position, Joint velocities, tau).
Input:
th1 : joint position of first link (closest to the base)
th2 : joint position of second link
thd1 : joint velocity of the first link
thd2 : joint velocity of the second link
tau1 : torque input to the first link
tau2 : torque input to the second link
'''
xd = np.zeros(4)
xd[0] = thd1
xd[1] = thd2
# defining the matrix A, b such that A * [thdd1, thdd2] = b. b is function of
# tau and th1, th2, thd1, thd2
A = np.zeros((2, 2))
A[0,0] = self.Im1 + self.m2*self.l1**2 + self.Im2 + self.m2*self.l1*self.l2*np.cos(th2)
A[0,1] = self.Im2 + self.m2*self.l1*self.l2*np.cos(th2)/2.0
A[1,0] = self.Im2 + self.m2*self.l1*self.l2*np.cos(th2)/2.0
A[1,1] = self.Im2
b = np.zeros(2)
b[0] = tau1 + self.m2*self.l1*self.l2*thd1*thd2*np.sin(th2) + \
self.m2*self.l1*self.l2*(thd2**2)*np.sin(th2)/2.0 - self.m2*self.l2*self.g*np.cos(th1+th2)/2.0 \
- (self.m1*self.l1/2.0 + self.m2*self.l1)*self.g*np.cos(th1)
b[1] = tau2 - self.m2*self.l1*self.l2*(thd1**2)*np.sin(th2)/2.0 - self.m2*self.l2*self.g*np.cos(th1+th2)/2.0
#computing inv
A_inv = np.zeros((2,2))
A_inv[0,0] = A[1, 1]
A_inv[1,1] = A[0, 0]
A_inv[0,1] = -A[0,1]
A_inv[1,0] = -A[1,0]
A_inv = (1/np.linalg.det(A))*A_inv
xd[2:] = np.matmul(A_inv, b.T)
return xd[0], xd[1], xd[2], xd[3]
def integrate_dynamics_euler(self, th1_t, th2_t, thd1_t, thd2_t, tau1_t, tau2_t):
'''
This funciton integrates the dynamics for one time step using euler integration
Input:
th1_t : joint position of first link (closest to the base)
th2_t : joint position of second link
thd1_t : joint velocity of the first link
thd2_t : joint velocity of the second link
tau1_t : torque input to the first link
tau2_t : torque input to the second link
'''
# computing joint velocities, joint acceleration
jt_vel1, jt_vel2, jt_acc1, jt_acc2 = self.dynamics(th1_t, th2_t, thd1_t, thd2_t, tau1_t, tau2_t)
# integrating using euler scheme
th1_t_1 = th1_t + jt_vel1*self.dt
th2_t_1 = th2_t + jt_vel2*self.dt
thd1_t_1 = thd1_t + jt_acc1*self.dt
thd2_t_1 = thd2_t + jt_acc2*self.dt
return th1_t_1, th2_t_1, thd1_t_1, thd2_t_1
def integrate_dynamics_runga_kutta(self, th1_t, th2_t, thd1_t, thd2_t, tau1_t, tau2_t):
'''
This funciton integrates the dynamics for one time step using runga kutta integration
Input:
th1_t : joint position of first link (closest to the base)
th2_t : joint position of second link
thd1_t : joint velocity of the first link
thd2_t : joint velocity of the second link
tau1_t : torque input to the first link
tau2_t : torque input to the second link
'''
k1_jt_vel1, k1_jt_vel2, k1_jt_acc1, k1_jt_acc2 = self.dynamics(th1_t, th2_t, thd1_t, thd2_t, tau1_t, tau2_t)
k2_jt_vel1, k2_jt_vel2, k2_jt_acc1, k2_jt_acc2 = \
self.dynamics(th1_t + 0.5*self.dt*k1_jt_vel1, th2_t + 0.5*self.dt*k1_jt_vel2, thd1_t + 0.5*self.dt*k1_jt_acc1, thd2_t + 0.5*self.dt*k1_jt_acc2, tau1_t, tau2_t)
k3_jt_vel1, k3_jt_vel2, k3_jt_acc1, k3_jt_acc2 = \
self.dynamics(th1_t + 0.5*self.dt*k2_jt_vel1, th2_t + 0.5*self.dt*k2_jt_vel2, thd1_t + 0.5*self.dt*k2_jt_acc1, thd2_t + 0.5*self.dt*k2_jt_acc2, tau1_t, tau2_t)
k4_jt_vel1, k4_jt_vel2, k4_jt_acc1, k4_jt_acc2 = \
self.dynamics(th1_t + self.dt*k3_jt_vel1, th2_t + self.dt*k3_jt_vel2, thd1_t + self.dt*k3_jt_acc1, thd2_t + self.dt*k3_jt_acc2, tau1_t, tau2_t)
th1_t_1 = th1_t + (1/6)*self.dt*(k1_jt_vel1 + 2*k2_jt_vel1 + 2*k3_jt_vel1 + k4_jt_vel1)
th2_t_1 = th2_t + (1/6)*self.dt*(k1_jt_vel2 + 2*k2_jt_vel2 + 2*k3_jt_vel2 + k4_jt_vel2)
thd1_t_1 = thd1_t + (1/6)*self.dt*(k1_jt_acc1 + 2*k2_jt_acc1 + 2*k3_jt_acc1 + k4_jt_acc1)
thd2_t_1 = thd2_t + (1/6)*self.dt*(k1_jt_acc2 + 2*k2_jt_acc2 + 2*k3_jt_acc2 + k4_jt_acc2)
return th1_t_1, th2_t_1, thd1_t_1, thd2_t_1
def reset_manipulator(self, init_th1, init_th2, init_thd1, init_thd2):
'''
This function resets the manipulator to the initial position
Input:
init_th1 : initial joint position 1 (in degrees)
init_th2 : initial joint position 2 (in degrees)
init_thd1 : initial joint velocity 1
init_thd2 : initial joint velocity 2
'''
# converting to radians
init_th1 = init_th1
init_th2 = init_th2
# Creating an array to store the history of robot states as the dynamics are integrated
# each row corresponds to one state just as in the case of the 1DOF env
self.sim_data = np.array([[init_th1], [init_th2], [init_thd1], [init_thd2], [0.0], [0.0]])
self.t = 0 # time counter in milli seconds
def step_manipulator(self, tau1, tau2, use_euler = False):
'''
This function integrated dynamics using the input torques
Input:
tau1 : joint 1 torque
tau2 : joint 2 torque
'''
self.sim_data[:,self.t][4:6] = [tau1, tau2]
th1_t = self.sim_data[:,self.t][0]
th2_t = self.sim_data[:,self.t][1]
thd1_t = self.sim_data[:,self.t][2]
thd2_t = self.sim_data[:,self.t][3]
if use_euler:
th1_t_1, th2_t_1, thd1_t_1, thd2_t_1 = \
self.integrate_dynamics_euler(th1_t, th2_t, thd1_t, thd2_t, tau1, tau2)
else:
th1_t_1, th2_t_1, thd1_t_1, thd2_t_1 = \
self.integrate_dynamics_runga_kutta(th1_t, th2_t, thd1_t, thd2_t, tau1, tau2)
# making sure that joint positions lie within 0, 360
th1_t_1 = np.sign(th1_t_1)*(np.abs(th1_t_1)%(2*np.pi))
th2_t_1 = np.sign(th2_t_1)*(np.abs(th2_t_1)%(2*np.pi))
sim_data_t_1 = np.array([[th1_t_1], [th2_t_1], [thd1_t_1], [thd2_t_1], [0.0], [0.0]])
# adding the data to sim_data
self.sim_data = np.concatenate((self.sim_data, sim_data_t_1), axis = 1)
# incrementing time
self.t += 1
def get_joint_position(self):
'''
This function returns the current joint position (degrees) of the mainpulator
'''
return self.sim_data[:,self.t][0], self.sim_data[:,self.t][1]
def get_joint_velocity(self):
'''
This function returns the current joint velocity (degrees/sec) of the mainpulator
'''
return self.sim_data[:,self.t][2], self.sim_data[:,self.t][3]
def animate(self, freq = 25):
sim_data = self.sim_data[:,::freq]
fig = plt.figure()
ax = plt.axes(xlim=(-self.l1 - self.l2 -1, self.l1 + self.l2 + 1), ylim=(-self.l1 - self.l2 -1, self.l1 + self.l2 + 1))
text_str = "Two Dof Manipulator Animation"
arm1, = ax.plot([], [], lw=4)
arm2, = ax.plot([], [], lw=4)
base, = ax.plot([], [], 'o', color='black')
joint, = ax.plot([], [], 'o', color='green')
hand, = ax.plot([], [], 'o', color='pink')
def init():
arm1.set_data([], [])
arm2.set_data([], [])
base.set_data([], [])
joint.set_data([], [])
hand.set_data([], [])
return arm1, arm2, base, joint, hand
def animate(i):
theta1_t = sim_data[:,i][0]
theta2_t = sim_data[:,i][1]
joint_x = self.l1*np.cos(theta1_t)
joint_y = self.l1*np.sin(theta1_t)
hand_x = joint_x + self.l2*np.cos(theta1_t + theta2_t)
hand_y = joint_y + self.l2*np.sin(theta1_t + theta2_t)
base.set_data([0, 0])
arm1.set_data([0,joint_x], [0,joint_y])
joint.set_data([joint_x, joint_y])
arm2.set_data([joint_x, hand_x], [joint_y, hand_y])
hand.set_data([hand_x, hand_y])
return base, arm1, joint, arm2, hand
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
ax.text(0.05, 0.95, text_str, transform=ax.transAxes, fontsize=15,
verticalalignment='top', bbox=props)
ax.grid()
anim = FuncAnimation(fig, animate, init_func=init,
frames=np.shape(sim_data)[1], interval=25, blit=True)
plt.show()
def plot(self):
'''
This function plots the joint positions, velocities and torques
'''
fig, axs = plt.subplots(3,1, figsize = (10, 10))
axs[0].plot((180/np.pi)*self.sim_data[0], label = 'joint position_1')
axs[0].plot((180/np.pi)*self.sim_data[1], label = 'joint position_2')
axs[0].grid()
axs[0].legend()
axs[0].set_ylabel("degrees")
axs[1].plot(self.sim_data[2], label = 'joint velocity_1')
axs[1].plot(self.sim_data[3], label = 'joint velocity_2')
axs[1].grid()
axs[1].legend()
axs[1].set_ylabel("rad/sec")
axs[2].plot(self.sim_data[4,:-1], label = 'torque_1')
axs[2].plot(self.sim_data[5,:-1], label = 'torque_2')
axs[2].grid()
axs[2].legend()
axs[2].set_ylabel("Newton/(Meter Second)")
plt.show()
|
f7691a737227df28f71e8c9d647858bf020523e7 | sidduGIT/Files_examples | /count_capitals.py | 163 | 3.671875 | 4 | with open('content.txt','r') as fh:
count=0
for line in fh:
for char in line:
if char.isupper():
count+=1
print(count)
|
ec458e18c02717868cd756367b3c7c1f7eb8b241 | pavdemesh/stepik_67 | /stepik_67_ex_2_6_spiral_v1.py | 512 | 3.703125 | 4 | number = int(input())
matrix = [[0] * number for h in range(number)]
row, col = 0, 0
for num in range(1, number * number + 1):
matrix[row][col] = num
if num == number * number:
break
if row <= col + 1 and row + col < number - 1:
col += 1
elif row < col and row+col >= number-1:
row += 1
elif row >= col and row+col > number-1:
col -= 1
elif row > col + 1 and row + col <= number - 1:
row -= 1
for row in range(number):
print(*matrix[row])
|
d9247e91833eb5a66e7388dc3f8e4e1ea99de9d3 | pavdemesh/stepik_67 | /stepik_67_ex_2_6_4.py | 827 | 3.8125 | 4 | # Create empty list
matrix = list()
# Get input from user
while True:
line = input()
# Check if input == "end", break
if line == "end":
break
# Else convert input to a list of ints and append to the matrix list
else:
matrix.append([int(i) for i in line.split()])
# Create variables to store the count of row and cols in the matrix
row_count = len(matrix)
col_count = len(matrix[0])
# Generate matrix of same size populated with 0
res = [[0] * col_count for i in range(row_count)]
for row in range(row_count):
for col in range(col_count):
n_1 = matrix[row - 1][col]
n_2 = matrix[row - row_count + 1][col]
n_3 = matrix[row][col - 1]
n_4 = matrix[row][col - col_count + 1]
res[row][col] = n_1 + n_2 + n_3 + n_4
for item in res:
print(*item)
|
23051e5670e7af0274ea6226d679cf8bed225244 | cnguyen-uk/Blockchain | /block.py | 1,420 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
This is our Block class for transaction storage.
Note that although every block has a timestamp, a proper
implementation should have a timestamp which is static from when a
block is finally placed into the blockchain. In our implementation
this timestamp changes every time the code is run.
Our hashing function is SHA-256 as it is used in most cryptocurrencies.
Information about SHA-256 can be found here:
https://en.wikipedia.org/wiki/SHA-2
"""
from datetime import datetime
from hashlib import sha256
class Block:
def __init__(self, transactions, previous_hash):
self.timestamp = datetime.now()
self.transactions = transactions
self.previous_hash = previous_hash
self.nonce = 0 # Initial guess for future Proof-of-Work
self.hash = self.generate_hash()
def __repr__(self):
return ("Timestamp: " + str(self.timestamp) + "\n"
+ "Transactions: " + str(self.transactions) + "\n"
+ "Current hash: " + str(self.generate_hash()))
def generate_hash(self):
"""Return a hash based on key block information."""
block_contents = (str(self.timestamp) + str(self.transactions)
+ str(self.previous_hash) + str(self.nonce))
block_hash = sha256(block_contents.encode())
return block_hash.hexdigest()
|
aab62b602367c12b4ebbf827a5b79ff4f1de84b9 | 18lkent/AFPwork | /GC-content.py | 682 | 3.53125 | 4 | dnaSequence = "ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT" #The sequence being counted from
print("This program will display the gc content of a DNA sequence")
seqLen = len(dnaSequence) #Length of the sequence
gAmount = dnaSequence.count('G') #Amount of G's in the sequence
cAmount = dnaSequence.count('C') #Amount of C's in the sequence
seqPer1 = gAmount + cAmount #Adds number of C's and number of G's
seqPer2 = seqPer1/seqLen*100 #Calculates percentage of G's and C's of sequence
print("The GC content of the sequence is {0:.2f}".format(seqPer2)) #The format method allows me to change the amount of decimal places
print(str(round(seqPer2, 2))+"%") #Prints Percentage |
0ea8e85c1cc8eee1846c38d7adf6dcbb8de16aa5 | cmniccum/Exploring-BikeShare-Data | /bikeshare.py | 10,201 | 3.78125 | 4 | import time
import pandas as pd
import sys
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
fname = ""
separate = False
def log():
"""
This is a logging function which will determine whether to log the information
to a given file or output it to the console based on the arugments given
when executing this file.
"""
def log_func(func):
def func_wrapper(*var):
try:
global fname
if separate:
fname = func.__name__ + ".txt"
#Will log to a file if the fname is not blank otherwise will
#go to the except block.
with open(fname,"a") as f:
holder = sys.stdout
sys.stdout = f
if func.__name__ == "time_stats":
sys.stdout.write('\nCalculating The Most Frequent Times of Travel...\n')
elif func.__name__ == "station_stats":
sys.stdout.write('\nCalculating The Most Popular Stations and Trip...\n')
elif func.__name__ == "trip_duration_stats":
sys.stdout.write('\nCalculating Trip Duration...\n')
elif func.__name__ == "user_stats":
sys.stdout.write('\nCalculating User Stats...\n')
start_time = time.time()
func(*var)
sys.stdout.write("\nThis took {0:.5f} seconds. \n".format(time.time() - start_time))
sys.stdout.write("-"*40 + "\n")
sys.stdout = holder
f.close()
except Exception:
#If no file is available to write to it will execute this code
#and output the information to the console.
if func.__name__ == "time_stats":
print('\nCalculating The Most Frequent Times of Travel...\n')
elif func.__name__ == "station_stats":
print('\nCalculating The Most Popular Stations and Trip...\n')
elif func.__name__ == "trip_duration_stats":
print('\nCalculating Trip Duration...\n')
elif func.__name__ == "user_stats":
print('\nCalculating User Stats...\n')
start_time = time.time()
func(*var)
print("\nThis took {0:.5f} seconds. \n".format(time.time() - start_time))
print("-"*40 + "\n")
return func_wrapper
return log_func
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('\nHello! Let\'s explore some US bikeshare data!\n')
# get user input for city (chicago, new york city, washington).
while True:
city = input("What city would you like to explore: Chicago, New York,"+
"or Washington?\n").lower()
if city in ('chicago', 'new york', 'washington'):
break
print("Sorry you chose a city with no data. Please try again.")
# get user input for month (all, january, february, ... , june)
while True:
choice = input("\nWould you like data for a month, day, or both?\n").lower()
if choice in ("month", "both"):
while True:
month = input("\nWhat month would you like data for: January, February,"+
"March, April, May, June, or all.\n").lower()
if (month in ("january", "february", "march", "april",
"may", "june", "all")):
if choice == "month":
day = "all"
break
print("Sorry you chose a month with no data. Please try again.")
# get user input for day of week (all, monday, tuesday, ... sunday)
if choice in ("day", "both"):
while True:
day = input("\nWhat day would you like data for: Monday, Tuesday, "+
"Wednesday, Thursday, Friday, Saturday, Sunday, or all \n").lower()
if (day in ("monday", "tuesday", "wednesday", "thursday",
"friday", "saturday", "sunday", "all")):
if choice == "day":
month == "all"
break
print("\nSorry you chose an invalid day. Please try again.\n")
if choice in ("day", "month", "both"):
break
print("\nInvalid choice Please try again.\n")
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# load data file into a dataframe
df = pd.read_csv(CITY_DATA[city])
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# extract month, day of week, and hours from Start Time to create new columns
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
df['hour'] = df['Start Time'].dt.hour
# filter by month if applicable
if month != 'all':
# use the index of the months list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week'] == day.title()]
return df
@log()
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
months = ['January', 'February', 'March', 'April', 'May', 'June']
# Most common month
print("\nMost common month:")
print(months[df['month'].mode()[0] - 1])
# Most common day of week
print("\nMost common day of week:")
print(df['day_of_week'].mode()[0])
# Most common start hour
print("\nMost common start hour:")
print(df['hour'].mode()[0])
@log()
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
# Most commonly used start station
print("\nMost commonly used start station:")
print(df['Start Station'].value_counts().index[0])
# Most commonly used end station
print("\nMost commonly used end station:")
print(df['End Station'].value_counts().index[0])
# Most frequent combination of start station and end station trip
df['Station Combo'] = df['Start Station'] +", "+ df['End Station']
print("\nMost frequent combination of start station and end station trip:")
print(str(df['Station Combo'].value_counts().index[0]) + "\t" +str(df['Station Combo'].value_counts().max()))
@log()
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
# Total Travel Time
print("\nTotal Travel Time:")
print(str(df['Trip Duration'].sum()) + " seconds")
# Mean Travel Time
print("\nMean Travel Time:")
print(str(df['Trip Duration'].mean()) + " seconds")
@log()
def user_stats(df):
"""Displays statistics on bikeshare users."""
# Diplays the counts of each user type
print("\nTypes of Users:")
print(df['User Type'].value_counts())
# Displays the number of each gender
print("\nMakeup of individuals by Gender:")
print(df['Gender'].value_counts())
# Oldest Individuals
print("\nOldest year of birth:")
print(int(df['Birth Year'].min()))
# Youngest individuals
print("\nMost recent year of birth:")
print(int(df['Birth Year'].max()))
# Most common year of birth of individuals
print("\nMost common year of birth:")
print(int(df['Birth Year'].mode()[0]))
def get_args(arguments):
"""
This function handles all arguments given when the file has been executed.
additional options:
-on
-on 'filename'
-on -s
If there are no additional options given it will print everything to console.
"""
global fname
global separate
if len(arguments) == 2:
if arguments[1] == '-on':
fname = "log.txt"
print("\n\nPlease note that your output will be logged in file '{}'.\n".format(fname))
elif len(arguments) == 3:
if arguments[1] == '-on':
if arguments[2] == '-s':
separate = True
print("\n\nPlease note that each function output will be logged separately.\n")
else:
fname = arguments[2]
print("\n\nPlease note that your output will be logged in file '{}'.\n".format(fname))
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
get_args(sys.argv)
main()
|
7e43010151fd990c1962e1c5847230315ff80d5c | kaka0525/data-strutctures-partII | /merge_sort.py | 1,792 | 3.703125 | 4 | from __future__ import unicode_literals
from time import time
from random import shuffle
def merge_sort(init_list):
if len(init_list) <= 1:
return init_list
list_left = init_list[:len(init_list) // 2]
list_right = init_list[len(init_list) // 2:]
left = merge_sort(list_left)
right = merge_sort(list_right)
return merge(left, right)
def merge(left, right):
return_list = []
while left and right:
if left[0] <= right[0]:
return_list.append(left[0])
left = left[1:]
else:
return_list.append(right[0])
right = right[1:]
while left:
return_list.append(left[0])
left = left[1:]
while right:
return_list.append(right[0])
right = right[1:]
return return_list
if __name__ == '__main__':
def build_list(iterations):
return_list = range(iterations)
return return_list
iteration_list = [10, 100, 1000, 10000]
random_list = [[] for x in range(4)]
sorted_list = [[] for x in range(4)]
for i in range(len(iteration_list)):
random_list[i].extend(build_list(iteration_list[i]))
shuffle(random_list[i])
sorted_list[i].extend(build_list(iteration_list[i]))
count = 0
for test in random_list:
t0 = time()
merge_sort(test)
worst_time = time() - t0
print "A random list with {} entries, takes {} seconds with mergesort"\
.format(len(test), worst_time)
count += 1
count = 0
for test in sorted_list:
t0 = time()
merge_sort(test)
worst_time = time() - t0
print "An already sorted list with {} entries, takes {} seconds with merge sort"\
.format(len(test), worst_time)
count += 1
|
d827875540a6004a7680a82649bdb58dc6f3431a | Aaron-Ramos/parcial-python | /py-parcial-q3-2020/clave_B/clave_b.py | 2,257 | 4.0625 | 4 | from math import pi
"""
***************************************************************
@@ ejercicio 1 @@
un metodo python que haga la suma de 3 numeros
2+4+6 = 12
"""
# start-->
def suma(numero1,numero2,numero3):
result = numero1 + numero2 + numero3
return result
"""
***************************************************************
@@ ejercicio 2 @@
la suma de los numeros impares del 1 al 1000
"""
# start-->
def sumaImpares(contador, result)
contador = 1
result= 0
while contador <=1000
if contador % 2 != 0
result += contador
contador+=1
return result
"""
***************************************************************
@@ ejercicio 3 @@
encontrar el perimetro, area y el volumen de un esfera
radio = 12 m
perimetro: 2*pi*r
area: 4*pi*r^2
volumen: (4/3)*pi*r^3
"""
# start-->
def definicionEsfera(radio):
result = print(obtenerPerimetro(result))
print (obtenerArea(result))
print (obtenerVolumen(result))
return result
def obtenerPerimetro(radio):
result = 2 * pi * radio
return result
def obtenerArea(radio):
result = 4 * pi * radio^2
return result
def obtenerVolumen(radio):
result = 4/3 * pi * radio^3
return result
"""
***************************************************************
@@ ejercicio 4 @@
el ejercicio numero 3 convertirlo en una clase
"""
# start-->
class Esfera:
def definicionEsfera(self):
return 0
"""
***************************************************************
@@ ejercicio 5 @@
Banco
Cliente
nombre
lugar
numero de cuenta
transaccion - retiro o abono
monto
"""
class Banco:
def procesar(self):
return 0
def abonosSanSalvador(self):
return 0
def abonosBalYRod(self):
return 0
class Cliente:
pass
"""
***************************************************************
@@ ejercicio 6 @@
colocar este proyecto en github
colocar aca debajo la url
ademas colocar la url en un archivo
github_<nombre>_<codigo>.txt y subirlo a moodle
"""
# github url-->
def getGithubUrl(numeroCarnet):
if numeroCarnet == "20195452"
return ""
|
590e8b488d96bf5961cd747a44386b563a34b76f | richnamk/python_nov_2017 | /richardN/pythFundamentals/multSumAve/multSumAve.py | 248 | 3.5 | 4 | #Mult
#part 1
for x in range (0,1000):
if (x % 2 == 1):
print x
#part 2
for x in range (5,1000000):
if (x % 5 == 0):
print x
#Sum
a = [1, 2, 5, 10, 255, 3]
print sum (a)
#Ave
a = [1, 2, 5, 10, 255, 3]
print sum (a) / (len(a))
|
a5bb79e5269dfb2ac5076f11585d078e404202f5 | zazaho/SimImg | /simimg/dialogs/infowindow.py | 994 | 3.765625 | 4 | from tkinter import messagebox as tkmessagebox
def showInfoDialog():
""" show basic info about this program """
msg = """
SiMilar ImaGe finder:
This program is designed to display groups of pictures that are similar.
In particular, it aims to group together pictures that show the same scene.
The use case is to be able to quickly inspect these pictures and keep only the best ones.
The program in not designed to find copies of the same image that have been slightly altered or identical copies, although it can be use for this.
There are already many good (better) solutions available to do this.
The workflow is as follows:
* Activate some selection criterion of the left by clicking on its label
* Adapt the parameters
* The matching groups are updated
* Select images by clicking on the thumbnail (background turns blue)
* Click the play button to inspect the selected images
* Click the delete button to delete selected images
"""
tkmessagebox.showinfo("Information", msg)
|
b9f24efdbaffa1d8c8968c95cafe3025fc01d7e7 | nithinp300/texteditor | /texteditor.py | 1,377 | 3.578125 | 4 | from Tkinter import *
import tkFileDialog
root = Tk("Text Editor")
text = Text(root)
text.grid()
savelocation = "none"
# creates a new file and writes to it
def saveas():
global text
global savelocation
t = text.get("1.0", "end-1c")
savelocation = tkFileDialog.asksaveasfilename()
file1 = open(savelocation, "w")
file1.write(t)
file1.close()
button = Button(root, text="Save As", command=saveas)
button.grid()
# opens a textedit file
def openfile():
global text
global savelocation
savelocation = tkFileDialog.askopenfilename()
file1 = open(savelocation, "r")
text.insert("1.0", file1.read())
file1.close()
button = Button(root, text="Open", command=openfile)
button.grid()
# overwrites the file that is currenly opened
def save():
global text
t = text.get("1.0", "end-1c")
file1 = open(savelocation, "w")
file1.write(t)
file1.close()
button = Button(root, text="Save", command=save)
button.grid()
# changes font style
def fontArial():
global text
text.config(font="Arial")
def fontCourier():
global text
text.config(font="Courier")
font = Menubutton(root, text="Font")
font.grid()
font.menu = Menu(font, tearoff=0)
font["menu"] = font.menu
arial = IntVar()
courier = IntVar()
font.menu.add_checkbutton(label="Arial", variable=arial,
command=fontArial)
font.menu.add_checkbutton(label="Courier", variable=courier,
command=fontCourier)
root.mainloop() |
d76be366cdc01b27a2071c7e88a63fa5b8cbb1e5 | attainu/python-project-Shiva-dwivedi-au9 | /Saanp_Seedhi/Saanp_Seedhi.py | 11,487 | 3.671875 | 4 | import random
import time
import sys
class Saanp_Seedhi:
def __init__(self):
self.DELAY_IN_ACTIONS = 1
self.DESTINATION = 100
self.DICE_FACE = 6
self.text = [
"Your move.",
"Go on.",
"Let's GO .",
"You can win this."
]
self.bitten_by_snake = [
"Aeeee kataaaaaaaaaaa",
"gaya gaya gaya gaya",
"bitten :P",
"oh damn",
"damn"
]
self.ladder_climb = [
"NOICEEE",
"GREATTTT",
"AWESOME",
"HURRAH...",
"WOWWWW"
]
self.snakes = {}
self.ladders = {}
self.players = []
self.num_of_players = int(input("Enter the num of players(2 or 4):"))
if self.num_of_players == 2 or self.num_of_players == 4:
for _ in range(self.num_of_players):
self.pl_name = input("Name of player " + str(_ + 1) + " : ")
self.players.append(self.pl_name)
print("\nMatch will be played between: ", end=" ")
print(",".join(self.players[:len(self.players)-1]), end=" ")
print("and", self.players[-1])
else:
print("Enter either 2 or 4")
self.num_of_players = int(input("Enter no. of players(2 or 4):"))
for _ in range(self.num_of_players):
self.pl_name = input("Name of player " + str(_ + 1) + " : ")
self.players.append(self.pl_name)
print("\nMatch will be played between: ", end=" ")
print(",".join(self.players[:len(self.players)-1]), end=" ")
print("and", self.players[-1])
def Snakes(self):
num_of_snakes = int(input("No. of snakes on your board :"))
if num_of_snakes > 0:
print("\n Enter Head and Tail separated by a space")
i = 0
while i < (num_of_snakes):
head, tail = map(int, input("\n Head and Tail: ").split())
if head <= 100 and tail > 0:
if tail >= head:
print("\n The tail of snake should be less than head")
i = i-1
elif head == 100:
print("\n Snake not possible at position 100.")
i = i-1
elif head in self.snakes.keys():
print("\n Snake already present")
i = i-1
else:
self.snakes[head] = tail
i += 1
else:
print("Invalid! kindly choose b/w 0 to 100")
print("\n Your Snakes are at : ", self.snakes, "\n")
else:
print("Please enter valid number of snakes")
self.Snakes()
return self.snakes
def Ladders(self):
num_of_ladders = int(input("No. of ladders on your board :"))
if num_of_ladders > 0:
print("\n Enter Start and End separated by a space")
i = 0
while i < (num_of_ladders):
flag = 0
start, end = map(int, input("\n Start and End: ").split())
if start > 0 and end < 100:
if end <= start:
print("\n The end should be greater than Start")
flag = 1
i -= 1
elif start in self.ladders.keys():
print("\n Ladder already present")
flag = 1
i -= 1
for k, v in self.snakes.items():
if k == end and v == start:
print("\nSnake present(will create infinite loop)")
print("\nPlease Enter valid Ladder")
flag = 1
i -= 1
else:
if flag == 0:
self.ladders[start] = end
else:
pass
i += 1
else:
print("Invalid! kindly choose b/w 0 to 100")
print("\n Your Ladders are at: ", self.ladders, "\n")
else:
print("Please select valid number of ladders")
self.Ladders()
return self.ladders
def get_player_names(self):
if self.num_of_players == 2:
pl_1 = self.players[0]
pl_2 = self.players[1]
return pl_1, pl_2
elif(self.num_of_players == 4):
pl_1 = self.players[0]
pl_2 = self.players[1]
pl_3 = self.players[2]
pl_4 = self.players[3]
return pl_1, pl_2, pl_3, pl_4
else:
return("Invalid choice")
def welcome_to_the_game(self):
message = """
Welcome to Saanp Seedhi.
GAME RULES
1. When a piece comes on a number which lies on the head of a snake,
then the piece will land below to the tail of the snake that can
also be said as an unlucky move.
2. If somehow the piece falls on the ladder base, it will climb to
the top of the ladder (which is considered to be a lucky move).
3. Whereas if a player lands on the tail of the snake or top of a
ladder, the player will remain in the same spot (same number)
and will not get affected by any particular rule.
The players can never move down ladders.
4. The pieces of different players can overlap each other without
knocking out anyone.There is no concept of knocking out by
opponent players in Snakes and Ladders.
5. To win, the player needs to roll the exact number of die to land
on the number 100. If they fails to do so, then the player needs
to roll the die again in the next turn. For eg, if a player is
on the number 98 and the die roll shows the number 4, then they
cannot move its piece until they gets a 2 to win or 1 to be on
99th number.
"""
print(message)
def roll_the_dice(self):
time.sleep(self.DELAY_IN_ACTIONS)
dice_val = random.randint(1, self.DICE_FACE)
print("Great.You got a " + str(dice_val))
return dice_val
def you_got_bitten(self, old_val, curr_val, pl_name):
print("\n" + random.choice(self.bitten_by_snake).upper() + " :(:(:(:(")
print("\n" + pl_name + " bitten. Dropped from ", end=" ")
print(str(old_val) + " to " + str(curr_val))
def climbing_ladder(self, old_val, curr_val, pl_name):
print("\n" + random.choice(self.ladder_climb).upper() + " :):):):)")
print("\n" + pl_name + " climbed from ", end=" ")
print(str(old_val) + " to " + str(curr_val))
def saanp_seedhi(self, pl_name, curr_val, dice_val):
time.sleep(self.DELAY_IN_ACTIONS)
old_val = curr_val
curr_val = curr_val + dice_val
if curr_val > self.DESTINATION:
print("You now need " + str(self.DESTINATION - old_val), end=" ")
print(" more to win this game.", end=" ")
print("Keep trying.You'll win")
return old_val
print("\n" + pl_name + " moved from " + str(old_val), end=" ")
print(" to " + str(curr_val))
if curr_val in self.snakes:
final_value = self.snakes.get(curr_val)
self.you_got_bitten(curr_val, final_value, pl_name)
elif curr_val in self.ladders:
final_value = self.ladders.get(curr_val)
self.climbing_ladder(curr_val, final_value, pl_name)
else:
final_value = curr_val
return final_value
def Winner(self, pl_name, position):
time.sleep(self.DELAY_IN_ACTIONS)
if self.DESTINATION == position:
print("\n\n\nBRAVO!!!!!.\n\n" + pl_name + " WON THE GAME.")
print("CONGRATULATIONS " + pl_name)
print("\nThank you for playing the game.")
sys.exit(1)
class Start(Saanp_Seedhi):
def start_the_game(self):
time.sleep(self.DELAY_IN_ACTIONS)
if self.num_of_players == 2:
pl_1, pl_2 = self.get_player_names()
elif self.num_of_players == 4:
pl_1, pl_2, pl_3, pl_4 = self.get_player_names()
time.sleep(self.DELAY_IN_ACTIONS)
pl_1_cur_pos = 0
pl_2_cur_pos = 0
pl_3_cur_pos = 0
pl_4_cur_pos = 0
while True:
time.sleep(self.DELAY_IN_ACTIONS)
if self.num_of_players == 2:
s = " Press enter to roll dice: "
_ = input(pl_1 + ": " + random.choice(self.text) + s)
print("\nRolling the dice...")
dice_val = self.roll_the_dice()
time.sleep(self.DELAY_IN_ACTIONS)
print(pl_1 + " moving....")
pl_1_cur_pos = self.saanp_seedhi(pl_1, pl_1_cur_pos, dice_val)
self.Winner(pl_1, pl_1_cur_pos)
_ = input(pl_2 + ": " + random.choice(self.text) + s)
print("\nRolling dice...")
dice_val = self.roll_the_dice()
time.sleep(self.DELAY_IN_ACTIONS)
print(pl_2 + " moving....")
pl_2_cur_pos = self.saanp_seedhi(pl_2, pl_2_cur_pos, dice_val)
self.Winner(pl_2, pl_2_cur_pos)
elif(self.num_of_players == 4):
s = " Press enter to roll dice: "
_ = input(pl_1 + ": " + random.choice(self.text) + s)
print("\nRolling the dice...")
dice_val = self.roll_the_dice()
time.sleep(self.DELAY_IN_ACTIONS)
print(pl_1 + " moving....")
pl_1_cur_pos = self.saanp_seedhi(pl_1, pl_1_cur_pos, dice_val)
self.Winner(pl_1, pl_1_cur_pos)
_ = input(pl_2 + ": " + random.choice(self.text) + s)
print("\nRolling dice...")
dice_val = self.roll_the_dice()
time.sleep(self.DELAY_IN_ACTIONS)
print(pl_2 + " moving....")
pl_2_cur_pos = self.saanp_seedhi(pl_2, pl_2_cur_pos, dice_val)
self.Winner(pl_2, pl_2_cur_pos)
_ = input(pl_3 + ": " + random.choice(self.text) + s)
print("\nRolling dice...")
dice_val = self.roll_the_dice()
time.sleep(self.DELAY_IN_ACTIONS)
print(pl_3 + " moving....")
pl_3_cur_pos = self.saanp_seedhi(pl_3, pl_3_cur_pos, dice_val)
self.Winner(pl_3, pl_3_cur_pos)
_ = input(pl_4 + ": " + random.choice(self.text) + s)
print("\nRolling dice...")
dice_val = self.roll_the_dice()
time.sleep(self.DELAY_IN_ACTIONS)
print(pl_4 + " moving....")
pl_4_cur_pos = self.saanp_seedhi(pl_4, pl_4_cur_pos, dice_val)
self.Winner(pl_4, pl_4_cur_pos)
if __name__ == "__main__":
lets_play_the_game = Start()
time.sleep(1)
lets_play_the_game.welcome_to_the_game()
lets_play_the_game.Snakes()
lets_play_the_game.Ladders()
lets_play_the_game.start_the_game()
|
c1ba8dbefafd9ea87f4fe74c93e76afa47766fd4 | yrachkov/Python_2_online | /lesson9/hw3.py | 83 | 3.609375 | 4 | s = {'n':2,'d':6,'h':4,'u':11}
for y,l in s.items():
if l ==2:
print(y) |
0ab6be587b51f02f0db4f53534281be61c664c01 | GuiBritoPy/SimplesPySimples | /Jogo.py | 2,323 | 3.84375 | 4 | # -*- coding: utf-8 -*-
while True:
ok = "Ok, vamos continuar"
nome = str(input("Olá, qual o seu nome? "))
idade = str(input("Quantos anos você tem? "))
sexo = str(input("Qual o seu sexo? (M - Masculino e S - Feminino) ")).upper()
if sexo == "F":
sexo = Feminino
if sexo == "S":
sexo = Masculino
ch = 0
print("Ok, vamos começar")
p1 = str(input("Telefonou para a vítima? (S - Sim e N - Não) ")).upper()
if p1 != "S" and p1 != "N":
print("Entrada Inválida")
elif p1 == "S":
ch += 1
print(ok)
else:
ch += 0
print(ok)
p2 = str(input("Esteve no local do crime? (S - Sim e N - Não) ")).upper()
if p2 != "S" and p2 != "N":
print("Entrada Inválida")
elif p2 == "S":
ch += 1
print(ok)
else:
ch += 0
print(ok)
p3 = str(input("Mora perto da vítima? (S - Sim e N - Não) ")).upper()
if p3 != "S" and p3 != "N":
print("Entrada Inválida")
elif p3 == "S":
ch += 1
print(ok)
else:
ch += 0
print(ok)
p4 = str(input("Devia para a vítima? (S - Sim e N - Não) ")).upper()
if p4 != "S" and p4 != "N":
print("Entrada Inválida")
elif p4 == "S":
ch += 1
print(ok)
else:
ch += 0
print(ok)
p5 = str(input("Já trabalhou para a vítima? (S - Sim e N - Não) ")).upper()
if p5 != "S" and p5 != "N":
print("Entrada Inválida")
elif p5 == "S":
ch += 1
print("Ok")
else:
ch += 0
print ("Ok")
#2 questões ela deve ser classificada como "Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente".
print ("#*"*10)
print("Vamos ao relatório")
print ("#*"*10)
if ch == 2:
print("{} de {} anos do sexo {} é considerado(a) Suspeito(a)".format(nome,idade))
elif 2 < ch <= 4:
print("{} de {} anos do sexo {} é considerado(a) Cúmplice.".format(nome,idade))
elif ch == 5:
print("{} de {} anos do sexo {} é considerado(a) Assassino(a) do crime.".format(nome,idade))
else:
print("{} de {} anos do sexo {} é considerado(a) Inocente.".format(nome,idade))
print("Próxima Pessoa")
|
33d262c8ef0f4f7de82ecab4a9fa9783c511e3ec | Italodias32/Python-Repository | /Animal.py | 1,486 | 3.6875 | 4 | class Animal():
def __init__(self, aux_nome, aux_peso):
self.__nome = aux_nome
self.__peso = aux_peso
#Getter e Setters do Nome
def get_nome(self):
return self.__nome
def set_nome(self, aux_nome):
if isinstance(aux_nome, str):
self.__nome = aux_nome
else:
self.__nome = None
#Property do Nome
@property
def __nome(self):
return self._nome
@__nome.setter
def __nome(self, aux_nome):
if isinstance(aux_nome, str):
self._nome = aux_nome
else:
self._nome = str(aux_nome)
#Getter e Setter do Peso
def get_peso(self):
return self.__peso
def set_peso(self, aux_peso):
if isinstance(aux_peso, float):
self.__peso = aux_peso
else:
self.__peso = float(aux_peso)
#Property do Peso
@property
def __peso(self):
return self._peso
@__peso.setter
def __peso(self, aux_peso):
if isinstance(aux_peso, float):
self._peso = aux_peso
else:
self._peso = float(aux_peso)
def __str__(self):
return "Nome: " + self.__nome + ", Peso: " + str(self.__peso) + '\n'
#Metodos da Classe
def imprime_animal(self):
print("Nome: " + self.__nome + ", Peso: " + str(self.__peso))
def alimentacao(self, peso_comida):
self.__peso += peso_comida
|
411a14d6899d35beeab715b621d75d8052b288c5 | Italodias32/Python-Repository | /campeonato.py | 1,335 | 3.65625 | 4 | def vencedor(lista):
maior = -1
for i in lista:
if i.get_pontos() >= maior:
maior = i.get_pontos()
campeao = i.get_nome()
return campeao
class Participante():
def __init__(self, nome, index):
self.__nome = nome
self.__pontos = 0
self.__index = index
def get_nome(self):
return self.__nome
def get_pontos(self):
return self.__pontos
def get_index(self):
return self.__index
def set_pontos(self, aux):
self.__pontos += aux
def duelo(self, other):
print('Duelo de ' + self.get_nome() + ' contra ' + other.get_nome())
p1 = int(input('Quantos duelos ' + self.get_nome() + ' venceu ? '))
p2 = int(input('Quantos duelos ' + other.get_nome() + ' venceu ? '))
if p1 == 2 and p2 == 0:
self.set_pontos(4)
elif p1 == 2 and p2 == 1:
self.set_pontos(3)
other.set_pontos(1)
elif p1 == 0 and p2 == 2:
other.set_pontos(4)
elif p1 == 1 and p2 == 2:
other.set_pontos(3)
self.set_pontos(1)
def pontucao_final(self):
print('A pontução final de ' + self.get_nome() + ' foi de: ' + str(self.get_pontos()) + ' pontos') |
c4eff3bd9244d150afd43170f9d11e910237e416 | Alparse/artificial_intelligence | /tic_tac_toe.py | 7,445 | 3.765625 | 4 | """
Classic tic tac toe system implemented by Serhat Alpar.
Copied from Xxxxxxxxxxxxxxxxx
permalink: Xxxxxxxxxxxxxx
"""
import math
import gym
from gym import spaces, logger
from gym.utils import seeding
import numpy as np
class TicTacToeEnv():
"""
Description:
A game of classical tic tac toe is played until either a draw (all 9 spaces filled without a win condition
being met) or a win (a player claims three horizontally or vertically connected cells in the game obs_space:
Game obs_space is represented by a 2 dimensional array of shape 3,3
Observation Space:
Type: Box(4)
Num Observation Values
0 [0,0]position (P1) 0,1
1 [0,1]position (P1) 0,1
2 [0,2]position (P1) 0,1
3 [1,0]position (P1) 0,1
4 [1,1]position (P1) 0,1
5 [1,2]position (P1) 0,1
6 [2,0]position (P1) 0,1
7 [2,1]position (P1) 0,1
8 [2,2]position (P1) 0,1
9 [0,0]position (P2) 0,1
10 [0,1]position (P2) 0,1
11 [0,2]position (P2) 0,1
12 [1,0]position (P2) 0,1
13 [1,1]position (P2) 0,1
14 [1,2]position (P2) 0,1
15 [2,0]position (P2) 0,1
16 [2,1]position (P2) 0,1
17 [2,2]position (P2) 0,1
Actions:
Type: Discrete(9)
Num Action(Claim) Values
0 [0,0]position (P1) 0,1
1 [0,1]position (P1) 0,1
2 [0,2]position (P1) 0,1
3 [1,0]position (P1) 0,1
4 [1,1]position (P1) 0,1
5 [1,2]position (P1) 0,1
6 [2,0]position (P1) 0,1
7 [2,1]position (P1) 0,1
8 [2,2]position (P1) 0,1
9 [0,0]position (P2) 0,1
10 [0,1]position (P2) 0,1
11 [0,2]position (P2) 0,1
12 [1,0]position (P2) 0,1
13 [1,1]position (P2) 0,1
14 [1,2]position (P2) 0,1
15 [2,0]position (P2) 0,1
16 [2,1]position (P2) 0,1
17 [2,2]position (P2) 0,1
Reward
1 for win
.5 for draw
.1 for move
0 for loss
Starting State:
All observations are set to 0
Episode Termination
Win/Loss/Draw Condition Met
"""
def __init__(self):
self.obs_space = np.zeros([1, 18])
self.allowed_action_space = np.arange(18)
self.allowed_total_action_space=np.zeros((1,9))
self.state = None
self.game_status = 0
# game status 0 = playing
# game status 1 = player 1 win
# game status 2 = player 2 win
# game status 3 = draw
self.turn = 1
self.yrl_ = np.zeros([1, 9])
self.reward1 = 0.0
self.total_rewards1 = 0
self.reward2 = 0.0
self.total_rewards2 = 0
self.reward_dictionary1=[]
def check_if_move_legal(self, player, move):
if player == 1:
if move not in self.allowed_action_space:
return False
else:
return True
if player == 2:
# if move not in self.allowed_action_space_player2:
if move not in self.allowed_action_space:
return False
else:
return True
def check_if_game_won(self, player):
if player == 1:
os = 0 # offset
else:
os = 9 # offset
if 1 == self.obs_space[0, 0 + os] == self.obs_space[0, 1 + os] == self.obs_space[0, 2 + os] \
or 1 == self.obs_space[0, 3 + os] == self.obs_space[0, 4 + os] == self.obs_space[0, 5 + os] \
or 1 == self.obs_space[0, 6 + os] == self.obs_space[0, 7 + os] == self.obs_space[0, 8 + os] \
or 1 == self.obs_space[0, 0 + os] == self.obs_space[0, 3 + os] == self.obs_space[0, 6 + os] \
or 1 == self.obs_space[0, 1 + os] == self.obs_space[0, 4 + os] == self.obs_space[0, 7 + os] \
or 1 == self.obs_space[0, 2 + os] == self.obs_space[0, 5 + os] == self.obs_space[0, 8 + os] \
or 1 == self.obs_space[0, 0 + os] == self.obs_space[0, 4 + os] == self.obs_space[0, 8 + os] \
or 1 == self.obs_space[0, 2 + os] == self.obs_space[0, 4 + os] == self.obs_space[0, 6 + os]:
return True
else:
return False
def check_if_draw(self):
if np.sum(self.obs_space) >= 8.5:
return True
else:
return False
def pick_random_legal_move(self, player):
if not self.check_if_draw():
if player == 1:
random_pool = len(self.allowed_action_space[self.allowed_action_space < 9])
random_pick = np.random.randint(0, random_pool)
random_action = self.allowed_action_space[random_pick]
return random_action
if player == 2:
random_pool = len(self.allowed_action_space[self.allowed_action_space >= 9])
random_pick = np.random.randint(0, random_pool)
random_action = self.allowed_action_space[random_pick + random_pool]
return random_action
else:
return False
def render(self):
player1_space = self.obs_space[0, :9]
player2_space = self.obs_space[0, 9:]
self.allowed_total_action_space=np.add(player1_space,player2_space)
self.allowed_total_action_space[np.where(self.allowed_total_action_space==2)]=1
player2_space = self.obs_space[0, 9:] * 2
render_space = np.add(player1_space, player2_space)
render_space = np.reshape(render_space, (3, 3))
print(render_space)
if self.game_status==1:
print("Player 1 Wins")
if self.game_status==2:
print("Player 2 Wins")
if self.game_status==3:
print ("Draw!")
if self.game_status==0:
print ("Player moved", self.turn)
def make_move(self, player, move):
try:
# assert (self.game_status ==0),"Game Over"
#assert (not self.check_if_draw()), "Game Over Drawn"
#assert (not self.check_if_game_won(player)), "Game Over Won"
#assert (self.check_if_move_legal(player, move)), "Illegal Move"
if player == 1:
self.obs_space[0][move] = 1
move_index = np.argwhere(self.allowed_action_space == move)
self.allowed_action_space = np.delete(self.allowed_action_space, move_index)
move_indexp2 = np.argwhere(self.allowed_action_space == move + 9)
self.allowed_action_space = np.delete(self.allowed_action_space, move_indexp2)
elif player == 2:
self.obs_space[0][move] = 1
move_index = np.argwhere(self.allowed_action_space == move)
self.allowed_action_space = np.delete(self.allowed_action_space, move_index)
move_indexp1 = np.argwhere(self.allowed_action_space == move - 9)
self.allowed_action_space = np.delete(self.allowed_action_space, move_indexp1)
except:
print("Illegal Move")
|
7f0d06254acda9ae0f22b35ddefa6f5d9bf53487 | league-python-student/level0-module1-samus114 | /_04_int/_2_simple_number_adder/simple_adder.py | 523 | 4.0625 | 4 | """
* Write a Python program that asks the user for two numbers.
* Display the sum of the two numbers to the user
"""
import tkinter as tk
from tkinter import messagebox, simpledialog, Tk
if __name__ == '__main__':
window = tk.Tk()
window.withdraw()
num1 = simpledialog.askinteger('', 'what is your first number to be added?')
num2 = simpledialog.askinteger('', 'what is the second number to be added?')
messagebox.showinfo('', 'your number is ' + str(num1+num2))
window.mainloop() |
19ed2bdb0d0e8098568d9cb987ddb8997124082b | Samson26/code | /minmax.py | 146 | 3.546875 | 4 | a=int(input())
arr=[int(i) for i in input().split()]
mini=min(arr)
mini1=int(mini)
maxi=max(arr)
maxi1=int(maxi)
print(str(mini1)+' '+str(maxi1))
|
15e7518c82297499f59d448a23822ee7c8859a8c | Samson26/code | /yesorno.py | 74 | 3.65625 | 4 | b=int(input())
if(b<=10 and b>=1):
print("yes")
else:
print("no")
|
525d87507fad34cf9a6ae9a4afa5c0f97b9af1aa | Samson26/code | /alpha.py | 97 | 3.75 | 4 | user=raw_input()
check=str(user.isalpha())
if check=='True':
print "Alphabet"
else:
print "No"
|
7190442863bed270614b64bd3e8e6055ec1f4960 | akansal1/statsintro_python | /Code/S10_normCheck.py | 930 | 3.515625 | 4 | '''Solution for Exercise "Normality Check"
'''
from scipy import stats
import matplotlib.pyplot as plt
import statsmodels.formula.api as sm
import seaborn as sns
# We don't need to invent the wheel twice ;)
from S12_correlation import getModelData
if __name__== '__main__':
# get the data
data = getModelData(show=False)
# Fit the model
model = sm.ols('AvgTmp ~ year', data)
results = model.fit()
# Normality check ----------------------------------------------------
res_data = results.resid # Get the values for the residuals
# QQ-plot, for a visual check
stats.probplot(res_data, plot=plt)
plt.show()
# Normality test, for a quantitative check:
_, pVal = stats.normaltest(res_data)
if pVal < 0.05:
print('WARNING: The data are not normally distributed (p = {0})'.format(pVal))
else:
print('Data are normally distributed.')
|
63e81f354f4ecbb4d2689d70815dfbec926c2013 | drashti2210/180_Interview_Questions | /merge_sorted_array.py | 1,444 | 3.84375 | 4 | import sys
sys.stdout = open('d:/Coding/output.txt','w')
sys.stdin = open('d:/Coding/input.txt','r')
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# Example
# INPUT
# nums1 = [1,2,3,0,0,0], m = 3
# nums2 = [2,5,6], n = 3
# OUTPUT
# [1,2,2,3,5,6]
nums1=list(map(int,input().split()))
m=int(input())
nums2=list(map(int,input().split()))
n=int(input())
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
# Solution 1
# check greater & append in nums1
if n==0:
return
elif m == 0:
j = 0
for j in range(n):
nums1[j] = nums2[j]
i, j = m-1, n-1
temp = 0
while i>=0 and j>=0:
if nums1[i] >= nums2[j]:
nums1[m+n-temp-1] = nums1[i]
i-=1
temp+=1
else:
nums1[m+n-temp-1] = nums2[j]
j-=1
temp+=1
if j < 0:
return
else:
while j>=0:
nums1[m+n-temp-1]=nums2[j]
j-=1
temp+=1
print(nums1)
return
# Solution 2
# Using Sort
for i in range(n):
nums1[i+m] = nums2[i]
nums1.sort()
merge(nums1,m,nums2,n)
print(nums1) |
45ba4bf16bf612a0b2c9be396a77290ba419215a | drashti2210/180_Interview_Questions | /Mid_of_Linked_List.py | 932 | 3.921875 | 4 | import sys
#Day 5
# 2. Middle of Linked List
# INPUT:-
# 1->2->3->4->5->NULL
# OUTPUT: -
# 3
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def middleNode(head):
# solution 1
# find the length of linked list
# iterate upto mid & return mid element
l=0
temp=head
while temp.next!=None:
temp=temp.next
l+=1
if l%2!=0:
l=(l//2)+1
else:
l=l//2
for i in range(l):
head=head.next
return head
# solution 2
# using array
arr = [head]
while arr[-1].next:
arr.append(arr[-1].next)
return A[len(arr) // 2]
# solution 3
# using slow & fast poiter
# When fast reaches the end of the list, slow must be in the middle.
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow |
b929e51eb223e63930330838af02d7d9fd37c9b7 | drashti2210/180_Interview_Questions | /Add_numbers_Linked_List.py | 1,159 | 3.875 | 4 | import sys
# Add two numbers as LinkedLis
# INPUT:-
# 2 linked list
# 1->2->3->->NULL
# 1->2->3->->NULL
# OUTPUT: -
# addition
# 2->4->6->NULL
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# sotion 1
# using another linked list to store sum
dummy = cur = ListNode(-1)
carry = 0
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
cur.next = ListNode(carry%10)
cur = cur.next
carry //= 10
return dummy.next
# solution 2
# recursive approach
temp = l1.val + l2.val
digit, tenth = temp% 10, temp// 10
answer = ListNode(digit)
if any((l1.next, l2.next, tenth)):
if l1.next:
l1 = l1.next
else:
l1 = ListNode(0)
if l2.next:
l2 = l2.next
else:
l2=ListNode(0)
l1.val += tenth
answer.next = self.addTwoNumbers(l1, l2)
return answer |
4e4019378a59f2b0eb3668cc4c4fbb0abcfa2139 | drashti2210/180_Interview_Questions | /merge_sorted_LL.py | 973 | 4.03125 | 4 | import sys
# Day 1
# 4. Merge Sorted Linked List
#Example:-
#INPUT:-
# 2 sorted linked list
# 1->2->4, 1->3->4
#OUTPUT:-
# Merged Linked List
# 1->1->2->3->4->4
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
if n==0:
return
elif m == 0:
j = 0
for j in range(n):
nums1[j] = nums2[j]
i, j = m-1, n-1
temp = 0
while i>=0 and j>=0:
if nums1[i] >= nums2[j]:
nums1[m+n-temp-1] = nums1[i]
i-=1
temp+=1
else:
nums1[m+n-temp-1] = nums2[j]
j-=1
temp+=1
if j < 0:
return
else:
while j>=0:
nums1[m+n-temp-1]=nums2[j]
j-=1
temp+=1
return
|
5eb0dc3ddab738e7e7d60960ce8e49142ab87a1f | mbaybay/cs686-2018-01 | /knn.py | 2,023 | 3.671875 | 4 | from classifier import classifier
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
class KNN(classifier):
def __init__(self, k=3):
self.x = None
self.y = None
self.k = k
def fit(self, x, y):
"""
:param X: pandas data frame, with rows as observations and columns as observation features
:param Y: pandas series, encoded as categorical classes
:return:
"""
# compute distances
self.x = x
self.y = y
def predict(self, x):
"""
:param x:
:return:
"""
pred = x.apply(self.__get_majority_class, axis=1)
return pred.tolist()
def __get_majority_class(self, obs):
"""
:param obs: one observation of test x
:return:
"""
# distances = pd.Series(index=self.x.index)
def __calc_euclidean_distance(row):
# https://en.wikipedia.org/wiki/Euclidean_distance
# d(p,q) = sqrt(sum((p_i-q_i)**2))
euc_dist = np.sqrt(np.square(row.subtract(obs)).sum()) # row - sub
return euc_dist
# calculate euclidean distance to all points
distances = self.x.apply(func=__calc_euclidean_distance, axis=1)
# sort by distance
distances.sort_values(ascending=False, inplace=True)
# take top-k observations by index
top_k = distances[0:self.k].index
# get majority class from y
majority_class = self.y[top_k].value_counts()
majority_class = majority_class.index[0]
return majority_class
if __name__ == '__main__':
import util
data = util.read_arff_as_df("../../data/PhishingData.arff.txt")
x = data.loc[:, data.columns != 'Result']
y = data['Result']
train_x, test_x, train_y, test_y = train_test_split(x, y)
clf = KNN(k=3)
clf.fit(train_x, train_y)
pred = clf.predict(test_x)
util.print_confusion_matrix(test_y, pred, labels=[-1, 0, 1])
|
bd5d648e9f62bc9ba12ade748eddcaf9aba03474 | cmdavis4/senior-thesis | /spherical_geo.py | 3,242 | 3.65625 | 4 | #+++++++++++++++++++++++++++++++++++++++
#
# Spherical Geometry
#
# Description:
# This file contains the functions for
# spherical geometry calcuations
# including rotations, coordinate transformations
# and angular separations
#
#---------------------------------------
import numpy as np
import numpy.linalg as LA
def to_sphere(point):
"""accepts a x,y,z, coordinate and returns the same point in spherical coords (r, theta, phi) i.e. (r, azimuthal angle, altitude angle) with phi=0 in the zhat direction and theta=0 in the xhat direction"""
coord = (np.sqrt(np.sum(point**2)),
np.arctan2(point[1],point[0]),
np.pi/2.0 - np.arctan2(np.sqrt(point[0]**2 + point[1]**2),point[2])
)
return np.array(coord)
def to_cartesian(point):
"""accepts point in spherical coords (r, theta, phi) i.e. (r, azimuthal angle, altitude angle) with phi=0 in the zhat direction and theta=0 in the xhat direction and returns a x,y,z, coordinate"""
coord = point[0]*np.array([np.cos(point[2])*np.cos(point[1]),
np.cos(point[2])*np.sin(point[1]),
np.sin(point[2])])
return coord
def rotate(p1, p2, p3):
"""rotates coordinate axis so that p1 is at the pole of a new spherical coordinate system and p2 lies on phi (or azimuthal angle) = 0
inputs:
p1: vector in spherical coords (phi, theta, r) where phi is azimuthal angle (0 to 2 pi), theta is zenith angle or altitude (0 to pi), r is radius
p2: vector of same format
p3: vector of same format
Output:
s1:vector in (r, theta, phi) with p1 on the z axis
s2:vector in (r,, theta, phi) with p2 on the phi-hat axis
s3:transformed vector of p3
"""
p1_cc=to_cartesian(p1)
p2_cc=to_cartesian(p2)
p3_cc=map(to_cartesian, p3)
p1norm = p1_cc/LA.norm(p1_cc)
p2norm = p2_cc/LA.norm(p2_cc)
p3norm = map(lambda x: x/LA.norm(x), p3_cc)
zhat_new = p1norm
x_new = p2norm - np.dot(p2norm, p1norm) * p1norm
xhat_new = x_new/LA.norm(x_new)
yhat_new = np.cross(zhat_new, xhat_new)
dot_with_units = lambda x: [np.dot(x, xhat_new), np.dot(x, yhat_new),
np.dot(x, zhat_new)]
s1 = np.array(dot_with_units(p1_cc))
s2 = np.array(dot_with_units(p2_cc))
s3 = np.array(map(dot_with_units, p3_cc))
s1=to_sphere(s1)
s2=to_sphere(s2)
s3=np.array(map(to_sphere, s3))
return s1, s2, s3
def calc_distance(center, points):
'''Calculate the circular angular distance of two points on a sphere.'''
center = np.array(center)
points = np.array(points)
lambda_diff = center[0] - points[:,0]
cos1 = np.cos(center[1])
cos2 = map(np.cos, points[:,1])
sin1 = np.sin(center[1])
sin2 = map(np.sin, points[:,1])
num1 = np.power(np.multiply(cos2, map(np.sin, lambda_diff)), 2.0)
num2 = np.subtract(np.multiply(cos1, sin2), np.multiply(np.multiply(sin1, cos2), map(np.cos, lambda_diff)))
num = np.add(num1, np.power(num2, 2.0))
denom1 = np.multiply(sin1, sin2)
denom2 = np.multiply(np.multiply(cos1, cos2), map(np.cos, lambda_diff))
denom = np.add(denom1, denom2)
return map(np.arctan2, map(np.sqrt, num), denom) |
dd50743885e2a849652cef7243486196ce364b33 | vikramdayal/RaspberryMotors | /example_simple_servo.py | 2,287 | 4.0625 | 4 | #!/usr/bin/env python3
'''
simple example of how to use the servos interface.
In this example, we are connecting a sinle servo control
to GPIO pin 11 (RaspberryPi 4 and 3 are good with it)
Wiring diagram
servo-1 (referred to S1 in the example code)
---------------------------------------------
| servo wire | connected to GPIO pin on Pi |
|------------|------------------------------|
| Brown | 6 (GND) |
| Red | 2 (5v power) |
| Yellow | 11(GPIO 17 on Pi-4) |
---------------------------------------------
Code of this example:
#create a servo object, connected to GPIO board pin #11
s1 = servos.servo(11)
#operate the servos. Note, we are using setAngleAndWait function
#which waits for a specific time (default 1 sec) for the servo to react
s1.setAngleAndWait(0) # move to default position of zero degrees
s1.setAngleAndWait(180) # move to position of 180 degrees
#in the above examples, the servo will wait for default 1 second to respond, we
#can change the respond time in seconds, in this example, we will wait 0.5 seconds
s1.setAngleAndWait(0, 0.5) # move back to position of zero degrees and wait 0.5
#we are done with the servo pin shut it down
s1.shutdown()
'''
# Name: example_simple_servo.py
# Author: Vikram Dayal
##############################################################
#import the servos package from motors module
from RaspberryMotors.motors import servos
def main():
print("starting example")
#create a servo object, connected to GPIO board pin #11
s1 = servos.servo(11)
#operate the servos. Note, we are using setAngleAndWait function
#which waits for a specific time (default 1 sec) for the servo to react
s1.setAngleAndWait(0) # move to default position of zero degrees
s1.setAngleAndWait(180) # move to position of 180 degrees
#in the above examples, the servo will wait for default 1 second to respond, we
#can change the respond time in seconds, in this example, we will wait 0.5 seconds
s1.setAngleAndWait(0, 0.5) # move back to position of zero degrees
# we are done with the servo pin shut it down
s1.shutdown()
if __name__ == "__main__":
main() |
13a7cd02724849f25e7775b0fd1045364f3a5b98 | Dan609/code_learn | /ipython_log1.py | 3,943 | 3.75 | 4 | # IPython log file
get_ipython().run_line_magic('logstart', '')
class Car:
speed = 5
car1 = Car()
car2 = Car()
car1.engine
car2.engine
car1.engine = 'V8 Turbo'
car1.engine
car2.engine
Car.wheels = 'Wagon wheels ('
c1.wheels
car1.wheels
Car = Car()
Car
new_car = Car()
Car.speed
car1.speed
car2.wheels
car2.engine
Car.engine
# Classes can have both methods and fields
class Window:
is_opened = False
def open(self):
self.is_opened = True
print('Window is now', self.is_opened)
def close(self):
self.is_opened = False
print('Window is now', self.is_opened)
window1 = Window()
window2 = Window()
window1.open()
window2.is_opened
dir(window2)
class Car:
speed = 0
Car.engine = 'V8'
class Car:
engine = 'V8'
speed = 0
window2.__class__
class Car:
speed = 0
def __init__(self, color):
print('Constructor is called!')
print('Self is the object itself!', self)
self.color = color
car1 = Car()
car1 = Car('red')
car2 = Car('black')
car1.speed
car2.speed
car2.color
car1.color
class Car:
speed = 0
def __init__(self, color, transmission='Auto'):
print('Constructor is called!')
print('Self is the object itself!', self)
self.color = color
self.transmission = transmission
car1 = Car('black')
car2 = Car('yellow', 'Manual')
car1.transmission
car1.color
car1.transmission
class Car:
speed = 0
def __init__(self, color='black', transmission='Auto'):
print('Constructor is called!')
print('Self is the object itself!', self)
self.color = color
self.transmission = transmission
car1 = Car(transmission='Manual')
car1 = Car(,'Manual')
Car()
c3 = Car()
car1.speed
class Test(object): # it is the same as the code above (py3 only)
pass
class Test: # it is the same as the code above (py3 only)
pass
class Person(object):
biological_name = 'homo sapiens'
def __init__(self, name, age):
self.name = name
self.age = age
def walk(self):
print('Walking...')
def say_hello(self):
print('I am a person', self.name, self.age)
person = Person('Ivan', 25)
person.walk()
person.say_hello()
class Student(Person):
def say_hello(self):
print('I am a student', self.name, self.age)
student = Student('Fedor', 19)
student.walk()
student.say_hello()
class Car:
pass
class CarWithManualTransmission(Car):
pass
class CarWithAutoTransmission(Car):
pass
type(student)
isinstance(student, Student)
isinstance(student, Person)
class Child(Person):
def walk(self):
raise ValueError('Can not walk')
def say_hello(self):
raise ValueError('Can not talk')
def crawl(self):
print('Haha!')
new_child = Child()
new_child = Child('Petr', 1)
new_child.walk()
new_child.say_hello()
new_child.crawl()
student.crawl()
person.crawl()
class Example(object):
def __init__(self):
self.a = 1
self._b = 2
self.__c = 3
print('{} {} {}'.format(
self.a, self._b, self.__c))
def call(self):
print('Called!')
def _protected_method(self):
pass
def __private_method(self):
pass
try:
print(example.__c)
except AttributeError as ex:
print(ex)
example = Example()
try:
print(example.__c)
except AttributeError as ex:
print(ex)
dir(example)
example._Example__c
class Parent(object):
def call(self):
print('Parent')
class Child(Parent):
def call(self):
print('Child')
len((1,3,4,))
len(['a', 'g', 'b'])
len("string")
def call_obj(obj):
obj.call()
call_obj(Child())
call_obj(Parent())
|
ecb3c2aa29cc645e011d5e599a0ed24eb1f983b2 | PraneshASP/LeetCode-Solutions-2 | /69 - Sqrt(x).py | 817 | 3.9375 | 4 | # Solution 1: Brute force
# Runtime: O(sqrt(n))
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
sqrt = 1
while sqrt*sqrt <= x:
sqrt += 1
return sqrt-1
# Solution 2: Use Newton's iterative method to repeatively "guess" sqrt(n)
# Say we want sqrt(4)
# Guess: 4
# Improve our guess to (4+(4/4)) / 2 = 2.5
# Guess: 2.5
# Improve our guess to (2.5+(4/2.5)) / 2 = 2.05
# ...
# We get to 2 very quickly
# Runtime: O(logn)
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
# Use newton's iterative method
delta = 0.0001
guess = x
while guess**2 - x > delta:
guess = (guess+(x/guess))/2.0
return int(guess) |
3785a9becaf8fad4904ea2ec560aec3e6da7de03 | PraneshASP/LeetCode-Solutions-2 | /277 - Find the Celebrity.py | 1,748 | 3.796875 | 4 | # Solution 1: This problem is the same as finding a "universal sink" in a graph.
# A universal sink in the graph => there is no other sink in the graph, so
# we can just iterate through the nodes until we find a sink. Then check if it's universal.
# O(n) runtime, O(n) space
class Solution(object):
def findCelebrity(self, n):
"""
:type n: int
:rtype: int
"""
visited = set()
node = 0
while len(visited) < n:
visited.add(node)
sink = True
for i in range(0, n):
if i == node:
continue
if i not in visited and knows(node,i):
# Visit i
node = i
sink = False
break
if sink:
# Found sink, check if it's universal
for i in range(0,n):
if i == node:
continue
if not knows(i, node):
return -1
if knows(node,i):
return -1
return node
return -1
# Solution 4: Let's shorten the code and use O(1) space
class Solution(object):
def findCelebrity(self, n):
"""
:type n: int
:rtype: int
"""
# find a sink in the graph
sink = 0
for i in range(1,n):
if knows(sink,i):
sink = i
# check if it's universal
for i in range(0,n):
if i == sink:
continue
if not knows(i, sink):
return -1
if knows(sink,i):
return -1
return sink
|
b535625fb73b96be2ba8156e9f77c789b9b6e29a | PraneshASP/LeetCode-Solutions-2 | /90 - Subsets II.py | 2,191 | 3.78125 | 4 | # Solution 1: It is sufficient to just do a lookup to see if we
# have already made an existing subset. Runtime = O(nlogn * (2^n))
# You may see the sort in the loop and say it's O(nlogn * (2^n)), which
# isn't wrong, but note that there is actually only one subset of length n.
# There are exponentially more subsets of length 1 (2^n / 2) or length 2 (2^n / 4), etc,
# so our sort is actually going to take much less than O(nlogn) on average. That's
# why this solution will still AC on LeetCode.
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
pset = []
size = 2 ** len(nums)
lookup = set()
for i in range(size):
subset = []
for j in range(len(nums)):
if (2**j) & i == (2**j):
subset.append(nums[j])
subset.sort()
if tuple(subset) not in lookup:
pset.append(subset)
lookup.add(tuple(subset))
return pset
# Solution 2: We can still make our solution faster if we take the
# sort outside of the loop. In order to do this we need to observe that
# we can treat duplicates as special numbers.
# ex. if an element is duplicated 3 times, we add this element 0 -> 3 times to
# every existing subset in our list
# For some reason this solution only works with Python 3 on LeetCode,
# maybe due to the list comprehension.
# Runtime = O(n * (2^n))
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
pset = [[]]
i = 0
while i < len(nums):
num = nums[i]
dupes = 1 # number of duplicates
curr = i+1
while curr < len(nums) and nums[curr] == nums[curr-1]:
dupes += 1
curr += 1
# Add the num 0 -> dupes times to each subset
for k in range(len(pset)):
for j in range(1, dupes+1):
pset += [pset[k] + [num for k in range(j)]]
i += dupes
return pset
|
d68997dde4826ce9781322db961198d8ac537173 | PraneshASP/LeetCode-Solutions-2 | /300 - Longest Increasing Subsequence.py | 5,129 | 3.828125 | 4 | # Solution 1: An O(n^2) algorithm is to start from the back of the array.
# Observe that the last element creates an LIS of size 1. Move to the
# next element, this will either create an LIS of size 2 (if it is smaller
# than the last element), or a new LIS of size 1.
# Repeat this process by moving backwards through the array and keeping track
# of <start of LIS, length of LIS>.
# tldr; Each element will either start a new LIS of size 1, or add to an existing LIS.
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if(len(nums) <= 1):
return len(nums)
lis = [] # list of <start of LIS, length of LIS>
for i in range(len(nums)-1,-1,-1):
lisLength = None
# Check if there's an existing LIS we can add to
for j in range(0, len(lis)):
if nums[i] < lis[j][0]:
if lisLength is None:
lisLength = lis[j][1]
elif lis[j][1] > lisLength:
lisLength = lis[j][1]
# Add to existing LIS, or start a new one
if lisLength:
lis.append([nums[i],lisLength+1])
else:
lis.append([nums[i], 1])
maxLis = 1
for i in range(0, len(lis)):
if(lis[i][1] > maxLis):
maxLis = lis[i][1]
return maxLis
# Solution 2: Let's make a small optimization.
# Observe that we only need to store the LARGEST element that starts an LIS.
# Ex. Let's say our list is [1, 110, 100]
# 100 starts an LIS of length 1. When we get to 110, rather than adding a new LIS of length 1,
# we can just update our existing LIS to use 110 instead of 100. This is because
# every element that would create a longer LIS with 100 will also create a longer LIS
# with 110.
# We can see how this logic works with the following example.
# Ex. Our list is [1,3,6,7,9,4,10,5,6]
# <length of LIS, largest element that starts LIS>
# 1st iteration: <1,6>
# 2nd iteration: <1,6>, <2,5>
# 3rd iteration: <1,10>, <2,5> *** UPDATE
# 4th iteration: <1,10>, <2,5>, <3,5>
# 5th iteration: <1,10>, <2,5>, <3,5>, <4, 4>
# 6th iteration: <1,10>, <2,9>, <3,5>, <4, 4> *** UPDATE
# 7th iteration: <1,10>, <2,9>, <3,6>, <4, 4> *** UPDATE
# 8th iteration: <1,10>, <2,9>, <3,6>, <4, 4>, <5, 3>
# 9th iteration: <1,10>, <2,9>, <3,6>, <4, 4>, <5, 3>, <6, 1>
# Longest LIS = length 6, starting with element 1
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if(len(nums) <= 1):
return len(nums)
lis = [] # list of <length of LIS, largest element that starts LIS>
for i in range(len(nums)-1,-1,-1):
update = 0
for j in range(0, len(lis)):
if nums[i] == lis[j][1]:
update = 1 # if there's a duplicate element, don't do anything
break
if nums[i] > lis[j][1]:
lis[j][1] = nums[i]
update = 2
break
if update == 0:
lis.append([len(lis)+1, nums[i]])
return len(lis)
# Solution #3: Notice that we don't actually need to store tuples anymore.
# We can just use the array index to represent the LIS length.
# I also noticed when writing this that we don't actually need to look
# from the back of the array :) Let's write the forloop from 0 -> n
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if(len(nums) <= 1):
return len(nums)
lis = [] # lis[i] = smallest element that starts an LIS of length i
for i in range(0,len(nums)):
update = 0
for j in range(0, len(lis)):
if nums[i] == lis[j]:
update = 1 # if there's a duplicate LIS, don't do anything
break
if nums[i] < lis[j]:
lis[j] = nums[i]
update = 2
break
if update == 0:
lis.append(nums[i])
return len(lis)
# Solution #4: O(nlogn) solution. Notice the lis list is always sorted. So we can
# use a binary search to determine where to update instead of a linear search.
import bisect
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if(len(nums) <= 1):
return len(nums)
lis = [nums[0]] # lis[i] = smallest element that starts an LIS of length i
for i in range(1,len(nums)):
binarySearchIndex = bisect.bisect(lis,nums[i])
# Avoid duplicate LIS
if binarySearchIndex > 0 and lis[binarySearchIndex-1] == nums[i]:
continue
if binarySearchIndex == len(lis):
lis.append(nums[i])
else:
lis[binarySearchIndex] = nums[i]
return len(lis)
|
4da19128caf20616ecbd36b297022b1d3ccb92ce | PraneshASP/LeetCode-Solutions-2 | /234 - Palindrome Linked List.py | 1,548 | 4.1875 | 4 | # Solution: The idea is that we can reverse the first half of the LinkedList, and then
# compare the first half with the second half to see if it's a palindrome.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None:
return True
slow = head
fast = head
# Move through the list with fast and slow pointers,
# when fast reaches the end, slow will be in the middle
# Trick #1: At the same time we can also reverse the first half of the list
tmp = slow.next
while fast is not None and fast.next is not None:
fast = fast.next.next
prev = slow
slow = tmp
tmp = slow.next
slow.next = prev
head.next = None
# Trick #2: If fast is None, the string is even length
evenCheck = (fast is None)
if evenCheck:
if slow.val != slow.next.val:
return False
slow = slow.next.next
else:
slow = slow.next
# Check that the reversed first half matches the second half
while slow is not None:
if tmp is None or slow.val != tmp.val:
return False
slow = slow.next
tmp = tmp.next
return True
|
9fa0f80646fcba2e31f4d42327304c335459cf81 | indefinitelee/Interview-Stuff | /numbers.py | 918 | 3.703125 | 4 | def main():
f("12365212354", 26)
def f(numbers, target):
for i in range(1, len(numbers)):
current = int(numbers[0:i])
to_end = numbers[i:-1]
evaluate(0, current, to_end, target, current)
def evaluate(sum, previous, numbers, target, out):
if len(numbers) == 0:
if sum + previous == int(target):
print str(out) + "=" + str(target)
else:
for i in range(1, len(numbers)):
current = int(numbers[0:i])
to_end = numbers[i:-1]
evaluate(sum + previous, int(current), to_end, target, str(out) + "+" + str(current))
evaluate(sum, previous * int(current), to_end, target, str(out) + "*" + str(current))
evaluate(sum, previous / int(current), to_end, target, str(out) + "/" + str(current))
evaluate(sum + previous, -int(current), to_end, target, str(out) + "-" + str(current))
main()
|
e1557d11a69c703d33d90b123f65d8b34d0c69d2 | iainhemstock/Katas | /BinarySearch/python/BinarySearch.py | 468 | 3.78125 | 4 | def find_index_of(value, list):
index = -1
if len(list) == 0: index = -1
else:
lowpoint = 0
highpoint = len(list)
while lowpoint < highpoint:
midpoint = int((lowpoint + highpoint) / 2)
if value == list[midpoint]:
index = midpoint
break
if value > list[midpoint]: lowpoint = midpoint + 1
if value < list[midpoint]: highpoint = midpoint
return index
|
9598e90194eb277fd04ea04f0bb09b10083ab33d | iainhemstock/Katas | /LcdDisplay/python/main.py | 1,000 | 3.703125 | 4 | from lcd_digits import one, two, three, four, five, six, seven, eight, nine, zero
def parse(input):
switcher = {
"1" : one,
"2" : two,
"3" : three,
"4" : four,
"5" : five,
"6" : six,
"7" : seven,
"8" : eight,
"9" : nine,
"0" : zero
}
lcd_digits = []
for char in input:
lcd_digits.append(switcher.get(char))
return lcd_digits
def buildOutput(lcd_digits, spacing):
output = ""
digit_height = len(lcd_digits[0]) if len(lcd_digits) >= 1 else 0
for i in range(digit_height):
for digit in lcd_digits:
output += digit[i] + (' ' * spacing)
output += "\n"
return output
def convertToLcd(input, spacing):
lcd_digits = parse(input)
return buildOutput(lcd_digits, spacing)
def main():
number = input("Enter a number:")
spacing = int(input("Enter spacing:"))
print (convertToLcd(number, spacing))
if __name__ == "__main__":
main()
|
ac95a08e0f92a66b9d1df15cddf154c33bc1befa | iainhemstock/Katas | /PrimeFactors/python/main.py | 916 | 3.828125 | 4 | import unittest
class PrimeFactors():
def of(n):
list = []
divisor = 2
while n >= 2:
while n % divisor == 0:
list.append(divisor)
n /= divisor
divisor += 1
return list
class PrimeFactororizerShould(unittest.TestCase):
def test_return_prime_factors_of_integer(self):
self.assertEqual(PrimeFactors.of(1), [])
self.assertEqual(PrimeFactors.of(2), [2])
self.assertEqual(PrimeFactors.of(3), [3])
self.assertEqual(PrimeFactors.of(4), [2,2])
self.assertEqual(PrimeFactors.of(5), [5])
self.assertEqual(PrimeFactors.of(6), [2,3])
self.assertEqual(PrimeFactors.of(7), [7])
self.assertEqual(PrimeFactors.of(8), [2,2,2])
self.assertEqual(PrimeFactors.of(9), [3,3])
self.assertEqual(PrimeFactors.of(10), [2,5])
|
b551eb195b0f3f912eb56fbb774f6054488ee8bd | jigarshah2811/Python-Programming | /6-DS-Graph/test_graph.py | 1,804 | 3.796875 | 4 | from Graph import Graph
"""
TEST CASES
"""
print("\n============ Directed Graph ==============\n")
g = Graph()
edges = [
("A", "B", 7),
("A", "D", 5),
("B", "C", 8),
("B", "D", 9),
("B", "E", 7),
("C", "E", 5),
("D", "E", 15),
("D", "F", 6),
("E", "F", 8),
("E", "G", 9),
("F", "G", 11),
("H", "I", 20)
]
for edge in edges:
src, dest = edge[0], edge[1]
g.add_edge(src, dest)
print(("Graph: {0}".format(sorted(iter(g.graph.items()), key=lambda x:x[0]))))
print("DFS---> connected graph")
print((g.dfs_connected_graph("A")))
print("DFS---> Disconnected graph")
print((g.dfs_disconnected_graph()))
print("BFS---> connected graph")
print((g.bfs_connected_graph('A')))
print("BFS---> Disconnected graph")
print((g.bfs_disconnected_graph()))
print("\n============ Weighted directed Graph ==============\n")
g = Graph()
edges = [
("A", "B", 7),
("A", "D", 5),
("B", "C", 8),
("B", "D", 9),
("B", "E", 7),
("C", "E", 5),
("D", "E", 15),
("D", "F", 6),
("E", "F", 8),
("E", "G", 9),
("G", "A", 9),
("F", "G", 11),
("H", "I", 20)
]
for edge in edges:
src, dest, weight = edge[0], edge[1], edge[2]
g.add_edge(src, dest, weight)
print(("Graph: {0}".format(sorted(iter(g.graph.items()), key=lambda x:x[0]))))
print("DFS---> Weighted Disconnected graph")
print((g.dfs_disconnected_graph()))
print("BFS---> Weighted Disconnected graph")
print((g.bfs_disconnected_graph()))
print("Detect Cycle---> Weighted Disconnected graph")
print((g.is_cycle()))
print("Find Path from Src to Dest---> Weighted Disconnected graph")
print((g.find_path("A", "G")))
clonedGraph = g.cloneGraph("A")
print("Original Graph: -->")
print(g.printGraph())
print("Cloned Graph: -->")
print(clonedGraph.printGraph()) |
869edf4c975e41ccdee0eacfbda1a636576578fc | jigarshah2811/Python-Programming | /Matrix_Print_Spiral.py | 1,741 | 4.6875 | 5 | """
http://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/
Print a given matrix in spiral form
Given a 2D array, print it in spiral form. See the following examples.
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Input:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Output:
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11
spiral-matrix
"""
def print_spiral(matrix):
'''matrix is a list of list -- a 2-d matrix.'''
first_row = 0
last_row = len(matrix) - 1
first_column = 0
last_column = len(matrix[0]) - 1
while True:
# Print first row
for col_idx in range(first_column, last_column + 1):
print(matrix[first_row][col_idx])
first_row += 1
if first_row > last_row:
return
# Print last column
for row_idx in range(first_row, last_row + 1):
print(matrix[row_idx][last_column])
last_column -= 1
if last_column < first_column:
return
# Print last row, in reverse
for col_idx in reversed(range(first_column, last_column + 1)):
print(matrix[last_row][col_idx])
last_row -= 1
if last_row < first_row:
return
# Print first column, bottom to top
for row_idx in reversed(range(first_row, last_row + 1)):
print(matrix[row_idx][first_column])
first_column += 1
if first_column > last_column:
return
if __name__ == '__main__':
mat = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
print_spiral(mat)
|
4d07e9f7c2199352a664077c93d640d55304e84a | jigarshah2811/Python-Programming | /Interviews/Meta/SlidingWindow-PartitionArray.py | 1,479 | 3.859375 | 4 | """ Q: Partition Array so that Sum of all partitions are SAME
Given an array of integers greater than zero, find if there is a way to
split the array in two (without reordering any elements) such that the
numbers before the split add up to the numbers after the split. If so,
print the two resulting arrays.
=== Test cases ===
In [1]: can_partition([5, 2, 3])
Output [1]: ([5], [2, 3])
Return [1]: True
In [2]: can_partition([2, 3, 2, 1, 1, 1, 2, 1, 1])
Output [2]([2, 3, 2], [1, 1, 1, 2, 1, 1])
Return [2]: True
In [3]: can_partition([1, 1, 3])
Return [3]: False
In [4]: can_partition([1, 1, 3, 1])
Return [4]: False
"""
class Solution:
def can_partition(self, nums):
Lsum, Rsum = 0, sum(nums)
for i, num in enumerate(nums):
Lsum += num
Rsum -= num
if Lsum == Rsum:
print(f"Found split at:{i}, LeftSum: {Lsum}, RightSum: {Rsum}")
L = nums[:i+1] # <--- ..i (includes 0.....i)
R = nums[i+1:] # ----> i... (includes i+1....)
return(L, R)
return None
s = Solution()
nums = [5, 2, 3]
print(s.can_partition(nums)) # output Output [1]: ([5], [2, 3])
nums = [2, 3, 2, 1, 1, 1, 2, 1, 1]
print(s.can_partition(nums)) # output ([2, 3, 2], [1, 1, 1, 2, 1, 1])
nums = [1, 1, 3]
print(s.can_partition(nums)) # output: None, FALSE
nums = [1, 1, 3, 1]
print(s.can_partition(nums)) # Output: None, False |
5ea6b05ac7cd8c380f3e58b0f667c3ee021a0214 | jigarshah2811/Python-Programming | /4-DS-LinkedList/LinkedList.py | 1,839 | 3.953125 | 4 | class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self, val=0):
self.head = None
def __append__(self, val):
if self.head is None:
self.head = self.Node(val)
return
# Append at the end of list
cur = self.head
while cur.next:
cur = cur.next
cur.next = self.Node(val)
""" Let's find out if this keyboard is working as expected254BTGBNBG """
def __insertAtPos__(self, pos, val):|
cur = self.head
while cur and pos > 1:
pos -= 1
cur = cur.next
# Either we reached to pos or reached end
newNode = self.Node(val)
newNode.next = cur.next
cur.next = newNode
def __pop__(self):
headVal = self.head.val
self.head = self.head.next
return headVal
def __popAtPos__(self, pos):
if self.head is None: # Empty list
raise IndexError
cur = self.head
while cur.next and pos > 0:
cur = cur.next
pos -= 1
if cur.next is None: # Trying to remove invalid index
raise IndexError
cur.next = cur.next.next
def __remove__(self, val):
if self.head is None: # Empty list
raise IndexError
cur = self.head
while cur.next and cur.next.val != val:
cur = cur.next
# cur is at point where next node is to be removed
if cur.next is None: # Trying to remove invalid index
raise IndexError
cur.next = cur.next.next
def __hasNext__(self):
return self.cur is None
def __print__(self):
cur = self.head
while cur:
print(cur.val,)
cur = cur.next
|
0fdb0ee310f777deb4a7de34085615bfe3d5802b | jigarshah2811/Python-Programming | /1-DS-Array-String/CarParking.py | 1,080 | 3.734375 | 4 | class Solution:
def parkingCars(self, parking):
freeSlot = len(parking)-1
for i, car in enumerate(parking):
if car == i: # If Car#K is already at ParkingSlot#K then no movement required
continue
# For car#i find target slot#i
targetSlot = car
if parking[targetSlot] != -1: # If target slot is NOT available,
# make it available by moving the car from targetSlot to freeSlot
parking[targetSlot], parking[freeSlot] = parking[freeSlot], parking[targetSlot]
# Target Slot is now available, simply move the car to target slot from current slot
parking[targetSlot], parking[i] = parking[i], parking[targetSlot]
return parking
s = Solution()
parking = [1, 0, -1] # spots: 3 and cars: 2
print(s.parkingCars(parking))
parking = [3, 1, 2, 0, -1] # spots: 5 and cars: 4
print(s.parkingCars(parking))
parking = [3, 5, 2, 0, 1, 4, -1] # spots: 5 and cars: 4
print(s.parkingCars(parking))
|
1c89bf03246ff0284b01255ec5827ff2866c8041 | jigarshah2811/Python-Programming | /Algo-Sorting-Searching/BinarySearch.py | 1,014 | 4.09375 | 4 | from typing import List
class Solution:
def BinarySearch(self, nums: List[int], target: int) -> int:
# Binary search works only for sorted array, so make sure array is sorted
# Setup indexes, low and high and move them around low++ or high-- based on mid value
low, high = 0, len(nums)-1
while low <= high:
mid = low // 2 # Works for even and odd size arr pretty well, left side will have 1 more element
if nums[mid] == target: # FOUND!
return mid
elif nums[mid] > target: # We are too much on right side, move to left
high = mid-1 # <---- High
else: # We are too much on left side, move to right
low = mid+1 # Low ---->
return -1 # if target element not found, return -1 == NOT_FOUND
s = Solution()
arr = [1, 2, 3, 4, 5, 6, 7]
print(s.BinarySearch(arr, target=6))
arr = [-1,0,3,5,9,12]
print(s.BinarySearch(arr, target=9))
|
3a369371f4bfaf5ebade5192a371a1d3e0214101 | jigarshah2811/Python-Programming | /1-DS-Array-String/Array-Misc-Easy.py | 3,101 | 4 | 4 | from typing import List, Tuple
"""
STRATEGY: Map, Modify as you go...
"""
class Solution:
def insertionSort(nums):
for i, num in enumerate(nums):
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and num < nums[j] :
nums[j+1] = nums[j]
j -= 1
nums[j+1] = num
return nums
def firstTwoMaxNums(self, nums: List) -> tuple():
firstMax, secondMax = float('-inf'), float('-inf')
for i, num in enumerate(nums):
if num > firstMax: # Found bigger firstMax
secondMax = firstMax # Backup previous firstMax as secondMax
firstMax = num # New firstMax
return (firstMax, secondMax)
"""
https://www.geeksforgeeks.org/sieve-of-eratosthenes/
"""
def countPrimes(self, n):
# Edge case
if n < 3:
return 0
# Create a table of all numbers are prime: True
prime = [True for i in range(n)]
prime[0] = prime[1] = False
# Iterate through each number in table starting from 1st prime number=2
for i in range(2, int(n ** 0.5) + 1):
if prime[i]:
# Mark all multiplication... prime=False!
# Start with 2*2 and mark all increments of 2
# Start with 3*3 and mark all increments of 3
# Start with 5*5 and mark all increments of 5
for p in range(i*i, n, i):
prime[p] = False
return sum(prime)
def firstNonRepeatingNum(self, nums):
from sys import maxsize
d = {}
# Build a freq map but also store index
# {Num --> (freq, index)}
for i, num in enumerate(nums):
if num in d:
d[num] = (d[num][0]+1, i)
else:
d[num] = (1, i)
print(d)
# Walk through dict key to find num with freq=1 and with min index
resIndex = float('inf')
for num, (freq, index) in list(d.items()): # OPTIMIZE: Iterate only on keys not the entire nums array again!!!
if freq == 1: # Non repeating number
resIndex = min(resIndex, index) # First non repeating number
print(resIndex)
return nums[resIndex] if resIndex == float('inf') else -1
s = Solution()
print("First two maximum numbers from the array")
nums = []
print(s.firstTwoMaxNums(nums))
nums = [1]
print(s.firstTwoMaxNums(nums))
nums = [1, 2]
print(s.firstTwoMaxNums(nums))
nums = [3, 6, 1, 4, 2]
print(s.firstTwoMaxNums(nums))
nums = [0,1,0,3,12]
print(s.firstTwoMaxNums(nums))
#print ("Total prime numbers till value: {0}, are: {1}".format(50, s.countPrimes(50)))
#print ("Total prime numbers till value: {0}, are: {1}".format(50, s.countPrimes(9999999)))
nums = [3,4,1,2,5,2,1,4,2] # 3 and 5 don't repeat, so return 3
print(("First non repeating number is: ", s.firstNonRepeatingNum(nums))) |
8d68737c1826c508a060af1873b139fa083af8f5 | jigarshah2811/Python-Programming | /Algo-Sorting-Searching/BS-RandomPickUniformDistribution.py | 1,736 | 3.5625 | 4 | import random
class Solution:
def __init__(self, w: List[int]):
# Generate [1/8, 3/8, 4/8]
totalWeight = sum(w)
for i, weight in enumerate(w):
w[i] = weight / totalWeight
# Generate on number line for uniform distribtion betwee 0%-100%
# [1/8, 4/8, 1] See last weight will always be 1 (=100%)
for i, weight in enumerate(w):
if i == 0: # skip 1st
continue
w[i] += w[i-1]
self.w = w
def pickIndex_orderN(self) -> int:
# Generate a random uniformity between 0...1
pickedWeight = random.uniform(0, 1)
for i, weight in enumerate(self.w):
if pickedWeight <= weight:
return i
""" Pattern: Binary Search ---- Get Index of value between (0, ..., 1)
If the value does not exists, return index of closest value target=0.26 in [0.1, 0.25, 0.75] would return index=1
"""
def pickIndex_BinarySearch(self):
target = random.uniform(0, 1)
# print(f"target: {target}")
# Make it unform by selecting the index based on probability weight
low, high = 0, len(self.weights)-1
while low < high:
mid = (low + high) >> 1
# print(f"mid: {mid}, val: {self.weights[mid]}")
if self.weights[mid] == target:
return mid
if target > self.weights[mid]:
# print(f"Searching on R ---> ")
low = mid + 1
else:
# print(f"Searching on L <----")
high = mid
# At this point low and high would be same
return min(low, high) |
dddd4ff528366a9bde62d630ef80f23abaeaa390 | jigarshah2811/Python-Programming | /5-DS-Tree/LL.py | 14,608 | 3.984375 | 4 | from TREE import TreeNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
class DLLNode(object):
def __init__(self, item):
self.val = item
self.next = None
self.prev = None
# Definition for a Node.
class RandomListNode:
def __init__(self, val, next=None, random=None):
self.val = val
self.next = next
self.random = random
"""
LL Tricks
1. Always check Current.next for condition, you have to mostly stop one node (current) before to operate upon
2. Where you can't check Current.next for condition, maintain prev
3. Head ?? validation
"""
class LinkedList:
def __init__(self, item=0):
self.head = ListNode(item)
pass
def insert(self, item):
newNode = ListNode(item)
if self.head is None:
# 1st Node, Make it head
self.head = newNode
# Otherwise find end of list
current = self.head
while current.next is not None:
current = current.next
# We are at end of list, insert
self.insertNode_Util(current, newNode)
def insertNode_Util(self, current, newNode):
# Link changes
savedNext = current.next
current.next = newNode
newNode.next = savedNext
def insertAtPosition(self, item, position):
newNode = ListNode(item)
if position == 0:
self.head = newNode
# edge case: what happens if position is given more than what list contains
# Find the right pos to insert
current = self.head
i = 0
while i < position-1:
current = current.next
i += 1
# We are at pos, insert now
self.insertNode_Util(current, newNode)
def insertInSortedOrder(self, item):
newNode = ListNode(item)
# Head ??
if self.head.val > item:
self.insertNode_Util(self.head, newNode)
# Search for right pos
current = self.head
while current.next.val < item:
current = current.next
self.insertNode_Util(current, newNode)
def remove(self, item):
# Head ??
if self.head.val == item:
newHeadRef = self.head.next
del self.head
self.head = newHeadRef
return
self.remove_node(ListNode(item))
def remove_node(self, node):
if isinstance(type(node), Node):
return -1
# Head with no next? Delete head with next is None!
if self.head == node and self.head.next is None:
del self.head
current = self.head
prev = self.head
while current is not None and current.val != node.val:
current = current.next
prev = current
# Tail ?
if current is None:
# Not found
return -1
elif current.next is None:
# Tail node to be deleted
prev.val = current.val
prev.next = current.next
else:
# Regular node
current.val = current.next.val
current.next = current.next.next
def reverse(self):
prev = None
current = self.head
while current is not None:
savedNext = current.next
# Reverse the link
current.next = prev
# Next iteration
prev = current
current = savedNext
self.head = prev
def detect_loop(self):
slow = self.head
fast = self.head
while fast is not None and fast.next is not None:
fast = fast.next
if fast.next is not None:
fast = fast.next
slow = slow.next
if fast == slow:
break
# fast & slow are pointing at k nodes away from LoopNode
# Head is pointing at k nodes away from LoopNode
current = self.head
while current is not slow:
current = current.next
slow = slow.next
return current
def size(self, head=None):
count = 0
if head is None:
current = self.head
else:
current = head
while current is not None:
count += 1
current = current.next
return count
def size_recur_util(self, node):
if node is None:
return 0
return 1 + self.size_recur_util(node.next)
def size_recur(self):
return self.size_recur_util(self.head)
def printLL(self):
current = self.head
while current:
print current.val,
current = current.next
def printLLReversed_Util(self, node):
if node is None:
return
self.printLLReversed_Util(node.next)
print node.val
def printLLReversed(self):
return self.printLLReversed_Util(self.head)
def swap(self, item, new_item):
current = self.head
while current.val != item:
if current.next is None:
return False
current = current.next
# We are at node to swap
current.val = new_item
def middle(self):
slow = self.head
fast = self.head
while fast is not None and fast.next is not None:
fast = fast.next
if fast.next is not None:
fast = fast.next
slow = slow.next
return slow
def get_nth_from_last(self, n):
slow = self.head
fast = self.head
while n > 0 and fast is not None:
fast = fast.next
n -= 1
while fast is not None:
fast = fast.next
slow = slow.next
return slow.val if fast is not None else -1
def isPalindrom_Util(self, Left, Right):
if Right is None:
return True, Left
# Left will be traversing reverse from back
# Right will be traversing reverse from back
isp, Left = self.isPalindrom_Util(Left, Right.next)
if isp is False:
return False, Left
# Compare values of Right <-- with Left --->
isp1 = (Left.val == Right.val)
# Move Left
Left = Left.next
return isp1, Left
def isPalindrom(self):
Left = self.head
Right = self.head
return self.isPalindrom_Util(Left, Right)
"""
ADD 2 numbers represented as reversed LinkedList
https://leetcode.com/problems/add-two-numbers/description/
"""
class Solution(object):
def addTwoNumbersRecur(self, l1, l2, carry):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Base Case
# Base Case
if l1 is None and l2 is None:
if carry:
return ListNode(carry)
else:
return None
#1) Constraint for root
sumVal = carry
if l1 is not None:
sumVal += l1.val
if l2 is not None:
sumVal += l2.val
newNode = ListNode(sumVal % 10)
# 2) Same constraint for next Node (Recurssion)
newNode.next = self.addTwoNumbersRecur(l1.next if l1 is not None else None,
l2.next if l2 is not None else None,
sumVal//10)
return newNode
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummyHeadNode = ListNode(0)
current = dummyHeadNode
sumVal, carry = 0, 0
# Iterate through both lists
while l1 or l2:
sumVal = 0
if l1:
sumVal += l1.val
if l2:
sumVal += l2.val
if carry > 0:
sumVal += carry
carry = sumVal // 10
# Create a result node
current.next = ListNode(sumVal % 10)
current = current.next
# Next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
# Edge case: Remaining carry!
if carry > 0:
current.next = ListNode(carry)
return dummyHeadNode.next
def removeNthFromEnd(self, head, n):
dummyHead = ListNode(0, head)
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
slow = fast = dummyHead
for i in xrange(n):
fast = fast.next
while fast.next:
slow = slow.next
fast = fast.next
# Slow is pointing to pre location of node to be deleted
slow.next = slow.next.next
return dummyHead.next
def swapPairs(self, head):
dummyHead = ListNode(0, head)
pre,pre.next = dummyHead, head
while pre.next and pre.next.next:
a = pre.next
b = a.next
# Swap a, b links
pre.next = b
a.next = b.next
b.next = a
# Next iteration
pre = a
return dummyHead.next
def findSize(self, head):
ptr = head
c = 0
while ptr:
ptr = ptr.next
c += 1
return c
def sortedListToBST(self, head):
size = self.findSize(head)
def convertRecur(l, h):
global head
# Base condition
if l > h:
return None
# if l == h:
# # Single node, let's make a TreeNode out of this
# node = TreeNode(l)
# return node
# Traversal, BST pre-order = sorted sequence, so building BST with pre-order from sorted LL
mid = (l + h) // 2
# 1) L
left = convertRecur(l, mid - 1)
# 2) C
node = TreeNode(head.val)
node.left = left # We are in LCR traversal, so earlier built node is Left of node built Now!
head = head.next # this node(head) is built in BST, keep traversing original LL
# 3) R
node.right = convertRecur(mid + 1, h)
return node
return convertRecur(0, size - 1)
def copyRandomList(self, head):
old = head
# Dict to map {oldNodeAddress -> sameNewNodeAddress}
d = {}
while old:
# Creating new Node and a dict[OldNodeAddress] = newNodeAddress
d[old] = RandomListNode(old.val, None, None)
old = old.next
# Edge case: Add last node Null!
d[None] = None
print(d)
old = head
while old:
# d[old] will give exact new node
d[old].val = old.val
d[old].next = d[old.next]
d[old].random = d[old.random]i3
old = old.next
return d[head]
def addLL_Util_Reverse(node1, node2):
# Base case
# Return node values when both lists are empty
if node1 is None and node2 is None:
return None, 0
headRef, carry = addLL_Util_Reverse(node1.next, node2.next)
sum_nodes = carry + node1.val + node2.val
newNode = ListNode(sum_nodes % 10)
carry = sum_nodes // 10
if headRef is None:
headRef = newNode
else:
newNode.next = headRef
headRef = newNode
return headRef, carry
def intersection(L1, L2):
m = L1.size()
n = L2.size()
if m > n:
fast = L1
slow = L2
else:
fast = L2
slow = L1
# Now SKIP abs(len(1)-len(2) nodes from bigger list
for i in xrange(abs(m-n)):
fast = fast.next
# Now both list are same nodes away from INTERSECTION
while slow != fast:
fast = fast.next
slow = slow.next
return slow
def addLL(L1, L2):
carry = 0
return addLL_Util(L1, L2, carry)
def addLLReversed(L1, L2, sizeL1, sizeL2):
skipNodes = abs(sizeL1 - sizeL2)
while skipNodes > 0:
L1 = L1.next
skipNodes -= 1
HeadRef, carry = addLL_Util_Reverse(L1, L2)
return HeadRef
"""
Reverses a LL and returns Head of new LL
"""
def reverse(head):
prev = None
current = head
while current is not None:
savedNext = current.next
# Reverse the link
current.next = prev
# Next iteration
prev = current
current = savedNext
return prev
def printLL(head):
while head:
print head.val,
head = head.next
def main():
# myLL = LinkedList(1)
# myLL.insert(2)
# myLL.insert(3)
# myLL.insert(4)
# myLL.insert(5)
#
# reversed_head = reverse(myLL.head)
# while reversed_head is not None:
# print reversed_head.val
# reversed_head = reversed_head.next
print "Adding 2 numbers represented by LL...."
L1 = LinkedList(3)
L1.insert(1)
L1.insert(5)
L1.insert(7)
L2 = LinkedList(5)
L2.insert(9)
L2.insert(2)
s = Solution()
result = s.addTwoNumbers(L1.head, L2.head)
printLL(result)
while result is not None:
print result.val
result = result.next
result = s.removeNthFromEnd(L1.head, 2)
printLL(result)
"""
myLL = LinkedList('k')
myLL.insert('a')
myLL.insert('y')
myLL.insert('a')
myLL.insert('k')
# myLL.printLL()
print"\nChecking palindrome"
isp, Left = myLL.isPalindrom()
print isp
myLL = None
myLL = LinkedList(1)
myLL.printLL()
print "\nChecking insertInSortedOrder"
myLL.insertInSortedOrder(4)
myLL.printLL()
print "\nChecking insertAtPosition"
myLL.insertAtPosition(5, 3)
myLL.printLL()
print "\nChecking remove"
myLL.remove(2)
myLL.printLL()
print "\nChecking remove HEAD"
myLL.remove(1)
myLL.printLL()
print "\nChecking remove NOT FOUND"
myLL.remove(15)
myLL.printLL()
print "\nChecking remove NOT FOUND"
myLL.remove_node(ListNode(1))
myLL.printLL()
print "\nChecking remove"
myLL.remove_node(ListNode(7))
myLL.printLL()
print "\nreverse"
myLL.reverse()
myLL.printLL()
print "\nsize"
print myLL.size()
print "\nsize recur"
print myLL.size_recur()
print "\nreverse print"
print myLL.printLLReversed()
print "\nswap"
myLL.swap(11, 5)
myLL.printLL()
print "\nmiddle"
print myLL.middle().val
print "get nth from last"
print myLL.get_nth_from_last(3)
"""
if __name__ == "__main__":
main()
|
b766eddd7865f3735da5cc59e44c22225c8cf644 | jigarshah2811/Python-Programming | /Algo-DP/Longest_SubString_Without_Repeat.py | 1,555 | 4.03125 | 4 | """
Longest Substring Without Repeating Characters
https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/779/
https://www.geeksforgeeks.org/length-of-the-longest-substring-without-repeating-characters/
"""
def longestUniqueSubStr(str):
# HashMap {Char --> IndexLastSeen}
d = dict()
cur_len = 0 # To store the length of current substring
max_len = 0 # To store the result
# Start from the second character. First character is already
# processed (cur_len and max_len are initialized as 1, and
# visited[str[0]] is set
for i in range(len(str)):
# Char not seen or seen but not part of Current SubString
# If the currentt character is not present in the already
# processed substring or it is not part of the current NRCS,
# then do cur_len++
if str[i] not in d or i - cur_len > d[str[i]]:
cur_len += 1
else:
# Char seen in current Substring
# Also, when we are changing the NRCS, we should also
# check whether length of the previous NRCS was greater
# than max_len or not.
max_len = max(cur_len, max_len)
cur_len = i - d[str[i]]
# update the index of current character
d[str[i]] = i
# Compare the length of last NRCS with max_len and update
# max_len if needed
max_len = max(cur_len, max_len)
return max_len
print(longestUniqueSubStr("GEEKSFORGEEKS"))
print(longestUniqueSubStr("LEETCODE")) |
56a53a69ddeb8f267a9ff221c3e91a7433af985a | jigarshah2811/Python-Programming | /8-DS-Design/HashMap.py | 2,321 | 3.859375 | 4 | """
https://leetcode.com/problems/design-hashmap/discuss/185347/Hash-with-Chaining-Python
"""
class ListNode:
def __init__(self, key, val):
self.pair = (key, val)
self.next = None
class HashMap:
def __init__(self):
"""
Initialize DS here: A HashMap is List of 1000 nodes, Each Index in List can have chain (ListNodes)
"""
self.capacity = 1000
self.m = [None] * self.capacity
def put(self, key, value):
"""
Key will always be in range (0...1million) and value can be any int
:param key: int
:param value: int
:return: void
"""
index = key % self.capacity
if self.m[index] is None: # No pair(key,val) at this index yet, this is the 1st node
self.m[index] = ListNode(key, value) # NEW
else: # Already pair(key, val) at this index, Use Chaining to see if pair exists
cur = self.m[index]
while cur.__next__ is not None:
if cur.pair[0] == key: # this key exists
cur.pair = (key, value) # UPDATE val
return
cur = cur.__next__
# key does not exists in chain. Add
cur.next = ListNode(key, value) # NEW: Collision
def get(self, key):
"""
Key will be at Index OR in case of collision of index, key will be part of chaining list.
:param key: int
:return: value int
"""
index = key % self.capacity
cur = self.m[index]
while cur:
if cur.pair[0] == key: # Found key
return cur.pair[1]
else:
cur = cur.__next__
# key not found
return -1
def remove(self, key):
return -1
def printMap(self):
print((self.m))
myHashMap = HashMap()
myHashMap.put(1, 1);
myHashMap.put(2, 2);
print(myHashMap.get(1)); # returns 1
print(myHashMap.get(3)); # returns -1 (not found)
myHashMap.put(2, 1); # update the existing value
print(myHashMap.get(2)); # returns 1
myHashMap.remove(2); # remove the mapping for 2
print(myHashMap.get(2)); # returns -1 (not found)
myHashMap.printMap()
|
4a5fc85b209138408683797ef784cbd59dd978fe | jigarshah2811/Python-Programming | /LL_MergeSort.py | 2,556 | 4.625 | 5 | # Python3 program merge two sorted linked
# in third linked list using recursive.
# Node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Constructor to initialize the node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Method to print linked list
def printList(self):
temp = self.head
while temp:
print temp.data
temp = temp.next
# Function to add of node at the end.
def append(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def splitList(head):
slow = fast = head
while fast:
fast = fast.next
if fast is not None:
fast = fast.next
slow = slow.next
# Now, Fast is at End and Slow is at Middle
A = head
B = slow
slow.next = None
return A, B
def mergeSort(head):
if head is None or head.next is None:
return head
# Split unsorted list into A and B
A, B = splitList(head)
# Indivudally sort A and B
mergeSort(A)
mergeSort(B)
# Now we have 2 sorted lists, A & B, merge them
return mergeLists(A, B)
# Function to merge two sorted linked list.
def mergeLists(A, B):
tail = None
if A is None:
return B
if B is None:
return A
if A.data < B.data:
tail = A
tail.next = mergeLists(A.next, B)
else:
tail = B
tail.next = mergeLists(A, B.next)
return tail
# Driver Function
if __name__ == '__main__':
# Create linked list :
# 10->20->30->40->50
list1 = LinkedList()
list1.append(3)
list1.append(5)
list1.append(7)
# Create linked list 2 :
# 5->15->18->35->60
list2 = LinkedList()
list2.append(1)
list2.append(2)
list2.append(4)
list2.append(6)
# Create linked list 3
list3 = LinkedList()
# Merging linked list 1 and linked list 2
# in linked list 3
list3.head = mergeLists(list1.head, list2.head)
print(" Merged Linked List is : ")
list3.printList()
print "Testing MergeSort"
# Create linked list 4 :
# 5->2->1->4->3
list3 = LinkedList()
list3.append(5)
list3.append(2)
list3.append(1)
list3.append(4)
list3.append(3)
sortedList = mergeSort(list3.head)
sortedList.printList() |
34860ea98e636d64ada5e34e3d025dcc898a23b1 | jigarshah2811/Python-Programming | /Algo-Greedy/timePlanner.py | 1,814 | 3.578125 | 4 | class Solution(object):
def planner(self, slotsA, slotsB, targetDuration):
res = []
a, b = 0, 0
start, end = 0, 1
while a < len(slotsA) and b < len(slotsB):
A = slotsA[a]
B = slotsB[b]
if self.overlaps(A, B):
print(("Overlapping found: SlotA: {0}, SlotB: {1}".format(A, B)))
res = self.findDuration(A, B, targetDuration)
if len(res) != 0:
return res
# Move to find next overlap
if B[start] <= A[start]:
b += 1
else:
a += 1
return res
def overlaps(self, A, B):
start, end = 0, 1
print(("Checking overlap: {0} and {1}".format(A, B)))
# If any point B[start] or B[end] is in middle of A[start] --> A[end] then it's overlapping
if A[start] <= B[start] <= A[end] or A[start] <= B[end] <= A[end]:
return True
return False
def findDuration(self, A, B, targetDuration):
start, end = 0, 1
print(("Checking duration {2} in overlap: {0} and {1}".format(A, B, targetDuration)))
if B[end] >= A[start]:
curDur = B[end] - A[start]
if curDur >= targetDuration:
# Bingo !
return [A[start], A[start]+targetDuration]
elif A[end] >= B[start]:
curDur = A[end] - B[start]
if curDur >= targetDuration:
# Bingo
return [B[start], B[start]+targetDuration]
return []
s = Solution()
slotsA = [[10, 50], [60, 120], [140, 210]]
slotsB = [[0, 15], [60, 70]]
print(s.planner(slotsA, slotsB, 8))
slotsA = [[10, 50], [60, 120], [140, 210]]
slotsB = [[0, 15], [60, 70]]
print(s.planner(slotsA, slotsB, 12))
|
ea993d762ecccbaf00c838eecd5530604263057e | jigarshah2811/Python-Programming | /Algo-Backtracking-Recurssion/5_GraphColor.py | 1,598 | 3.90625 | 4 | class Solution:
def graphColor(self, graph, V, numColors):
def isSafe(curV, c):
# Check if this color is not applied to any connection of V.
for i in range(V):
print(("Checking vertex: [0]".format(curV)))
if graph[curV][i] and c == color[i]: # There is edge between curV and i, and that neighbour has same color
return False
return True
def backtrack(curV):
# 1) Base case: If all vertex are colored, then we found solution
if curV == V:
return True
# 2) Breath ---> Possible moves are to select any from available colors
for c in range(1, numColors+1):
# 3) Check if it's safe to apply this color to vertex
if isSafe(curV, c):
# 4) Apply this color
print(("vertex:[0] color:[1]".format(curV, c)))
color[curV] = c
# 5) Recursively apply available colors to next vertex
if backtrack(curV+1):
return True
# 6) Backtrack: If we can't find solution recursively for all vertexes
print(("Backtrack vertex:[0] color:[1]".format(curV, c)))
color[curV] = 0
return False
color = [0] * V
backtrack(0)
return color
s = Solution()
graph = [[0, 1, 1, 1],
[1, 0, 1, 0],
[1, 1, 0, 1],
[1, 0, 1, 0]]
print((s.graphColor(graph=graph, V=4, numColors=3)))
|
483184733d370d27c5b02dbaf2d578cac47f8701 | jigarshah2811/Python-Programming | /7-DS-Heap/TopKFreq.py | 1,699 | 3.78125 | 4 | from typing import List
import collections
import heapq
class Solution:
""" DS: Freq Map Algorithm: Bucket Sort
FreqMap {num: times}
Bucket {times: [num1, num2, num3]}
"""
def topKFrequent(self, nums: List[str], k: int) -> List[str]:
# Create Freq Map # {num: times}
freqMap = collections.defaultdict(int)
for num in nums:
freqMap[num] += 1
print(freqMap)
# Create FreqBucketMap # {times: [num1, num2, ...]}
freqBucketMap = collections.defaultdict(list)
for num, times in freqMap.items():
freqBucketMap[times].append(num)
print(freqBucketMap)
# Now freqMap buckets stores all freq, we are interested in high to low times
topFreqList = []
for times in range(len(nums), -1, -1): # <----- Descending order of "frequency"
listOfWords = freqBucketMap[times]
# Same freq words should be in sorted order!
sortedWords = sorted(listOfWords)
topFreqList.extend(sortedWords)
print(topFreqList)
return topFreqList[:k]
def topKWords(words, k=1):
freqMap = collections.defaultdict(int)
maxHeap = []
res = []
for word in words:
freqMap[word] += 1
for word, freq in freqMap.items():
heapq.heappush(maxHeap, (-freq, word))
for i in range(k):
(freq, word) = heapq.heappop(maxHeap)
res.append(word)
return res
words = ["i","love","leetcode","i","love","coding"]
res = topKWords(words, k=2)
print(res)
words = ["the","day","is","sunny","the","the","the","sunny","is","is"]
res = topKWords(words, k=4)
print(res) |
f9e0bf6998f5ee9065ca8b27e56baa95907cb486 | jigarshah2811/Python-Programming | /Advance-OOP-Threading/OOP/ClassObject.py | 1,422 | 4.53125 | 5 | """
This is valid, self takes up the arg!
"""
# class Robot:
# def introduce(self):
# print("My name is {}".format(self.name))
#
# r1 = Robot()
# r1.name = "Krups"
# #r1.namee = "Krups" # Error: Because now self.name wouldn't be defined!
# r1.introduce()
#
# r2 = Robot()
# r2.name = "Pasi"
# r2.introduce()
""" OOP
Class constructor
"""
class Robot:
def __init__(self, name, color, weight):
self.name, self.color, self.weight = name, color, weight
def introduce(self):
print("My name: {}, color: {}, weight: {}".format(self.name, self.color, self.weight))
r1 = Robot(name="Google", color="Pink", weight=10)
r2 = Robot(name="Alexa", color="Purple", weight=60)
r1.introduce()
r2.introduce()
class Person:
def __init__(self, name, personality, isSitting=True):
self.name, self.personality, self.isSitting = name, personality, isSitting
def introduce(self):
print("Person name: {}, personality: {}, isSitting: {}".format(self.name, self.personality, self.isSitting))
krups = Person(name="Krups", personality="Talkative", isSitting=False)
pasi = Person(name="pasi", personality="Singing", isSitting=True)
""" OOP: Relationship between objects
"""
krups.robot_owned = r1 # A class member can be defined "Run-Time"!. This will be self.robot_owned in "krups" object
pasi.robot_owned = r2
krups.robot_owned.introduce()
pasi.robot_owned.introduce()
|
082fb020db06e9d58f4ff9d06abe8fd3db745131 | jigarshah2811/Python-Programming | /Algo-Backtracking-Recurssion/Recur_BackTracking_WordSearch_Matrix.py | 1,733 | 3.734375 | 4 | class Solution(object):
def exist(self, board, word):
###### BACKTRACKING ##########
# 1) Breath -->: Go through all cells in matrix
for i in range(len(board)):
for j in range(len(board[0])):
# 2) isSafe --> Constraint: Word char match
# 3) Depth --->
if self.DFS(board, word, i, j):
# All word char matched from this cell
return True
return False
def DFS(self, board, word, i, j):
# Base case
if len(word) == 0:
# Everything from the word matched
return True
# 2) isSafe --> # OOB
if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]):
# print "OOB {0}{1}".format(i,j)
return False
# Constraint: word char should match to this cell
if board[i][j] != word[0]:
# print "Don't match {0}{1}".format(i,j)
return False
# Most Imp DFS thing: Mark the cell visited to prevent visiting again!!!
# 4) BackTracking
# 4.1) Take a move
tmp = board[i][j]
board[i][j] = "#"
# 4.2) See if recursively lead to solution
res = self.DFS(board, word[1:], i, j + 1) or \
self.DFS(board, word[1:], i, j - 1) or \
self.DFS(board, word[1:], i - 1, j) or \
self.DFS(board, word[1:], i + 1, j)
# 4.3) Backtrack
board[i][j] = tmp
return res
board =[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
s = Solution()
print(s.exist(board, "ABCCED"))
print(s.exist(board, "SEE"))
print(s.exist(board, "ABCB"))
board = [["a"]]
print(s.exist(board, "a")) |
30947d19e31e5d58137168d179d797d3f9c2a333 | jigarshah2811/Python-Programming | /3-DS-Stack-Queue/IncreasingStack-LargestAreaRectangle.py | 1,666 | 3.90625 | 4 | def largestRect(hist):
stack = list()
maxArea = 0
# Go through the hist once
i = 0
while i < len(hist):
if (not stack) or (hist[i] >= hist[stack[-1]]):
# Increasing sequence so keep adding indexes on stack
stack.append(i)
print(("Push index: {0}, currentEle: {1}, stackEle: {2}".format(i, hist[i], hist[stack[-1]])))
i += 1
else:
top_of_stack = stack.pop()
# Calc area
#width = i - top_of_stack # MOST TRICKY to find the width
width = abs(i - stack[-1] - 1) if stack else i
height = hist[top_of_stack]
area = height * width
maxArea = max(maxArea, area)
print(("Pop index: {0}, currentEle: {1}, stackEle: {2} MaxArea: {3}".format(top_of_stack, hist[i], hist[top_of_stack], maxArea)))
# Remaining elements on stack
print("Remaining...")
while stack:
top_of_stack = stack.pop()
# Calc area
width = abs(i - stack[-1] - 1) if stack else i
height = hist[top_of_stack]
area = height * width
maxArea = max(maxArea, area)
print(("Pop i: {0}, stackEle: {1}, MaxArea: {2}".format(top_of_stack, hist[top_of_stack], maxArea)))
return maxArea
hist = [2, 3, 4, 5, 3, 3, 1]
#print ("Maximum rectangle area in histogram is: ", largestRect(hist))
hist = [2, 1, 2]
#print ("Maximum rectangle area in histogram is: ", largestRect(hist))
hist = [5,4,1,2]
#print ("Maximum rectangle area in histogram is: ", largestRect(hist))
hist = [4,2,0,3,2,5]
print(("Maximum rectangle area in histogram is: ", largestRect(hist))) |
f8290f38eb41af185b5ae229ea1fe60c9b887fc5 | jigarshah2811/Python-Programming | /Pattern_BitManipulation_Sets/Bit_Manipulation.py | 1,578 | 3.578125 | 4 | class Solution(object):
def countBits(self, value):
count = 0
while value != 0:
if value & 1:
count = count + 1
value = value >> 1
return count
def setBit(self, value, bitNum):
value = value | (1 << bitNum)
return value
def resetBit(self, value, bitNum):
value = value & ~(1 << bitNum)
return value
def flipBit(self, value, bitNum):
if value & (1 << bitNum):
result = self.resetBit(value, bitNum)
else:
result = self.setBit(value, bitNum)
return result
def findOddOccuringNumber(self, array):
result = 0
for num in array:
result = result ^ num
return result
def find2OddOccuringNumber(self, array):
result = 0
for num in array:
result = result ^ num
return result
def powerSet(self, array):
powerSetSize = pow(2, len(array))
print(powerSetSize)
powerSet = []
for counter in range(powerSetSize):
subset = []
for bitPosition in range(len(array)):
if counter & (1 << bitPosition):
subset.append(array[bitPosition])
powerSet.append(subset)
return powerSet
s = Solution()
print(s.countBits(5))
print(s.countBits(7))
print(s.countBits(8))
print(s.flipBit(5, 1))
print(s.findOddOccuringNumber([12, 12, 14, 90, 14, 14, 14]))
"""
https://www.geeksforgeeks.org/?p=588
"""
QueSet = ['a', 'b', 'c']
print(s.powerSet(QueSet)) |
da82f9c03c227499e5f72a758513c8e71a1f43cd | jigarshah2811/Python-Programming | /Algo-Sorting-Searching/Array_BinarySearch.py | 5,031 | 3.875 | 4 | import collections
import sys
"""
Regular Binday Search
"""
class Solution(object):
def binsearch(self, nums, target):
low, high = 0, len(nums)-1
while low < high:
mid = (low + high) >> 1
if target == nums[mid]: # Check if target is HERE
return mid # FOUND Target, Bingo
elif target > nums[mid]: # Target is HIGHER?
low = mid + 1 # Search on R ----->
else: # Target is LOWER?
high = mid - 1 # Search on <------- L
return -1
def binsearch_nolen(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = sys.maxsize
while low <= high:
mid = (low + (high - low)) >> 1
if target == nums[mid]:
return mid
elif target > nums[mid]:
# Target must be on Right side
low = mid + 1
else:
# Target must be on left side
high = mid
return -1
"""Tweaked Binday Search:
If multiple values are same as target,
return the lowest index instead of 1st hit in binary search
"""
def BinarySearch_LowestIndex(nums, target):
low, high = 0, len(nums)-1
result = -1 # Not found by default
while low < high:
mid = (low + high) >> 1
if target == nums[mid]:
# Trick: This can be one of the dup, we still want to find the first occurance
result = mid
high = mid - 1 # Keep searching on <------ L side
elif target > nums[mid]: # Target is Higher, must be on R ---> side
low = mid + 1
else: # Target is Lower, must be on <------ L side
high = mid - 1
return result
""" Follow Up: Can you write BS for Last Occurance? """
"""
https://leetcode.com/problems/search-in-rotated-sorted-array
Search in Rotated Sorted Array
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
"""
def BinarySearch_SortedRotatedArray(nums, target):
low = 0
high = len(nums)-1
while low <= high:
mid = (low + high) >> 1
if nums[mid] == target:
return mid
if nums[low] <= nums[mid]:
# LEFT half is Sorted. Perform regular ops
if nums[low] <= target <= nums[mid]:
high = mid - 1 # <----- L Search Left Half
else:
low = mid + 1 # ----> R Search Right Half
else:
# RIGHT half is sorted. Perform regular ops but inverted
if nums[mid] <= target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return -1
def main():
"""
a = [1, 3, 5, 6, 8, 10, 10, 10, 12]
target = 10
result = BinarySearch(a, target)
if result == -1:
print "Value {0} Not found".format(target)
else:
print "Found {0} at location Index {1}".format(target, result)
result = BinarySearch_LowestIndex(a, target)
if result == -1:
print "Value {0} Not found".format(target)
else:
print "Found {0} at location Index {1}".format(target, result)
result = BinarySearch_HighestIndex(a, target)
if result == -1:
print "Value {0} Not found".format(target)
else:
print "Found {0} at location Index {1}".format(target, result)
sumToFind = 14
low, high = FindPairWithSum(a, sumToFind, 0, len(a)-1)
if low == -1 or high == -1:
print "Sum {0} Not found".format(sumToFind)
else:
print "Sum {0} found at pair of index {1} and {2}".format(sumToFind, low, high)
sumToFind = 16
for i in xrange(0, len(a)-1):
low, high = FindPairWithSum(a, sumToFind-i, i, len(a)-1)
if low != -1 and high != -1:
print "Sum {0} found at index {1} {2}".format(sumToFind, low, high)
index = BinarySearch_SortedRotatedArray([4, 5, 6, 7, 0, 1, 2, 3], 0)
print "Index found: {0}".format(index)
index = BinarySearch_SortedRotatedArray([4, 5, 6, 7, 0, 1, 2, 3], 7)
print "Index found: {0}".format(index)
index = BinarySearch_SortedRotatedArray([5 ,1, 3], 5)
print "Index found: {0}".format(index)
index = BinarySearch_SortedRotatedArray([5, 1, 3], 1)
print "Index found: {0}".format(index)
index = BinarySearch_SortedRotatedArray([5, 1, 3], 3)
print "Index found: {0}".format(index)
index = BinarySearch_SortedRotatedArray([5, 1, 3], 0)
print "Index found: {0}".format(index)
"""
if __name__ == "__main__":
s = Solution()
nums = [-1,0,3,5,9,12]
print(("Find 9, index: {0}".format(s.binsearch(nums, 9))))
nums = [5]
print(("Find 5, index: {0}".format(s.binsearch(nums, 5))))
|
aef347e759278a90472b16dc638a64282aabb574 | jigarshah2811/Python-Programming | /Stack_LargestRectangleInHistogram.py | 3,616 | 3.640625 | 4 | from STACK import Stack
"""
http://www.geeksforgeeks.org/largest-rectangle-under-histogram/
"""
def LargestRectangleInHistogram(hist):
s = Stack()
i = 0
max_area = 0
# Scan through Histogram
while i < len(hist):
# Increasing ---> Current Hist > Prev Hist
if s.isEmpty() or hist[i] >= hist[s.peek()]:
s.push(i)
# Decreased! ---> Current Hist < Prev Hist (Hisab lagavi do)
else:
# Pop hist till Decreasing stops
while not s.isEmpty() and hist[s.peek()] > hist[i]:
L = s.pop()
height = hist[L]
if s.isEmpty():
area = height * i
else:
area = height * (i - s.peek() - 1)
max_area = max(max_area, area)
s.push(i)
i += 1
while not s.isEmpty():
L = s.pop()
height = hist[L]
area = height * (i - L - 1)
max_area = max(max_area, area)
return max_area
"""
Optimized version
"""
def LargestRectangleInHistogram_optimized(hist):
s = Stack()
max_area = 0
i = 0
# Scan through Histogram
while i < len(hist):
# Increasing ---> Current Hist > Prev Hist
if s.isEmpty() or hist[i] >= hist[s.peek()]:
s.push(i)
i += 1
# Decreased! ---> Current Hist < Prev Hist (Hisab lagavi do)
else:
# Pop hist till Decreasing stops
L = s.pop()
# Calculate area
if s.isEmpty():
current_area = hist[L] * i
else:
current_area = hist[L] * (i - s.peek() - 1)
# Hisab for max area
max_area = max(max_area, current_area)
# Consider all remaining histogram
while not s.isEmpty():
L = s.pop()
# Calculate area
if s.isEmpty():
current_area = hist[L] * i
else:
current_area = hist[L] * (i - s.peek() - 1)
# Hisab for max area
max_area = max(max_area, current_area)
return max_area
hist = [6, 2, 5, 4, 5, 1, 6]
print LargestRectangleInHistogram(hist)
print LargestRectangleInHistogram_optimized(hist)
hist = [2, 1, 5, 6, 2, 3]
print LargestRectangleInHistogram(hist)
print LargestRectangleInHistogram_optimized(hist)
"""
Nearest Smaller Element
Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i.
More formally,
G[i] for an element A[i] = an element A[j] such that
j is maximum possible AND
j < i AND
A[j] < A[i]
Elements for which no smaller element exist, consider next smaller element as -1.
Example:
arr = [4, 5, 2, 10]
result = [-1, 4, -1, 2]
arr = [3, 2, 1]
result = [-1, -1, -1]
"""
def Nearest_Smallest(arr):
result = [-1] * len(arr)
s = Stack()
s.push(-1)
# Scan through entire Array
for index in xrange(len(arr)):
# Nearest value is lesser ? Choose it
if arr[index] > s.peek():
result[index] = s.peek()
else:
# Go till the prev nearest value that's lesser? Choose it
while arr[index] > s.peek():
s.pop()
result[index] = s.peek()
# Get ready for next iteration
s.push(arr[index])
return result
arr = [4, 5, 2, 10]
print Nearest_Smallest(arr)
arr = [4, 5, 6, 1, 2]
print Nearest_Smallest(arr)
arr = [4, 2, 10, 6, 5]
print Nearest_Smallest(arr)
arr = [3, 2, 1]
print Nearest_Smallest(arr)
arr = [1, 3, 0, 2, 5]
print Nearest_Smallest(arr)
|
67c3f537284076c7a52854c5d1dc7a58d99d908d | jigarshah2811/Python-Programming | /Algo-DP/DP_LCS.py | 607 | 3.546875 | 4 | """
http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/
"""
def LCS(str1, str2):
m = len(str1)
n = len(str2)
L = [[0]*50]*50
for i in range(len(str1)+1):
for j in range(len(str2)+1):
if i == 0 or j == 0:
L[i][j] = 0
elif str1[i-1] == str2[j-1]: # MATCH
L[i][j] = 1 + L[i-1][j-1] # = 1 + diagonal
else:
L[i][j] = max(L[i-1][j], L[i][j-1]) # No Match = max match from prior row or col
print(L[m][n])
str1 = "ABCDGH"
str2 = "AEDFHR"
LCS(str1, str2) |
8fe0bcd0540ab6b12b3db8f6fa0619f218f0d89b | jigarshah2811/Python-Programming | /Hash_Last2ShortestStrings.py | 670 | 3.828125 | 4 | k = 3
mydict = {}
def insert(str):
global k
global mydict
try:
mydict[len(str)] = mydict[len(str)].append(str)
except KeyError:
mydict[len(str)] = [str]
sortedKeys = sorted(mydict.iterkeys())
# mydict = sorted(mydict, key=lambda item: item[0], reverse=True)
inserted = 0
for key in sortedKeys:
if inserted > k:
del mydict[key]
else:
inserted += 1
continue
def lookup(k):
global mydict
for key, val in mydict.items():
print val
insert("That is")
insert("nothing")
insert("Compare to")
insert("What I have gone through")
insert("This")
lookup(3)
|
923c91352c1941344adada6d21014b06ce7add3d | jigarshah2811/Python-Programming | /8-DS-Design/DS_bloom_filter.py | 960 | 3.71875 | 4 | """
Space efficient probablistic DS for membership testing
Google uses it before Map Reduce
"""
from random import seed, sample
class BloomFilter(object):
def __init__(self, iterable=(), population=56, probes=6):
self.population = range(population)
self.probes = probes
self.data = set()
for name in iterable:
self.add(name)
def add(self, name):
seed(name)
lucky = sample(self.population, self.probes)
print(lucky)
self.data.update(lucky)
def __contains__(self, name):
seed(name)
lucky = sample(self.population, self.probes)
return set(lucky).issubset(self.data)
#return set(lucky) <= self.data
if __name__ == "__main__":
names = 'raymond rachel matthew ramon gayle dennis sharon'
hettingers = BloomFilter(names, population=100, probes=10)
for name in names.split():
hettingers.add(name)
print('rachel' in hettingers)
print('Jigar' in hettingers)
|
2949f87f4092c51a398b8a3081bb45a42b010432 | jigarshah2811/Python-Programming | /Pattern-2-Pointers/2.MultiPassPattern-ProductExceptSelf.py | 2,519 | 3.734375 | 4 | from math import prod
from typing import List
"""
Pattern: Multi-Pass L -----> & <------- R
L = Prefix L Running Multiplier
R = Suffix R Running Multiplier
Result = Multiplier of (Prefix L * Suffix R)
Next Q: Trapping Rain Water!
"""
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
N = len(nums)
L, R, res = [1]*N, [1]*N, [1]*N
# L -----> Traverse front
# Left Product at i is: Prefix product of i-1 * previous num
for i in range(1, N):
L[i] = L[i-1] * nums[i-1]
# <---------R Traverse back
# Right Product at i is: Prefix product until i+1 * previous num
for i in range(N-2, -1, -1):
R[i] = R[i+1] * nums[i+1]
# L[i] has product of all numbers till i
# R[i] has product of all numbers till i
# Result is simply L[i] (prefix product of all L) * R[i] (prefix product of all R)
for i in range(N):
res[i] = L[i] * R[i]
return res
def productExceptSelfOptimized(self, nums: List[int]) -> List[int]:
"""
Optimized version O(1) space
L ---->
Result while R <-------
"""
N = len(nums)
res = [1]*N
# L -----> Traverse front
# Left Product at i is: Prefix product of i-1 * previous num
for i in range(1, N):
res[i] = res[i-1] * nums[i-1]
print(res)
# <---------R Traverse back
# Right Product at i is: Prefix product until i+1 * previous num
rMax = 1
for i in range(N-1, -1, -1):
# Result at i is: L prefix product till now (res[i]) * Right prefix product till now (rMax)
res[i] = res[i] * rMax
# Update max R prefix product to carry forward
rMax = rMax * nums[i]
print(res[i], rMax)
return res
def productExceptSum(nums):
N = len(nums)
# ----> L Prefix
L = [1] * N
for i in range(1, N):
L[i] = L[i-1] * nums[i-1]
print(f"Left: {L}")
# <---- R Prefix
RMul = 1
# Total
res = [1] * N
for i in range(N-1, -1, -1):
# Res here is the LeftPrefix * RightPrefix
res[i] = L[i] * RMul
# RightPrefix is now ThisNum*LastRightPrefix
RMul = nums[i] * RMul
return res
nums = [8, 10, 2]
print(productExceptSum(nums)) # [20, 16, 80]
nums = [2, 7, 3, 4]
print(productExceptSum(nums)) # [84, 24, 56, 42]
nums = [4, 5, 1, 8, 2]
print(productExceptSum(nums)) # [80, 64, 320, 40, 160]
|
6bbd0b28467b15d9d3d5103b41375d6c79999f6c | brunda4/Trees-1 | /solution41.py | 1,036 | 3.59375 | 4 | class Solution:
prev=None #initializing the global variabe prev to hold the previous node
def isValidBST(self, root: TreeNode) -> bool:
return self.inorder(root) #caling the inorder function for root
def inorder(self,root:TreeNode)->bool:
if root==None: # if the root is Null node return True
return True
if (self.inorder(root.left)==False): #if the inorder of left subtree s false return false
return False
if(self.prev!=None and self.prev.val>=root.val): # if the previous node is not empty and its value is greater than current node value
return False #return False
self.prev=root #update the previous node
return self.inorder(root.right) #return the boolean value after checking the right subtree |
b510a87a4c15901bfb22b5568623d78be1a35d6d | EFulmer/sorts_of_sorts | /merge_sort.py | 895 | 4.0625 | 4 | # Standard merge sort, done in Python as an exercise.
from math import floor
from random import shuffle
def merge_sort(ls):
if len(ls) <= 1:
return ls
# in smaller arrays, it'd be better to do insertion sort to reduce overhead
mid = int(floor(len(ls)/2))
left = merge_sort(ls[0:mid])
right = merge_sort(ls[mid:])
return merge(left, right)
def merge(a, b):
c = []
i = 0
j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i = i + 1
else:
c.append(b[j])
j = j + 1
if i < len(a):
c.extend(a[i:])
else:
c.extend(b[j:])
return c
def main():
print 'Test of merge sort:'
lst = [x for x in range(10)]
shuffle(lst)
print 'Input:', lst
lst = merge_sort(lst)
print 'Output:', lst
if __name__ == '__main__':
main()
|
28a8e6ee2b125056cfe0c3056d6e3a92ba5e4a65 | sabeeh99/Batch-2 | /fathima_ashref.py | 289 | 4.28125 | 4 | # FathimaAshref-2-HelloWorldAnimation
import time
def animation(word):
"""this function takes the input and displays it
character by character with a delay of 1 second"""
for i in word:
time.sleep(1)
print(i, end="")
animation("Hello World")
|
7fa5ac027e065348e292847aa7b03933fc57bef0 | Andriy-Hladkiy/ITEA_Python_Basic | /topic_1/task_4.py | 213 | 3.828125 | 4 | # Напишите программу, которая сортирует заданный список из чисел
list = ['topic_1', '23', '435', '143', 'topic_2', 'topic_1']
print(sorted(list, key = int))
|
56a57411d7f44b8a7c15b69fcbf11ac3001f3ab4 | hanucane/dojo | /Bootcamp/bootcamp-python/python_algorithm/lambda.py | 245 | 3.96875 | 4 | def map(list, function):
for i in range(len(list)):
list[i] = function(list[i])
return list
print( map([1,2,3,4], (lambda num: num*num) ))
print( map([1,2,3,4], (lambda num: num*3) ))
print( map([1,2,3,4], (lambda num: num%2) )) |
1fda8b3fd2d9f8aa385c9f365ae983fde0bc711a | hanucane/dojo | /Bootcamp/bootcamp-algorithms/linked-lists/SLists.py | 1,353 | 3.625 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class SList:
def __init__(self, value):
node = Node(value)
self.head = node
def printAllValues(self):
runner = self.head
while runner.next != None:
print(id(runner), runner.value, id(runner.next))
runner = runner.next
print(id(runner), runner.value, id(runner.next))
def addNode(self, value):
node = Node(value)
runner = self.head
while runner.next != None:
runner = runner.next
runner.next = node
def removeNode(self, value):
runner = self.head
prev = None
if runner != None:
if runner.value == value:
self.head = runner.next
runner = None
return
while runner != None:
if runner.value == value:
break
prev = runner
runner = runner.next
if runner == None:
return
prev.next = runner.next
runner = None
slist = SList(5)
slist.addNode(7)
slist.addNode(3)
slist.addNode(8)
slist.printAllValues()
slist.removeNode(7)
slist.removeNode(5)
slist.printAllValues()
slist.addNode(10)
slist.addNode(2)
slist.printAllValues() |
d2f96447565c188fcc5fb24a24254dc68a2f5b60 | hanucane/dojo | /Online_Academy/python-intro/datatypes.py | 763 | 4.3125 | 4 | # 4 basic data types
# print "hello world" # Strings
# print 4 - 3 # Integers
# print True, False # Booleans
# print 4.2 # Floats
# print type("hello world") # Identify data type
# print type(1)
# print type(True)
# print type(4.2)
# Variables
name = "eric"
# print name
myFavoriteInt = 8
myBool = True
myFloat = 4.2
# print myFavoriteInt
# print myBool
# print myFloat
# Objects
# list => array (referred to as list in Python)
# len() shows the length of the variable / object
myList = [
name,
myFavoriteInt,
myBool,
myFloat,
[myBool, myFavoriteInt, myFloat]
]
print len(myList)
# Dictionary
myDictionary = {
"name": "Eric",
"title": "Entrepenuer",
"hasCar": True,
"favoriteNumber": 8
}
print myDictionary["name"] |
cdb6fb12e74cffd7dce421a4edd389d02d2b4523 | haalogen/hash_table | /func.py | 2,197 | 3.703125 | 4 | """Basic functionality of the project "Hash_Table"."""
def float2hash(f):
"""Float value to hash (int)"""
s = str(f)
n_hash = 0
for ch in s:
if ch.isdigit():
n_hash = (n_hash << 5) + n_hash + ord(ch)
# print ch, n_hash
return n_hash
class HashTable(object):
def __init__(self, q_probe=False , sz=101):
self.size = sz
self.slots = [None] * self.size
# False <-> linear probing
# True <-> quadratic probing
self.quad_probe = q_probe
def __repr__(self):
return str(self.slots)
def hash_function(self, key):
return float2hash(key) % self.size
def rehash(self, oldhash, iteration):
n_hash = 0
if self.quad_probe:
# do quadratic probing rehash
n_hash = (oldhash + iteration**2) % self.size
print 'rehash_qua:', n_hash
else:
# do linear probing rehash
n_hash = (oldhash + iteration) % self.size
print 'rehash_lin: ', n_hash
# raw_input()
return n_hash
def put(self, key):
collis_cnt = 0
hashvalue = self.hash_function(key)
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
else:
if self.slots[hashvalue] == key:
pass # do nothing
else:
iter_cnt = 1
first_hash = hashvalue
nextslot = self.rehash(first_hash, iter_cnt)
# looking for our key or empty slot
while self.slots[nextslot] != None and \
self.slots[nextslot] != key and iter_cnt <= self.size:
iter_cnt += 1
nextslot = self.rehash(first_hash, iter_cnt)
collis_cnt = iter_cnt
if self.slots[nextslot] == None:
self.slots[nextslot] = key
# else <-> self.slots[nextslot] == key => do nothing
return collis_cnt
|
eb392b54023303e56d23b76a464539b70f8ee6e8 | shamim-ahmed/udemy-python-masterclass | /section-4/examples/guessinggame6.py | 507 | 4.1875 | 4 | #!/usr/bin/env python
import random
highest = 10
answer = random.randint(1, highest)
is_done = False
while not is_done:
# obtain user input
guess = int(input("Please enter a number between 1 and {}: ".format(highest)))
if guess == answer:
is_done = True
print("Well done! The correct answer is {}".format(answer))
else:
suggestion = "Please guess higher" if guess < answer else "Please guess lower"
print(f"Sorry, your guess is incorrect. {suggestion}")
|
7a3191f98809ba4587415bae2f7f638446c5d8c6 | shamim-ahmed/udemy-python-masterclass | /section-12/examples/condcomp1.py | 1,472 | 3.8125 | 4 | #!/usr/bin/env python
menu = [
["egg", "spam", "bacon"],
["egg", "sausage", "bacon"],
["egg", "spam"],
["egg", "bacon", "spam"],
["egg", "bacon", "sausage", "spam"],
["spam", "bacon", "sausage", "spam"],
["spam", "egg", "spam", "spam", "bacon", "spam"],
["spam", "egg", "sausage", "spam"],
["chicken", "chips"]
]
for meal in menu:
print(meal, "contains sausage" if "sausage" in meal else "contains bacon" if "bacon" in meal else "contins egg")
print()
items = set()
for meal in menu:
for item in meal:
items.add(item)
print(items)
print()
menu = [
["egg", "spam", "bacon"],
["egg", "sausage", "bacon"],
["egg", "spam"],
["egg", "bacon", "spam"],
["egg", "bacon", "sausage", "spam"],
["spam", "bacon", "sausage", "spam"],
["spam", "egg", "spam", "spam", "bacon", "spam"],
["spam", "egg", "sausage", "spam"],
["chicken", "chips"]
]
result1 = []
for meal in menu:
if "spam" not in meal:
result1.append(meal)
else:
print("A meal was skipped")
print(result1)
print()
result2 = [meal for meal in menu if "spam" not in meal and "chicken" not in meal]
print(result2)
print()
result3 = [meal for meal in menu if "spam" in meal or "egg" in meal if not "bacon" in meal and "sausage" in meal]
print(result3)
print()
result4 = [meal for meal in menu if ("spam" in meal or "egg" in meal) and ("bacon" not in meal and "sausage" in meal)]
print(result4)
print()
|
3d1946247a3518c4bd2128786609946be2ae768c | shamim-ahmed/udemy-python-masterclass | /section-4/exercises/exercise11.py | 638 | 4.21875 | 4 | #!/usr/bin/env python3
def print_option_menu(options):
print("Please choose your option from the list below:\n")
for i, option in enumerate(options):
print("{}. {}".format(i, option))
print()
if __name__ == "__main__":
options = ["Exit", "Learn Python", "Learn Java", "Go swimming", "Have dinner", "Go to bed"]
print_option_menu(options)
done = False
while not done:
choice = int(input())
if choice == 0:
done = True
elif 0 < choice < len(options):
print("You have entered {}".format(choice))
else:
print_option_menu(options)
|
f9610b35b3785f1cd0b5a7ae4f00e2cd9856034a | shamim-ahmed/udemy-python-masterclass | /section-4/examples/strings3.py | 279 | 4.0625 | 4 | #!/usr/bin/env python
number = "9,223;372:036 854,775;807"
separators = ""
for c in number:
if not c.isnumeric():
separators += c
print(separators)
values = "".join([c if c not in separators else " " for c in number]).split()
print([int(val) for val in values])
|
75f04b946796c071f7913bf308f0bf1c40a4c441 | shamim-ahmed/udemy-python-masterclass | /section-4/examples/conditions.py | 135 | 4.15625 | 4 | #!/usr/bin/env python3
age = int(input("Please enter your age: "))
if age >= 16 and age <= 65:
print("Have a good day at work!")
|
bcd6ddba72d2fe2c22112c11f6dbea95fe536d37 | shamim-ahmed/udemy-python-masterclass | /section-12/examples/example_kwargs.py | 323 | 4.3125 | 4 | #!/usr/bin/env python
def print_keyworded_arguments(arg1, **kwargs):
print("arg1 = {}".format(arg1))
for key, value in kwargs.items():
print("{} = {}".format(key, value))
# you can mix keyworded args with non-keyworded args
print_keyworded_arguments("Hello", fruit="Apple", number=10, planet="Jupiter")
|
43836b3fe753f9a651cd9f6cbc636c462cd63c81 | shamim-ahmed/udemy-python-masterclass | /section-4/examples/guessinggame4.py | 416 | 4.0625 | 4 | #!/usr/bin/env python
import random
done = False
while done == False:
answer = random.randrange(1, 11)
guess = int(input("Please enter a number between 1 and 10: "))
if guess == answer:
print("Your guess is correct. The answer is {}".format(answer))
done = True
else:
print("Sorry, your guess was not correct. Please try again")
print()
print("Have a nice day!")
|
f6008700b5aafa0c7f732e3d5e701832554017a7 | alihaiderrizvi/Leetcode-Practice | /all/29-Divide Two Integers/solution.py | 634 | 3.5625 | 4 | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if dividend > 0:
div_sign = 0
else:
div_sign = 1
if divisor > 0:
dvs_sign = 0
else:
dvs_sign = 1
dividend = abs(dividend)
divisor = abs(divisor)
ans = dividend // divisor
if (div_sign == 1 and dvs_sign == 1) or (div_sign == 0 and dvs_sign == 0):
if ans > 2**31 -1:
ans = 2**31 -1
return ans
else:
if ans < -2**31:
ans = -2**31
return -ans
|
4ec2bd94203ef8db68cd0039227d84bc4ea4c62e | alihaiderrizvi/Leetcode-Practice | /all/20-Valid Parenthesis/solution.py | 457 | 3.828125 | 4 | class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 != 0:
return False
stk = []
for i in s:
if i == "(" or i == "[" or i == "{":
stk.append(i)
elif stk and ((i == ")" and stk[-1] == "(") or (i == "]" and stk[-1] == "[") or (i == "}" and stk[-1] == "{")):
stk.pop()
else:
return False
return not stk
|
7cae510cb7d7080ad784927bf19c07b3220aa64e | alihaiderrizvi/Leetcode-Practice | /all/720- Longest Word in Dictionary/720- Longest Word in Dictionary.py | 728 | 3.515625 | 4 | class Solution:
def longestWord(self, words: List[str]) -> str:
s = set(words)
good = set()
for word in words:
n = len(word)
flag = True
while n >= 1:
if word[:n] not in s:
flag = False
n -= 1
if flag:
good.add(word)
good = list(good)
d = {}
for i in good:
if len(i) not in d:
d[len(i)] = [i]
else:
d[len(i)].append(i)
max_count = max(list(d.keys()))
main_ans = d[max_count]
main_ans.sort()
return main_ans[0]
|
ffb117397ed8532cd62567473b9fea61de0e3ee6 | Frankyyoung24/SequencingDataScientist | /Algrithms/week2/bm_algorithm.py | 1,283 | 3.5 | 4 | def boyer_moore(p, p_bm, t):
"""
Do Boyer-Moore matching.
p = pattern, t = text, p_bm = Boyer-Moore object for p (index)
"""
i = 0 # track where we are in the text
occurrences = [] # the index that p match t
while i < len(t) - len(p) + 1:
# loop though all the positions in t where p should start
shift = 1
mismatched = False
for j in range(len(p) - 1, -1, -1):
# the 3rd word '-1' means we're going backwards
if not p[j] == t[i + j]: # when we have a mismatch
# calculate the bad character rule and good suffix rule to see
# how many bases we can skip
skip_bc = p_bm.bad_character_rule(j, t[i + j])
skip_gs = p_bm.good_suffix_rule(j)
# calculate the max shift bases.
shift = max(shift, skip_bc, skip_gs)
mismatched = True
break
if not mismatched: # if there is no mismatch.
occurrences.append(i)
# if there is no mismatch we don't need to use the
# bad_character_rule
skip_gs = p_bm.match_skip()
shift = max(shift, skip_gs)
i += shift # add the value of shift to i
return occurrences
|
617cd19401efd048959af80295b6a2fef88a15b6 | Amo123456/Assignment-submission | /project assignment/Project 1.py | 755 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Develop a cryptography app using python?
# In[9]:
from cryptography.fernet import Fernet
def generate_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("Secret.key","wb")as key_file:
key_file.write(key)
def load_key():
"""
Load the previously generated key
"""
return open("Secret.key","rb").read()
def encrypt_message(message):
"""
Encrypts a message
"""
key = load_key()
encoded_message = message.encode()
f = Fernet(key)
encrypted_message = f.encrypt(encoded_mmessage)
print(encrypted_mmessage)
if __name__ == "__main__":
encrypt_message("encrypt this message")
# In[ ]:
|
e6f7d7097cd80230a9374bfa5067e0759030ba45 | setu-parekh/Interactive-Programming-in-Python-Coursera | /Project 4: Arcade game - Pong/pong_game.py | 4,341 | 3.84375 | 4 | # Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_HEIGHT = HEIGHT / 2
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
ball_pos = [WIDTH / 2, HEIGHT /2 ]
ball_vel = [(random.randrange(120, 240)/60.0),-(random.randrange(60, 180)/60.0)]
right_dir = 'True'
paddle1_pos = float(HEIGHT/2)
paddle2_pos = float(HEIGHT/2)
paddle1_vel = 0.0
paddle2_vel = 0.0
score1 = 0
score2 = 0
# helper function that spawns a ball by updating the
# ball's position vector and velocity vector
# if right is True, the ball's velocity is upper right, else upper left
def ball_init(right_dir):
global ball_pos, ball_vel # these are vectors stored as lists
ball_pos = [WIDTH / 2, HEIGHT /2 ]
ball_vel[1] = -(random.randrange(60, 180)/60.0)
if right_dir:
ball_vel[0] = -(random.randrange(120, 240)/60.0)
else:
ball_vel[0] = (random.randrange(120, 240)/60.0)
# define event handlers
def new_game():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are floats
global score1, score2 # these are ints
right_dir = 'True'
paddle1_pos = float(HEIGHT/2)
paddle2_pos = float(HEIGHT/2)
paddle1_vel = 0.0
paddle2_vel = 0.0
score1 = 0
score2 = 0
ball_init(right_dir)
def draw(c):
global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel
a = -1.1
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
# update ball
if ball_pos[1] <= BALL_RADIUS:
ball_vel[1] = - ball_vel[1]
elif (HEIGHT - ball_pos[1])<= BALL_RADIUS:
ball_vel[1] = - ball_vel[1]
right_dir = (ball_vel[0] > 0)
if (ball_pos[0]-PAD_WIDTH <= BALL_RADIUS):
if ((paddle1_pos-HALF_PAD_HEIGHT)<= ball_pos[1]<=(paddle1_pos+HALF_PAD_HEIGHT)):
ball_vel[0] = a * ball_vel[0]
else:
score2 += 1
ball_init(right_dir)
elif ((WIDTH - ball_pos[0]) <= BALL_RADIUS + PAD_WIDTH):
if ((paddle2_pos- HALF_PAD_HEIGHT)<= ball_pos[1]<=(paddle2_pos+HALF_PAD_HEIGHT)):
ball_vel[0] = a * ball_vel[0]
else:
score1 += 1
ball_init(right_dir)
score1_s = str(score1)
score2_s = str(score2)
# update paddle's vertical position, keep paddle on the screen
if ((paddle1_pos + paddle1_vel >= HALF_PAD_HEIGHT) and ((paddle1_pos + paddle1_vel + HALF_PAD_HEIGHT) <= HEIGHT)):
paddle1_pos += paddle1_vel
if ((paddle2_pos+paddle2_vel >= HALF_PAD_HEIGHT) and ((paddle2_pos+paddle2_vel + HALF_PAD_HEIGHT) <= HEIGHT)):
paddle2_pos += paddle2_vel
# draw mid line and gutters
c.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
c.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
c.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# draw paddles
c.draw_line([HALF_PAD_WIDTH,(paddle1_pos-HALF_PAD_HEIGHT)],[HALF_PAD_WIDTH,(paddle1_pos + HALF_PAD_HEIGHT)],PAD_WIDTH, "White")
c.draw_line([WIDTH - HALF_PAD_WIDTH,(paddle2_pos- HALF_PAD_HEIGHT)],[WIDTH - HALF_PAD_WIDTH,(paddle2_pos + HALF_PAD_HEIGHT)],PAD_WIDTH, "White")
# draw ball and scores
c.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
c.draw_text(score1_s,[150,100], 50, "Yellow")
c.draw_text(score2_s,[400,100], 50, "Yellow")
def keydown(key):
global paddle1_vel, paddle2_vel
if key == simplegui.KEY_MAP['w']:
paddle1_vel = -2.0
elif key == simplegui.KEY_MAP['s']:
paddle1_vel = 2.0
elif key == simplegui.KEY_MAP['up']:
paddle2_vel = -2.0
elif key == simplegui.KEY_MAP['down']:
paddle2_vel = 2.0
def keyup(key):
global paddle1_vel, paddle2_vel
if key == simplegui.KEY_MAP['w']:
paddle1_vel = 0.0
elif key == simplegui.KEY_MAP['s']:
paddle1_vel = 0.0
elif key == simplegui.KEY_MAP['up']:
paddle2_vel = 0.0
elif key == simplegui.KEY_MAP['down']:
paddle2_vel = 0.0
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.add_button("Restart", new_game, 100)
# start frame
frame.start()
|
94dea85884bca08feccbf1c68e3bcc3388af668e | JosephLimWeiJie/algoExpert | /prompt/medium/MinHeightBST.py | 2,135 | 3.59375 | 4 | import unittest
def minHeightBst(array):
return constructMinHeightBST(array, 0, len(array) - 1)
def constructMinHeightBST(array, startIdx, endIdx):
if (startIdx > endIdx):
return None
midIdx = (startIdx + endIdx) // 2
bst = BST(array[midIdx])
bst.left = constructMinHeightBST(array, startIdx, midIdx - 1)
bst.right = constructMinHeightBST(array, midIdx + 1, endIdx)
return bst
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value < self.value:
if self.left is None:
self.left = BST(value)
else:
self.left.insert(value)
else:
if self.right is None:
self.right = BST(value)
else:
self.right.insert(value)
def inOrderTraverse(tree, array):
if tree is not None:
inOrderTraverse(tree.left, array)
array.append(tree.value)
inOrderTraverse(tree.right, array)
return array
def validateBst(tree):
return validateBstHelper(tree, float("-inf"), float("inf"))
def validateBstHelper(tree, minValue, maxValue):
if tree is None:
return True
if tree.value < minValue or tree.value >= maxValue:
return False
leftIsValid = validateBstHelper(tree.left, minValue, tree.value)
return leftIsValid and validateBstHelper(tree.right, tree.value, maxValue)
def getTreeHeight(tree, height=0):
if tree is None:
return height
leftTreeHeight = getTreeHeight(tree.left, height + 1)
rightTreeHeight = getTreeHeight(tree.right, height + 1)
return max(leftTreeHeight, rightTreeHeight)
class TestProgram(unittest.TestCase):
def test_case_1(self):
array = [1, 2, 5, 7, 10, 13, 14, 15, 22]
tree = minHeightBst(array)
self.assertTrue(validateBst(tree))
self.assertEqual(getTreeHeight(tree), 4)
inOrder = inOrderTraverse(tree, [])
self.assertEqual(inOrder, [1, 2, 5, 7, 10, 13, 14, 15, 22])
if __name__ == '__main__':
unittest.main() |
047b6808f400db0906409e22fb7e3897f9bda51a | kirillrssu/pythonintask | /PMIa/2014/Samovarov/task_3_17.py | 810 | 4.1875 | 4 | #Задача №3, Вариант 7
#Напишите программу, которая выводит имя "Симона Руссель", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
#Samovarov K.
#25.05.2016
print("Герой нашей сегодняшней программы - Симона Руссель")
psev=input("Под каким же именем мы знаем этого человека? Ваш ответ:")
if (psev)==("Мишель Морган"):
print ("Все верно: Симона Руссель - "+psev)
else:
print("Вы ошиблись, это не его псевдоним.")
input(" Нажмите Enter для выхода") |
b40e51de38b2a5a3721f823e707b4bf526e1aefc | tioguil/LingProg | /-Primeira Entrega/Exercicio01 2018_08_14/atv1.py | 208 | 4.0625 | 4 | # 1 Faça um Programa que peça o raio de um círculo, calcule e
# mostre sua área.
raio = 0
print("Digite o Raio do circulo")
raio = int(input())
area = 3.14 * raio**2
print("Área do circulo: %s" %(area)) |
34a43cd286f6018aee4d23a683ee1e6211db43f1 | tioguil/LingProg | /-Primeira Entrega/Exercicio03 2018_08_28/atv18.py | 268 | 3.65625 | 4 | # 18. A série de Fibonacci é formada pela seqüência
# 1,1,2,3,5,8,13,21,34,55,... Faça um programa capaz de gerar a série
# até o n−ésimo termo.
a = 0
b = 1
n = int(input("Quantidade: "))
for i in range(n):
print(a)
aux = b
b = a + b
a = aux |
6820cd52316dc5bca7f89c75c7e7a1a6972981dd | tioguil/LingProg | /-Primeira Entrega/Exercicio03 2018_08_28/atv12.py | 1,154 | 4.09375 | 4 | # 12. Uma fruteira está vendendo frutas com a seguinte tabela de
# # preços:
# # Até 5 Kg Acima de 5 Kg
# # Morango R$ 2,50 por Kg R$ 2,20 por Kg
# # Maçã R$ 1,80 por Kg R$ 1,50 por Kg
# # Se o cliente comprar mais de 8 Kg em frutas ou o valor total da
# # compra ultrapassar R$ 25,00, receberá ainda um desconto de 10%
# # sobre este total. Escreva um algoritmo para ler a quantidade (em
# # Kg) de morangos e a quantidade (em Kg) de maças adquiridas e
# # escreva o valor a ser pago pelo cliente.
list = {"morango":[2.50,2.20], "maca": [1.80, 1.50]}
morango = float(input("qunatidade em kg de morando: "))
maca = float(input("qunatidade em kg de maça: "))
if morango <= 5:
valor_morando = list["morango"][0]
else:
valor_morando = list["morango"][1]
if maca <=5:
valor_maca = list["maca"][0]
else:
valor_maca = list["maca"][1]
total_kg = morango + maca
total_valor = (morango * valor_morando) + (maca * valor_maca)
if total_kg > 8 or total_valor > 25:
desconto = total_valor * 0.10
print("valor da total da compra com desconto: ",( total_valor -desconto))
else:
print("valor total da compra: ", total_valor) |
5b577b07f4542809d54f9b64631cf258fcfcce8a | tioguil/LingProg | /-Primeira Entrega/Exercicio01 2018_08_14/atv7.py | 961 | 3.65625 | 4 | # João Papo-de-Pescador, homem de bem, comprou um
# microcomputador para controlar o rendimento diário de seu
# trabalho. Toda vez que ele traz um peso de peixes maior que o
# estabelecido pelo regulamento de pesca do estado de São Paulo (50
# quilos8 deve pagar uma multa de R$ 4,00 por quilo excedente. João
# precisa que você faça um programa que leia a variável peso (peso
# de peixes8 e verifque se há excesso. Se houver, gravar na variável
# excesso e na variável multa o valor da multa que João deverá pagar.
# Caso contrário mostrar tais variáveis com o conteúdo ZERO.
excesso =0
multa = 0.0
print("digitar peso do Peixe")
peso = float(input())
if peso > 50:
excesso = peso - 50
multa = excesso*4
print("peso excedido: %s KG - valor da multa: %s R$" %(excesso, multa))
print("peso informado: ",peso, "KG")
else:
print("Não houve excesso de peso - peso excedido: ",excesso,"KG")
print("Peso: %s KG- Multa %s R$" %(peso, multa)) |
33377065d8e963885d95fa94d891b11720bb44e9 | tioguil/LingProg | /-Primeira Entrega/Exercicio02 2018_08_21/atv05.py | 321 | 4.0625 | 4 | # 5 Escreva um programa que conta a quantidade de vogais em uma
# string e armazena tal quantidade em um dicionário, onde a chave é
# a vogal considerada.
print("entre com a frase")
frase = input()
frase = frase.lower()
vogais = 'aeiou'
dicionario = {i: frase.count(i) for i in vogais if i in frase}
print(dicionario) |
5d35beb083b9d0eff0c68ee9d8575431b5d6fb70 | tioguil/LingProg | /-Primeira Entrega/Exercicio01 2018_08_14/atv11.py | 574 | 3.78125 | 4 | # 11 Faça um programa que solicite a data de nascimento
# (dd/mm/aaaa8 do usuário e imprima a data com o nome do mês por
# extenso.
# Data de Nascimento: 29/10/1973
# Você nasceu em 29 de Outubro de 1973.
# Obs.: Não use desvio condicional nem loops.
import datetime
print("Informe sua data de nascimento ex: 01/01/2018")
nascimento = input()
ano,mes,dia = map(int, nascimento.split('/'))
tipo_date = datetime.date(dia, mes, ano)
data = tipo_date.strftime('%d/%B/%Y')
dia, mes,ano = map(str, data.split('/'))
print ("Você nasceu em %s de %s de %s" %(dia, mes,ano)) |
b16820e8981e0acd4bb8d117ee31925e97f29dc2 | tioguil/LingProg | /-Primeira Entrega/Exercicio03 2018_08_28/atv11.py | 1,018 | 4.09375 | 4 | # 11. Faça um programa que faça 5 perguntas para uma pessoa
# sobre um crime. As perguntas são:
# "Telefonou para a vítima?"
# "Esteve no local do crime?"
# "Mora perto da vítima?"
# "Devia para a vítima?"
# "Já trabalhou com a vítima?"
# O programa deve no fnal emitir uma classifcação sobre a
# participação da pessoa no crime. Se a pessoa responder
# positivamente a 2 questões ela deve ser classifcada como
# "Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso
# contrário, ele será classifcado como "Inocente".
list = []
list.append(input("Telefonou para a vítima? (s/n): "))
list.append(input("Esteve no local do crime? (s/n): "))
list.append(input("Mora perto da vítima? (s/n): "))
list.append(input("Devia para a vítima? (s/n): "))
list.append(input("Já trabalhou com a vítima? (s/n): "))
total = list.count("s")
if total == 2:
print("Suspeita")
elif total == 3 or total == 4:
print("Cúmplice")
elif total == 5:
print("Assassino")
else:
print("Inocente") |
9f73c064597a294823c10d6e511d4ddaacb55790 | dcassells/Rumour-Animation | /animated_rumour.py | 4,940 | 3.6875 | 4 | """
==================
Animated histogram
==================
Use a path patch to draw a bunch of rectangles for an animated histogram.
from terminal write:
python animated_rumour.py #number_of_nodes #number_of_initial_infective
"""
import sys
#import argparse
#parser = argparse.ArgumentParser(
# description = 'Simulation of rumour model in Maki and Thompson (1973) to show proportion of population never hearing a rumour\n\n'+
# 'usage is: python animated_rumour.py #number_of_nodes #number_of_initial_infective',
# epilog = 'Should converge to 0.203 - A. Sudbury (1985)')
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import matplotlib.animation as animation
# Fixing random state for reproducibility
#np.random.seed(19680801)
# initialise number of nodes and number of initial infective
if len(sys.argv) < 2:
# number of nodes
num = 100
# number of initial infective
i_0 = 10
elif len(sys.argv) < 3:
# number of nodes
num = int(sys.argv[1])
# number of initial infective
i_0 = 10
else:
# number of nodes
num = int(sys.argv[1])
# number of initial infective
i_0 = int(sys.argv[2])
# define spread function
def spread():
# count of infective
I = i_0
# count of susceptible
S = num - i_0
# initial state of nodes
nodes = ['s']*num
for i in range(i_0):
nodes[i] = 'i'
# run until no infective
while I != 0 and S != 0:
# caller
u = np.random.randint(num)
# receiver
v = np.random.randint(num)
# is u infective
if nodes[u] == 'i':
# is v suscpetible
if nodes[v] == 's':
# change v from susceptible to infected
nodes[v] = 'i'
# one more infective
I += 1
# one less susceptible
S -= 1
# else v is infective or removed
else:
# change u from infective to removed
nodes[u] = 'r'
# one less infective
I -= 1
return S/num
# histogram our data with numpy
initial = [1]*100
n, bins = np.histogram(initial, 100, density=True, range=(0,1))
data = [spread()]
# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
nrects = len(left)
###############################################################################
# Here comes the tricky part -- we have to set up the vertex and path codes
# arrays using ``plt.Path.MOVETO``, ``plt.Path.LINETO`` and
# ``plt.Path.CLOSEPOLY`` for each rect.
#
# * We need 1 ``MOVETO`` per rectangle, which sets the initial point.
# * We need 3 ``LINETO``'s, which tell Matplotlib to draw lines from
# vertex 1 to vertex 2, v2 to v3, and v3 to v4.
# * We then need one ``CLOSEPOLY`` which tells Matplotlib to draw a line from
# the v4 to our initial vertex (the ``MOVETO`` vertex), in order to close the
# polygon.
#
# .. note::
#
# The vertex for ``CLOSEPOLY`` is ignored, but we still need a placeholder
# in the ``verts`` array to keep the codes aligned with the vertices.
nverts = nrects * (1 + 3 + 1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
verts[0::5, 1] = bottom
verts[1::5, 0] = left
verts[1::5, 1] = top
verts[2::5, 0] = right
verts[2::5, 1] = top
verts[3::5, 0] = right
verts[3::5, 1] = bottom
###############################################################################
# To animate the histogram, we need an ``animate`` function, which runs the
# spread() function and updates the locations of the vertices for the
# histogram (in this case, only the heights of each rectangle). ``patch`` will
# eventually be a ``Patch`` object.
patch = None
def animate(i):
# simulate new data coming in
data.append(spread())
n, bins = np.histogram(data, 100, density=True, range=(0,1))
top = bottom + n
verts[1::5, 1] = top
verts[2::5, 1] = top
print(str(i)+': ',np.mean(data))
return [patch, ]
###############################################################################
# And now we build the `Path` and `Patch` instances for the histogram using
# our vertices and codes. We add the patch to the `Axes` instance, and setup
# the `FuncAnimation` with our animate function.
fig, ax = plt.subplots()
barpath = path.Path(verts, codes)
patch = patches.PathPatch(
barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)
ax.set_xlim(0, 0.5)
ax.set_ylim(bottom.min(), top.max())
ax.set_xlabel('$S/n$')
ax.set_ylabel('Density')
ax.set_title('Distribution of the proportion never hearing the rumour\n for '+str(num)+' nodes and $i_0$ = '+str(i_0))
ani = animation.FuncAnimation(fig, animate, 200, repeat=False, blit=True)
# use .save() to save
#ani.save('rumour.mp4',dpi=250)
# use plt.show() to display
plt.show()
|
7e848517d2ba88ba39d23220858eb341a601d66d | Sullivannichols/classes | /csc321/hw/hw4/parse.py | 2,055 | 3.59375 | 4 | #!/usr/bin/env python3
import csv
import socket
import pygraphviz as pgv
def domains():
''' This function extracts domain names from a .tsv file, performs a
forward DNS lookup on each domain, performs a reverse DNS lookup on
each returned IP, then adds all of the info to a graph.
'''
g = pgv.AGraph()
with open('domains.tsv', newline='') as tsvfile:
tsvin = csv.DictReader(tsvfile, delimiter='\t')
print("domains.tsv loaded into dictionary")
for line in tsvin:
# Forward Lookup
domain = line['domain']
g.add_node(domain)
print("node added for " + domain)
try:
ips = socket.gethostbyname_ex(domain)
except socket.gaierror:
print("socket.gaierror: nodename nor servname provided")
continue
# Reverse Lookup
for item in ips[2]:
noerror = True
try:
result = socket.gethostbyaddr(item)
result = result[0]
result = result.split(".")
result = ".".join(len(result[-2]) < 4 and\
result[-3:] or result[-2:])
except IndexError:
print('IndexError')
noerror = False
continue
except socket.herror:
print('socket.herror')
noerror = False
continue
except:
print('REVERSE DNS ERROR for ' + result)
noerror = False
continue
if noerror:
# add nodes
g.add_node(result)
g.add_edge(domain, result)
print("node added for " + result)
print("edge added between " + domain + " and " + result)
g.layout(args='-Goverlap=false')
g.draw('simple.png')
if __name__ == '__main__':
domains()
|
e53f2538cd20c70b5a7a04de4f714f2077194c65 | cyrusv/Birthday-Problems | /puzzle2.py | 386 | 3.53125 | 4 | # Puzzle 2
# Do Men or Women take longer Hubway rides in Boston?
# By how many seconds? Round the answer DOWN to the nearest integer.
# Use the Hubway data from 2001-2013 at http://hubwaydatachallenge.org/
import pandas as pd
df = pd.DataFrame(pd.read_csv('hubway_trips.csv'))
mean = df.groupby('gender')['duration'].mean()
print df
print mean
print round(abs(mean[1] - mean[0]), 0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.