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 |
|---|---|---|---|---|---|---|
8db500414203b1a1da1f3641c9d24b45fb95ee09 | sweta-chauhan/Simulation | /plotter.py | 1,233 | 3.5625 | 4 | import matplotlib.pyplot as plt
import sys as s
import reader as r
def plot_it(x,size):
y = x[1:]+[x[-1]]
plt.scatter(x,y,marker='p')
plt.show()
return True
def calc_frequency_table(ls,interval_size):
max1,min1 = max(ls),min(ls)
prev1 = min1
x = []
step= (max1-min1)/interval_size
min1+=step
while(min1<=max1):
x.append(min1)
min1+=step
#print(min1>x[-1],max1>x[-1],max1,min1,x[-1])
if(max1>x[-1]):
x.append(max1+1)
len1=len(x)
count = 0
y = []
for i in range(len1):
for j in ls:
if(prev1<=j and j<x[i]):
count+=1
prev1=x[i]
y.append(count)
count =0
print(len(y),len(x),len(ls))
return x,y
def histogram(x,y,xlabel,ylabel):
plt.plot(x,y,color='red')
plt.bar(x,y,width=0.5)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.show()
return True
if __name__ =='__main__':
try:
assert(len(s.argv)>=2)
except:
print("Please insert file name")
print("May be specified is reside in your system")
x=r.read_csv(s.argv[1])
plot_it(x,len(x))
x,y=calc_frequency_table(x,int(s.argv[2]))
histogram(x,y,"x_axis","y_axi")
|
f6ccc6983dc26acd00b2d2fcddd48de22e9d03fd | sweta-chauhan/Simulation | /weibull_distribution.py | 2,253 | 3.515625 | 4 | '''
It is normally used to predict time to failure for machine or electronic components.
alpha scale parameter
beeta shape parameter
{
f(x) = {
{
{
F(x)= { 1-exp(-(x/alpha)^beeta)
{
let X be random variate
then
X = alpha*(-ln(Ui))^(1/beeta)
Note :-
if X is weibull variate then X^beeta is exp(alpha^beeta).
Conversely, if Y is an exponential variate with mean mhu then Y^(1/beeta) is weibull variate with shape parameter beeta and scale parameter alpha = mhu^(1/beeta).
'''
import numpy as np
import random_generator as rd
import plotter as pd
class Weibull_Random_Variate_Generator:
def __init__(self,size,alpha,beeta,r_generator):
self.size=size
self.alpha=alpha
self.r_generator = r_generator
self.beeta = beeta
def __iter__(self):
return self
def __next__(self):
if(self.size==0):
raise StopIteration
self.size-=1
return self.alpha*[-np.log(next(self.r_generator))]**(1/self.beeta)
def weibull_rand_gen(size,alpha,beeta):
l = Weibull_Random_Variate_Generator(size,alpha,beeta,rd.rand())
return list(l)
def func(data,beeta,n,ln_sum):
x1=list(map(lambda x:np.power(x,beeta)*np.log(x),data))
x2=list(map(lambda x:np.power(x,beeta),data))
return (n/beeta)+ln_sum+n*(sum(x1))/(sum(x2))
def func_differenciation(data,beeta,n):
f1 = -n/beeta
x1 = sum([map(lambda x:np.power(x,beeta)),data])
x2=list(map(lambda x:np.power(x,beeta)*(np.log(x)**2),data))
f2 = n*(sum(x2)/x1)
x3=sum(list(map(lambda x:np.power(x,beeta)*np.log(x),data)))
f3 = n*np.power(x3,2)/np.power(x1,2)
return f1-f2+f3
def weibull_parameter_estimator(data,size):
i_beta = np.mean(data)/np.std(data)
i1_beta = 0.0
l = list(map(lambda x: np.log(x),data))
ln_sum = sum(l)
while(np.abs(func(data,i_beta,size,ln_sum))<=0.001):
i1_beta = i_beta - func(data,i_beta,size,ln_sum)/func_differenciation(data,i_beta,size)
i_beta = i1_beta
alpha = np.power(sum(data)/size,1/i_beta)
return alpha,i_beta
#weibull_parameter_estimator()
'''
ls=weibull_rand_gen(500,2,3.5)
pt.plot_it(ls,len(ls))
x,y=pt.calc_frequency_table(ls,10)
pt.histogram(x,y,"x","y")
'''
|
0f5b747e54aad064293a13fc8ba3fdd814499222 | BlackCode7/Projetos_Python | /LoopForPython.py | 267 | 3.890625 | 4 | volwes = ['a', 'e', 'i', 'o', 'u']
word = 'Anderson'
for leters in word:
if leters in word:
print(leters)
for leters in word:
if leters in word:
print(leters)
for leters in word:
if leters in word:
print(" Comandos do python") |
a92e982df871e169a33577d6ba0e404009a98e6a | emonhossainraihan/exp-python-tutorial | /Application/DB/create.py | 365 | 4.03125 | 4 | import sqlite3
connection = sqlite3.connect('movies.db')
cursor = connection.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS Movies
(Title TEXT, Director TEXT, Year INT)''')
cursor.execute("INSERT INTO Movies VALUES ('Taxi Driver', 'Unknown', 1990)")
cursor.execute("SELECT * FROM Movies")
print(cursor.fetchall())
connection.commit()
connection.close() |
ca4cc6cbb80f10cc7209ad1d1ce055f420790538 | bruxeiro/AulasPython | /app_py/aula6.py | 225 | 3.75 | 4 | conjunto = {1, 2, 3, 4}
conjunto2 = {4, 5, 6, 7}
conjunto_uniao = conjunto.union(conjunto2)
print('União: {} '.format(conjunto_uniao))
# conjunto = {1, 2, 3, 4}
#
# conjunto.add(5)
# conjunto.discard(1)
# print(conjunto) |
4e630b1beba7ebcc60203ddce1ba624d893d03ea | nyagajr/password-locker | /run.py | 3,008 | 4.4375 | 4 | #!/usr/bin/env python3.6
from credentials import Credentials
from user_details import User
def create_credentials(fname,lname,uname,phone,email,password):
'''
Function to create a new credentials
'''
new_credentials = Credentials(fname,lname,uname,phone,email,password)
return new_credentials
def save_credential(credentials):
'''
Function to save credentials
'''
credentials.save_credential()
def delete_credential(credentials):
'''
Function to delete a credential
'''
credentilas.delete_credential()
def display_credentials():
'''
Function that returns all the saved credentials
'''
return Credentials.display_credentials()
def main():
print("Hello Welcome to your credentials list. What is your name?")
user_name = input()
print(f"Welcome {user_name}. \n what would you like to do?")
print('\n')
while True:
print("Use these short codes : cc - create a new credentials, dc - display credentials, ex -exit the credentials list ")
short_code = input().lower()
if short_code == 'cc':
print("New Credential")
print("-"*10)
print ("First name ....")
f_name = input()
print("Last name ...")
l_name = input()
print("user name ...")
u_name = input()
print("Phone number ...")
p_number = input()
print("Email address ...")
e_address = input()
print("password ...")
password = input()
save_credential(create_credentials(f_name,l_name,u_name,p_number,e_address,password))
print ('\n')
print(f"New Credential {f_name} {l_name} created")
print ('\n')
elif short_code == 'dc':
if display_credentials():
print("Here is a list of all your credentials")
print('\n')
for credentials in display_credentials():
print(f"first name: {credentials.first_name}\n\nlast name: {credentials.last_name}\n\nuser name: {credentials.user_name}\n\nphone number: {credentials.phone_number}\n\nemail: {credentials.email}\n\nyour password: {credentials.password}")
print('\n')
else:
print('\n')
print("You dont seem to have any credentials saved yet")
print('\n')
elif short_code == "ex":
print("Thank you for using password locker")
break
else:
print("INVALID!! Please use the short codes provided")
if __name__ == '__main__':
main()
|
73000a7cbc05bc572ba79ab8baab763df0b45017 | codywsy/PythonCode | /Project1/util.py | 577 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# lines产生一个生成器generator对象,作用在文件file参数的最后追加一个空行'\n'
def lines(file):
for line in file: yield line
yield '\n'
#
def blocks(file):
block = []
for line in lines(file):
if line.strip(): # strip()是为了去除文本内容开头和结尾中多余的空格
block.append(line) #加入列表对象block中
elif block: #如果此时line为空行(文本块结束标志),则将block元素链接起来,作为文本块输出
yield ''.join(block).strip()
block = []
|
500a0e7fefbe931bb987afb5fe2b9777ff56a2fc | ZhifeiCheng/TCSS-Final-Project | /Dungeon.py | 8,663 | 3.75 | 4 | import math
import random
from RoomFactory import RoomFactory
class Dungeon:
"""
This class randomly generates a maze of rooms given the desired dimensions
which players can pass through to play the Dungeon Adventure game.
"""
def __init__(self, column_count, row_count):
"""
Given dungeon dimensions, a dungeon can be constructed with rooms that can contain items for the game.
"""
self.__column_count = column_count
self.__row_count = row_count
self.__room_list = []
self.__room_content = {"M": 0.1, "X": 0.1, "V": 0.2, "H": 0.2} # dict of each room content & ratio
self.__pillar = ["A", "E", "I", "P"]
self.__room_content_count = None # number count of each room content
self.__vision_rooms = []
self.__entrance_exit_pos = []
self.__empty_rooms = column_count * row_count - 6
@property
def room_content(self):
""""Gives other classes access to the private field of self.__room_content.keys()."""
return self.__room_content.keys()
@property
def room_list(self):
""""Gives other classes access to the private field of self.__room_list."""
return self.__room_list
def entrance_generator(self):
"""
Generates the 2d coordinate pair for the entrance by randomly pick one coordinate along the perimeter.
"""
entrance_x = random.choice([0, self.__row_count - 1])
entrance_y = random.choice([0, self.__column_count - 1])
entrance_location = random.choice([[entrance_x, random.randint(0, self.__column_count - 1)],
[random.randint(0, self.__row_count - 1), entrance_y]])
return entrance_location
def dungeon_generator(self):
"""
Generates the dungeon by setting up the entrance point, create_room from RoomFactory class and lists of lists.
"""
self.cal_room_content()
# populate empty dungeon without room_content
for r in range(0, self.__row_count):
room_row = []
for c in range(0, self.__column_count):
room_row.append(RoomFactory.create_room(r, c, self.__row_count - 1, self.__column_count - 1))
self.__room_list.append(room_row)
# call set_traverse_path function to set door alignments between rooms
self.set_traverse_path()
# assign room_content for empty rooms that are not entrance or exit
for row in range(0, self.__row_count):
for column in range(0, self.__column_count):
room = self.__room_list[row][column]
if room.room_content is None:
room.room_content = self.room_content_generator()
if room.room_content == "V":
self.__vision_rooms.append([row, column])
self.set_room_vision_potion()
return self.__room_list
def set_traverse_path(self):
"""
Finds a traversable path from the entrance room by randomly picking the moving direction until
reach the perimeter of the dungeon, which will be the exit room. The method guarantees each generated dungeon is
valid and has at least one traversable path. Four pillars are assigned along the path as room_content.
"""
entrance_point = self.entrance_generator()
RoomFactory.update_room_as_exit(self.__room_list[entrance_point[0]][entrance_point[1]], entrance_point[0],
entrance_point[1], self.__row_count - 1,
self.__column_count - 1, "i")
self.__entrance_exit_pos.append(entrance_point)
path_room_list = []
curr_x = entrance_point[0]
curr_y = entrance_point[1]
path_room_list.append(entrance_point)
while curr_x != 0 and curr_x != self.__row_count - 1 and curr_y != 0 and curr_y != self.__column_count - 1 or [
curr_x, curr_y] == entrance_point or len(path_room_list) < 6:
random_dir_generator = random.choice(["W", "S", "E", "N"])
self.__room_list[curr_x][curr_y].is_visited = True
if random_dir_generator == "N" and curr_x - 1 >= 0 and not self.__room_list[curr_x][curr_y - 1].is_visited:
next_room = [curr_x - 1, curr_y]
path_room_list.append(next_room)
curr_x -= 1
elif random_dir_generator == "E" and curr_y + 1 < self.__column_count and self.__room_list[curr_x][
curr_y + 1].is_visited is False:
next_room = [curr_x, curr_y + 1]
path_room_list.append(next_room)
curr_y += 1
elif random_dir_generator == "S" and curr_x + 1 < self.__row_count and self.__room_list[curr_x + 1][
curr_y].is_visited is False:
next_room = [curr_x + 1, curr_y]
path_room_list.append(next_room)
curr_x += 1
elif random_dir_generator == "W" and curr_y - 1 >= 0 and self.__room_list[curr_x][
curr_y - 1].is_visited is False:
next_room = [curr_x, curr_y - 1]
path_room_list.append(next_room)
curr_y -= 1
else:
self.__entrance_exit_pos.append([curr_x, curr_y])
for idx in range(len(path_room_list)-1):
room2_loc = path_room_list[idx+1]
room1_loc = path_room_list[idx]
RoomFactory.connect_room(self.__room_list[room1_loc[0]][room1_loc[1]], self.__room_list[room2_loc[0]][room2_loc[1]],
room1_loc, room2_loc)
selected_room = random.sample(path_room_list[1:-1], 4)
for room_idx in selected_room:
pillar_room = self.__room_list[room_idx[0]][room_idx[1]]
pillar_room.room_content = self.__pillar.pop(0)
RoomFactory.update_room_as_exit(self.__room_list[curr_x][curr_y], curr_x, curr_y, self.__row_count - 1,
self.__column_count - 1)
def room_content_generator(self):
"""
generate a sequence of random numbers based on the room has content
"""
num = random.randint(0, sum(self.__room_content_count) + self.__empty_rooms)
for idx in range(len(self.__room_content)): # iterate through each room content type
if num < self.__room_content_count[idx]:
self.__room_content_count[idx] -= 1
return list(self.__room_content.keys())[idx]
else:
num -= self.__room_content_count[idx]
self.__empty_rooms -= 1
return " "
def cal_room_content(self):
"""
Calculates the count of each room content type by percentage
"""
self.__room_content_count = [math.floor(x * self.__empty_rooms) for x in self.__room_content.values()]
self.__empty_rooms = self.__empty_rooms - sum(self.__room_content_count)
def entrance_exit_pos(self):
""""Gives other classes access to the private field of self.__entrance_exit_pos."""
return self.__entrance_exit_pos
def set_room_vision_potion(self):
"""
Visualize the 8 adjacent rooms around the current room
"""
for row, col in self.__vision_rooms:
self.__room_list[row][col].vision_potion_rooms = self.get_vision_potion_rooms(row, col)
def get_vision_potion_rooms(self, row, col):
"""
Visualize the 8 adjacent rooms around the current room
"""
rooms = []
offsets = [-1, 0, 1]
for r_offset in offsets:
n_row = row + r_offset
if 0 <= n_row < self.__row_count:
room = []
for c_offset in offsets:
n_col = col + c_offset
if 0 <= n_col < self.__column_count:
room.append(self.__room_list[n_row][n_col])
rooms.append(room)
return rooms
def __str__(self):
"""
Returns a str visualization of the dungeon.
"""
res = ""
for row in self.__room_list:
for i in range(3):
line = []
for col in row:
line += col.room_matrix[i]
line.append(" ")
res += "".join(line) + "\n"
return res
if __name__ == "__main__":
dungeon = Dungeon(6, 6)
dungeon.dungeon_generator()
print(dungeon)
# print(dungeon.entrance_exit_generator())
# print(dungeon.set_room_content())
|
df3c0636f2994c4fdb3828e3220665960f75cfbe | jnash10/Ration-delivery-post-disaster-IISC-Hackathon- | /dist_matrix.py | 470 | 3.640625 | 4 | import numpy as np
def dist(a, b):
return int(((a[0]-b[0])**2+(a[1]-b[1])**2)**(1/2))
def matrix(cities):
dist_matrix = []
for city in cities:
city_dist = []
for i in range(0,len(cities)):
city_dist.append(dist(city,cities[i]))
#print(type(city_dist), city_dist)
dist_matrix.append(city_dist)
dist_matrix = np.array(dist_matrix)
#print(dist_matrix)
dist_matrix[:, 0]=0
return dist_matrix
|
ede71eaf8f409a526b48ecbe81898c13826be3c0 | ali-almousa/CS50-AI-Project0-degrees | /util.py | 1,617 | 4.09375 | 4 |
class Node:
def __init__(self, state, parent, action):
# the state attribute is a coordinate for the node in the maze
self.state = state
# the parent attribute is an object (node) of Node class
self.parent = parent
# the action attribute is a string (up, down, left, right)
self.action = action
class StackFrontier:
def __init__(self):
self.frontier = [] # creating an empty frontier with a list data structure
def add(self, node):
self.frontier.append(node)
# checks if the passsed state is existent in the frontier (True) or not (False)
def contains_state(self, state):
return any(node.state == state for node in self.frontier)
# no args; when invoked would return True if the frontier is empty and False otherwise
def empty(self):
return len(self.frontier) == 0
# no args: raises an Exception when the frontier is empty otherwise the last node in the frontier is returned
def remove(self):
if self.empty():
raise Exception("frontier is empty")
else:
node = self.frontier[-1]
# del self.frontier[-1]
self.frontier = self.frontier[:-1]
return node
class QueueFrontier(StackFrontier):
# Q1 = how can I access frontier attribute in line 41 without invoking the superclass's constructor (__init__).
def remove(self):
if self.empty():
raise Exception("frontier is empty")
else:
node = self.frontier[0]
self.frontier = self.frontier[1:]
return node
|
973f74c535a6a6eb0505a92ae35cdf09581f46cc | jpallavi23/Smart-Interviews | /07_SI_Primary-Hackerrank/01_Print Hollow Diamond Pattern.py | 587 | 3.734375 | 4 | # For question to go
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-print-hollow-diamond-pattern
no_of_test_cases = int(input())
iter = 1
while iter <= no_of_test_cases:
size_n = int(input())
count = size_n - 1
count = count / 2
print("Case #{}:".format(iter))
for itr in range(size_n):
for jtr in range(size_n):
if itr + jtr == count or jtr - itr == count or itr - jtr == count or itr + jtr == (count*3):
print("*", end = "")
else:
print(end = " ")
print()
iter += 1 |
147a8d125d9289c6b7bd0dc4ca7f5b7d8096f029 | jpallavi23/Smart-Interviews | /01_B_Algorithms-Hackerrank/22_Drawing Book.py | 292 | 3.5625 | 4 | # For question go to:
# https://www.hackerrank.com/challenges/drawing-book/problem
no_of_pages = int(input())
page_reqd = int(input())
min_no_of_turns = (no_of_pages // 2) - (page_reqd // 2)
if min_no_of_turns > (page_reqd // 2):
min_no_of_turns = page_reqd // 2
print(min_no_of_turns) |
bb0e1fe19f80ab08f9d338483c1c88b3b253b1f1 | jpallavi23/Smart-Interviews | /01_B_Algorithms-Hackerrank/10_Time Conversion.py | 247 | 3.78125 | 4 | # For question go to:
# https://www.hackerrank.com/challenges/time-conversion/problem
time = input().upper().split(":")
time[0] = int(time[0])%12
if "PM" in time[-1] and [0]:
time[0]+=12
time[0] = '%02d' % time[0]
print(":".join(time)[:-2]) |
da7c6439c4344639aadbf4f3ce7f97fa6ceba643 | jpallavi23/Smart-Interviews | /01_A_Data Structures-Hackerrank/01_Array - DS.py | 185 | 3.578125 | 4 | # For question go to:
# https://www.hackerrank.com/challenges/arrays-ds/problem
array_size = int(input())
array_elements = list(map(int, input().split()))
print(*array_elements[::-1]) |
b22864e5fc16f9a52eec5dbc3ae9d570fcef1b4f | jpallavi23/Smart-Interviews | /03_Code_Forces/22_Beautiful Matrix.py | 1,565 | 4.0625 | 4 | '''
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
Swap two neighboring matrix rows, that is, rows with indexes i and i + 1 for some integer i (1 ≤ i < 5).
Swap two neighboring matrix columns, that is, columns with indexes j and j + 1 for some integer j (1 ≤ j < 5).
You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
Input
The input consists of five lines, each line contains five integers: the j-th integer in the i-th line of the input represents the element of the matrix that is located on the intersection of the i-th row and the j-th column. It is guaranteed that the matrix consists of 24 zeroes and a single number one.
Output
Print a single integer — the minimum number of moves needed to make the matrix beautiful.
Examples
Input
0 0 0 0 0
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Output
3
Input
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 0 0
Output
1
'''
for i in range(5):
arr = [int(x) for x in input().split()]
for j in range(5):
if arr[j] == 1:
print(abs(2 - i) + abs(2 - j))
exit |
4ba77e1ec6d8665a964f988cba5286746e8c60f3 | jpallavi23/Smart-Interviews | /07_SI_Primary-Hackerrank/02_Print Right Angled Triangle Pattern.py | 606 | 3.796875 | 4 | # For question go to:
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-print-right-angled-triangle-pattern
# Input:
# 2
# 1
# 4
# Ouput:
# Case #1:
# *
# Case #2:
# *
# **
# ***
# ****
no_of_test_cases = int(input())
iter = 1
while iter <= no_of_test_cases:
size = int(input())
i = j = 1
count = 2 * size - 2
print("Case #{}:".format(iter))
while i < size+1:
for j in range(i, size):
print(end=" ")
count = count - 2
for j in range(1, i + 1):
print("*", end="")
i += 1
print("")
iter += 1 |
dd23412ee46c88333b88c07b3d8a270143a6cdc3 | jpallavi23/Smart-Interviews | /01_B_Algorithms-Hackerrank/02_Simple Array Sum.py | 328 | 3.75 | 4 | # For question go to:
# https://www.hackerrank.com/challenges/simple-array-sum/problem
def simpleArraySum(ar):
sum = 0
for obj in ar:
sum = sum + obj
return sum
if __name__ == '__main__':
ar_count = int(input())
ar = list(map(int, input().split()))
result = simpleArraySum(ar)
print(result) |
97a312f66353fb5fd0a5c918f54f557e2479559d | jpallavi23/Smart-Interviews | /03_Code_Forces/29_Petya and Strings.py | 1,301 | 3.859375 | 4 | '''
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.
Input
Each of the first two lines contains a bought string. The strings' lengths range from 1 to 100 inclusive. It is guaranteed that the strings are of the same length and also consist of uppercase and lowercase Latin letters.
Output
If the first string is less than the second one, print "-1". If the second string is less than the first one, print "1". If the strings are equal, print "0". Note that the letters' case is not taken into consideration when the strings are compared.
Examples
Input
aaaa
aaaA
Output
0
Input
abs
Abz
Output
-1
Input
abcdefg
AbCdEfF
Output
1
Note
If you want more formal information about the lexicographical order (also known as the "dictionary order" or "alphabetical order"), you can visit the following site:
http://en.wikipedia.org/wiki/Lexicographical_order
'''
str1, str2 = input().lower(), input().lower()
print(-1 if str1 < str2 else (1 if str1 > str2 else 0)) |
dbbbb52829963fe9ea2b1015d3cdaa17ffc9cc3d | jpallavi23/Smart-Interviews | /07_SI_Primary-Hackerrank/14_Finding Missing Number.py | 526 | 3.703125 | 4 | # For question go to:
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-finding-missing-number
def findMissingNum(length_of_num_list, list_nums):
total_sum = (length_of_num_list + 1) * (length_of_num_list + 2) / 2
print(int(total_sum - sum(list_nums)))
if __name__ == '__main__':
no_of_test_cases = int(input())
iter = 1
while iter <= no_of_test_cases:
ar_count = int(input())
ar = list(map(int, input().split()))
findMissingNum(ar_count, ar)
iter += 1 |
fe297a22342a92f9b3617b827367e60cb7b68f20 | jpallavi23/Smart-Interviews | /03_Code_Forces/08_cAPS lOCK.py | 1,119 | 4.125 | 4 | '''
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentally switched on, if:
either it only contains uppercase letters;
or all letters except for the first one are uppercase.
In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed.
Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.
Input
The first line of the input data contains a word consisting of uppercase and lowercase Latin letters. The word's length is from 1 to 100 characters, inclusive.
Output
Print the result of the given word's processing.
Examples
Input
cAPS
Output
Caps
Input
Lock
Output
Lock
'''
word = input()
if word[1:].upper() == word[1:]:
word = word.swapcase()
print(word) |
4344f818cad8fd3759bab9e914dafb31171782f8 | jpallavi23/Smart-Interviews | /06_SI_Basic-Hackerrank/40_Hollow rectangle pattern.py | 628 | 4.21875 | 4 | '''
Print hollow rectangle pattern using '*'. See example for more details.
Input Format
Input contains two integers W and L. W - width of the rectangle, L - length of the rectangle.
Constraints
2 <= W <= 50 2 <= L <= 50
Output Format
For the given integers W and L, print the hollow rectangle pattern.
Sample Input 0
5 4
Sample Output 0
*****
* *
* *
*****
'''
cols, rows = map(int, input().split())
for itr in range(1, rows+1):
for ctr in range(1, cols+1):
if itr == 1 or itr == rows or ctr == 1 or ctr == cols:
print("*", end="")
else:
print(" ", end="")
print("\r") |
510827c32bcef49a1c3216fe969b687d5e904027 | jpallavi23/Smart-Interviews | /Filtering_Contest/04_Anagrams Easy.py | 358 | 3.84375 | 4 | # For question go to:
# https://www.hackerrank.com/contests/smart-interviews-gcet-2021-a/challenges/si-check-anagrams
no_of_test_cases = int(input())
iter = 1
while iter <= no_of_test_cases:
string1, string2 = list(map(str, input().split()))
if sorted(string1) == sorted(string2):
print("True")
else:
print("False")
iter += 1 |
a200d058612bb4a449731837d3cb3578b6f8a24d | jpallavi23/Smart-Interviews | /01_B_Algorithms-Hackerrank/07_Staircase.py | 305 | 3.921875 | 4 | # For question go to:
# https://www.hackerrank.com/challenges/staircase/problem
size = int(input())
i = j = 1
count = 2 * size - 2
while i < size+1:
for j in range(i, size):
print(end=" ")
count = count - 2
for j in range(1, i + 1):
print("#", end="")
i += 1
print("") |
bfb85080d765702f7c45dddf6c2b9301af95ddce | jpallavi23/Smart-Interviews | /01_B_Algorithms-Hackerrank/28_Climbing the Leaderboard.py | 445 | 3.5 | 4 | # For question go to:
# https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
no_of_players = int(input())
leaderBoard_Scores = sorted(set(list(map(int, input().split()))), reverse = True)
no_of_games = int(input())
gameScores = list(map(int, input().split()))
length = len(leaderBoard_Scores)
for itr in gameScores:
while (length > 0) and (itr >= leaderBoard_Scores[length - 1]):
length -= 1
print(length + 1) |
56efa98ef892acdad26a8a53fe38b1616cb4b143 | jpallavi23/Smart-Interviews | /06_SI_Basic-Hackerrank/10_Natural Numbers Sum.py | 325 | 4 | 4 | '''
Given positive integer - N, print the sum of 1st N natural numbers.
Input Format
Input contains a positive integer - N.
Constraints
1 <= N <= 104
Output Format
Print the sum of 1st N natural numbers.
Sample Input 0
4
Sample Output 0
10
'''
n = int(input())
sum_n = 0
for _ in range(n+1):
sum_n += _
print(sum_n) |
df06707786077c8da542e958d33b91b9ba2f4e99 | Marian4/Classes | /Questão3.py | 879 | 3.78125 | 4 | class retangulo(object):
def __init__(self):
self.base = 1
self.altura = 2
def MudarValorLados(self,novaBase,novaAltura):
self.base = novaBase
self.altura = novaAltura
def RetornarValorLados(self):
return self.base,self.altura
def calcularArea(self):
return self.base*self.altura
def calcularPerimetro(self):
return (self.base*2)+(self.altura*2)
base = eval(input("Informe a medida da base/largura do local:"))
altura = eval(input("Informe a medida da altura/comprimento do local:"))
basePiso = eval(input("Informe a medida da base/largura do piso:"))
alturaPiso = eval(input("Informe a medida da altura/comprimento do piso:"))
areaPiso = basePiso*alturaPiso
local = retangulo()
local.MudarValorLados(base,altura)
areaLocal = local.calcularArea()
QuantPisos = areaLocal/areaPiso
print("\nSo necessrios %i pisos para o local."%QuantPisos) |
b70e5919523c5da709d17b4312f368d33e67de01 | GorgonEnterprises/HackerRank-Practice | /ProblemSolving/warmup/comparetheTriplets/comparetheTriplets.py3 | 263 | 3.640625 | 4 | def compareTriplets(a, b):
arr = [0,0]
for i in range(0,3):
print("i=", i)
if(a[i] > b[i]):
arr[0]+=1
print("a", a[i])
if(b[i] > a[i]):
arr[1]+=1
print("b", b[i])
return arr
|
9f482988c925e7a83335560e4b5c2c5880a0d3ab | muklah/Kattis | /Problems' Solutions/akcija.py | 281 | 3.5625 | 4 | books = int(input())
prices = [int(input()) for _ in range(books)]
prices.sort()
total = 0
group = []
for price in range(books):
group.append(prices.pop())
if len(group) == 3:
total += sum(group) - min(group)
group = []
total += sum(group)
print(total)
|
3cb40bd32d698d618bc51c960460955075357217 | muklah/Kattis | /Problems' Solutions/everywhere.py | 232 | 3.5 | 4 | t = int(input())
f_result = {}
for i in range(t):
n = int(input())
result = []
for j in range(n):
c = input()
result.append(c)
f_result[i] = [set(result)]
ee = type(f_result[0])
print(ee)
|
5b6e8deee28ff65889d15ec612f3f778cce1b097 | bumiltacaldrin11/datascience | /Bumiltacaldrin.py | 1,043 | 4 | 4 | # COE 003 / CPE22FA1
# Datascience
# Programs and Contents
a = []
while True:
print("MENU")
print(" ")
print("1.) Add Bookmarks")
print("2.) Edit Bookmarks")
print("3.) Delete Bookmarks")
print("4.) View Bookmarks")
print("5.) Exit")
print(" ")
x = input("What do you want to do ? ")
if x == '1':
print("----- Add Bookmarks-----")
a_bm = input("Add Bookmarks:")
a.append(a_bm)
print(" ")
elif x == '2':
print("-----Edit Bookmarks-----")
a_eb = input("Edit Bookmarks:")
dex = a.index(a_eb)
a.remove(a_eb)
a_eb1 = input("New Bookmarks:")
a.insert(dex,a_eb1)
print(" ")
elif x == '3':
print("----- Delete Bookmarks-----")
a_db = input("Delete Bookmarks:")
a.remove(a_db)
print(" ")
elif x == '4':
print("-----View Bookmarks-----")
print(a)
print(" ")
elif x == '5':
print("Thank you !!")
break
|
5510d31f40b640c9a702d7580d1d434715469ba9 | smzapp/pyexers | /01-hello.py | 882 | 4.46875 | 4 |
one = 1
two = 2
three = one + two
# print(three)
# print(type(three))
# comp = 3.43j
# print(type(comp)) #Complex
mylist = ['Rhino', 'Grasshopper', 'Flamingo', 'Bongo']
B = len(mylist) # This will return the length of the list which is 3. The index is 0, 1, 2, 3.
print(mylist[1]) # This will return the value at index 1, which is 'Grasshopper'
print(mylist[0:1]) # This will return the first 3 elements in the list.
print(mylist[1:]) # is equivalent to "1 to end"
print(len(mylist))
# Example:
# [1:5] is equivalent to "from 1 to 5" (5 not included)
# [1:] is equivalent to "1 to end"
# [len(a):] is equivalent to "from length of a to end"
#---------
tups = ('TupName', 'TupsAddress', 'TupsContact') #@TUPLE
listo = ['ListName', 'Address', 'Contact']
print(type(tups))
print(type(listo))
print(tups[0], tups[2] ) #tups[3] is out of range
print(listo[0])
#--------- |
8189e8d5c7169ba0b1f1e17268d440c03a5874cf | kangminsu1598/TIL | /algorithm/list_algorithm/2nd-list/test.py | 458 | 3.890625 | 4 | # 행 우선순회, i: i행, j: j열
array = [[0,1,2,3]
,[4,5,6,7]]
for i in range(len(array)):
for j in range(len(array[i])):
print(array[i][j], end='')
print()
# 열 우선순회
for j in range(len(array[0])):
for i in range(len(array)):
print(array[i][j], end='')
print()
# 지그재그
for i in range(len(array)):
for j in range(len(array[0])):
print(array[i][j+(4-1-2*j)*(i%2)], end='')
print() |
6042f3d8fc435e8d33b2ef7e7d04f51f7b85a743 | kangminsu1598/TIL | /startcamp/test/string_test.py | 671 | 3.84375 | 4 | # 파이썬 과거 단축
#print('일은 영어로 %s, 이는 영어로 %s' % ('one', 'two'))
# pyformat
print('{} {}'.format('one', 'two'))
#name = '강민수'
#e_name = 'Kang'
#print('안녕하세요. {}입니다. My name is {}'.format(name, e_name))
#f-string python 3.6
#print(f'안녕하세요.{name}입니다. My name is {e_name}')
#오늘의 행운의 번호는 ~~ 입니다, f-string 사용
import random
numbers = list(range(1,46))
lotto = random.sample(numbers,6)
lotto.sort()
print(f'오늘의 행운의 번호는 {lotto}입니다')
print("오늘의 행운의 번호는 {}입니다".format(lotto))
name = 'k'
print('안녕하세요'+ name +'입니다.') |
c2d87e140241f97ab0bb59d363db33133b079c2f | shofi384/CSC.11300 | /cube.py | 205 | 4 | 4 | def main():
n= int(input("Please enter an integer.\nI will print the sum of all cubes up to the integer: "))
SumTotal=0
for i in range(n+1):
SumTotal+=i*i*i
print(SumTotal)
main()
|
51d06bd680e05e77c24e7927219e9d97db5661f2 | pool-prateek/Lucia-examples | /Text Input Example/text_input_example.py | 862 | 3.65625 | 4 | #This program demonstrates how to use virtual input in Lucia
#The program will prompt the user to type in a message and will print it to the screen before exiting
import lucia
import sys
#Must be called in order for lucia to work properly
#Since we are using bass, I will just call init without the open Al parameter.
#Should you wish to change it, the desired param is in __init__.py in Lucia's directory
lucia.initialize()
def main():
#Create a game window
lucia.show_window("Input Example.")
#Create the virtualInput object. See the module itself for further details
input_handler = lucia.ui.virtualinput.virtualInput()
#Gather our user input.
user_response = input_handler.run("Please enter something!")
#Output our response
print(user_response)
#Properly quit
lucia.quit()
sys.exit()
#Run this via command line
if __name__ == "__main__":
main() |
9a3e48d47cf481867703918e5c959b1be81448a0 | Bchass/Algorithms | /Sort/QuickSort/QuickSort.py | 367 | 3.96875 | 4 | def QuickSort(list):
if len(list) <= 1:
return list
else:
pivot = list.pop()
high = []
low = []
for item in list:
if item > pivot:
high.append(item)
else:
low.append(item)
return QuickSort(low) + [pivot] + QuickSort(high)
print(QuickSort([6,2,10,4,3,1])) |
5da5f3b2063362046288b6370ff541a13552f9c8 | adamyajain/PRO-C97 | /countingWords.py | 279 | 4.28125 | 4 | introString = input("Enter String")
charCount = 0
wordCount = 1
for i in introString:
charCount = charCount+1
if(i==' '):
wordCount = wordCount+1
print("Number Of Words in a String: ")
print(wordCount)
print("Number Of Characters in a String: ")
print(charCount) |
b79c328c307619ebb2896624af769cf418af0694 | kaulashish/Edyoda | /Python/Assignment 1/Sequence of travel.py | 1,528 | 4.09375 | 4 | # You will be given an integer number of elements and for next n lines space
# separeted key value pairs. make a dict from strings of tickets("to":"from").
# find out the sequence of travel.
# Assuming that there will be only one starting point for the journey.
# Input Format:
# You will be given an integer number of elements and for next n lines
# space separeted key value pairs
# Output Format:
# Print The dictionary fro the sequence of travel.
# Sample Input 0:
# {"Chennai":"Bangalore","Bombay":"Delhi","Goa":"Chennai","Delhi":"Goa"}
# Sample Output 0:
# {'Bombay':'Delhi','Delhi':'Goa','Goa':'Chennai','Chennai':'Banglore'}
# ----- Solution -----
# n = int(input())
# dict_ = dict(input().split() for _ in range(n))
# print(dict_)
dict_ = {
"Chennai": "Bangalore",
"Bombay": "Delhi",
"Goa": "Chennai",
"Delhi": "Goa"
}
source, dest = list(dict_.keys()), list(dict_.values())
new_source, new_dest = [], []
# create starting point
for i in source:
if i in source and i not in dest:
new_source.append(i)
# check dest corresponding to source and append to new_dest and vice-versa
for i in range(0, len(source)):
new_dest.append(dest[source.index(new_source[i])])
if new_dest[-1] not in new_source: # avoiding repitition
if new_dest[-1] in source: # avoiding final destination to enter
# new_source, i.e Bangalore
new_source.append(new_dest[-1])
print(dict(zip(new_source, new_dest)))
|
9757bf55218b0805da802ced331ce27b2f123cb6 | ailenbianchi/Practica-Pandas-y-Matplotlib | /ejfinanzas.py | 759 | 3.609375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
fin = pd.read_csv(r"C:\Users\LENOVO\PycharmProjects\Practica Pandas - Matplotlib\finanzas.csv")
#print(fin)
columnas = fin.columns.values
print(columnas)
#Ver las primeras filas de la categoria comestibles
vol = fin[fin.Categoría == "Comestibles"]
print(vol.head())
#Contar la cantidad de articulos de la categoria comestibles
print(vol.Artículo.value_counts())
#Grafico de barras, barras laterales, de torta, de puntos
vol.Artículo.value_counts().plot(kind = 'bar', color = "green", figsize = (10,5));
#vol.Artículo.value_counts().plot(kind = 'barh', color = "red");
#vol.Artículo.value_counts().plot(kind = 'pie');
#fin.plot(kind = "scatter", x = "Unidades", y = "Ganancia")
plt.show()
|
cf241ae2cf67158ceeaff90d474e63468116b6bf | ChenchuSowmyaDhulipalla/Python_Training_Basics | /Assignment_q2_functions.py | 1,438 | 3.84375 | 4 | #!usr/bin/python
def lcount():
string=raw_input("Enter Your string")
if string:
letters={'upper':'isupper()', 'lower':'abcdefghijklmnopqrstuvwxyz', 'digits':'0123456789', 'space':' '}
let={'uc':[],'lc':[],'spa':[],'di':[],'spe':[]}
count={'u':0,'l':0,'sp':0,'sc':0,'d':0}
for x in string:
if x in letters['upper']:
let['uc'].append(x)
count['u']=count['u']+1
elif x in letters['lower']:
let['lc'].append(x)
count['l']=count['l']+1
elif x in letters['space']:
let['spa'].append(x)
count['sp']=count['sp']+1
elif x in letters['digits']:
let['di'].append(x)
count['d']=count['d']+1
else:
let['spe'].append(x)
count['sc']=count['sc']+1
if len(string)>=8 and count['u']>0 and count['l']>0 and count['sc']>0 and count['d']>0:
print "your password is correct"
else:
print "Not a correct password"
else:
lcount()
lcount() |
3051fe1bd45b615c243a5896f3c28994f6f744a1 | platt607/December19 | /test.py | 1,544 | 4.03125 | 4 | # Write any code you like in here
# Run your code from the 'Run current' menu item above
# Open the README.md file for more instructions
# Import the modules
import sys
import random
import sys
'''
Section 1: Collect customer input
'''
##Collect Customer Data - Part 1
##1) Request Rental code:
#Prompt --> "(B)udget, (D)aily, or (W)eekly rental?"
#rentalCode = ?
rentalCode = input("(B)udget, (D)aily, or (W)eekly rental?\n")
#2) Request time period the car was rented.
#Prompt --> "Number of Days Rented:"
#rentalPeriod = ?
# OR
#Prompt --> "Number of Weeks Rented:"
#rentalPeriod = ?
if rentalCode=="D":
rentalPeriod = input("Number of Days Rented?\n")
elif rentalCode=="W":
rentalPeriod = input("Number of Weeks Rented?\n")
#CUSTOMER DATA CHECK 1
#ADD CODE HERE TO PRINT:
#rentalCode
#rentalPeriod
nthNumbers = []
if stop < N:
print(numbers)
elif N > 0:
nthNumbers = numbers
nthNumbers = [M * i for i in nthNumbers[N::N]]
for j in range (len(numbers)):
if numbers[j]==N:
numbers.insert(j, j)
print(nthNumbers)
print(numbers)
#Calculation Part 1
##Set the base charge for the rental type as the variable baseCharge.
#The base charge is the rental period * the appropriate rate:
#break
else:
for j in range (len(numbers)):
if numbers[j]==N:
for k in numbers:
k = M * numbers[j]
elif numbers[j]==N*2:
for l in numbers:
l = M * numbers[j]
numbers[(N)] = k
numbers[(N)+N] =l
print(numbers) |
a3b8219f6e886f67e10ac77514bc350ef7990ac7 | hungnv132/algorithm | /books/python_cookbook_3rd/ch08_classes_and_objects/08_inteface_and_abstract_class.py | 814 | 3.640625 | 4 | def define_interface_and_abstrace_class():
"""
- Problem: You want to define a class that serves as an interface or abstract
base class from which you can perform type checking and ensure that certain
methods are implemented in subclass.
- Solution: user the `abc` module.
"""
from abc import ABCMeta, abstractmethod
class IStream(metaclass=ABCMeta):
@abstractmethod
def read(self, maxbytes=-1):
pass
@abstractmethod
def write(self, data):
pass
class SocketStream(IStream):
def read(self, maxbytes=-1):
print("Socket Stream is reading data")
def write(self, data):
print("Socket Stream is writing data")
if __name__ == "__main__":
define_interface_and_abstrace_class() |
80240cb2d0d6c060e516fd44946fd7c57f1a3b06 | hungnv132/algorithm | /recursion/draw_english_ruler.py | 1,689 | 4.5 | 4 | """
+ Describe:
- Place a tick with a numeric label
- The length of the tick designating a whole inch as th 'major tick length'
- Between the marks of whole inches, the ruler contains a series of 'minor sticks', placed at intervals of 1/2 inch,
1/4 inch, and so on
- As the size of the interval decrease by half, the tick length decreases by one
+ Base cases(recursion): tick_length = 0
+ Input: inch, major tick length
+ Output:
--- 0
-
--
-
--- 1
-
--
-
--- 2
+ Ideas:
- method draw_tick(...) is only responsible for printing the line of ticks (eg: ---, -, ---, --)
- method interver_v (...) : recursion of draw_tick(...) mehtod until tick_length = 0
- draw_english_ruler(...) is main method
- for loop: for displaying 'inch'
+ References: Data structures and Algorithms in Python by Goodrich, Michael T., Tamassia, Roberto, Goldwasser, Michael
"""
def draw_tick(length , tick_label=''):
line = '-'*int(length)
if tick_label:
line += ' ' + tick_label
print(line)
# interval_version 1
def interval_v1(tick_length):
if tick_length > 1:
interval_v1(tick_length - 1)
draw_tick(tick_length)
if tick_length > 1:
interval_v1(tick_length - 1)
# interval_version 2
def interval_v2(tick_length):
if tick_length > 0:
interval_v2(tick_length - 1)
draw_tick(tick_length)
interval_v2(tick_length - 1)
def draw_english_ruler(inch, major_tick_length):
draw_tick(major_tick_length, '0')
for i in range(1,inch):
interval_v2(major_tick_length - 1)
draw_tick(major_tick_length, str(i))
if __name__ == '__main__':
draw_english_ruler(4, 5)
|
f02cbda65847efff6b096c0ec3973e7656c1d8aa | hungnv132/algorithm | /recursion/reversing_sequence.py | 501 | 3.921875 | 4 |
def _reverse(S, start, stop):
if start < stop:
S[start], S[stop] = S[stop], S[start]
_reverse(S, start+1, stop-1)
def reverse(S):
_reverse(S, 0, len(S)-1)
# using a repetitive structure instead of recurring
def reverse_v2(S):
start, stop = 0,len(S)-1
while start < stop:
S[start], S[stop] = S[stop], S[start]
start, stop = start+1, stop-1
if __name__ == '__main__':
S = [1, 2, 3, 4, 5, 6, 7, 8]
#reverse(S)
reverse_v2(S)
print(S)
|
7240fb816fb1beba9bf76eaf89579a7d87d46d67 | hungnv132/algorithm | /books/python_cookbook_3rd/ch01_data_structures_and_algorithms/07_most_frequently_occurring_items.py | 1,516 | 4.28125 | 4 | from collections import Counter
def most_frequently_occurring_items():
"""
- Problem: You have a sequence of items and you'd like determine the most
frequently occurring items in the sequence.
- Solution: Use the collections.Counter
"""
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
word_counts = Counter(words)
print(word_counts)
# Counter({'eyes': 8, 'the': 5, 'look': 4, 'my': 3, 'into': 3, 'around': 2,
# "don't": 1, 'not': 1, "you're": 1, 'under': 1})
top_three = word_counts.most_common(3)
print(top_three) # [('eyes', 8), ('the', 5), ('look', 4)]
print(word_counts['look']) # 4
print(word_counts['the']) # 5
print(word_counts['into']) # 3
print(word_counts['eyes']) # 8
# if you want to increment the count manually, simply use addition
morewords = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes']
for word in morewords:
word_counts[word] += 1
print(word_counts['eyes']) # 9
# or use update() method
word_counts.update(morewords)
print(word_counts['eyes']) # 10
a = Counter(words)
b = Counter(morewords)
# Combine counts
c = a + b
# Subtract counts
d = a - b
if __name__ == '__main__':
most_frequently_occurring_items() |
d5004f19368c1db3f570771b70d9bd82f94f1a3b | hungnv132/algorithm | /design_patterns/decorator.py | 1,029 | 4.3125 | 4 | def decorator(func):
def inner(n):
return func(n) + 1
return inner
def first(n):
return n + 1
first = decorator(first)
@decorator
def second(n):
return n + 1
print(first(1)) # print 3
print(second(1)) # print 3
# ===============================================
def wrap_with_prints(func):
# This will only happen when a function decorated
# with @wrap_with_prints is defined
print('wrap_with_prints runs only once')
def wrapped():
# This will happen each time just before
# the decorated function is called
print('About to run: %s' % func.__name__)
# Here is where the wrapper calls the decorated function
func()
# This will happen each time just after
# the decorated function is called
print('Done running: %s' % func.__name__)
return wrapped
@wrap_with_prints
def func_to_decorate():
print('Running the function that was decorated.')
func_to_decorate()
print("================")
func_to_decorate() |
28552575419755dab6accc6f1b71a408dc85f106 | hungnv132/algorithm | /basic_python/python_unittest/basic_examples.py | 595 | 3.90625 | 4 | import unittest
class TestStringMethod(unittest.TestCase):
def test_uppper(self):
self.assertEqual('hung'.upper(), 'HUNG')
def test_isupper(self):
self.assertTrue('HUNG'.isupper())
self.assertFalse('Hung'.isupper())
def test_split(self):
s = 'Hello World'
self.assertTrue(s.split(), ['Hello', 'World'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(8)
# RUN: python -m unittest -v basic_examples
# or
if __name__ == '__main__':
unittest.main()
|
e99d73ce04dfc38b413d95a316b163913e8f60a1 | hungnv132/algorithm | /recursion/power.py | 541 | 4.0625 | 4 | """
+ Describe: x^n =?
+ References: Data structures and Algorithms in Python by Goodrich, Michael T., Tamassia, Roberto, Goldwasser, Michael
"""
# Performance: O(n)
def power_v1(x, n):
if n == 0:
return 1
else:
return x * power_v1(x, n-1)
# Performance: O(log(n))
def power_v2(x, n):
if n == 0:
return 1
else:
partial = power_v2(x, n//2)
result = partial * partial
if n % 2 == 1:
result *= x
return result
if __name__ == '__main__':
print(power_v1(2, 3))
print(power_v2(4, 5)) |
41fb69abf407da6702944ec82295f3167246a900 | anuragrana/2019-Indian-general-election | /election_data_analysis.py | 4,064 | 3.65625 | 4 | import json
with open("election_data.json", "r") as f:
data = f.read()
data = json.loads(data)
def candidates_two_constituency():
candidates = dict()
for constituency in data:
for candidate in constituency["candidates"]:
if candidate["party_name"] == "independent":
continue
name = candidate["candidate_name"] + " (" + candidate["party_name"] + ")"
candidates[name] = candidates[name] + 1 if name in candidates else 1
print("List of candidates contesting from two constituencies")
print(json.dumps({name: seats for name, seats in candidates.items() if seats == 2}, indent=2))
def candidate_highest_votes():
highest_votes = 0
candidate_name = None
constituency_name = None
for constituency in data:
for candidate in constituency["candidates"]:
if candidate["total_votes"] > highest_votes:
candidate_name = candidate["candidate_name"]
constituency_name = constituency["constituency"]
highest_votes = candidate["total_votes"]
print("Highest votes:", candidate_name, "from", constituency_name, "got", highest_votes, "votes")
def highest_margin():
highest_margin_count = 0
candidate_name = None
constituency_name = None
for constituency in data:
candidates = constituency["candidates"]
if len(candidates) < 2:
# probably voting was rescinded
continue
candidates = sorted(candidates, key=lambda candidate: candidate['total_votes'], reverse=True)
margin = candidates[0]["total_votes"] - candidates[1]["total_votes"]
if margin > highest_margin_count:
candidate_name = candidates[0]["candidate_name"]
constituency_name = constituency["constituency"]
highest_margin_count = margin
print("Highest Margin:", candidate_name, "from", constituency_name, "won by", highest_margin_count, "votes")
def lowest_margin():
lowest_margin_count = 99999999
candidate_name = None
constituency_name = None
for constituency in data:
candidates = constituency["candidates"]
if len(candidates) < 2:
# probably voting was rescinded
continue
candidates = sorted(candidates, key=lambda candidate: candidate['total_votes'], reverse=True)
margin = candidates[0]["total_votes"] - candidates[1]["total_votes"]
if margin < lowest_margin_count:
candidate_name = candidates[0]["candidate_name"]
constituency_name = constituency["constituency"]
lowest_margin_count = margin
print("Lowest Margin:", candidate_name, "from", constituency_name, "won by", lowest_margin_count, "votes")
def total_votes():
total_votes_count = sum(
[candidate["total_votes"] for constituency in data for candidate in constituency["candidates"]])
print("Total votes casted:", total_votes_count)
def nota_votes():
nota_votes_count = sum(
[candidate["total_votes"] for constituency in data for candidate in constituency["candidates"] if
candidate["candidate_name"] == "nota"])
print("NOTA votes casted:", nota_votes_count)
def seats_won_by_party(party_name):
winning_party = list()
for constituency in data:
candidates = constituency["candidates"]
if len(candidates) < 2:
# probably voting was rescinded
continue
candidates = sorted(candidates, key=lambda candidate: candidate['total_votes'], reverse=True)
if candidates[0]["party_name"] == party_name:
winning_party.append(
candidates[0]["candidate_name"] + " from " + constituency["constituency"] + ". Votes: " + str(
candidates[0]["total_votes"]))
print(len(winning_party))
for l in winning_party:
print(l)
candidates_two_constituency()
candidate_highest_votes()
highest_margin()
lowest_margin()
total_votes()
nota_votes()
seats_won_by_party("indian national congress")
|
e93d3094a36e01dba4266f745ae941b69f66f896 | SIDORESMO/crAssphage | /bin/location_db.py | 4,391 | 4.34375 | 4 | """
Create a location database for our data. This is a SQLite3 database that
has a single table with the following attributes:
0. latitude
1. longitude
2. locality: the name of the city, municipality, or province in utf-8 encoding
3. country: the name of the country in utf-8 encoding
4. ascii_locality: the name of the city, municipality, or province in pure ascii
5. ascii_country: the name of the country in pure ascii
NOTE:
The latitude and longitude are stored as REALs (ie. floats) and so you
may or may not need to convert them from str. I made this decision
because they are floating point numbers and there are some
GIS calculations we could potentially do using them.
"""
import os
import sys
import sqlite3
connection = None
def get_database_connection(dbfile='../data/localities.db'):
"""
Create a connection to the database
"""
global connection
if not connection:
connection = sqlite3.connect(dbfile)
return connection
def get_database_cursor(conn=None):
"""
Connect to the database and get a cursor
:param conn: the optional connection. We will make it if not provided
"""
if not conn:
conn = get_database_connection()
return conn.cursor()
def create_database(cursor=None):
"""
Create the database tables
:param cursor: the database cursor. If not provided we'll make one and return it
"""
if not cursor:
cursor = get_database_cursor()
cursor.execute('''CREATE TABLE location (latitude real, longitude real, locality text, country text, ascii_locality text, ascii_country text)''')
get_database_connection().commit()
return cursor
def save_location(latitude, longitude, locality, country, ascii_locality, ascii_country, cursor=None):
"""
Insert something into the database
:param latitude: the latitude in decimal degrees (signed float)
:param longitude: the longitude in decimal degrees (signed float)
:param locality: the town or metropolitan area in utf-8 text
:param country: the country in utf-8
:param ascii_locality: the locality in ascii format
:param ascii_country: the country in ascii format
:param cursor: the database cursor. If not provided we'll make one. We return this
"""
if not cursor:
cursor = get_database_cursor()
# first check to see if it exists
cursor.execute("select * from location where latitude=? and longitude=?", (latitude, longitude))
result = cursor.fetchone()
if result:
sys.stderr.write("We already have an entry for {}, {}: {}, {}\n".format(result[0], result[1], result[4], result[5]))
return cursor
cursor.execute("insert into location values (?, ?, ?, ?, ?, ?)", (latitude, longitude, locality, country, ascii_locality, ascii_country))
get_database_connection().commit()
return cursor
def get_by_latlon(latitude, longitude, cursor=None):
"""
Get the location based on the latitude and longitude
:param latitude: the latitude in decimal degrees (signed float)
:param longitude: the longitude in decimal degrees (signed float)
:param cursor: the db cursor. We can get this
:return : the array of all data
"""
if not cursor:
cursor = get_database_cursor()
cursor.execute("select * from location where latitude=? and longitude=?", (latitude, longitude))
return cursor.fetchone()
def get_by_ascii(ascii_locality, ascii_country, cursor=None):
"""
Get the lat lon based on the ascii location
:param ascii_locality: the locality in ascii format
:param ascii_country: the country in ascii format
:return : the array of all the data
"""
if not cursor:
cursor = get_database_cursor()
cursor.execute("select * from location where ascii_locality=? and ascii_country=?", (ascii_locality, ascii_country))
return cursor.fetchone()
def get_by_locale(locality, country, cursor=None):
"""
Get the lat lon based on the ascii location
:param locality: the locality in ascii format
:param country: the country in ascii format
:return : the array of all the data
"""
if not cursor:
cursor = get_database_cursor()
cursor.execute("select * from location where locality=? and country=?", (locality, country))
return cursor.fetchone()
|
535a354eedfbd2326a5f9b5291625503cff16d67 | SIDORESMO/crAssphage | /bin/cophenetic.py | 2,213 | 3.546875 | 4 | """
Read a cophenetic matrix
"""
import os
import sys
import argparse
import gzip
def pairwise_distances(matrixfile):
"""
Read the matrix file and return a hash of all distances
:param treefile: The cophenetic matrix file to read
:return: a dict of each entry and its distances
"""
global verbose
distances = {}
f = None
if matrixfile.endswith('.gz'):
f = gzip.open(matrixfile, 'rt')
else:
f = open(matrixfile, 'r')
l = f.readline()
ids = l.rstrip().split("\t")
for i,name in enumerate(ids):
if i == 0:
continue
distances[name] = {}
for l in f:
data = l.rstrip().split("\t")
for i,dist in enumerate(data):
if i == 0:
continue
distances[data[0]][ids[i]] = float(dist)
distances[ids[i]][data[0]] = float(dist)
f.close()
return distances
def closest_dna_dist(matrixfile):
"""
Read the matrix file and get the id of the point with the closest distance that is not ourself
:param treefile: The cophenetic matrix file to read
:return: a dict of a node and its closest leaf
"""
global verbose
distances = {}
f = None
if matrixfile.endswith('.gz'):
f = gzip.open(matrixfile, 'rt')
else:
f = open(matrixfile, 'r')
l = f.readline()
ids = l.rstrip().split("\t")
for i,name in enumerate(ids):
if i == 0:
continue
distances[name] = {}
for l in f:
data = l.rstrip().split("\t")
for i,dist in enumerate(data):
if i == 0:
continue
distances[data[0]][ids[i]] = float(dist)
distances[ids[i]][data[0]] = float(dist)
closest = {}
for d in distances:
closest[d] = {}
for k in sorted(distances[d], key=distances[d].get):
if k == d:
continue
closest[d][k] = distances[d][k]
break
return closest
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="")
parser.add_argument('-f', help='')
parser.add_argument('-v', help='verbose output')
args = parser.parse_args() |
2f3534e15f5a56418438272837b0cbad3c461d9d | SIDORESMO/crAssphage | /bin/count_sequences.py | 689 | 3.6875 | 4 | """
Count the abundance of sequences in a fasta file
"""
import os
import sys
import argparse
from collections import Counter
from roblib import read_fasta
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Count the abundance of sequences in a fasta file")
parser.add_argument('-f', help='fasta file', required=True)
parser.add_argument('-v', help='verbose output', action="store_true")
args = parser.parse_args()
ids = read_fasta(args.f)
lowercaseids = {k: v.lower() for k, v in ids.items()}
seqs = Counter(lowercaseids.values())
counts = Counter(seqs.values())
for k,v in sorted(counts.items()):
print(f"{k}\t{v}")
|
cb64e41f14386d24d6d928f6b8ce21e4f4bcc5f5 | 1505069266/python-study | /day7/缺省参数.py | 275 | 3.640625 | 4 | # 调用函数时,缺省的函数如果没有传入,则被认为是默认值,下例会默认打印的age,如果没有age传入
def main(name,age = 18):
# 打印任何传入的字符串
print("name=%s"%name)
print("age=%d"%age)
main("朱晓乐")
main("郑璇",24) |
fe9b66a099c25bf54d095202059736826b12a219 | 1505069266/python-study | /day9/面向对象.py | 658 | 3.625 | 4 | # 面向过程容易被初学者接受,其往往用一段长代码来实现制定功能,开发过程的思路是将数据与函数按照执行的逻辑顺序组织在一起,数据与函数分开考虑
# 面向对象:将数据与函数绑定到一起,进行封装,这样能够快速的开发程序,减少了重复代码的重写过程
def 发送邮件(内容):
# 发送邮件提醒
连接邮箱服务器
发生邮件
关闭连接
while True:
if cpu利用率 > 90%:
发送邮件("CPU报警)
if 键盘利用率 > 90%:
发送邮件("键盘报警")
if 内容占用 > 90%:
发送邮件("内存报警) |
f41a55e4ca0d385fa4de53d022888e1961718f55 | 1505069266/python-study | /day7/名片管理系统函数版.py | 1,788 | 3.9375 | 4 | # 用来储存名片
lists = []
# 1.打印功能提示
def print_menu():
print("="*30)
print(" 名片管理系统 V1.0.0")
print(" 1. 添加一个新的名片")
print(" 2. 删除一个名片")
print(" 3. 修改一个名片")
print(" 4. 查询一个名片")
print(" 5. 退出系统")
print("="*30)
def add_new_card():
"""这是用来增加名片功能的方法"""
new_name = input("请输入新的名字:")
new_weixin = input("请输入新的QQ:")
new_qq = input("请输入新的微信:")
new_addr = input("请输入新的住址:")
# 定义一个新的字典
new_info = {}
new_info["name"] = new_name
new_info["weixin"] = new_weixin
new_info["qq"] = new_qq
new_info["addr"] = new_addr
global lists
lists.append(new_info)
print(lists)
help(add_new_card)
print_menu()
# 2.获取用户的输入
# 3.根据用户的数据执行相应的功能
while True:
num = int(input("请输入操作序号:"))
if num == 1:
add_new_card()
elif num == 2:
pass
elif num == 3:
pass
elif num == 4:
find_name = input("请输入要查找的姓名:")
find_flag = 0
for temp in list:
if find_name == temp["name"]:
print("%s\t%s\t%s\t%s"%(temp["name"],temp["qq"],temp["weixin"],temp["addr"]))
find_flag = 1 #表示找到了
break #跳出循环
if find_flag == 0:
print("查无此人")
pass
elif num == 5:
print("姓名\t\tQQ\t\t微信\t\t住址")
for temp in list:
print("%s\t%s\t%s\t%s"%(temp["name"],temp["qq"],temp["weixin"],temp["addr"]))
elif num == 6:
break
else:
print("输入有误,请重新输入")
|
b4df6fe80ec75894b86504a9cfd03dc9d54da50b | spconger/CardGamePython | /card.py | 2,010 | 4.09375 | 4 | #Card
'''
This class represents a playing care. It has a rank and suit.
The rank is a number between 1 and 13, 1 being an ace and 13
being a king. The value is not set because that depends upon
the game context, though the getValue() method, if called
assigns the usually assumed values.
The suit is generally Hearts, clubs, diamonds
and spades,and is passed in via a single character.
The suit and the rank are passed in with the constructor.
The getSuite() method takes the character and translates it
into the complete name for the suit
The string method translates the suite and the rank
into the usual name of the card such as 'ace of spaces'
or 'queen of hearts.'
'''
class Card:
def __init__(self, rank, suit):
self.rank=rank
self.suit=suit
self.value=0
#return the rank
def getRank(self):
return self.rank
#return the suit
def getSuit(self):
return self.suit
#get the play value of the card
def getValue(self):
if self.rank > 10:
self.value=10
else:
self.value=self.rank
return self.value
#get the suite name
def getSuitName(self):
self.su=""
if self.suit =="d":
self.su="diamonds"
elif self.suit=="h":
self.su="hearts"
elif self.suit=="s":
self.su="spades"
else:
self.su ="clubs"
return self.su
#use the rank and suit to return the name of the card.
def __str__(self):
if self.rank >1 and self.rank< 11:
self.name=str(self.rank) + " of " + self.getSuit()
if self.rank==1:
self.name="the ace of " + self.getSuitName()
if self.rank==11:
self.name="the jack of " + self.getSuitName()
if self.rank==12:
self.name="the queen of " + self.getSuitName()
if self.rank==13:
self.name="the king of " + self.getSuitName()
return self.name |
dd9f51c988dfb236495b7e0c296665e333a54e52 | yylong711/shixun | /jieba分词/play_pickle.py | 203 | 3.5625 | 4 | import pickle
class A:
def __init__(self):
self.s=3
def add(self):
self.s+=2
a=A()
a.add()
result=pickle.dumps(a)
print(result)
aa=pickle.loads(result)
print(aa.s
)
|
9f75bdbd937e01d95d48c30411170658a939bbf2 | renarsuurpere/prog_alused | /2/yl1.py | 110 | 3.59375 | 4 | kord = int(input("Sisestage mitu korda äratada: "))
for k in range(1, kord + 1):
print("Tõuse ja sära") |
52dae5211d71f556f5794b6e39776235a4f196a8 | bluish3101/primeirostestes | /teste_random.py | 102 | 3.609375 | 4 | lista = []
for c in range(0,10):
lista.append (int(input('Digite o número: ')) )
print(lista) |
fd258b407871d2879cde7a88fcbd60bf419f9136 | georgedimitriadis/themeaningofbrain | /ExperimentSpecificCode/_2018_Chronic_Neuroseeker_TouchingLight/Common_functions/csv_manipulation_funcs.py | 2,913 | 3.9375 | 4 |
import csv
from os import path
import pandas as pd
import numpy as np
def find_number_of_frames_from_video_csv(video_csv_file):
"""
Get the number of frames the camera collected (including the frames that were dropped from the Video.avi file)
using the Video.csv file information
:param video_csv_file: The full path to the Video.csv
:return: The number of frames
"""
frame_numbers = []
with open(video_csv_file, newline='') as csvfile:
video_csv_reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in video_csv_reader:
frame_numbers.append(row[1])
return int(frame_numbers[-1]) - int(frame_numbers[0]) + 1
def video_csv_as_dataframe(video_csv_file):
"""
Turns the Video.csv file into a data frame with columns = Date Hour Minute Second FrameAdded and FrameNumber.
The FrameNumber column is the frame number given by the camera and takes into account any dropped frames
:param video_csv_file: the Video.csv file
:return: The DataFrame
"""
video_record = pd.read_csv(video_csv_file, sep='-|T|:|\+|00 ', engine='python', header=None)
video_record.columns = ['Year', 'Month', 'Day', 'Hour', 'Minute', 'Second', 'FrameAdded', 'Nothing', 'FrameNumber']
video_record = video_record.drop('Nothing', axis=1)
return video_record
def get_true_frame_array(data_folder):
"""
Returns an array with length the number of frames in the video.avi and each element the camera frame number that
corresponds to this video frame.
\n
So if true_frame_index[5] = 8 that means that the 5th frame of the video.avi
corresponds to the 8th frame captured by the camera (which means there had been 3 frames dropped from the video).
:param data_folder: The folder that the Video.csv file is in
:return: The true_frame_index
"""
video_csv_file = path.join(data_folder, 'Video.csv')
video_record = video_csv_as_dataframe(video_csv_file)
true_frame_index = np.array((video_record['FrameNumber'] - video_record['FrameNumber'].iloc[0]).tolist())
return true_frame_index
def create_events_from_events_csv(csv_folder):
"""
Under construction
:param csv_folder:
:return:
"""
events_csv_file = path.join(csv_folder, 'Events.csv')
date_time = []
event_name = []
event_info = []
with open(events_csv_file, newline='') as csvfile:
events_csv_reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in events_csv_reader:
date_time.append(row[0])
event_name.append(row[1])
event_info.append(row[2])
def get_rat_positions_from_bonsai_image_processing(csvfile):
"""
Under construction
:param csvfile:
:return:
"""
positions_df = pd.read_csv(csvfile, delim_whitespace=True )
positions_df.columns = ['Frame', 'Brother XY', 'Recorded XY']
|
08bead65e08b3db80c7760dc04e53802932be5b2 | matyh/scrabble_cheat | /bin/wordlist_length.py | 1,590 | 3.59375 | 4 | from itertools import permutations
with open('../docs/sowpods.txt', 'r') as word_file:
word_file = word_file.read().lower()
scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10
}
word_list = word_file.split('\n') # list of all possible words
rack = raw_input('Type your letters: ').lower() # user letters in lowercase
# # my solution (super slow)
# # find all words combinations comprising of user letters
# combinations = []
# for n in range(len(rack) + 1):
# for p in permutations(rack, n):
# if p is not ():
# combinations.append(''.join(p))
# combinations = set(combinations) # remove duplicates
# # list only viable words from reference word_list
# words = []
# for word in combinations:
# if word in word_list:
# words.append(word)
# different solution (fast)
rack = list(rack)
words = []
for word in word_list:
letters = rack[:]
for i in range(len(word)):
if word[i] in letters:
letters.remove(word[i])
if i == len(word) - 1:
words.append(word)
else:
break
# common part of solutions
# assign scores to words
word_dict = {}
for item in words:
word_dict[item] = len(item)
# print words sorted by their score
for key in sorted(word_dict, key=word_dict.get, reverse=True):
print "%s: %i" % (key, word_dict[key])
# print len(word_dict)
|
53603c7a810e6e521c1d74e7cf13634e34ed02b8 | AuroraBoreas/python_advanced_tricks | /py_ad_04_trick.py | 182 | 3.765625 | 4 | # Python >= 3.7
from dataclass import dataclass
@dataclass
class Card:
rank: str
suit: str
card1 = Card("Q", "hearts")
print(card1 == card1)
print(card1.rank)
print(card1)
|
2d1041ac01853c9bd6bd8092c50595db5eb787fd | AuroraBoreas/python_advanced_tricks | /python-06-expert/python_05_gen.py | 511 | 3.640625 | 4 | def g(n):
for i in range(n):
yield i
# result = g(5)
# print(next(result))
# print(next(result))
# print(next(result))
# print(next(result))
# print(next(result))
### generator not only yield result, but yiled 'control'
for i in g(10):
print(i)
def first():
print("first")
def second():
print("second")
def last():
print("last")
def api():
first()
yield
second()
yield
last()
# this api must be sequential first -> second -> last
|
0f4be732d8717e1cc46b09e6b5a6edb98cf61b29 | AuroraBoreas/python_advanced_tricks | /python-05-flntPy-Review/fpy_33_operator.py | 1,892 | 3.96875 | 4 | ### start functional programming using operator module
import operator
import itertools
fmt = "\n{:-^50}"
# some iterable. fractal essences calculation
a = range(10, 1, -1)
print(fmt.format("simple usage"))
# get sum
ttl = itertools.accumulate(a, lambda x, y: x + y)
print(list(ttl))
# or alternative
ttl = itertools.accumulate(a, operator.add)
print(list(ttl))
# operator.itemgetter(), operator.attrgetter()
# more examples
metro_areas = [
('Tokyo','JP',36.933,(35.689722,139.691667)),
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
]
# operator.itemgetter(index) returns iterable[index]
# it's similar with lambda: seq: seq[index]
print(fmt.format("sorting based on population(index2)"))
for city in sorted(metro_areas, key=operator.itemgetter(2)):
print(city)
# if passing more paramters to operator.itemgetter() ...
print(fmt.format("passing multiple indexes(i.e 2 indexes)"))
city_name = operator.itemgetter(1, 0)
for city in sorted(metro_areas):
print(city_name(city))
# operator.attrgetter(fields) ...
import collections
Latlong = collections.namedtuple('Latlong', 'Lat Lng')
# you can't do nested tuple inside a namedtuple...
# City = collections.namedtuple('City', 'Name short pop (lat., lng.)') # ValueError
City = collections.namedtuple('City', 'name short pop latlong')
redim_metro_areas = [City(name, cc, pop, Latlong(lat, lng))
for name, cc, pop, (lat, lng) in metro_areas
]
print(fmt.format("operator.attrgetter()..."))
# for city in redim_metro_areas:
# print(city)
name_lat = operator.attrgetter('name', 'latlong.Lat')
for city in sorted(redim_metro_areas, key=operator.attrgetter('latlong.Lng')):
print(name_lat(city)) |
166da2f7107c017ec2283b27aeb5b2c924f01e8e | AuroraBoreas/python_advanced_tricks | /python-06-expert/python_04_dec.py | 690 | 3.625 | 4 | ### decorator in Python
import time
def activate(flag=True): # decorator factory
def timer(func): # true decoractor
def inner(*a, **kw): # decorated function
if flag:
start = time.perf_counter()
result = func(*a, **kw)
end = time.perf_counter()
print("elapsed: {}".format(end - start))
return result
else:
return func(*a, **kw)
return inner
return timer
@activate(False)
def add(x, y):
return x + y
@activate(True)
def subs(x, y):
return x - y
a = add(10, 1000)
print(a)
a = subs(10, 1000)
print(a)
|
6f59f5ba43ff2a6dfdcfdca44e8f3c13e5fcda0f | rontou2/Sprint-Challenge--Graphs | /graph_social_network/social.py | 2,240 | 3.640625 | 4 | import random
names = ["bob","steve","dave","zorg, destroyer of worlds","fred","greg","mark"]
class User:
def __init__(self, name):
self.name = name
class SocialGraph:
def __init__(self):
self.lastID = 0
self.users = {}
self.friendships = {}
def addFriendship(self, userID, friendID):
if userID == friendID:
print("WARNING: You cannot be friends with yourself")
elif friendID in self.friendships[userID] or userID in self.friendships[friendID]:
print("WARNING: Friendship already exists")
else:
self.friendships[userID].add(friendID)
self.friendships[friendID].add(userID)
def addUser(self, name):
self.lastID += 1 # automatically increment the ID to assign the new user
self.users[self.lastID] = User(name)
self.friendships[self.lastID] = set()
def populateGraph(self, numUsers, avgFriendships):
self.lastID = 0
self.users = {}
self.friendships = {}
ranges = len(names)-1
copy = numUsers
while copy > 0:
self.addUser(names[random.randint(0,ranges)])
copy = copy - 1
# Create friendships
copy = numUsers
friendNums = list()
high,low = avgFriendships,avgFriendships
if avgFriendships%2 == 1:
friendNums.append(avgFriendships)
copy = copy - 1
while low > 1:
low = low -1
high = high +1
i = 0
while copy/2 > i:
num = random.randint(low,high)
if num > avgFriendships:
friendNums.append(num)
friendNums.append(num-avgFriendships)
elif num == avgFriendships:
friendNums.append(num)
friendNums.append(num)
else:
friendNums.append(num)
friendNums.append(num+avgFriendships)
i = i + 1
length = len(self.users)
for j in range(1,length+1):
already_added = self.friendships[j]
for k in range(0,friendNums.pop(0)):
f = random.randint(1,length)
while f == j or f in already_added:
f = random.randint(1,length)
self.addFriendship(j,f)
already_added.add(f)
def getAllSocialPaths(self, userID):
visited = {} # Note that this is a dictionary, not a set
# !!!! IMPLEMENT ME
return visited
if __name__ == '__main__':
sg = SocialGraph()
sg.populateGraph(10,2)
print(sg.friendships)
connections = sg.getAllSocialPaths(1)
print(connections)
|
a5de25231cef8caf3e2112c8f2168fe179e267a7 | smorzhov/adventofcode2017 | /02_corruption_checksum.py | 1,046 | 3.53125 | 4 | from os import path
PWD = path.dirname(path.realpath(__file__))
FILE_NAME = 'input.txt'
def read_input(file_name=path.join(PWD, FILE_NAME)):
content = []
with open(file_name) as file:
for line in file:
content.append(list(map(int, line.split())))
return content
def find_checksum(data, part=1):
def part_1(row):
return max(row) - min(row)
def part_2(row):
sorted_row = sorted(row)
for i in range(len(sorted_row) - 1, 1, -1):
for j, _ in enumerate(sorted_row):
if j < i and sorted_row[i] % sorted_row[j] == 0:
return sorted_row[i] / sorted_row[j]
return
solution = 0
if part == 1:
for row in data:
solution += part_1(row)
else:
for row in data:
solution += part_2(row)
return solution
def main():
data = read_input()
print('Part 1: ' + str(find_checksum(data)))
print('Part 2: ' + str(find_checksum(data, 2)))
if __name__ == '__main__':
main() |
cc94542945d9391098c4583819ace83a81ed1f02 | matchalunatic/honkhonk | /honkhonk | 891 | 3.546875 | 4 | #!/usr/bin/env python3
import sys
import re
import string
GOOSE_EMOJI = '🦢'
has_cap = lambda x: x[0] in list(chr(a) for a in range(ord('A'), ord('Z')))
LETTERS = string.ascii_letters
UPPERCASE_LETTERS = string.ascii_uppercase
def honkhonk(stream):
i = 0
for line in stream:
prev_is_letter = False
o = ""
line = line.rstrip()
for c in line:
if c not in LETTERS:
if prev_is_letter:
o = o[:-2] + 'nk'
o += c
prev_is_letter = False
if c in LETTERS:
if not prev_is_letter:
if c in UPPERCASE_LETTERS:
o += 'H'
else:
o += 'h'
else:
o += 'o'
prev_is_letter = True
print(o)
honkhonk(sys.stdin)
|
edfb520b99ff35f709065255f6ffbfca8e766d5b | paulmburu08/Lockpass | /user_test.py | 1,340 | 3.875 | 4 | import unittest
from user import User
class UserTest(unittest.TestCase):
def setUp(self):
'''
Set up method to run before each test cases.
'''
self.new_user = User('Paul','Mburu','paulmburu08@gmail.com','python34562')
def tearDown(self):
'''
tearDown method that does clean up after each test case has run.
'''
User.login_details = []
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_user.first_name,'Paul')
self.assertEqual(self.new_user.last_name,'Mburu')
self.assertEqual(self.new_user.email,'paulmburu08@gmail.com')
self.assertEqual(self.new_user.password,'python34562')
def test_save_account(self):
'''
test_save_account test case to test if the new_user object is saved into
the login_details
'''
self.new_user.save_account()
self.assertEqual(len(User.login_details),1)
def test_delete_account(self):
'''
test_delete_contact to test if we can remove an account from our login_details
'''
self.new_user.save_account()
self.new_user.delete_account()
self.assertEqual(len(User.login_details),0)
if __name__ == '__main__':
unittest.main()
|
10bdaba3ac48babdc769cb838e1f7f4cdef66ae9 | nikitaagarwala16/-100DaysofCodingInPython | /MonotonicArray.py | 705 | 4.34375 | 4 | '''
Write a function that takes in an array of integers and returns a boolean representing whether the array is monotonic.
An array is said to be monotonic if its elements, from left to right, are entirely non-increasing or entirely non -decreasing.
'''
def monoArray(array):
arraylen=len(array)
increasing=True
decreasing=True
for i in range(arraylen-1):
if(array[i+1]>array[i]):
decreasing=False
if(array[i+1]<array[i]):
increasing=False
if not increasing and not decreasing:
return False
return increasing or decreasing
if __name__ == "__main__":
array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001]
print(monoArray(array))
|
be012b97acfa6aff0075c6349da435b4b22f8d12 | gaurav-kay/GitHub-Art | /app.py | 799 | 3.5625 | 4 | from os import system
# accepted date formats: rfc2822 (Mon, 3 Jul 2006 17:18:43 +0200) and iso8601 (2006-07-03 17:18:43 +0200)
def get_commit_hash(op1):
return op1.split(' ')[1]
def draw(dates):
for date in dates:
print(date)
command = 'echo "commit" >> test.txt'
system(command) # number of times
command = 'git add -A'
system(command)
command = 'git commit -m "commit"'
system(command)
# command = r'git log -1'
# op = check_output(command)
# commit_hash = get_commit_hash(op)
command = 'git commit --amend --no-edit --date ' + '\"' + date + '\"'
# format: "Mon 10 Jan 2019 20:19:19 IST"
system(command)
|
5335fe276809fcebf1992c1725b3189fb73cb091 | AntonChernov/luxsoft_task_poland | /token_validator.py | 1,676 | 4.03125 | 4 | import argparse
import itertools
def letters(obj): # separate string to letters
if isinstance(obj, list):
# itertools.chain.from_iterable(obj) --> from ['asd', 'sdf'] to ['asdsdf']
return list(set(itertools.chain.from_iterable(obj))) # from ['asd', 'sdf'] to ['asdsdf'] but the string
# contains only unique letters
elif isinstance(obj, str):
return list(set(obj)) # obj str contains only unique letters
else:
raise ValueError
def validate_token(token_str, input_str):
if len(input_str) < len(token_str):
print(False) # if len of tokens example less then input string no need to check so just return False
else:
tokens = letters(token_str)
inputs = letters(input_str)
if all(elem in tokens for elem in inputs): # if all elements from input we have in tokens so it is good input
# if no bad input
print(True)
else:
print(False)
if __name__ == '__main__':
'''
In program we have 2 two sickles (#8, #22) so in a best case O(n) Worst case O(n^2)
Also about empty string i believe not good solution use "" as valid value.
'''
new_parser = argparse.ArgumentParser()
new_parser.add_argument('-t',
'--tokens',
# action='store_true',
help='Tokens separate by ","')
new_parser.add_argument('-i',
'--inputstr',
# action='store_true',
help='Input str')
args = new_parser.parse_args()
validate_token(args.tokens.split(','), args.inputstr)
|
4dc1099a08a4bcd40eaeba6643a060338e624638 | jjjjooonno/fc_wc | /코드/Week1/b.py | 260 | 3.921875 | 4 | list_ = ['a',3,5]
print(list_[0])
list_.append(7)
print(list_[3])
dic = {'a' : 1, 'b' : 2}
print(dic['a'])
dic.update({'c' : 3})
print(dic['c'])
for item in list_:
print(item)
for index, item in enumerate(list_):
print(str(index)+'th item is'+str(item)) |
64816cb5e3c9e27c1773b76d35ef320bddf5949b | putraeka/python | /arkadiusz-wlodarczyk/11-simple-calculator.py | 606 | 4.0625 | 4 | # Membuat calculator berdasarkan input yang dimasukkan oleh user
menuOption = input("+ Add - Substract * Multiply / divide : ")
first = int (input("Input your first number : "))
second = int (input("Input your second number: "))
if menuOption == '+' :
print(first + second)
elif menuOption == '-' :
print(first - second)
elif menuOption == '*' :
print(first * second)
elif menuOption == '/' :
if second == 0 :
print("Divided by zero, you can't do it!")
else :
print(first / second)
else :
print("You must type one of the following character : +/-/* or /")
|
2696cdcf687d654d2ce468327bd39f2a6196a86b | putraeka/python | /arkadiusz-wlodarczyk/19-list-operations-and-functions.py | 565 | 3.96875 | 4 | """
operasi yang ada di list
len() - length of list
.append - adding on the end of SINGLE element
.extend - extending list by another list
.insert(index, what) - put in
.index(what) - return index of 'what'
.sort(reverse=False) -sort ascending
.sort(reverse=True) - sort descending
.max()
.min()
.count - how many occurence (how many times it shows up)
.pop - pop last element (remove)
.remove - remove first occurence (firt time it shows up)
.clear - clear entire list
.reverse - change the order
"""
list1 = [54, 7, -2, 20,7]
list2 = ["Arkadiusz", "Jacob"]
|
1c0951e02ae8e0298db3bd4c6bd91152e51542f7 | putraeka/python | /arkadiusz-wlodarczyk/23-nested-types.py | 755 | 3.65625 | 4 | # Nested Types
# Digunakan untuk memasukkan data yang banyak dan mirip
# Nested Types sendiri adalah LIST didalam LIST
# Nested LIST juga bisa memuat tuple
"""
Misalkan kita punya beberapa orang dengan tamu
name = "Arkadiusz"
age = 29
sex = "man"
name2 = "Jessica"
age2 = 23
sex2 = "woman"
name3 = "John"
age3 = 32
sex3 = "man"
Tentu ini adalah cara yang tidak baik
Cara yang kedua adalah dengan membuat LIST
person1 = ['Arkadiusz', 29, 'man']
person2 = ['Jessica', 23, 'woman']
person3 = ['John', 32, 'man']
Tapi ada cara yang lebih baik lagi dengan Nested LIST
"""
guestList = [
['Arkadiusz', 29, 'man'],
['Jessica', 23, 'woman'],
['John', 32, 'man']
]
|
7e68f4da3b81c0adee9db128dc3dc706bc6942f4 | rohit-konda/systemcontrol | /systemcontrol/basic_systems.py | 8,219 | 3.65625 | 4 | #!/usr/bin/env python
"""
Class defintions for creating basic feedback control affine systems
"""
import numpy as np
class System:
"""general formulation for a continuous system"""
def __init__(self, x, dt=.1, params=None, t=0):
self.x = x # state
self.t = t # time
self.y = self.output() # output
self.dt = dt # time step
self.params = params # define parameters
# x dot = f(t, x)
def flow(self):
""" dynamics of system """
return self.f()
def f(self):
""" drift term """
pass
def output(self):
""" set output of the system """
pass
def step(self):
""" euler approximation integration"""
self.x += self.flow()*self.dt
self.y = self.output()
self.t += self.dt
def runge_kutta_step(self):
""" RK 4th order approximation integration """
state = np.copy(self.x)
k1 = self.flow()*self.dt
self.x = state + .5*k1
k2 = self.flow()*self.dt
self.x = state + .5*k2
k3 = self.flow()*self.dt
self.x = state + k3
k4 = self.flow()*self.dt
self.x = state + (k1+2*k2+2*k3+k4)/6
self.y = self.output()
self.t += self.dt
def run(self, t):
""" get trajectory from initial value for t time"""
temp_x = self.x
temp_t = self.t
traj = np.zeros((len(self.x), int(t/self.dt)))
for i in range(len(traj.T)):
traj.T[i] = self.x
self.step()
self.x = temp_x
self.t = temp_t
self.y = self.output()
return traj
class ControlSystem(System):
""" general control affine system """
def __init__(self, x, dt=.1, params=None, t=0):
System.__init__(self, x, dt, params, t)
# x dot = f(t, x) + g(t, x)*u(t, x)
def flow(self):
""" dynamics of control system """
return self.f() + np.dot(self.g(), self.u())
def g(self):
""" control affine term"""
pass
def u(self):
""" input """
pass
class Linear(ControlSystem):
""" time invariant linear system """
def __init__(self, x, A, B, C, D):
ControlSystem.__init__(self, x)
self.A = A
self.B = B
self.C = C
self.D = D
def f(self):
""" linear system """
return np.dot(self.A, self.x)
def g(self):
""" control affine term"""
return self.B
def output(self):
""" y = Cx + Du """
return np.dot(self.C, self.x) + np.dot(self.D, self.u())
class SingleIntegrator(ControlSystem):
""" single integrator control system with x, y """
def __init__(self, x):
ControlSystem.__init__(self, x)
def f(self):
""" single integrator dynamics """
xdot = 0
ydot = 0
return np.array([xdot, ydot]).T
def g(self):
""" control affine term"""
return np.identity(2)
def u(self):
""" 2 inputs: v_x , v_y """
return np.array([0, 0])
class DoubleIntegrator(ControlSystem):
""" double integrator control system with x, y, vx, and vy """
def __init__(self, x):
ControlSystem.__init__(self, x)
def f(self):
""" double integrator dynamics """
xdot = self.x[2]
ydot = self.x[3]
vxdot = 0
vydot = 0
return np.array([xdot, ydot, vxdot, vydot]).T
def g(self):
""" control affine term"""
return np.array([[0, 0, 1, 0], [0, 0, 0, 1]]).T
def u(self):
""" 2 inputs: acc_x , acc_y """
return np.array([0, 0])
class SingleUnicycle(ControlSystem):
""" unicycle control system with states x, y, th """
def __init__(self, x):
ControlSystem.__init__(self, x)
def f(self):
""" single unicycle dynamics """
return np.array([0, 0, 0]).T
def g(self):
""" control affine term"""
return np.array([[np.cos(self.x[2]), np.sin(self.x[2]), 0], [0, 0, 1]]).T
def step(self):
""" step function that wraps theta """
ControlSystem.step(self)
self.x[2] = np.arctan2(np.sin(self.x[2]), np.cos(self.x[2]))
def u(self):
""" 2 inputs: velocity, angular velocity """
return np.array([0, 0])
class DoubleUnicycle(ControlSystem):
""" double integrator unicycle control system with states x, y, v, th """
def __init__(self, x):
ControlSystem.__init__(self, x)
def f(self):
""" double unicycle dynamics """
xdot = self.x[2]*np.cos(self.x[3])
ydot = self.x[2]*np.sin(self.x[3])
vdot = 0
thdot = 0
return np.array([xdot, ydot, vdot, thdot]).T
def g(self):
""" control affine term"""
return np.array([[0, 0, 1, 0], [0, 0, 0, 1]]).T
def step(self):
ControlSystem.step(self)
self.x[3] = np.arctan2(np.sin(self.x[3]), np.cos(self.x[3]))
def u(self):
""" 2 inputs: acceleration, angular velocity """
return np.array([0, 0])
class NetworkSystem(System):
""" Parent class for systems with interactions """
def __init__(self, x, sys_list):
System.__init__(self, x)
self.sys_list = sys_list
class SimulationSystem(ControlSystem):
""" Parent class for generating traces for desired input """
def __init__(self, x, gamma, simx=None):
ControlSystem.__init__(self, x)
self.gamma = gamma # fake feedback controller
self.simx = simx # simulated state
self.simt = 0 # simulated time
self.simdt = self.dt # simulated dt
def gamma_flow(self, x):
""" xdot for a given state """
tempx = self.x.copy()
self.x = x
xdot = self.f() + np.dot(self.g(), self.gamma(x))
self.x = tempx
return xdot
def gamma_step(self):
""" flow for simx using gamma """
self.simx += self.gamma_flow(self.simx)*self.simdt
self.simt += self.simdt
def reset(self, simx):
""" reset simulated system """
self.simx = simx
self.simt = 0
class FeedbackController(ControlSystem):
""" Parent class for feedback control """
def __init__(self, x):
ControlSystem.__init__(self, x)
def feedback(self, x, isStep=False):
""" return controller for given state """
if isStep:
self.step()
self.x = x
self.t += self.dt
return self.u()
class Discrete:
"""general formulation for a discrete system"""
def __init__(self, x, params=None, n=0):
self.x = x # state
self.n = n # time step
self.y = self.output() # output
self.params = params # define parameters
# x^+ = f(t, x, u(t, x))
def f(self):
""" define dynamics of discrete function"""
pass
def output(self):
""" set output of the system """
pass
def step(self):
""" euler approximation integration"""
self.x = self.f()
self.y = self.output()
self.n += 1
def run(self, N):
""" get trajectory from initial value for N steps"""
temp_x = self.x
temp_n = self.n
traj = np.zeros((len(self.x), N))
for i in range(len(traj.T)):
traj.T[i] = self.x
self.step()
self.x = temp_x
self.n = temp_n
self.y = self.output()
return traj
def u(self):
""" input """
pass
class DiscreteControl(Discrete):
""" general control affine discrete system"""
def __init__(self, x, params=None, n=0):
Discrete.__init__(self, x, params, n)
# x^+ = f(t, x) + g(t, x)*u(t, x)
def flow(self):
""" dynamics of control system """
return self.f() + np.dot(self.g(), self.u())
def g(self):
""" control affine term"""
pass
|
f9f970c1c2d316b760035fb8942de4882d06fdc0 | rohit-konda/systemcontrol | /examples/obstacle_avoidance_CBF.py | 3,944 | 3.96875 | 4 | #!/usr/bin/env python
"""
Tutorial example for using barrier functions for collision avoidance
Environment includes a unicycle model of a car,
and some obstacles that the car has to avoid
"""
import numpy as np
from systemcontrol.basic_systems import SingleUnicycle
from systemcontrol.CBF_systems import FeasibleCBF
from systemcontrol.animate import Animate, Actor
import matplotlib.pyplot as plt
from matplotlib import patches
class SmartCar(FeasibleCBF, SingleUnicycle, Actor):
""" car example that is programmed to avoid
certain placed obstacled and go in a circle """
def __init__(self, x, obstacles, r):
self.obstacles = obstacles # list of obstacles
self.r = r # radius of obstacle
self.v = .4 # velocity constraint for barrier
self.w = 1 # maximum angular velocity
self.Ds = .5 # safety distance buffer between COM and obstacle
self.p = 3 # radius of limit cycle to converge to
FeasibleCBF.__init__(self, x, self.seth(), self.seta())
SingleUnicycle.__init__(self, x)
Actor.__init__(self)
def nominal(self):
"""
controller to go in a circle
set desired theta to converge to limit cycle
"""
norm = np.minimum((self.x[0]**2 + self.x[1]**2)**.5, 2*self.p)
td = np.arctan2(self.x[1], self.x[0]) + norm/self.p*np.pi/2
u = np.array([self.v - .2, np.sin(td - self.x[2])])
return u
def input_cons(self):
""" actuation constraints """
n = np.shape(self.g())[1]
Ca1 = np.identity(n, dtype='float32')
Ca2 = -np.identity(n, dtype='float32')
Ca = np.hstack((Ca1, Ca2))
ba = np.array([self.v, -self.w, -2, -self.w])
# constraints are self.v <= v <= 2, -self.w <= w <= -self.w
return (Ca, ba)
def seth(self):
""" set up barrier functions """
listofh = [] # list of barrier function constraints
v = self.v
w = self.w
for obs in self.obstacles:
# create barrier functions
# applied a nested lambda trick to get scopes to work out
listofh.append((lambda y:
lambda x: ((x[0] - y[0] - v/w*np.sin(x[2]))**2 +
(x[1] - y[1] + v/w*np.cos(x[2]))**2)**.5 -
(v/w + self.r + self.Ds))(obs))
return listofh
def seta(self):
""" alpha functions f(x) = x^3"""
return [lambda x: x**3 for obs in obstacles]
def uni_draw(self):
""" function to draw a triangle representing the unicycle model"""
w = .3 # width
le = .75 # length
th = self.x[2] # direction
# points for triangle for plotting
offset = np.array([le/2*np.cos(th), le/2*np.sin(th)]).T
p1 = self.x[0:2] + np.array([-w*np.sin(th), w*np.cos(th)]).T-offset
p2 = self.x[0:2] + np.array([w*np.sin(th), -w*np.cos(th)]).T-offset
p3 = self.x[0:2] + np.array([le/2*np.cos(th), le/2*np.sin(th)]).T
return [p1, p2, p3]
def draw_setup(self, axes):
""" draw self """
self.drawings.append(plt.Polygon(xy=self.uni_draw(), color='red'))
def draw_update(self, axes):
""" update position """
self.drawings[0].set_xy(self.uni_draw())
if __name__ == '__main__':
obstacles = [np.array([3, 2]),
np.array([-3, -2]),
np.array([-.5, 2.5])] # obstacles
r = .5 # radius of obstacles
Car = SmartCar(np.array([6, -1, np.pi/2]), obstacles, r) # initialize SmartCar
sys_list = [Car] # set up list of systems that will be plotted
ob_list = [patches.Circle(obs, r) for obs in obstacles] # plot obstacles
animator = Animate(sys_list, ob_list)
animator.animate() # run animation
|
3a690d3c0bc3b56ac34c5b83025d8fd13a6af716 | askariya/seng533_project | /seng533_assign1.py | 10,801 | 3.75 | 4 | import sys
import csv
from collections import defaultdict
def calculateAnswers(csv_file, txt_file):
columns = defaultdict(list) # each value in each column is appended to a list
file = csv_file
reader = csv.DictReader(open(file, newline=""), dialect="excel")
for row in reader:
for (k,v) in row.items(): # go over each column name and value
columns[k].append(v) # append the value into the appropriate list
# print(columns['Time']) # based on column name k
columns['Time'] = [int(i) for i in columns['Time']]
# print(columns['Time'])
# # 4, Part 1
first_val = columns['Time'][0]
last_val = columns['Time'][len(columns['Time'])-1]
time = (last_val - first_val)
print("Total time taken to run tests: " + str(time) + " seconds")
# 4, part 2
prev_value = None
diff_array = []
for value in columns['Time']:
if prev_value is None:
prev_value = value
continue
else:
diff_array.append(value - prev_value)
prev_value = value
diff_array.append(value - prev_value)
print("Mean Sampling Rate:" + str(sum(diff_array)/len(diff_array)))
#4, part 3
#TODO Calculate Utilization for Physical Disk and Processor columns????
print("\n__Utilization for DB__")
#list of disk and processor utilization columns
dp_column_names = ["\PhysicalDisk(_Total)\% Disk Time", "\Processor(0)\% DPC Time",
"\Processor(0)\% Interrupt Time", "\Processor(0)\% Privileged Time", "\Processor(0)\% Processor Time",
"\Processor(0)\% User Time", "\Process(Idle)\% Processor Time"]
print_averages(columns, dp_column_names)
#4, part 4
print("\n__Utilization for Web App Processes__")
#list of Web Server utilization columns
wa_process_cols = ["\\\\isp-01\Process(wHTTPg)\% Privileged Time", "\\\\isp-01\Process(wHTTPg)\% User Time"]
print_averages(columns, wa_process_cols)
print("\n__Utilization for App Processes__")
app_process_cols = [
"\\\\isp-01\Process(server#0)\% Privileged Time", "\\\\isp-01\Process(server#0)\% User Time",
"\\\\isp-01\Process(server#1)\% Privileged Time", "\\\\isp-01\Process(server#1)\% User Time",
"\\\\isp-01\Process(server#2)\% Privileged Time", "\\\\isp-01\Process(server#2)\% User Time",
"\\\\isp-01\Process(server#3)\% Privileged Time", "\\\\isp-01\Process(server#3)\% User Time",
"\\\\isp-01\Process(server#4)\% Privileged Time", "\\\\isp-01\Process(server#4)\% User Time",
"\\\\isp-01\Process(server#5)\% Privileged Time", "\\\\isp-01\Process(server#5)\% User Time",
"\\\\isp-01\Process(server#6)\% Privileged Time", "\\\\isp-01\Process(server#6)\% User Time",
"\\\\isp-01\Process(server#7)\% Privileged Time", "\\\\isp-01\Process(server#7)\% User Time",
"\\\\isp-01\Process(server#8)\% Privileged Time", "\\\\isp-01\Process(server#8)\% User Time",
"\\\\isp-01\Process(server#9)\% Privileged Time", "\\\\isp-01\Process(server#9)\% User Time",
"\\\\isp-01\Process(server#10)\% Privileged Time", "\\\\isp-01\Process(server#10)\% User Time",
"\\\\isp-01\Process(server#11)\% Privileged Time", "\\\\isp-01\Process(server#11)\% User Time",
"\\\\isp-01\Process(server#12)\% Privileged Time", "\\\\isp-01\Process(server#12)\% User Time",
"\\\\isp-01\Process(server#13)\% Privileged Time", "\\\\isp-01\Process(server#13)\% User Time",
"\\\\isp-01\Process(server#14)\% Privileged Time", "\\\\isp-01\Process(server#14)\% User Time",
"\\\\isp-01\Process(server#15)\% Privileged Time", "\\\\isp-01\Process(server#15)\% User Time"
]
# print_averages(columns, app_process_cols)
get_averages(columns, app_process_cols)
print("\n__Utilization for DB Server__")
db_process_cols = ["\Process(db2syscs)\% User Time", "\Process(db2syscs)\% Privileged Time"]
print_averages(columns, db_process_cols)
#5 A) part 1
print("\n__________5) A.1___________")
input_file = open(txt_file,"r")
line_count = -1
total_resp_time = 0
total_conn_time = 0
total_firstbyte_time = 0
total_lastbyte_time = 0
for line in input_file:
if line_count == -1:
line_count = 0
continue
line_count+=1
line = line.split(",")
#[2]Time taken to open connection with server (ms) + [3]Time taken to receive first byte of reply (ms) +
#[4]Time taken to receive last byte of reply (ms)
total_conn_time += float(line[2])
total_firstbyte_time += float(line[3])
total_lastbyte_time += float(line[4])
total_resp_time += (float(line[2]) + float(line[3]) + float(line[4]))
mean_resp_time = total_resp_time/line_count
avg_conn_time = total_conn_time/line_count
avg_firstbyte_time = total_firstbyte_time/line_count
avg_lastbyte_time = total_lastbyte_time/line_count
print("Avg Conn Time: " + str(avg_conn_time))
print("Avg First Byte Time: " + str(avg_firstbyte_time))
print("Avg Last Byte Time: " + str(avg_lastbyte_time))
print("\nMean Response Time: " + str(mean_resp_time))
# 5 A) part 2
req_per_sec = (line_count/11139282.538)*1000
print("Requests/sec: " + str(req_per_sec))
# 5 B)
print("\n__________5) B___________")
do5B()
#6 B)
print("\n__________6) B___________")
total_time = None
num_requests = None
if txt_file == "case1-httperf-detailed-output.txt" and csv_file == "case1-perfmon-data.csv":
total_time = 11064
num_requests = 89602
elif txt_file == "case2-httperf-detailed-output.txt" and csv_file == "case2-perfmon-data.csv":
total_time = 12026
num_requests = 90400
else:
raise Exception("Invalid File Names! Make sure you are using matching CSV and TXT files.")
print("\n__Demand for Web Process__")
get_demands(columns, wa_process_cols, total_time, num_requests)
print("\n__Demand for App Processes__")
get_demands_app(columns, app_process_cols, total_time, num_requests)
print("\n__Demand for DB Process__")
get_demands(columns, db_process_cols, total_time, num_requests)
def print_averages(columns, col_names):
col_total = 0
for col in col_names:
total = 0
count = 0
# try:
# columns[col] = [float(i) for i in columns[col]] #convert values to float
# except Exception as e:
# print(e)
for value in columns[col]:
if value == "":
continue
total += float(value)
count += 1
col_total = col_total + (total/count)
print(col + ": " + str(total/count))
print("Sum: " + str(col_total))
def get_averages(columns, col_names):
prev_col = None
for col in col_names:
total = 0
count = 0
for value in columns[col]:
if value == "":
count += 1
continue
total += float(value)
count += 1
if prev_col == None:
prev_col = total/count
else:
cur_col = total/count
print(col)
print (str(prev_col + cur_col))
prev_col = None
def get_demands(columns, col_names, total_time, num_requests):
col_total = 0
for col in col_names:
total = 0
count = 0
# try:
# columns[col] = [float(i) for i in columns[col]] #convert values to float
# except Exception as e:
# print(e)
for value in columns[col]:
if value == "":
continue
total += float(value)
count += 1
col_total = col_total + (total/count)
# print(col + ": " + str(total/count))
utilization = col_total/100
demand = ((utilization*total_time)/num_requests)*1000
print("Demand: " + str(demand))
def get_demands_app(columns, col_names, total_time, num_requests):
prev_col = None
for col in col_names:
total = 0
count = 0
for value in columns[col]:
if value == "":
count += 1
continue
total += float(value)
count += 1
if prev_col == None:
prev_col = total/count
else:
cur_col = total/count
# print(col)
# print (str(prev_col + cur_col))
utilization = (prev_col + cur_col)/100
demand = ((utilization*total_time)/num_requests)*1000
print(str(demand))
prev_col = None
def do5B():
filenameCase1 = "case1-httperf-detailed-output.txt"
filenameCase2 = "case2-httperf-detailed-output.txt"
input_file = open(filenameCase1,"r")
min_bytes_per_ms = float('inf')
total_bytes_per_ms = 0
line_count = -1
total_resp_time = 0
for line in input_file:
if line_count == -1:
line_count = 0
continue
line_count+=1
line = line.split(",")
resp_time = (float(line[2]) + float(line[3]) + float(line[4]))
total_resp_time += resp_time
total_bytes_per_ms += float(line[6])/resp_time
if float(line[6])/resp_time < min_bytes_per_ms:
min_bytes_per_ms = float(line[6])/resp_time
mean_resp_time = total_resp_time/line_count
print("\nMean Response Time Case1: " + str(mean_resp_time))
print("Mean KB/Sec Case1: " + str(total_bytes_per_ms/line_count))
print("Min KB/Sec Case1: " + str(min_bytes_per_ms))
print("Total Requests: " + str(line_count))
min_bytes_per_ms = float('inf')
mean_bytes_per_ms = 0
input_file = open(filenameCase2,"r")
line_count = -1
total_resp_time = 0
for line in input_file:
if line_count == -1:
line_count = 0
continue
line_count+=1
line = line.split(",")
resp_time = (float(line[2]) + float(line[3]) + float(line[4]))
total_resp_time += resp_time
total_bytes_per_ms += float(line[6])/resp_time
if float(line[6])/resp_time < min_bytes_per_ms:
min_bytes_per_ms = float(line[6])/resp_time
mean_resp_time = total_resp_time/line_count
print("\nMean Response Time Case2: " + str(mean_resp_time))
print("Mean KB/Sec Case2: " + str(total_bytes_per_ms/line_count))
print("Min KB/Sec Case2: " + str(min_bytes_per_ms))
print("Total Requests: " + str(line_count))
def main():
if len(sys.argv) < 3:
print('Usage: ' + sys.argv[0] + ' <csv_file> <txt_file>')
sys.exit(1)
csv_file = sys.argv[1]
txt = sys.argv[2]
calculateAnswers(csv_file, txt)
if __name__ == '__main__':
main() |
867ab00937a707e8f1de468f62b501e0c4019d3d | ganesh-santhanam/Spark | /Spark Basics.py | 6,558 | 3.71875 | 4 | #data is just a normal Python list, containing Python tuples objects
data[0]
len(data) #Length 10000
#Create a dataframe using Sql Context
#DataFrames are ultimately represented as RDDs, with additional meta-data.
dataDF = sqlContext.createDataFrame(data, ('last_name', 'first_name', 'ssn', 'occupation', 'age'))
#Print type
print 'type of dataDF: {0}'.format(type(dataDF))
dataDF.printSchema() #DataFrame's schema
sqlContext.registerDataFrameAsTable(dataDF, 'dataframe') # register the newly created DataFrame as a named table
dataDF.rdd.getNumPartitions() # Prints partitions DataFrame to be split into
newDF = dataDF.distinct().select('*')
newDF.explain(True) #examine the query plan using the explain() function
# Transform dataDF through a select transformation and rename the newly created '(age -1)' column to 'age'
# Because select is a transformation and Spark uses lazy evaluation, no jobs, stages,
# or tasks will be launched when we run this code.
subDF = dataDF.select('last_name', 'first_name', 'ssn', 'occupation', (dataDF.age - 1).alias('age'))
# Let's collect the data
results = subDF.collect()
subDF.show()
subDF.show(n=30, truncate=False) # View 30 rows
display(subDF) #Databricks helper function to get nicer views
print subDF.count() # prints Counts of elements
#Filter Transformation
filteredDF = dataDF.filter(dataDF.age < 10)
filteredDF.show(truncate=False)
filteredDF.count()
#Using UDF with Lambda functions
from pyspark.sql.types import BooleanType
less_ten = udf(lambda s: s < 10 , BooleanType()) # Filtering numbers less than 10
lambdaDF = subDF.filter(less_ten(subDF.age))
lambdaDF.show()
lambdaDF.count()
#Let's collect the even values less than 10
even = udf(lambda s: s % 2 == 0, BooleanType())
evenDF = lambdaDF.filter(even(lambdaDF.age))
evenDF.show()
evenDF.count()
display(filteredDF.take(4)) # return the first 4 elements of the DataFrame.
# Get the five oldest people in the list. To do that, sort by age in descending order.
display(dataDF.orderBy(dataDF.age.desc()).take(5)) #Sort by age in descending order
# Something like orderBy('age'.desc()) would not work, because there's no desc() method on Python string objects
#That's why we needed the column expression
display(dataDF.orderBy('age').take(5)) # Clubbing the expressions
print dataDF.distinct().count() # distinct() filters out duplicate rows, and it considers all columns.
print dataDF.dropDuplicates(['first_name', 'last_name']).count()
#dropDuplicates() is like distinct(), except that it allows us to specify the columns to compare.
#drop() is like the opposite of select() it drops a specifed column from a DataFrame
dataDF.drop('occupation').drop('age').show()
# groupBy() is a transformations. It allows you to perform aggregations on a DataFrame.
# count() is the common aggregation, but there are others (like sum(), max(), and avg()
dataDF.groupBy('occupation').count().show(truncate=False) # Count of Column
dataDF.groupBy().avg('age').show(truncate=False) # Average of column
print "Maximum age: {0}".format(dataDF.groupBy().max('age').first()[0]) # Max
print "Minimum age: {0}".format(dataDF.groupBy().min('age').first()[0]) # Minimum
'''
sample() transformation returns a new DataFrame with a random sample of elements from the dataset
withReplacement argument specifies if it is okay to randomly pick the same item multiple times from the parent DataFrame
withReplacement=True, you can get the same item back multiple times
It takes in a fraction parameter, which specifies the fraction elements in the dataset you want to return.
So a fraction value of 0.20 returns 20% of the elements in the DataFrame.
It also takes an optional seed parameter that allows you to specify a seed value for the random number generator
'''
sampledDF = dataDF.sample(withReplacement=False, fraction=0.10)
print sampledDF.count()
sampledDF.show()
print dataDF.sample(withReplacement=False, fraction=0.05).count()
#if you plan to use a DataFrame more than once, then you should tell Spark to cache it
# Cache the DataFrame
filteredDF.cache()
# Trigger an action
print filteredDF.count()
# Check if it is cached
print filteredDF.is_cached
# If we are done with the DataFrame we can unpersist it so that its memory can be reclaimed
filteredDF.unpersist()
# Check if it is cached
print filteredDF.is_cached
''' Recommended Spark coding style '''
df2 = df1.transformation1()
df2.action1()
df3 = df2.transformation2()
df3.action2()
''' Expert Style of coding
Make use of Lambda functions
To make the expert coding style more readable, enclose the statement in parentheses and put each method, transformation, or action on a separate line.
'''
df.transformation1().transformation2().action()
# Cleaner code through lambda use
myUDF = udf(lambda v: v < 10)
subDF.filter(myUDF(subDF.age) == True)
# Final version
from pyspark.sql.functions import *
(dataDF
.filter(dataDF.age > 20)
.select(concat(dataDF.first_name, lit(' '), dataDF.last_name), dataDF.occupation)
.show(truncate=False)
)
# Multiply the elements in dataset by five, keep just the even values, and sum those values
finalSum = (dataset
.map(lambda x: x*5)
.filter(lambda x: (x%2==0))
.reduce(lambda x,y: x+y)
)
print finalSum
#NUMPY AND MATH BASICS
#Scalar multiplication
import numpy as np
simpleArray = np.array([1, 2, 3])
timesFive = 5*simpleArray
#Element-wise multiplication and dot product
u = np.arange(0, 5, .5)
v = np.arange(5, 10, .5)
elementWise = u*v
dotProduct = np.dot(u, v)
Matrix math
from numpy.linalg import inv
A = np.matrix([[1,2,3,4],[5,6,7,8]])
# Multiply A by A transpose
AAt = np.dot(A, A.T)
# Invert AAt with np.linalg.inv()
AAtInv = np.linalg.inv(AAt)
# Show inverse times matrix equals identity
print ((AAtInv * AAt)
'''
PySpark provides a DenseVector class within the module pyspark.mllib.linalg.
DenseVector is used to store arrays of values for use in PySpark.
DenseVector actually stores values in a NumPy array and delegates calculations to that object.
You can create a new DenseVector using DenseVector() and passing in an NumPy array or a Python list
Dense vector stores values as float and uses .dot() to do dot product
'''
from pyspark.mllib.linalg import DenseVector
numpyVector = np.array([-3, -4, 5])
myDenseVector = DenseVector([3.0, 4.0, 5.0])
denseDotProduct = myDenseVector.dot(numpyVector)
|
82dd250d063086764db4e2d70150afbff03079d4 | chang02/alg | /hw1/checker.py | 534 | 3.78125 | 4 | import sys
def check(arr, nth, value):
lower = 0
same = 0
for x in arr:
if x < value:
lower = lower + 1
if x == value:
same = same + 1
if lower < nth <= (lower + same):
return True
else:
return False
nth = int(sys.argv[1])
filename = sys.argv[2]
value = int(sys.argv[3])
f = open(filename, 'r')
lines = f.readlines()
arr = []
for line in lines:
line_arr = line.split(" ")
for number in line_arr:
if number != '' and number != '\n':
arr.append(int(number))
result = check(arr, nth, value)
print(result) |
583e51f6ed23c94ce3bb92e143f67452c23c76ca | KGeetings/CMSC-115 | /Assignments/progNumber13.py | 1,595 | 3.671875 | 4 | #Write a program which will read the dictionary file (words.txt),
#and calculate the answer to the question: "What percentage of words have more vowels than consonants?"
file = open("words.txt","r")
vowelWords = 0
counter = 0
content = file.read()
newList = content.split("\n")
for line in file:
line = line.upper()
#attempt at making a very verbose for loop that is not optimized at all
for i in newList:
if i:
counter += 1
vowelsInWord = 0
consonantsInWord = 0
for l in range(len(i)):
if i[l] == "A" or i[l] == "E" or i[l] == "I" or i[l] == "O" or i[l] == "U" or i[l] == "a" or i[l] == "e" or i[l] == "i" or i[l] == "o" or i[l] == "u":
vowelsInWord += 1
if i[l] == "Q" or i[l] == "W" or i[l] == "R" or i[l] == "T" or i[l] == "Y" or i[l] == "P" or i[l] == "S" or i[l] == "D" or i[l] == "F" or i[l] == "G" or i[l] == "H" or i[l] == "J" or i[l] == "K" or i[l] == "L" or i[l] == "Z" or i[l] == "X" or i[l] == "C" or i[l] == "V" or i[l] == "B" or i[l] == "N" or i[l] == "M" or i[l] == "q" or i[l] == "w" or i[l] == "r" or i[l] == "t" or i[l] == "y" or i[l] == "p" or i[l] == "s" or i[l] == "d" or i[l] == "f" or i[l] == "g" or i[l] == "h" or i[l] == "j" or i[l] == "k" or i[l] == "l" or i[l] == "z" or i[l] == "x" or i[l] == "c" or i[l] == "v" or i[l] == "b" or i[l] == "n" or i[l] == "m":
consonantsInWord += 1
if vowelsInWord > consonantsInWord:
vowelWords += 1
percentage = (vowelWords/counter)*100
file.close()
print(f"The percentage of words that have more vowels than consonants is {percentage:.2f}%") |
a7f8f0101b6b47a71048c2eb19c5b64d530857bf | KGeetings/CMSC-115 | /In Class/Year100.py | 159 | 3.734375 | 4 | userAge = int(input("What is your age? "))
yearBorn = 2021 - userAge
yearHundred = yearBorn + 100
print("You will be 100 years old in the year", yearHundred) |
fa6ab346c0be5b1ed20ef6441f4f6a5f6d404baa | KGeetings/CMSC-115 | /In Class/BankAccount.py | 1,131 | 3.703125 | 4 | class BankAccount:
def __init__(self, owner, startingBalance):
self.owner = owner
self.balance = startingBalance
self.interestRate = .05
def withdraw(self, amount):
if self.balance >= amount:
self.balance = self.balance - amount
else:
print("OVERDRAFT!!!")
self.balance -= 50
def deposit(self, amount):
self.balance += amount
def addMonthlyInterest(self):
newInterest = self.interestRate * self.balance / 12
self.balance += newInterest
def transfer(self, other, amount):
if self.balance >= amount:
self.balance -= amount
other.balance += amount
else:
print("OVERDRAFT")
self.balance -= 50
def getBalance(self):
return self.balance
def getOwner(self):
return self.owner
a = BankAccount("Kenyon", 40000)
b = BankAccount("Fido", 250)
b.withdraw(75)
a.addMonthlyInterest()
b.addMonthlyInterest()
a.transfer(b, 600)
print(f"{a.getOwner()} has ${a.getBalance()}.")
print(f"{b.getOwner()} has ${b.getBalance()}.") |
6e046e3427b8592f75a5ea3702ec14fbc4a30101 | KGeetings/CMSC-115 | /In Class/turtlePetals.py | 601 | 3.984375 | 4 | import turtle
petal_length = 15
petal_angle = 50
num_petals = 360 // petal_angle // 2
for petals in range(num_petals):
if petals % 3 == 0:
turtle.color("red")
elif petals % 3 == 1:
turtle.color("pink")
else:
turtle.color("purple")
turtle.begin_fill()
for i in range(2):
turtle.fd(petal_length)
turtle.left(petal_angle)
turtle.fd(petal_length)
turtle.left(petal_angle)
turtle.fd(petal_length)
turtle.left(180 - 2 * petal_length)
turtle.left(360/num_petals)
turtle.end_fill()
turtle.exitonclick()
|
9e56e18be02f567543d7b8467f42a613e7b0df43 | KGeetings/CMSC-115 | /In Class/ColatzSequence.py | 425 | 3.546875 | 4 | longest_seq = 0
longest_sew_orig = 0
for n in range(2,1000):
if n % 1000 == 1:
print(n / 100000 * 100, "%")
orig = n
while n > 1:
if n % 2 == 0:
n = n//2
else:
n = n*3 + 1
if count > longest_seq:
longest_seq = count
longest_seq_orig = orig
print("The longest sequnce I've seen is:", longest_seq, "starting from", longest_seq_orig) |
f1e02a8d95ca7d162383ade1c14bab27b45b22ac | KGeetings/CMSC-115 | /In Class/Hello_World.py | 195 | 4.25 | 4 | diameter_str = input("What is the diameter of your circle? ")
diameter_int = int(diameter_str)
radius = diameter_int / 2
area = 3.1415 * radius ** 2
print("The area of your circle is: ", area) |
b27ea7f9301fbf02aba5a63a90b9845a5a0b05d0 | formazione/python_book | /snippets/lists.py | 141 | 4.1875 | 4 | Lists in Python
1. Insert items in a list
Insert an Item at the end
==========================
lst.insert(tk.END, entry.get())
v.set("")
|
f4dfebe98073181b1352701e3246e96603bacb05 | mananshah511/Machine_learning | /Simple linear regression/simple_linear_regression.py | 1,366 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 20 12:19:27 2020
@author: manan
"""
#simple linear regression
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#importing dataset
dataset=pd.read_csv('Salary_Data.csv')
#creating independent and depenedent matrix
X=dataset.iloc[:,:-1].values
y=dataset.iloc[:,1].values
#splitting the data for train and test
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=1/3,random_state=0)
#fitting training data
from sklearn.linear_model import LinearRegression
regressor=LinearRegression()
regressor.fit(X_train,y_train)
#prediction based on model which we have trained
y_pred=regressor.predict(X_test)
#plotting graph for better understanding and visual(training data)
plt.scatter(X_train,y_train,color='black')
plt.plot(X_train,regressor.predict(X_train),color='blue')
plt.title('Salary vs Experience(Training data)')
plt.xlabel('Experience')
plt.ylabel('Salary')
plt.savefig('Train_graph.png')
plt.show()
#plotting graph for better understanding and visual(testing data)
plt.scatter(X_test,y_test,color='black')
plt.plot(X_train,regressor.predict(X_train),color='blue')
plt.title('Salary vs Experience(Testing data)')
plt.xlabel('Experience')
plt.ylabel('Salary')
plt.savefig('Test_graph.png')
plt.show()
|
440c99c8f7628b5ff1f311a0f9bd0cf35b47cdcd | rmanzano-sps/IS211_Assignment4 | /search_compare.py | 4,062 | 3.78125 | 4 | #HOW TO: In terminal type 'python search_compare.py' to run program
import timeit
import random
from timeit import Timer
def sequential_search(a_list, item):
pos = 0
found = False
while pos < len(a_list) and not found:
if a_list[pos] == item:
found = True
else:
pos = pos+1
return found
def ordered_sequential_search(a_list, item):
pos = 0
found = False
stop = False
while pos < len(a_list) and not found and not stop:
if a_list[pos] == item:
found = True
else:
if a_list[pos] > item:
stop = True
else:
pos = pos+1
return found
def binary_search_iterative(a_list, item):
first = 0
last = len(a_list) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if a_list[midpoint] == item:
found = True
else:
if item < a_list[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found
def binary_search_recursive(a_list, item):
if len(a_list) == 0:
return False
else:
midpoint = len(a_list) // 2
if a_list[midpoint] == item:
return True
else:
if item < a_list[midpoint]:
return binary_search_recursive(a_list[:midpoint], item)
else:
return binary_search_recursive(a_list[midpoint + 1:], item)
def main():
sequential_search_list = []
ordered_sequential_search_list = []
binary_search_iterative_list = []
binary_search_recursive_list = []
def generate_lists(total_lists, list_length):
input_lists = [random.sample(range(list_length), list_length) for x in range(total_lists)]
for input_list in input_lists:
sequential_search_timer = Timer(lambda: sequential_search(input_list, -1))
sequential_search_results = sequential_search_timer.timeit(number=1)
sequential_search_list.append(sequential_search_results)
input_list.sort()
ordered_sequential_search_timer = Timer(lambda: ordered_sequential_search(input_list, -1))
ordered_sequential_search_results = ordered_sequential_search_timer.timeit(number=1)
ordered_sequential_search_list.append(ordered_sequential_search_results)
binary_search_iterative_timer = Timer(lambda: binary_search_iterative(input_list, -1))
binary_search_iterative_results = binary_search_iterative_timer.timeit(number=1)
binary_search_iterative_list.append(binary_search_iterative_results)
binary_search_recursive_timer = Timer(lambda: binary_search_recursive(input_list, -1))
binary_search_recursive_results = binary_search_recursive_timer.timeit(number=1)
binary_search_recursive_list.append(binary_search_recursive_results)
sequential_search_average = sum(sequential_search_list)/len(input_list)
ordered_sequential_search_average = sum(ordered_sequential_search_list)/len(input_list)
binary_search_iterative_average = sum(binary_search_iterative_list)/len(input_list)
binary_search_recursive_average = sum(binary_search_recursive_list)/len(input_list)
print("Sequential Search, for a list size of %s took %10.7f seconds to run, on average"% (list_length, sequential_search_average))
print("Ordered Sequential Search, for a list size of %s took %10.7f seconds to run, on average"% (list_length, ordered_sequential_search_average))
print("Binary Search Iterative, for a list size of %s took %10.7f seconds to run, on average"% (list_length, binary_search_iterative_average))
print("Binary Search Recursive, for a list size of %s took %10.7f seconds to run, on average"% (list_length, binary_search_recursive_average))
generate_lists(100, 500)
generate_lists(100, 1000)
generate_lists(100, 10000)
if __name__ == '__main__':
main()
|
eb05a439ca3e8cb84a9dd47e7476548ed343a980 | cizixs/playground | /leetcode/strStr.py | 386 | 3.609375 | 4 | class Solution:
# @param haystack, a string
# @param needle, a string
# @return a string or None
def strStr(self, haystack, needle):
if len(haystack) < len(needle):
return None
if needle == "":
return haystack
result = haystack.find(needle)
if result < 0:
return None
return haystack[result:]
|
dfb99f0bdecab494bd696ff377a85a4d25272b5e | cizixs/playground | /eulerproject/largestprimefactor.py | 353 | 3.6875 | 4 | # -*- coding: utf-8 -*-
from math import ceil, sqrt
def largestFactor(n):
if n < 3:
return n
if n <= 0:
raise ValueError('can;t handle non-positive number')
root = int(ceil(sqrt(n)))
for x in range(2, root):
if n % x == 0:
return largestFactor(n/x)
return n
print largestFactor(600851475143)
|
32b719757a612498a8de225ae39e9966434a5b78 | cizixs/playground | /leetcode/generateParenthesis.py | 597 | 3.65625 | 4 | class Solution:
# @param an integer
# @return a list of string
def generateParenthesis(self, n):
result = ["()"]
if n == 1:
return result
while True:
import pdb; pdb.set_trace()
t = result.pop(0)
if len(t) == 2*n:
result.append(t)
return result
for tmp in ["()" + t, "(" + t + ")", t + "()"]:
if tmp not in result:
result.append(tmp)
return [""]
if __name__ == "__main__":
print(Solution().generateParenthesis(4))
|
552e54f97f701a2424f9319fcf6fb6e470c155b5 | Tzhong16/python | /logic_operators.py | 2,386 | 3.890625 | 4 | # Comparisons
print(True == False)
print(-5 * 15 != 75)
print('pyscript' == 'PyScript')
print(True == 1)
x = -3 * 6
print(x >= -10)
y = "test"
print( 'test' <= y)
print(True > False)
#array comparison
import numpy as np
my_house = np.array([18.0, 20.0, 10.75, 9.50])
your_house = np.array([14.0, 24.0, 14.25, 9.0])
print(my_house >= 18)
print(my_house < your_house)
######################################################
# logical_and() , logical_or(), logical_not() in Numpy
######################################################
#basic comparison
my_kitchen = 18.0
your_kitchen = 14.0
print(my_kitchen > 10 and my_kitchen < 18)
print(my_kitchen < 14 or my_kitchen > 17)
print(my_kitchen * 2 < your_kitchen * 3 )
#array comparison with Numpy
import numpy as np
my_house = np.array([18.0, 20.0, 10.75, 9.50])
your_house = np.array([14.0, 24.0, 14.25, 9.0])
print(np.logical_or(my_house>18.5, my_house<10))
print(np.logical_and(my_house < 11 , your_house <11))
################################################
# if , elif , else
################################################
#example1
room = "kit"
area = 14.0
if room == "kit" :
print("looking around in the kitchen.")
if area > 15 :
print("big place!")
#example2
if room == "kit" :
print("looking around in the kitchen.")
else :
print("looking around elsewhere.")
if area > 15 :
print("big place!")
else:
print('pretty small.')
#example3
room = "bed"
area = 14.0
if room == "kit" :
print("looking around in the kitchen.")
elif room == "bed":
print("looking around in the bedroom.")
else :
print("looking around elsewhere.")
if area > 15 :
print("big place!")
elif area > 10:
print("medium size, nice")
else :
print("pretty small.")
#subset data with logical operator
#example1
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
dr = cars['drives_right']
# alternative methods: sel=cars[cars['drive_right']]
sel = cars[dr]
print(sel)
#example2
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
cpc = cars['cars_per_cap']
many_cars = cpc > 500
car_maniac= cars[many_cars]
print(car_maniac)
# example3
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
import numpy as np
cpc = cars['cars_per_cap']
between = np.logical_and(cpc > 100, cpc < 500)
medium = cars[between]
print(medium)
|
0915b352ed93be7c1fe19f751d021b7b74cafbc2 | alexthotse/data_explorer | /Data-Engineering/Part 07_(Elective):Intro_to_Python /Lesson_04.control_flow/control_flow.py | 1,798 | 4.28125 | 4 | # #1. IF Statement
#
# #2. IF, ELIF, ELSE
# #n = str(input("Favourite_number: " ))
# n = 25
# if n % 2 == 0:
# print("The value of " + str(n) + " is even")
# else:
# print("The value of " + str(n) + " is odd")
#
# print(n)
#
# ########################
#
# # season = 'spring'
# # season = 'summer'
# # season = 'fall'
# # season = 'winter'
# # season = 'chill dude!'
# #
# # if season == 'spring':
# # print('plant the garden!')
# # elif season == 'summer':
# # print('water the garden!')
# # elif season == 'fall':
# # print('harvest the garden!')
# # elif season == 'winter':
# # print('stay indoors!')
# # else:
# # print('unrecognized season')
#
# ######Juno's Code######
# #First Example - try changing the value of phone_balance
# phone_balance = 10
# bank_balance = 50
#
# if phone_balance < 10:
# phone_balance += 10
# bank_balance -= 10
#
# print(phone_balance)
# print(bank_balance)
#
# #Second Example - try changing the value of number
#
# number = 145
# if number % 2 == 0:
# print("Number " + str(number) + " is even.")
# else:
# print("Number " + str(number) + " is odd.")
#
# #Third Example - try to change the value of age
# age = 35
#
# # Here are the age limits for bus fares
# free_up_to_age = 4
# child_up_to_age = 18
# senior_from_age = 65
#
# # These lines determine the bus fare prices
# concession_ticket = 1.25
# adult_ticket = 2.50
#
# # Here is the logic for bus fare prices
# if age <= free_up_to_age:
# ticket_price = 0
# elif age <= child_up_to_age:
# ticket_price = concession_ticket
# elif age >= senior_from_age:
# ticket_price = concession_ticket
# else:
# ticket_price = adult_ticket
#
# message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age, ticket_price)
# print(message)
|
1641ddf27ade4047141364e400008e5877c8fd33 | mungjin/2020-Python-code | /Chapter05/05-10wordsort.py | 262 | 3.84375 | 4 | word = list('삶꿈정')
word.extend('복빛')
print(word)
word.sort()
print(word)
fruit = ['복숭아', '자두', '골드키위', '귤']
print(fruit)
fruit.sort(reverse=True)
print(fruit)
mix = word + fruit
print(sorted(mix))
print(sorted(mix, reverse=True))
|
9db6dac80ca8a24e68c5e7b08ac5b3e6a3e65696 | Pozyvnoy/laboratoranaya | /lab1_6.py | 200 | 3.9375 | 4 | chislo = int(input("Введите целое: "))
mult = 1
while (chislo != 0):
mult = mult * (chislo % 10)
chislo = chislo // 10
print("Произведение цифр равно: ", mult) |
098cd36626e7398e75c3dd56dd85ed21e46bd080 | Pozyvnoy/laboratoranaya | /lab1_7.py | 98 | 3.671875 | 4 | x1 = input("Введите число:")
x2 = x1 [::-1 ]
print("Обратное число:", x2) |
3b36b4c4131dc250dd3a079cbe749344c442e9c4 | senorpatricio/python-exercizes | /exercise8.py | 485 | 3.53125 | 4 | from time import clock
def naive_fib(n):
if n == 0 or n == 1:
return n
else:
return naive_fib(n - 1) + naive_fib(n - 2)
def fib_helper(n):
if n == 0:
return 0
else:
return fib_improved(n, 0, 1)
def fib_improved(n, p0, p1):
if n == 1:
return p1
else:
return fib_improved(n-1, p1, p0 + p1)
start = clock()
result = naive_fib()
stop = clock()
difference = (stop - start) * 1000
naive_fib(3)
print difference |
433ad06ffcf65021a07f380078ddf7be5a14bc0d | senorpatricio/python-exercizes | /warmup4-15.py | 1,020 | 4.46875 | 4 | """
Creating two classes, an employee and a job, where the employee class has-a job class.
When printing an instance of the employee object the output should look something like this:
My name is Morgan Williams, I am 24 years old and I am a Software Developer.
"""
class Job(object):
def __init__(self, title, salary):
self.title = title
self.salary = salary
class Employee(object):
def __init__(self, name, age, job_title, job_salary):
self.name = name
self.age = age
self.job = Job(job_title, job_salary)
def __str__(self):
return "Hi my name is %s, I am %s Years old and I am a %s, making $%i per year." \
% (self.name, self.age, self.job.title, self.job.salary)
# def speak(self):
# print "Hi my name is %s, I am %s Years old and I am a %s, making $%i per year." \
# % (self.name, self.age, self.job.title, self.job.salary)
morgan = Employee("Morgan Williams", 24, "Software Developer", 60000)
print morgan
# morgan.speak() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.