blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
bdddbdc8dbabac3b1f981478cf53c0d1e592571b | RANUX/simptools | /simptools/decorators.py | 850 | 3.640625 | 4 | # -*- coding: UTF-8 -*-
import logging
__author__ = 'Razzhivin Alexander'
__email__ = 'admin@httpbots.com'
class catch_and_log_exception(object):
def __init__(self, return_expression=None):
"""
If there are decorator arguments, the function
to be decorated is not passed to the constructor!
"""
self.return_expressions = return_expression
def __call__(self, f):
"""
If there are decorator arguments, __call__() is only called
once, as part of the decoration process! You can only give
it a single argument, which is the function object.
"""
def wrapped_f(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception, e:
logging.exception(e)
return self.return_expressions
return wrapped_f |
c900994ac9a4e20302919d40aee91ae0981ef92c | haimianying/Open-Sesame | /basicexample.py | 2,376 | 3.6875 | 4 | # make matrix of products given two lists of values for x/y-axis
def distance_matrix(x_axis, y_axis):
x_size = len(x_axis)
y_size = len(y_axis)
matrix = [0]*y_size # set up matrix's full length along y-axis
for j in range(y_size):
temp_list = []
for i in range(x_size):
value = distance(x_axis[i], y_axis[j]) # this is the value to put into the matrix at position (i, j)
temp_list.append(value)
matrix[j] = temp_list
return matrix
# calculate distance between two given points
def distance(a, b):
return abs(a-b)
def warped_matrix(matrix):
new_matrix = matrix
for y in range(len(matrix[0])):
for x in range(len(matrix)):
new_matrix[x][y] = cell_value(matrix, x, y)
return new_matrix
# what to fill in cell, given the position (x, y) of the cell in that matrix
# only doing min of cell above or to left, going from top left to bottom right
def cell_value(matrix, x, y):
if x == 0 or y == 0: # to handle items along edges so it doesn't go into negative indexes for the lists in the matrix
if x == 0 and y == 0: # starting position
prev = 0
elif x == 0 and y > 0: # along top edge (x = 0)
prev = matrix[0][y-1]
else: # should be y == 0 and x > 0 True, along left edge (y = 0)
prev = matrix[x-1][y]
else:
prev = min(matrix[x-1][y], matrix[x][y-1])
v = matrix[x][y] + prev
return v
"""
build matrix of set A on one axis vs. set B on another axis
create matrix of local distance (abs. value)
create 2nd matrix of local distance (abs. value) + min of distance in previous cells that are closer to the origin cell
determine lowest value path (sum values to get path value, and do so for all potential paths?)
get coordinates of lowest value path
calculate difference between lowest value path and perfect diagonal for "similarity score"
"""
# Christian's example from 4/10 talk
a = 1, 2, 1
b = 1, 1, 2, 1
"""
first distance matrix should look like this:
1 2 1
1] 0 1 0
1] 0 1 0
2] 1 0 1
1] 0 1 0
temp_list=[]
temp_list.append(a[0]*b[0])
temp_list.append(a[1]*b[0])
temp_list.append(a[2]*b[0])
matrix[0] = temp_list
temp_list=[]
temp_list.append(a[0]*b[1])
temp_list.append(a[1]*b[1])
temp_list.append(a[2]*b[1])
matrix[1] = temp_list
second warped matrix should look like this, only doing min of cell above or to left, going from top left to bottom right:
1 2 1
1] 0 1 1
1] 0 1 1
2] 1 1 2
1] 1 2 2*
""" |
c87ceaf5958865dedc875d358c29b4e26380638d | VinegarRick/Mancala | /solutions/p2_alphabeta_player.py | 491 | 3.796875 | 4 | # -*- coding: utf-8 -*-
__author__ = 'Dan'
__email__ = 'daz040@eng.ucsd.edu'
from assignment2 import Player, State, Action
class AlphaBetaPlayer(Player):
def move(self, state):
"""Calculates the best move from the given board using the minimax
algorithm with alpha-beta pruning and transposition table.
:param state: State, the current state of the board.
:return: Action, the next move
"""
raise NotImplementedError("Need to implement this method") |
bf11aa922410bede968ad3dcfd959d063fdc07db | ShiyiDu/Practice-RandomStuff | /py3/combi.py | 262 | 3.5625 | 4 | import sys
def factor(n):
result = 1
if n == 0: return 1
for i in range(1, n+1):
result = result * i;
return result
def combinator(n, k):
return int(factor(n) / (factor(n-k)*factor(k)))
n = int(sys.argv[1])
k = int(sys.argv[2])
print(combinator(n,k)) |
780d7918e9d76fc469fed5cf272e1889d53c30a7 | menghaoshen/python | /11.面向对象/11.类方法和静态方法.py | 1,941 | 4.0625 | 4 | class Person(object):
type = 'human'
def __init__(self, name, age):
self.name = name
self.age = age
#实例方法,会用到实例对象属性,self指向调用这个方法的实例对象
#两种调用方式:
#实例对象,方法名,不需要手动给self传参,会自动将实例对象传递给self
#类对象,方法名 需要手动给self传参
def eat(self, food): # 对象方法有一个self,指的是实例对象
print(self.name + '正在吃东西' + food)
# 如果一个方法里面没有用到实例对象的任何属性,可以将这个方法定义成静态方法
@staticmethod # 不用实例对象的任何属性
def demo(): # 默认的方法都是对象方法
print('hello')
# 如果这个函数只用到类属性,我们可以把它定义成为一个类方法
@classmethod
def test(cls):
# 类方法有一个参数cls,也不需要手动传参,会自动传参
# cls 指的是类对象,cls == person
print(cls.type)
print('yes')
p1 = Person('张三', '18')
# 实例对象在调用方法时,不需要给形参self传参,会自动的把实例对象传递给self
# eat 对象方法,可以直接使用实例对象,方法名(参数)调用
p1.eat('红烧牛肉泡面') # 直接使用实例对象调用方法
p2 = Person('李四', '19')
p2.eat('momo')
print(p1 is p2)
# 对象方法还可以使用,类对象来调用类名.方法名()
# 这种方法,不会给self传参,需要手动的指定self
print(Person.eat(p2, '西红柿'))
# 静态方法的调用,没有用到实例对象的任何属性
Person.demo()
p1.demo()
#类方法,可以使用实例对象和类对象调用
p1.test()
Person.test()
# 静态的方法,没有用到实例对象的东西
class Utils(object):
@staticmethod
def add(a, b):
return a + b
@staticmethod
def minus(a, b):
return a - b
print(Utils.add(4, 5))
|
186fdacafd8b951afdf112af34ef20e2b11ae98d | rolang12/archivospythonclase | /peso.py | 611 | 3.578125 | 4 |
uno=0
dos=0
tres=0
cua=0
cont=0
num=int(input("Cuántas personas desean registrar su peso?"))
while cont <= num-1:
pes=float(input("¿Cuál es su peso?"))
cont+=1
if pes<=40:
uno +=1
elif pes> 40 and pes <=50:
dos +=1
elif pes>50 and pes <=60:
tres+=1
elif pes>60:
cua +=1
print(f"El total de personas cuyo peso es menor a 40 es: {uno} ")
print(f"El total de personas cuyo peso es mayor a 40 y menor que 50 es: {dos} ")
print(f"El total de personas cuyo peso es mayor a 50 y menor a 60 es: {tres} ")
print(f"El total de personas cuyo peso es mayor a 60 es: {cua} ")
|
ae309c1159d27a36e437ad0129d2b5a12212d376 | gaabyaolivera/exercicios-python | /EstruturaSequencial/ex005.py | 108 | 3.5 | 4 | m = float(input('(M): '))
conversao = m * 100
print('{} metro(s) equivale a {} cm'.format(m, conversao))
|
64e2ceeed717ef8adfde0e4772c4dd984950817b | mdevilliers/python-bestiary | /codility/tape_equilibrium.py | 472 | 3.609375 | 4 | # https://codility.com/programmers/task/tape_equilibrium
def main():
print(solution([3,1,2,4,3])) # 1
def solution(A):
head = A[0]
tail = sum(A[1:])
smallest_difference = abs(head-tail)
for x in xrange(1,len(A)-1):
head += A[x]
tail -= A[x]
diff = abs(head - tail)
if diff < smallest_difference:
smallest_difference = diff
return smallest_difference
if __name__ == "__main__":
main() |
a060a4d2684130437915578ebca3113acabf9522 | sham1lk/subarray_counter | /main.py | 1,775 | 3.953125 | 4 | import unittest
from random import randint
def even_subarray(numbers, k):
"""
:param numbers: list of integers
:param k: int, max number of odd elements in subarray
:return: number of subarrays
"""
count = 0
odd_num = 0
dp = [0 for i in range(len(numbers)+1)]
for i in range(len(numbers)):
dp[odd_num] += 1
# if array element is odd
if numbers[i] % 2:
odd_num += 1
for j in range(min(odd_num, k) + 1):
count += dp[odd_num - j]
return count
class TestEvenSubarray(unittest.TestCase):
"""
Test even_subarray function
"""
def test_all_even(self):
"""
All even test case.
The answer should be all combinations of all sizes
"""
for p in range(100):
size_of_arr = randint(1, 10000)
arr = [0 for i in range(size_of_arr)]
ans = 0
for i in range(size_of_arr):
ans += size_of_arr - i
self.assertEqual(even_subarray(arr, 0), ans)
def test_all_odd(self):
"""
All odd test case.
The answer should be all combination of all sizes smaller then k
"""
for p in range(100):
k = randint(0, 10)
size_of_arr = randint(10, 10000)
arr = [1 for i in range(size_of_arr)]
ans = 0
for i in range(k):
ans += size_of_arr - i
self.assertEqual(even_subarray(arr, k), ans)
def test_some_cases(self):
tests = [([6, 3, 5, 8], 1, 6),
([2, 3, 3, 2, 2, 3, 2, 2, 2, 2], 3, 55)]
for t in tests:
self.assertEqual(even_subarray(t[0], t[1]), t[2])
if __name__ == '__main__':
unittest.main()
|
4b991c7bd0137383efc7014d2d7d2526f6b9ed12 | ahmedezzeldin93/python_goodrich_solutions | /ex1.py | 2,693 | 3.96875 | 4 | '''
This is file contain exercises 1 for
data structures and algorithms in python
All Exercises Done by github@ahmedezzeldin93
'''
#R-1.1
def is_multiple(n,m):
return True if n%m == 0 else False
#R-1.2
def is_even(k):
return not k & 1
#R-1.3
def minmax(data):
minimum, maximum = 99999999,0
for i in data:
if i > maximum:
maximum = i
continue
if i < minimum:
minimum = i
continue
return minimum, maximum
#R-1.4 #R-1.5
def sum_of_squares(n):
arr = [i**2 for i in range(1,n)]
return sum(arr)
#R-1.6 #R-1.7
def sum_of_squares_of_odds(n):
arr = [i**2 for i in range(1,n) if i%2 != 0]
return sum(arr)
#R-1.12
import random
def mychoice_random(arr):
choice = random.randrange(0,len(arr),1)
return arr[choice]
#C-1.13
def reverse_list(arr):
reversed_list = []
i = len(arr)-1
while i >= 0:
reversed_list.append(arr[i])
i = i - 1
return reversed_list,
#C-1.14
def detect_odd_product(arr):
i = 0
while i < len(arr)-1:
if (arr[i] * arr[i+1])%2 != 0:
return True
i+=1
return False
#C-1.15
def element_in_list(element,arr):
for i in arr:
if i == element:
return True
return False
def distinct_list(arr):
mylist = []
for i in arr:
if element_in_list(i,mylist):
return False
else:
mylist.append(i)
return True
#C-1.20
def myshuffle(data):
arr= []
k = 0
length = len(data)
while k < length:
i = random.randint(0,length-k-1)
arr.append(data[i])
del data[i]
k +=1
return arr
#C.1.22
def dot_product(a,b):
c = []
i = 0
while i < len(a):
c.append(a[i] * b[i])
i+=1
return c
#C-1.28
def norm(v, p=2):
arr = [i**p for i in v]
summ = sum(arr)
return summ ** (1./float(p))
if __name__ == '__main__':
#R-1.1
print(is_multiple(10,5))
#R-1.2
print(is_even(22))
#R-1.3
print(minmax([4,4,6,7,8,1,10]))
#R-1.4 R-1.5
print(sum_of_squares(5))
#R-1.6 R-1.7
print(sum_of_squares_of_odds(10))
print([2**i for i in range(9)])
#R-1.12
print(mychoice_random([3,4,5,5,6,7,8,8,9,12,19]))
#C-1.13
print(reverse_list([1,2,3,4,5,6,7,8]))
#C-1.14
print(detect_odd_product([1,2,3,4,5,6,3,7,8]))
#C-1.15
print(distinct_list([1,2,3,4,5,6,6]))
#C-1.18
print([i*(i+1) for i in range(10)])
#C-1.19
print([chr(x) for x in range(97,123)])
#C-1.28
print(norm([1,2,3,4,5],3))
#C-1.20
print(myshuffle([1,2,3,4,5]))
#C-1.22
print(dot_product([1,2,3,4],[5,6,7,8]))
|
7115dac02a343502fc094d7ee5de02919eeea3f0 | kajendranL/Daily-Practice | /workouts/12.calander.py | 316 | 3.984375 | 4 | print("Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s)")
print()
import calendar
month = calendar.month(2019, 7)
year = calendar.FRIDAY
print("The calendar for the year 2019 and the 7th month is" ,month)
print("The number of Fridays are: ", year) |
6aa200771edd89a5c97c301512a6fedc2c608fbe | shitalmahajan11/letsupgrade | /Assingment2.py | 2,854 | 4.25 | 4 |
# LetsUpgrade Assignment 2
1. Back slash:- it is continuation sign.
Ex. print*("hello \
welcome")
2. triple Quotes:-represent the strings containing both single and double quotes to eliminate the need of escaping any.
Ex:- print("""this is python session""")
3.String inside the quotes:-there are 2 way to declared on string inside the quotes.
Ex. 1) print('hello world')
2) print("python's World")
4. Escape Sequence of String:- the backslash "\" is a special character, also called the "escape" character.and"\t" is a tab, "\n" is a newline, and "\r" is a carriage return are used.
Ex:- print("hello\tworld")
print("welcome\nhome")
5.Formatted output:- There are several ways to present the output of a program, data can be printed in a human-readable form, or written to a file for future use.
Ex:- name=ABC
age=24
print("the name of person is", name," age is",age)
# variable:- variables means linking of the data to name or A Python variable is a reserved memory location to store values.
Ex:- a=20
# Rules to variable
1. A variable name must start with a letter or the underscore character.
2. A variable name cannot start with a number.
3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
4. Variable names are case-sensitive (age, Age and AGE are three different variables)
# python Operator:-
there are 7 type of operator
1. Arithmatic operator
2. Comparison Operator
3. Assignment Operator
4. Bitwise Operator
5. Logical operator
6. Membership Operator
7. Identity Operator
# Arithmatic Operator:- Arithmetic operators are used with numeric values to perform common mathematical operations.
1. + Addition
2. - Subtraction
3. * Multiplication
4. / Division
5. % Modulus
6. ** Exponentiation
7. // Floor division
# Comparision Operator:-Comparison operators are used to compare two values.
1. == Equal
2. != Not equal
3. > Greater than
4. < Less than
5. >= Greater than or equal to
6. <= Less than or equal to
# Assignment Operator:-Assignment operators are used to assign values to variables.used = operator.
# Bitwise operators are used to compare (binary) numbers:-
1. & AND
2. | OR
3. ^ XOR
4. ~ NOT
5. << Zero fill left shift
6. >> Signed right shift
# Logical operator:-Logical operators are used to combine conditional statement.
1. and
2. or
3. not
# Membership Operator:-Membership operators are used to test if a sequence is presented in an object.
1. in
2. not in
# Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory locationIdentity Operator.
1. is
2. is not
|
b7e1e92e9bc2889e4851ceb4922397b7e5bf738f | sreejithev/pythoncodes | /day5/iterators/basics/1.py | 71 | 3.515625 | 4 | a = [1,2,3]
b = iter(a)
print b.next()
print b.next()
print b.next()
|
dfd666d54a86616dacc7e32cf8f0832f2741c753 | theallegrarr/Sprint-Challenge--Graphs | /adv.py | 4,854 | 3.59375 | 4 | from room import Room
from player import Player
from world import World
from collections import defaultdict
from util import Stack, Queue
import random
from ast import literal_eval
# Load world
world = World()
# You may uncomment the smaller graphs for development and testing purposes.
# map_file = "maps/test_line.txt"
# map_file = "maps/test_cross.txt"
# map_file = "maps/test_loop.txt"
# map_file = "maps/test_loop_fork.txt"
map_file = "maps/main_maze.txt"
# Loads the map into a dictionary
room_graph=literal_eval(open(map_file, "r").read())
world.load_graph(room_graph)
# Print an ASCII map
world.print_rooms()
player = Player(world.starting_room)
# Fill this out with directions to walk
# traversal_path = ['n', 'n']
traversal_path = []
opposite_direction = { 'n': 's', 's': 'n','e': 'w','w': 'e'}
graph = {}
# finding the last room with BFS
def breadth_first_search(graph, starting_room):
queue = Queue()
visited_set = set()
queue.enqueue([starting_room])
while queue.size():
path = queue.dequeue()
next_room = path[-1]
# if next room has not been visited
if next_room not in visited_set:
visited_set.add(next_room)
# check all exits in the next room
for room in graph[next_room]:
# check if an exit has been visited
if graph[next_room][room] == 'visited':
return path
for any_exit in graph[next_room]:
# set the exit to be tracked to a variable
neighboring_room = graph[next_room][any_exit]
# copy the path
new_path = list(path)
new_path.append(neighboring_room)
# save the path
queue.enqueue(new_path)
while len(graph) < len(room_graph):
current_room_id = player.current_room.id
# if current room is not yet in the graph
if current_room_id not in graph:
# insert the room as an empty dict
graph[current_room_id] = {}
# loop over the exits
for room_exits in player.current_room.get_exits():
# check if they have been visited
graph[current_room_id][room_exits] = "visited"
# loop over any direction a room can go
for direction in graph[current_room_id]:
# check if player can not move beyond room
if direction not in graph[current_room_id]:
break
# check if all exits have been visited
if graph[current_room_id][direction] == 'visited':
# if there is an exit in the dictionary
if direction is not None:
traversal_path.append(direction)
player.travel(direction)
# create a variable to hold current room id
room_id = player.current_room.id
# if the room_id has not been visited
if room_id not in graph:
graph[room_id] = {}
# for each available exit in the room, set exits to visited
for any_exit in player.current_room.get_exits():
graph[room_id][any_exit] = 'visited'
# set previous room directions and exits
graph[current_room_id][direction] = room_id
graph[room_id][opposite_direction[direction]] = current_room_id
current_room_id = room_id
# using BFS, with parameters for graph and current room
bfs_path = breadth_first_search(graph, player.current_room.id)
# create directions using all rooms in the path and appending all directions
if bfs_path is not None:
for room in bfs_path:
for any_exit in graph[current_room_id]:
if graph[current_room_id][any_exit] == room:
traversal_path.append(any_exit)
# move in that direction
player.travel(any_exit)
current_room_id = player.current_room.id
# TRAVERSAL TEST
visited_rooms = set()
player.current_room = world.starting_room
visited_rooms.add(player.current_room)
for move in traversal_path:
player.travel(move)
visited_rooms.add(player.current_room)
if len(visited_rooms) == len(room_graph):
print(f"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited")
else:
print("TESTS FAILED: INCOMPLETE TRAVERSAL")
print(f"{len(room_graph) - len(visited_rooms)} unvisited rooms")
#######
# UNCOMMENT TO WALK AROUND
#######
player.current_room.print_room_description(player)
while True:
cmds = input("-> ").lower().split(" ")
if cmds[0] in ["n", "s", "e", "w"]:
player.travel(cmds[0], True)
elif cmds[0] == "q":
break
else:
print("I did not understand that command.")
|
4b27bdb09df3b06fa121c266055dcfdd2f027fcc | 409085596/TallerHC | /Clases/Programas/Tarea06Integral.py | 925 | 3.640625 | 4 | # -*- coding: utf-8 -*-
def integral(a,b,n):
intervalos=[a+i*(b-a)/float(n) for i in range(n+1)]
areaMinima=0
areaMaxima=0
areaTrapecio=0
for i in range(len(intervalos)-1):
valori = -6*intervalos[i]**3+5*intervalos[i]**2+2*intervalos[i]+12
valorii = -6*intervalos[i+1]**3+5*intervalos[i+1]**2+2*intervalos[i+1]+12
mayor,menor=0,0
if valori > valorii:
mayor = valori
menor = valorii
else:
mayor = valorii
menor = valori
areaMinima += menor * (intervalos[i+1]-intervalos[i])
areaMaxima += mayor * (intervalos[i+1]-intervalos[i])
areaTrapecio += menor * (intervalos[i+1]-intervalos[i]) + (mayor-menor)*(intervalos[i+1]-intervalos[i])/2.0
return "El área mínima es %.3f, el área máxima %.3f y el área de trapecios es %.3f" %(areaMinima,areaMaxima,areaTrapecio)
|
cbf772ae2b31cc7cad3c77e29505be0a10d2d856 | decchu14/Python-Image-Processing | /4_ImageProcessing.py | 732 | 3.796875 | 4 | from sys import argv
import os
from PIL import Image
# grabing first and second arguements from commandline
jpg_folder = argv[1]
png_folder = argv[2]
# checking whether folder exists if not creating
if not os.path.exists(png_folder):
os.mkdir(png_folder)
# path of the folder which contains jpg images
directory = f'path/{jpg_folder}'
# looping through folder and converting images to png and saving it in another folder
for filename in os.listdir(directory):
img = Image.open(f'{directory}/{filename}')
# splitting the name from its extension
filename_without_ext = os.path.splitext(filename)[0]
# new_filename = f'{filename_without_ext}.png'
img.save(f'{png_folder}/{filename_without_ext}.png', 'png')
|
190ae68e6580f721e1748f4ce55ee643d5e73878 | freeland120/Algorithm_Practice | /CodingTest_Python/BaekJoon/Algorithm/Stack&Queue.py | 368 | 3.671875 | 4 |
stack = []
stack.append(1)
stack.append(2)
stack.append(3)
stack.append(4)
stack.append(5)
stack.pop()
stack.append(7)
print(stack[::-1])
print(stack)
from collections import deque
queue = deque()
queue.append(5)
queue.append(4)
queue.append(3)
queue.append(2)
queue.append(1)
print(queue)
queue.popleft()
print(queue)
queue.reverse()
print(queue) |
95f09e85006c82ef1c9cefd00f9d97cc09497195 | stecat/pyTraining | /Day2/file_op_2.py | 585 | 3.75 | 4 | # Author:Steve
# 读写文件用迭代器,效率高,每次读一行内存存一行,读完后内存删除
f = open("yesterday")
count = 0
for line in f: # f此时变成了迭代器,此时就没有下标了,需要自己添加计数器
if count == 9:
print("-------第10行分割线——————————")
count += 1 # 如果count +=1不写这边会一直打印上句,因为到9时就一直在if判断里面continue
continue
count += 1 # 这边也要有对应加的计数器
print("%s:" % count, line)
f.close() |
fa28557f5b8cdf5e0992665a7fd08d21082fe7f0 | Averiandith/jubilant-ahri | /itertools_product.py | 277 | 3.78125 | 4 | # https://www.hackerrank.com/challenges/itertools-product/problem
from itertools import product
if __name__ == '__main__':
a = [int(i) for i in input().split(" ")]
b = [int(i) for i in input().split(" ")]
for pair in product(a, b):
print(pair, end=" ")
|
a27f7281a13e5fbdd978f02112a4f39818fd6486 | Sainterman/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 258 | 4 | 4 | #!/usr/bin/python3
""" define append_write that adds text at end of file """
def append_write(filename="", text=""):
""" open file in append mode to add at end """
with open(filename, encoding='utf-8', mode='a') as f:
return(f.write(text))
|
acc4ca1f04e3720e4ff2dfe181cc7d4bd92e03a6 | king-11/Information-Technology-Workshop | /python assignments/Assignment3/19075043/2.py | 119 | 3.734375 | 4 | x = open('test.txt')
n = int(input("Number of lines to read : "))
for i in range(n):
print(x.readline(), end="")
|
c59cfce1a9bb674586dfc6a4bb7b19b16310cf5c | chrislimqc/NTU_CompSci | /CZ1012/lab03/midpoint rule.py | 412 | 3.796875 | 4 | import math
def fx(x):
return x / (1 + math.pow(x, 2))
def interval(a, b, n):
return (b - a) / n
for n in range(5, 55, 5):
result = 0
my_interval = interval(0, 2, n)
xi = 0
for count in range(1, n+1):
xi += my_interval
xi_avg = xi - (0.5 * my_interval)
result += (my_interval * fx(xi_avg))
print("midpoint result for n = {} is : {}".format(n, result))
|
92f7b8c1ba2718d895abeab544a02b7960a43d50 | sandwu/leetcode_problems | /专题训练/数组/简单/合并有序数组2到有序数组1中.py | 331 | 3.71875 | 4 |
class Solution:
def mergesortarray(self,nums1,m,nums2,n):
while m >0 and n >0:
if nums1[m-1] > nums2[n-1]:
nums1[n+m-1] = nums1[m-1]
m -= 1
else:
nums1[n+m-1] = nums2[n-1]
n -= 1
if n >0:
nums1[:n] = nums2[:n] |
4f4c34be57e5be56e0fdb03de0183340f26f89cf | miuiunguyen/100days-of-Coding | /Day-1-100days-of-Coding/HelloWorld.py | 208 | 3.5 | 4 | print("Hello. Welcome to my Youtube Channel")
nick_name = input("What's your nick name?\n")
family_name = input("What is your family name?\n")
print("Your brand name should be " + nick_name +"_"+ family_name) |
763c0836fba1315a667034397bc8a6a742a2b89d | ngocson2vn/learnpython | /itv/find_diff_char.py | 300 | 3.515625 | 4 | #!/usr/bin/python
def find_diff_xor(s1, s2):
result = 0
for c in s1:
result = result ^ ord(c)
for c in s2:
result = result ^ ord(c)
diff = chr(result)
return diff if diff in s1 or diff in s2 else None
s1 = "Son Nguyen"
s2 = "Son Ngxuyen"
print find_diff_xor(s1, s2) |
115be49e83083d9adf4f549aa2c367cc2112802e | pmns314/daa | /project1/currency.py | 15,393 | 3.5625 | 4 | from TdP_collections.map.avl_tree import AVLTreeMap
from project1.double_hashing_hash_map import DoubleHashingHashMap
import re
class Currency:
"""A Currency Class implementation in Python."""
def __init__(self, c):
"""The constructor of the class takes as input a code 'c' and initializes Code to this value,
denominations as an empty map, and change as an empty hash map.
:parameter 'c' The code three capital letters identifying a currency according to the standard ISO 4217.
:raise 'ValueError' if 'c' do not respect ISO 4217."""
if not self._validate_iso4217(c):
raise TypeError('c must respect ISO 4217')
self._code = c
self._denomination = AVLTreeMap()
self._changes = DoubleHashingHashMap()
def code(self):
return self._code
# complexity O(2 log N)
def add_denomination(self, value):
"""Add value in the Denominations map. It raises an exception if value is already present.
:parameter 'value' is the value to add in Denomination map.
:raise 'ValueError' if value is already present in the map."""
if value in self._denomination: # O(log N)
raise ValueError('The value is already present')
self._denomination[value] = 0 # O(log N)
# complexity O(log N)
def del_denomination(self, value):
"""Remove value from the Denominations map. It raises an exception if value is not present.
:parameter 'value' is the value to remove in Denomination map.
:raise 'ValueError' if value is not present in the map."""
del (self._denomination[value]) # O(log N)
# complexity O(2 log N)
def min_denomination(self, value=None):
"""The parameter value is optional. If it is not given, it returns the minimum denomination (it raises an
exception if no denomination exists), otherwise it returns the minimum denomination larger than value
(it raises an exception if no denomination exists larger than value)."""
if value is None:
e = self._denomination.find_min() # O(log N)
if e is None:
raise ValueError('no denomination exists')
return e[0]
else:
p = self._denomination.find_position(value) # O(log N)
if p.key() < value:
p = self._denomination.after(p) # O(log N)
if p is None:
raise ValueError('no denomination exists')
return p.key()
# complexity O(2 log N)
def max_denomination(self, value=None):
"""The parameter value is optional. If it is not given, it returns the maximum denomination(it raises an
exception if no denomination exists), otherwise it returns the maximum denomination smaller than value (it
raises an exception if no denomination exists larger than value)."""
if value is None:
e = self._denomination.find_max() # O(log N)
if e is None:
raise ValueError('no denomination exists')
return e[0]
else:
p = self._denomination.find_position(value) # O(log N)
if p.key() > value:
p = self._denomination.before(p) # O(log N)
if p is None:
raise ValueError('no denomination exists')
return p.key()
# complexity O(2 log N)
def next_denomination(self, value):
"""Return the denomination that follows value, if it exists, None otherwise. If value is not a denomination it
raises an exception."""
p = self._denomination.find_position(value) # O(log N)
if p is None or p.key() != value:
raise ValueError('denomination not present')
n = self._denomination.after(p) # O(log N)
return n.key() if n is not None else None
# complexity O(2 log N)
def prev_denomination(self, value):
"""Return the denomination that precedes value, if it exists, None otherwise. If value is not a denomination it
raises an exception."""
p = self._denomination.find_position(value) # O(log N)
if p is None or p.key() != value:
raise ValueError('denomination not present')
prev = self._denomination.before(p) # O(log N)
return prev.key() if prev is not None else None
def has_denominations(self):
"""Return true if the Denominations map is not empty."""
return not self._denomination.is_empty() # O(1)
def num_denominations(self):
"""Returns the number of elements in the Denominations map."""
return len(self._denomination) # O(1)
def clear_denominations(self):
"""Remove all elements from the Denominations map."""
self._denomination.clear() # O(N)
def iter_denominations(self, reverse=False):
"""Returns an iterator over the Denominations map. If reverse is false (default value), the iterator must
iterate from the smaller to the larger denomination, otherwise it must iterate from the larger to the smaller
denomination."""
if reverse:
for k in reversed(self._denomination):
yield k
else:
for k in iter(self._denomination):
yield k
def add_change(self, currencycode, change):
"""Add an entry in the Changes hash map, whose key is currencycode and whose value is change. It raises an
exception if the key currencycode is already present."""
if currencycode in self._changes: # O(1) EXPECTED
raise KeyError('currencycode already exists')
self._changes[currencycode] = change # O(1) EXPECTED
def remove_change(self, currencycode):
"""Remove the entry with key currencycode from the Changes hash map. It raises an exception if the key
currencycode is not present."""
del (self._changes[currencycode]) # O(1) EXPECTED
def update_change(self, currencycode, change):
"""Updates the value associated with key currencycode to change.If the key currencycode does not exist, it will
be inserted in the Changes hash map."""
self._changes[currencycode] = change # O(1) EXPECTED
def get_change(self, currencycode):
return self._changes[currencycode]
def iter_changes(self):
for key in self._changes:
yield key
def copy(self):
"""Create a new Object Currency whose attributes are equivalent to the ones of the current currency.
:return: a copy of the object."""
new = Currency(self._code)
new._code = self._code
new._denomination = self._denomination
new._changes = self._changes
return new
def deepcopy(self):
"""Create a new Object Currency whose attributes are equivalent but not identical to the ones of the current
currency.
:return: a deepcopy of the object."""
new = Currency(self._code)
for d in self._denomination:
new.add_denomination(d)
for c in self._changes:
new.add_change(c, self._changes[c])
return new
@staticmethod
def _validate_iso4217(s):
pattern = re.compile("^[A-Z]{3}$")
return pattern.match(s) is not None
def __str__(self):
return self._code
def __repr__(self):
return str(self)
if __name__ == '__main__':
print('---------- Try add_denomination and reverse iter ----------------------')
cur = Currency('EUR')
print("cur = Currency('EUR')")
for e in cur.iter_denominations(True):
print(e, end=' ')
print()
print('\ncur.add_denomination(50)')
cur.add_denomination(50)
for e in cur.iter_denominations(True):
print(e, end=' ')
print()
print('\ncur.add_denomination(10)')
cur.add_denomination(10)
for e in cur.iter_denominations(True):
print(e, end=' ')
print()
print('\ncur.add_denomination(200)')
cur.add_denomination(200)
for e in cur.iter_denominations(True):
print(e, end=' ')
print()
print('\ncur.add_denomination(10)')
try:
cur.add_denomination(200)
except ValueError as e:
print('error:', e)
for e in cur.iter_denominations(True):
print(e, end=' ')
print()
print('\n\n---------- Try del_denomination and iter----------------------')
print('\ncur.del_denomination(200)')
try:
cur.del_denomination(200)
except ValueError as e:
print('error:', e)
for e in cur.iter_denominations():
print(e, end=' ')
print()
print('\ncur.del_denomination(500)')
try:
cur.del_denomination(500)
except KeyError as e:
print('error:', e)
for e in cur.iter_denominations():
print(e, end=' ')
print()
print('\n\n---------- Try min_denomination ----------------------')
print('\ncur.min_denomination(): ', end='')
try:
print(cur.min_denomination())
except ValueError as e:
print('error:', e)
print('\ncur.min_denomination(10): ', end='')
try:
print(cur.min_denomination(10))
except ValueError as e:
print('error:', e)
print('\ncur.min_denomination(20): ', end='')
try:
print(cur.min_denomination(20))
except ValueError as e:
print('error:', e)
print('\ncur.min_denomination(50): ', end='')
try:
print(cur.min_denomination(50))
except ValueError as e:
print('error:', e)
print('\ncur.min_denomination(70): ', end='')
try:
print(cur.min_denomination(70))
except ValueError as e:
print('error:', e)
print('\n\n---------- Try max_denomination ----------------------')
print('\ncur.max_denomination(): ', end='')
try:
print(cur.max_denomination())
except ValueError as e:
print('error:', e)
print('\ncur.max_denomination(70): ', end='')
try:
print(cur.max_denomination(70))
except ValueError as e:
print('error:', e)
print('\ncur.max_denomination(50): ', end='')
try:
print(cur.max_denomination(50))
except ValueError as e:
print('error:', e)
print('\ncur.max_denomination(20): ', end='')
try:
print(cur.max_denomination(20))
except ValueError as e:
print('error:', e)
print('\ncur.max_denomination(10): ', end='')
try:
print(cur.max_denomination(10))
except ValueError as e:
print('error:', e)
print('\ncur.max_denomination(5): ', end='')
try:
print(cur.max_denomination(5))
except ValueError as e:
print('error:', e)
print('\n\n---------- Try next_denomination ----------------------')
print('\ncur.next_denomination(10): ', end='')
try:
print(cur.next_denomination(10))
except ValueError as e:
print('error:', e)
print('\ncur.next_denomination(50): ', end='')
try:
print(cur.next_denomination(50))
except ValueError as e:
print('error:', e)
print('\ncur.next_denomination(70): ', end='')
try:
print(cur.next_denomination(70))
except ValueError as e:
print('error:', e)
print('\n\n---------- Try prev_denomination ----------------------')
print('\ncur.prev_denomination(10): ', end='')
try:
print(cur.prev_denomination(10))
except ValueError as e:
print('error:', e)
print('\ncur.prev_denomination(50): ', end='')
try:
print(cur.prev_denomination(50))
except ValueError as e:
print('error:', e)
print('\ncur.prev_denomination(70): ', end='')
try:
print(cur.prev_denomination(70))
except ValueError as e:
print('error:', e)
print('\n\n---------- Try has_denomination, num_denomination e clear_denomination----------------------')
print('\ncur.has_denominations(): {}'.format(cur.has_denominations()))
print('\ncur.num_denominations(): {}'.format(cur.num_denominations()))
print('\ncur.clear_denominations()')
cur.clear_denominations()
print('\ncur.has_denominations(): {}'.format(cur.has_denominations()))
print('\ncur.num_denominations(): {}'.format(cur.num_denominations()))
print('\n\n---------- Try add_change ----------------------')
print("\ncur.add_change('USD', 1.35): ", end='')
try:
cur.add_change('USD', 1.35)
print('success')
except KeyError as e:
print('error:', e)
print("\ncur.add_change('JBP', 0.49): ", end='')
try:
cur.add_change('JBP', 0.49)
print('success')
except KeyError as e:
print('error:', e)
print("\ncur.add_change('JBP', 0.78): ", end='')
try:
cur.add_change('JBP', 0.78)
print('success')
except KeyError as e:
print('error:', e)
print('\n\n---------- Try update_change ----------------------')
print("\ncur.update_change('USD', 1.45): ", end='')
try:
cur.update_change('USD', 1.45)
print('success')
except KeyError as e:
print('error:', e)
print("\ncur.update_change('FFP', 1.45): ", end='')
try:
cur.update_change('FFP', 1.38)
print('success')
except KeyError as e:
print('error:', e)
print('\n\n---------- Try remove_change ----------------------')
print("\ncur.remove_change('USD'): ", end='')
try:
cur.remove_change('USD')
print('success')
except KeyError as e:
print('error:', e)
print("\ncur.remove_change('BAB'): ", end='')
try:
cur.remove_change('BAB')
print('success')
except KeyError as e:
print('error:', e)
print('\n\n---------- Try copy and deepcopy ----------------------')
print('\ncur.add_denomination(50)')
cur.add_denomination(50)
for e in cur.iter_denominations(True):
print(e, end=' ')
print()
print('\ncur.add_denomination(10)')
cur.add_denomination(10)
for e in cur.iter_denominations(True):
print(e, end=' ')
print()
print('\ncur.add_denomination(200)')
cur.add_denomination(200)
for e in cur.iter_denominations(True):
print(e, end=' ')
print()
print('\ncopy_cur = cur.copy()')
copy_cur = cur.copy()
print('\ndeepcopy_cur = cur.deepcopy()')
deepcopy_cur = cur.deepcopy()
print('\ncur is copy_cur: {}'.format(cur is copy_cur))
print('\ncur is deepcopy_cur: {}'.format(cur is deepcopy_cur))
print('\ncur._denomination == copy_cur._denomination: {}'.format(cur._denomination == copy_cur._denomination))
print(
'\ncur._denomination == deepcopy_cur._denomination: {}'.format(cur._denomination == deepcopy_cur._denomination))
print('\ncur._denomination is copy_cur._denomination: {}'.format(cur._denomination is copy_cur._denomination))
print(
'\ncur._denomination is deepcopy_cur._denomination: {}'.format(cur._denomination is deepcopy_cur._denomination))
print('\ncur._changes == copy_cur._changes: {}'.format(cur._changes == copy_cur._changes))
print('\ncur._changes == deepcopy_cur._changes: {}'.format(cur._changes == deepcopy_cur._changes))
print('\ncur._changes is copy_cur._changes: {}'.format(cur._changes is copy_cur._changes))
print('\ncur._changes is deepcopy_cur._changes: {}'.format(cur._changes is deepcopy_cur._changes))
|
5ca516cb4dd793ff061ef08807fe7510d232c1cf | zf1102/py_demo | /demo7/dice_count_v3.0.py | 1,372 | 3.625 | 4 | """
作者:zf
功能:投掷骰子,显示点数的出现次数及频率
版本:3.0
日期:20181024
新增功能:可视化同时投掷两个骰子的结果
"""
import random
import matplotlib.pyplot as plt
def roll_dice():
"""
模拟掷骰子
"""
roll = random.randint(1, 6)
return roll
def main():
"""
主函数
"""
total_times = 100
# 初始化列表
result_list = [0] * 11
# 初始化点数列表
roll_list = list(range(2, 13))
roll_dict = dict(zip(roll_list, result_list))
# 分别记录骰子的结果
roll1_list = []
roll2_list = []
for i in range(total_times):
roll1 = roll_dice()
roll2 = roll_dice()
roll1_list.append(roll1)
roll2_list.append(roll2)
for j in range(2, 13):
if (roll1+roll2) == j:
roll_dict[j] += 1
print(result_list)
for i, result in roll_dict.items():
print('点数{}出现的次数是:{},频率是:{}'.format(i, result, result / total_times))
# 数据可视化,散点图
x = range(1, total_times + 1)
plt.scatter(x, roll1_list, c='red', alpha=0.5)
plt.scatter(x, roll2_list, c='green', alpha=0.5)
plt.show()
if __name__ == '__main__':
main()
|
e1a9418165f2e04c58564f7753acadcec8d3fb96 | AliShahram/Maze-Search | /breadth_first.py | 4,401 | 3.65625 | 4 | #!/usr/bin/python
import copy
import sys
from collections import defaultdict
from data_structures import Tra_model, Stack, Queue
from state_rep import extractParams
big_list = []
# Take a .txt file, parses out the maze, and returns a
# 2D representation of the array
def parser(file):
file_open = open (file, "r")
for line in file_open:
line = line.strip("\n")
line = list(line)
big_list.append(line)
return big_list #Returns the 2d array
#-------------------------------------------------------------------
# Single Breadth First Search
# Take the 2D array, and the position of the agent as an input
# and returns the biglist with the path from
# the agent to the prize marked with "#"
# It also returns a stack of the explored cells
def single_bfs(big_list, current):
queue = Queue()
explored = Queue()
newExplored = Stack()
seen = set()
pointer = current
queue.enqueue(pointer) #Add the our initial position to the
explored.enqueue(pointer) #queue
tra_model = Tra_model()
while True:
if queue.isEmpty():
break
else:
pointer = queue.dequeue()
# First move to the right and check what it is
pointer = tra_model.move_right(pointer)#make the first move
x = pointer[0]
y = pointer[1]
if big_list[x][y] == " ":#if it is space, add its location
queue.enqueue(pointer)
explored.enqueue(pointer)
big_list[x][y] = "#"
pointer = tra_model.move_left(pointer)
if big_list[x][y] == "%" or "#" :#if it is hardle, move back
pointer = tra_model.move_left(pointer)
if big_list[x][y] == ".":#if it is goal, add its location
queue.enqueue(pointer)
explored.enqueue(pointer)
break
# second move to the bottom and check what it is
pointer = tra_model.move_down(pointer)
x = pointer[0]
y = pointer[1]
if big_list[x][y] == " ": #if it is space, add its location
explored.enqueue(pointer)
queue.enqueue(pointer)
big_list[x][y] = "#"
pointer = tra_model.move_up(pointer)
if big_list[x][y] == "%" or "#" : #if it is hardle, move back
pointer = tra_model.move_up(pointer)
if big_list[x][y] == ".": #if it is goal, add its location
queue.enqueue(pointer)
explored.enqueue(pointer)
break
# Third move to the left and check what it is
pointer = tra_model.move_left(pointer)
x = pointer[0]
y = pointer[1]
if big_list[x][y] == " ": #if it is space, add its location
explored.enqueue(pointer)
queue.enqueue(pointer)
big_list[x][y] = "#"
pointer = tra_model.move_right(pointer)
if big_list[x][y] == "%" or "#": #if it is hardle, move back
pointer = tra_model.move_right(pointer)
if big_list[x][y] == ".":#if it is goal, add its location
queue.enqueue(pointer)
explored.enqueue(pointer)
break
# Fourth move to the left and check what it is
pointer = tra_model.move_up(pointer)
x = pointer[0]
y = pointer[1]
if big_list[x][y] == " ": #if it is space, add its location
explored.enqueue(pointer)
queue.enqueue(pointer)
big_list[x][y] = "#"
pointer = tra_model.move_down(pointer)
if big_list[x][y] == "%" or "#": #if it is hardle, move back
pointer = tra_model.move_down(pointer)
if big_list[x][y] == ".": #if it is goal, add its location
queue.enqueue(pointer)
explored.enqueue(pointer)
break
expanded = 0
for i in explored.items:
expanded += 1
steps = 0
for item in explored.items:
t = tuple(item)
if t not in seen:
steps += 1
newExplored.push(item)
seen.add(t)
return newExplored, big_list, steps, expanded |
42fda3c35945c1d3c36078edf415161fc1c99fed | marianellamonroyortizhb/holbertonschool-higher_level_programming | /0x02-python-import_modules/2-args.py | 390 | 3.5625 | 4 | #!/usr/bin/python3
if __name__ == "__main__":
import sys
argum = sys.argv
size = len(argum) - 1
if size == 0:
print("0 arguments.")
elif size == 1:
print("1 argument:")
print("1: {}".format(argum[1]))
else:
print("{} arguments:".format(size))
for ind in range(1, size + 1):
print("{}: {}".format(ind, argum[ind]))
|
4a9d536187abe7763af32704ef898eac453fb8fe | KushalkumarUmesh/Internal-Initiative | /GoalSheet/empDash_Goalsheet_OnlineExam/realapp/shared/readconfig/appconfig.py | 1,258 | 3.53125 | 4 | import openpyxl
class AppConfig(object) :
def __init__(self, configInfile) :
self.configInfile = configInfile
self.attribute = {} # Dict of Attributes
self.readConfigFile()
#Reading the file, and save keyValue pairs, convert everything into String
def readConfigFile(self) :
conf_wb = openpyxl.load_workbook(self.configInfile)
ws = conf_wb.worksheets[0]
c_row = 0
circuitBreaker = 100
while circuitBreaker :
c_row += 1
circuitBreaker -= 1
c = ws.cell(row=c_row, column=1).value
v = ws.cell(row=c_row, column=2).value # Value
if c :
c=str(c) # Convert to String, just to be sure
c= c.strip() # Remove white space
v=str(v) # All Values are also treated as strings, its for the program to ensure that its correct number
v= v.strip() # Remove white space
if c == "END" : break
if v :
self.attribute[c] = v
else :
print("Variable{0} is does not have a value.format(c)")
return(1)
else :
continue
return (0) |
c8f55cee4f9d5b84ec85522c8b5ac9c3ee4ef909 | gabriellaec/desoft-analise-exercicios | /backup/user_020/ch6_2020_03_03_10_17_40_405609.py | 165 | 4.0625 | 4 | # Programa que converte temperaturas em Fahrenheit para Celsius
def celsius_para_fahrenheit(c):
f = ((9*c)/(5))+32
return f
print(celsius_para_fahrenheit(5)) |
47050ddd18aff093180dbece6141e20efb88c3a5 | himashugit/python_dsa | /function/funcwithargreturnvalue.py | 604 | 4.125 | 4 | '''
def add_num(a,b):
result=a+b
return result # here we're returning the value in result and result on the main func has addition...
def main():
a=eval(input("Enter your first num : "))
b=eval(input("Enter your sec num : "))
result=add_num(a,b)
print(f'addition of your number is {result}')
main()
'''
def multiply_num(c,d):
result1=c*d
return result1
def main():
a=eval(input("Enter your num1: "))
b=eval(input("Enter your num2: "))
result1=multiply_num(a,b)
print("multiplication of these two number", result1)
main()
#multiply_num(3,4)
|
05d322ede0904b4bacc6c55de3c478814393f4f1 | Mehedi-Bin-Hafiz/Udemy-Python-Programming-Beginners | /NumericDatatype/CompundOperatorAndOperatorPrecedence.py | 297 | 3.6875 | 4 | #compund operator
x=10
y=3
x%=y
print(x)
x += 10
print(x)
""" Notice there is no space between + and ="""
#operator precedence
#for precedence python follow BODMAS rule if there are same precedence operator are coming then it follow left associative rule
v=2+6/3
print(v)
v=2* 3/3
print(v)
|
ae761ad0121441d42c533212c27eb2e70ac0e486 | CMWatson2138/flask_app_yelp | /yelp_app.py | 3,565 | 3.5625 | 4 | #!/usr/bin/env python
#import libraries
import flask
from flask import Flask, json, render_template, redirect
import requests
import os
from bs4 import BeautifulSoup as bs
from lxml import html
#create instance of app
app = flask.Flask(__name__)
#greeting page
@app.route('/', methods = ['GET'])
def home():
return '''<h1>Top 50 Local Restaurants</h1>
<p>This site is an API for retrieval of information about the top 50 local restaurants to Benton Park, MO.</p>
<p>In order to access a scraping tool to retrieve urls for the top 50 restaurants visit: http://127.0.0.1:5000/api/v1/top50/urls<p>
<p>In order to access a scraping tool to retrieve this information: http://127.0.0.1:5000/api/v1/top50/scrape<p>
<p>In order to access a list of the top 50 restaurants and their details: http://127.0.0.1:5000/api/v1/top50/all<p>'''
@app.route('/api/v1/top50/urls', methods=['GET'])
def get_urls():
all_urls = []
for i in range(0, 50, 10):
url = f'https://www.yelp.com/search?find_desc=&find_loc=Saint%20Louis%2C%20MO%2063104&start={i}'
response = requests.get(url)
soup = bs(response.text, 'html.parser')
for item in soup.select('h4'):
try:
if item.find('a'):
href = item.find('a', href = True)
all_urls.append(href['href'])
except Exception as e:
raise e
print('')
with open('all_urls.json', 'w') as fout:
json.dump(all_urls, fout)
return '''<h1>all_urls have been received</h1>'''
@app.route('/api/v1/top50/scrape', methods=['GET'])
def yelp_scraped():
rest_dict={}
top_50=[]
all_urls = os.path.join('all_urls.json')
data_json_file = json.load(open(all_urls))
all_urls=data_json_file
#return render_template('index.html',data=data_json)
for url in all_urls:
path = "https://www.yelp.com" + url
response=requests.get(path)
soup = bs(response.text, 'html.parser')
tree = html.fromstring(response.content)
try:
restaurant=tree.xpath('//*[@id="wrap"]/div[2]/yelp-react-root/div[1]/div[3]/div[1]/div[1]/div/div/div[1]/h1/text()')
restaurant_location=tree.xpath('//*[@id="wrap"]/div[2]/yelp-react-root/div[1]/div[4]/div/div/div[2]/div/div[2]/div/div/section[1]/div/div[3]/div/div[1]/p[2]/text()')
phone = tree.xpath('//*[@id="wrap"]/div[2]/yelp-react-root/div[1]/div[4]/div/div/div[2]/div/div[2]/div/div/section[1]/div/div[2]/div/div[1]/p[2]/text()')
restaurant_website = tree.xpath('//*[@id="wrap"]/div[2]/yelp-react-root/div[1]/div[4]/div/div/div[2]/div/div[2]/div/div/section[1]/div/div[1]/div/div[1]/p[2]/a/text()')
price = tree.xpath('//*[@id="wrap"]/div[2]/yelp-react-root/div[1]/div[3]/div[1]/div[1]/div/div/span[2]/span/text()')
rest_dict={'name': restaurant, 'location': restaurant_location, 'phone_number': phone, 'website': restaurant_website, 'price_range': price}
top_50.append(rest_dict)
except Exception as e:
raise e
print('')
with open('outputfile.json', 'w') as fout:
json.dump(top_50, fout)
return redirect ('/api/v1/top50/all')
@app.route('/api/v1/top50/all', methods=['GET'])
#def api_all():
def home2():
json_url = os.path.join('outputfile.json')
data_json = json.load(open(json_url))
return render_template('index.html',data=data_json)
if __name__ == "__main__":
app.run(debug=True) |
5dc45f7b292cb30c096de4622b23a1c3786df0ab | jadilson12/studied | /python/56 - Nome - sexo - idade com for.py | 626 | 3.65625 | 4 | # Ano 2018
# exercício realizado durante o curso
# @jadilson12
a = 0
b = 0
c = 0
n = ''
for i in range(4):
nome = str(input('Digite o nome :')).strip()
idade = int(input('olá {} digite sua idade '.format(nome)))
sexo = str(input('Digite M para masculino e F para feminino ')).upper().strip()
a += idade
if sexo == 'M' and idade > b:
b = idade
n = nome
if sexo == 'F' and idade < 20:
c += 1
print('\nA média de idade do grupo é: {}'.format(a/4))
print('O homem mais velho é: {}'.format(n))
print('{} mulheres tem menos de 20 anos'.format(c))
|
40bf9f8db1ee3a036d177f51471f50d9dac69d2e | lvwuwei/pythoncode | /showmecode/day11/replaceword.py | 528 | 3.734375 | 4 | import os
def Words(path):
filterWords=[]
with open(path, 'r',encoding= 'utf-8') as f:
for word in f:
filterWords.append(word.strip('\n'))
print(filterWords)
return filterWords
if __name__=='__main__':
filterwords=Words('filtered_words.txt')
while(True):
myinput=input("input your line:")
for word in filterwords:
if word in myinput:
myinput=myinput.replace(word,''.join(['*' for x in range(len(word))]))
print(myinput) |
7ef1350e8d9f9371f66ed184c67b1a82aefc24d5 | TwoSails/SmartBlinds | /motor.py | 3,121 | 3.640625 | 4 | import RPi.GPIO as GPIO
from time import *
class Motor:
def __init__(self, steps):
self.delay = 0.0001 # Sets the delay between pulses - Basically controls the speed of the motor
self.PUL = 17 # Stepper Drive Pin
self.DIR = 27 # Direction Control Bit (HIGH for Controller default / LOW to Force a Direction Change)
self.ENA = 22 # Enable Control Bit (HIGH for Enable / LOW for Disable)
self.downSwitch = 6
self.upSwitch = 5
self.relay = 4
self.cycles = steps
def setup(self):
GPIO.setmode(GPIO.BCM) # Sets the mode for the GPIO Pins - NOTE: It will not work if it is in GPIO.BOARD
GPIO.setup(self.PUL, GPIO.OUT) # Sets up the pin for the Stepper Drive Pulse
GPIO.setup(self.DIR, GPIO.OUT) # Sets up the pin for the Directional Bit
GPIO.setup(self.ENA, GPIO.OUT) # Sets up the pin for the Enable Bit
GPIO.setup(self.downSwitch, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(self.upSwitch, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(self.relay, GPIO.IN, GPIO.PUD_UP)
def descend(self):
print('Motor - descending')
steps = 0
GPIO.output(self.ENA, GPIO.HIGH) # Enables the Stepper Driver
sleep(.5) # Allows for any updates
GPIO.output(self.DIR, GPIO.LOW) # Sets the direction of the motor
while steps <= self.cycles: # Pulses the motor for the length of the blinds
relay_state = GPIO.input(self.relay)
downStateSwitch = GPIO.input(self.downSwitch)
GPIO.output(self.PUL, GPIO.HIGH)
sleep(self.delay)
GPIO.output(self.PUL, GPIO.LOW)
sleep(self.delay)
steps += 1
if downStateSwitch == GPIO.LOW or relay_state == GPIO.LOW:
print('downSwitch')
GPIO.output(self.ENA, GPIO.LOW)
break
GPIO.output(self.ENA, GPIO.LOW) # Disables the Stepper Driver
sleep(.5) # Allows for any updates
return steps
def ascend(self):
print('Motor - ascending')
steps = 0
GPIO.output(self.ENA, GPIO.HIGH) # Enables the Stepper Driver
sleep(.5) # Allows for any updates
GPIO.output(self.DIR, GPIO.HIGH) # Sets the direction of the motor
while steps <= self.cycles: # Pulses the motor for the length of the blinds
relay_state = GPIO.input(self.relay)
upStateSwitch = GPIO.input(self.upSwitch)
GPIO.output(self.PUL, GPIO.HIGH)
sleep(self.delay)
GPIO.output(self.PUL, GPIO.LOW)
sleep(self.delay)
steps += 1
if upStateSwitch == GPIO.LOW or relay_state == GPIO.LOW:
print('Motor - downSwitch activated')
GPIO.output(self.ENA, GPIO.LOW)
break
GPIO.output(self.ENA, GPIO.LOW) # Disables the Stepper Driver
sleep(.5) # Allows for any updates
return steps
def cleanup(self):
GPIO.cleanup() # Cleans up the pins on the board
print('Motor - Cleaning Up GPIO')
|
5c724a58f658195c6b5e61f1907df90f2df8d64e | shonali-ks/HCI_lab | /assignment-1/gui.py | 1,728 | 3.734375 | 4 | import tkinter as tk
root = tk.Tk()
animals1=["dog","cat","cow"]
animals2=["horse","monkey","lion"]
animals3=["tiger","bear","gorilla"]
def button_pressed():
button.destroy()
label = tk.Label(root, text=" Dog\n\nCat\n\nCow\n\nHorse\n\nMonkey\n\nLion\n\nTiger\n\nBear\n\nGorilla\n\n")
label.pack()
root.after(8000, label.destroy)
root.after(8000,canvas1.pack)
button = tk.Button(root, text="Press Button to see the list", command=button_pressed)
button.pack()
canvas1 = tk.Canvas(root, width = 400, height = 300)
entry1 = tk.Entry (root)
canvas1.create_window(200, 140, window=entry1)
def getSquareRoot ():
x1 = entry1.get()
label = tk.Label(root, text= "Enter all the animals you remember in the form(small cases)- animal1,animal2,..")
label.pack()
x=x1.split(",")
first = 0
middle = 0
last = 0
for i in x:
if i in animals1:
first=first+1
elif i in animals2:
middle=middle+1
elif i in animals3:
last=last+1
else:
x.remove(i)
label2 = tk.Label(root, text="Following are the correct animal names\n")
label2.pack()
label1 = tk.Label(root, text=x)
label1.pack()
label3 = tk.Label(root, text="Analysis of first, middle and last respectively(percentage):-\n ")
label3.pack()
label4 = tk.Label(root, text=first*100/3)
label4.pack()
label5 = tk.Label(root, text=middle*100/3)
label5.pack()
label6 = tk.Label(root, text=last*100/3)
label6.pack()
canvas1.destroy()
entry1.destroy()
button1.destroy()
button1 = tk.Button(text='See the list', command=getSquareRoot)
canvas1.create_window(200, 180, window=button1)
root.mainloop() |
d773f9a4068e425b30f269544c616bdd4bf5d0ab | dorokhin/py.checkio | /Oreilly/median.py | 870 | 3.84375 | 4 | def checkio(data):
numbers = sorted(data)
center = len(numbers) / 2
if len(numbers) % 2 == 0:
center = int(center)
return sum(numbers[center - 1:center + 1]) / 2.0
else:
return numbers[int(center)]
checkio2 = lambda data: sorted(data)[len(data)//2] if len(data) % 2 == 1 else (sum(sorted(data)[len(data)//2-1:len(data)//2+1])/2)
if __name__ == '__main__':
print("Example:")
print(checkio([1, 2, 3, 4, 5]))
assert checkio([1, 2, 3, 4, 5]) == 3, "Sorted list"
assert checkio([3, 1, 2, 5, 3]) == 3, "Not sorted list"
assert checkio([1, 300, 2, 200, 1]) == 2, "It's not an average"
assert checkio([3, 6, 20, 99, 10, 15]) == 12.5, "Even length"
print("Start the long test")
assert checkio(list(range(1000000))) == 499999.5, "Long."
print("Coding complete? Click 'Check' to earn cool rewards!")
|
6ce82a7b800ed56b661803ddf812c58ea20e42fe | fleamon/algorithm_python | /programmers/level2/stack_and_queue/Tower_20190530.py | 646 | 3.5625 | 4 | # -*- encoding: utf-8
# https://programmers.co.kr/learn/courses/30/lessons/42588
"""
송신 탑(높이) 수신 탑(높이)
5(4) 4(7)
4(7) 2(9)
3(5) 2(9)
2(9) -
1(6) -
"""
def solution(heights):
answer = []
tmp = []
for i in range(len(heights) - 1, -1, -1):
for j in range(i - 1, -1, -1):
if heights[i] < heights[j]:
tmp.append(j + 1)
break
if j == 0:
tmp.append(0)
tmp.append(0)
for i in range(len(tmp) - 1, -1, -1):
answer.append(tmp[i])
return answer
print solution([6, 9, 5, 7, 4])
|
f7b313797b710974dc6f66acac5002f0a54ade1c | amit-kr-debug/CP | /Geeks for geeks/array/Implement two stacks in an array.py | 2,895 | 3.9375 | 4 | """
Your task is to implement 2 stacks in one array efficiently .
Example 1:
Input:
push1(2)
push1(3)
push2(4)
pop1()
pop2()
pop2()
Output:
3 4 -1
Explanation:
push1(2) the stack1 will be {2}
push1(3) the stack1 will be {2,3}
push2(4) the stack2 will be {4}
pop1() the poped element will be 3
from stack1 and stack1 will be {2}
pop2() the poped element will be 4
from stack2 and now stack2 is empty
pop2() the stack2 is now empty hence -1 .
Your Task:
Since this is a function problem, you don't need to take any input. Just complete the provided functions.
You are required to complete the 4 methods push1, push2 which takes one argument an integer 'x' to be pushed into
the stack one and two and pop1, pop2 which returns the integer poped out from stack one and two (if no integer is
present in the array return -1)
Expected Time Complexity: O(1) for all the four methods.
Expected Auxiliary Space: O(1) for all the four methods.
Constraints:
1 <= Number of queries <= 100
1 <= value in the stack <= 100
"""
#User function Template for python3
'''
Function Arguments :
@param : a (auxilary array),
top1 and top2 are declared as two tops of stack.
# initialized value of tops of the two stacks
top1 = -1
top2 = 101
@return : Accordingly.
'''
def pop1(a):
#code here
global top1
if top1 == -1:
pop = -1
else:
pop = a[top1]
top1 -= 1
return pop
def pop2(a):
#code here
global top2
if top2 == 101:
pop = -1
else:
pop = a[top2]
top2 += 1
return pop
def push1(a,x):
#code here
global top1
top1 += 1
a[top1] = x
def push2(a,x):
#code here
global top2
top2 -= 1
a[top2] = x
#{
# Driver Code Starts
#Initial Template for Python 3
import atexit
import io
import sys
#Contributed by : Nagendra Jha
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
top2=101
top1=-1
if __name__ == '__main__':
test_cases = int(input())
for cases in range(test_cases) :
n = int(input())
arr = list(map(int,input().strip().split()))
a = [-1 for i in range(101)] # array to be used for the 2 stacks.
i=0 # curr index
while i<len(arr):
if arr[i] == 1:
if arr[i+1] == 1:
push1(a,arr[i+2])
i+=1
else:
print(pop1(a),end=" ")
i+=1
else:
if arr[i+1] == 1:
push2(a,arr[i+2])
i+=1
else:
print(pop2(a),end=" ")
i+=1
i+=1
top2=101
top1=-1
print(' ')
# } Driver Code Ends |
95cd63f7172edb04a6d81716b0d50fb4662dd1c3 | Laksh8/competitive-programming | /recursion/Recursionbinarysearch.py | 319 | 3.90625 | 4 | def BinarySearch(start,end,lst,value):
mid = (start+end)//2
if lst[mid] == value:
return mid
elif lst[mid] > value:
return BinarySearch(start,mid,lst,value)
else:
return BinarySearch(mid,end,lst,value)
lst = [1,2,3,4,5,6,7,8,9,10]
print(BinarySearch(0,len(lst)-1,lst,7))
|
53a7f78605dffeb60fe651a85efc130b18f8945e | tariqrahiman/pyComPro | /leetcode/google/1340/l1340.py | 2,143 | 4.0625 | 4 | """leetcode.com/explore/interview/card/google/61/trees-and-graphs/1340/"""
class Tuple(tuple):
"""overload + for tuples with custom built class T"""
def __add__(self, other):
return Tuple(x+y for x, y in zip(self, other))
def __sub__(self, other):
return Tuple(x-y for x, y in zip(self, other))
def distance(self):
"""compute metric distance for tuple representing
(x, y) on a cartesian grid"""
return abs(self[0])+abs(self[1])
SEQ = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def move_to(robot, direction, start, end):
"""move_to procedure to make the robot move
Args:
robot: Robot instance
direction: (0, 1) ..
start: (x,y)
end: (x,y), important |end - start| == 1
Returns:
new_directions, end
"""
first, new_direction = SEQ.index(direction), end - start
second = SEQ.index(new_direction)
rotations = second - first if second > first else second + 4 - first
if rotations == 1:
robot.turnRight()
elif rotations == 2:
robot.turnRight(); robot.turnRight()
elif rotations == 3:
robot.turnLeft()
moved = robot.move()
return new_direction, end if moved else start
class Solution(object):
def cleanRoom(self, robot):
"""
:type robot: Robot
:rtype: None
"""
pos, direction = Tuple((0, 0)), Tuple((0, 1))
stack, visited, prev = [pos], set(), {}
while stack:
node = stack.pop()
# moves robot to node
while (pos - node).distance() > 1:
direction, pos = move_to(robot, direction, pos, prev[pos])
if (pos - node).distance() == 1:
direction, pos = move_to(robot, direction, pos, node)
# clean and get adj
robot.clean()
visited.add(node)
for adj in [Tuple((pos[0], pos[1]+1)), Tuple((pos[0], pos[1]-1)),
Tuple((pos[0]+1, pos[1])), Tuple((pos[0]-1, pos[1]))]:
if adj not in visited:
stack.append(adj)
prev[adj] = pos
|
682ac7c6655d29a6ac87e97cf3f30792038e68d4 | hateif/Protector | /protector/tests/sanitizer_test/test_sanitizer.py | 584 | 3.515625 | 4 | import unittest
from protector.sanitizer import sanitizer
class TestSanitizer(unittest.TestCase):
def setUp(self):
self.sanitizer = sanitizer.Sanitizer()
def test_parse_url(self):
"""
Test url parsing
"""
self.assertEqual(self.sanitizer.sanitize(""), "")
self.assertEqual(self.sanitizer.sanitize("SELECT * fROm bla where X=Y"), "select * from bla where x=y")
self.assertEqual(
self.sanitizer.sanitize("select%20*%20from%20bla%20where%20x%3Dy"),
"select * from bla where x=y"
)
|
6bccf19d3741ba8f08f7fb0bb5909c6c180b46a7 | MD-AZMAL/python-programs-catalog | /Data-Structures/graphs/dijkstra.py | 2,363 | 3.671875 | 4 | """ Author - Sidharth Satapathy """
""" This code is in python 3 """
import sys
from collections import defaultdict
class Edge(object):
def __init__(self,weight,start,end):
self.weight = weight
self.startNode = start
self.endNode = end
class Vertex(object):
def __init__(self,name):
self.name = name
self.visited = False
self.predecessor = None
self.neighbours = []
self.minDistance = sys.maxsize
def __cmp__(self,otherVertex):
return self.cmp(self.minDistance, otherVertex.minDistance)
def __lt__(self,otherVertex):
selfPriority = self.minDistance
otherPriority = self.minDistance
return selfPriority < otherPriority
class Graph(object):
def calculateShortestPath(self,startVertex):
q = []
startVertex.minDistance = 0
heapq.heappush(q,startVertex)
while len(q) > 0:
actualVertex = heapq.heappop(q)
for edge in actualVertex.neighbours:
u = edge.startNode
v = edge.endNode
newDistance = u.minDistance + edge.weight
if newDistance < v.minDistance:
v.minDistance = newDistance
v.predecessor = u
heapq.heappush(q, v)
def getShortestPath(self,targetVertex):
print (f"The shortest path to vertex targetVertex {targetVertex.name} is ",targetVertex.minDistance)
node = targetVertex
while node is not None:
print (" -> ",node.name)
node = node.predecessor
nodes = input("Enter the nodes separated by spaces : ")
nodes = nodes.split(" ")
allNodes = defaultdict()
for x in nodes :
allNodes[x] = Vertex(x)
choice = 1
while choice == 1:
edges = input("Enter the weight start vertex and end vertex separated by space : ")
edges = [allNodes[x] if x in allNodes.keys() else float(x) for x in edges.split(" ")]
edges[1].neighbours.append(Edge(edges[0],edges[1],edges[2]))
choice = int(input("Want to add another edge ? (1 - yes, 2 - no) : "))
startVert = input("Enter the node to calculate the shortest path from : ")
startVert = startVert.strip()
g = Graph()
g.calculateShortestPath(allNodes[startVert])
endVert = input("Enter the node to calculate the shortest path to : ")
g.getShortestPath(allNodes[endVert])
|
b9cc6e410249539b8240d272c3bdbf83cce69c24 | xiasiliang-hit/leetcode | /radix.py | 474 | 3.984375 | 4 | def radix_sort(array):
l = len(array)
re = [0]* l
for e in array:
re[e] = re[e] + 1
j = 0
result = [0]*l
for i in range(l):
# if re[i] != None:
count = re[i]
k = 0
while k < count:
result[j] = i
j = j+1
k = k+1
return result
if __name__ == "__main__":
array=[1,2,1,2,5,3,4,4,3]
print radix_sort(array)
|
82a2af7f98a8b4a41023959a7376607b2ba93989 | wisecube-cn/LeetCode | /0007 Reverse Integer.py | 1,011 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 20:49:01 2019
@author: 24283
"""
class Solution:
def reverse(x):
"""
:type x: int
:rtype: int
"""
global symbol
global reverse_number
global str_x
global y
symbol=int()
reverse_number=int()
str_x=list()
y=int()
if x<0:
y=-x
symbol=1
if x==0:
return 0
if x>0:
y=x
symbol=0
str_x = list(map(int, str(y)))
str_x.reverse()
n=len(str_x)
for i in range(n):
reverse_number=reverse_number+str_x[i]*10**(n-1-i)
if reverse_number>2147483647 or reverse_number<-2147483648 :
return 0
if symbol==1:
return -reverse_number
else:
return reverse_number
|
8857c486b00592eb64c1b950617da757504b80de | jessegtz7/Python-Learning-Files | /Loops.py | 955 | 4.4375 | 4 | #a for Loop is used for iterate over a sequence (that is either a list, tuple, dictionary, set or string).
empresas = ['IBM', 'DELL', 'HP', 'INTEL']
#Simple for loop
for posiblesTrabajos in empresas:
print(f'Posibles puestos en: {posiblesTrabajos}')
print('***Simple Loop***')
#Break that stops when the condition is found
for posiblesTrabajos2 in empresas:
if posiblesTrabajos2 == 'HP':
break
print(f'Posibles puestos en: {posiblesTrabajos2}')
print('***Loop and Break***')
#Continue
for posiblesTrabajos3 in empresas:
if posiblesTrabajos3 == 'IBM':
continue
print(f'Posibles puestos en: {posiblesTrabajos3}')
print('***Loop and Continue***')
#Range
for i in range(0, 5):
print(f'Numeros: {i}')
print('***loop and Range***')
#While Loops: execute a set of statements as long as a conditions is true
conteo = 0
while conteo <= 5:
print(f'Numeros: {conteo}')
conteo += 1
print('***loops and while***') |
6deae37e392e1b0e2f132de6f88ff0369ba97a7e | SeongHyukJang/HackerRank | /Python/Regex and Parsing/Re.findall() & Re.finditer().py | 236 | 3.8125 | 4 | import re
vowel = "aeiouAEIOU"
s = input()
pattern = r'(?<=[^%s])([%s]{2,})(?=[^%s])' %(vowel,vowel,vowel)
check = re.search(pattern,s)
if check == None:
print(-1)
res = re.finditer(pattern,s)
for i in res:
print(i.group())
|
48427936ef8b2fe265c80a3ce8850a8431dab617 | roysgitprojects/Unsupervised-Learning-Middle-Project | /data_set_preparations.py | 2,875 | 3.546875 | 4 | import pandas as pd
from sklearn.preprocessing import StandardScaler
def prepare_data_set(number_of_data_set):
"""
Prepare the data set for the clustering.
:param number_of_data_set: number of data set to be prepared
:return: prepared data
"""
if number_of_data_set == 1:
return prepare_data_set1()
elif number_of_data_set == 2:
return prepare_data_set2()
else:
return prepare_data_set3()
def prepare_data_set1():
"""
Prepare the first data set to clustering.
:return: prepared data
"""
data = pd.read_csv("dataset/online_shoppers_intention.csv")
# drop 3 last columns
data = data.drop(columns=['VisitorType', 'Weekend', 'Revenue'])
print(data.columns)
print(data.info)
# months strings to int
data['Month'] = data['Month'].astype('category')
cat_columns = data.select_dtypes(['category']).columns
data[cat_columns] = data[cat_columns].apply(lambda x: x.cat.codes)
return data
def prepare_data_set2():
"""
Prepare the second data set to clustering.
:return: prepared data
"""
data = pd.read_csv("dataset/diabetic_data.csv", skiprows=lambda x: x % 4 != 0)
# drop race and gender
data = data.drop(columns=['race', 'gender'])
data = data.replace({'?': None})
print(data)
print(data.dtypes)
for column in data.columns:
if data.dtypes[column] == 'object':
data[column] = data[column].astype('category')
cat_columns = data.select_dtypes(['category']).columns
data[cat_columns] = data[cat_columns].apply(lambda x: x.cat.codes)
print(data.dtypes)
print(data)
print("Impute missing values with the median value and check again for missing values:")
# impute with median
for column in data.columns:
data.loc[data[column].isnull(), column] = data[column].median()
print(data.isna().sum())
print("There are no missing values now")
return data
def prepare_data_set3():
"""
Prepare the third data set to clustering.
:return: prepared data
"""
data = pd.read_csv("dataset/e-shop clothing 2008.csv", sep=';', skiprows=lambda x: x % 10 != 0)
data = data.drop(columns=['country'])
data['page 2 (clothing model)'] = data['page 2 (clothing model)'].astype('category')
cat_columns = data.select_dtypes(['category']).columns
data[cat_columns] = data[cat_columns].apply(lambda x: x.cat.codes)
print(data.columns)
print(data.dtypes)
print(data['page 2 (clothing model)'])
return data
def scale_the_data(data):
"""
Scales the data
:param data: data to scale
:return: scaled data
"""
scaler = StandardScaler()
return scaler.fit_transform(data)
if __name__ == '__main__':
prepare_data_set1()
|
f097b0e13a7bfd2cc7d9a68c5eae7af309f248c0 | jlopezariza/Cursos | /ejercicios/maximo.py | 883 | 4.125 | 4 | # Pregunta al usuario por 2 numeros
# Vais a llamar a una funcion que os vais a definir llamada identificarMaximo(2 numeros)
# La funcion debe imprimir por pantalla el maximo valor
def identificarMaximo(numero1, numero2):
return numero1 if numero1>numero2 else numero2
#maximo=numero2
#if numero1 > numero2:
# maximo= numero1
#return maximo
def identificarMaximoDeTres(numero1, numero2, numero3):
return identificarMaximo(numero1, identificarMaximo(numero2, numero3))
print("Bienvenido al calculador del mayor numero")
numero1=int( input("Dame un número: ") )
numero2=input("Dame otro número: ")
maximo = identificarMaximo( numero1 , int(numero2) )
print("El máximo es: " + str(maximo) )
numero3=input("Dame otro número más: ")
maximo = identificarMaximoDeTres( numero1 , int(numero2), int(numero3) )
print("El máximo es: " + str(maximo) )
|
34c0a35a62bb8620b1b4daac4e39bb50031d9df6 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/bcoates/lesson08/circle.py | 1,914 | 4.40625 | 4 | #!/usr/bin/env python3
import math
class Circle(object):
def __init__(self, the_radius):
""" Initialize circle based on given radius """
self.radius = the_radius
def __str__(self):
return "Circle with radius: {}".format(self.radius)
def __repr__(self):
return "Circle({})".format(self.radius)
def __add__(self, circle_2):
total = self.radius + circle_2.radius
return Circle(total)
def __mul__(self, value):
total = self.radius * value
return Circle(total)
def __rmul__(self, value):
total = self.radius * value
return Circle(total)
def __lt__(self, circle_2):
if self.radius < circle_2.radius:
return True
else:
return False
def __eq__(self, circle_2):
if self.radius == circle_2.radius:
return True
else:
return False
@property
def diameter(self):
""" Calculate diamater based on radius """
return self.radius * 2
@diameter.setter
def diameter(self, the_diameter):
""" Set diameter to a given value """
self.radius = the_diameter / 2
@property
def area(self):
""" Calculate area based on radius """
return math.pi * (self.radius ** 2)
@classmethod
def from_diameter(cls, the_diameter):
""" Create a Circle directly with the diameter """
return cls(the_diameter / 2)
class Sphere(Circle):
def __str__(self):
return "Sphere with radius: {}".format(self.radius)
def __repr__(self):
return "Sphere({})".format(self.radius)
@property
def volume(self):
""" Calculate volume based on radius """
return 4 / 3 * math.pi * (self.radius ** 3)
@property
def area(self):
""" Calcuate area based on radius """
return 4 * math.pi * (self.radius ** 2) |
89e71a344754b694e1b3faf6a8ee5a820bb911de | aniltalaviya0114/demo | /Exercise 4/17.py | 290 | 3.6875 | 4 | class Whether:
a = 123
#print(hasattr(Whether,'a'))
if hasattr(Whether,'a') == True:
print("YES")
else:
print("NO")
print(getattr(Whether,'a'))
setattr(Whether,'a','Anil')
print(getattr(Whether,'a'))
delattr(Whether,'a')
print(getattr(Whether,'a'))
#print(delattr(Whether,'a')) |
613cc97ba446ee37c87e91fa5eedc78c230ad685 | ShreyasKadiri/CodeChef | /Word List.py | 553 | 3.828125 | 4 | wordList, tempList = list(), list()
for _ in range(int(input())):
tempList.extend(input().strip().lower().split(' '))
for word in tempList:
word = word.replace('\n', '')
word = word.replace('\'', '')
word = word.replace('.', '')
word = word.replace(',', '')
word = word.replace(':', '')
word = word.replace(';', '')
if len(word) > 0 and word not in wordList:
wordList.append(word)
tempList.clear()
wordList.sort()
print(len(wordList))
for word in wordList:
print(word)
|
ea16f93c31ccf02b1fc664c5d9ae959df8b50d0f | rtchavali/Algorithmica | /linked_list.py | 1,970 | 4.0625 | 4 | class Node(object):
def __init__(self, data=None, next=None):
self.data=data
self.next=next
class Linked_list(object):
def __init__(self, head=None, tail=None):
self.head=head
self.tail=tail
def show_elements(self):
print 'showing list elements'
current = self.head
while current is not None:
print current.data, "-->",
current = current.next
print None
def append(self, data):
next = Node(data, None)
if self.head == None:
self.head=self.tail=next
else:
self.tail.next = next
self.tail=next
def remove(self, next_value):
current=self.head
previous = None
while current is not None:
if current.data== next_value:
if previous is not None:
previous.next = current.next
else :
self.head=current.next
previous = current
current = current.next
def search(self, node_data):
current = self.head
node_point = 1
while current is not None:
if current.data == node_data:
print 'Element found at %s' % (node_point)
break
else :
current = current.next
node_point+=1
# below function need to be modified .. it is replacing , it should insert
def insert_arbitratry(self, position, new):
previous = current = self.head
new = Node(new, next)
while position is not 0:
current=current.next
previous=previous.next
position-=1
print position, previous, current
previous.next=new.next
new.next= current.next
s=Linked_list()
s.append(31)
s.append(2)
s.append(23)
s.insert_arbitratry(2, 12)
s.append(25)
s.show_elements()
s.remove(23)
s.append(55)
s.show_elements()
s.search(55)
|
fefc47ac908f9534a35c508cbcb9c05e60db7dcc | AnindhaxNill/URI | /BEGINNER/uri1070.py | 155 | 3.640625 | 4 | x = int(input())
count = 0
while True:
if(x%2 != 0):
count += 1
print(x)
x += 1
if(count == 6):
break
|
f04d70b6ce76c65ea61271e58ef84547239491f3 | Ihyatt/coderbyte_challenge | /simplesymbols.py | 873 | 4.3125 | 4 | def simple_symbols(str):
"""The str parameter will be composed of + and = symbols with several letters
between them (ie. ++d+===+c++==a) and for the string
to be true each letter must be surrounded by a + symbol. So the string to
the left would be false.
Example::
>>> simple_symbols("+d+=3=+s+")
True
>>> simple_symbols("f++d+")
False
"""
letters_symbols = list(str)
if letters_symbols[0].isalpha():
return False
if letters_symbols[-1].isalpha():
return False
idx = 1
while idx < len(letters_symbols) - 1:
if letters_symbols[idx].isalpha():
if letters_symbols[idx - 1] == "+" and letters_symbols[idx + 1] == "+":
return True
return False
#####################################################################
if __name__ == "__main__":
print
import doctest
if doctest.testmod().failed == 0:
print "*** ALL TESTS PASSED ***"
|
841906dfc17ca2b321885e2177bcfd6a55436070 | Alexkaer/dailyleetecode | /day017.py | 1,345 | 3.640625 | 4 | """
地址:https://leetcode.com/problems/remove-linked-list-elements/description/
描述:
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
思路:
这个一个链表基本操作的题目,思路就不多说了。
关键点:
链表的基本操作(删除指定节点)
虚拟节点dummy 简化操作
其实设置dummy节点就是为了处理特殊位置(头节点),这这道题就是如果头节点是给定的需要删除的节点呢? 为了保证代码逻辑的一致性,即不需要为头节点特殊定制逻辑,才采用的虚拟节点。
如果连续两个节点都是要删除的节点,这个情况容易被忽略。 eg:
// 只有下个节点不是要删除的节点才更新current
if (!next || next.val !== val) {
current = next;
}
"""
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = next
class Solution(object):
@staticmethod
def removeElements(head, val):
dummy_node = ListNode(val - 1)
dummy_node.next = head
prev = dummy_node
while prev.next is not None:
if prev.next.val == val:
prev.next = prev.next.next
else:
prev = prev.next
return dummy_node.next
|
dd9e9f4cc7ed3e5635f5ceb9479ce9cca1ee258c | Dhanya1234/python-assignment-7 | /assignment 7_ to count odd and even number.py | 246 | 4.0625 | 4 | num= (1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12)
countodd = 0
counteven = 0
for x in num:
if x % 2:
counteven+=1
else:
countodd+=1
print("Number of even numbers ",counteven)
print("Number of odd numbers ",countodd)
|
6b787e2b762b9d7ddf051ded9bf60b95e5249012 | jhoover4/algorithms | /cracking_the_coding/chapter_2-LinkedLists/6_palindrome.py | 1,867 | 4.375 | 4 | import unittest
from collections import deque
from .LinkedList import SinglyLinkedList
def palindrome(lis):
"""
Problem: Check if a linked list is a palindrome.
Answer: Check for palindrome using a stack. Use two pointers, the second will skip ahead by two to find the length.
Once length is found, we begin popping from the stack to check if there's a palindrome.
Time complexity: O(n)
:param LinkedList lis:
:return bool:
"""
pointer1 = lis.head
pointer2 = lis.head
if not pointer1 or not pointer1.next:
return False
stack = deque()
length = 1
length_found = False
while pointer1:
data = pointer1.data
if length_found:
last = stack.pop()
# Stack doesn't match
if last != data:
return False
else:
stack.append(data)
if pointer2.next and pointer2.next.next:
length += 2
pointer2 = pointer2.next.next
else:
if pointer2.next:
length += 1
length_found = True
# If its odd, don't need to repeat the middle entry
if length % 2 != 0:
stack.pop()
pointer1 = pointer1.next
return True
class Test(unittest.TestCase):
def test_is_palindrome(self):
linked_lis = SinglyLinkedList()
linked_lis.add(1)
linked_lis.add(2)
linked_lis.add(3)
linked_lis.add(2)
linked_lis.add(1)
self.assertTrue(palindrome(linked_lis))
def test_is_not_palindrome(self):
linked_lis = SinglyLinkedList()
linked_lis.add(1)
linked_lis.add(7)
linked_lis.add(3)
linked_lis.add(5)
linked_lis.add(1)
self.assertFalse(palindrome(linked_lis))
|
833b7943529abf4eb40f845b4e9f5cbe2c6666cd | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Kristy_Martini/lesson01/break_me.py | 901 | 3.71875 | 4 | def createNameError():
name = "Kristy"
try:
print("My name is " + nome)
except NameError:
print("You have a NameError")
def createTypeError():
name = "Kristy"
try:
new_name = name + 5
except TypeError:
print("You have a TypeError")
def createSyntaxError():
name = "Kristy"
# try:
# print name
# except SyntaxError:
# print("You have a SyntaxError")
def createAttributeError():
name = "Kristy"
try:
print(name.last())
except AttributeError:
print("You have an AttributeError")
def sleep_in(weekday, vacation):
if vacation:
return True
elif not weekday and not vacation:
return True
elif weekday and not vacation:
return False
if __name__ == "__main__":
createNameError()
createTypeError()
createSyntaxError()
createAttributeError()
|
ce64a60052e72a8a28f9727ef7671e0a57f131be | kiri3L/TPR | /LP.py | 688 | 3.53125 | 4 | from matplotlib import pyplot as plt
print("f(x) = C1x1 + C2x2")
c1 = int(input("C1 = "))
c2 = int(input("C2 = "))
print("f(x) = {}*x1 + {}*x2".format(c1, c2))
def value_in_poin():
a1 = int(input("A1 = "))
b1 = int(input("B1 = "))
d1 = int(input("D1 = "))
a2 = int(input("A2 = "))
b2 = int(input("B2 = "))
d2 = int(input("D2 = "))
D = a1 * b2 - a2 * b1
D1 = d1 * b2 - d2 * b1
D2 = a1 * d2 - a2 * d1
if D != 0:
print("{}/{} = {}".format(D1, D, D1 / D))
print("{}/{} = {}".format(D2, D, D2 / D))
print("f(x) = {}*{} + {}*{} = {}".format(c1, D1 / D, c2, D2 / D, c1 * (D1 / D) + c2 * (D2 / D)))
value_in_poin()
plt.show() |
29612e02938821bd37e1b1eaababae9e058446cd | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_4/208.py | 2,358 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Python for Google Code Jam 2008 Round 1
Minimum Scalar Product
'''
def solve_problems(inputs):
r'''Generate output for the problem
Example:
>>> input = """\
... 2
... 3
... 1 3 -5
... -2 4 1
... 5
... 1 2 3 4 5
... 1 0 1 0 1
... """
>>> print solve_problems(input)
Case #1: -25
Case #2: 6
<BLANKLINE>
'''
line = inputs.split("\n")
l = 0
num_cases = int(line[l])
l+=1
solution = []
for c in xrange(num_cases):
# parse out bits
size = int(line[l])
l+=1
v1 = [int(x) for x in line[l].split()]
l+=1
v2 = [int(x) for x in line[l].split()]
l+=1
assert(len(v1) == len(v2))
assert(len(v1) == size)
solution.append(solve(v1, v2))
output = []
for s, n in zip(solution, xrange(1, num_cases+1)):
output.append("Case #%d: %d"%(n, s))
return "\n".join(output) + "\n"
def solve(vec1, vec2):
'''Solve a problem instance
Example:
>>> v1 = [1,3,-5]
>>> v2 = [-2,4,1]
>>> print solve(v1, v2)
-25
'''
m = 10**10
p1s = all_perms(vec1)
p2s = all_perms(vec2)
for p1 in p1s:
for p2 in p2s:
sum = add(p1, p2)
#print p1, p2, sum, m
if sum < m: m = sum
return m
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
yield perm[:i] + str[0:1] + perm[i:]
def add(vec1, vec2):
sum = 0
for x, y in zip(vec1, vec2): sum += x*y
return sum
def _usage():
print "Usage: %s <input_file> <output_file>"%sys.argv[0]
print "If output_file omitted, printed to stdout"
def _test():
import doctest
return doctest.testmod()
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
_usage()
print "Running test suite..."
failed, total = _test()
if (not failed): print "All %d tests passed"%total
elif len(sys.argv) == 2:
inputs = file(sys.argv[1]).read()
print solve_problems(inputs)
elif len(sys.argv) == 3:
inputs = file(sys.argv[1]).read()
file(sys.argv[2],"w").write(solve_problems(inputs))
else:
_usage()
sys.exit(1)
|
dfaa047c3e395a2ad8d23588fc5651760733cf76 | ye-kyaw-thu/tools | /python/en-word-tokenizer.py | 654 | 3.90625 | 4 | import sys
import argparse
from nltk.tokenize import word_tokenize
# word tokenizing for English with NLTK library
# Written by Ye Kyaw Thu, LST, NECTEC, Thailand
# Reference: Python 3 Text Processing with NLTK 3 Cookbook
# How to run:
# python ./en-word-tokenizer.py ./en.sentence.txt
# cat en.sentence.txt | python ./en-word-tokenizer.py
# python ./en-word-tokenizer.py < ./en.sentence.txt
parser=argparse.ArgumentParser()
parser.add_argument('inputFile', default=sys.stdin, type=argparse.FileType('r'), nargs='?')
args=parser.parse_args()
textLines=args.inputFile.readlines()
count=0
for line in textLines:
count +=1
print(word_tokenize(line))
|
f20ecaaa68ce1eb927adfdb6474d29ee9a96f77b | SzymonLeszkiewicz/Wstep_do_algorymtow | /Lista 2/1.py | 2,549 | 3.71875 | 4 | import time, random, sys #time do mierzenia czasu oraz wstrzymywanie programu random to losowania liczb sys do zamykania
from statistics import mean #srednia
try:
q=int(input("Podaj ile elementow ma miec lista do posortowania: "))
b=int(input("Podaj dolna granice zakresu z ktorego ma byc losowana liczba: "))
c=int(input("Podak gorna granice zakresu: "))
except:
print("podano niepoprawna wartosc !")#wstrzymywanie programu w razie podania wartosci nie calkowitych
print("program zakonczy dzialanie za 5 sek ")
time.sleep(5)
sys.exit(0)
print("******************************************")
print()
czasy=list() #tworzenie listy na pomiary czsów
maks_bubble=0 #zmienna przechowywujaca maks czas
for pow in range(10): # losowanie 10 ciagów
a = list() #pusta lista na wylosowane wartosci
for x in range(q):
a.append(random.randint(b,c))#losowanie liczb calkowitych z podanego zakresu
start=time.time() #zmienna na czas początkowy
#sortowanie bąbekowe
for x in range(len(a)-1, 0, -1):
for y in range(0, x):
if a[y]>a[y+1]:
a[y], a[y+1]=a[y+1], a[y] #zamiana wartosci bez uzywania zmiennej tymczasowej
stop=time.time() #zmienna na czas koncowy
czas=stop-start #obliczanie czas wykonywania
czasy.append(czas)#dodawanie pomiaru do listy
if czas>maks_bubble:#wyznaczanie maks czasu
maks_bubble=czas
print("****BUBBLESORT****")
print("Średni czas: ", mean(czasy))# obliczanie średniego czasu Bubble
print("Maksymalnu czas: ", maks_bubble)
czasy=[]
maks_wybor=0
for pow in range(10): # losowanie 10 ciagów
a =[] #pusta lista na wylosowane wartosci
for x in range(q):
a.append(random.randint(b,c))#losowanie liczb calkowitych z podanego zakresu
start=time.time() #zmienna na czas początkowy
#sortowanie przez wybor
for i in range(0, len(a)):
k=i
for j in range(i+1, len(a)):# w tej petli szukamu indeksu najmniejszego elementu
if a[j]<a[k]: #znajdującego się najblizej poczatku tablicy
k=j
a[k], a[i]=a[i],a[k]# zamiana wartosci bez uzywania zmiennej pomocniczej
stop=time.time() #zmienna na czas koncowy
czas=stop-start #obliczanie czas wykonywania
czasy.append(czas)#dodawanie pomiaru do listy
if czas > maks_wybor:
maks_wybor=czas
print()
print("****SORTOWANIE PRZEZ WYBOR****")
print("Średni czas: ", mean(czasy))
print("Maksymalny czas: ", maks_wybor)
print()
print("PROGRAM ZAKONCZY DZIAŁANIE ZA 10 SEKUND")
time.sleep(10) |
9dc938231f569a18afd873a9502db7b3a81b2438 | matheus-nbx52/Python | /loteria.py | 516 | 3.84375 | 4 | amigo1 = float(input('quanto o amigo 1 apostou? '))
amigo2 = float(input('quanto o amigo 2 apostou? '))
amigo3 = float(input('quanto o amigo 3 apostou? '))
totala = amigo1 + amigo2 + amigo3
premio = float(input('qual o valor do premio? '))
valor1 = (amigo1/totala) * premio
valor2 = (amigo2/totala) * premio
valor3 = (amigo3/totala) * premio
print('o amigo 1 recebeu: {:.2f}, o amigo 2 recebeu: {:.2f}, o amigo 3 recebeu: {:.2f}'.format(valor1, valor2, valor3))
|
94ed7089d7659d56883f9dd6d9e3a600983cc5d7 | atashi/LLL | /python/test/test.py | 813 | 3.6875 | 4 | import unittest
from orderedSet import OrderedSet
class OrderedDictTestCase(unittest.TestCase):
def setUp(self):
self.ordSet = OrderedSet(list('abc'))
def tearDown(self):
self.ordSet = None
def test_init(self):
self.assertEqual(list(self.ordSet), list('abc'))
def test_contains(self):
self.assertTrue('a' in self.ordSet)
self.assertFalse('d' in self.ordSet)
def test_add(self):
self.ordSet.add('d')
self.assertTrue('d' in self.ordSet)
def test_remove(self):
self.ordSet.discard('a')
self.assertFalse('a' in self.ordSet)
def test_bool(self):
self.assertTrue(bool(self.ordSet))
def test_len(self):
self.assertEqual(len(self.ordSet), 3)
if __name__ == '__main__':
unittest.main()
|
329d29270db34fc5bfb1a9344838b2e8083d5c7b | largelymfs/lab_numeric_analysis | /lab3/exp3.py | 1,288 | 3.671875 | 4 | #-*- coding:utf-8 -*-
#lab 3
from equation import solve
from matplotlib import pyplot as plt
def OLS(n, x, y):
A = []
m = len(x)
if m!=len(y):
return None
for i in range(n + 1):
A.append([])
for j in range(n + 1):
if i <= j:
tmp = 0.0
for p in range(m):
#for q in range(m):
tmp += (float(x[p]) ** i) * (float(x[p]) ** j)
A[i].append(tmp)
else:
A[i].append(A[j][i])
B = []
for i in range(n+1):
tmp = 0.0
for p in range(m):
#for q in range(m):
tmp += (float(x[p]) ** i) * y[p]
B.append(tmp)
flag, answer = solve(A, B)
return answer
if __name__=="__main__":
x = [20, 25, 30, 35, 40, 45, 50, 55, 60]
y = [805, 985, 1170, 1365, 1570, 1790, 2030, 2300, 2610]
a = OLS(3, x, y)
f = []
for i in range(len(x)):
tmp = 1.0
tmp_f = 0.0
for j in range(len(a)):
tmp_f += tmp * a[j]
tmp *= x[i]
f.append(tmp_f)
print "Answer : ","\t",
for i in range(len(a)):
print i,"\t",
print
print "\t",
for i in range(len(a)):
print a[i],"\t",
print
print "Estimation\t\t Actual Value\t\t ERROR"
sum = 0.0
for i in range(len(y)):
print f[i],"\t\t",y[i],"\t\t",abs(f[i]-y[i])
sum += abs(f[i]-y[i])**2
print "TOTAL ERROR : ",sum
plt.plot(x, y,'r.',label="x-y")
plt.plot(x, f, 'g',label="x-f")
plt.legend()
plt.show() |
a2d7459279bdf181ebadb338da8e543d5b89ce5d | Azure-Whale/Kazuo-Leetcode | /Array/subarray/53. Maxium Subarray.py | 1,530 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@File : 53. Maxium Subarray.py
@Time : 10/21/2020 10:16 PM
@Author : Kazuo
@Email : azurewhale1127@gmail.com
@Software: PyCharm
'''
"""
Most used approach:
The idea here is to achieve global optimal solution from every local optimal solution
To get a maxium subarray, two things need to be get, the start and end of this subarray
Iterate the array:
Suppose we start from the index 0, and iterate following elements to see where we should end. B
But How to get to know where is the best the place to end, there are two cases:
1. The start need to be reset
2. Note the ending index make the subarray biggest so far and till you iterate the end of the whole array
Method 2 is easy to understand, just assume you have already get the start of your desirable subarray
Method 1, however, the only case there is a reason you should change your start is that the end is bigger than previous
extend. Since the end is bigger than previous sum, why not start from itself? So we update our start and then continue
the iteration till we found the optimal solution.
"""
#这个solution会返回start 和 end,只求sum的话不需要
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
curr_sofar = max_sofar = nums[0]
if not nums:
return None
for i in range(1,len(nums)):
if nums[i-1]>0:
nums[i] += nums[i -1]
curr_sofar = nums[i]
max_sofar = max(max_sofar, curr_sofar)
return max_sofar
|
0d35b5307ae40b5e9571b7de4a014ed34c063db9 | bob7757/Repo | /Fizz_Buzz.py | 271 | 3.65625 | 4 | def fizz_buzz(number):
fizz_check = number % 3
buzz_check = number % 5
if fizz_check == 0:
print("Fizz")
if buzz_check == 0:
print("Buzz")
if buzz_check != 0 and fizz_check != 0:
print(number)
print("Name Jeff")
fizz_buzz(11) |
ef48385dacc3df34cf6a67ae741940aed90b83a4 | sureshrmdec/algorithms | /app/arrays/longest_contiguous_subarray_sum.py | 484 | 3.75 | 4 | """
Find contiguous subarray of maximum sum in an array of positive and negative integers
eg - [2, 4, -5, 6, -10, 21, 4]
cumulative_sum = [2, 6, 1, 7, - 3, 18, 22] (A)
min_cum_sum; starting with 0 = [0, 0, 0, 0, - 3, -3, -3] (B)
do A - B at each step [2, 6, 1, 7, 0, 21, 25]
also keep an array of indices for A,B.
Hence, it works in a greedy way with O(n). Some people incorrectly call it dynamic programing
""" |
2ad15faff84a762dc0279aad43da5c85e168d618 | shahaddhafer/Murtada_Almutawah | /Challenges/weekThree/dayTwo.py | 1,835 | 4.125 | 4 | # Remove Blanks
# ---------------------------------------------------------------------------------------------
# Create a function that, given a string, returns the string, without blanks. Given " play that
# Funky Music ", returns a string containing "playthatFunkyMusic".
def removeBlanks(givenStr):
text = ''
for char in givenStr:
if not(char.isspace()):
text += char
return text
testString1 = ' play that Funky Music '
print(removeBlanks(testString1))
# Get String Digits
# ---------------------------------------------------------------------------------------------
# Create a JavaScript function that given a string, returns the integer made from the string’s
# digits. Given "0s1a3y5w7h9a2t4?6!8?0", the function should return the number 1,357,924,680.
def getStringDigits(givenStr):
text = ''
for char in givenStr:
if char.isdigit():
text += char
return int(text)
testString2 = '0s1a3y5w7h9a2t4?6!8?0'
print(getStringDigits(testString2))
# Acronyms
# ---------------------------------------------------------------------------------------------
# Create a function that, given a string, returns the string’s acronym (first letters only,
# capitalized). Given "there's no free lunch - gotta pay yer way", return "TNFL-GPYW". Given
# "Live from New York, it's Saturday Night!", return "LFNYISN".
def acronyms(givenStr):
text = ''
traceBool = True
for char in givenStr:
if (traceBool and not(char.isspace())):
text += char
traceBool = False
elif (char.isspace()):
traceBool = True
return text.upper()
testString3 = 'there\'s no free lunch - gotta pay yer way'
testString4 = 'Live from New York, it\'s Saturday Night!'
print(acronyms(testString3))
print(acronyms(testString4))
|
53e0f4826f2921f68fc3c5f275a01eaaa1ce459e | hasirto/7 | /5raise.py | 202 | 3.84375 | 4 | while True:
bölünen=int(input("bölünen sayi :"))
if bölünen==8:
raise Exception("bu programda 8 sayısını görmek istemiyorum")
#raise exception özel hata oluşturur |
de6afda4f902247b2564d347e687f5621d9a3bed | csgn/MY_DOCS | /pyNotes/note02.py | 384 | 3.75 | 4 | #!/usr/bin/env python
from datetime import date, datetime
class Book:
def __init__(self, author:str, name:str, issueDate:date, numberOfPages:int):
self.author = author
self.name = name
self.issueDate = issueDate
self.numberOfPages = NumberOfPages
x = Book("Paulo Coelho", "Alchemist", date(2018, 3, 5), 140)
print(x.author, x.name, x.issueDate, x.numberOfPages)
|
28c534da960b44e0156e5ac5d1157835656cff46 | joaovicentefs/cursopymundo2 | /exercicios/ex0048.py | 175 | 3.75 | 4 | soma = 0
cont = 0
for c in range(1, 501, 2):
if c % 3 == 0:
soma = soma + c
cont = cont +1
print('O resultado final de todos os {} números é de {}'.format(cont, soma))
|
44442503e11ba082cc5668bf3d2da0f87fb54956 | coderfengyun/TCSE2012 | /WeeklyCode/week5/Path Sum/gaoqiang.py | 693 | 3.8125 | 4 | # Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
targetValue = 0
def hasPathSum(self, root, sum):
self.targetValue = sum
return self.dfs(root,0)
def dfs(self, root, sum):
if root==None:
return False
sum = sum+root.val
if sum==self.targetValue and root.left==None and root.right==None:
return True
result = self.dfs(root.left, sum)
if result:
return result
result = self.dfs(root.right, sum)
return result
|
010d299557d7833509f72b6989a49cf6874c24fa | Aasthaengg/IBMdataset | /Python_codes/p04029/s686428555.py | 210 | 3.65625 | 4 | import math
import collections
import fractions
import itertools
import functools
import operator
def solve():
n = int(input())
print((n*(n+1))//2)
return 0
if __name__ == "__main__":
solve()
|
6cc3c6bee7536c0cdc14f472f0f8484480dfc65a | twdockery/PythonProgramming | /Lab12P3P4Helper/drone.py | 594 | 3.5 | 4 | class Drone:
def __init__(self):
# initialize self.__speed to 0
# initialize self.__height to 0
def accelerate(self):
# increase self.__speed by 10
def decelerate(self):
# decrease self.__speed by 10
# if self.__speed is less than 0, change it to 0
def ascend(self):
# increase self.__height by 10
def descend(self):
# decrease self.__height by 10
# if self.__height is less than 0, change it to 0
def __str__(self):
return "Speed: " + str(self.__speed) + " Height: " + str(self.__height)
|
7f352f37b4c8f97b81df4a57fec34f62fd41df18 | pavanmurugesh2002/unit1-2 | /unit1-2.py | 1,388 | 3.703125 | 4 | print('enter your name the height, length and width of your desired pool')
name = int(input()) #square and rectangle
height = int(input())
length = int(input())
width = int(input())
volume = (length * width * height * 7.5)
print(name, volume)
print('enter your name height diameter radius of your desired pool')
name1 = int(input()) #cylinder
height = int(input())
diameter = int(input())
radius = diameter/2
import math
from math import pi
print (name1,((pi*radius**2)*h*5.875))
print('first enter all four of your names the your respective gpas')
student1 = int(input()) # Average GPA
student2 = int(input())
student3 = int(input())
student4 = int(input())
gpa1 = int(input())
gpa2 = int(input())
gpa3 = int(input())
gpa4 = int(input())
print(student1,student2,student3,student4,(gpa1 + gpa2 + gpa3 + gpa4)/4)
print('digit by digit enter a two digit number that you want swapped')
tens = int(input()) # Swapping digits of two digit numbers
ones = int(input())
print(tens,ones)
print(ones,tens)
year = int(input()) # print century giver year
import math
from math import floor
century = floor(year/100) + 1
print(century)
print('enter an a, b, and h value respectively')
a = int(input()) #snail
b = int(input())
h = int(input())
movement = (a - b)
print(h/movement)
k = int(input())
day = ((k%7) + 4)
print(day)
|
db6e253679a179aef969da38d1fc6e61396b5614 | lonelyarcher/leetcode.python3 | /BackTrack_Pruning_BFS_Counter_Hash_691_Stickers to Spell Word.py | 3,607 | 4.3125 | 4 | """ We are given N different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given target string by cutting individual letters from your collection of stickers and rearranging them.
You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
What is the minimum number of stickers that you need to spell out the target? If the task is impossible, return -1.
Example 1:
Input:
["with", "example", "science"], "thehat"
Output:
3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
Example 2:
Input:
["notice", "possible"], "basicbasic"
Output:
-1
Explanation:
We can't form the target "basicbasic" from cutting letters from the given stickers.
Note:
stickers has length in the range [1, 50].
stickers consists of lowercase English words (without apostrophes).
target has length in the range [1, 15], and consists of lowercase English letters.
In all test cases, all words were chosen randomly from the 1000 most common US English words, and the target was chosen as a concatenation of two random words.
The time limit may be more challenging than usual. It is expected that a 50 sticker test case can be solved within 35ms on average. """
'''
based on the input size, it should be a search question, but can be optimized by backtracking
'''
import collections
from typing import List
class Solution_BFS:
def minStickers(self, stickers: List[str], target: str) -> int:
collections.Counter.__hash__ = lambda self: hash(tuple(sorted(self.items()))) #override __hash__ function of Counter
t = collections.Counter(target)
s = [collections.Counter(sticker) for sticker in stickers]
step = 0
seen = {t}
q = collections.deque([t])
while q:
l = len(q)
for _ in range(l):
cnt = q.popleft()
if sum(cnt.values()) == 0: return step
for ss in s:
if list(cnt.keys())[-1] in ss: # Pruning, when use sticker to substract target, the order is irrelevant to result.
#so we can first choose must substract one of character (here I pick the last one of counter keys) in target, then next character, the minimum step must be one of selections.
nt = cnt - ss
if sum(nt.values()) == 0: return step + 1
if nt not in seen:
q.append(nt)
seen.add(nt)
step += 1
return -1
import functools
class Solution_DFS:
def minStickers(self, stickers: List[str], target: str) -> int:
collections.Counter.__hash__ = lambda self: hash(tuple(sorted(self.items()))) #override __hash__ function of Counter
t = collections.Counter(target)
s = list(map(collections.Counter, stickers))
if set(t).difference(*s): return -1 # set difference() = setA - setB, it can accept multiple arguments *
@functools.lru_cache(None)
def dfs (t):
return 1 + min(dfs(t - cnt) for cnt in s if [*t][0] in cnt) if t else 0 #same pruning as BFS
return dfs(t)
s = Solution_DFS()
print(s.minStickers(["these","guess","about","garden","him"], "atomher")) #3
print(s.minStickers(["with", "example", "science"], "thehat")) #3
print(s.minStickers(["notice", "possible"], "basicbasic")) #-1
|
d7b1677598c30b4540da30ef5e092142478c1977 | HoangAce/ExerciseCodeforcer | /1549A.py | 200 | 3.703125 | 4 | def main():
for i in range(int(input())):
P = int(input())
if P % 2 == 0:
print(2, P)
else:
print(2, P - 1)
if __name__ == '__main__':
main()
|
3ac38e167523e1f9a3891746951872908e34fcf0 | litvinovserge/WebAcademy | /HomeWork_09/logic_v1.py | 2,356 | 4.03125 | 4 | class TicTacToe:
"""
Main Logic class - для игры крестики-нолики. Работает только с игровой сеткой NxN
"""
def __init__(self, current_game, win_conditions=3):
self.current_game = current_game
self.win_conditions = win_conditions
self.go()
def go(self):
return any((
self.horizontal_check(),
self.vertical_check(),
self.diagonal_main_check(),
self.diagonal_reverse_check()
))
# 0 - определяем условия для победы
def is_winner(self, current_result):
return any((
'x' * self.win_conditions in current_result,
'o' * self.win_conditions in current_result
))
# 1 - поиск победителя по горизонтали - по линиям
def horizontal_check(self):
for line in self.current_game:
current_line = ''
for element in line:
current_line += element
return self.is_winner(current_line)
# 2 - поиск победителя по вертикали - по столбцам
def vertical_check(self):
for line in range(len(self.current_game)):
current_column = ''
for column in range(len(self.current_game[line])):
current_column += self.current_game[column][line]
return self.is_winner(current_column)
# 3 - поиск победителя по главной диагонали
def diagonal_main_check(self):
current_diagonal = ''
for i in range(len(self.current_game)):
current_diagonal += self.current_game[i][i]
return self.is_winner(current_diagonal)
# 4 - поиск победителя по обратной диагонали
def diagonal_reverse_check(self):
current_diagonal = ''
for i in range(len(self.current_game)):
current_diagonal += self.current_game[-i - 1][i]
return self.is_winner(current_diagonal)
if __name__ == '__main__':
test = [
['x', 'q', 's', 'x', 'a'],
['a', 'x', 'o', 'x', ''],
['x', '', 'x', 'i', ''],
['w', 'x', '', 'x', ''],
['x', '', '', '', '']
]
game = TicTacToe(test, 5)
print(game.go())
|
1ef8b00918375ff2e1a8e60b0e44cef0bddf69a4 | sandeep256-su/python | /atmadv.py | 3,005 | 3.921875 | 4 | #atm system
class atm:
"""docstring for atm."""
i=1 #transaction fail attempts
j=1 #pin attempts
bal = 20000.00 #innitial balance
def __init__(self, pin):
self.pin = pin
def security(self):
z=int(8888) # ATM pin
if self.pin==z:
print('\n--------------Welcome to Python Bank---------------')
atm.banking()
else:
if atm.j<=3:
print('wrong pin, attempts left:',4-atm.j)
print('\n')
atm.j+=1
start()
else:
print('\n')
print('Your ATM card is locked plz contact Karthik for pin')
def banking():
print('\nEnter your choice')
key = int(input('---> 1 withdrawal\n---> 2 Deposit\n---> 3 Balacne\n---> 4 Exit\nEnter the transaction number: '))
if key == 1:
atm.withdraw()
elif key == 2:
atm.deposit()
elif key==3:
atm.balance()
elif key==4:
atm.exit()
else:
print('\n')
print('enter valid key')
atm.retry()
def withdraw():
print('\n')
amt = float(input('enter amount to withdraw: '))
if atm.bal <= amt:
print('\n')
print('insufficient fund')
elif amt<100:
print('\n')
print('min balance to withdraw is 100')
else:
atm.bal = atm.bal - amt
print('\n')
print('%d withdrawn from account'%amt)
print('balance',atm.bal)
atm.retry()
def deposit():
print('\n')
amt = float(input('enter amount to deposit: '))
if amt<100:
print('\n')
print('min balance to deposit is 100')
else:
atm.bal = atm.bal + amt
print('\n')
print('%d withdrawn from account'%amt)
print('balance',atm.bal)
atm.retry()
def balance():
print('\n')
print('balance',atm.bal)
atm.retry()
def exit():
import sys
print('\n')
print('-----------------thank you for using ATM--------------')
sys.exit()
def retry():
print()
e = input('\n Press c to continue \n Press n to exit\n (c/n): ')
if e=='c':
atm.banking()
elif e=='n':
atm.exit()
else:
i=1
if i<=3:
print('\n')
print('inalid key, attempts left:',4-atm.i)
atm.i+=1
atm.retry()
else:
print('\n')
print('you tried max limit')
atm.exit()
atm.i+=1
def start():
print('Enter your ATM card pin: ')
p = atm(int(input()))
p.security()
start()
|
d7155cf88281b39f0f4c7996b9b73ae49533222c | js6450/Intro-to-CS | /class assignments/alive_day_calculator.py | 329 | 4.09375 | 4 | import time
import datetime
year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))
today = datetime.date.today()
days_lived = datetime.date(today.year, today.month, today.day)\
- datetime.date(year, month, day)
print("You have lived: " + str(days_lived.days) + " days")
|
a9116f94927e6bf2bf7a1f4afc57b7c36e953782 | tapioka324/atcoder | /TTPC/2015/a.py | 129 | 3.59375 | 4 | S = input()
if S[2] == 'B':
ans = 'Bachelor'
elif S[2] == 'M':
ans = 'Master'
else:
ans = 'Doctor'
print(ans ,S[:2])
|
997ed1074701aa5e892eaeb7d4fbbfa19555c9b2 | RichieSong/algorithm | /算法/Week_03/55. 跳跃游戏.py | 1,185 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
示例 1:
输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
示例 2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
解题思路:
"""
from typing import *
class Solution:
def canJump(self, nums: List[int]) -> bool:
"""能到达的最远位置"""
reach = 0
for i in range(len(nums)):
if i > reach:
return False
reach = max(i + nums[i], reach)
return True
def canJump1(self, nums: List[int]) -> bool:
"""倒推 :假设能到达最后位置,向前推"""
end = len(nums) - 1
for i in range(end, -1, -1):
if nums[i] + i >= end:
end = i
return end == 0
|
01ed46978b20be74dfd19f042ef5b22d2a1a95e0 | DESPEL/programacion-python | /P4 CURP Reborn/lib.py | 663 | 3.53125 | 4 | from os import system
def is_convertible(type_, val):
try:
type_(val)
return True
except ValueError:
return False
def safe_input(
verifier,
msg="",
errmsg="Ingrese algo válido",
loop=True,
type_=str
):
val = input(msg)
while loop and not (is_convertible(type_, val) and verifier(type_(val))):
val = input(errmsg)
return type_(val)
def typed_input(type_, msg="", errmsg="Ingrese algo válido", loop=True):
val = input(msg)
while loop and not is_convertible(type_, val):
val = input(msg)
return type_(val)
def clear_screen():
system("cls")
|
2cf90b7217a555e0f0a1f066674394b3d932e069 | danielns-op/CursoEmVideo | /Python/exercicios/ex025.py | 116 | 3.515625 | 4 | cidade = str(input('Seu nome completo: ')).strip()
print('Possuí SILVA: {}'.format('SILVA' in cidade.upper()))
|
225bddb5442524d498255240b174b2c1f1a6ec15 | xuedong/leet-code | /Problems/Algorithms/1971. Find If Path Exists in Graph/find_path.py | 755 | 3.640625 | 4 | #!/usr/bin/env python3
from collections import defaultdict
from typing import List
class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
graph = defaultdict(set)
for edge in edges:
x, y = edge
graph[x].add(y)
graph[y].add(x)
visited = set()
queue = [source]
while len(queue) > 0:
curr = queue.pop(0)
if curr not in visited:
if curr == destination:
return True
for neighbor in graph[curr]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(curr)
return False
|
be5445d8e582a2aa362b564d05d5a434a62f3c88 | alex-mocanu/EPFL | /Semester 2/Information Security and Privacy/Homework/Hw3/ex2c.py | 2,235 | 3.515625 | 4 | import re
import sys
import hashlib
def generate_pwds(word, mappings):
# Generate all possible passwords according to the available types of changes
pwds = [word, word.title()]
for m in mappings:
pwds = pwds + [w.replace(m, mappings[m]) for w in pwds]
return set(pwds)
if __name__ == '__main__':
# Read encrypted passwords
with open('data/hw3_ex2.txt', 'r') as f:
data = f.read().split('\n')
# Check if to read salt and hash or just hash
if sys.argv[2] == 'b':
enc_pwds = data[12:22]
elif sys.argv[2] == 'c':
enc_pwds = data[23:33]
salts = [x.split(', ')[0] for x in enc_pwds]
enc_pwds = [x.split(', ')[1] for x in enc_pwds]
else:
print('Wrong task provided as second parameter')
sys.exit(1)
# Read dictionary
with open(sys.argv[1], 'r', errors='ignore') as f:
words = f.read().split('\n')
# Keep only words containing alphanumeric characters
words = list(filter(lambda x: re.match('^[\w-]+$', x) is not None, words))
pwds = {}
mappings = {'e': '3', 'o':'0', 'i':'1'}
for word in words:
# Finish searching if we've retrieved all passwords
if len(pwds) == len(enc_pwds):
break
# Generate possible passwords from the original word
possible_pwds = generate_pwds(word, mappings)
# Check if any of the passwords matches any of the ecrypted ones
for p in possible_pwds:
# Check if salt is needed
if sys.argv[2] == 'b':
enc_p = hashlib.sha256(p.encode()).hexdigest()
if enc_p in enc_pwds:
print("Match", enc_p, p)
pwds[enc_p] = p
else:
for salt, enc_pwd in zip(salts, enc_pwds):
enc_p = hashlib.sha256((p + salt).encode()).hexdigest()
if enc_p == enc_pwd:
print("Match", enc_p, p)
pwds[enc_p] = p
# Write passwords to file
with open(f'ex2c.txt', 'w') as f:
res = ''
for enc_p in enc_pwds:
res += pwds[enc_p] + ','
f.write(res[:-1]) |
d48c17cbace2fb74b18d8021875b3f10636ddc10 | artorious/python3_dojo | /custom_modules/get_integer_in_range.py | 1,451 | 4.28125 | 4 | #!/usr/bin/env python3
"""Prompt user for an integer within the specified range
"""
def get_int_in_range(first, last):
""" (int, int) -> int
Prompt user for an integer within the specified range
<first> is either a min or max acceptable value.
<last> is the corresponding other end of the range, either a min or max
acceptable value.
Returns an acceptable value from the user
"""
if isinstance(first, int) and isinstance(last, int):
if first > last: # If larger no. is provided 1st
first, last = last, first # Switch the parameters
# Insist on value in the range <first>...<last>
try:
in_value = int(input('Enter value in the range {0} .... {1} : '\
.format(first, last)))
while in_value < first or in_value > last:
print('{0} IS NOT in the range {1} .... {2}'.format(in_value, first, last))
in_value = int(input('Try again: '))
return in_value
except ValueError as err:
return err
else:
return 'Expected an integers. int_in_range({0}, {1}) not surpported' \
.format(type(first), type(last))
if __name__ == '__main__':
print(__doc__)
print(get_int_in_range(-100, 100))
print(get_int_in_range(10, 20))
print(get_int_in_range(5, 5))
print(get_int_in_range(-1, 1)) |
efcecf121022879dcc17971179d74c192bf39274 | ilahoti/csci-101-102-labs | /102/Week2B-list_slicing.py | 416 | 3.703125 | 4 | # Ishaan Lahoti
# CSCI 102 – Section C
# Week 2 - Lab B - List Slicing
# References: None
# Time: 30 minutes
print("Enter your string:")
words = str(input("STRING> "))
print("Enter four numbers to slice the string")
first = int(input("A> "))
second = int(input("B> "))
third = int(input("C> "))
fourth = int(input("D> "))
newfirst = words[first:second+1]
newsec = words[third:fourth+1]
print("OUTPUT", newfirst, newsec)
|
5b63d94333fd9e6b6d7e8aa845788e88a915c464 | leetcode-notebook/wonz | /solutions/1390-Four-Divisors/1390.py | 906 | 3.703125 | 4 | from typing import List
class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
sum = 0
for x in nums:
if x == 1 or x == 2 or x == 3:
continue
num = 2
temp = [1, x]
# 计算因数
while num ** 2 <= x: # 用 num^2 <= x 比 num <= sqrt(x) 好
if len(temp) > 4:
break
if not x % num:
if num not in temp:
temp.append(num)
if int(x/num) not in temp:
temp.append(int(x/num))
num += 1
# print(temp)
if len(temp) == 4:
for _ in temp:
# print(_)
sum += _
return int(sum)
if __name__ == "__main__":
nums = [21,4,7]
print(Solution().sumFourDivisors(nums)) |
921cc217991348e085128559647078cacb007fa0 | ravaliv/Competitive_programming | /week-1/day-5/RotationIndex.py | 1,328 | 3.75 | 4 | import unittest
def find_rotation_point(words):
starting_word = words[0]
last_index = 0
first_index = len(words)-1
while last_index<first_index:
guess_word = last_index+((first_index-last_index)/2)
if words[guess_word] >= starting_word:
last_index = guess_word
else:
first_index = guess_word
if last_index +1 == first_index:
return first_index
return -1
class Test(unittest.TestCase):
def test_small_list(self):
actual = find_rotation_point(['cape', 'cake'])
expected = 1
self.assertEqual(actual, expected)
def test_medium_list(self):
actual = find_rotation_point(['grape', 'orange', 'plum',
'radish', 'apple'])
expected = 4
self.assertEqual(actual, expected)
def test_large_list(self):
actual = find_rotation_point(['ptolemaic', 'retrograde', 'supplant',
'undulate', 'xenoepist', 'asymptote',
'babka', 'banoffee', 'engender',
'karpatka', 'othellolagkage'])
expected = 5
self.assertEqual(actual, expected)
unittest.main(verbosity=2)
|
e9df51d6b27a736b1be4fe83e39aee3db64cb349 | architpandita/dataStructure | /maxSubarray.py | 1,659 | 3.96875 | 4 | #maximum sum array
"""
1. using(Kadane’s Al) optimized technique with O(n) time complexity
2. sum the elements in order and if val is greater than maxsm will update maxsm;
3. sum will continue till its sum of subarray is greater than 0, which mean it will have somthing to addup in total sum;
4. for all neg 2 step will help
"""
def maxSumOpt(arr):
maxsm=-9999
tillmax=0
for i in range(len(arr)):
tillmax+=arr[i]
if tillmax >maxsm:
maxsm=tillmax
if tillmax<=0:
tillmax=0
return maxsm
#arr=[-2, -3, 4, -1, -2, 1, 5, -3]
"""
naive technique using 2 loops with O(n^2) time complexity.
"""
def maxSumNaive(arr):
sum=0
maxtillnow=-999999
n=len(arr)
for i in range(0,n):
sum=0
for j in range(i,n):
sum+=arr[j]
if sum>maxtillnow:
maxtillnow=sum
return maxtillnow
"""
using Divide and conqure technique with O(nlog(n)) time complexity.
"""
def maxSumMidDAC(arr, l, m, r):
sm=0 # initalize sum
lsm=-99999 #very small no. to set lower limit of max sum
for i in range(m,l-1,-1):
sm+=arr[i]
if sm > lsm:
lsm=sm
sm=0
rsm=-99999
for i in range(m+1, r+1):
sm+=arr[i]
if sm > rsm:
rsm=sm
return rsm+lsm
def maxSumDAC(arr, l, r):
"""
Divde the list in three part 1) left to mid 2) right to mid and 3) crossover at mid
then will retain the value which is max in above three cases
Provide start point and lenght of array
"""
if (l==r):
return arr[l]
m=(l+r)//2
return max(maxSumDAC(arr,l,m),maxSumDAC(arr,m+1,r), maxSumMidDAC(arr, l, m, r))
arr=[-2, -3, 4, -1, -2, 1, 5, -3]
print( maxSumNaive(arr))
print(maxSumDAC(arr,0 , len(arr)-1))
print(maxSumOpt(arr))
|
befbe72242b33b7343e638cac71414237a0acc6f | hyelim-kim1028/lab-python | /lec02_control/WHILE03.py | 1,544 | 3.9375 | 4 | #반복문 연습 3
# 1 + 2 + 3 + ... 100 = ?
#Using while
# n = 1
# sum = 0
# while n <= 100:
# sum = sum + n
# n += 1
# print(sum)
total, n = 0, 1 #이렇게 변수를 선언할 수도 있다
while n <= 100:
total += n
n += 1
print(total)
#Using For: My answer/ Wrong
# total = 0 #shadow built-in name 'sum' (sum 이라는 함수가 있다) # 이제는 썸이라는 함수는 사용할 수 없다 (shift + F6)
# for i in range(1, 101):
# total = total + total[i] #sum += x
# if i > 101:
# break
# print(total)
# shift + F6: refactor/rename 이라는 기능
# 변수 이름을 바꿔주겠다! 라는 것
# 바꾸고싶은 기능에다 커서를 누르고 shift + F6 그러면 모든 sum이 내가 지정한 이름 (total)로 바뀐다
# Teacher's solution
# total = 0
# for x in range(1,101):
# total += x
# print(f'sum = {total}') # Indent here means to show all the calculated numbers
#Method 2
# n=100
# print((n*(n+1))/2)
#Method 3: List comprehension
# numbers = [x for x in range(1,101)]
# print(sum(numbers))
# Question 2: 1 + 2 + 3+ ... + x <= 100
#Using while
# n = 1
# sum = 0
# while n:
# sum = sum + n
# n += 1
# if sum == 100:
# break
# print(f'{sum},{n}')
total = 0
x = 1
while True:
total += x
print(f'x = {x}, sum = {total}')
if total > 100:
break
x +=1
# total, x = 0,1
# while total <= 100:
# total += x
# print(f'x = {x}, sum = {total}')
# x+=1
#Using for
# sum = 0
# for i in range(1,101):
# sum = sum + sum[i]
|
d67abf27ddbcbf729e43daed1fd7ae7a6e182c61 | martinezpl/Strive | /M6/mini projects/car_detection/car_detection.py | 1,758 | 3.765625 | 4 | '''
Create a classifier to detect cars in an image
If at least one car was detected write Car Detected (in Green) on top of the image, otherwise write No car detected (in Red)
Save the image to disk
Show the image result inside the notebook
Make it work with a video
Put a bounding box around the cars detected
Get a higher resolution video and extract the car plates and save them to disk
'''
import cv2
def detect_cars(image, classifier):
# Convert the image to grayscale
img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Using the classifiers detect all cars on the image
cars = classifier.detectMultiScale(img_gray, minNeighbors = 4, minSize = (20, 20))
# Draw a rectangle on each car that has been detected
for (x,y,w,h) in cars:
cv2.rectangle(image, (x,y), (x+w, y+h), (0,255,0), 2)
#cv2.putText(image, f"{w * h}", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 1)
return image
if __name__ == "__main__":
cap = cv2.VideoCapture('videos/video.avi')
# FOR RECORDING
#width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) + 0.5)
#height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) + 0.5)
#size = (width, height)
#fourcc = cv2.VideoWriter_fourcc(*'XVID')
#out = cv2.VideoWriter('test.avi', fourcc, 20.0, size)
cv2.namedWindow('preview')
cv2.moveWindow("preview", 2000, 100)
car_classifier = cv2.CascadeClassifier('haarcascade_car.xml')
while cap.isOpened():
rval, frame = cap.read()
frame_f = detect_cars(frame, car_classifier)
cv2.imshow("preview", frame_f)
#out.write(frame_f)
key = cv2.waitKey(20)
if key == 27: # exit on ESC
break
cap.release()
#out.release()
cv2.destroyWindow("preview")
|
07a0843d6b0eec2314ba614d751d1493767b33f6 | escape0707/usaco_trainings | /milk.py | 945 | 3.5625 | 4 | """
ID: totheso1
LANG: PYTHON3
TASK: milk
"""
from typing import List
fin = open("milk.in", "r")
fout = open("milk.out", "w")
def fprint(*args, **kwargs) -> None:
print(*args, file=fout, **kwargs)
# Code start
MAX_PRICE = 1000
N, M = map(int, fin.readline().split())
# quotation_collection = list(tuple(map(int, line.split())) for line in fin)
# quotation_collection.sort()
# cost = 0
# for quotation in quotation_collection:
# buy_unit = min(quotation[1], N)
# cost += buy_unit * quotation[0]
# N -= buy_unit
# if N == 0:
# break
# fprint(cost)
count_by_cost: List[int] = [0] * (MAX_PRICE + 1)
for line in fin:
unit_cost, unit_count = map(int, line.split())
count_by_cost[unit_cost] += unit_count
total_cost = 0
for cost, count in enumerate(count_by_cost):
buy_unit = min(count, N)
total_cost += cost * buy_unit
N -= buy_unit
if N == 0:
break
fprint(total_cost)
# Code end
|
27a111c5a47de068f9c2ef57ee88480108c27c60 | ankurgajurel/PythonBasicsAnkur | /for_loop_list.py | 760 | 4.46875 | 4 | #working with list
numbers = []
#for loop for number between 1 to 20 inclusive
print("Numbers between 1 to 20 inclusive\n")
for number in range(1,21):
numbers.append(number)
print (numbers)
#for loop for the odd number between 1 to 20 inclusive
print("Odd numbers between 1 to 20 inclusive\n")
for i in range(2,22,2):
numbers.remove(i)
print (numbers)
#for loop for multiple of 3 upto 20
print("Table of Three:\n")
for prod in range(1,21):
print (" 3 * " + str(prod) + " = " + str(prod * 3))
#list of cubes
cubes = []
for i in range(1,11):
cubes.append(i**3)
print("FROM FOR LOOP:\n")
print (cubes)
#list comprehension
cubes = [num**3 for num in range(1,11)]
print("FROM LIST COMPREHENSION:\n")
print (cubes)
|
b35b27430b012d22f3e4fd897f0674ae47c96a05 | xinjianChen/python-- | /bracketMatch.py | 1,113 | 3.5625 | 4 | def checkOut(arg):
#判断长度是否大于等于2
length = len(arg)-1
#判断长度是否为偶数
if length<1 or length & 1 == 0:
return False
#储存括号种类
leftParenthesis = "("
rightParenthesis = ")"
leftBrackets = "["
rightBrackets = "]"
leftBrace = "{"
rightBrace = "}"
#栈
stack = []
while length>=0:
#栈为空时取最右一个入栈
if len(stack)==0:
stack.append(arg[length])
length -= 1
#获取栈顶括号和字符串当前括号
argCur = arg[length]
stackCur = stack[len(stack)-1]
#校验,匹配则删除,不匹配则入栈
if stackCur == rightBrace and argCur == leftBrace:
stack.pop()
elif stackCur == rightBrackets and argCur == leftBrackets:
stack.pop()
elif stackCur == rightParenthesis and argCur == leftParenthesis:
stack.pop()
else:
stack.append(argCur)
length -= 1
#栈为空时匹配正确
if len(stack)==0:
return True
return False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.