blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
0841a731df7c492819267af739a51675eff73436 | oguipcj/ListaDeExercicios | /EstruturaDeDecisao/7.py | 3,008 | 4.25 | 4 | # 7. Faça um Programa que leia três números e mostre o maior e o menor deles.
primeiro_numero = float(input("Digite o primeiro número:"))
segundo_numero = float(input("Digite o segundo número:"))
terceiro_numero = float(input("Digite o terceiro número:"))
if primeiro_numero == segundo_numero and segundo_numero == terceiro_numero: # elif primeiro_numero == segundo_numero == terceiro_numero:
print("Os números são iguais.")
else:
#confere o(s) maior(es)
if primeiro_numero > segundo_numero and primeiro_numero > terceiro_numero: # if segundo_numero < primeiro_numero > terceiro_numero:
print("O maior número é o primeiro:", primeiro_numero)
elif segundo_numero > primeiro_numero and segundo_numero > terceiro_numero: # elif primeiro_numero < segundo_numero > terceiro_numero:
print("O maior número é o segundo:", segundo_numero)
elif terceiro_numero > primeiro_numero and terceiro_numero > segundo_numero: # elif primeiro_numero < terceiro_numero > segundo_numero:
print("O maior número é o terceiro:", terceiro_numero)
else:
if primeiro_numero == segundo_numero:
print("O primeiro número (",primeiro_numero,") e o segundo número (",segundo_numero,") são maiores que o terceiro número (",terceiro_numero,").")
elif primeiro_numero == terceiro_numero:
print("O primeiro número (",primeiro_numero,") e o terceiro número (",terceiro_numero,") são maiores que o segundo número (",segundo_numero,").")
elif segundo_numero == terceiro_numero:
print("O segundo número (",segundo_numero,") e o terceiro número (",terceiro_numero,") são maiores que o primeiro número (",primeiro_numero,").")
#confere o(s) menor(es)
if primeiro_numero < segundo_numero and primeiro_numero < terceiro_numero: # if segundo_numero < primeiro_numero > terceiro_numero:
print("O menor número é o primeiro:", primeiro_numero)
elif segundo_numero < primeiro_numero and segundo_numero < terceiro_numero: # elif primeiro_numero < segundo_numero > terceiro_numero:
print("O menor número é o segundo:", segundo_numero)
elif terceiro_numero < primeiro_numero and terceiro_numero < segundo_numero: # elif primeiro_numero < terceiro_numero > segundo_numero:
print("O menor número é o terceiro:", terceiro_numero)
else:
if primeiro_numero == segundo_numero:
print("O primeiro número (",primeiro_numero,") e o segundo número (",segundo_numero,") são menores que o terceiro número (",terceiro_numero,").")
elif primeiro_numero == terceiro_numero:
print("O primeiro número (",primeiro_numero,") e o terceiro número (",terceiro_numero,") são menores que o segundo número (",segundo_numero,").")
elif segundo_numero == terceiro_numero:
print("O segundo número (",segundo_numero,") e o terceiro número (",terceiro_numero,") são menores que o primeiro número (",primeiro_numero,").")
|
4793dfc338f66ac4fd66f3b43d4785eb82842a32 | XihangJ/leetcode | /BFS/463. Island Perimeter.py | 2,045 | 3.703125 | 4 | '''
You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
'''
class Solution:
#method 1. BFS. O(n^2), S(n^2)
def islandPerimeter(self, grid: List[List[int]]) -> int:
queue = collections.deque()
visited = set()
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
for x in range(len(grid)):
for y in range(len(grid[0])):
if grid[x][y] == 1:
break
if grid[x][y] == 1:
break
queue.append((x, y))
visited.add((x, y))
count = 0
while queue:
x, y = queue.popleft()
count += self.decideType(grid, x, y)
for direction in directions:
dx, dy = direction
curr_x = x + dx
curr_y = y + dy
if (curr_x >= 0 and curr_x < len(grid) and curr_y >= 0 and curr_y < len(grid[0])
and grid[curr_x][curr_y] == 1 and (curr_x, curr_y) not in visited):
visited.add((curr_x, curr_y))
queue.append((curr_x, curr_y))
return count
def decideType(self, grid, x, y):
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
count = 0
for direction in directions:
dx, dy = direction
curr_x = x + dx
curr_y = y + dy
if curr_x < 0 or curr_x >= len(grid) or curr_y < 0 or curr_y >= len(grid[0]) or grid[curr_x][curr_y] == 0:
count += 1
return count
|
22e99c6dcdf463a4dd3a06f797c57b136529e5ff | yuxluo/umtri_label | /XDG_CACHE_HOME/Microsoft/Python Language Server/stubs.v1/M2KcDmVDYL_Yq1CJMCom4n3OUETWJLIvUfy8ZvHg0Zw=/python3._elementtree.pyi | 5,923 | 3.703125 | 4 | class Element(object):
__class__ = Element
def __copy__(self):
pass
def __deepcopy__(self, memo):
pass
def __delitem__(self, key):
'Delete self[key].'
return None
def __getattribute__(self, name):
'Return getattr(self, name).'
pass
def __getitem__(self, key):
'Return self[key].'
pass
def __getstate__(self):
pass
def __init__(self, *args, **kwargs):
pass
@classmethod
def __init_subclass__(cls):
'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n'
return None
def __len__(self):
'Return len(self).'
return 0
def __repr__(self):
'Return repr(self).'
return ''
def __setitem__(self, key, value):
'Set self[key] to value.'
return None
def __setstate__(self, state):
return None
def __sizeof__(self):
return 0
@classmethod
def __subclasshook__(cls, subclass):
'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n'
return False
def append(self, subelement):
pass
@property
def attrib(self):
"A dictionary containing the element's attributes"
pass
def clear(self):
pass
def extend(self, elements):
pass
def find(self, path, namespaces):
pass
def findall(self, path, namespaces):
pass
def findtext(self, path, default, namespaces):
pass
def get(self, key, default):
pass
def getchildren(self):
pass
def getiterator(self, tag):
pass
def insert(self, index, subelement):
pass
def items(self):
pass
def iter(self, tag):
pass
def iterfind(self, path, namespaces):
pass
def itertext(self):
pass
def keys(self):
pass
def makeelement(self, tag, attrib):
pass
def remove(self, subelement):
pass
def set(self, key, value):
pass
@property
def tag(self):
'A string identifying what kind of data this element represents'
pass
@property
def tail(self):
'A string of text directly after the end tag, or None'
pass
@property
def text(self):
'A string of text directly after the start tag, or None'
pass
class ParseError(SyntaxError):
__class__ = ParseError
__dict__ = {}
def __init__(self, *args, **kwargs):
pass
@classmethod
def __init_subclass__(cls):
'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n'
return None
__module__ = 'xml.etree.ElementTree'
@classmethod
def __subclasshook__(cls, subclass):
'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n'
return False
@property
def __weakref__(self):
'list of weak references to the object (if defined)'
pass
def SubElement():
pass
class TreeBuilder(object):
__class__ = TreeBuilder
def __init__(self, *args, **kwargs):
pass
@classmethod
def __init_subclass__(cls):
'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n'
return None
@classmethod
def __subclasshook__(cls, subclass):
'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n'
return False
def close(self):
pass
def data(self, data):
pass
def end(self, tag):
pass
def start(self, tag, attrs):
pass
class XMLParser(object):
__class__ = XMLParser
def __getattribute__(self, name):
'Return getattr(self, name).'
pass
def __init__(self, *args, **kwargs):
pass
@classmethod
def __init_subclass__(cls):
'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n'
return None
@classmethod
def __subclasshook__(cls, subclass):
'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n'
return False
def _parse_whole(self, file):
pass
def _setevents(self, events_queue, events_to_report):
pass
def close(self):
pass
def doctype(self, name, pubid, system):
pass
def feed(self, data):
pass
__doc__ = None
__name__ = '_elementtree'
__package__ = ''
|
7d4ff1656699d4f507c8a6892e917fc30fbce73b | Anuvrat-Singh/SeleniumWD_Python | /Practice/classesAndObj.py | 551 | 3.703125 | 4 | class fruit():
def __init__(self):
print("fruit created")
def nutrition(self):
print("This is a nutritiuos fruit")
def fruit_shape(self):
print("The fruit is cylindrical")
class kiwi(fruit):
def __init__(self):
super(kiwi, self).__init__()
print("Kiwi is created")
def nutrition(self):
print("Kiwi has vitamin c")
def color(self):
print("Kiwi skin color is brown")
#
# f = fruit()
# f.nutrition()
# f.fruit_shape()
k = kiwi()
k.nutrition()
k.fruit_shape()
k.color() |
eab81bbc5c4abeb93569572f6b23f4bc4b4f7992 | tony148565/BPlusTree | /main.py | 3,719 | 3.53125 | 4 | from Bplustree import Bplustree
import csv
fn = "C:/Users/user/PycharmProjects/bptree/output_big5.csv"
# output_big5.csv
# test.csv
def build(a, b):
with open(fn) as csvFile:
csv_reader = csv.reader(csvFile)
lists = list(csv_reader)
csvFile.close()
lists.remove(lists[0])
# print(lists)
new_tree = Bplustree()
dicts = new_tree.merge_data(lists, a, b)
for k in lists:
if k[1] in new_tree.course_name:
continue
else:
new_tree.course_name[k[1]] = k[2]
for i in dicts:
# print(i)
# print(dicts[i])
ll=[]
ll.append(str(i))
new_tree.sett(ll, dicts[i])
print(new_tree.course_name)
return new_tree
# print(dicts)
# print("B+tree create complete")
# ins = str(input())
# ser = []
# ser.append(ins)
# print(dicts[tree.get(ser)])
aa = 0
while True:
# c = "BPlusTree no exist"
if aa == 0:
tree = build(0, 1)
c = "BPlusTree Build Complete (Default)(Sort By StudentID)"
aa = 3
if aa == 1:
c = "BPlusTree Build Complete (Sort By StudentID)"
elif aa == 2:
c = "BPlusTree Build Complete (Sort By CourseID)"
print(c)
print("What are you want to do?")
print("1. Insert data")
print("2. Delete data")
print("3. build BPlusTree by StudentID")
print("4. build BPlusTree by CourseID")
print("5. search")
print("6. Exit")
# print(type(tree))
choose = input()
if choose == "1":
print("Insert")
key = input()
value = input()
ll = []
ll.append(key)
# li = []
# li.append(value)
# set data to B+tree
if value not in tree.course_name:
print("this course is new course")
print("please type the course name")
new_course = input()
tree.course_name[value] = new_course
tree.insert(key, value) # add data to dicts
tree.sett(ll, tree.dicts[key])
elif choose == "2":
key = input()
ll = []
ll.append(key)
print("Delete ", key, "all data?(y/n)")
scan = input().upper()
if scan == "Y":
try:
tree.remove_item(ll) # remove item in B+tree
if aa == 2:
print("Do you want to remove this course", key, "(y/n)?")
sc = input()
if sc == "y":
del tree.course_name[key]
except ValueError:
print(key, "is not in list")
elif scan == "N":
print("type studentID or CourseID:")
value = input()
print(type(tree.dicts[key]))
tree.dicts[key].remove(value) # remove data in dicts
else:
print("incorrect command!!!")
elif choose == "3":
print("build")
tree = build(0, 1)
a = "BPlusTree Build Complete (Sort By StudentID)"
aa = 1
print()
elif choose == "4":
print("build")
tree = build(1, 0)
a = "BPlusTree Build Complete (Sort By CourseID)"
aa = 2
print()
elif choose == "6":
break
elif choose == "5":
print("type studentID or CourseID")
ins = str(input())
ser = []
ser.append(ins)
try:
lisss = tree.get(ser)
print(lisss)
for i in lisss:
print(i, " ", tree.course_name[i])
except ValueError:
print(ins, "is not in list")
else:
print("incorrect command!!!")
|
3a4b50731f55c808cb779f73a7eb045a4acb0bc4 | jochumb/adventofcode | /2019/python/03.py | 1,706 | 3.5625 | 4 | def part1(wires):
paths = [path(wire) for wire in wires]
intersections = list(set(paths[0]) & set(paths[1]))
manhattans = [abs(i[0]) + abs(i[1]) for i in intersections]
return min(manhattans)
def part2(wires):
paths = [path(wire) for wire in wires]
intersections = list(set(paths[0]) & set(paths[1]))
steps = [sum(path.index(i) + 1 for path in paths) for i in intersections]
return min(steps)
def path(wire):
return calc_path(wire, (0,0), [])
def calc_path(wire, cur, path):
if len(wire) == 0:
return path
res = section(cur, wire[0])
return calc_path(wire[1:], res[-1], path + res)
def section(cur, direction):
if direction[0] == "R":
return [(cur[0] + n, cur[1]) for n in range(1, direction[1]+1)]
elif direction[0] == "L":
return [(cur[0] - n, cur[1]) for n in range(1, direction[1]+1)]
elif direction[0] == "U":
return [(cur[0], cur[1] + n) for n in range(1, direction[1]+1)]
elif direction[0] == "D":
return [(cur[0], cur[1] - n) for n in range(1, direction[1]+1)]
def intersections(wire1, wire2):
distances = {}
for intersection in list(set(wire1) & set(wire2)):
distances[abs(intersection[0]) + abs(intersection[1])] = intersection
return distances
def parse_directions(wire):
return [parse_direction(direction) for direction in wire.split(",")]
def parse_direction(direction):
return direction[0], int(direction[1:])
if __name__ == "__main__":
with open("../input/03") as f:
wires = [parse_directions(line) for line in f.readlines()]
print('Part 1: {}'.format(part1(list(wires))))
print('Part 2: {}'.format(part2(list(wires)))) |
5353968fce6015ec3f0be46381f56fc238ac32f2 | EonKid/HackerrankProblemSolving | /migratoryBirds.py | 600 | 3.6875 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
# https://www.hackerrank.com/challenges/migratory-birds/problem
def migratoryBirds(arr):
arr_types = [0]*5
for type in arr:
count = arr_types[type-1]
count += 1
arr_types[type-1] = count
return arr_types.index(max(arr_types)) + 1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
ar_count = int(raw_input())
ar = map(int, raw_input().rstrip().split())
result = migratoryBirds(ar)
fptr.write(str(result) + '\n')
fptr.close() |
6f41f85494878ba603cc1ec18df79ab17106dc41 | PMiskew/Year9DesignTeaching2020_PYTHON | /Simple_Game_Example/game_stage_clicklocation.py | 1,968 | 4.09375 | 4 | import tkinter as tk
import tkinter.font as tkFont
#Binding Source Link
#https://www.python-course.eu/tkinter_events_binds.php
def motion(event):
print("Mouse position: (%s %s)" % (event.x, event.y))
def click(event):
print("click")
x = event.x
y = event.y
if not(100 < x < 200 and 100 < y < 200):
print("outside")
canvas.create_oval(x,y,x+5,y+5,fill = "blue")
def drawcheckerboard():
#Creates 10 by 10 checkerboard:
canvas.create_rectangle(100,100,200,200);
ypos = 100;
for j in range(0,5,1):
#The inside loop fills in an entire row.
for i in range(100,200,20):
#The two rows are offset, we only draw the black squares.
canvas.create_rectangle(i,ypos,i + 10,ypos + 10,fill="black") #first row
canvas.create_rectangle(i+10,ypos + 10,i + 20,ypos + 20,fill="black") #second row
#shifts the drawing position down 20 pixles. This is two rows since each row is 10 pixles.
ypos = ypos + 20;
root = tk.Tk()
#https://effbot.org/tkinterbook/canvas.htm
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
#The outside loop is for the rows. It completes two rows at a time to account for
#the alternation between white and black first square.
'''
j = 0
i = 100 RUN LOOP CODE
B
B
i = 120 RUN LOOP CODE
B B
B B
i = 140 RUN LOOP CODE
B B B
B B B
i = 160 RUN LOOP CODE
B B B B
B B B B
i = 180 RUN LOOP CODE
B B B B B
B B B B B
i = 200 EXIT LOOP
ypos = ypos + 20
j = 1
i = 100 RUN LOOP CODE
B B B B B
B B B B B
B
B
i = 120 RUN LOOP CODE
B B B B B
B B B B B
B B
B B
i = 140 RUN LOOP CODE
B B B B B
B B B B B
B B B
B B B
i = 160 RUN LOOP CODE
B B B B B
B B B B B
B B B B
B B B B
i = 180 RUN LOOP CODE
B B B B B
B B B B B
B B B B B
B B B B B
i = 200 EXIT LOOP
'''
drawcheckerboard()
#drawcheckerboard(100)
canvas.bind('<Motion>',motion) #bind a mouse motion listener
canvas.bind('<Button-1>',click) #bind a mouse motion listener
root.mainloop();
|
f0e008b24a72712c5f07c797da15002c350235c9 | KimYeong-su/sw_expert | /D3/exponential1217.py | 260 | 3.53125 | 4 | def expo(number, Many):
if Many == 1:
return number
return number*expo(number,Many-1)
cases = 10
for case in range(cases):
n = int(input())
num, m = map(int, input().split())
result = expo(num, m)
print(f'#{case+1} {result}')
|
416210c6fc7f394a82e7e06e44a8de9a94e21427 | sunrain0707/python_exercise_100 | /ex12.py | 260 | 3.609375 | 4 | #12.判断101-200之间有多少个素数,并输出所有素数。
import math
x = True
for i in range(101,200):
for j in range(2,int(math.sqrt(i))+1):
if i%j == 0:
x = False
if x == True:
print(i)
x = True |
7b77226958cc484adbb8e8dfd3a51530cc3e9431 | Mukesh010/Python-Programs | /Formula Validation.py | 3,416 | 4.03125 | 4 | # We used Topological sorting for validation of given equations in formula.
# This Topological sort function provides order of nodes in a Directed Graph based on dependency and empty list if a cycle is present
# We took input of equations and created a dictionary ‘dic’ according to dependency
# e.g. Followings are input equations:
# A = B+C
# B= I/J
# C = F*G
# These will represent following dictionary and Directed Graph structure:
# dic = {'c': ['a'], 'f': ['c'], 'g': ['c'], 'b': ['a'], 'i': ['b'], 'j': ['b'], 'a': []}
# A
# / \ # Assume these are arrow in upward direction (represents dependency)
# B C
# /\ /\
# I J F G
# This dictionary is used in Topological sort as input
# We used one more dictionary ‘eqn’ to print output result in order provided from Topological sort
# e.g. : In previous example eqn value will be:
# eqn = {'c': 'c = f*g', 'b': 'b = i/j', 'a': 'a = b+c'}
# Assuption Each input equation is valid equation where Left hand value is always character
# Input format:
# First line is an integer value which represents number of equations
# After that each line represents and equation
def Topologicalsort(G):
in_degree = {u: 0 for u in G} # calculate in-degree value of each node
for u in G:
for v in G[u]:
in_degree[v] += 1
Q = [] # Initialize Queue as empty list
for u in in_degree: # collect nodes which have zero in-degree
if in_degree[u] == 0:
Q.append(u)
result = [] # initialized output order
while (len(Q) > 0):
u = Q.pop(0) # choose node which in-degree value is zero
result.append(u) # 'remove' it from Graph G
for v in G[u]:
in_degree[v] -= 1 # Decrease degree of each adjacent node of current node
if in_degree[v] == 0:
Q.append(v)
if len(result) == len(G):
return result # return calculated order
else: # if a cycle is present
return [] # return an empty list
# Assuption Each input equation is valid equation where Left hand value is always character
N = input("Enter number of equations ") # Input number of equations
N = int(N)
eqn = {} # Initialized dictionary 'eqn' for storing equations (It helps in final output)
dic = {} # Initialized a dictionary to store equation with respect to dependency
for i in range(N):
x = input().strip()
eqn[x[0]] = x # First character is always a Left hand side value
if(x[0] not in dic):
dic[x[0]] = []
for j in range(1, len(x)):
if(x[j].isalpha()): # Creating nodes from alphabate characters
dic[x[j]] = [x[0]]
order = Topologicalsort(dic) # Output order from Topological sort function
if(len(order) == 0):
print("Input is not a valid Formula, Cyclic in Nature")
else:
order.reverse() # Reverse the order because as required Problem statement example
print("Valid Formula - Dependency order is ")
for i in range(len(order)):
if (order[i] in eqn.keys()): # Using 'eqn' dictionary to output equation sequence baesd on order
print(eqn[order[i]])
|
36d31c608750b0f412f801df82881c0a07e6acd8 | 8589/codes | /python/leetcode/tests/ladder_length.py | 3,544 | 3.640625 | 4 | def is_diff_one(str1, str2):
diff_sum = 0
for i in xrange(len(str1)):
if str1[i] != str2[i]:
diff_sum+=1
if diff_sum >= 2:
return False
return True
def find_diff_one_indexes(begin_word, word_list, exclude_indexs):
result = []
for i in xrange(len(word_list)):
if exclude_indexs[i] != True:
if is_diff_one(begin_word, word_list[i]):
result.append(i)
return result
def find_diff_one_words(begin_word, word_list):
result = []
for word in word_list:
if is_diff_one(begin_word, word):
result.append(word)
return result
def find_shortest(begin_word, end_word_index, word_list, exclude_indexs, cache):
one_indexes = find_diff_one_indexes(begin_word, word_list, exclude_indexs)
if len(one_indexes) == 0:
cache[(begin_word, word_list[end_word_index])] = -1
return 0
if end_word_index in one_indexes:
return 1
shortest_path_count = len(word_list) + 1
for cur_i in one_indexes:
cur_exclude_indexs = exclude_indexs[:]
cur_exclude_indexs[cur_i] = True
cur_key = (word_list[cur_i],word_list[end_word_index])
if cur_key in cache:
cur_result = 1+cache[cur_key]
else:
cur_result = 1+find_shortest(word_list[cur_i], end_word_index, word_list, cur_exclude_indexs, cache)
if cur_result > 1 and shortest_path_count > cur_result:
shortest_path_count = cur_result
if shortest_path_count == len(word_list) + 1:
cache[(begin_word, word_list[end_word_index])] = 0
else:
cache[(begin_word, word_list[end_word_index])] = shortest_path_count
return cache[(begin_word, word_list[end_word_index])]
class Solution(object):
# time limit
def ladderLength_dp_top_down(self, begin_word, end_word, word_list):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
cache = {}
exclude_indexs = [False] * len(word_list)
if end_word not in word_list:
return 0
end_index = word_list.index(end_word)
result = find_shortest(begin_word, end_index, word_list, exclude_indexs, cache)
if result > 0:
result += 1
return result
def ladderLength(self, begin_word, end_word, word_list):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if end_word not in word_list:
return 0
begin_set, end_set = [begin_word], [end_word]
visited = {}
# visited[end_word] = True
the_len = 1
while len(begin_set) > 0 and len(end_set) > 0:
# (begin_set, end_set).p()
if len(begin_set) > len(end_set):
begin_set, end_set = end_set, begin_set
temp_words = []
for word in begin_set:
# word.p()
adj_words = find_diff_one_words(word, word_list)
# adj_words.p()
for adj_word in adj_words:
# (adj_word,end_set,the_len + 1).p()
if adj_word in end_set:
return the_len + 1
if visited.get(adj_word, False) == False:
temp_words.append(adj_word)
visited[adj_word] = True
begin_set = temp_words
the_len+=1
return 0
|
0821ea685e34767ab7e0bcc869231163fcc487e3 | csdu/coding-club-sessions | /2021-02-14-recursion-basics/binary_search.py | 1,227 | 3.84375 | 4 | # Simple Iterative Binary Search
def binary_search(a: list, k: int) -> bool:
low, high = 0, len(a) - 1
while low <= high:
mid = (low + high) // 2
if a[mid] == k:
return True
elif a[mid] > k:
high = mid - 1
else:
low = mid + 1
return False
# Simple Recursive Binary Search
def binary_search_recursive(low: int, high: int, a: list, k: int) -> bool:
# Base case: invalid range (search space)
# This happens when we exhaust all of our list
if low > high:
return False
mid = (low + high) // 2
if a[mid] == k:
return True
if a[mid] > k:
return binary_search_recursive(low, mid - 1, a, k)
else:
return binary_search_recursive(mid + 1, high, a, k)
if __name__ == '__main__':
n, k = map(int, input().strip().split())
a = list(map(int, input().strip().split()))
print('Iterative: ', end='')
if binary_search(a, k):
print('FOUND!')
else:
print('NOT FOUND!')
print('Recursive: ', end='')
if binary_search_recursive(0, len(a) - 1, a, k):
print('FOUND!')
else:
print('NOT FOUND!')
'''
Inputs:
5 4
1 2 3 4 5
5 8
1 2 3 4 5
'''
|
b961dce59fa89f13944205a68f71e6e34977b02c | lalitkar/work | /func2.py | 154 | 3.90625 | 4 | def add():
a=10
b=20
c=a+b
#return c
#print('after')
#return
#return [a,b,c]
return (a+b)/(b-a)
i=add()
print(i) |
1212b8c618d0eb15b8f66a9d34c07e84910bb124 | QWCD12/TIC-TAC-TOE | /tic_tac_toe.py | 1,547 | 4.0625 | 4 | # Set up environment
board = [a1:'', a2:'', a3:'', b1:'', b2:'', b3:'', c1:'', c2:'', c3:'']
# Winner variable used to stop the program
winner = 0
# Set up winning environments
def win():
if board[a1] == board[b2] and board[b2] == board[c3]:
print( str(board[a1]) + "'s wins.")
winner += 1
return winner
elif board[a1] == board[a2] and board[a2] == board[a3]:
print( str(board[a1]) + "'s wins.")
winner += 1
return winner
elif board[b1] == board[b2] and board[b2] == board[b3]:
print( str(board[b1]) + "'s wins.")
winner += 1
return winner
elif board[c1] == board[c2] and board[c2] == board[c3]:
print( str(board[c1]) + "'s wins.")
winner += 1
return winner
elif board[a1] == board[b1] and board[b1] == board[c1]:
print( str(board[a1]) + "'s wins.")
winner += 1
return winner
elif board[a2] == board[b2] and board[b2] == board[c2]:
print( str(board[a2]) + "'s wins.")
winner += 1
return winner
elif board[a3] == board[b3] and board[b3] == board[c3]:
print( str(board[a3]) + "'s wins.")
winner += 1
return winner
# Player inputs
def move():
next_move = input("What is your next move")
# Convert next_move value to the certain board position
if current_player == 'o':
# Replace current value with o
board[next_move] = 'o'
elif current_player == 'x':
# Replace current value with x
board[next_move] = 'x'
|
54a1144c00646a0f91900ce63082335db2db1478 | jinurajan/Datastructures | /LeetCode/top_interview_qns/easy/reverse_integer.py | 1,096 | 4.0625 | 4 | """
Reverse Integer
Solution
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
"""
from math import pow
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0:
return x
elif x < 0:
flag = -1
else:
flag = 1
x = x*flag
no_of_10s = 0
array = []
while x > 0:
array.append(x%10)
no_of_10s +=1
x = x / 10
result = 0
for i in array:
result += i*int((pow(10, no_of_10s-1)))
no_of_10s -=1
if result > pow(2, 31):
return 0
return result*flag
|
31c8151663e8f9c68a6eb4d9be6808cf60c1b298 | max180643/PSIT-IT | /Week-10/AlmostMean.py | 561 | 3.59375 | 4 | """
AlmostMean
Author : Chanwit Settavongsin
"""
def main(total, data, avg, answer):
""" Find who almostMean """
for _ in range(total): # store data
temp = input().split("\t")
data[temp[0]] = temp[1]
for j in data: # find average
avg += float(data[j])
avg = avg / total
value = avg
for k in data: # find nearest number
if float(data[k]) < avg and (avg - float(data[k]) < value):
value = avg - float(data[k])
answer = k
print("%s\t%s" % (answer, data[answer]))
main(int(input()), {}, 0, "")
|
08cf04137dc9e7c444c728901be44f34b9bc6ed0 | cog-isa/htm-rl | /htm_rl/htm_rl/agents/q/balancing_param.py | 769 | 3.640625 | 4 | class BalancingParam:
value: float
min_value: float
max_value: float
delta: float
negative_delta_rate: float
def __init__(
self, initial_value: float, min_value: float, max_value: float,
delta: float, negative_delta_rate: float,
):
self.value = initial_value
self.min_value = min_value
self.max_value = max_value
self.delta = delta
self.negative_delta_rate = negative_delta_rate
def balance(self, increase: bool = True):
if increase:
new_value = self.value + self.delta
else:
new_value = self.value - self.delta * self.negative_delta_rate
if self.min_value < new_value < self.max_value:
self.value = new_value
|
a36cc45966123693a8a6b6e8916b77cb57200a36 | dulatemesgen/module-10 | /class_definitions/tests/test_students.py | 2,006 | 3.65625 | 4 | """
Author: Dula Temesgen
program: students.py
testing student class
"""
import unittest
from class_definitions import students as s
class MyTestCase(unittest.TestCase):
def setUp(self):
self.student = s.Student('Temesgen', 'Dula', 'Maths', 4.0)
def tearDown(self):
del self.student
def test_object_created_required_attributes(self):
self.assertEqual(self.student.first_name, "Dula")
self.assertEqual(self.student.last_name, "Temesgen")
self.assertEqual(self.student.major, "Maths")
self.assertEqual(self.student.gpa, 4.0)
def test_object_created_all_attributes(self):
student = s.Student('Temesgen', 'Dula', 'Maths', 4.0)
assert student.last_name == 'Temesgen'
assert student.first_name == "Dula"
assert student.major =="Maths"
assert student.gpa == 4.0
def test_student_str(self):
self.assertEqual(str(self.student), "Temesgen, Dula has major Maths with gpa: 4.0")
def test_object_not_created_error_last_name(self):
with self.assertRaises(ValueError):
stu = s.Student("234fre", "Dula", "Maths", 4.0)
def test_object_not_created_error_first_name(self):
with self.assertRaises(ValueError):
stu = s.Student("Temesgen", "3D43ula", "Maths", 4.0)
def test_object_not_created_error_major(self):
with self.assertRaises(ValueError):
stu = s.Student("Temesgen", "Dula", "Spells", 4.0)
def test_object_not_created_error_gpa_high(self):
with self.assertRaises(ValueError):
stu = s.Student("Temesgen", "Dula", "Maths", 4.1)
def test_object_not_created_error_gpa_low(self):
with self.assertRaises(ValueError):
stu = s.Student("Temesgen", "Dula", "Maths", -0.01)
def test_object_not_created_error_gpa_not_float(self):
with self.assertRaises(ValueError):
stu = s.Student("Temesgen", "Dula", "Maths", 'A')
if __name__ == '__main__':
unittest.main()
|
daa67f9b5dc7c7157a887a776577125ba5ff4b29 | pk1397117/python_study01 | /study01/chap03/Demo05.py | 478 | 3.96875 | 4 | # 布尔运算符
print("-------与-------")
print(True and True)
print(True and False)
print(False and False)
print("-------或-------")
print(True or True)
print(True or False)
print(False or False)
print("-------非-------")
print(not True)
print(not False)
print("-------in-------")
s = "HelloWorld"
print("W" in s)
print("k" in s)
print("W" not in s)
print("k" not in s)
print("-------位运算-------")
print(4 & 8)
print(4 | 8)
print(4 << 1)
print(4 >> 1)
print(-4 >> 2)
|
454765fd74e18f4bdfd58dc1df6aaedcb8a56819 | RafaelMuniz94/Primeiros-Passos | /Exercicios/Aula/ex1Aula.py | 314 | 4.0625 | 4 | # fibonacci
# 1,1,2,3,5,8 ....
# Resolver de forma Recursiva:
def fibonacci(numero):
if numero == 1 or numero == 2:
return 1
return fibonacci(numero - 1) + fibonacci(numero - 2)
#print(fibonacci(6))
resposta = []
numero = 8
for p in range(1,numero + 1):
resposta.append(fibonacci(p))
print(resposta)
|
7157f20e3565c8ec175b673725fd2073ad8ae33e | fennieliang/week3 | /lesson_0212_regex.py | 1,082 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 25 14:40:57 2021
@author: fennieliang
"""
#useful links for regular expression
#http://python-learnnotebook.blogspot.com/2018/10/python-regular-expression.html
#https://www.tutorialspoint.com/python/python_reg_expressions.htm
#regular expression
import re
string = 'I bet you’ve heard of Harry James Poter for 11,000,000.00 times.'
#string = "We are leaving in Taipei City in Taiwan"
'''
#match capital words
#matches = re.finditer('([A-Z][a-z]+\s)', string)
#matches = re.finditer('([A-Z][a-z]+\s+[A-Z][a-z]+\s)', string)
matches = re.finditer('([A-Z][a-z]+\s){1,}', string)
for word in matches:
print (word[0])
try names with first and last names or even middle names
then a find_name function to the class
'''
#match money style digits
#matches = re.finditer('(\d+\s)', string)
#matches = re.finditer('(\d+\.\d\d\s)', string)
matches = re.finditer('(\d+,){0,}(\d+.)(\d+)', string)
for digit in matches:
print (digit[0])
'''
try big money with decimals
add a find_digit function to the class
''' |
598a83bd56d9a7bda8e453482602fa185f6bfbd5 | RUSTHONG/RosalindProblems | /1-21/10_ConsensusAndProfile/ConsensusAndProfile.py | 2,368 | 3.875 | 4 | """
Problem
A matrix is a rectangular table of values divided into rows and columns. An m*n matrix has m rows and n columns.
Given a matrix A, we write Ai,j to indicate the value found at the intersection of row i and column j.
Say that we have a collection of DNA strings, all having the same length n. Their profile matrix is a 4*n
matrix P in which P1,j represents the number of times that 'A' occurs in the jth position of one of the strings,
P2,j represents the number of times that C occurs in the jth position, and so on (see below).
A consensus string c is a string of length n formed from our collection by taking the most common symbol at each
position; the jth symbol of c therefore corresponds to the symbol having the maximum value in the j-th column of
the profile matrix. Of course, there may be more than one most common symbol, leading to multiple possible
consensus strings.
A T C C A G C T
G G G C A A C T
A T G G A T C T
DNA Strings A A G C A A C C
T T G G A A C T
A T G C C A T T
A T G G C A C T
A 5 1 0 0 5 5 0 0
Profile C 0 0 1 4 2 0 6 1
G 1 1 6 3 0 1 0 0
T 1 5 0 0 0 1 1 6
Consensus A T G C A A C T
"""
import re
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
file = open("./rosalind_cons.txt", "r").read().replace("\n", "")
def cut(rawData):
rawDataList = re.split(r">Rosalind_\d+", rawData)
del rawDataList[0]
return rawDataList
def convertToMatrix(rawDataList):
rawDataList = [list(n) for n in rawDataList]
dataMatrix = np.array(rawDataList).T.tolist()
return dataMatrix
def calProfile(processedList):
baseList = ["A", "C", "G", "T"]
for n in baseList:
result = [str(i.count(n)) for i in processedList]
print("%s: %s" %(n, (" ").join(result)))
def calConsensus(processedList):
baseList = ["A", "C", "G", "T"]
#profileList = []
df = DataFrame()
for n in baseList:
List = [i.count(n) for i in processedList]
df[n] = Series(List)
for value in df.idxmax(axis=1):
print(value, end="")
if __name__ == "__main__":
rawDataList = cut(file)
processedList = convertToMatrix(rawDataList)
calConsensus(processedList)
print(" ")
calProfile(processedList)
|
9672539eebfeb187227d5e075efb4cb5f3f115b6 | ezhang315/cs-110 | /lab-4-cwolosh1/lab4.py | 8,925 | 3.984375 | 4 | '''
Estimates pi using Monte Carlo simulation
Virtual Dartboard has area 2 X 2 to accommodate unit circle
Total area is 4
Therefore, since area of unit circle = pi * radius^2 (and radius of 1 squared
is 1), ratio of area of unit circle to area of board should be pi/4
Theoretically, if you fill the entire board with darts, counting
the number of darts that fall within the circle divided by the
total number of darts thrown should give us that ratio (i.e., 1/4 * pi)
Therefore, multiplying that result by 4 should give us an approx. of pi
Output to monitor:
approximation of pi (float)
Output to window:
colored dots that simulate unit circle on 2x2 square
Functions you must implement:
drawSquare(turtle, width, top_left_x, top_left_y) - to outline dartboard
drawLine(turtle, x_start, y_start, x_end, y_end) - to draw axes
drawCircle(turtle, radius) - to draw the circle
setUpDartboard(screen, turtle) - to set up the board using the above functions
isInCircle(turtle, circle_center, radius) - determine if dot is in circle
throwDart(turtle)
playDarts(turtle)
montePi(turtle, num_darts) - simulation algorithm returns the approximation of pi
'''
import turtle
import random
import time
# List constants here (NO MAGIC NUMBERS!):
BATCH_OF_DARTS = 5000
BOARD_WIDTH = 2
RIGHT_ANGLE = 90
#########################################################
# Your Code Goes Below #
#########################################################
def drawSquare(tortle, width, top_left_x, top_left_y):
""" Draws a square with a turtle at a specified location.
args: tortle [turtle.Turtle] - the object used to draw the square
width[int] - the length value of each side of the square
top_left_x [int] - the x coordinate of the top left corner of the square
top_left_y [int] - the y coordinate of the top left corner of the square
return: none
"""
tortle.up()
tortle.goto(top_left_x,top_left_y)
tortle.down()
for i in range(4):
tortle.forward(width)
tortle.right(RIGHT_ANGLE)
def drawLine(tortle, x_start, y_start, x_end, y_end):
""" Draws a line with a turtle between two points.
args: tortle [turtle.Turtle] - the object used to draw the line
x_start [int] - the x coordinate for the starting point of the line
y_start [int] - the y coordinate for the starting point of the line
x_end [int] - the x coordinate for the ending point of the line
y_end [int] - the y coordinate for the ending point of the line
return: none
"""
tortle.up()
tortle.goto(x_start, y_start)
tortle.down()
tortle.goto(x_end, y_end)
def drawCircle(tortle, radius):
""" Draws a circle of a certain radius with a turtle.
args: tortle [turtle.Turtle] - the object used to draw the circle
radius [int] - the radius of the circle that is drawn
return: none
"""
tortle.penup()
tortle.goto(0,-1)
tortle.pendown()
tortle.circle(radius, steps=360)
def setUpDartboard(screen, tortle):
""" Uses previously defined functions to draw an x-y axis, draw a square, and draw an inscribed circle.
args: screen [turtle.Screen] - inputs the screen so the world coordinates can be changed
tortle [turtle.Turtle] - the object used to draw the aforementioned shapes
return: none
"""
tortle.reset()
screen.setworldcoordinates(-2, -2, 2, 2)
drawSquare(tortle, BOARD_WIDTH, -1, 1)
drawLine(tortle, -2, 0, 2, 0)
drawLine(tortle, 0, -2, 0, 2)
drawCircle(tortle, 1)
def throwDart(tortle):
""" Moves a turtle to a random point within the drawn square, and marks where the dart hits the target. If it lands within the circle, the dart's mark will be blue, if it lands outside the circle, the dart's mark will be red.
args: tortle [turtle.Turtle] - the object used to mark where the "dart" hits the target
return: none
"""
num_x = random.random()
num_y = random.random()
neg = [-1, 1]
neg_int_x = random.choice(neg)
neg_int_y = random.choice(neg)
x = num_x * neg_int_x
y = num_y * neg_int_y
tortle.penup()
tortle.goto(x, y)
if isInCircle(tortle, (0,0), 1):
tortle.color('blue')
tortle.dot()
tortle.color('black')
else:
tortle.color('red')
tortle.dot()
tortle.color('black')
def isInCircle(tortle, circle_center, radius):
""" Checks if a turtle is in the circle by comparing its distance from the circle's center to the radius of the circle.
args: tortle [turtle.Turtle] - the object who's distance is compared to the radius of the circle
circle_center [tuple] - the coordinate point representing the center of the circle
radius [int] - the value that is compared to the distance between the turtle an the circle's center, to determine if that point is in the circle
return: a boolean.
"""
return tortle.distance(circle_center) < radius
def montePi(tortle, num_darts):
""" Estimates the value of pi by taking the ratio between a number of darts thrown at the target that land in the circle, with the total number of darts thrown, and then multiplying that number by 4.
args: tortle [turtle.Turtle] - the object used to mark where the dart hits the target.
num_darts[int] - the total number of darts to be thrown at the target
return: an approximation of pi.
"""
inside_count = 0
for i in range(num_darts):
throwDart(tortle)
if isInCircle(tortle, (0,0), 1):
inside_count += 1
return((float(inside_count) / float(num_darts)) * 4) #function returned 0 after dividing integers so I converted both to float.
def playDarts(tortle):
""" Plays a simulated game of darts by having two players switch off throwing a dart for ten rounds. Each player's score will increase by one if their dart is in the circle. At the end of each round the current score will be printed. The player with the highest score at the end of the 10 rounds will be the winner!
args: tortle [turtle.Turtle] - the object used to mark where the "dart" hits the target.
return: The current score between the players each round. The winner after 10 rounds.
"""
player1_score = 0
player2_score = 0
for i in range(10):
throwDart(tortle)
if isInCircle(tortle, (0,0), 1):
player1_score += 1
throwDart(tortle)
if isInCircle(tortle, (0,0), 1):
player2_score += 1
print('Player 1 has ' + str(player1_score) + ' point(s). Player 2 has '+ str(player2_score) + ' point(s).')
if player1_score > player2_score:
print("Player 1 is the winner!")
elif player2_score > player1_score:
print("Player 2 is the winner!")
else:
print("Neither player has one; it's a draw!")
#########################################################
# Do not alter any code below here #
# Your code must work with the main proivided #
#########################################################
def main():
# Get number of darts for simulation from user
# Note continuation character <\> so we don't go over 78 columns:
print("This is a program that simulates throwing darts at a dartboard\n" \
"in order to approximate pi: The ratio of darts in a unit circle\n"\
"to the total number of darts in a 2X2 square should be\n"\
"approximately equal to pi/4")
print("=========== Part A ===========")
#Create window, turtle, set up window as dartboard
window = turtle.Screen()
darty = turtle.Turtle()
darty.speed(0) # as fast as it will go!
setUpDartboard(window, darty)
# Loop for 10 darts to test your code
for i in range(10):
throwDart(darty)
print("\tPart A Complete...")
print("=========== Part B ===========")
# Includes the following code in order to update animation periodically
# instead of for each throw (saves LOTS of time):
window.tracer(BATCH_OF_DARTS)
# Conduct simulation and print result
number_darts = int(input("\nPlease input the number of darts to be thrown in the simulation: "))
approx_pi = montePi(darty, number_darts)
print("\nThe estimation of pi using "+str(number_darts)+" virtual darts is " + str(approx_pi))
print("\tPart B Complete...")
# Keep the window up until dismissed
print("=========== Part C ===========")
darty.clear() # CHANGED "window.clear()" TO "darty.clear()" AS MENTIONED IN CLASS!
setUpDartboard(window, darty)
playDarts(darty)
print("\tPart C Complete...")
# Don't hide or mess with window while it's 'working'
window.exitonclick()
main()
|
ad20fc4f7a94bfaf03582323dd06306d7f4362f0 | AnikethSDeshpande/Order-Management | /order_management/order/test_order.py | 878 | 3.609375 | 4 | import unittest
from order_management.order.order import Order
from order_management import CATALOGUE
class Test_Order_Creation(unittest.TestCase):
def test_order_creation_1(self):
order1 = Order()
self.assertEqual(order1.order_id, 0)
order2 = Order()
self.assertEqual(order2.order_id, 1)
def test_order_customer_compulsory(self):
order = Order()
print(order.customer)
def test_order_item_addition(self):
order = Order()
order.customer = 'Aniketh'
order.gst_number = '123'
item_name = 'Pen'
qty = 100
order.add_item(item_name, qty)
self.assertEqual(order.order_total, qty*CATALOGUE[item_name])
def test_order_repr(self):
o = Order()
o.customer = 'Aniketh'
print(o)
if __name__ == '__main__':
unittest.main()
|
2eda781017aaf6df04a2b755885017521d3d7e0b | wendelcampos/python-desafios-cursoemvideo | /ex098.py | 753 | 3.6875 | 4 | from time import (sleep)
def linha():
print('-=-' * 20)
def contador(i, f, p):
if p == 0:
p = 1
if i < f:
print(f'Contagem de {i} até {f} de {p} em {p}')
for c in range(i, f+1, p):
print(c, end=' ', flush=True)
sleep(0.5)
print('FIM!')
if i > f:
print(f'Contagem de {i} até {f} de {p} em {p}')
for c in range(i, f-1, -p):
print(c, end=' ', flush=True)
sleep(0.5)
print('FIM!')
linha()
contador(1, 10, 1)
linha()
contador(10, 0, 2)
linha()
print('Agora é a sua vez de personalizar a contagem!')
inicio = int(input('Inicio: '))
fim = int(input('Fim: '))
passo = abs(int(input('Passo: ')))
linha()
contador(inicio, fim, passo)
|
80f900ac334c6170c524edfbfb3984694f145950 | sk-coder/HackerRank_Challenges | /Python/NewYearChaos2.py | 2,464 | 3.71875 | 4 | #!/usr/bin/python
import math
import os
import random
import re
import sys
# Complete the minimumBribes function below.
def minimumBribes(arr):
arr_len = len(arr)
is_valid = 1
bribes = 0
in_order = 1
idx_sum = 0
val_sum = 0
last_match = 0
# Test for a too long array
if arr_len >= 10**5:
is_valid = 0
if is_valid:
# Continue processing the array
# Iterate through the array to see how many moves needed to be made
for i in range(arr_len):
idx = i + 1
val = arr[i]
print "Idx: " + str(idx) + " V: " + str(val)
# Is the current value greater than the maximum position shift of 2
if val > idx + 2:
is_valid = 0
break
if in_order:
# did we find a mis-match?
if idx != val:
in_order = 0
idx_sum = idx
val_sum = val
print (" -- Out Of Order")
else:
# add idx and val to sums, we will use this later
idx_sum = idx_sum + idx
val_sum = val_sum + val
# is the value less than the index
if val < idx:
# This person got bribed. Count how many times
bribes = bribes + (idx - val)
if last_match > val:
bribes = bribes + 1
if idx_sum == val_sum:
# we have found the end of this series of bribes
in_order = 1
idx_sum = 0
val_sum = 0
last_match = val
elif val == idx:
# This person had to bribe someone to remain in the same spot
bribes = bribes + 1
print " Br: " + str(bribes) + " Last: " + str(last_match) + " iSum: " + str(idx_sum) + " vSum: " + str(val_sum)
# Output the result
if is_valid:
print(bribes)
else:
print "Too chaotic"
if __name__ == '__main__':
f = open("NY_Chaos_TC06.txt", "r")
line = f.readline()
t = int(line)
for t_itr in xrange(t):
line = f.readline()
n = int(line)
line = f.readline()
q = map(int, line.rstrip().split())
print""
minimumBribes(q)
|
b39a5d32d9d79125cedb8a3147f70632a5be56bd | wscheib2000/CS1110 | /higher_lower_player.py | 1,305 | 4.15625 | 4 | # Will Scheib wms9gv
"""
Plays a guessing game where the computer guesses a user-selected number between 1 and 100.
"""
print("Think of a number between 1 and 100 and I'll guess it.")
num_guesses = int(input("How many guesses do I get? "))
lower_bound = 0
upper_bound = 101
while num_guesses > 0:
answer = input("Is the number higher, lower, or the same as " + str((lower_bound + upper_bound) // 2) + "? ")
answer = answer.strip(" ")
answer = answer.lower()
num_guesses -= 1
if answer == "same":
num_guesses = -1
print("I won!")
elif answer == "lower":
upper_bound = ((lower_bound + upper_bound) // 2)
elif answer == "higher":
lower_bound = ((lower_bound + upper_bound) // 2)
if num_guesses == 0:
num = int(input("I lost, what was the answer? "))
if lower_bound < num < upper_bound:
print("Well played!")
elif num < lower_bound:
print("That can't be, you said it was higher than " + str(lower_bound) + "!")
else:
print("That can't be, you said it was lower than " + str(upper_bound) + "!")
if lower_bound + 1 >= upper_bound:
num_guesses = 0
print("Wait; how can it be both higher than " + str(lower_bound) + " and lower than " + str(upper_bound) + "?")
|
17931ab709720975d89b6dcb37cbb9ac2c12a296 | seyedmm/pythonestan | /alarm/alarm.py | 560 | 3.53125 | 4 | from winsound import Beep
from time import localtime, strftime, sleep
import keyboard
alarm_time=input("What time does the alarm sound?(Enter it in 24-hour format like 05:13 or 00:15):")
text = input("If your alarm has text, enter it:")
pattern = "%H:%M"
while True:
now = strftime(pattern, localtime())
if now==alarm_time:
print(text)
print("Your alarm time has come. It is now "+alarm_time)
while True:
Beep(1000,500)
if keyboard.is_pressed("Esc"):
break
break
sleep(15)
|
d7ded8761703fed2f75c48429bedee098799351d | junteak/subjectC | /C-7.py | 1,885 | 4.28125 | 4 | '''
C-5,6,
'''
# C-1. フルネームを取得できる
class Customer:
def __init__(self, first_name, family_name, age):
self.first_name = first_name
self.family_name = family_name
self.age = age
def full_name(self):
print(self.family_name + ' ' + self.first_name)
def entry_fee(self):
if self.age <= 3:
return 0
if self.age <= 15:
return 1000
if self.age <= 57:
return 1500
if self.age <= 74:
return 1200
if self.age >= 75:
return 500
def info_csv(self):
list = [self.family_name + ' ' + self.first_name, str(self.age), str(self.entry_fee())]
result = '\t'.join(list)
return result
# print(list)
# return f'{self.family_name} {self.first_name} {self.age} {self.entry_fee()}'
print()
# #c-4
# ken = Customer(first_name="Ken", family_name="Tanaka", age=15)
# ken.info_csv() # "Ken Tanaka,15,1000" という値を返す
#
# tom = Customer(first_name="Tom", family_name="Ford", age= 57)
# ken.info_csv() # "Tom Ford,57,1500" という値を返す
#
# ieyasu = Customer(first_name="Ieyasu", family_name="Tokugawa", age=73)
# ieyasu.info_csv() # "Ieyasu Tokugawa,73,1200" という値を返す
# print(ken.info_csv())
# print(ken.info_csv())
# print(ieyasu.info_csv())
#c-6
kumi = Customer(first_name="kumi", family_name="mitsuki", age=2)
print(kumi.info_csv()) #タダ
takao = Customer(first_name="takao", family_name="tajima", age=12)
print(takao.info_csv()) #1000
jun = Customer(first_name="jun", family_name="tanaka", age=40)
print(jun.info_csv()) #1500
kazuhiko = Customer(first_name="kazuhiko", family_name="tanaka", age=74)
print(kazuhiko.info_csv()) #1200
chigiku = Customer(first_name="chigiku", family_name="yoshioka", age=89)
print(chigiku.info_csv()) #500
|
b5c12e2bbb870aca3d24a2e786856190b1592eea | stellakaniaru/practice_solutions | /manipulate_data.py | 349 | 4.0625 | 4 | '''
Create a function that takes in a list of numbers and returns the
sum total of negative numbers and the number of positive integers
in the list. The output should be in a list.
'''
def manipulate(a):
totalP = 0
totalN = 0
if type(a) is list:
for i in a:
if i >= 0:
totalP += 1
else:
totalN += i
return [totalP, totalN]
|
30564b98097b9b855a82ee8c67a0d7b23b307875 | athulyakv/basic-python-program | /program_3.py | 105 | 3.671875 | 4 | '''write a program to get the sum of all the no.s in a list'''
list= [1,2,3,4,5,6,7]
print(sum(list))
|
d42ae7760aff0f8c10a551b8e4dcf05a42669318 | yatingupta10/Coding-Practice | /LeetCode/461_Hamming_Distance.py | 285 | 3.546875 | 4 | class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
binx = '{0:032b}'.format(x)
biny = '{0:032b}'.format(y)
return sum([1 for x,y in zip(binx,biny) if x!=y])
|
7b564dec41eb7e97dbdd70642eb916fa8b9539d7 | crawsome/Python-programming-exercises | /100q/question_067/hint067.py | 269 | 4.25 | 4 | """Hint 067
We can define recursive function in Python.
Use list comprehension to generate a list from an existing list.
Use string.join() to join a list of strings.
In case of input data being supplied to the question, it should be assumed to be a console input.
""" |
ccc61f4fab2d41f66ea20ce608c84d77309197a6 | NoobsZero/DesignMode | /automation/ algorithm/sort/InsertionSort.py | 1,014 | 4.3125 | 4 | # encoding: utf-8
"""
@file: InsertionSort.py
@time: 2021/7/8 14:39
@author: Chen
@contact: [email protected]
@software: PyCharm
"""
def insertionSort(A):
"""
插入排序
Args:
A: 数组
Returns:升序数组
"""
# 初始化:第一次循环迭代之前(当j=2时),循环不变式成立
# j[1,2,...,N-1]
for j in range(1, len(A)):
key = A[j]
i = j - 1
# 保持:证明每次迭代保持循环不变式
while i >= 0 and A[i] > key:
A[i+1] = A[i]
i = i - 1
A[i+1] = key
# 终止:在循环终止时,不变式为我们提供一个有用的性质,该性质有助于证明算法是正确的。
return A
def selectA(A, x):
# for j in range(len(A)):
if x in A:
print(x)
else:
print(None)
def selectB(A, x):
for j in range(len(A)):
print(j)
if __name__ == '__main__':
x = 6
A = [5, 2, 4, 6, 1, 3]
# print(insertionSort(A))
selectB(A, x)
|
4d779f3c0fb0bcac2059a3c3f72bcad355d59b03 | A-Alexander-code/150-Python-Challenges--Solutions | /Ejercicio_N041.py | 215 | 4.09375 | 4 | num = int(input("Ingrese un número: "))
if num <= 10:
name = input("Ingrese su nombre: ")
for i in range(0,num+1):
print(name)
else:
for j in range(0,3):
print("Demasiado alto")
|
95893be438a389e00c0e67efff2cd40a658012fb | JJWSSS/exercise | /filtered_words.py | 674 | 3.734375 | 4 | __author__ = 'JJW'
# -*- coding: utf-8 -*-
import re
def filtered_words(word):
with open('filtered_words.txt', 'r', encoding='utf-8') as f:
s = f.read()
words = re.split(' |\n', s)
print(words)
for fword in words:
print(fword)
if word.__contains__(fword):
# if word == fword:
print('Freedom')
replace_string = ''
for i in range(0, len(fword)):
replace_string += '*'
print(word.replace(fword, replace_string))
return
print('Human Rights')
print(word)
return
filtered_words('北京')
|
2618367c571003d76373b5d64615e8c68d132b03 | kaust-cs249-2020/MOHSHAMMASI-CS249-BIOINFORMATICS | /Chapter-7/ChromosomeToCycle_section12.py | 867 | 3.609375 | 4 |
def read_input(filename):
try:
input_file = open(filename, "r")
chromosome = input_file.readline().rstrip('\n')
chromosome = chromosome[:-1]
chromosome = chromosome[1:]
chromosome = [int(i) for i in chromosome.split(" ")]
input_file.close()
except:
print("Exception caught, file probably doesnt exist")
return chromosome
def chromosome_to_cycle(chromosome):
n = len(chromosome)
nodes = []
for j in range(0, n):
i = chromosome[j]
if i > 0:
nodes.append(2*i-1)
nodes.append(2*i)
else:
nodes.append(-2*i)
nodes.append(-2*i-1)
return nodes
def start():
chromosome = read_input("dataset.txt")
result = chromosome_to_cycle(chromosome)
print('(', *result, ')')
if __name__ == '__main__':
start()
|
802cc01e6ffc3325df9cafc9a9e1c29e813b877e | Riskybiznuts/it-python | /zipcode.py | 1,022 | 3.953125 | 4 | from banner import banner
banner ("ZIP CODE SORTER", "Brad")
print("Welcome to the Newaygo County zip code sorter.")
go_again = True
while go_again:
zipcode = int(input("Please enater a zip code: "))
if zipcode == 49309:
print("The zipcode 49309 is for Bitely.")
elif zipcode == 49312:
print("The zipcode 49312 is for Brohman.")
elif zipcode == 49337:
print("The zipcode 49337 is for Croton and Newaygo.")
elif zipcode == 49412:
print("The zipcode 49412 is for Fremont.")
elif zipcode == 49413:
print("The zipcode 49413 is for Fremont.")
elif zipcode == 49327:
print("The zipcode 49327 is for Grant.")
elif zipcode == 49349:
print("The zipcode 49349 is for White Cloud.")
else:
print("The zipcode is not in Newaygo County")
go_again = False
if input("Would you like to enter another zipcode (Y/N)?") == "Y":
go_again = True
print("Thank you for using the Newaygo County zip code sorter. Goodbye.") |
2b571a348218d28e59149c0371e01cee42f011fc | beidou9313/deeptest | /第一期/广州-Roger/task2/error01.py | 763 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-01-23 17:33:47
# @Author : Roger TX ([email protected])
# @Link : https://github.com/paotong999
# @Version : $Id$
import os,time
import re
# 定义函数
def temp_convert(var):
try:
return int(var)
except (ValueError) as Argument:
print ("参数没有包含数字\n", Argument)
# 调用函数
temp_convert("xyz");
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) ', line, re.M|re.I)
if matchObj:
print ("matchObj.group() : ", matchObj.group())
print ("matchObj.group(1) : ", matchObj.group(1))
print ("matchObj.group(2) : ", matchObj.group(2))
else:
print ("No match!!")
localtime = time.localtime()
print ("本地时间为 :", localtime) |
30f39a52e1ce8ec5419c3b43630dfa5d58b17c3f | ttyskg/ProgrammingCompetition | /AtCoder/ABC/035/d.py | 1,350 | 3.53125 | 4 | import sys
from heapq import heappush, heappop, heapify
def dijkstra(s, links):
"""Dijkstra algorism
s: int, start node.
t: int, target node.
links: iterable, link infomation.
links[i] contains edges from node i: (cost, target_node).
return int, minimal cost from s node to t node.
"""
INF = 10**9
dist = [INF] * len(links)
dist[s] = 0
heap = list(links[s])
heapify(heap)
while len(heap) > 0:
cost, node = heappop(heap)
if dist[node] < cost:
continue
dist[node] = cost
for cost2, node2 in links[node]:
if dist[node2] < cost + cost2:
continue
dist[node2] = cost + cost2
heappush(heap, (cost + cost2, node2))
return dist
def main():
input = sys.stdin.readline
N, M, T = map(int, input().split())
A = list(map(int, input().split()))
Gf = [set() for _ in range(N)]
Gr = [set() for _ in range(N)]
for _ in range(M):
a, b, c = map(int, input().split())
a, b = a-1, b-1
Gf[a].add((c, b))
Gr[b].add((c, a))
minf = dijkstra(0, Gf)
minr = dijkstra(0, Gr)
ans = 0
for i in range(N):
res = (T - minf[i] - minr[i]) * A[i]
ans = max(ans, res)
return ans
if __name__ == '__main__':
print(main())
|
ef65b3c70fda21b66833f10295da1851140d638e | officialGanesh/Guess-My-Number | /main.py | 711 | 4.0625 | 4 | # import the required module
from random import randint
Secret_number_range = int(input("Enter the range of secret number --> "))
def playerGuess(Secre_number_range):
secret_number = randint(1, Secret_number_range)
player_guess = 0
count = 0
while player_guess != secret_number:
player_guess = int(input("guess the number: "))
if player_guess > secret_number:
count += 1
print("your guess is too high!")
elif player_guess < secret_number:
count += 1
print("your guess is too low!")
count += 1
print(f"you guessed the secretNumber ({secret_number}) in {count} guesses.")
playerGuess(Secret_number_range) |
2826bb57d4af9caa338a68659b16d67ef258e671 | eselyavka/python | /leetcode/solution_213.py | 871 | 3.765625 | 4 | #!/usr/bin/env python
import unittest
class Solution(object):
def _rob(self, nums):
dp = [0] * len(nums)
res = 0
for i in range(len(nums)):
res = max(nums[i]+(dp[i-2] if i >= 2 else 0), (dp[i-1] if i > 0 else 0))
dp[i] = res
return res
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums)
return max(self._rob(nums[:-1]), self._rob(nums[1:]))
class TestSolution(unittest.TestCase):
def test_rob(self):
solution = Solution()
self.assertEqual(solution.rob([2, 3, 2]), 3)
self.assertEqual(solution.rob([1, 2, 3, 1]), 4)
if __name__ == '__main__':
unittest.main()
|
e1bc10063075d65d8273d74e1e9f9c72e877426f | vishrutkmr7/DailyPracticeProblemsDIP | /2023/03 March/db03282023.py | 630 | 4.03125 | 4 | """
Given two non-negative integers low and high, return the total count of odd numbers between them (inclusive).
Ex: Given the following low and high…
low = 1, high = 3, return 2 (1 and 3 are both odd).
Ex: Given the following low and high…
low = 1, high = 10, return 5.
"""
class Solution:
def countOdds(self, low: int, high: int) -> int:
if low % 2 == 0 and high % 2 == 0:
return (high - low) // 2
else:
return (high - low) // 2 + 1
# Test Cases
if __name__ == "__main__":
solution = Solution()
print(solution.countOdds(1, 3))
print(solution.countOdds(1, 10))
|
5ea7a6930208fed56c08f85f0f40cd92c795c8c9 | mahdi00021/Twitter_and_Locations_gis | /tweeter_crawler/factory/IFactorySocial.py | 371 | 3.5625 | 4 | """ this class is interface for implement factory pattern"""
import abc
class IFactorySocial(metaclass=abc.ABCMeta):
@staticmethod
def read_and_save(request):
pass
@staticmethod
def save_images(request):
pass
@staticmethod
def read_data_from_mongodb():
pass
@staticmethod
def find_data(request):
pass
|
d3d0d7f317264b773af5dd3b2c534822a84bdac4 | vinayak906/whatsapp_spam_bot | /spam_bot.py | 1,193 | 3.65625 | 4 | from pyautogui import press,sleep,hotkey,confirm,prompt,typewrite
FAILSAFE = False
sleep(1)
con=confirm(text='Please make sure whatsapp is installed in your system and login your whatsapp account ',title="Confirmation promt",buttons=['Continue','Quit'])
if con=='Continue':
press("win")
sleep(.2)
typewrite("whatsapp",interval=0.2)
press("enter")
sleep(4)
hotkey('win','up')
contact=prompt(text='Please make sure whatsapp account is login and wondow is loaded\nEnter the contect name for spam',title='Enter the contect name for spam :- ')
sleep(2)
if contact!=None:
press("tab")
typewrite(contact)
press("enter")
sleep(2)
message=prompt(text="What massage you want to spam", title="Spam Massage input box")
if message!=None:
n=prompt(text="how many messages you want to spam", title="Spam count input box",default=100)
for i in range (0,int(n)):
typewrite(message,interval=0.02)
press('Enter')
else:
hotkey('alt','f4')
quit
else:
hotkey('alt','f4')
quit
else:
quit |
b467a7a15bf0dcd523a7de566ed85f0db1c76a9e | kuzin2006/codewars | /encrypt.py | 332 | 3.890625 | 4 | def encrypt_this(text):
return " ".join(filter(None, [''.join([str(ord(word[0])) if len(word) else '', word[-1] if len(word) > 1 else '',
''.join([word[2:-1], word[1]]) if len(word) > 2 else ''])
for word in text.split(" ")])) \
if text else ''
print(encrypt_this(" T a "))
|
ddafeb652804ec6307ec4f6238b5d094414c47c5 | noppakorn-11417/psit-2019 | /problem/Triangle.py | 383 | 3.71875 | 4 | """despacito"""
def cal(num, count=2):
"""despacito"""
for i in range(-num, 0):
if i == -num:
print(" "*(abs(i)-1)+"%02d"%abs(i))
elif i == -num+1:
print(" "*(abs(i)-1)+"%02d"%abs(i)+" "+"%02d"%abs(i))
else:
count += 4
print(" "*(abs(i)-1)+"%02d"%abs(i)+" "*(count)+"%02d"%abs(i))
cal(int(input()))
|
ad270e9e7ffd738382ab37202a3e9d1c6c6bd9ab | Farah-Amalia/ML-Algorithms | /LinearRegression/LinearRegression.py | 2,012 | 3.703125 | 4 | # Import required module
import numpy as np
# Creating class
class LinearRegression:
def __init__(self, cost_function="l2", learning_rate=0.01, epochs=1000000) :
self.learning_rate = learning_rate
self.epochs = epochs
self.cost_function = cost_function
# Model fitting
def fit(self, X, Y):
# Define number of training samples and number of features
self.m, self.n = X.shape
# Weight initialization
self.W = np.zeros(self.n)
self.b = 0
self.X = X
self.Y = Y
# Implementing Gradient Descent
# for Mean Square Error
if self.cost_function == "l2":
for i in range(self.epochs):
Y_pred = self.predict(self.X)
# Calculating derivatives
dW = - (2 * (self.X.T).dot(self.Y - Y_pred)) / self.m
db = - 2 * np.sum(self.Y - Y_pred) / self.m
# Updating parameters
self.W = self.W - self.learning_rate * dW
self.b = self.b - self.learning_rate * db
# for Mean Absolute Error
elif self.cost_function == "l1":
for i in range(self.epochs):
Y_pred = self.predict(self.X)
# Calculating derivatives
dW = - (1/self.m) * np.sum(((self.X.T).dot(self.Y - Y_pred)) / abs(self.Y - Y_pred))
db = - (1/self.m) * np.sum((self.Y - Y_pred) / abs(self.Y - Y_pred))
# Updating parameters
self.W = self.W - self.learning_rate * dW
self.b = self.b - self.learning_rate * db
self.coef_ = self.W
self.intercept_ = self.b
return self
# Prediction
def predict(self, X):
Y_pred = X.dot(self.W) + self.b
return Y_pred
|
b3308e5d3a3bfa2039381f896d74fa37dcbdd8b0 | srikanthpragada/PYTHON_29_OCT_2020 | /demo/funs/passing_list.py | 90 | 3.6875 | 4 | def prepend(lst, value):
lst.insert(0, value)
l = [1, 2, 3]
prepend(l, 10)
print(l)
|
e51124ffcd43400885523e0e67e95386cf9da3b9 | manimanis/2TI_2020-2021 | /progs/prj01/s02.py | 791 | 3.578125 | 4 | from random import randint
eq1 = input('Nom 1ère équipe : ')
eq2 = input('Nom 2ème équipe : ')
print('Le match est joué entre', eq1, 'et', eq2)
num_eq = randint(0, 1)
if num_eq == 0:
eq = eq1
autre_eq = eq2
else:
eq = eq2
autre_eq = eq1
print("Le capitaine de l'équipe", eq, 'choisit Pile/Face')
choix_cap = int(input('0: Pile, 1: Face ? '))
if choix_cap == 0:
ch_cap = 'Pile'
else:
ch_cap = 'Face'
print("Le capitaine de l'équipe", eq, "a choisi", ch_cap)
ts = randint(0, 1)
if ts == 0:
face = 'Pile'
else:
face = 'Face'
print("L'arbitre lance la pièce puis il l'attrape")
print("Résultat du tirage au sort :", face)
if ts == choix_cap:
equipe = eq
else:
equipe = autre_eq
print("Le ballon est en possession de l'équipe :", equipe)
|
2ff0d12f11fb06aa751506b4e1964d00c18a2a67 | enzomasson25/football_data_science | /equipe.py | 3,363 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 09:03:24 2020
@author: 33762
"""
# import the libraries we'll need
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
# instantiate the BeautifulSoup to find data on the website
html = urlopen("https://fbref.com/en/country/clubs/ENG/England-Football-Clubs")
html_soup = BeautifulSoup(html, 'html.parser')
# get every line with the string "tr" in it
rows = html_soup.findAll("tr")
# create the tab that will stock the informations about teams
teams = []
i=0
# for each row in rows
for row in rows:
i=i+1
# if the line contains the tag "a" this is the name of the squad (only this line contains this tag)
squad = row.find("a")
# search for every td tag in the line
cells = row.findAll("td")
# if there is 7 td tag then
if (len(cells) == 7):
# the beginning of the url of the squad is the 20 first characters
debut_url = squad['href'][0:20]
# the end of the url of the squad is the last characters from the index 28
fin_url = squad['href'][28:-1]
html = urlopen("https://fbref.com" + squad['href'])
html_soup = BeautifulSoup(html, 'html.parser')
images = html_soup.findAll("img")
print(str(round((i/877)*100)) + '%')
try:
# different entries for the team
team_entry = {
# name of the squad/team
"squad": squad.text,
# url of the squad
"url": "https://fbref.com" + squad['href'],
# url of the current season for the team
"url_saison_actuelle": "https://fbref.com" + debut_url + fin_url,
# type of squad, if this is an team of male or female
"gender": cells[0].text,
# the league where the squad is
"comp": cells[1].text,
# first season we have data for the squad
"from": cells[2].text,
# last season we have data for the squad
"to": cells[3].text,
# number of time the squad participated to cup
"comps": cells[4].text,
# number of time the squad was champion of their league
"champs": cells[5].text,
# if the team changes it name
"other_names": cells[6].text,
"logo": images[1]['src']
}
# add the information about the squad
teams.append(team_entry)
except ValueError:
print("Ouch!")
# on veut passer de https://fbref.com/en/squads/18bb7c10/history/Arsenal-Stats
# a https://fbref.com/en/squads/18bb7c10/Arsenal-Stats
# create a dataframe with the different informations we gathered
df = pd.DataFrame(teams,
columns=['squad', 'url', 'url_saison_actuelle', 'gender', 'comp', 'from', 'to', 'comps', 'champs',
'other_names','logo'])
# methods to avoid an encoding error that appears on column 'comp'
def without_error_encoding(entry):
if "—" in entry:
entry = entry.replace(u"—", u"-")
return entry
df["comp"] = df["comp"].apply(without_error_encoding)
# convert this dataframe to a csv
df.to_csv("js/public/teams.csv")
# print done
print("Done !")
|
fa28db55af034eb591e5b04ff2130b46f82af22f | FreemanG/Introduction-to-Computational-Thinking-and-Data-Science-6.00.2x- | /w5l904_shortestDFS.py | 2,505 | 3.796875 | 4 | from graph import *
#def DFS(graph, start, end, path = [], shortest = None):
# #assumes graph is a Digraph
# #assumes start and end are nodes in graph
# path = path + [start]
# print 'Current dfs path:', printPath(path)
# if start == end:
# return path
# for node in graph.childrenOf(start):
# if node not in path: #avoid cycles
# newPath = DFS(graph,node,end,path,shortest)
# if newPath != None:
# return newPath
def DFSShortest(graph, start, end, path = [], shortest = None):
#assumes graph is a Digraph
#assumes start and end are nodes in graph
path = path + [start]
print 'Current dfs path:', printPath(path)
if start == end:
return path
for node in graph.childrenOf(start):
if node not in path: #avoid cycles
if shortest == None or len(path)<len(shortest):
newPath = DFSShortest(graph,node,end,path,shortest)
if newPath != None:
shortest = newPath
return shortest
def DFS2(digraph, start, end, path = [], res = [], recur = 0):
#assumes graph is a Digraph
#assumes start and end are nodes in graph
recur += 1 # depth of recursion
path = path + [start]
if start == end:
res.append(path)
for node in digraph.childrenOf(start):
if node not in path: #avoid cycles
DFS(digraph, node, end, path, res, recur)
if recur == 1 and node == digraph.childrenOf(start)[-1]:
return res
def printPath2(path):
# a path is a list of nodes
result = ''
for i in range(len(path)):
for j in range(len(path[i])):
if j == len(path[i]) - 1:
result = result + str(path[i][j]) + '\n'
else:
result = result + str(path[i][j]) + '->'
return result
def testSP():
nodes = []
for name in range(6):
nodes.append(Node(str(name)))
g = Digraph()
for n in nodes:
g.addNode(n)
g.addEdge(Edge(nodes[0],nodes[1]))
g.addEdge(Edge(nodes[1],nodes[2]))
g.addEdge(Edge(nodes[2],nodes[3]))
g.addEdge(Edge(nodes[2],nodes[4]))
g.addEdge(Edge(nodes[3],nodes[4]))
g.addEdge(Edge(nodes[3],nodes[5]))
g.addEdge(Edge(nodes[0],nodes[2]))
g.addEdge(Edge(nodes[1],nodes[0]))
g.addEdge(Edge(nodes[3],nodes[1]))
g.addEdge(Edge(nodes[4],nodes[0]))
sp = DFS2(g, nodes[0], nodes[5])
print 'Shortest path found by DFS:', printPath2(sp) |
8d56615cfb12c572596e077c2c2cf68f6acf74e3 | ecoronado92/MIT_Covid19 | /objects/input_class.py | 2,627 | 3.765625 | 4 | import pandas as pd
import numpy as np
import random as rnd
import networkx as nx
import osmnx as ox
class Inputs():
def __init__(self,num_points = None):
self.points = num_points
def random_point_generator(self,num_points):
"""
Generate random latitude and longitude points from a given center (just to simulate ;) )
Params
--------------
num_points : int (how much data you want)
Returns
------------
latitude: latitude random points
longitude: longtiude random points
"""
origin_point = (-12.0432,-77.0141)
latitude = []
longitude = []
for row in range(num_points):
temp = float(rnd.randint(0,100))
latitude.append(origin_point[0] + rnd.random()/100)
longitude.append(origin_point[1] + rnd.random()/100)
return latitude,longitude
def generate_demand(self,num_points):
"""
Generate random daily demands given the needed distribution points
Params
--------------
num_points : int (how much data you want)
Returns
------------
df : DataFrame with latitude,longitude of points as well as demand for the
vending machines
"""
latitude,longitude = self.random_point_generator(num_points)
demand = np.array([np.random.randint(10,100) for observation in range(num_points)])
return latitude, longitude, demand
def cost_matrix(self,num_points):
"""
Creates a cost matrix for the model to later minimize (cost function must be defined first).
For now just return the distance between the points. FUTURE : Use Google API (optimized performance, but costs).
For now using osmnx algorithm for calculating shortest paths from a graph (dijkstra algorithm)
Params
--------------
num_points : int (how much data you want)
Returns
------------
"""
latitude,longitude,demand = self.generate_demand(num_points)
lat_lon = tuple(zip(latitude,longitude))
g = ox.graph_from_point((-12.0432,-77.0141) , distance = 500)
matrix = np.zeros((num_points,num_points))
for row in range(num_points):
temp1 = ox.get_nearest_node(g,lat_lon[row])
for column in range(num_points):
temp2 = ox.get_nearest_node(g,lat_lon[column])
distance = nx.shortest_path_length(g,source = temp1,target = temp2)
matrix[row,column] = distance
return matrix, lat_lon, demand
|
477b951778f051f37647d54f1f1a3bdf16b38a6a | guruc-134/Py_programs | /SUM.py | 550 | 3.8125 | 4 | N = int(input())
answer=list()
for i in range(12):
str=input()
commands=str.split()
if commands[0] == "insert":
answer.insert(int(commands[1]),int(commands[2]))
elif commands[0] == "print":
print(answer)
elif commands[0] == "remove":
answer.remove(int(commands[1]))
elif commands[0] == "append":
answer.append(int(commands[1]))
elif commands[0] == "sort":
answer.sort()
elif commands[0] == "reverse":
answer.reverse()
elif commands[0] == "pop":
answer.pop()
|
086eadc21eae4f2077911657e4705a13fb49f77c | Emdesade/test1 | /zad6.py | 1,601 | 3.640625 | 4 | class Slowa:
def __init__(self,slowo1,slowo2):
self.slowo1 = slowo1
self.slowo2 = slowo2
def sprawdz_czy_palindrom(self):
rev = ''.join(reversed(self.slowo1))
if (self.slowo1 == rev):
return True
return False
def sprawdz_czy_metagramy(self):
a = self.slowo1
b = self.slowo2
a_1 = len(a)
b_1 = len(b)
test = 0
liczenie = 0
if(a_1 == b_1):
for n in a:
if (a[test] == b[test]):
liczenie += 1
else:
pass
test += 1
else:
return "Nie metagramy"
if(liczenie == a_1-1):
return "Metagramy"
else:
return "Nie metagramy"
def sprawdz_czy_anagramy(self):
a = self.slowo1
b = self.slowo2
c = []
d = []
for m in a:
if(m in a and m not in c):
c.append(m)
for m in b:
if(m in b and m not in d):
d.append(m)
c.sort()
d.sort()
if c == d:
return "Anagramy"
else:
return "Nie Anagramy"
def wyswietl_wyrazy(self):
return self.slowo1,self.slowo2
obiekt = Slowa("kajak","kajek")
ans = (obiekt.sprawdz_czy_palindrom())
if ans ==1:
print("tak to palindrom")
else:
print("nie to nie palindrom")
print(obiekt.sprawdz_czy_metagramy())
print(obiekt.sprawdz_czy_anagramy())
print(obiekt.wyswietl_wyrazy()) |
47fce24a77e525c391482c7bd520d2e55a9c30ad | five-hundred-eleven/cs-module-project-hash-tables | /applications/markov/markov.py | 945 | 3.53125 | 4 | import random
# Read in all the words in one go
with open("input.txt") as f:
words = f.read()
# TODO: analyze which words can follow other words
import re
from collections import defaultdict
from spacy.lang.en import English
from spacy.tokenizer import Tokenizer
nlp = English()
tokenizer = Tokenizer(nlp.vocab)
w2w = defaultdict(lambda: [])
words = [re.sub(r"[^a-z0-9]", "", t.lemma_.lower()).strip() for t in tokenizer(words)
if not t.is_punct and t.text.strip()]
for word1, word2 in zip(words, words[1:]):
w2w[word1].append(word2)
# TODO: construct 5 random sentences
# Your code here
import random
for _ in range(5):
word = random.choice(list(w2w.keys()))
sentence = [word]
for _ in range(random.randint(4, 12)):
following = w2w[word]
if following:
word = random.choice(following)
sentence.append(word)
else:
break
print(" ".join(sentence))
|
c4e0de17109faac11758640c07bb2a9ab35a4dcb | KuboBahyl/coding-interviews | /Algo topics/Problems Simple/QueueCircular.py | 409 | 4.03125 | 4 | # Queue - insert into circular queue
def circular_insert(queue, data):
# empty queue
if queue.front is None:
self.front = self.back = 0
# full queue
if (queue.back + 1) % queue.size == queue.front:
return print("Queue overflow!")
# boundary case
elif queue.back == queue.size - 1:
queue.back = 0
else:
queue.back += 1
queue[queue.back] = data |
bccea5d749fc030dc1e896d31734ff5ea1423bc3 | brevnoman/chinchopa | /lesson4/Task4.py | 1,601 | 4 | 4 | import math
while True:
hi=input("1 or 2?:")
if hi=="1":
ch=input("10 or 01")
if ch=="10":
ans1=input("write correct answer for !12=")
right_ans1= math.factorial(12)
if ans1==str(right_ans1):
print("good job", right_ans1, "is write answer)")
break
else:
print("wrong")
break
elif ch=="01":
ans2=input("write correct answer for 1+2=")
right_ans2=1+2
if ans2==str(right_ans2):
print("good job", right_ans2, "is write answer)")
break
else:
print("wrong")
break
elif hi=="2":
ch=input("jscript or 001")
if ch=="001":
ans3=input("write correct answer for 11*187=")
rigth_ans3=11*187
if ans3==str(rigth_ans3):
print("good job", rigth_ans3, "is write answer)")
break
else:
print("wrong")
break
elif ch=="jscript":
ans4=input("write correct answer for 1+12")
right_ans4="112"
if ans4==right_ans4:
print("wth, is this real, how can 1+12 be", right_ans4,"but you right...")
break
elif ans4=="13":
print("sorry buddy, but this is question for jscript-guys")
break
else:
print("wrong")
break
else:
print("you should chose only from given options")
|
92a3df9af4c613e67fdc91fe11944ae8b9a95da2 | manigh/ghc | /main.py | 2,993 | 3.703125 | 4 | #!/bin/python2
import ride
from ride import *
import car
import sys
import parser
import random
def do(r, c, t):
c.do_this_ride(r, t)
r.isDone=True
def pick_from_available_cars(r, available_cars, t):
bonus_cars=[]
deadline_cars=[]
for c in available_cars:
time_to_make_itAND_bonus_list=r.time_to_make_itAND_bonus(c,t)
spare_toDEADLINE = int(time_to_make_itAND_bonus_list[0])
spare_toBONUS = int(time_to_make_itAND_bonus_list[1])
if(spare_toDEADLINE==0):
deadline_cars.append(c)
elif(spare_toDEADLINE>0):
deadline_cars.append(c)
if(spare_toBONUS>=0):
bonus_cars.append(c)
d=len(deadline_cars)
b=len(bonus_cars)
if (d==0):
print "no car could make it to ride on time for ride " + str(ride_list.index(r))
elif (d==1):
c=deadline_cars[0]
print "only car " + str(car_list.index(c)) + " could make it to ride " + str(ride_list.index(r))
do(r,c,t)
elif (d>1):
if (b==0):
print "no car could get the bonus on time for ride " + str(ride_list.index(r))
c_index=random.randint(0,len(deadline_cars)-1)
c=deadline_cars[c_index]
print "picked car " + str(car_list.index(c)) + " to do the ride " + str(ride_list.index(r))
do(r,c,t)
elif (b==1):
c=bonus_cars[0]
print "only car " + str(car_list.index(c)) + " could get bonus on ride " + str(ride_list.index(r))
do(r,c,t)
elif (b>1):
c_index=random.randint(0,len(bonus_cars)-1)
c=bonus_cars[c_index]
print "picked car " + str(car_list.index(c)) + " to get bonus on ride " + str(ride_list.index(r))
do(r,c,t)
return True
filename = sys.argv[1]
f = open(filename)
passed_list=[]
passed_list = parser.read(f)
f.close()
I=int(passed_list[0])
J=int(passed_list[1])
F=int(passed_list[2])
R=int(passed_list[3])
B=int(passed_list[4])
T=int(passed_list[5])
car_list=passed_list[6]
ride_list=passed_list[7]
t=0
while t <= T:
#for all rides
#if !isDone
#if ride_is_possible at t
for r in ride_list:
if(r.ride_is_possible(int(t))):
#for all cars
#if car.is_available(t)==True
available_cars=[]
for c in car_list:
#remove r is done to try diff ways
if(c.is_available(t)):
available_cars.append(c)
if (len(available_cars)==0):
print "no car available for ride " + str(ride_list.index(r)) + " at time " + str(t)
else:
print "We can pick " + str(len(available_cars)) + " cars for ride " + str(ride_list.index(r)) + " at time " + str(t)
pick_from_available_cars(r, available_cars, t)
t+=1
outputfilename = filename .rstrip('in')
outputfilename += "out"
o = open(outputfilename, "w")
parser.save(o, car_list, ride_list)
o.close()
|
d3c2e5c28fc14a43774f1d1c158140f990c4624e | Pranav174/Paraphrase_generation | /functions/paraphrase_with_syn_ant.py | 1,464 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import json
import random
import re
def replace_paryavachi(sentence):
filename = 'paryavachis.txt'
with open(filename, 'r') as f:
paryavachis = json.load(f)
sentence = sentence.split(" ")
for i, word in enumerate(sentence):
for synset in paryavachis:
if word in synset:
replacement = word
while replacement == word:
replacement = random.choice(synset)
sentence[i] = replacement
sentence = ' '.join(sentence)
sentence = re.sub('\s+', ' ', sentence).strip()
return sentence
def replace_vilom_shabd(sentence):
filename = 'vilom_shabds.txt'
with open(filename, 'r') as f:
vilom_shabds = json.load(f)
negative = u"नहीं"
sentence = sentence.split(" ")
for i, word in enumerate(sentence):
if word in vilom_shabds.keys():
if sentence[i+1] == negative:
sentence[i] = random.choice(vilom_shabds[word])
sentence[i+1] = ''
else:
sentence[i] = random.choice(vilom_shabds[word])+" "+negative
sentence = ' '.join(sentence)
sentence = re.sub('\s+', ' ', sentence).strip()
return sentence
if __name__ == "__main__":
print("please provide the sentance:")
text = input()
text1 = replace_paryavachi(text)
print(text1)
possible_ant = replace_vilom_shabd(text)
print(possible_ant)
|
be3063a710771888934f0ca61dba60816344e583 | DILEEPKUMA/Python_practice | /practice/condtion2.py | 148 | 4.09375 | 4 | temp=int(input('enter the temp : '))
temp1=45
if (temp > temp1):
print("its hot day")
else:
print("its cool day")
print("enjoy your day") |
da1a0381b84cb07be6c59277c16de50dcc979a44 | KUNAL932/linear_search_algorithm | /linear_algo.py | 534 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 27 20:19:48 2018
@author: kunal
"""
list=[]
num=int(input("enter the range of the list: \t"))
for n in range(num):
number=int(input("enter the number to be added in list \t"))
list.append(number)
x=int(input("enter the value to be searched \n"))
found=False
for i in range(len(list)):
if list[i]==x:
found=True
print("\n%d the number is found %d" % (x,i))
break
else:
found=False
print("\n%d the number is not found %d"%x)
|
df6888ee48b5cbb8463523f90edccf44d114b23d | bbkang2018/coding-practice | /jeju6/app2.py | 175 | 3.734375 | 4 | is_female = True
is_beautiful = False
is_young = True
if is_female and is_beautiful and is_young:
print("Your are beautiful young female")
else:
print("You're oopse")
|
44257e016d8ec57474daa2dee499f07f7dc2d0b6 | AlexPersaud17/my_python_progress | /projects/calculator.py | 899 | 4.25 | 4 | # This program computes various operatios based on the user input
x, y = eval(input("Enter two numbers: "))
operation = input("Enter the operation: ")
result = ""
if operation == "+" or operation == "a" :
operation = "+"
result = x + y
elif operation == "-" or operation == "s" :
operation = "-"
result = x - y
elif operation == "*" or operation == "m" :
operation = "*"
result = x * y
elif operation == "/" or operation == "d" :
if y != 0 :
operation = "/"
result = x / y
else :
print("Cannot compute! The divisor operand should not be zero!")
elif operation == "%" or operation == "r" :
operation = "%"
result = x % y
elif operation == "^" or operation == "p" :
operation = "^"
result = x ** y
if result != "":
print("Result: ", x, operation, y," = ", result, sep="")
else :
print("Please enter a valid operation!") |
f754f747d1429ad6c4d9a85e996b76cd088b10c9 | sumanth82/py-practice | /practicepython/exercise-1.py | 197 | 3.765625 | 4 | # http://www.practicepython.org/exercise/2014/01/29/01-character-input.html
import datetime
from datetime import date
user_input = input("Enter your age : ")
year_when_user_turns_100_years =
|
ffc4f1335d52ae4eae1e7477258f6c70afb61d3d | amaljoy93/EDA | /learning panda.py | 8,364 | 3.921875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool, built on top of the Python programming language
# Pandas - Panel Data
# Datatypes in Pandas
# Series
# Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index.
#
# Dataframe
# DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object.
#
# Panel
# A panel is a 3D container of data
#
# To install
# pip install pandas
# In[2]:
import pandas as pd
import numpy as np
# In[3]:
get_ipython().run_line_magic('pinfo', 'pd')
# In[4]:
s=pd.Series([10,30,50,np.nan,60,89])#here we are creating a Series using a list
# In[5]:
s
# In[6]:
type(s)
# In[6]:
s.shape #shape will show the shape(#rows and # columns) - For series #columns will be always 1.
# In[7]:
s.head() #head used to display the first n number of observations default n = 5
# In[8]:
s.tail() #tail used to display the last n number of observations default n = 5
# In[12]:
s.dtypes #dtypes used to identify the datatype of the series/dataframe
# In[9]:
s1 = pd.Series([9, 12, 15, 18, 21, 24])
# In[11]:
s1.add(1)
# In[13]:
s1.subtract(1)
# In[14]:
s1.mean()
# In[16]:
s1.median()
# In[19]:
s.mode()[0]
# In[20]:
arr=np.arange(10,20,2)
s2=pd.Series(arr)#creating a Series from numpy array
# In[21]:
s2
# In[22]:
s2.dtypes
# # Dataframe
# In[24]:
df=pd.read_csv("C://Users/Amil/Downloads/supermarket_sales.csv") # read_csv is used to read a csv file and create a DataFrame
# In[26]:
type(df)
# In[16]:
df.shape
# In[25]:
df.head()
# In[26]:
df.tail(20)
# In[27]:
df.columns #columns will display all the column names
# In[28]:
df.index #index will display the index of rows
# In[25]:
df.dtypes
# In[29]:
df.size
# In[89]:
df.shape[0]*df.shape[1]
# In[30]:
df.describe()#describe function will give us the summary of dataframe (only numerical features)
# In[31]:
df.describe(include='O')#Summary of Object columns
# In[36]:
# checking for missing values information
df.isna().sum()#is not available function
# Theres is no missing value in the present data set
# In[38]:
s=pd.read_csv("C://Users/Amil/Downloads/pqrs.csv")
# In[41]:
s.isna().sum()
# # creating data frame
# In[109]:
#1 Loading existing data
#2 create a DataFrame Programatically
df=pd.DataFrame([["Amal",10],["Babu",11],["Cat",12],["Don",13]],columns=['Name','Age'])
# In[110]:
df.shape
# In[111]:
df.tail()
# In[112]:
df.head()
# In[113]:
df.describe()
# In[114]:
df['Gender']=['M','M','M','F']
# In[104]:
df
# # Access Data from DataFrame
# In[115]:
# to access a column
df['Name']
# In[116]:
df[['Name','Age']]
# In[117]:
#to acess row we need to specify the row index.
#loc means location -we are specifying the location by index.
df.loc[[0,1,2]]
# In[118]:
df.loc[0]
# In[119]:
df.loc[0:4]
# In[120]:
df.index=df['Name']
# In[121]:
df
# In[122]:
df.loc['Amal']
# In[95]:
df
# In[123]:
df.loc[['Amal','Babu','Cat']] #in loc function we are providing the actual index.
# In[65]:
# iloc fuction accept range index ie (0,1,2,4///)
# In[124]:
df.iloc[range(0,df.shape[0])]
# In[126]:
#To access a cell using loc
df.loc['Amal','Age']=27
# In[127]:
df.iloc[0,1]
# In[128]:
df
# In[129]:
# duplicatr index
# loading existing data
# crate a DataFrame Programtically
df1=pd.DataFrame([["A",20],["B",21],["C",22],["A",23]],columns=['Name','Age'])
df1
# In[130]:
df1.index=df1['Name']
# In[131]:
df1['Age']
# In[132]:
df1.iloc[:,1]
# In[133]:
df1.loc['B','Age']
# In[134]:
df.iloc[:,:]
# In[113]:
df.iloc[:,1]
# In[92]:
df.iloc[1,1]
# # Delete rows and columns from DataFrame
# In[136]:
# for deleting rows and columns we use function called 'drop'
# we have to specift the axis
# Axis=0 for rows
# Axis=1 for columns
df1=df1.drop('A')
# In[138]:
df1
# In[139]:
df
# In[141]:
df=df.drop('Gender',axis=1)
# In[142]:
df
# In[143]:
del df['Age']#del command is an alternative to delete columns
# In[144]:
df
# In[4]:
df=pd.read_csv("C://Users/Amil/Downloads/supermarket_sales.csv")
# In[5]:
df.head()
# In[103]:
df.describe()
# In[9]:
# what is tge total gross income?
total_income=df['gross income'].sum()
print("total gross income=",total_income)
# In[119]:
df.iloc[:,15].sum()
# In[13]:
list(df['Payment'].unique())
# In[14]:
# which is the most commonly used payment type
df['Payment'].describe()
# In[15]:
# what is the average unit price of the products¶
df['Unit price'].mean()
# In[17]:
df.iloc[:,6].mean()
# In[18]:
# what is the total number of sales
df['Invoice ID'].unique()
# In[130]:
df['Invoice ID'].describe()
# In[22]:
sales=df.describe(include='O').loc['unique','Invoice ID']
print("Total number of sales:",sales)
# In[19]:
# what is the average gross income
df['gross income'].mean()
# In[20]:
# what is the standard deviation of product unit price
df['Unit price'].std()
# In[24]:
# unique and nunique
# what are the different types of Product line
df['Product line'].unique()
# In[26]:
# How many customer classes are there
df['Product line'].nunique()
# In[115]:
s=pd.read_csv("C://Users/Amil/Downloads/adult.csv")
# In[34]:
s.describe(include='O')
# In[29]:
s.head()
# In[32]:
s.shape
# In[33]:
s.columns
# In[35]:
s.head()
# In[36]:
s.isna().sum()
# In[37]:
s['occupation'].unique()
# In[38]:
s['occupation'].nunique()
# In[39]:
s.dtypes
# # can you calculate average hours per week
# c
# In[40]:
s.describe()
# In[43]:
s['hours-per-week'].mean()
# # can you calculate average hours per male
#
# In[44]:
# when we use grope by it will create data frame into groups in this example it will group into a data frame that consist only of male and other data frame consist of female
# In[46]:
k=s.groupby('gender')
# In[47]:
print(k)
# In[49]:
k['hours-per-week'].mean()
# In[51]:
s['race'].unique()
# In[54]:
s.groupby('race')['hours-per-week'].mean()
# In[65]:
output_df=s.groupby(['race','gender'])[['age','hours-per-week']].median()
# In[66]:
print(output_df)
# In[78]:
output_df1=s.groupby(['race','gender']).median()[['age','hours-per-week']]
# In[68]:
print(output_df1)
# In[72]:
# work class and gender hours per week
s.groupby(['workclass','gender'])['age','hours-per-week'].mean()
# In[75]:
output_df3=s.groupby(['workclass','gender']).median()['hours-per-week']
# In[76]:
print(output_df3)
# In[109]:
output_df3
# # we can create csv file and store our result using following code
# In[113]:
output_df3.to_csv('C://Users/Amil/Downloads/class18mmresults.csv')
# saving as a csv file
# In[114]:
output_df3.to_excel('C://Users/Amil/Downloads/class18mmresults.xlsx')
# saving as a csv file
# # value counts
# value counts() function used to calculate the distrbution
# In[116]:
s['workclass'].value_counts()
# In[118]:
s['gender'].value_counts()
# # combaining 2 dataframes
#
# In[135]:
dataframe1=pd.DataFrame([[1,25,'F'],[2,26,'M'],[3,27,'F'],[4,28,'F'],[7,29,'M'],[89,30,'F'],[390,31,'F']],columns=['ID','Age','Gender'])
# In[128]:
print(dataframe1)
# In[136]:
dataframe2=pd.DataFrame([[1,'A'],[2,'B'],[3,'C'],[29,'D'],[7,'E'],[39,'F'],[38,'G']],columns=['ID','Name'])
# In[137]:
print(dataframe2)
# # Merge is the funtion used for SQL joins in Pandas
# In[138]:
inner_join=pd.merge(dataframe1,dataframe2,how="inner",on="ID")
# dataframe1 is left table
# dataframe2 is the right table
# In[139]:
print(dataframe1)
print(dataframe2)
print(inner_join)
# In[141]:
left_join=pd.merge(dataframe1,dataframe2,how="left",on="ID")
print(left_join)
# In[142]:
right_join=pd.merge(dataframe1,dataframe2,how="right",on="ID")
print(right_join)
# In[143]:
outer_join=pd.merge(dataframe1,dataframe2,how="outer",on="ID")
print(outer_join)
# In[ ]:
|
1d2d55c257cbc981bb800db4f4f429d480d7397f | harishassan85/python-assignment- | /assignment#2/question4.py | 384 | 4.1875 | 4 | #Write a Python program to sum all the numeric items in a list?
#initializing veriable sum
sum = 0
#empty list
numbers = []
n = int(input("How many number of sum you want: "))
#append user input in list
for i in range(n):
number = int(input("Enter Number: "))
numbers.append(number)
#sum of user input
for i in range(n):
sum += numbers[i]
print(sum) |
35f941abd52ec6fd7097326a853447c2b34b44b8 | ravioliasb/COSC310NovaBot | /Code/Wikipedia_Api.py | 514 | 3.734375 | 4 | import wikipedia
import warnings
warnings.catch_warnings()
warnings.simplefilter("ignore")
def wikiSearch(input_): # Takes user input and tries to find it on Wikipedia
input_lower = input_.lower()
input_split = input_lower.split()
ask_wiki = ""
ask = range(1, len(input_split))
for i in ask:
ask_wiki = ask_wiki + input_split[i] + ""
try:
ask_wiki = wikipedia.summary(ask_wiki)
except:
ask_wiki = "Wikipedia could not provide a summary"
return ask_wiki
|
61b588a8547ca9b9c8816d640a6f27d83148bf9c | kumar6273/greyatom-python-for-data-science | /myfolder/code.py | 1,520 | 4.25 | 4 | # --------------
# Code starts here
# Create the lists
class_1= [ "Geoffrey Hinton", " Andrew Ng", "Sebastian Raschka", "Yoshua Bengio"]
class_2= ["Hillary Mason", "Carla Gentry", "Corinna cortes"]
# Concatenate both the strings
new_class = class_1+ class_2
print(new_class)
# Append the list
new_class.append("Peter Warden")
# Print updated list
print(new_class)
# Remove the element from the list
new_class.remove("Carla Gentry")
# Print the list
print(new_class)
# Create the Dictionary
courses={"Math": 65, "English" : 70, "History": 80, "French" : 70, "Science": 60}
print(courses)
total= 65+70+80+70+60
print(total)
percentage= (total/500)*100
print(percentage)
# Slice the dict and stores the all subjects marks in variable
# Store the all the subject in one variable `Total`
# Print the total
# Insert percentage formula
# Print the percentage
# Create the Dictionary
mathematics ={"Geoffrey Hinton": 78, "Andrew Ng": 95, "Sebastian Raschka": 65, "Yoshua Benjio":50, "Hillary Mason": 70, "Corrnna Cortes": 66, "Peter Warden": 75}
print(mathematics)
topper= max(mathematics,key= mathematics.get)
print(topper)
# Given string
# Create variable first_name
first_name= topper.split()[0]
print(first_name)
# Create variable Last_name and store last two element in the list
Last_name= topper.split()[1]
print(Last_name)
# Concatenate the string
full_name = Last_name + " "+ first_name
# print the full_name
print(full_name)
# print the name in upper case
certificate_name = full_name.upper()
print(certificate_name)
# Code ends here
|
c3e785f9e9c628f506e6d3009dd0fb8d22c7c703 | KaloyankerR/python-advanced-repository | /Assignments/Exam Preparation/Python Advanced Exam - 27 June 2020/02. Snake.py | 1,976 | 3.84375 | 4 | def get_snake_position():
global matrix
for r in range(n):
if 'S' in matrix[r]:
for c in range(n):
if matrix[r][c] == 'S':
return [r, c]
# get the index with the .index() method
def get_burrows_indexes(field):
global n
res = []
for x in range(n):
if 'B' in field[x]:
res.append([x, field[x].index('B')])
return res
def is_valid(row1, col1, row2, col2):
global n
return 0 <= (row1 + row2) < n and 0 <= (col1 + col2) < n
moves = {
'up': [-1, 0],
'down': [1, 0],
'left': [0, -1],
'right': [0, 1]
}
n = int(input())
matrix = [[x for x in input()[:n]] for _ in range(n)]
burrows = get_burrows_indexes(field=matrix)
food_quantity = 0
while True:
current_row, current_col = get_snake_position()
current_move = input()
next_row, next_col = moves[current_move]
if not is_valid(current_row, current_col, next_row, next_col):
matrix[current_row][current_col] = '.'
print('Game over!')
break
matrix[current_row][current_col] = '.'
next_snake_position = matrix[current_row + next_row][current_col + next_col]
if next_snake_position == '*':
current_row, current_col = current_row + next_row, current_col + next_col
food_quantity += 1
if food_quantity == 10:
print('You won! You fed the snake.')
matrix[current_row][current_col] = 'S'
break
elif next_snake_position == 'B':
for burrow in burrows:
if [current_row + next_row, current_col + next_col] != burrow:
matrix[current_row + next_row][current_col + next_col] = '.'
current_row, current_col = burrow
else:
current_row, current_col = current_row + next_row, current_col + next_col
matrix[current_row][current_col] = 'S'
print(f'Food eaten: {food_quantity}')
[print(''.join(x)) for x in matrix]
|
68732c8b1e392c646de7a3aa508acc61f3b499e9 | enosteteo/Introducao-a-Programacao-P1 | /4. Estrutura de Repeticao While/Lista 02/programa 02.py | 185 | 3.609375 | 4 | cont = 25
qtdeParEPositivo = 0
while cont > 0:
numero = int(input())
if (numero >= 0) and (numero % 2 == 0):
qtdeParEPositivo += 1
cont -= 1
print(qtdeParEPositivo)
|
75ca1c0aae4309048b616aa5657307dc4ee5ea0b | alexjwong/learning-python | /tictactoe.py | 14,030 | 3.765625 | 4 | #Alexander Wong
#EK128
#If I were to write this again, I would definitely try to use more functions
#-its a little messy right now (but still very much understandable)
import random
#The board will be held in a list
#e will be empty
#o will be a spot where player 'o' has played
#x is a spot where player 'x' has played
board=['e','e','e','e','e','e','e','e','e']
#moves will be referenced by positions 0-8
#012
#345
#678
#print the board
def printboard(board):
print(board[0:3])
print(board[3:6])
print(board[6:9],'\n')
#Check to see if anyone has won
def boardcheck(board):
#compare all possible game ending situations to see if gameover is false
#check horizontals
if (board[0]==board[1]==board[2]=='x') or (board[0]==board[1]==board[2]=='o'):
return True
elif (board[3]==board[4]==board[5]=='x') or (board[3]==board[4]==board[5]=='o'):
return True
elif (board[6]==board[7]==board[8]=='x') or (board[6]==board[7]==board[8]=='o'):
return True
#check verticals
elif (board[0]==board[3]==board[6]=='x') or (board[0]==board[3]==board[6]=='o'):
return True
elif (board[1]==board[4]==board[7]=='x') or (board[1]==board[4]==board[7]=='o'):
return True
elif (board[2]==board[5]==board[8]=='x') or (board[2]==board[5]==board[8]=='o'):
return True
#check diagonals
elif (board[0]==board[4]==board[8]=='x') or (board[0]==board[4]==board[8]=='o'):
return True
elif (board[2]==board[4]==board[6]=='x') or (board[2]==board[4]==board[6]=='o'):
return True
else:
return False
def isEmpty(board,space):
if board[space]=='e':
return True
else:
return False
def canWin(board,player): #where player is either x or o
#checks to see if a winning move is possible during a certain turn
#If there is, it will also return the spot that will result in a win
#horizontal move check
if (board[0]==board[1]==player) and (isEmpty(board,2)==True):
spot=2
return True,spot
elif (board[1]==board[2]==player) and (isEmpty(board,0)==True):
spot=0
return True,spot
elif (board[0]==board[2]==player) and (isEmpty(board,1)==True):
spot=1
return True,spot
elif (board[3]==board[4]==player) and (isEmpty(board,5)==True):
spot=5
return True,spot
elif (board[4]==board[5]==player) and (isEmpty(board,3)==True):
spot=3
return True,spot
elif (board[3]==board[5]==player) and (isEmpty(board,4)==True):
spot=4
return True,spot
elif (board[6]==board[7]==player) and (isEmpty(board,8)==True):
spot=8
return True,spot
elif (board[7]==board[8]==player) and (isEmpty(board,6)==True):
spot=6
return True,spot
elif (board[6]==board[8]==player) and (isEmpty(board,7)==True):
spot=7
return True,spot
#Verticals
elif (board[0]==board[3]==player) and (isEmpty(board,6)==True):
spot=6
return True,spot
elif (board[3]==board[6]==player) and (isEmpty(board,0)==True):
spot=0
return True,spot
elif (board[0]==board[6]==player) and (isEmpty(board,3)==True):
spot=3
return True,spot
elif (board[1]==board[4]==player) and (isEmpty(board,7)==True):
spot=7
return True,spot
elif (board[4]==board[7]==player) and (isEmpty(board,1)==True):
spot=1
return True,spot
elif (board[1]==board[7]==player) and (isEmpty(board,4)==True):
spot=4
return True,spot
elif (board[2]==board[5]==player) and (isEmpty(board,8)==True):
spot=8
return True,spot
elif (board[5]==board[8]==player) and (isEmpty(board,2)==True):
spot=2
return True,spot
elif (board[2]==board[8]==player) and (isEmpty(board,5)==True):
spot=5
return True,spot
#diagonals
elif (board[0]==board[4]==player) and (isEmpty(board,8)==True):
spot=8
return True,spot
elif (board[4]==board[8]==player) and (isEmpty(board,0)==True):
spot=0
return True,spot
elif (board[0]==board[8]==player) and (isEmpty(board,4)==True):
spot=4
return True,spot
elif (board[2]==board[4]==player) and (isEmpty(board,6)==True):
spot=6
return True,spot
elif (board[4]==board[6]==player) and (isEmpty(board,2)==True):
spot=2
return True,spot
elif (board[2]==board[6]==player) and (isEmpty(board,4)==True):
spot=4
return True,spot
else:
return False
def computermove(board,player):
#random corner logic (see corner move below)
corners=[0,2,6,8]
randomcorner1=random.choice(corners)
corners.remove(randomcorner1)
randomcorner2=random.choice(corners)
corners.remove(randomcorner2)
randomcorner3=random.choice(corners)
corners.remove(randomcorner3)
randomcorner4=corners[0]
#random side logic (see side move below)
sides=[1,3,5,7]
rside1=random.choice(sides)
sides.remove(rside1)
rside2=random.choice(sides)
sides.remove(rside2)
rside3=random.choice(sides)
sides.remove(rside3)
rside4=sides[0]
#If can't win, will check if can block
#if can't block, will select intelligent move
if canWin(board,player)==False: #will block in a specific order...note that if the opponent can win in multiple ways, it doesn't matter which spot is blocked first
#determine who is being block based on what player is taking their turn
if player=='x':
blockwho='o'
else:
blockwho='x'
#horizontal move check
if (board[0]==board[1]==blockwho) and (isEmpty(board,2)==True):
return 2
elif (board[1]==board[2]==blockwho) and (isEmpty(board,0)==True):
return 0
elif (board[0]==board[2]==blockwho) and (isEmpty(board,1)==True):
return 1
elif (board[3]==board[4]==blockwho) and (isEmpty(board,5)==True):
return 5
elif (board[4]==board[5]==blockwho) and (isEmpty(board,3)==True):
return 3
elif (board[3]==board[5]==blockwho) and (isEmpty(board,4)==True):
return 4
elif (board[6]==board[7]==blockwho) and (isEmpty(board,8)==True):
return 8
elif (board[7]==board[8]==blockwho) and (isEmpty(board,6)==True):
return 6
elif (board[6]==board[8]==blockwho) and (isEmpty(board,7)==True):
return 7
#Verticals
elif (board[0]==board[3]==blockwho) and (isEmpty(board,6)==True):
return 6
elif (board[3]==board[6]==blockwho) and (isEmpty(board,0)==True):
return 0
elif (board[0]==board[6]==blockwho) and (isEmpty(board,3)==True):
return 3
elif (board[1]==board[4]==blockwho) and (isEmpty(board,7)==True):
return 7
elif (board[4]==board[7]==blockwho) and (isEmpty(board,1)==True):
return 1
elif (board[1]==board[7]==blockwho) and (isEmpty(board,4)==True):
return 4
elif (board[2]==board[5]==blockwho) and (isEmpty(board,8)==True):
return 8
elif (board[5]==board[8]==blockwho) and (isEmpty(board,2)==True):
return 2
elif (board[2]==board[8]==blockwho) and (isEmpty(board,5)==True):
return 5
#diagonals
elif (board[0]==board[4]==blockwho) and (isEmpty(board,8)==True):
return 8
elif (board[4]==board[8]==blockwho) and (isEmpty(board,0)==True):
return 0
elif (board[0]==board[8]==blockwho) and (isEmpty(board,4)==True):
return 4
elif (board[2]==board[4]==blockwho) and (isEmpty(board,6)==True):
return 6
elif (board[4]==board[6]==blockwho) and (isEmpty(board,2)==True):
return 2
elif (board[2]==board[6]==blockwho) and (isEmpty(board,4)==True):
return 4
#-------------------
#Moves if not 'easy'
#if opponent moves corner for first move, computer must choose center
elif (board[0]==blockwho) and (board[1]==board[2]==board[3]==board[4]==board[5]==board[6]==board[7]==board[8]=='e'):
return 4
elif (board[2]==blockwho) and (board[0]==board[1]==board[3]==board[4]==board[5]==board[6]==board[7]==board[8]=='e'):
return 4
elif (board[6]==blockwho) and (board[0]==board[1]==board[2]==board[3]==board[4]==board[5]==board[7]==board[8]=='e'):
return 4
elif (board[8]==blockwho) and (board[0]==board[1]==board[2]==board[3]==board[4]==board[5]==board[6]==board[7]=='e'):
return 4
#if center taken, take corner
elif (board[4] != 'e') and (board[0]==board[1]==board[2]==board[3]==board[5]==board[6]==board[7]==board[8]=='e'):
return random.choice([0,2,6,8])
#special case if opponent has two opposite corners and player has center, need to play a side!
elif (board[4]==player) and (board[0]==board[8]==blockwho) and (board[1]==board[2]==board[5]==board[3]==board[6]==board[7]=='e'):
return random.choice([1,3,5,7])
elif (board[4]==player) and (board[2]==board[6]==blockwho) and (board[0]==board[1]==board[3]==board[5]==board[7]==board[8]=='e'):
return random.choice([1,3,5,7])
#if corner NOT taken already, take random corner
elif board[randomcorner1] == 'e':
return randomcorner1
elif board[randomcorner2] == 'e':
return randomcorner2
elif board[randomcorner3] == 'e':
return randomcorner3
elif board [randomcorner4] == 'e':
return randomcorner4
#center
elif board[4] == 'e':
return 4
#random sides:
elif board[rside1] == 'e':
return rside1
elif board[rside2] == 'e':
return rside2
elif board[rside3] == 'e':
return rside3
elif board[rside4] == 'e':
return rside4
else:
return 'No moves'
elif (canWin(board,player)[0])==True: #if canWin, play winning move
return canWin(board,player)[1]
def tiecheck(board):
if (board[0] !='e') and (board[1] !='e') and (board[2] !='e') and (board[3] !='e') and (board[4] !='e') and (board[5] !='e') and (board[6] !='e') and (board[7] !='e') and (board[8] !='e'):
return True
else:
return False
#Choose what type of game to play
print('What kind of game would you like?')
print('[1] Two player')
print('[2] Player vs.Computer')
print('[3] Computer vs. Computer (simulations)')
gametype=int(input('Enter 1, 2, or 3\n'))
#Variable initialization
gameover=False
numberofmoves=0
#----------------------------------------------------------
#2-PLAYER GAME
#----------------------------------------------------------
if gametype==1:
while gameover==False:
printboard(board)
#player turns
print("Player X's turn")
#enter the position you want to play
xmove=input('Enter a number corresponding to the board:\n012\n345\n678\n')
#modifies the board with player x's move
board[int(xmove)]='x'
if boardcheck(board)==True:
print('Player X wins!')
break
if tiecheck(board)==True:
print('Tie game.')
break
#print the board
printboard(board)
print("Player O's turn")
omove=input('Enter a number corresponding to the board:\n012\n345\n678\n')
board[int(omove)]='o'
if boardcheck(board)==True:
print('Player O wins!')
break
if tiecheck(board)==True:
print('Tie game.')
break
#NOTE*** I have not implemented player so that it allows any combination of human/computer
#At this point, human can only be player 'x' and the computer can only be player 'o'
#---------------------------------------------------------
#PLAYER VS. COMPUTER
#---------------------------------------------------------
elif gametype==2:
while gameover==False:
printboard(board)
xmove=input('Enter a number corresponding to the board:\n012\n345\n678\n')
board[int(xmove)]='x'
if boardcheck(board)==True:
print('You win!')
break
if tiecheck(board)==True:
print('Tie game.')
break
omove=computermove(board,'o')
board[int(omove)]='o'
if boardcheck(board)==True:
printboard(board)
print()
print('The computer won.')
break
if tiecheck(board)==True:
print('Tie game.')
break
#---------------------------------------------------------
#COMPUTER GAME (SIMULATION)
#---------------------------------------------------------
elif gametype==3:
xwin=0
owin=0
tie=0
simulations=int(input('How many simulations?\n'))
for s in range(simulations):
#board reset
board=['e','e','e','e','e','e','e','e','e']
while gameover==False:
#Computer X's turn
xmove=computermove(board,'x')
#modifies the board with player x's move
board[int(xmove)]='x'
if boardcheck(board)==True:
xwin=xwin+1
break
if tiecheck(board)==True:
tie=tie+1
break
#Computer O's turn
omove=computermove(board,'o')
board[int(omove)]='o'
if boardcheck(board)==True:
owin=owin+1
break
if tiecheck(board)==True:
tie=tie+1
break
print('X won',xwin,'times')
print('O won',owin,'times')
print('ties:',tie)
|
1df9a2f92bfefa79e8d51a703936c01a6eac7da4 | AamodPaud3l/python_assignment_dec22 | /dict_num_numsquare.py | 311 | 3.796875 | 4 | # Program to ask a number, n from user and generate a dictionary containing (i, i*i), where i = 1 to n
num = int(input("Enter a number: "))
init = 1
final = 0
num_square = {
}
while num != 0:
if init <= num:
final += init
num_square[final] = final * final
num -= 1
print(num_square)
|
94f81ede48c26011c79cbc4f4ec243a204efb5cc | giserh/com.sma | /src/main/python/alg/best_time_to_buy_and_sell_stock_with_cooldown.py | 1,136 | 3.8125 | 4 | """
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like
(ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
"""
from alg.label import Label
Label(Label.Array, Label.DynamicProgramming, Label.LinearTime, Label.LeetCode)
class Solution(object):
def maxProfit(self, prices):
size = len(prices)
if not size:
return 0
buys = [None] * size
sells = [None] * size
sells[0], buys[0] = 0, -prices[0]
for x in range(1, size):
delta = prices[x] - prices[x - 1]
sells[x] = max(buys[x - 1] + prices[x], sells[x - 1] + delta)
buys[x] = max(buys[x - 1] - delta, sells[x - 2] - prices[x] if x > 1 else None)
return max(sells)
|
b2f7493d2ea2c23c884aaeda4a30735a297054b1 | LucianoPAlmeida/udacity-data-analysis-exercices | /Lesson4/Code/project.py | 707 | 3.640625 | 4 | import numpy as np
import pandas as pd
titanic_df = pd.read_csv('../titanic_data.csv')
# How many of the survivals where female and male
print 'How many of the survivals where female and male'
print titanic_df.groupby('Sex')['Survived'].sum()
# How many of the survivals per class
print 'How many of the survivals per class'
print titanic_df.groupby('Pclass')['Survived'].sum()
# Mean price for each class
print 'Mean price for each class'
print titanic_df.groupby('Pclass')['Fare'].mean()
# Graphical plot of tickets fare
print 'Graphical plot of tickets fare'
ticket_fare = titanic_df['Fare']
ticket_standarize = (ticket_fare - ticket_fare.mean()) / ticket_fare.std(ddof=0)
ticket_standarize.plot() |
f53b2bbfe37ed53c0f9994ddcfce1535f7e6cd3f | nicksteffen/GroupmeBot | /parser.py | 406 | 3.796875 | 4 | import re
def contains_key_phrase(phrase):
word_list=[]
word_list=phrase.split()
for word in word_list:
word= re.sub(r'\W+','',word)
if word.endswith("er"):
return word
return False
def format_message(phrase):
word=contains_key_phrase(phrase)
if word == False:
return False
message = word[:1].upper()+word[1:-2]+" her?"
return message
|
198723bc3f8a4509816288c68788c462962ac0de | linminhtoo/algorithms | /greedy/medium/jumpGameI.py | 495 | 3.625 | 4 | # https://leetcode.com/problems/jump-game/submissions/
from typing import List
class Solution:
def canJump(self, nums: List[int]) -> bool:
furthest_idx = 0
for i in range(len(nums)):
if furthest_idx < i:
# check if position i could be reached based on current furthest_idx
# if it cant be reached, we cant continue, so False
return False
furthest_idx = max(furthest_idx, nums[i] + i)
return True |
deb9a1136a297ffb4ed4c417e4745d70d4b0a3ca | Akimov232/big_work | /hangman.py | 2,173 | 3.765625 | 4 | from random import choice
def generate_word(w):
'''
input: list of words
output: 1 word which generated choice
'''
return choice(w)
def start_string(w):
tp = []
for i in w :
tp.append('_')
return tp
def welcome_speake(t):
print(f'''Добро пожаловать в игру hangman2000
Вам надо отгадать словов за три попытки или вы проиграете!
Загаданное слово состоит из {len(t)} букв {t}
''')
def user_guess():
return input("Введите букву:")
def build_tamplate_in_game(w , r , n=''):
for i in range(len(r)):
if w[i] == '_':
if r[i] == n:
w[i] = r[i]
else:
w[i] = '_'
return w
def listen_convert(t):
s = ''
return s.join(t)
def print_resalts(w):
print(f"Ваш результат:{w}")
def check_win(w):
for i in w:
if i == '_':
return True
return False
def check_mistake(w, g):
foo = False
for i in w:
if i == g:
foo = True
return foo
def check_lifes(life):
life = life - 1
return life
def lose_print():
print("Вы проиграли!")
def win_print():
print("Поздравляю, Вы выйграли!")
def main():
game = True
lifes = 3
word = ['ban' , 'daniil' , 'love']
word_play = generate_word(word)
string = start_string(word_play)
welcome_speake(listen_convert(string))
while game:
user_input = user_guess()
tamplate = build_tamplate_in_game(string , word_play , user_input)
guessed = listen_convert(tamplate)
print_resalts(guessed)
game = check_win(guessed)
if not check_mistake(word_play , user_input):
print(f"У вас осталось {lifes} попыток!")
lifes = check_lifes(lifes)
if lifes == 0:
lose_print()
if not game :
win_print()
main() |
0f807f2f2637748a25e2ff2df3c8c4c5a91d7ebe | needsomeham/School_Projects | /CS5050_Advanced_Algos/HW7_FFT/PythonFFT.py | 3,868 | 3.75 | 4 | import cmath
import numpy as np
import matplotlib.pyplot as plt
import time
import random
# Small function to ensure that the string is of length 2^something
# If not, pad the end till it is
def addPadding(x):
# Finds the smallest power of 2 that is larger than the len(x)
power = 0
while 2**power < len(x):
power +=1
if len(x) == 2**power:
return x
# Creating new string and padding it
fullX = [0 for i in range(2**power)]
for i in range(len(x)):
fullX[i] = x[i]
return fullX
# A helper function to kick off the recursive FFT function
def FFThelper(x):
finalX = addPadding(x)
answer = FFT(finalX,len(finalX))
return answer
# Main FFT function
# Based off of the Cooley and Tukey exploitation of the discrete Fourier Transform
# Works based on symmetry in the function to exploti the fact that you can split even and odd parts of the function
# based on a small algebraic trick. Basically without the algebra the function is O(n^2), but with the trick
# it becomes O(nlogn + n) but the final +n falls off.
# You could also get rid of the the passed N and just take the size of the array on the first step reducing the need
# for a recursive kick off function.
# Based on: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm
def FFT(x:[],N:int):
# Base case
if N <= 1:
return x
else:
# Splitting the lists into even and odd bins
listEven = FFT(x[::2], int(N/2))
listOdd = FFT(x[1::2], int(N/2))
# Making an array for to hold the solution
ans = [0 for i in range(N)]
# Populating the array where one half of the complex conjugate goes in the first position while the second half
# goes in the N/2 th position.
for k in range(int(N/2)):
ans[k] = listEven[k] + cmath.exp(-2j*cmath.pi*k/N)*listOdd[k]
ans[k+int(N/2)] = listEven[k] - cmath.exp(-2j*cmath.pi*k/N)*listOdd[k]
return ans
# Just a little safety net just in case the program crashes or something
def printToFile(pow:int,npFFT,stFFT):
file = open('dataCache.txt','a')
file.write(f"pow:{pow}\n")
file.write(f"n:{npFFT}\n")
file.write(f"s:{stFFT}\n\n")
file.close()
# Function to graph the time comparison of my FFT vs community numpy FFT
def graphTimes(powers:[],studentTimes:[],numpyTimes:[]):
# Scattering each of the datasets
plt.scatter(powers,studentTimes, color = 'red', label = 'Student FFT times')
plt.scatter(powers,numpyTimes, color = 'blue', label = 'Numpy FFT times')
# Some general overhead for the graph
plt.yscale('log')
plt.xlabel('Size of array, exponent of 2')
plt.ylabel('Time to complete FFT in nanoseconds')
plt.title('Time to solve FFT for various sized arrays')
# Showing the graph
plt.legend()
plt.show()
if __name__ == '__main__':
# Some containers to hold the data
pows = []
timeNumpy = []
timeMyFFT = []
# Largest power user would like to run to
largestPow = 24
# Timing various lengths of strings
for pow in range(largestPow + 1):
print(f'Working on string length of 2^{pow}')
# Generating a randomly filled array
FFTthis = [random.randint(0,50) for i in range(2**pow)]
# Timing my FFT
start = time.time_ns()
FFThelper(FFTthis)
end = time.time_ns()
deltaMyFFT = end - start
# Timing numpy FFT
startNP = time.time_ns()
np.fft.fft(FFTthis)
endNP = time.time_ns()
deltaNP = endNP - startNP
# Adding results to both the safety file and also to the graph
printToFile(pow,deltaNP,deltaMyFFT)
pows.append(pow)
timeNumpy.append(deltaNP)
timeMyFFT.append(deltaMyFFT)
# Graphing the results
graphTimes(pows,timeMyFFT,timeNumpy) |
0cbfdd0fbafb72100c5c75e4a3d8532dee14e046 | richard-durham/AdventOfCode | /Advent_day2.py | 1,441 | 3.84375 | 4 | ''' From www.adventofcode.com
Day 2 questions
'''
with open('day2.txt', 'r') as input_packages:
list_of_packages = input_packages.readlines()
print len(list_of_packages)
def make_package_usable(package):
''' split the package into seperate dimensions, convert them to int, and sort
'''
dimensions = package.split('x')
int_dimensions = (int(dimensions[0]), int(dimensions[1]), int(dimensions[2]))
sorted_package_dimensions = sorted(int_dimensions)
return sorted_package_dimensions
def wrapping_paper(dimensions):
''' calculate amount of wrapping paper needed
assumes sorted dimensions as input
'''
length = dimensions[0]
width = dimensions[1]
height = dimensions[2]
dim1 = 2 * length * width
dim2 = 2 * length * height
dim3 = 2 * width * height
extra = length * width # assumes dimensions are sorted so height is the largest measure
return dim1 + dim2 + dim3 + extra
def ribbon(dimensions):
''' calculate amount of ribbon needed
'''
length = dimensions[0]
width = dimensions[1]
height = dimensions[2]
ribbon_only = length + length + width + width
bow = length * width * height
return ribbon_only + bow
paper_needed = 0
ribbon_needed = 0
for package in list_of_packages:
dimensions = make_package_usable(package)
paper_needed += wrapping_paper(dimensions)
ribbon_needed += ribbon(dimensions)
print "Wrapping paper needed: %d" % paper_needed
print "and this much ribbon: %d" % ribbon_needed
|
7ed798f39088ad9c6bd27506104abd0a8560245c | JimzyLui/pySplitFiles | /pySplitFiles old.py | 3,245 | 3.984375 | 4 |
# from itertools import chain
import csv
import argparse
import os
def split_file(filename, pattern, size):
"""
Split a file into multiple output files.
The first line read from 'filename' is a header line that is copied to every output file. The remaining lines are split into blocks of at least 'size' characters and written to output files whose names are pattern.format(1), pattern.format(2), and so on. The last output file may be short.
"""
with open(filename, 'r') as f:
header = next(f)
for index, line in enumerate(f, start=1):
with open(pattern.format(index), 'w') as out:
out.write(header)
n = 0
for line in chain([line], f):
out.write(line)
n += len(line)
if n >= size:
break
def split_csv(filename, pattern, maxlines):
arrHeadings = []
with open(filename, newline='') as f:
csv_reader = csv.reader(f,delimiter=',')
arrHeadings = next(csv_reader,None)
file_counter=1
# print(arrHeadings)
for index, line in enumerate(f, start=1):
print('line #',index)
newfile = pattern.format(index)
print('-->new filename:',newfile, index)
with open(newfile, 'w', newline='') as csv_partialfile:
rowcount = 1
csv_writer = csv.writer(csv_partialfile, delimiter=',')
csv_writer.writerow(arrHeadings)
for row in csv_reader:
# print(row)
csv_writer.writerow(row)
# print('line: ',line)
rowcount=rowcount+1
if rowcount >= maxlines:
# print('break:',index, row)
file_counter = file_counter +1
break
def split_txt(filename, pattern, maxlines):
txtPartial = None
filecount=1
with open(filename,'r') as txt:
headingRow = txt.readline()
for index, line in enumerate(txt):
if index % maxlines == 0:
if txtPartial:
txtPartial.close()
# newfile = pattern.format(index)
newfile = pattern.format(filecount)
filecount = filecount +1
txtPartial = open(newfile, "w")
txtPartial.write(headingRow)
txtPartial.write(line)
if txtPartial:
txtPartial.close()
def generateNewFilePattern(inputFilepath):
filename_w_ext = os.path.basename(inputFilepath)
filebasename, file_extension = os.path.splitext(filename_w_ext)
pattern = filebasename+'_part_{0:03d}'+'.'+file_extension
return pattern
if __name__ == '__main__':
parser = argparse.ArgumentParser(
prog='pySplitFiles',
description='Splits csv files into smaller ones with headings'
)
parser.add_argument("csvfilename", help="the name of the csv file to be split up")
parser.add_argument("maxlines", action='store', type=int, default=5, help="the max number of lines in each new file")
args = parser.parse_args()
namingPattern = generateNewFilePattern(args.csvfilename)
# split_file('data.csv', 'part_{0:03d}.txt', 15)
# split_txt(args.csvfilename, 'part_{0:03d}.txt', args.maxlines)
split_txt(args.csvfilename, namingPattern, args.maxlines) |
ddef51a783c2db7f3b6caf511b9003a0d5216816 | Tai-Son/Python-Chile | /python/funciones6.py | 381 | 3.875 | 4 | # Escribir una funcion recursiva para contar en cuantos intentos
#Practica de funciones
#! /usr/bin/python
# -*- coding: iso-8859-15
from random import *
def adivina(n):
n = randint(1,6)
return n
a = int(input("Adivina el numero: "))
for i in range(a):
print adivina(1)
if a== adivina(i):
print("Acerto ", a, i )
else:
print ("Fallo", a, i)
|
b5cd8af793e0ecf8025cdd667133a50610930e1e | dmitry-pechersky/algorithms | /hackerrank/The Longest Increasing Subsequence.py | 636 | 4 | 4 | def smallest_greater_dc(array, a, b, value):
while a != b:
c = (a + b) // 2
if array[c] < value:
a = c + 1
else:
b = c
return b
def longest_increasing_subsequence(sequence):
dp = [sequence[0]]
for i in range(1, len(sequence)):
if sequence[i] > dp[-1]:
dp.append(sequence[i])
elif sequence[i] < dp[-1]:
dp[smallest_greater_dc(dp, 0, len(dp) - 1, sequence[i])] = sequence[i]
return len(dp)
if __name__ == '__main__':
sequence = [int(input()) for i in range(int(input()))]
print(longest_increasing_subsequence(sequence))
|
e4739c89a498e0612dceaf22d47c31777c20097c | GTxx/leetcode | /algorithms/283. Move Zeroes/main.py | 823 | 3.609375 | 4 | from typing import List
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero_num = 0
non_zero_idx = 0
idx = 0
while non_zero_idx < len(nums):
if nums[non_zero_idx] == 0:
non_zero_idx += 1
zero_num += 1
else:
nums[idx] = nums[non_zero_idx]
idx += 1
non_zero_idx += 1
for i in range(idx, len(nums)):
nums[i] = 0
if __name__ == "__main__":
nums = [0,1,0,3,12]
s = Solution()
s.moveZeroes(nums)
assert nums == [1,3,12,0,0]
nums = []
s.moveZeroes(nums)
assert nums == []
nums = [0]
s.moveZeroes(nums)
assert nums == [0]
|
030284e80b92f1f2c886bde002847f65d4c86bb2 | 666syh/Learn_Algorithm | /31_Next_Permutation.py | 1,430 | 3.875 | 4 | """
https://leetcode.com/problems/next-permutation/
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
"""
class Solution:
def nextPermutation(self, nums: 'List[int]') -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# 1. 从后往前遍历,找到第一个比后一个小的数字
e = len(nums)
l = len(nums)-2
while l>=0:
if nums[l] < nums[l+1]:
break
l-=1
if l == -1:
nums[:] = nums[::-1]
return
# 2. 将后面比这个数字大的第一个数字与这个数字交换
t = len(nums)-1
while nums[t]-nums[l]<=0:
t-=1
nums[l], nums[t] = nums[t], nums[l]
# 3。 之后将所有后边的数转置
l, r = l+1, e-1
while l<r:
nums[l], nums[r] = nums[r], nums[l]
l+=1
r-=1
x = Solution()
nums = [1,3,2]
x.nextPermutation(nums)
print(nums) |
26af18f58bbf0dda025b7bec0e2d98b03d917029 | bemcgahan/webscraper | /business_record.py | 1,791 | 3.5 | 4 | import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://www.businessrecord40.com/caroline-bettis'
# opeining up connection, grabbing page
uClient = uReq(my_url)
# puts content into variable
page_html = uClient.read()
#close web connection
uClient.close()
filename = "test3.csv"
# use if creating new file
f = open(filename, "w")
# use if adding to an existing file
#f = open(filename, "a")
header = "name, age, title, family, reason 40 under 40, motivation, fun fact\n"
# use only when writing a document otherwise comment out
f.write(header)
# html parsing
page_soup = soup(page_html, "html.parser")
# change ID for each person
content = page_soup.find("div",{"id":"block-7a5c1de9ad874ac39e2e"})
name_field = content.p.text
age_start = content.find_all('p')[1].text
index = age_start.find(':') + 2
age = age_start[index:]
title_start= content.find_all('p')[2].text
index = title_start.find(':') + 2
title = title_start[index:]
family_start = content.find_all('p')[3].text
index = family_start.find(':') + 2
family = family_start[index:]
reason_start = content.find_all('p')[4].text
index = reason_start.find(':') + 2
reason = reason_start[index:]
motivation_start = content.find_all('p')[5].text
index = motivation_start.find(':') + 2
motivation = motivation_start[index:]
fact_start = content.find_all('p')[6].text
index = fact_start.find(':') + 2
fact = fact_start[index:]
# chance commas to bars so it's not separated into multiple columns
f.write(name_field + "," + age + "," + title.replace(",", "|") + "," + family.replace(",", "|") + "," + reason.replace(",", "|") + "," + motivation.replace(",", "|") + "," + fact.replace(",", "|") + "\n")
f.close() |
4fb8dd222e8f3caa16f4e2a40c8bf0f060f85e03 | divindvm/MyStudyCompanion-MSC- | /projecttrials/timetable/inputtkinter.py | 506 | 3.5 | 4 | from Tkinter import *
def get_class():
print(var.get())
def get_entry():
print(ent.get())
lsum["text"]="ohh noooo"
textinp.set("shit")
root=Tk()
var=StringVar()
textinp=StringVar()
ent=Entry(root,textvariable=var)
ent.place(x=10,y=10,width=100)
ent2=Entry(root,textvariable=textinp)
lsum=Label(root,text="the")
btn1=Button(root,text="Variable class",command=get_class)
btn2=Button(root,text="Get Method",command=get_entry)
ent.pack()
ent2.pack()
btn1.pack()
btn2.pack()
lsum.pack()
root.mainloop()
|
64bb1ec663ceae762087718988c004d1f199b8a3 | jcockbain/ctci-solutions | /chapter-10/Q02_group_anagrams.py | 827 | 4 | 4 | import unittest
def group_anagrams(word_list):
anagrams = {}
for w in word_list:
sorted_word = "".join(sorted(w))
if sorted_word in anagrams:
anagrams[sorted_word].append(w)
else:
anagrams[sorted_word] = [w]
res = []
for sorted_word in anagrams:
for word in anagrams[sorted_word]:
res.append(word)
return res
class GroupAnagramsTest(unittest.TestCase):
def test_group_anagrams(self):
wordList = ["cheese", "ham", "hceese", "mha", "spam"]
expected = ["cheese", "hceese", "ham", "mha", "spam"]
self.assertEqual(expected, group_anagrams(wordList))
wordList2 = ["hello", "world", "olleh"]
expected2 = ["hello", "olleh", "world"]
self.assertEqual(expected2, group_anagrams(wordList2))
|
8bad5445386914131da5f76922cd9b19a739cb93 | gabriellaec/desoft-analise-exercicios | /backup/user_063/ch36_2019_09_18_19_55_17_743327.py | 232 | 3.625 | 4 | def eh_primo(x):
y=2
if x==2:
return True
if x==0 or x==1:
return False
while x>y:
if x%y==0:
return False
else:
return True
y+=1 |
62775ac7718476541df572166c25fc69f94dcbe6 | mohira/oop-iroha-python | /interface_08.py | 2,186 | 3.953125 | 4 | """
https://qiita.com/nrslib/items/73bf176147192c402049#interface
もう1つのif文 要素の評価 に interface を使ってみる
"""
from abc import ABCMeta, abstractmethod
from typing import List
class IConverter(metaclass=ABCMeta):
@abstractmethod
def convert(self, data: List[str]) -> str:
pass
class CsvConverter(IConverter):
def convert(self, data: List[str]) -> str:
if data:
csv = data[0]
else:
csv = ""
for d in data[1:]:
csv += f",{d}"
return csv
class TsvConverter(IConverter):
def convert(self, data: List[str]) -> str:
if data:
tsv = data[0]
else:
tsv = ""
for d in data[1:]:
tsv += f"\t{d}"
return tsv
class PipeJoinConverter(IConverter):
def convert(self, data: List[str]) -> str:
if data:
text = data[0]
else:
text = ""
for d in data[1:]:
text += f"|{d}"
return text
class IEvaluator(metaclass=ABCMeta):
@abstractmethod
def evaluate(self, data: List[str]) -> None:
pass
class NormalEvaluator(IEvaluator):
def evaluate(self, data: List[str]) -> None:
if len(data) > 10:
print("Many elements.")
else:
print("Few elements.")
class IsEvenEvaluator(IEvaluator):
def evaluate(self, data: List[str]) -> None:
if len(data) % 2 == 0:
print("even")
else:
print("odd")
class Program:
def process(self, converter: IConverter, data: List[str], evaluator: IEvaluator):
output = converter.convert(data)
evaluator.evaluate(data)
print(output)
if __name__ == "__main__":
data = ["Bob", "Tom", "Ken"]
Program().process(CsvConverter(), data, NormalEvaluator())
Program().process(TsvConverter(), data, NormalEvaluator())
Program().process(PipeJoinConverter(), data, NormalEvaluator())
Program().process(CsvConverter(), data, IsEvenEvaluator())
Program().process(TsvConverter(), data, IsEvenEvaluator())
Program().process(PipeJoinConverter(), data, IsEvenEvaluator())
|
dcf84af54b511a5cb05b8346d687bb1687eb2f1a | bybside/cb-trade-analysis | /models/strategy.py | 685 | 3.546875 | 4 | from models.wallet import Wallet
class Strategy:
"""
this class is intended as an abstract base class
for implementing various trading strategies
"""
def __init__(self, token: str, init_cash_amount: float):
self.wallet = Wallet(token, init_cash_amount)
self.start_amount = init_cash_amount
# this should be set once strategy has run
self.end_amount = 0
# rate of return will be calculated once strategy is executed
self.ror = 0
def run(self):
pass
def calculate_ror(self):
raw_ror = ((self.end_amount - self.start_amount) / self.start_amount) * 100
self.ror = round(raw_ror, 2)
|
b73f68257023c1fa8bc857f401cec846ef532ede | ejm714/dsp | /python/advanced_python_regex.py | 741 | 3.59375 | 4 | ## Q1
import pandas as pd
from collections import Counter
df = pd.read_csv('https://raw.githubusercontent.com/ejm714/dsp/master/python/faculty.csv')
print(df.columns.tolist())
df.columns = df.columns.str.strip()
degrees = df['degree'].str.strip().str.replace('.', '').str.split()
degree_counts = Counter(degrees.sum())
print degree_counts
len(degree_counts)
## Q2
title = df['title'].str.replace(' is ', ' of ')
title_counts = title.value_counts()
print title_counts
len(title_counts)
## Q3
emails = df['email'].tolist()
print emails
txt_file = open('q3.txt', 'w')
txt_file.write('%s' % emails)
txt_file.close()
## Q4
unique_domains = df['email'].str.split('@').str[1].drop_duplicates().tolist()
print unique_domains
len(unique_domains)
|
a83f619f7756122c0107bfdc6914965af3a10aee | DavidToca/programming-challanges | /leetcode/130. Surrounded Regions/solve.py | 1,962 | 3.625 | 4 | CHANGE_TO_O = '1'
class Solution:
def generate_n(self, board, row, col):
n = []
options = [
(-1, 0),
(0, -1),
(0, 1),
(1, 0),
]
max_row = len(board)
max_col = len(board[0])
for option in options:
x, y = option
row2 = row + x
col2 = col + y
if row2 >= max_row or row2 < 0:
continue
if col2 >= max_col or col2 < 0:
continue
if board[row2][col2] == 'O':
n.append((row2, col2))
return n
def dfs_color(self, board, row, col, visited, color):
hash_code = f"{row}-{col}"
if hash_code in visited:
return
visited[hash_code] = True
board[row][col] = color
coordinates = self.generate_n(board, row, col)
for coordinate in coordinates:
x, y = coordinate
self.dfs_color(board, x, y, visited, color)
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
max_rows = len(board)
max_cols = len(board[0])
if max_rows <= 2 or max_cols <= 2:
return
for row in range(max_rows):
columns = [0, max_cols - 1]
if row in [0, max_rows - 1]:
columns = list(range(max_cols))
for col in columns:
print(row, col)
if board[row][col] != 'O':
continue
self.dfs_color(board, row, col, dict(), CHANGE_TO_O)
for row in range(max_rows):
for col in range(max_cols):
if board[row][col] == 'X':
continue
if board[row][col] == CHANGE_TO_O:
board[row][col] = 'O'
else:
board[row][col] = 'X'
|
4dd47f5967bb70ec3f26e8a9ded13eada675c1ad | Aasthaengg/IBMdataset | /Python_codes/p02261/s775073974.py | 1,173 | 3.609375 | 4 | def selectionSort(n, A):
cnt = 0
for i in range(n):
minj = i
for j in range(i, n):
if A[minj][1] > A[j][1]:
minj = j
if i != minj:
A[i], A[minj] = A[minj], A[i]
cnt += 1
return A
def bubbleSort(n, A):
flag = True
cnt = 0
while flag:
flag = False
for j in range(n - 1, 0, -1):
if A[j - 1][1] > A[j][1]:
A[j - 1], A[j] = A[j], A[j - 1]
cnt += 1
flag = True
return A
def stableSort(input, output):
n = len(input)
for i in range(n):
for j in range(i + 1, n):
for a in range(n):
for b in range(a + 1, n):
if input[i][1] == input[j][1] and input[i] == output[b] and input[j] == output[a]:
return print("Not stable")
return print("Stable")
if __name__ == '__main__':
n = int(input())
R = list(map(str, input().split()))
C = R[:]
D = R[:] #????????¨?????????
SR = selectionSort(n, R)
BR = bubbleSort(n, C)
print(*BR)
stableSort(D,BR)
print(*SR)
stableSort(D,SR) |
8c843be93c18671fa448c3fd6de4f76473f0f22f | notveryfamous/python1 | /冒泡排序.py | 502 | 3.734375 | 4 | nums = [6, 5, 3, 1, 8, 7, 2, 4]
# 冒泡排序思想:
# 让一个数字和它相邻的下一个数字进行比较运算
# 如果前一个数字大于后一个数字,交换两个数据的位置
# 每一次比较次数的优化
# 总比较次数的优化
i = 0
while i < len(nums) - 1:
i += 1
n = 0
while n < len(nums) - 1:
# print(nums[n], nums[n + 1])
if nums[n] > nums[n + 1]:
nums[n], nums[n + 1] = nums[n + 1], nums[n]
n += 1
print(nums)
|
8d392335fb299af93dfa607c97b00191d60e6fb1 | jonasmzsouza/fiap-tdsr-ctup | /20200408/problema4.4.py | 482 | 3.90625 | 4 | # Problema 4.4: Escreva um programa que dadas duas notas de 0 a 10 calcula a média aritmética entre elas.
nota1 = float(input("Digite a primeira nota: "))
while nota1 < 0 or nota1 > 10:
nota1 = float(input("Nota inválida, digite a primeira nota: "))
nota2 = float(input("Digite a segunda nota: "))
while nota2 < 0 or nota2 > 10:
nota2 = float(input("Nota inválida, digite a segunda nota: "))
media = (nota1 + nota2) / 2
print("A média vale {:.2f}".format(media))
|
17007871b3550fee5fafef115ccf5cbe9b377467 | nguyntyler/DigitalCrafts-Algorithms | /NumOccurence.py | 371 | 4.1875 | 4 | # 2. Write a function that counts the number of times the number 7 occurs in a given integer
# without converting it to a string.
# # For example the number 7,704,793 would output 3
import math
def seven_counter(num):
count = 0
while num > 0:
rem = num % 10
if rem == 7:
count += 1
num = math.floor(num/10)
print(count)
|
64928fd3a60a32ca6ef2596d9feacde57cd5040a | strategist922/SinicaSemanticParserChinese | /shared/prepareData.py | 10,222 | 3.59375 | 4 | import string
import re
class Tree(object):
def __init__(self):
self.children = []
self.data = None
self.pos = None
self.position = None
self.word = None
self.depth = 0
self.terminal = False
self.terNo = None
self.parent = None
#self.sid = None
def print_tree(tree):
if tree != None:
print str(tree.terNo)+' ('
for ch in tree.children:
print_tree(ch)
print ')'
def print_tree_file(tree,tree_line):
if tree != None:
if tree.children == []:
tree_line.append('(' + str(tree.data)+' '+str(tree.word)+')')
return tree_line
else:
tree_line.append('('+str(tree.data)+' ')
for ch in tree.children:
tree_line = print_tree_file(ch,tree_line)
tree_line.append(') ')
return tree_line
def parseExpr(expr,depth,r):
expr = expr.rstrip()
expr = ''.join(list(expr)[1:-1]).rstrip(' ')
#print expr
if expr.find('(') == -1:
#print expr
#print
node = Tree()
node.data = ''.join(expr.split(' ')[0])
node.word = ''.join(expr.split(' ')[1])
node.terminal = True
node.depth = depth
node.terNo = r
r = r + 1
node.children = []
'''print node.data
print node.word
print node.depth
print node.terminal
print node.terNo
print'''
return (node,r)
else:
node = Tree()
node.data = ''.join(expr.split(' ')[0])
#node.word = ''.join(expr.split(' ')[1])[0:-1]
node.terminal = False
#node.terNo = r
node.depth = depth
children = findChildren(' '.join(expr.split(' ')[1:]))
'''print node.data
print node.word
print node.depth
print node.terminal
print node.terNo
print'''
#print len(children)
#print children
#print
for ch in children:
(n,r) = parseExpr(ch.lstrip('\n').lstrip('\t').lstrip(' '),depth+1,r)
node.children.append(n)
n.parent = node
return (node,r)
def findChildren(exp):
#print exp
#print
expr = list(exp.lstrip(' ').lstrip('\t').lstrip('\n').rstrip(' ').rstrip('\t').rstrip('\n'))
c = 0
buffer = []
children = []
for tk in expr:
if tk == '(':
c = c + 1
buffer.append(tk)
elif tk == ')':
c = c - 1
buffer.append(tk)
if c == 0:
children.append((''.join(buffer)).lstrip())
buffer = []
continue
elif tk == '\t' or tk == '\n':
continue
else:
buffer.append(tk)
#children.append(''.join(buffer))
return children
def traverse_tree(t,c):
if t.terNo == c:
print t.data
for chh in t.children:
print chh.data
return t
for ch in t.children:
traverse_tree(ch,c)
def traverse_tree_depth(t,n,d):
for ch in t.children:
t_found = find_terminal(ch,n,None)
if t_found != None:
#print t_found.data
#print t_found.depth
td = t_found.depth
#arg = find_arg(ch,td-d,None)
arg = find_arg(t_found,d)
#print arg.data
#print_tree(arg)
return (arg,t_found.terNo)
break
return (0,0)
def find_terminal(ch,n,c):
if ch.terNo == n:
c = ch
for sub_ch in ch.children:
c = find_terminal(sub_ch,n,c)
return c
def find_arg(node,d):
for i in range (0,d):
node = node.parent
return node
def find_gov(t,n,d):
for ch in t.children:
t_found = find_terminal(ch,n,None)
if t_found != None:
#print t_found.data
#print t_found.depth
td = t_found.depth
#arg = find_arg(ch,td-d,None)
arg = find_arg(t_found,d)
if arg != None:
while arg.data != 'S' or arg.data != 'VP':
arg = arg.parent
if arg != None:
if arg.data == 'S' or arg.data == 'VP':
return arg.data
continue
else:
return 'none'
def path(t,n,d,pred):
for ch in t.children:
t_found = find_terminal(ch,n,None)
if t_found != None:
#print t_found.data
#print t_found.depth
td = t_found.depth
#arg = find_arg(ch,td-d,None)
arg = find_arg(t_found,d)
if arg != None:
full_path = find_full_path(arg,t,n,d,pred)
(path_to_BA,BA_terNo) = find_path_to_BA(arg,t,n,d,pred,'BA','BA')
(path_to_BEI,BEI_terNo) = find_path_to_BA(arg,t,n,d,pred,'SB','LB')
if path_to_BA != [] and 'dBA' in path_to_BA:
#print path_to_BA
path_BA = path_to_BA[0:path_to_BA.index('dBA')]
voice = 'passive'
else:
path_BA = 'no-BA'
voice = 'active'
if path_to_BEI != []:
if 'dSB' in path_to_BEI:
path_BEI = path_to_BEI[0:path_to_BEI.index('dSB')]
voice = 'passive'
elif 'dLB' in path_to_BEI:
path_BEI = path_to_BEI[0:path_to_BEI.index('dLB')]
voice = 'passive'
else:
path_BEI = 'no-BEI'
voice = 'active'
else:
path_BEI = 'no-BEI'
voice = 'active'
return (full_path,''.join(path_BA),''.join(path_BEI),voice,BA_terNo,BEI_terNo)
'''full_path = [arg.data]
found = False
while found == False and arg!= None and arg.parent != None:
partial_path = []
invalid_ch = arg
arg = arg.parent
full_path.append(arg.data)
(partial_path,found) = find_predicate(arg,invalid_ch,pred,[],found)
full_path = full_path + partial_path
#path_to_BA =
return full_path'''
def find_full_path(arg,t,n,d,pred):
full_path = [arg.data]
found = False
partial_path = []
while found == False and arg!= None and arg.parent != None:
partial_path = []
invalid_ch = arg
arg = arg.parent
path_node = 'u'+arg.data.rstrip() # 'u' to denote upward direction
#full_path.append(arg.data.rstrip())
full_path.append(path_node)
(partial_path,found) = find_predicate(arg,invalid_ch,pred,[],found)
full_path = full_path + partial_path
#path_to_BA =
return ''.join(full_path)
def find_predicate(arg,invalid_ch,pred,p_path,f):
for ch in arg.children:
if ch != invalid_ch:
if ch == pred and ch.terNo == pred.terNo and f == False:
#print ch.data
#print ch.terNo
#print n
f = True
path_node = 'd'+ch.data.rstrip() # 'd' to denote downward direction
p_path.append(path_node)
#p_path.append(ch.data.rstrip())
break
elif f == False:
#f = False
path_node = 'd'+ch.data.rstrip() # 'd' to denote downward direction
p_path.append(path_node)
#p_path.append(ch.data.rstrip())
#print p_path
(p_path,f) = find_predicate(ch,'',pred,p_path,f)
else:
continue
if f == False:
p_path = p_path[0:-1]
return (p_path,f)
def find_path_to_BA(arg,t,n,d,pred,b1,b2):
full_path = [arg.data]
found = False
while found == False and arg!= None and arg.parent != None:
partial_path = []
invalid_ch = arg
arg = arg.parent
path_node = 'u'+arg.data.rstrip() # 'u' to denote upward direction
full_path.append(path_node)
#full_path.append(arg.data)
(partial_path,found,BA_terNo) = find_BA(arg,invalid_ch,pred,[],found,b1,b2,0)
if found != False:
full_path = full_path + partial_path
#print partial_path
else:
full_path = []
BA_terNo = 0
#path_to_BA =
return (full_path,BA_terNo)
def find_BA(arg,invalid_ch,pred,p_path,f,b1,b2,BA_terNo):
for ch in arg.children:
if ch != invalid_ch:
if ch.data == b1 or ch.data == b2 and f == False:
#print ch.data
#print ch.terNo
#print n
f = True
BA_terNo = ch.terNo
path_node = 'd'+ch.data.rstrip() # 'd' to denote upward direction
p_path.append(path_node)
#p_path.append(ch.data)
break
elif f == False:
#f = False
#print ch.data
path_node = 'd'+ch.data.rstrip() # 'd' to denote upward direction
p_path.append(path_node)
#p_path.append(ch.data)
#print p_path
(p_path,f,BA_terNo) = find_BA(ch,'',pred,p_path,f,b1,b2,BA_terNo)
else:
continue
if f == False:
p_path = p_path[0:-1]
return (p_path,f,BA_terNo)
'''def convert_trees(file_id):
penn_tree_file = open(file_id,"r")
penn_trees = penn_tree_file.read()
tokens = list(penn_trees)
c = 0
trees = []
tree = []
for t in tokens:
if t == '(':
c = c + 1
tree.append(t)
#print tree
elif t == ')':
c = c - 1
if c == 0:
tree.append(t)
trees.append(''.join(tree[2:-1]))
tree = []
continue
else:
tree.append(t)
elif t == '\n':
continue
else:
tree.append(t)
return trees
'''
def convert_trees(file_id):
penn_tree_file = open(file_id,"r")
penn_trees = penn_tree_file.read()
#m=re.compile('<S ID=\d+>(.*?)</S>', re.DOTALL).findall(penn_trees)
m=re.compile('<S ID=\d+[abc]*>(.*?)</S>', re.DOTALL).findall(penn_trees)
mm = make_tree_list(''.join(m),[])
return mm
def make_tree_list(str,list_trees):
expr = list(str)
c = 0
buffer = []
#children = []
for tk in expr:
if tk == '(':
c = c + 1
buffer.append(tk)
elif tk == ')':
c = c - 1
buffer.append(tk)
if c == 0:
list_trees.append((''.join(buffer)).lstrip())
buffer = []
continue
elif tk == '\t' or tk == '\n':
continue
else:
buffer.append(tk)
#list_trees.append(''.join(buffer))
return list_trees
def make_train_test():
data = open('cpb1.0.txt')
for t in data.readlines():
file_no = t.split(' ')[0].split('/')[-1].split('_')[1].split('.')[0]
if int(file_no) > 80 and int(file_no) < 900:
#if (int(file_no) > 0 and int(file_no) < 41) or (int(file_no) > 899 and int(file_no) < 932):
print t.rstrip()
def dev_train_test():
data = open('cpb1.0.txt')
for t in data.readlines():
file_no = t.split(' ')[0].split('/')[-1].split('_')[1].split('.')[0]
#if int(file_no) > 40 and int(file_no) < 71:
if (int(file_no) > 70 and int(file_no) < 81):
print t.rstrip()
def test_cpb2():
data = open('./cpb2/data/verbs.txt.gbk')
for t in data.readlines():
file_no = t.split(' ')[0].split('_')[1].split('.')[0]
#testing
if (int(file_no) > 0 and int(file_no) < 81) or (int(file_no) > 1140 and int(file_no) < 1151):
print t.rstrip()
def train_cpb2():
data = open('./cpb2/data/verbs.txt.gbk')
for t in data.readlines():
file_no = t.split(' ')[0].split('_')[1].split('.')[0]
#training
if (int(file_no) > 80 and int(file_no) < 1110):
print t.rstrip()
if __name__ == "__main__":
import sys
try:
'''trees = convert_trees('./bracketed/chtb_001.fid')
for t in trees[0:1]:
(parsed,r) = parseExpr(t,0,0)
#traverse_tree(parsed,16)
traverse_tree_depth(parsed,8,0)
#print t
#print parsed
#print '''
#make_train_test()
#dev_train_test()
#train_cpb2()
test_cpb2()
except:
print >>sys.stderr, __doc__
raise |
1aa119f0896b708cbfb0eb04268b9087dfa2b44a | noahfp/Project_Euler | /p004.py | 365 | 3.875 | 4 | def is_palindrome(x):
x = str(x)
if x == x[::-1]:
return True
else:
return False
def large_palindrome(cap):
for i in range(cap):
for j in range(i):
val = (cap-j)*(cap-i+j)
if is_palindrome(val):
return val
return -1
print large_palindrome(int(raw_input("")))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.