blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fea6f1c04b8693eea7fa413cbe9d4f53fabf7d9c | joelhrobinson/Python_Code | /Create_file.py | 572 | 3.5 | 4 | ### Change the working directory so can use local files
import os ## import os operating sytem library
os.getcwd()
os.chdir ("L:/SOFTWARE/PYTHON/TEMP")
os.getcwd()
############################################################################
f = open("joel-created-by-python.txt","w+")
## f = open("joel02.txt","w+")
## f = open("joel03txt","w+")
for i in range(10):
f.write("Hello world %d" % (i+1))
f.close()
print ("done")
## with open("TestAnalysisData.csv") as csv_file:
## file_reader = csv.reader(csv_file)
## print (file_reader)
|
a2b1d9892942dd8997511fb161f66151a3912e9e | langtaosha1/CodeSet | /group7/palindromic.py | 368 | 3.6875 | 4 | try:
str = input('输入任意5位数:')
if len(str) > 5:
print('输入数字长度错误!')
else:
if str[0] == str[4] and str[1] == str[3]:
print('这是一个回文数!')
else:
print('这不是一个回文数,请重新输入!')
except ValueError:
print('输入类型错误,请重新输入!')
|
3ede9ea2c06c134a572029dcaa7079efaa5e7ac9 | apolanco18/CS334 | /HW2/f.py | 235 | 3.609375 | 4 | import pandas as pd
def main():
x,y = list((4,4,4,5)), list();
y.append(2)
print(max(set(x), key=lambda f: x.count(f)))
print(x)
for i in range(5,35,5):
print(i)
if __name__ == "__main__":
main() |
ca2e95482e2fcec8fec680061b19e11f1e07cbec | neilmarshall/html_snippets | /flask_login_example/mysql/create_dataset_for_bulk_upload.py | 616 | 3.625 | 4 | #! venv/bin/python3.7
import csv
import sqlite3
def main():
with sqlite3.connect('app/comic_book_characters.db') as connection:
connection.execute('''CREATE TEMP VIEW IF NOT EXISTS combined AS SELECT * FROM DC UNION SELECT * FROM Marvel;''')
data = connection.execute('''SELECT hero_name, ID, ALIGN, GSM, SEX, EYE, HAIR, ALIVE, APPEARANCES FROM COMBINED ORDER BY hero_name;''')
with open('mysql/comic_book_characters.txt', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for row in data:
writer.writerow(row)
if __name__ == '__main__':
main()
|
1fa996e1384fd0e3b55cf55a714de61d4cd40986 | RafaRlv/CalculadoraPy | /Calculadora.py | 4,191 | 3.59375 | 4 | from tkinter import *
from math import *
import sys
class Calculadora:
def __init__(self, toplevel):
# Janela
toplevel.title('Calculadora')
toplevel.geometry("240x200")
# Espaçamento
self.frame1 = Frame(toplevel)
self.frame1.pack()
# Box 1
self.frame2 = Frame(toplevel)
self.frame2.pack()
# Box 2
self.frame3 = Frame(toplevel)
self.frame3.pack()
# Operações
self.frame4 = Frame(toplevel, pady=12)
self.frame4.pack()
# Resultado
self.frame5 = Frame(toplevel)
self.frame5.pack()
# Botões
self.frame6 = Frame(toplevel, pady=12)
self.frame6.pack()
# Cor e tamanho das letras
Label(self.frame1,text='', fg='black',
font=('Verdana','10'), height=1).pack()
fonte1=('Verdana','10')
# Botão somar
somar=Button(self.frame4,font=fonte1, text='+',command=self.somar)
somar.pack(side=LEFT)
# Botão subtrair
subtrair=Button(self.frame4,font=fonte1, text='-',command=self.subtrair)
subtrair.pack(side=LEFT)
# Botão multiplicar
multiplicar=Button(self.frame4,font=fonte1, text='*',command=self.multiplicar)
multiplicar.pack(side=LEFT)
# Botão dividir
dividir=Button(self.frame4,font=fonte1, text='/',command=self.dividir)
dividir.pack(side=LEFT)
# Botão raiz
raiz=Button(self.frame4,font=fonte1, text='Sqrt',command=self.sqrt)
raiz.pack(side=LEFT)
# Botão Limpar
limpar=Button(self.frame6, font=fonte1, text= 'Limpar', command=self.limpar)
limpar.pack(side=LEFT)
# Botão Sair
sair=Button(self.frame6, font=fonte1, text= 'Sair', command=self.sair)
sair.pack(side=LEFT)
# Box 1 para entrada de número
Label(self.frame2,text='Valor1 :', font=fonte1,width=8).pack(side=LEFT)
self.valor1=Entry(self.frame2,width=10,font=fonte1)
self.valor1.focus_force()
self.valor1.pack(side=LEFT)
# Box 2 para entrada de número
Label(self.frame3,text='Valor2 :',font=fonte1,width=8).pack(side=LEFT)
self.valor2=Entry(self.frame3,width=10,font=fonte1)
self.valor2.pack(side=LEFT)
# Resultado
Label(self.frame5,text=' = ',font=fonte1,width=8).pack(side=LEFT)
self.msg=Label(self.frame5,width=10,font=fonte1)
self.msg.pack(side=LEFT)
def somar(self):
valor1 = self.valor1.get()
valor2 = self.valor2.get()
valor1 = float(valor1)
valor2 = float(valor2)
c = valor1 + valor2
c = float(c)
self.msg['text']= '%.2f' %(c)
def subtrair(self):
valor1 = self.valor1.get()
valor2 = self.valor2.get()
valor1 = float(valor1)
valor2 = float(valor2)
c = valor1 - valor2
c = float(c)
self.msg['text']= '%.2f' %(c)
def multiplicar(self):
valor1 = self.valor1.get()
valor2 = self.valor2.get()
valor1 = float(valor1)
valor2 = float(valor2)
c = valor1 * valor2
c = float(c)
self.msg['text']= '%.2f' %(c)
def dividir(self):
valor1 = self.valor1.get()
valor2 = self.valor2.get()
valor1 = float(valor1)
valor2 = float(valor2)
c = valor1 / valor2
c = float(c)
self.msg['text']= '%.2f' %(c)
def sqrt(self):
try:
valor1 = self.valor1.get()
valor1 = float(valor1)
c = sqrt(valor1)
c = float(c)
self.msg['text']= '%.2f' %(c)
except:
valor2 = self.valor2.get()
valor2 = float(valor2)
c = sqrt(valor2)
c = float(c)
self.msg['text']= '%.2f' %(c)
def limpar(self):
pass
def sair(self):
app.destroy()
app=Tk()
Calculadora(app)
app.mainloop()
|
31377c4b29a8099782167fbaa49a0684683c15eb | ban-do/Dokugaku_programer | /04_class_lesson/Orange.py | 272 | 3.546875 | 4 |
class Orange:
def __init__(self, w, c):
self.weight = w
self.color = c
self.mold = 0
print("Created!!")
def rot(self,days,temp):
self.mold = days * temp
or1 = Orange(10,"dark")
print(or1)
or1.rot(10,37)
print(or1.mold)
|
20fc933e71c3b69ebb9b2e9fa09166e3c8c514ce | zharfanf/Algorithm | /Sorting/quicksort.py | 463 | 4 | 4 | def partitioning(arr,start,end):
i = start-1
j = start
pivot = arr[end-1]
while j < end-1:
if arr[j] < pivot:
i += 1
arr[i],arr[j] = arr[j],arr[i] #swap element
j += 1
p = i + 1
arr[p],arr[end-1] = arr[end-1],arr[p] #swap pivot and element on i+1
return p
def quicksort(arr,start,end):
if start >= end: # return nothing
return
examine = partitioning(arr,start,end)
quicksort(arr,start,examine)
quicksort(arr,examine+1,end)
return arr
|
e45a85ec4a5f7053ea5a372f4e19099384eaf5a1 | mag-id/epam_python_autumn_2020 | /homework_4/tasks/task_1.py | 1,821 | 3.953125 | 4 | """
Write a function that gets file path as an argument.
Read the first line of the file.
If first line is a number return true if number in an interval [1, 3)*
and false otherwise.
In case of any error, a ValueError should be thrown.
Write a test for that function using pytest library.
Definition of done:
- function is created
- function is properly formatted
- function has positive and negative tests
- all temporary files are removed after test run
You will learn:
- how to test Exceptional cases
- how to clean up after tests
- how to check if file exists**
- how to handle*** and raise**** exceptions in test. Use sample from the documentation.
* https://en.wikipedia.org/wiki/Interval_(mathematics)#Terminology
** https://docs.python.org/3/library/os.path.html
*** https://docs.python.org/3/tutorial/errors.html#handling-exceptions
**** https://docs.python.org/3/tutorial/errors.html#raising-exceptions
"""
from os import F_OK, R_OK, access
NOT_EXIST = "Path is not exists."
NOT_READABLE = "Path is not readable."
def read_magic_number(path: str) -> bool:
"""
Returns `True` if first line of file in `path` is
number where in range 1 <= number < 3 else `False`.
Exceptions:
-----------
+ If the file does not exist then `ValueError(Path does not exist.)` raises.
+ If the file is not readable then `ValueError(Path is not readable.)` raises.
"""
if not access(path, F_OK):
raise ValueError(NOT_EXIST)
if not access(path, R_OK):
raise ValueError(NOT_READABLE)
with open(file=path, mode="tr", encoding="utf-8") as file:
first_line = file.readline().strip()
prepared = first_line.replace(",", ".", 1)
replased = prepared.replace(".", "", 1)
return replased.isdigit() and (1.0 <= float(prepared) < 3.0)
|
ed3e99830f95377502dbc0fad44a56b23ae72d28 | BugHunters-bug/AlgorithmBank | /important algo related problems/sort_an_array_0_1_2.py | 829 | 3.5625 | 4 | #User function Template for python3
class Solution:
def sort012(self,arr,n):
low,mid,high=0,0,n-1
while mid<=high:
if arr[mid]==0:
arr[low],arr[mid]=arr[mid],arr[low]
low+=1
mid+=1
elif arr[mid]==1:
mid+=1
elif arr[mid]==2:
arr[high],arr[mid]=arr[mid],arr[high]
high-=1
# code here
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t=int(input())
for _ in range(t):
n=int(input())
arr=[int(x) for x in input().strip().split()]
ob=Solution()
ob.sort012(arr,n)
for i in arr:
print(i, end=' ')
print()
# } Driver Code Ends |
5d5e053b1eeb85745defbb776ac86e6065bb512d | surajgholap/python-Misc | /DP_sum.py | 338 | 3.78125 | 4 | def sum_134(n):
"Return num of ways n can be represented as a sum of 1, 3, 4."
sum_num = []
for i in range(3):
sum_num.append(1)
sum_num.append(2)
for i in range(4, n+1):
sum_num.append(sum_num[i-1] + sum_num[i-3] + sum_num[i-4])
return sum_num[n]
if __name__ == "__main__":
print(sum_134(3))
|
0998fa5b9ed46b60857f0527c6f3b51fd781521f | yifanbao/590PZ-Project | /generate_maze.py | 10,470 | 3.75 | 4 | """
Generate Maze
"""
import random
from copy import deepcopy
import numpy as np
import matplotlib.pyplot as pyplot
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
class Maze:
__marks = {
'aisle': 0,
'solution': 0.4,
'key': 0.5,
'door': 0.55,
'portal': 0.6,
'portal_solution': 0.65,
'start': 0.8,
'end': 0.9,
'wall': 1,
}
def __init__(self, mode='easy', num_rows=31, num_columns=41, complexity=0.5, num_portals=0, has_key=False):
# set up board size and difficulty
self.M = num_rows
self.N = num_columns
self.complexity = complexity
self.num_portals = num_portals
self.has_key = has_key
if mode == 'easy':
self.M = 31
self.N = 41
self.complexity = 0.6
self.num_portals = 0
self.has_key = True
elif mode == 'median':
self.M = 41
self.N = 61
self.complexity = 0.65
self.num_portals = 1
self.has_key = False
elif mode == 'hard':
self.M = 61
self.N = 81
self.complexity = 0.8
self.num_portals = 1
self.has_key = True
else:
if type(num_rows) != int or num_rows % 2 == 0 or num_rows <= 0:
raise ValueError("Oops, the number of rows should be positive odd number")
if type(num_columns) != int or num_columns % 2 == 0 or num_columns <= 0:
raise ValueError("Oops, the number of columns should be positive odd number")
if type(complexity) != float or complexity <= 0 or complexity >= 1:
raise ValueError("Oops, the complexity should be more than 0 and less than 1")
if type(num_portals) != int or num_portals < 0:
raise ValueError("Oops, the number of portals should be non-negative integer")
if type(has_key) != bool:
raise ValueError("Oops, the has_key parameter should be a boolean")
# initialize board
self.board = [[Maze.__marks['wall'] for _ in range(self.N)] for _ in range(self.M)]
self.solution_length = int(self.complexity * self.M * self.N / 8)
self.solution = []
self.start_point = None
self.end_point = None
self.portals = {}
self.keys = []
sequence = ['portal'] * self.num_portals
if self.has_key:
sequence += ['key']
random.shuffle(sequence)
sequence += ['end']
self.generate_board(sequence)
@staticmethod
def get_marks():
return Maze.__marks
def generate_board(self, sequence: list):
# randomly choose a start point on the outer border
self.start_point = random.choice([
(0, random.randint(0, (self.N - 2) // 2) * 2 + 1),
(self.M - 1, random.randint(0, (self.N - 2) // 2) * 2 + 1),
(random.randint(0, (self.M - 2) // 2) * 2 + 1, 0),
(random.randint(0, (self.M - 2) // 2) * 2 + 1, self.N - 1)
])
marks = Maze.__marks
# generate solution according to the sequence
start_point = self.start_point
path_contain_key = False
for i, item in enumerate(sequence):
if item == 'key':
path_contain_key = True
continue
max_length = (self.solution_length - len(self.solution)) / (len(sequence) - i)
end_point = self.generate_path(start_point, is_solution=True, max_length=max_length)
# add a pair of portals
if item == 'portal':
self.board[end_point[0]][end_point[1]] = marks['portal_solution']
start_point = (
random.randint(0, (self.M - 2) // 2) * 2 + 1,
random.randint(0, (self.N - 2) // 2) * 2 + 1
)
while self.board[start_point[0]][start_point[1]] != marks['wall']:
start_point = (
random.randint(0, (self.M - 2) // 2) * 2 + 1,
random.randint(0, (self.N - 2) // 2) * 2 + 1
)
self.portals[end_point] = start_point
self.portals[start_point] = end_point
elif item == 'end':
self.end_point = end_point
if path_contain_key:
len_key_to_end = int(max_length // 2)
m, n = self.solution[-len_key_to_end]
self.board[m][n] = marks['key']
self.keys.append((m, n))
path_contain_key = False
# mark special items on the board
self.board[self.start_point[0]][self.start_point[1]] = marks['start']
self.board[self.end_point[0]][self.end_point[1]] = marks['end']
for m, n in self.portals:
self.board[m][n] = marks['portal_solution']
# generate branches from the solution path
num_branches = int(len(self.solution) * self.complexity / 4)
count_branches = 0
branch_start_points = self.solution.copy()
random.shuffle(branch_start_points)
while count_branches < num_branches and len(branch_start_points):
m, n = branch_start_points.pop()
end = self.generate_path((m, n))
if end != (-1, -1):
count_branches += 1
# fill the board
for m in range(1, self.M - 1, 2):
for n in range(1, self.N - 1, 2):
if self.board[m][n] == marks['wall']:
self.generate_path((m, n), avoid_visited=False, max_length=self.solution_length, min_length=1)
def generate_path(self, start_point: tuple, is_solution=False, avoid_visited=True, max_length=None, min_length=None) -> tuple:
marks = Maze.__marks
# reset if do not meet min length requirement
initial_board = deepcopy(self.board)
initial_solution = self.solution.copy()
# set up default parameters
if is_solution:
max_length = max_length or self.solution_length
min_length = min_length or int(max_length * 0.75)
target_mark = marks['solution']
forbidden_depth = 3
else:
max_length = max_length or int(self.solution_length * self.complexity / 3)
min_length = min_length or int(max_length * 0.4)
target_mark = marks['aisle']
forbidden_depth = 1
forbidden_mark = set()
if avoid_visited:
for item in marks:
if item != 'wall':
forbidden_mark.add(marks[item])
m, n = start_point
curt_length = 0
curt_path = set()
# move one cell first if start from a border
if start_point == self.start_point:
self.board[m][n] = target_mark
if m == 0:
m += 1
elif m == self.M - 1:
m -= 1
elif n == 0:
n += 1
else:
n -= 1
# generate path
# move one step (two cells) each time, until meeting max length or no allowed movement
while curt_length < max_length:
# mark current cell
if self.board[m][n] == marks['wall']:
self.board[m][n] = target_mark
curt_length += 1
curt_path.add((m, n))
if is_solution:
self.solution.append((m, n))
# get neighbors
neighbors = self.get_neighbors_coordinates(m, n, curt_path, forbidden_mark, forbidden_depth)
if not len(neighbors):
break
# choose a neighbor and break the wall in-between
m_, n_ = random.choice(neighbors)
self.board[(m + m_) // 2][(n + n_) // 2] = target_mark
# if the neighbor is a wall, replicate the above operations for the neighbor
if self.board[m_][n_] == marks['wall']:
m, n = m_, n_
# otherwise, update forbidden marks and find another neighbor for the current cell
else:
for item in marks:
if item != 'wall':
forbidden_mark.add(marks[item])
if self.board[m][n] == marks['wall']:
self.board[m][n] = target_mark
# reset if do not meet min length requirement
if curt_length < min_length:
self.board = initial_board
self.solution = initial_solution
if is_solution:
m, n = self.generate_path(start_point, is_solution, avoid_visited, max_length, min_length - 1)
else:
return -1, -1
# return the coordinate of the last cell in current path
return m, n
def get_neighbors_coordinates(self, m: int, n: int, forbidden_cell=None, forbidden_mark=None, forbidden_depth=1) -> list:
# set up default parameters
if forbidden_cell is None:
forbidden_cell = set()
if forbidden_mark is None:
forbidden_mark = set()
# find neighbors with a step of 2
neighbors = []
for m_, n_ in [(m - 2, n), (m + 2, n), (m, n - 2), (m, n + 2)]:
# skip invalid neighbors
if not 0 < m_ < self.M or not 0 < n_ < self.N:
continue
if (m_, n_) in forbidden_cell:
continue
if forbidden_depth > 0 and self.board[m_][n_] in forbidden_mark:
continue
if forbidden_depth > 1 and not len(self.get_neighbors_coordinates(m_, n_, forbidden_cell, forbidden_mark, forbidden_depth - 1)):
continue
neighbors.append((m_, n_))
return neighbors
def print(self, show_solution=False):
figure = pyplot.figure(figsize=(10, 5))
viridis = pyplot.cm.get_cmap('viridis', 256)
new_colors = viridis(np.linspace(0, 1, 256))
pink = np.array([248 / 256, 24 / 256, 148 / 256, 1])
new_colors[:25, :] = pink
new_cmp = ListedColormap(new_colors)
# pyplot.imshow(self.board, cmap=new_cmp, interpolation='nearest')
pyplot.imshow(self.board, cmap=pyplot.cm.get_cmap('viridis_r', 256), interpolation='nearest')
pyplot.xticks([]), pyplot.yticks([])
figure.show()
if __name__ == '__main__':
maze = Maze()
maze.print()
|
5284a3a0d8860f18bc652291aba8189d08d79f9f | arnottrcaiado/curso-python-senac | /aula1/aula1-ex15.py | 538 | 3.8125 | 4 | # aula1 - ex 15 - Arnott Ramos Caiado
# calculo de salario
valor_hora = float(input("\n Quanto vc ganha por hora? "))
horas_trabalhadas = int(input("\n Quantas horas vc trabalhou no mes? "))
salario_bruto = valor_hora * horas_trabalhadas
inss = 0.08 * salario_bruto
ir = 0.11 * salario_bruto
sindicato = 0.05 * salario_bruto
print("\n +Salario Bruto: ", salario_bruto)
print("\n - IR (11%) : ", ir)
print("\n - INSS (8%) : ", inss)
print("\n - Sindicato (5%) : ", sindicato)
print("\n = Salario Liquido : ", salario_bruto - inss - ir - sindicato )
|
1c18bd43933cd9f7a88e8e70e3fac6052531c629 | natepill/problem-solving | /LeetCode/add_two_nums.py | 2,894 | 4 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
l1_curr = l1
l2_curr = l2
answer_node_curr = None
answer_node_head = None
carry_over = False
while l1_curr is not None and l2_curr is not None:
# print("l1 curr: " + str(l1_curr.val))
# print("l2 curr: " + str(l2_curr.val))
base_sum = l1_curr.val + l2_curr.val
# Carry over is always going to add one if indicated by carry over flag
node_sum = base_sum if carry_over == False else base_sum + 1
# print(node_sum)
# Sum is larger than 9 implies carry over
if node_sum > 9:
# First iteration to set appropriate values
if answer_node_curr is None:
# mod 10 gets us the remainder of what doesn't need to be carried over
answer_node_curr = ListNode(node_sum%10)
# We need to track the head node of our answer list because there is no LL class
answer_node_head = answer_node_curr
else:
answer_node_curr.next = ListNode(node_sum%10)
# Carry over to be done next iteration
carry_over = True
# Sum is less than 9 implies NO carry over
else:
if answer_node_curr is None:
answer_node_curr = ListNode(node_sum)
answer_node_head = answer_node_curr
else:
answer_node_curr.next = ListNode(node_sum)
print(node_sum)
# No carry over to be done next iteration
carry_over = False
# Traverse both LL
# No more addition
if l1_curr.next is None and l2_curr.next is None:
break
# both lists can be traversed
elif l1_curr.next is not None and l2_curr.next is not None:
l1_curr = l1_curr.next
l2_curr = l2_curr.next
# list 1 is longer than list 2
elif l1_curr.next is not None and l2_curr.next is None:
l1_curr = l1_curr.next
l2_curr.next = ListNode(0)
l2_curr = l2_curr.next
# list 1 is shorter than list 2
elif l1_curr.next is None and l2_curr.next is not None:
l1_curr.next = ListNode(0)
l1_curr = l1_curr.next
l2_curr = l2_curr.next
return answer_node_head
def print_ll(head_node):
node = head_node
value = ''
while node is not None:
value += str(node.val)
node = node.next
return value
if __name__ == "__main__":
l1 = ListNode(2)
l1a = ListNode(3)
l1.next = l1a
l1a.next = ListNode(6)
l2 = ListNode(5)
l2a = ListNode(3)
l2.next = l2a
l2a.next = ListNode(7)
answer_node = addTwoNumbers(l1, l2)
print(print_ll(answer_node))
|
7712c40c660dacfe1c70f66d8360f9c555e3da27 | Bonnieliuliu/LeetCodePlayGround | /Companies/KickStart/PlanetDistance/PlanetDistance.py | 3,699 | 3.828125 | 4 | # -*- coding:utf-8 -*-
"""
author:Bonnieliuliu
email:fangyuanliu@pku.edu.cn
file: PlanetDistance.py
time: 2018/11/18 11:52
"""
from collections import defaultdict
# This class represents a undirected graph using adjacency list representation
class Graph:
def __init__(self, vertices, dis, res):
self.V = vertices # No. of vertices
self.distance = dis
self.res = res
self.graph = defaultdict(list) # default dictionary to store graph
# function to add an edge to graph
def addEdge(self, v, w):
self.graph[v].append(w) # Add w to v_s list
self.graph[w].append(v) # Add v to w_s list
# A recursive function that uses visited[] and parent to detect
# cycle in subgraph reachable from vertex v.
def isCyclicUtil(self, v, visited, parent):
# Mark the current node as visited
visited[v] = True
# Recur for all the vertices adjacent to this vertex
for i in self.graph[v]:
# If the node is not visited then recurse on it
if visited[i] == False:
if (self.isCyclicUtil(i, visited, v)):
return True
# If an adjacent vertex is visited and not parent of current vertex,
# then there is a cycle
elif parent != i:
self.res.append(v)
return True
return False
# Returns true if the graph contains a cycle, else false.
def isCyclic(self):
# Mark all the vertices as not visited
visited = [False] * (self.V + 1)
# Call the recursive helper function to detect cycle in different
# DFS trees
for i in range(1, self.V + 1):
if visited[i] == False: # Don't recur for u if it is already visited
if (self.isCyclicUtil(i, visited, -1)) == True:
return True
return False
def judge(self, u, v):
visited = [False] * (self.V + 1)
distance = [0 for i in range(self.V + 1)]
queue = []
queue.append(u)
visited[u] = True
while queue:
x = queue.pop(0)
for i in self.graph[x]:
if visited[i] == False:
distance[i] = distance[x] + 1
queue.append(i)
visited[i] = True
return distance[v]
def count_dis(self):
cycle_list = []
for i in self.graph[self.res[0]]:
cycle_list.append(i)
cycle_list.append(self.res[0])
visited = [False] * (self.V + 1)
for i in range(1, self.V + 1):
if i in cycle_list:
self.distance[i] = 0
else:
len_min = self.V + 1
for j in cycle_list:
tem_min = self.judge(i, j)
if tem_min < len_min:
len_min = tem_min
self.distance[i] = len_min
if __name__ == '__main__':
# input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Kickstart problems.
t = int(input()) # read a line with a single integer
for ti in range(1, t + 1):
n = int(input())
dis = [0 for i in range(n + 1)]
res = []
g = Graph(n, dis, res)
for i in range(n):
n, m = [int(s) for s in input().split(" ")]
g.addEdge(n, m)
if g.isCyclic():
g.count_dis()
print("Case #{0}:".format(ti), end='')
for x in dis[1:]:
print(' ',x, end='')
print('\n', end='')
# check out .format's specification for more formatting options |
e919b4e56ff0d23e592e01ac4066a1d7e7cb3908 | MKarolis/address-classification-ai | /prepare.py | 5,183 | 3.5625 | 4 | import pandas as pd
import re
from utils import read_DataFrame_from_excel, write_DataFrame_to_excel
DATA_INPUT_FILENAME = 'raw_data.xlsx'
DATA_OUTPUT_FILENAME = 'training_data.xlsx'
NUMBER_OF_PARSABLE_RECORDS = 999
PROPERTY_LABEL = 'label'
PROPERTY_ADDRESS = 'address'
PROPERTY_LENGTH = 'length'
PROPERTY_DIGITS_COUNT = 'digit_count'
PROPERTY_DIGITS_GROUP_COUNT = 'digits_group_count'
PROPERTY_SEPARATED_DIGIT_GROUP_COUNT = 'separated_digits_group_count'
PROPERTY_TOKEN_COUNT = 'token_count'
PROPERTY_COMMA_COUNT = 'comma_count'
PROPERTY_COMMA_SEPARATED_ENTITIES_HAVING_DIGITS = 'comma_separated_entities_having_numbers'
PROPERTY_COMMA_SEPARATED_ENTITIES_HAVING_DIGITS_NEAR_WORDS = 'comma_separated_entities_having_numbers_near_words'
# Gets the length of address
def getAddressLength(address: str):
"""
Gets the length of address.
Args:
address (str): address
Returns:
length: of the address
"""
return len(address)
# Counts digits within an address
def getDigitsCount(address: str):
"""
Counts digits within an address.
Args:
address (str): address
Returns:
digitsCount: within an address
"""
return len(re.findall(r'\d', address))
# Count how many groups of consecutive digits are there
def getDigitGroupCount(address: str):
"""
Count how many groups of consecutive digits are there.
Args:
address (str): address
Returns:
digitGroupCount: within an address
"""
return len(re.findall(r'(\d+)', address))
# Count how many separated groups of consecutive numbers are there, for instance, (1-123, 124 565, 12/27)
def getSeparatedDigitGroupCount(address: str):
"""
Count how many separated groups of consecutive numbers are there, for instance, (1-123, 124 565, 12/27).
Args:
address (str): address
Returns:
separatedDigitGroupCount: within an address
"""
return len(re.findall(r'(\d+)[^\d,](\d+)', address))
# Count the number of tokens, separated by spaces or commas
def getTokenCount(address: str):
"""
Count the number of tokens, separated by spaces or commas.
Args:
address (str): address
Returns:
tokenCount: within an address
"""
return len(re.findall(r'([^\s,]+)', address))
# Counts the number of commas
def getCommaCount(address: str):
"""
Counts the number of commas.
Args:
address (str): address
Returns:
commaCount: within an address
"""
return len(re.findall(r',', address))
# Counts number of comma separated entities, having a number within them
def getCommaSeparatedEntityWithNumbersCount(address: str):
"""
Counts number of comma separated entities, having a number within them.
Args:
address (str): address
Returns:
commaSeparatedEntityWithNumbersCount: within an address
"""
return len(re.findall(r'[^,]*\d+[^,]*', address))
# Counts number of comma separated entities, having a number and a separated word:
def getCommaSeparatedEntityWithNumbersNearWordsCount(address: str):
"""
Counts number of comma separated entities, having a number and a separated word.
Args:
address (str): address
Returns:
commaSeparatedEntityWithNumbersCount: within an address
"""
return len(re.findall(r'([a-zA-Z]{3,})\s(\w+-)?\d+(-\w+)?|(\w+-)?\d+(-\w+)?\s([a-zA-Z]{3,})[^,]*', address))
def enrichDataFrameWithProperties(frame: pd.DataFrame):
"""
Enrichs a dataframe with derivate features like length, token count, etc...
Args:
frame (pd.DataFrame): dataframe to be enrichen
"""
assignProperty(frame, PROPERTY_LENGTH, getAddressLength)
assignProperty(frame, PROPERTY_DIGITS_COUNT, getDigitsCount)
assignProperty(frame, PROPERTY_DIGITS_GROUP_COUNT, getDigitGroupCount)
assignProperty(frame, PROPERTY_SEPARATED_DIGIT_GROUP_COUNT, getSeparatedDigitGroupCount)
assignProperty(frame, PROPERTY_TOKEN_COUNT, getTokenCount)
assignProperty(frame, PROPERTY_COMMA_COUNT, getCommaCount)
assignProperty(frame, PROPERTY_COMMA_SEPARATED_ENTITIES_HAVING_DIGITS, getCommaSeparatedEntityWithNumbersCount)
assignProperty(frame, PROPERTY_COMMA_SEPARATED_ENTITIES_HAVING_DIGITS_NEAR_WORDS, getCommaSeparatedEntityWithNumbersNearWordsCount)
def assignProperty(dataFrame: pd.DataFrame, property: str, fun: callable):
"""
Derivate a feature and assign it to a dataframe as a column
Args:
dataFrame (pd.DataFrame): dataframe to be assign a feature
property (str) : feature to assign to the dataframe
fun (callable): function responsible to derivate the feature
"""
dataFrame[property] = dataFrame.apply(lambda row: fun(row[PROPERTY_ADDRESS]), axis=1)
if __name__ == '__main__':
rawData = read_DataFrame_from_excel(DATA_INPUT_FILENAME, NUMBER_OF_PARSABLE_RECORDS)
parsedData = pd.DataFrame()
parsedData[PROPERTY_ADDRESS] = rawData['person_address']
enrichDataFrameWithProperties(parsedData)
parsedData[PROPERTY_LABEL] = rawData['label']
write_DataFrame_to_excel(parsedData, DATA_OUTPUT_FILENAME) |
5b1b33c0a3ae8931765915408b858b37bb64d631 | happyandy2017/LeetCode | /Largest Number At Least Twice of Others.py | 949 | 3.6875 | 4 | class Solution:
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 1. find the largest num: num_largest, index_largest
num_largest = max(nums)
index_largest = nums.index(num_largest)
# num_largest = -1
# index_largest = -1
# i = 0
# for num in nums:
# if num > num_largest:
# index_largest = i
# num_largest = num
# i += 1
# 2. iterate nums, check whether num_largest is at least twice as much as every other number in the array
i = 0
for num in nums:
if num == num_largest:
i += 1
continue
if num*2 > num_largest:
return -1
i += 1
return index_largest
solution = Solution()
print(solution.dominantIndex([0,0,3,2])) |
67fcfafc07f4a04a1a48bdd2a6306038e3dc01f8 | RosezClassrooms/final-group-assignment-team-ieq | /UniversityFaculty.py | 2,421 | 4.03125 | 4 | # CS342 Final Project #1
# Ezgi Cakir
# Composite Design Pattern for various departments/faculties in a university
from abc import ABC, abstractmethod
class Department(ABC):
def __init__(self):
pass
@abstractmethod
def make_announcements(self):
pass
@abstractmethod
def create_syllabus(self):
pass
class ComputerScience(Department):
def __init__(self, update, num_course):
self.update = update
self.num_course = num_course
def make_announcements(self):
print("The Computer Science Department announces that " + self.update)
def create_syllabus(self):
print("The Computer Science Department currently has " + str(self.num_course) + " various courses to pick from!")
return self.num_course
class MechanicalEngineering(Department):
def __init__(self, update, num_course):
self.update = update
self.num_course = num_course
def make_announcements(self):
print("The Mechanical Engineering Department announces that " + self.update)
def create_syllabus(self):
print("The Mechanical Engineering Department currently has " + str(self.num_course) + " various courses to pick from!")
return self.num_course
class University(Department):
def __init__(self):
self.departments = []
def make_announcements(self):
print("The Binghamton University currently has " + str(len(self.departments)) + " number of departments.")
for dpt in self.departments:
dpt.make_announcements()
def create_syllabus(self):
total = 0
for dpt in self.departments:
total += dpt.create_syllabus()
print("Binghamton University has " + str(total) + " number of courses to assist its students.")
def add_department(self, dpt):
self.departments.append(dpt)
def remove_department(self, dpt):
self.departments.remove(dpt)
def main():
computer_science = ComputerScience("due to COVID-19, the classes will be online for two weeks mandatorily.", 48)
mechanical_eng = MechanicalEngineering("the examination period will be extended 3 more days.", 52)
university = University()
university.add_department(computer_science)
university.add_department(mechanical_eng)
university.make_announcements()
university.create_syllabus()
if __name__ == "__main__":
main()
|
e2aed4d6f6e3c08357b480497a3a5033eb68627d | hakuya0421/python-example | /bmi.py | 236 | 3.90625 | 4 | height = input('키를 입력하세요 (cm) : ')
weight = input('몸무게를 입력하세요(kg) : ')
height = int(height)
weight = float(weight)
BMI = weight / height ** 2 * 10000
print('당신의 BMI 지수는 : {:.2f} '.format(BMI)) |
f640390c74bcbb47de7b424d74ad16305f2aabb5 | NeerajChhabra/GoogleMaps_bus | /task2.py | 1,058 | 3.578125 | 4 | import csv
import sys
import googlemaps
from datetime import datetime
gmaps = googlemaps.Client(key='AIzaSyCxv_9IXZmugxkUEKwQ5-u8Wo7hLe-_2AE')
source=input("Enter the Source bus stop number = ")
def get_lat_long(stop):
csv_file = csv.reader(open('Bus_Stops.csv', "rt"))
for row in csv_file:
if stop == row[4]:
x=float(row[1])
y=float(row[0])
lat=("{:.6f}".format(x))
long=("{:.6f}".format(y))
li=[lat,long]
return(li)
s_li=get_lat_long(source)
s_lat=s_li[0]
s_long=s_li[1]
dest=input("Enter the destination bus stop number = ")
d_li=get_lat_long(dest)
d_lat=s_li[0]
d_long=s_li[1]
reverse_geocode_result_org=(s_lat, s_long)
reverse_geocode_result_dest=(d_lat, d_long)
now = datetime.now()
directions_result = gmaps.directions(reverse_geocode_result_org,
reverse_geocode_result_dest,
mode="transit",
departure_time=now)
print("The distance to be travelled is : ",directions_result[0]['legs'][0]['distance']['text'])
|
938326be33c238063f1ab5ae48b58363b563845b | t-dawei/leetcode | /code/14. 长公共前缀.py | 951 | 3.953125 | 4 | '''
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
'''
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
思路:
一位一位比较
"""
string = ''
if not strs:
return string
str_0 = strs[0]
index = 0
L = len(str_0)
while index < L:
s = str_0[index]
for ss in strs:
if ss[index:index+1] != s:
return string
else:
string += s
index += 1
return string |
b02b16eab31661c21194cca45b5f9e538d92d556 | sathvikrav/scraper | /sqlite.py | 1,477 | 3.703125 | 4 | import sqlite3
class PremierDatabase:
conn = sqlite3.connect('premier_lg.db') # static variable connects to database
c = conn.cursor()
tableCreated = False
@staticmethod
def create_table():
print("Table initialized")
PremierDatabase.c.execute('''CREATE TABLE IF NOT EXISTS latlong
(player_name text, player_country text, player_team text, player_assists text, latitude real, longitude real)''') # create a database table if it does not currently exist
PremierDatabase.conn.commit() # commits changes to sqlite database
PremierDatabase.tableCreated = True
@staticmethod
def insert_player(player_name, player_country, player_team, player_assists, player_lat, player_long):
print("Player entered into database")
PremierDatabase.c.execute("INSERT INTO latlong VALUES (?, ?, ?, ?, ?, ?)", (player_name, player_country, player_team, player_assists, player_lat, player_long))
PremierDatabase.conn.commit()
@staticmethod
def select_player(player_name):
print("Player selected")
PremierDatabase.c.execute("SELECT * FROM latlong WHERE player_name=?", (player_name,)) # retrieves all information about specific player from table row
return PremierDatabase.c.fetchone()
@staticmethod
def close():
print("Database connection closed")
PremierDatabase.conn.close() # closes the databse connection |
134a4adddd5fd408658c36ddc0521cc1d9e23b21 | Degbang/100DaysOfPython | /Day3 - controlFlow and logical Operators- start/BMI.py | 462 | 4.375 | 4 | # BMI Calculation 2.0
height = float(input("enter your height "))
weight = float(input("enter your weight "))
bmi = round(weight / height ** 2)
if bmi < 18.5:
print(f"your bmi is {bmi}, you are underweight ")
elif bmi < 25:
print(f"your bmi is {bmi}, your are normal")
elif bmi < 30:
print(f"your bmi is {bmi}, you are overweight")
elif bmi < 35:
print(f"your bmi is {bmi}, you are obese")
else:
print(f"your bmi is {bmi}, you are clinically obese") |
0d84f0f830ab4fd7cd707bf21d340be616f20b23 | SabithaSubair/Luminar_PythonDjangoProjects_May | /collections/tuples/sample.py | 559 | 4.375 | 4 | tuple=(1,2,3,4,5)
print(tuple)
print(type(tuple))
print("empty tuple")
tuple2=()
print(tuple2)
tuple3=1,2,3,5 # not necessary for ()
print(tuple3)
print(type(tuple3))
# .......features.............
#immutable...updation is not posiibble and not remove
#heterogeneous
#indexing possible
#not update and remove
print("heterogenous")
t="hai",1,8.9
print(t)
print("indexing")
print("first index:",tuple[1])
print("last index:",tuple[-1])
# to find max vale and min value
print("min value:",min(tuple),"\n","Max value:",max(tuple),"\n","Lenght is:",len(tuple))
|
0dbb90ed13641fab3694434598d23fd4e8ef8484 | msjithin/python-for-finance | /practice_games/rockPaperScissors/rps.py | 1,647 | 3.9375 | 4 | from random import randint
picks = ['Rock', 'Paper', 'Scissors']
score_1 = 0
score_2 = 0
#set player to False
player1 = False
while True:
go_on = input('Play again! ')
if len(go_on) == 0 :
print('Scores : \n You {} \t Computer {} '.format(score_1, score_2))
break
print('Rock Paper or Scissors ? ')
for i in range(len(picks)):
print('[{}] {}'.format(i+1, picks[i]))
picked_index = input('Make selection : ')
if picked_index not in ['1', '2', '3']:
print('Select one of the options with 1,2, or 3')
continue
player1 = picks[int(picked_index)-1].lower()
player2 = picks[randint(0,2)].lower()
print('Selections.... Computer : {} , You : {} '.format(player2, player1))
if player1 == player2 :
print('Its a Tie! {} - {} '.format(player1, player2))
elif player1 == 'rock':
if player2 == 'paper':
print('Computer wins! Paper covers Rock')
score_2 += 1
elif player2 == 'scissors':
print('You win! Rock crushes Scissors')
score_1 += 1
elif player1 == 'paper':
if player2 == 'rock':
print('You win! Paper covers Rock')
score_1 += 1
elif player2 == 'scissors':
print('Computer wins! Scissors cuts paper')
score_2 += 1
elif player1 == 'scissors':
if player2 == 'paper':
print('You win! Scissors cuts paper')
score_1 += 1
elif player2 == 'rock':
print('Computer wins! Rock crushes Scissors')
score_2 += 1
else:
print('Something is fishy')
|
8166340880871c9fff860feaba305e1af3ca5dfc | KopalGupta1998/Python-Programs- | /gui based project.py | 3,811 | 4.28125 | 4 | # GUI-based version of RPSLS
###################################################
# Student should add code where relevant to the following.
import simplegui
import random
# Functions that compute RPSLS
# Rock-paper-scissors-lizard-Spock template
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# helper functions
import random
def name_to_number(name):
# delete the following pass statement and fill in your code below
if(name=="rock"):
return 0
elif(name =="Spock"):
return 1
elif(name=="paper"):
return 2
elif(name=="lizard"):
return 3
elif(name=="scissors"):
return 4
else:
print "Error: Invalid Name!"
# convert name to number using if/elif/else
# don't forget to return the result!
def number_to_name(number):
# delete the following pass statement and fill in your code below
if(number==0):
return "rock"
elif(number==1):
return "Spock"
elif(number==2):
return "paper"
elif(number==3):
return "lizard"
elif(number==4):
return "scissors"
else:
print "Error: Invalid Input"
# convert number to a name using if/elif/else
# don't forget to return the result!
def rpsls(player_choice):
# delete the following pass statement and fill in your code below
print ""
# print a blank line to separate consecutive games
print "Player chooses "+ player_choice
# print out the message for the player's choice
player_number=name_to_number(player_choice)
# convert the player's choice to player_number using the function name_to_number()
comp_number=random.randrange(0,5)
# compute random guess for comp_number using random.randrange()
comp_choice=number_to_name(comp_number)
# convert comp_number to comp_choice using the function number_to_name()
print "Computer chooses "+comp_choice
# print out the message for computer's choice
difference= (comp_number-player_number)%5
# compute difference of comp_number and player_number modulo five
if(difference==1 or difference==2):
print "Computer wins!"
# use if/elif/else to determine winner, print winner message
elif(difference==3 or difference==4):
print "Player wins!"
else:
print "Player and computer tie!"
# test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
# always remember to check your completed program against the grading rubric
# Handler for input field
def get_guess(guess):
if not(guess=="rock" or guess=="paper" or guess=="scissors" or guess=="Spock" or guess=="lizard"):
print ("Error: Bad Input to RPSLS")
else:
rpsls(guess)
# Create frame and assign callbacks to event handlers
frame = simplegui.create_frame("GUI-based RPSLS", 200, 200)
frame.add_input("Enter guess for RPSLS", get_guess, 200)
# Start the frame animation
frame.start()
###################################################
# Test
get_guess("Spock")
get_guess("dynamite")
get_guess("paper")
get_guess("lazer")
###################################################
# Sample expected output from test
# Note that computer's choices may vary from this sample.
#Player chose Spock
#Computer chose paper
#Computer wins!
#
#Error: Bad input "dynamite" to rpsls
#
#Player chose paper
#Computer chose scissors
#Computer wins!
#
#Error: Bad input "lazer" to rpsls
#
|
5e0f408acb5652a44aca4c1177c9aebbfb7b9be0 | size1995/Coding_Interviews-personal_solutions | /10_斐波那契数列.py | 255 | 3.75 | 4 | class Solution:
def Fibonacci(self,n):
a0,a1=0,1
if n==0:
return 0
if n==1:
return 1
for i in range(2,n+1):
a3=a0+a1
a0=a1
a1=a3
return a1
|
10783a6e8a9330f6c9d9a9f3204707db62a98d51 | eugenechernykh/coursera_python | /week8_null_or_not.py | 671 | 4.03125 | 4 | '''
https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/9uqay/nol-ili-nie-nol
Проверьте, есть ли среди данных N чисел нули.
Формат ввода
Вводится число N, а затем N чисел.
Формат вывода
Выведите True, если среди введенных чисел есть хотя бы один нуль, или False в
противном случае.
'''
print(
any(
map(
lambda x: x == 0,
map(
lambda x: int(input()),
range(int(input()))
)
)
)
)
|
17ce02a7fada7c0664322b794a572192b48f7c13 | startsUp/Algorithms-Practice | /amzn/fill-trucks/fill-trucks.py | 2,546 | 4.53125 | 5 | """
An Amazon Warehouse manager needs to create a shipment to fill a truck. All of the products in the warehouse are in boxes of
the same size. Each product is packed in some number of units per box. Given the number of boxes the truck can hold, write an
algorithm to determine the maximum number of units of any mix of products that can be shipped.
Input
The input to the function method consists of five arguments:
num, an integer representing number of products;
boxes, a list of integers representing the number of available boxes for products;
unitSize, an integer representing size of unitsPerBox;
unitsPerBox, a list of integers representing the number of units packed in each box;
truckSize, an integer representing the number of boxes the truck can carry.
Output
Return an integer representing the maximum units that can be carried by the truck.
Constraints
1 <= |boxes| <= 10^5
|boxes| == |unitsPerBox|
1 <= boxes[i] <= 10^7
1 <= i <= |boxes|
1 <= unitsParBox[i] <= 10^5
1 <= j <= |unitsPerBox|
1 <= truckSize <= 10 ^ 8
Note
[list name] denotes length of the list.
Example
Input:
num=3
boxes=[1,2,3]
unitSize=3
unitsPerBox= [3,2,1]
truckSize = 3
Output
7
Explanation:
Product 0: because boxes[0] = 1, we know there is 1 box in product 0. And because unitsPerBox[0] = 3, we know there is 1 box with 3 units in product 0.
Product 1: 2 boxes with 2 units each
Product 2: 3 boxes with 1 unit each
Final we have the packed products like a list : [3, 2, 2, 1, 1, 1]
The truckSize is 3, so we pick the top 3 from the above list, which is [3, 2, 2], and return the sum 7.
The maximum number of units that can be shipped = 3 + 2 + 2 = 7 units
"""
def fill_truck(boxes, units, truckSize):
# [3, 4, 6]
# [5, 3 ,2]
# truck size = 4 boxes
products = [(units[i], boxes[i]) for i in range(len(boxes))]
products.sort(reverse=True)
print(products)
units_loaded = 0
boxes_loaded = 0
i=0
while (boxes_loaded < truckSize and i < len(boxes)):
p_units, p_boxes = products[i]
boxes_to_load = min(p_boxes, truckSize - boxes_loaded)
boxes_loaded += boxes_to_load
units_loaded += boxes_to_load * p_units
i+=1
return units_loaded
# 3
# return max number of units you can fit in truck
test_boxes = [5, 23, 63]
test_units = [53, 23, 34]
truck_size = 3
print(fill_truck(test_boxes, test_units, truck_size)) |
bf9010a95acfb49e42bf6f45b40eda9a51f7f75e | Arunnithyanand/luminarpython | /Flowcontrols/functions/variable length argument method/variable length argument method.py | 391 | 3.6875 | 4 | def add(num1,num2):
return num1+num2
res=add(10,20)
print(res)
def add(num1,num2,num3):
return num1+num2
res=add(10,20,30)
print(res)
def add(*args):
res=0
for num in args:
res+=num
return res
print(add(10,20,30,40))
def print_employee(**kwargs):
for k,v in kwargs.items():
print(k,"=>",v)
print_employee(id=100,place="thrissur",job="kakkanad")
|
0f28892c71fa47d1f2aced8869f04785866516cd | gongtian1234/-offer | /test13_机器人的运动范围.py | 3,846 | 3.578125 | 4 | '''
面试题13:机器人的运动范围。地上有一个m行n列的格子。一个机器人从坐标(0,0)的位置开始移动,每次可以向左右上下移动一格,但不能进入
行坐标和列坐标位数之和大于k的格子。如k=18时,机器人可以进入(35,37), 但不能进入(35,38)。问该机器人能到达多少个格子?
思路:
对比:矩阵中的路径中使用了for循环先匹配首字母,匹配成功后在其上下左右匹配下一个字母,匹配成功后,再匹配下一个字母;否则表明该路径不
通,重新用for匹配首字母;
机器人的运动范围中没有使用for,因为这个题不用先匹配首字母再匹配下一个,相当于首字母给出,需要不断以上下左右的方式寻找满足条件
的下一个,直至到路的尽头为止,具体还得结合demo理解。
问题:movingCountCore()的递归没有绕明白,check通过进入一个点后,开始上下左右测试,先上递归,上面如果通过check,在这一个点再上下左右
递归,直到到达尽头为止【有点不撞南墙不回头的意思,在一个满足的点上,没有找到尽头是不会结束递归的】
'''
class Solution:
def movingCount(self, threshold, rows, cols):
if threshold<0 or rows<=0 or cols<=0:
return 0
visited = [False]*(rows*cols)
count = self.movingCountCore(rows, cols, threshold, 0, 0, visited)
return count
def movingCountCore(self, rows, cols, threshold, row, col, visited):
count = 0
if self.check(rows, cols, threshold, row, col, visited):
visited[row*cols+col] = True
count = 1 + \
self.movingCountCore(rows, cols, threshold, row-1, col, visited) + \
self.movingCountCore(rows, cols, threshold, row+1, col, visited) + \
self.movingCountCore(rows, cols, threshold, row, col-1, visited) + \
self.movingCountCore(rows, cols, threshold, row, col+1, visited)
return count
def check(self, rows, cols, threshold, row, col, visited):
if row>=0 and row<rows and col>=0 and col<cols and (self.getDigitSum(row)+self.getDigitSum(col)<=threshold) and not visited[row*cols+col]:
return True
return False
def getDigitSum(self,num):
sum = 0
while num>0:
sum += (num%10)
num = num//10
return sum
test1 = Solution()
print(test1.movingCount(5, 10, 10))
print(test1.movingCount(10,1,100))
# 这种解法不考虑机器人,仅考虑在限定的格子内能到达多少个点,但是以下这种方法还是有点暴力,可以考虑一下更优化的方法
##【注意:好像跑题了,题目问的是能到达多少个格子,不是能到达多少个点;原题中的上下左右走法其实就限定了是格子】##
class Solution2:
def movingCount(self,threshold, rows, cols):
if threshold<0 or rows<=0 or cols<=0:
return 0
count_lst = []
for row in range(rows):
for col in range(cols):
str_row, str_col = str(row), str(col)
n_r, n_c = len(str_row), len(str_col)
n_sum = 0
for i in range(n_r):
n_sum += int(str_row[i])
for j in range(n_c):
n_sum += int(str_col[j])
if threshold>=n_sum:
count_lst.append(1)
else:
continue
return len(count_lst)
test2 = Solution2()
# print(test.movingCount(500,500,75)) # 250000 1.1s
print(test2.movingCount(5, 10, 10))
print(test2.movingCount(10,1,100))
|
3631e11c386b4814d7306484ad0237ae75fb4574 | jeffleon/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/7-islower.py | 98 | 3.578125 | 4 | #!/usr/bin/python3
def islower(c):
return(True if ord(c) > 96 and ord(c) < 123 else False)
|
a225cdb3e7d0d853c48541784cd2317cb19891f4 | kmadhav907/CP-Tutorials | /swap_adjacent_nodes_in_ll.py | 731 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
self.swapNodes(head)
return head
def swapNodes(self , head):
if head is None:
return head
if head.next is None:
return head
cur = head
swap_ptr = head.next
while(cur != None and swap_ptr != None ):
temp = cur.val
cur.val = swap_ptr.val
swap_ptr.val = temp
cur = cur.next.next
if swap_ptr.next is None:
break
swap_ptr = swap_ptr.next.next |
583455dc3c84e28d0d1e361010c20161b95cd036 | mrudula-pb/Python_Code | /Udacity/Project2/BS_Iterative_Solution.py | 1,586 | 4.375 | 4 |
def binary_search(array, target):
'''Write a function that implements the binary search algorithm using iteration
args:
array: a sorted array of items of the same type
target: the element you're searching for
returns:
int: the index of the target, if found, in the source
-1: if the target is not found
'''
lower_bound = 0
upper_bound = len(array)
center_of_array = int(lower_bound + upper_bound/2)
while lower_bound <= upper_bound:
#for element in array[lower_bound:upper_bound + 1]:
#print("Target: ", target)
#print("Lower Bound: ", lower_bound)
#print("Upper Bound: ", upper_bound)
#print(center_of_array)
if target == array[center_of_array]:
return center_of_array
elif target > array[center_of_array]:
lower_bound = center_of_array + 1
# input_list[input_list.index(element)] = None
array[:center_of_array + 1] = [None for item in array[:center_of_array + 1]]
center_of_array = int((lower_bound + upper_bound) / 2)
#print(center_of_array)
elif target < array[center_of_array]:
upper_bound = center_of_array - 1
array[center_of_array:] = [None for item in array[center_of_array:]]
center_of_array = int((lower_bound + upper_bound) / 2)
else:
return -1
return center_of_array
array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 6
index_of_target = binary_search(array, target)
print("Index of Target value: ", index_of_target) |
6284f66c0a767a4adc8de44e502949c28a81b749 | sorryDave/diceGenerator | /randomSys.py | 1,073 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 21 11:41:24 2018
@author: hellodave
"""
import random
#random.sample(range(1, 100), 3)
#numLow=0
#numHigh=0
#
#listOfNumbers=[]
#
#def randum(n):
# random.randint(numLow, numHigh)
#
# for x in range(0, n):
# listOfNumbers.append(random.randint(numLow, numHigh))
#####################################################33
def dice(n, nmax):
print("Rolling dices...")
print("The values are....")
print(random.randint(n, nmax))
print (random.randint(n,nmax))
#################################################################
#question='n'
#
#while question != 'n':
# if question == 'y':
# die1 = random.randint(1, 6)
# die2 = random.randint(1, 6)
# print(die1, die2)
# question = input('Would you like to roll the dice [y/n]?\n')
# else:
# print('Invalid response. Please type "y" or "n".')
# question = input('Would you like to roll the dice [y/n]?\n')
#
# print('Good-bye!')
#
# |
429b49adc4b5e5d8500b50a0383168f437fd8105 | dizballanze/breaking-point | /breaking_point/breaking_point.py | 1,494 | 3.78125 | 4 | import timeit
def find_breaking_point(f1, f2, input_generator, start=1, step=1,
limit=1000000, trial_count=1000, repeat_count=3):
"""
Find size of input arguments (n0) for which f2(n0) is faster than f1(n0).
- f1, f2 - functions to test.
- input_generator - function that receives current size of input arguments and returns input data in form of tuple with first item - list of non-keyword arguments and second item - dict of keyword arguments.
- start - initial input data size.
- step - iteration step.
- limit - maximum size of input data.
- trial_count - count of executions of f1/f2 on each iteration.
- repeat_count - to repeat trials several times and use average performance value.
returns n0 - size of input data for which f2(n0) is faster than f1(n0)
or None if reaches limit.
"""
for n in range(start, limit+1):
curr_input = input_generator(n)
# Test first function
f1_results = timeit.repeat(lambda: f1(*curr_input[0], **curr_input[1]),
repeat=repeat_count, number=trial_count)
f1_avg = sum(f1_results) / len(f1_results)
# Test second function
f2_results = timeit.repeat(lambda: f2(*curr_input[0], **curr_input[1]), repeat=repeat_count, number=trial_count)
f2_avg = sum(f2_results) / len(f2_results)
# Compare performance
if f2_avg < f1_avg:
return n
return None
|
be1b6c54c892748c0608edf86bd0a740268b9f94 | nsshayan/DataStructuresAndAlgorithms | /addArray.py | 220 | 3.703125 | 4 |
''' Given a list of integers for eg. [1,2,3] and one to the element and print the list [1,2,4] '''
N = raw_input().split()
L = [1,2,3]
str1 = ''.join(str(e) for e in L)
value = int(str1)+1
print map(int,str(value)) |
4a18fa28e6a45ac45baa941d95607a4b064e1021 | amod26/DataStructuresPython | /Valid Parentheses.py | 418 | 3.703125 | 4 | Valid Parentheses
class Solution:
def isValid(self, s: str) -> bool:
stack,pairs = [],{"(":")","[":"]","{":"}"}
for char in s:
if char in pairs:
stack.append(char)
elif len(stack)<=0:
return False
elif char in pairs.values() and char!=pairs[stack.pop()]:
return False
return True if stack==[] else False
|
629338549257059fc61b289e3f4d30d536f1be69 | 836304831/leetcode | /leetcode_algorithm151/chapter2/2_1_2remove_duplicate_from_sorted_array2.py | 937 | 3.5625 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 20 ms 11.7 MB
if len(nums) == 0:
return 0
if len(nums) == 1:
return 1
num_len = 0
for idx in range(1, len(nums)):
if nums[num_len] == nums[idx]:
if num_len >= 1:
if nums[num_len - 1] != nums[idx]:
num_len += 1
nums[num_len] = nums[idx]
else:
num_len += 1
nums[num_len] = nums[idx]
else:
num_len += 1
nums[num_len] = nums[idx]
return num_len + 1
if __name__ == "__main__":
# nums = [1, 1, 1, 2, 2, 3]
nums = [1, 2]
num_len = Solution().removeDuplicates(nums)
print("num_len: {}, nums: {}".format(num_len, nums))
|
366e4d56391a33c6e25aaa6538f01aeff6a3dd9a | BrunoCAF/CT213 | /Lab 10 - Object Detection with YOLO/yolo_detector.py | 5,193 | 3.578125 | 4 | from keras.models import load_model
import cv2
import numpy as np
from utils import sigmoid
class YoloDetector:
"""
Represents an object detector for robot soccer based on the YOLO algorithm.
"""
def __init__(self, model_name, anchor_box_ball=(5, 5), anchor_box_post=(2, 5)):
"""
Constructs an object detector for robot soccer based on the YOLO algorithm.
:param model_name: name of the neural network model which will be loaded.
:type model_name: str.
:param anchor_box_ball: dimensions of the anchor box used for the ball.
:type anchor_box_ball: bidimensional tuple.
:param anchor_box_post: dimensions of the anchor box used for the goal post.
:type anchor_box_post: bidimensional tuple.
"""
self.network = load_model(model_name + '.hdf5')
self.network.summary() # prints the neural network summary
self.anchor_box_ball = anchor_box_ball
self.anchor_box_post = anchor_box_post
def detect(self, image):
"""
Detects robot soccer's objects given the robot's camera image.
:param image: image from the robot camera in 640x480 resolution and RGB color space.
:type image: OpenCV's image.
:return: (ball_detection, post1_detection, post2_detection), where each detection is given
by a 5-dimensional tuple: (probability, x, y, width, height).
:rtype: 3-dimensional tuple of 5-dimensional tuples.
"""
# Todo: implement object detection logic
image = self.preprocess_image(image)
output = self.network.predict(image)
return self.process_yolo_output(output)
def preprocess_image(self, image):
"""
Preprocesses the camera image to adapt it to the neural network.
:param image: image from the robot camera in 640x480 resolution and RGB color space.
:type image: OpenCV's image.
:return: image suitable for use in the neural network.
:rtype: NumPy 4-dimensional array with dimensions (1, 120, 160, 3).
"""
# Todo: implement image preprocessing logic
image = cv2.resize(image, (160, 120), interpolation=cv2.INTER_AREA)
image = np.array(image)
image = (1.0*image)/255.0
image = np.reshape(image, (1, 120, 160, 3))
return image
def process_yolo_output(self, output):
"""
Processes the neural network's output to yield the detections.
:param output: neural network's output.
:type output: NumPy 4-dimensional array with dimensions (1, 15, 20, 10).
:return: (ball_detection, post1_detection, post2_detection), where each detection is given
by a 5-dimensional tuple: (probability, x, y, width, height).
:rtype: 3-dimensional tuple of 5-dimensional tuples.
"""
coord_scale = 4 * 8 # coordinate scale used for computing the x and y coordinates of the BB's center
bb_scale = 640 # bounding box scale used for computing width and height
output = np.reshape(output, (15, 20, 10)) # reshaping to remove the first dimension
# Todo: implement YOLO logic
features = np.reshape(output, (300, 10))
features = np.array_split(features, 10, 1)
t_ball, t_post = features[0], features[5]
t_ball, t_post = np.reshape(t_ball, (15, 20)), np.reshape(t_post, (15, 20))
i_b, j_b = np.argwhere(t_ball == t_ball.max())[0]
post_order = np.reshape(t_post, 300)
post_1, post_2 = post_order[post_order.argsort()[::-1][0:2]]
i_p_1, j_p_1 = np.argwhere(t_post == post_1)[0]
i_p_2, j_p_2 = np.argwhere(t_post == post_2)[0]
feat_ball = output[i_b][j_b]
feat_post_1 = output[i_p_1][j_p_1]
feat_post_2 = output[i_p_2][j_p_2]
# Todo: change this line
ball_detection = (sigmoid(feat_ball[0]),
(j_b + sigmoid(feat_ball[1]))*coord_scale,
(i_b + sigmoid(feat_ball[2]))*coord_scale,
bb_scale*self.anchor_box_ball[0]*np.exp(feat_ball[3]),
bb_scale*self.anchor_box_ball[1]*np.exp(feat_ball[4]))
# Todo: change this line
post1_detection = (sigmoid(feat_post_1[5]),
(j_p_1 + sigmoid(feat_post_1[6]))*coord_scale,
(i_p_1 + sigmoid(feat_post_1[7]))*coord_scale,
bb_scale*self.anchor_box_post[0]*np.exp(feat_post_1[8]),
bb_scale*self.anchor_box_post[1]*np.exp(feat_post_1[9]))
# Todo: change this line
post2_detection = (sigmoid(feat_post_2[5]),
(j_p_2 + sigmoid(feat_post_2[6]))*coord_scale,
(i_p_2 + sigmoid(feat_post_2[7]))*coord_scale,
bb_scale*self.anchor_box_post[0]*np.exp(feat_post_2[8]),
bb_scale*self.anchor_box_post[1]*np.exp(feat_post_2[9]))
return ball_detection, post1_detection, post2_detection
|
a2959d4fe27029b2855f4bafe854416f98b08305 | qperotti/Cracking-The-Coding-Interview-Python | /Chapter 1 - Arrays and Strings/ex4.py | 837 | 4.0625 | 4 | '''
Exercise 1.4 - Palindrome Permutation:
Given a string, write a function to check if it is a permutation of a palindrome.
The palindrome does not need to be limited to just dictionary words.
'''
def checkPalindrome(s):
# number of odd counts
count = 0
char_dict = dict()
for character in s:
if character != ' ':
if character not in char_dict:
char_dict[character] = 1
count += 1
else:
char_dict[character] += 1
if char_dict[character] % 2 == 0:
count -= 1
else:
count += 1
return count
def palindromePermutation(s):
count = checkPalindrome(s)
return count <= 1
if __name__ == "__main__":
# True
print(palindromePermutation('atco cta'))
print(palindromePermutation('aaabb cc'))
# False
print(palindromePermutation('hello world'))
print(palindromePermutation('aaa bbb cc')) |
4523eac7c1e61f1f78dec89a0d8ed4fe9f40abf1 | alteryx/featuretools | /featuretools/primitives/standard/transform/natural_language/number_of_unique_words.py | 2,223 | 3.59375 | 4 | from string import punctuation
from typing import Iterable
import pandas as pd
from woodwork.column_schema import ColumnSchema
from woodwork.logical_types import IntegerNullable, NaturalLanguage
from featuretools.primitives.base import TransformPrimitive
from featuretools.primitives.standard.transform.natural_language.constants import (
DELIMITERS,
)
class NumberOfUniqueWords(TransformPrimitive):
"""Determines the number of unique words in a string.
Description:
Determines the number of unique words in a given string. Includes options for
case-insensitive behavior.
Args:
case_insensitive (bool, optional): Specify case_insensitivity when searching for unique words.
For example, setting this to True would mean "WORD word" would be treated as having
one unique word. Defaults to False.
Examples:
>>> x = ['Word word Word', 'This is a SENTENCE.', 'green red green']
>>> number_of_unique_words = NumberOfUniqueWords()
>>> number_of_unique_words(x).tolist()
[2, 4, 2]
>>> x = ['word WoRD WORD worD', 'dog dog dog', 'catt CAT caT']
>>> number_of_unique_words = NumberOfUniqueWords(case_insensitive=True)
>>> number_of_unique_words(x).tolist()
[1, 1, 2]
"""
name = "number_of_unique_words"
input_types = [ColumnSchema(logical_type=NaturalLanguage)]
return_type = ColumnSchema(logical_type=IntegerNullable, semantic_tags={"numeric"})
default_value = 0
def __init__(self, case_insensitive=False):
self.case_insensitive = case_insensitive
def get_function(self):
def _unique_word_helper(text):
if not isinstance(text, Iterable):
return pd.NA
unique = set()
for t in text:
punct_less = t.strip(punctuation)
if len(punct_less) > 0:
unique.add(punct_less)
return len(unique)
def num_unique_words(array):
if self.case_insensitive:
array = array.str.lower()
array = array.str.split(f"{DELIMITERS}")
return array.apply(_unique_word_helper)
return num_unique_words
|
55467941eea61791561f0ad4f73498692f82138d | jerrytnutt/Automate-the-Boring-Stuff-Project-Solutions | /CH03-Functions/collatzSequence.py | 619 | 4.4375 | 4 | # The Collatz Sequence
# Write a function named collatz with number parameter.
# If number is even, return (number // 2)
# If number is odd, return (3 * number + 1)
# Use try and except for correct int input.
def collatz(number):
if number == 1:
return number
elif number % 2 == 0:
number = (number//2)
elif number % 2 == 1:
number = (3 * number) + 1
print(number)
return collatz(number)
if __name__ == '__main__':
while True:
number = input('Enter a integer: ')
try:
collatz(int(number))
break
except:
print('Please enter an integer')
|
5c93fc414bc4d7fe4b5434da4c5400fc96dbfd5e | cosetteke/Programming-Algorithm | /3loop/isbn3.py | 427 | 3.65625 | 4 | # https://dodona.ugent.be/nl/courses/359/series/3487/activities/1898834779
# https://dodona.ugent.be/nl/courses/359/series/3486/activities/182880102
first = input()
while first != 'stop':
sum = int(first)
for index in range(2, 10):
next_digit = int(input())
sum += index * next_digit
sum %= 11
ten = int(input())
print('OK' if ten == sum else 'WRONG')
# read next ten
first = input() |
08dab1fbf3d40915cfcd4e52adc4c69aae729355 | veronikanska/pyladies | /02/ctverec.py | 284 | 3.625 | 4 | strana = float(input('Zadej cislo: '))
cislo_je_spravne = strana > 0
if cislo_je_spravne:
print('obvod ctverce o strane', strana, 'cm je', 4 * strana, 'cm')
print('obsah ctverce o strane', strana, '356 cm je', strana * strana, 'cm2')
else:
print('strana musi byt kladna') |
0b52027b187435de3f6cc6981ea725960bd827d1 | pyaephyokyaw15/PythonFreeCourse | /chapter6/list_demo.py | 463 | 3.703125 | 4 | lst = [10,20,30,40,50]
lst[0] = 20
print("list ",lst, " type ",type(lst))
lst_1_to_ten = list(range(1,10,2))
print("list from range ",lst_1_to_ten)
str_list = "Hello World".split()
str_list[0] = str_list[0].upper()
print("Str_list ",str_list)
my_str = "hello"
#my_str[0] = "K"
my_str = "How are you"
print("str [0] ",my_str[0])
for i in lst:
i = i+1
print("Item => ",i)
for index,value in enumerate(lst):
lst[index] *= 2
print("Double list ",lst) |
8dc5762bd350f1f9c7cacfbf01c8318aae9b077b | 1i0n0/Python-Learning | /practices/temp_converter.py | 1,576 | 4.25 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import re
base = 32
conversion_factor = 9.0 / 5.0
degree_symbol = '\xB0'
# Computes the Fahrenheit (F) equivalent of a specific Celsius (C)
# F = (9 / 5) * C + 32
def celsius2fahrenheit(c):
return conversion_factor * c + 32
# Computes the Celsius (C) equivalent of a specific Fahrenheit (F)
# C = (F - 32) / (9 / 5)
def fahrenheit2celsius(f):
return (f - 32) / conversion_factor
if __name__ == "__main__":
# Get a temperature like 24C or 75.2F
temp = input("Please enter a temperature (end with C/F): \n")
# Call sys.exit() if it is not a temperature
temp = temp.strip()
if not re.match('[0-9]+(\.[0-9]+)*[C|F]$', temp, re.I):
print("Please enter a temperature, e.g. 24C, 75.2F")
sys.exit(1)
# Convert the temperature
if temp[-1] in ['C', 'c']:
# degrees Celsius to degrees Fahrenheit
celsius_temp = float(temp[0:-1])
fahrenheit_temp = celsius2fahrenheit(celsius_temp)
print("Celsius Temperature: {0:.1f}{1}C".format(celsius_temp, degree_symbol))
print("Fahrenheit Equivalent: {0:.1f}{1}F".format(fahrenheit_temp, degree_symbol))
elif temp[-1] in ['F', 'f']:
# degrees Fahrenheit to degrees Celsius
fahrenheit_temp = float(temp[0:-1])
celsius_temp = fahrenheit2celsius(fahrenheit_temp)
print("Fahrenheit Temperature: {0:.1f}{1}F".format(fahrenheit_temp, degree_symbol))
print("Celsius Equivalent: {0:.1f}{1}C".format(celsius_temp, degree_symbol))
else:
sys.exit(2)
|
7d3d672be0104f58fc9af203d3fe960e72bfca3e | jhtc5898/ExamenComputacionParalela | /tenesacaJohn_Multiprocessing.py | 2,004 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 4 09:38:36 2020
@author: usuario
"""
import random
import time
import multiprocessing
def how_many_max_values_sequential(ar):
#find max value of the list
maxValue = 0
for i in range(len(ar)):
if i == 0:
maxValue = ar[i]
else:
if ar[i] > maxValue:
maxValue = ar[i]
#find how many max values are in the list
contValue = 0
for i in range(len(ar)):
if ar[i] == maxValue:
contValue += 1
return contValue
# Complete the how_many_max_values_parallel function below.
def how_many_max_values_parallel(ar):
datos=[0,10,20,30,40]
p = multiprocessing.Pool(5)
#p.map(multi, datos)
#p.close()
#p.join()
print(p.map(multip, datos))
return 0
def multip(datos):
#find max value of the list
maxValue = 0
for i in range(len(ar)):
if i == 0:
maxValue = ar[i]
else:
if ar[i] > maxValue:
maxValue = ar[i]
#find how many max values are in the list
contValue = 0
for i in range(len(ar)):
if ar[i] == maxValue:
contValue += 1
return contValue
if __name__ == '__main__':
ar_count = 100
#Generate ar_count random numbers between 1 and 30
ar = [random.randrange(1,30) for i in range(ar_count)]
inicioSec = time.time()
resultSec = how_many_max_values_sequential(ar)
finSec = time.time()
inicioPar = time.time()
resultPar = how_many_max_values_parallel(ar)
finPar = time.time()
print('Results are correct!\n' if resultSec == resultPar else 'Results are incorrect!\n')
print('Sequential Process took %.3f ms with %d items\n' % ((finSec - inicioSec)*1000, ar_count))
print('Parallel Process took %.3f ms with %d items\n' % ((finPar - inicioPar)*1000, ar_count)) |
ba9f296a8d1626c0ef834b302a9380e16253b79a | amlewis4/Learn-Python-the-Hard-Way | /ex34.py | 365 | 4.3125 | 4 | animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print animals
for i in animals:
print 1
Print ""
Print "First, second, third are ordinal numbers but we"
Print "Need to count by cardinal numbers: 1, 2, 3."
Print "With lists, you start at 0"
Print ""
for i in range(len)(animals)):
print "Index %d in the list is %s." % (u, animals[i]) |
e3dc88fa8b605e3dd4ca12dabe786290fe984e84 | TheFuzzStone/hello_python_world | /chapter_5/5_1.py | 2,095 | 4.375 | 4 | #5-1. Conditional Tests: Write a series of conditional tests.
#Print a statement #describing each test and your prediction for
# the results of each test. Your code
#should look something like this:
#car = 'subaru'
#print("Is car == 'subaru'? I predict True.")
#print(car == 'subaru')
#print("\nIs car == 'audi'? I predict False.")
#print(car == 'audi')
#Look closely at your results, and make sure you understand why each line
#evaluates to True or False.
cars = ['buick', 'pontiac', 'subaru', 'toyota', 'saab', 'audi', 'bmw']
car = cars.pop(-2)
if car == 'audi':
print('This is ' + car.title() + '. The statement is \'True\':')
else:
print('<<<It\'s not Audi. Statement is \'False\'>>>')
print(car == 'audi')
print('----------------------------------------')
print('Is car == bmw? Will be False, because I\'ve popped "Audi"\
in previous step:')
print(car == 'bmw')
print('----------------------------------------')
print('Is audi == Audi? Nope, because testing for equality is case sensitive \
in Python. So it\'s \'False\':')
print(car.upper() == car)
print('----------------------------------------')
print('Let\'s try \'!=\'. Is car != cars? I think it\'s True:')
print(cars != car)
print('----------------------------------------')
print('Let\'s check \'Ferrari\' in cars. Will be False:')
print('ferrari' in cars)
print('----------------------------------------')
print('Now we\'ll check same \'Ferrari\' using the keyword "not". Will be True,\
because Ferrari isn\'t in list right now:')
print('ferrari' not in cars)
print('----------------------------------------')
num_0 = 100
num_1 = 99
print("Is (100 > 99) and (99 > 100)? One of the result's is wrong, so \
the whole statement will be \'False\':")
print( (num_0 > num_1) and (num_1 > num_0) )
print('----------------------------------------')
print("Is (100 > 99) or (99 > 100)? The first result is True, so the \
whole statement will be \'True\':")
print( (num_1 < num_0) or (num_0 > num_1) )
print('----------------------------------------')
### I understand why some lines evaluates to True and False.
|
6b4efeb73f2bd2ff39630b2476dd381b4aec6970 | dudulydesign/python_basic_pratice | /py_basic/a010.py | 427 | 3.828125 | 4 |
'''
撰寫一程式可供使用者輸入一整數N
a.假如(N < 60)印出"不及格"
b.假如(N≥60)而且(N < 90)印出"及格"
c.假如(N≥90)而且(N < 100)印出"表現優異"
'''
if __name__ == "__main__":
text = raw_input("enter:")
print text
n1 = int(text)
if n1 < 60:
print u"不及格"
elif n1 >= 60 and n1 < 90:
print u"及格"
elif n1 >= 90 and n1 <= 100:
print u"表現優異"
|
aa0a98a2728c3ab0db19101d33f8eb57eb45e511 | maheshhingane/LeetCode | /Algorithms/Easy/ReverseInteger.py | 579 | 3.5625 | 4 | """
https://leetcode.com/problems/reverse-integer/description/
"""
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
abs_x = abs(x)
return_val = 0
multiple = (10 ** len(str(abs_x))) // 10
while abs_x > 0:
return_val += ((abs_x % 10) * multiple)
abs_x = abs_x // 10
multiple //= 10
if x < 0:
return_val *= -1
if (-2 ** 31) <= return_val <= ((2 ** 31) - 1):
return return_val
else:
return 0
|
fd1885547b1e423a7a89fc306d72ebe37a104cc0 | racingslab/python-kiwoom | /5주차/cycle.py | 326 | 3.65625 | 4 | class cycle:
wheel = 0
speed = 5
def __init__(self, wheel, speed):
self.wheel = wheel
self.speed = speed
def run(self, sec):
return self.speed * sec
def getType(self):
return (str(self.wheel) + '발 자전거')
one = cycle(1, 10)
print(one.run(5))
print(one.getType())
|
9f1ce721be73fb0f92948ec5bde3a35fe08eb158 | griffinpup/obsidian | /test_csv_consolidator.py | 785 | 3.53125 | 4 | import unittest
import os
import csv_consolidator
class test_csv_consolidator(unittest.TestCase):
def test_consolidate_CSV(self):
with open("test.csv", "w") as output:
output.write("1,20.0,20.0\n1,30.0,30.0")
csv_consolidator.consolidate_CSV("test.csv", "testout.csv")
with open("testout.csv") as input:
first_line = input.readline()
os.remove("test.csv")
os.remove("testout.csv")
self.assertEqual("1,25.0,25.0\n", str(first_line))
def test_incorrect_CSV_format(self):
with open("test_incorrect_csv.csv", "w") as output:
output.write("1,20,20")
self.assertFalse(csv_consolidator.is_valid_input_CSV("test_incorrect_csv.csv"))
os.remove("test_incorrect_csv.csv")
|
4b85914de266c2c2bd949c3fa611767bb48ed187 | jmcada2503/datosEstructurados | /main.py | 3,118 | 3.71875 | 4 | from funciones import *
subjectsRoot = "./subjects.txt"
studentsRoot = "./students.txt"
estudiantes = cargarDatosEstudiantes(studentsRoot)
cursos = cargarDatosCursos(subjectsRoot)
print(cursos)
print(estudiantes)
while True:
menu = """
1. Agregar estudiante
2. Crear nuevo curso
3. Matricular estudiante en un curso
4. Mostrar todos los cursos registrados
5. Mostrar todos los estudiantes registrados
6. Consultar promedio de estudiante
7. Consultar materias matriculadas por estudiante
8. Consultar estudiantes matriculados en un curso
9. Porcentaje de estudiantes que ganó y perdió un curso
10. Salir
"""
print(menu)
try:
op = int(input("Seleccione una opción: "))
except ValueError:
op = None
if op == 1:
estudiante = agregarEstudiante()
estudiantes[estudiante[0]] = estudiante[1]
actualizarEstudiantes(studentsRoot, estudiantes)
elif op == 2:
curso = crearNuevoCurso()
cursos[curso[0]] = [curso[1], curso[2], {}]
actualizarCursos(subjectsRoot, cursos)
elif op == 3:
estudiante = cedulaEstudiante(estudiantes)
curso = nombreCurso(cursos)
try:
cursos[curso][2][estudiante]
printAdvice("Este estudiante ya está registrado en este curso")
except:
cursos[curso][2][estudiante] = []
actualizarCursos(subjectsRoot, cursos)
elif op == 4:
mostrarCursos(cursos)
elif op == 5:
mostrarEstudiantes(estudiantes)
elif op == 6:
estudiante = cedulaEstudiante(estudiantes)
promedio = calcularPromedioPonderado(estudiante, cursos)
print(f"El promedio de este estudiante es: {round(promedio, 2)}")
elif op == 7:
estudiante = cedulaEstudiante(estudiantes)
print("\nCursos en los que el estuidante está matriculado:\n")
none = True
for i, j in cursos.items():
try:
j[2][estudiante]
print(i)
none = False
except KeyError:
pass
if none:
print("Este estudiante no está matriculado en ningún curso")
elif op == 8:
curso = nombreCurso(cursos)
if len(cursos[curso][2]) > 0:
print(f"\nEstudiantes matriculados en {curso}:\n")
for i in cursos[curso][2].keys():
print(f"\nNombre del estudiante: {estudiantes[i]}\nNúmero de identificación del estudiante: {i}\n")
else:
print("\nNo existen estudiantes matriculados a este curso")
elif op == 9:
curso = nombreCurso(cursos)
passed = 0
for i in cursos[curso][2].values():
nota = 0
for j in i:
nota += j
nota = nota/cursos[curso][0]
if nota >= 3:
passed += 1
print(f"\nEstudiantes que ganaron el curso: {(passed*100)/len(cursos[curso][2])}%\nEstudiantes que perdieron el curso: {100-((passed*100)/len(cursos[curso][2]))}%")
elif op == 10:
break
else:
print("Debes seleccionar una opción válida")
|
bd04eb1ffaee29a83a26b738e6bd478fff33e40a | Santi-hr/Acronymate | /src/initScripts/argvHandler.py | 1,197 | 3.828125 | 4 | import argparse
import pathlib
class ArgvHandler:
"""Class to handle input arguments if existant. Provides support for the word integration which calls this program
using arguments"""
def __init__(self):
# 1. Use argparse to read all arguments. All set to optional to allow launching the script without them
parser = argparse.ArgumentParser(
description="Script to extract acronyms from Word documents. Don't arguments to access the user interface")
parser.add_argument("-i", "--input", type=str, default="", help="Path to word document", required=False)
parser.add_argument("-m", "--mode", type=str, default="", help="Processing mode", required=False)
parser.add_argument("-fn", "--filename", type=str, default=None, help="Original filename of document", required=False)
args = parser.parse_args()
# 2. Perform checks
aux_path = pathlib.Path(args.input)
if not aux_path.exists():
exit(-1) #Fixme: Raise an exception and only exit on the main script
# 3. Expose arguments
self.input_path = args.input
self.mode = args.mode
self.filename = args.filename
|
a51f0368b9e8e305e71a8e02e9f734217ec6ee50 | Silentsoul04/my_software_study | /Algorithm/SWEA/6258_자료구조_셋,딕셔너리_6.py | 621 | 3.703125 | 4 | #다음과 같이 정수 N을 입력받아서 1부터 N까지의 정수를 키로 하고,
#그 정수의 제곱을 값으로 하는 딕셔너리 객체를 만드는 코드를 작성하십시오.
#입력 : 5
#출력 : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
#1. 인풋을 받는 친구를 만든다.
#2. dictionary를 넣을 변수를 초기화한다.
#3. 인풋 받은 친구에 +1을 하여 for문을 돌린다.
#5. for문 내의 변수와 제곱한 변수(i**2)를 dictionary에 update로 집어넣는다.
#6. 출력한다.
number = int(input(''))
dic = {}
for i in range(1, number + 1):
dic.update({i:i**2})
print(dic)
|
9004598c263ab24da4001ee2fe6db9432b84438d | DannyShien/DC-python-exercise | /square.py | 188 | 3.78125 | 4 | # Print a Square
count_row = 0
while count_row < 5:
count_col = 0
while count_col < 5:
print('*', end = '')
count_col = count_col + 1
count_row = count_row + 1
print() |
ff82ac36280118a30c86d061da83898a789a9129 | FerCremonez/College-1st-semester- | /lista4e4.py | 171 | 3.765625 | 4 | cont=0
while (cont<10):
nota1=float(input('Primeira nota:'))
nota2=float(input('Segunda nota:'))
media=(nota1+nota2)/2
cont += 1
print(media)
|
db4a5e57ab78c686c5f3d4d278d2b91e094afe5f | Fizzor96/algo-vizsga | /3.Rendezés/osszefuttatas.py | 772 | 3.75 | 4 | sorozat1 = [3, 20, 5, 9, 10, 13, 11, 12, 16, 18, 17]
sorozat1.sort()
sorozat2 = [2, 1, 4, 8, 15, 7, 6, 14, 19]
sorozat2.sort()
def merge(arr1, arr2):
arr3=[0] * (len(arr1)+len(arr2))
i = j = 0
k=-1
while i < len(arr1) and j <len(arr2):
k=k+1
if arr1[i] < arr2[j]:
arr3[k]=arr1[i]
i=i+1
elif arr1[i] > arr2[j]:
arr3[k]=arr2[j]
j=j+1
else:
arr3[k]=arr1[i]
i=i+1
k=k+1
arr3[k]=arr2[j]
j=j+1
while i < len(arr1):
k=k+1
arr3[k]=arr1[i]
i=i+1
while j <len(arr2):
k=k+1
arr3[k]=arr2[j]
j=j+1
return arr3
mergedlist = merge(sorozat1, sorozat2)
print(mergedlist)
print("len of arr1:",len(sorozat1),", len of arr2: ",len(sorozat2),", len of mergedlist: ",len(mergedlist))
|
34e72efc3d0f0277b4fdbb006f13e19824b27e90 | hnm6500/csci141---python | /snowflake (2).py | 1,518 | 4.28125 | 4 | # Name : Hrishikesh Moholkar
# Draws a snowflake using turtle commands
import turtle
def star(S,N):
"""
:param S: lenght of snowflake
:param N: counter (depth)
:return:none
"""
if N<=0:
return 0
turtle.forward(S)
snowflake(S/3,N)
turtle.back(S)
turtle.left(60)
turtle.forward(S)
snowflake(S/3,N)
turtle.back(S)
turtle.left(60)
turtle.forward(S)
snowflake(S/3,N)
turtle.back(S)
turtle.left(60)
turtle.forward(S)
snowflake(S/3,N)
turtle.back(S)
turtle.left(60)
turtle.forward(S)
snowflake(S/3,N)
turtle.back(S)
turtle.left(60)
turtle.forward(S)
snowflake(S/3,N)
turtle.back(S)
turtle.left(60)
def snowflake(S,N):
"""
Draws the inner branches of snowflakes
:param S: length /3 of inner branches
:param N: counter >1
:return:none
"""
if N==1:
pass
else:
turtle.forward(S)
snowflake(S/3,N-1)
turtle.back(S)
turtle.left(60)
turtle.forward(S)
snowflake(S/3,N-1)
turtle.back(S)
turtle.left(60)
turtle.forward(S)
snowflake(S/3,N-1)
turtle.back(S)
turtle.left(120)
turtle.forward(S)
snowflake(S/3,N-1)
turtle.back(S)
turtle.left(60)
turtle.forward(S)
snowflake(S/3,N-1)
turtle.back(S)
turtle.left(60)
def main(S,N):
star(S,N)
input("Enter ")
main(S=int(input("enter length:")),N=int(input("enter N:")))
|
82e5ef5525bde7713c03c812e2eea31cd866caca | Robin-wang-long/python-study | /文本处理/检查word文档中的连续重复字/try1.py | 344 | 3.75 | 4 | from docx import Document
doc = Document('test.docx')
contents = ''.join((p.text for p in doc.paragraphs))
words = []
for index,ch in enumerate(contents[:-2]):
if ch == contents[index+1] or ch == contents[index+2]:
word = contents[index:index+3]
if word not in words:
words.append(word)
print(word)
|
8b9c55b52973bf6eb2c13431640fa530ef6b66e3 | irene-yi/Classwork | /Lesson5_Library.py | 979 | 3.984375 | 4 | class Car:
def __init__(self):
self.carFare = {'Hatchback': 30, 'Sedan': 50, 'SUV': 100}
def displayFareDetails(self):
print("Cost per day: ")
print("Hatchback: $",self.carFare['Hatchback'])
print("Sedan: $", self.carFare['Sedan'])
print("SUV: $", self.carFare['SUV'])
def calculateFare(self, type, days):
return self.carFare[type] * days
car = Car()
while True:
print("Enter 1: Fare details")
print("Enter 2: Rent a car")
print("Enter 3: Exit")
userChoice = (int(input()))
if userChoice is 1:
car.FareDetails()
elif userChoice is 2:
print("What type of car you want rent?")
typeOfCar = input()
print("How many days do you want to rent the car?")
numberOfDays = int(input())
fare = car.calculateFare(type, days)
print("Total amount: $",fare)
print("Thank you for shopping at Walmart!")
elif userChoice is 3:
quit()
|
882cf45a215630d3469b27d34f7aaa266fe5e773 | shubhamoy/project-euler-solutions | /python/problem3.py | 414 | 3.6875 | 4 | import math
def isPrime(n):
if n == 2: return 1
if n == 3: return 1
if n % 2 == 0: return 0
if n % 3 == 0: return 0
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return 0
i += w
w = 6 - w
return 1
n = 600851475143
b = math.sqrt(n)
i = 1
while(i<b):
if(isPrime(i) == 1):
if(n % i == 0):
print i
print '\n'
i = i+1
|
96d3787b0f6021fbe44f86af09966d85a5d272be | elena314/yandex-algos-training | /hw4/b.py | 806 | 3.71875 | 4 | import sys
from collections import Counter
def word_number(text):
result = []
words_counter = Counter()
for word in text.split():
result.append(words_counter[word])
words_counter.update([word])
return result
assert word_number('one two one tho three') == [0, 0, 1, 0, 0]
assert word_number('''She sells sea shells on the sea shore;
The shells that she sells are sea shells I'm sure.
So if she sells sea shells on the sea shore,
I'm sure that the shells are sea shore shells.''') == \
[0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 2, 2, 0, 0, 0, 0, 1, 2, 3, 3, 1, 1, 4, 0, 1, 0, 1, 2, 4, 1, 5, 0, 0]
assert word_number('aba aba; aba @?"') == [0, 0, 1, 0]
def main():
text = sys.stdin.read()
print(*word_number(text))
if __name__ == '__main__':
main()
|
50c013ae3cd3a0d10d95f85080f209e5451da9d8 | dreamofwind1014/gloryroad | /练习题/2020.06.05练习题--赵华恬.py | 2,322 | 3.953125 | 4 | # 练习106:画直角三角形(实心、空心)
# 实心
# for i in range(1, 7):
# print()
# for k in range(i):
# print("* ", end="")
# 空心
# for i in range(7):
# print()
# for k in range(i):
# if (i >= 3) and i <= 5:
# if k == 0 or k == i - 1:
# print("* ", end="")
# else:
# print(" ", end="")
# else:
# print("* ", end="")
# 练习107:要求实现一函数,该函数用于求两个集合的差集,
# 结果集合中包含所有属于第一个集合但不属于第二个集合的元素
# def diff_set(s1, s2):
# diff_set = []
# for v in s1:
# if v not in s2:
# diff_set.append(v)
# return set(diff_set)
#
#
# set_1 = {1, 2, 3, 4, 9}
# set_2 = {1, 2, 3, 5, 6, 7}
# print(diff_set(set_1, set_2))
# 练习108:找出一段句子中最长的单词及其索引位置,以list返回
# def find_max_length(ss):
# import string
# for c in ss:
# if c in string.punctuation:
# ss =ss.replace(c, " ")
# print(ss)
# max_length_word = sorted(ss.split(), key=len, reverse=True)[0]
#
# max_length_word_index = 0
# max_length = len(max_length_word)
# for i in range(len(ss)):
# if ss[i:i+max_length] == max_length_word:
# max_length_word_index = i
# return max_length_word, max_length_word_index
#
#
# s = "i am a good boy,huhongqiang!"
# print("最长的单词是%s,索引位置是%d" % find_max_length(s))
# 练习109:返回序列中的最大数
# def max_number(seq):
# import sys
#
# if not isinstance(seq, (list, tuple, str)):
# print("参数传入错误。")
# sys.exit(1)
# max_number = 0.0
# if isinstance(seq, str):
# for v in seq:
# if float(v) > max_number:
# max_number = float(v)
# else:
# for v in seq:
# if v > max_number:
# max_number = v
# return max_number
#
#
# print(max_number("123456"))
# print(max_number([1, 2, 3, 4, 5, 50]))
# print(max_number((1, 2, 3, 4, 5, 50)))
# 练习110:把一个字典的 key,value互换
# dict1 = {"a": 1, "b": 2}
# dict2 = {}
# for key, value in dict1.items():
# dict2[value] = key
# print(dict2)
# 共计61行代码
|
220c45819b6500aa21ebee6242eb0e6f581d858f | kunal-1308/Python | /functions_in_python/different_types_of_args.py | 881 | 3.5 | 4 | #!/usr/bin/python
def PositionalArgumentDemo(number1, number2):
print(number1, number2)
PositionalArgumentDemo(10, 20)
def DefaultArgumentDemo(num1, num2, num3 = 0, num4 = 0, num5 = 0):
print (num1+num2+num3+num4+num5)
DefaultArgumentDemo(10, 20, 30)
DefaultArgumentDemo(10, 20)
def KeywordArgumentDemo(number1, number3, number2):
print(number1, number2)
KeywordArgumentDemo(20, number2=10, number3=20)
def VariableArgumentsDemo(a,b,*args):
print(type(args))
for x in args:
print (x)
VariableArgumentsDemo(1,2)
VariableArgumentsDemo(1,3)
VariableArgumentsDemo(1,2)
VariableArgumentsDemo(1,2,3,4,5,6)
def VariableDictionaryArgumentsDemo(n1,n2,a,b,*args, **kwargs):
for x in args:
print(x)
for x in kwargs:
print(x, kwargs[x])
VariableDictionaryArgumentsDemo(1,2,20,10,1,2,3,4, name="Kunal", surname="Bhapkar", age="29")
|
f6e968477158eb982edc9dd6b99fb8bdfe38d508 | Lalesh-code/PythonLearn | /operations.py | 87 | 3.578125 | 4 |
def add (num1,num2):
print(num1+num2)
def mul(num1,num2):
print(num1*num2)
|
f055e90d6eba6787a0e78d1cccdaff13760874a9 | blemay360/CS-UY-1114 | /Homework/hw7/bl2448_hw7_q2.py | 3,307 | 3.515625 | 4 | #!/usr/bin/python3
'''
Brandon LeMay
CS 1114
bl2448
'''
# Part A
def clean_data(complete_weather_filename, cleaned_weather_filename):
read_file=open(complete_weather_filename, 'r');
write_file=open(cleaned_weather_filename, 'w');
print('City,Date,High,Low,Precipitation',file=write_file);
label=read_file.readline();
for line in read_file:
lst=line[0:len(line)-1].split(',');
if lst[8].isalpha() == True:
print(lst[0],lst[1],lst[2],lst[3],'0',sep=',',file=write_file)
else:
print(lst[0],lst[1],lst[2],lst[3],lst[8],sep=',',file=write_file)
read_file.close();
write_file.close();
# Part B
def f_to_c(f_temperature):
return (f_temperature-32)*(5/9)
def in_to_cm(inches):
return (inches/0.394)
def convert_data_to_metric(imperial_weather_filename, metric_weather_filename):
read_file=open(imperial_weather_filename, 'r');
write_file=open(metric_weather_filename, 'w');
print('City,Date,High,Low,Precipitation',file=write_file);
label=read_file.readline();
for line in read_file:
lst=line[0:len(line)-1].split(',');
print(lst[0],lst[1],f_to_c(int(lst[2])),f_to_c(int(lst[3])),in_to_cm(float(lst[4])),sep=',',file=write_file)
read_file.close();
write_file.close();
# Part C
def print_average_temps_per_month(city, weather_filename, unit_type):
read_file=open(weather_filename,'r');
label=read_file.readline();
high_averages=[0,0,0,0,0,0,0,0,0,0,0,0];
low_averages=[0,0,0,0,0,0,0,0,0,0,0,0];
months=[['January',0],['February',0],['March',0],['April',0],['May',0],['June',0],['July',0],['August',0],['September',0],['October',0],['November',0],['December',0]];
for line in read_file:
lst=line[0:len(line)-1].split(',');
lst[1]=lst[1].split('/');
if lst[0] == city:
high_averages[int(lst[1][0])-1]+=float(lst[2]);
low_averages[int(lst[1][0])-1]+=float(lst[3]);
months[int(lst[1][0])-1][1]+=1
print("\nAverage temperatures for ",city,':\n',sep='');
for i in range(12):
high_averages[i]=high_averages[i] / months[i][1];
low_averages[i]=high_averages[i] / months[i][1];
if unit_type == 'imperial':
print(months[i][0],': ',high_averages[i],'F High, ',low_averages[i],'F Low',sep='');
else:
print(months[i][0],': ',high_averages[i],'C High, ',low_averages[i],'C Low',sep='');
read_file.close();
# Part D
#How many days did New York have precipitation while the low was below 32F?
def possible_snow(city, weather_filename):
read_file=open(weather_filename, 'r');
label=read_file.readline();
counter=0;
for line in read_file:
lst=line[0:len(line)-1].split(',');
if float(lst[4]) != 0 and city == lst[0] and int(lst[3]) < 32:
counter+=1;
print("There were",counter,"days on record with a chance for snow");
read_file.close();
def main():
print ("Running Part A")
clean_data("weather.csv", "weather in imperial.csv")
print ("Running Part B")
convert_data_to_metric("weather in imperial.csv", "weather in metric.csv")
print ("Running Part C")
print_average_temps_per_month("San Francisco", "weather in imperial.csv", "imperial")
print_average_temps_per_month("New York", "weather in metric.csv", "metric")
print_average_temps_per_month("San Jose", "weather in imperial.csv", "imperial")
print ("Running Part D")
possible_snow('New York', "weather in imperial.csv");
main()
|
a389e3c0c0147cfb6e5cdc814cb8340f36644f7e | andiaprian/excercise2 | /fundamental-03.py | 999 | 3.734375 | 4 | """
Tipe data dictionary sekedar menghubungkan antara KEY dan VALUE
KVP = Key Value Pair
dictionary = kamus
"""
#comment bisa diganti dengan double """""
kamus = {}
kamus['anak'] = 'son'
kamus['istri'] = 'wife'
kamus['ayah'] = 'father'
kamus['ibu'] = 'mother'
print(kamus)
print(kamus['ayah'])
print(kamus['ibu'])
#Contoh Kasus
print('\nData ini dikirimkan oleh server Gojek, untuk memberikan info driver disekitar pemakai aplikasi')
data_dari_server_gojek = {
'tanggal': '2020-06-10',
'driver_list': [
{'nama': 'Eko', 'jarak': 10},
{'nama': 'Dwi', 'jarak': 50},
{'nama': 'Tri', 'jarak': 150},
{'nama': 'Catur', 'jarak': 200}
]
}
print(data_dari_server_gojek)
print(f"\nDriver disekitar sini {data_dari_server_gojek['driver_list']}")
print(f"Driver #1 {data_dari_server_gojek['driver_list'][0]}")
print(f"Driver #4 {data_dari_server_gojek['driver_list'][3]}")
print(f"Jarak driver #1 adalah {data_dari_server_gojek['driver_list'][0]['jarak']} meter")
|
baad00fb7eb3c2cc34e21d63bdd4d4d155e88d1d | Jihan-Jung/python_cookbook_study | /10주차/ch14_code/14_3.py | 1,082 | 3.609375 | 4 | import unittest
def parse_int(s):
return int(s)
class TestConversion(unittest.TestCase):
def test_bad_int(self):
self.assertRaises(ValueError, parse_int, 'not_number')
def test_bad_int_with_value(self):
self.assertRaisesRegex(ValueError, ".* 'not_number'", parse_int, 'not_number')
# assertEqual을 써서 예외를 테스트하려면 coner case 처리가 필요해서 이렇게 구질구질해진다
def test_bad_by_assertEqual(self):
try:
r = parse_int('a')
except ValueError as e:
self.assertEqual(type(e), ValueError)
else:
self.fail('ValueError not raised')
# context manager로도 사용할 수 있다!
def test_bad_by_multiple_step(self):
with self.assertRaisesRegex(ValueError, 'invalid literal .*'):
r = parse_int('N/A')
with self.assertRaises(ValueError):
r = parse_int('N/A')
if __name__ == '__main__':
unittest.main()
|
e0545fdaab9f02d41bc51ead130b07b575111d5e | Mitsz/Universidade | /tela/telaprofessor.py | 1,222 | 3.96875 | 4 |
class TelaProfessor():
def __init__(self):
pass
def tela_aluno(self):
print('----- ALUNO -----')
print('ESCOLHA O NÚMERO DA OPÇÃO QUE DESEJA REALIZAR')
print('1 - Cadastrar aluno')
print('2 - Excluir aluno')
print('3 - Modificar aluno')
print('4 - Lista de alunos')
print('0 - Retornar')
opcao = (input('Escolha a opção: '))
while True:
if opcao is not int:
raise ValueError
else:
return opcao
def cadastra_aluno(self):
print('Você escolheu cadastrar aluno')
print('Preencha os campos a seguir')
nome = input('Nome: ')
data_nasc = input('Data de Nascimento: ')
matricula = input('Matrícula: ')
return {
'nome': nome,
'idade': data_nasc,
'matricula': matricula
}
def excluir_aluno(self):
print('Você escolheu excluir aluno')
print('Preencha a matrícula do aluno que deseja excluir do sistema')
codigo = input('Matrícula: ')
return codigo
def lista_alunos(self):
print('Você escolheu listar os alunos cadastrados')
|
9ef08d21e0b56e9d3b00b778c654062a5bf6e89a | DayGitH/Python-Challenges | /DailyProgrammer/DP20140721A.py | 1,855 | 3.84375 | 4 | """
[7/21/2014] Challenge #172 [Easy] ■■□□□▦■□
https://www.reddit.com/r/dailyprogrammer/comments/2ba3g3/7212014_challenge_172_easy/
#Description
A portable bitmap is one of the oldest image formats around and grants access to very simple image creation and
sharing. Today, you will be creating an image of this format.
A simple PBM program can be seen [here] (http://en.wikipedia.org/wiki/Netpbm_format)
(Note that we'll be creating the simplest version, a PBM, not PPM or PGM.)
But basically the program consists of the following:
* A 2byte string (usually 'P1') denoting the file format for that PBM
* 2 integers denoting the Width and Height of our image file respectively
* And finally, our pixel data - Whether a pixel is 1 - Black or 0 - White.
#Formal Inputs & Outputs
##Input description
On standard console input you should be prompted to enter a small piece of text ("programming", "proggit", "hello
world" etc...)
##Output description
The output will be a .PBM file consiting of an image which contains the text you have entered
#Notes
/u/chunes has kindly mapped all alpha characters to their 0 1 equivalents, saving you a lot of time.
https://gist.github.com/anonymous/0ce707518d9e581499f5
Here is a worthwhile tutorial on the PBM format and programming for it
http://blog.plover.com/prog/perl/lines.html
The .PBM (you may also see it called NetPBM) is not very well supported any more, this makes actually viewing the PBM
difficult as not many programs support it.
Feel free to download software which would render your .PBM to the screen but for all intents and purposes, the format
is more important than the output cosidering the difficulty of viewing the image.
#Finally
Have a good challenge idea?
Consider submitting it to /r/dailyprogrammer_ideas
"""
def main():
pass
if __name__ == "__main__":
main()
|
ce3c12182379859ae88182f9af496d3d05a06d67 | bellyflopp/Six-Degrees-of-Bacon | /src/kb_bfs_priority.py | 5,970 | 3.734375 | 4 | """
Six Degrees of Kevin Bacon
Author: Chris Lim
Date: 2/28/18
This intelligent agent determines how far a given individual is from following
Kevin Bacon on Twitter. The agent is limited to using the search() function
from the Twython API.
"""
import sys
from collections import deque
from threaded_twitter_wrapper import TwitterConnection
# open connection to Twitter API
TWITTER = TwitterConnection()
KEVIN_BACON = 'Kevin Bacon'
TWEET_TEXT = 'full_text'
VERIFIED = 'verified'
UNVERIFIED = 'unverified'
# "The average Bacon number is 2.955. Using one of the actors
# with the highest known finite Bacon number (7), William Rufus Shafter as
# the centre of the acting universe instead of Bacon, we can find two
# actors with a Rufus Shafter number of 15." - Wikipedia
SHAFTER_LIMIT = 15
def __contains_kevin_bacon__(tweet):
"""
Check if a tweet contains Kevin Bacon, Kevin_Bacon, or KevinBacon (case
insensitive).
Args:
tweet: tweet text
Return:
True if the tweet text contains a form of "Kevin Bacon"
"""
tweet_text = tweet.lower()
if "kevin bacon" in tweet_text:
return True
if "kevin_bacon" in tweet_text:
return True
if "kevinbacon" in tweet_text:
return True
return False
def __generate_path__(seen, user):
"""
Generates the path to a user.
Args:
seen: dictionary of seen users and their predecessors
user: user generate the path from
Return:
A list of the path from the user to the parent node
"""
path_to_bacon = []
while user:
predecessor = seen[user]
if predecessor:
path_to_bacon.append(predecessor)
user = predecessor[0]
else:
break
return reversed(path_to_bacon)
def __search_queue__(search_queue, seen):
"""
Searches a dictionary of queues and checks to see if Kevin Bacon exists.
If Kevin Bacon is found, return True and the path to get to him, otherwise
check if the tweet is a retweet of a verified user and add that user to the
verified stack. If not, add any mentioned users to the queue. Repeat until
Kevin Bacon is found or the queues are empty.
Args:
search_queue: a dictionary of queues containing the users to search
through
seen: a dictionary containing what twitter users have been seen and
their predecessor
Returns:
True if Kevin Bacon has been found, and the path used to reach him
"""
while search_queue[VERIFIED] or search_queue[UNVERIFIED]:
# get the current user to search
if search_queue[VERIFIED]:
current_user = search_queue[VERIFIED].popleft()
else:
current_user = search_queue[UNVERIFIED].popleft()
# queries twitter
query = "from:%s" % current_user
tweets = TWITTER.search_twitter(query)
# search through current users tweets
try:
for tweet in tweets['statuses']:
if __contains_kevin_bacon__(tweet[TWEET_TEXT]):
# mark Kevin Bacon as seen and generate path to him
seen[KEVIN_BACON] =\
(current_user, tweet['id'], tweet[TWEET_TEXT])
path_to_kevin_bacon = __generate_path__(seen, KEVIN_BACON)
return True, path_to_kevin_bacon, search_queue, seen
try:
# find verified retweeted user and add to queue
if tweet['retweeted_status']['user']['verified']:
retweeted_user =\
tweet['retweeted_status']['user']['screen_name']
if retweeted_user in seen:
continue
# generate path and add retweeted user to seen
path_to_mention =\
(current_user, tweet['id'], tweet[TWEET_TEXT])
seen[retweeted_user] = path_to_mention
search_queue[VERIFIED].append(retweeted_user)
except (TypeError, KeyError):
pass
# search for mentions to add to queue
for mention in tweet['entities']['user_mentions']:
mentioned_user = mention['screen_name']
if mentioned_user in seen:
continue
# generate path to mentioned user and add to seen
path_to_mention =\
(current_user, tweet['id'], tweet[TWEET_TEXT])
seen[mentioned_user] = path_to_mention
search_queue[UNVERIFIED].append(mentioned_user)
except TypeError:
pass
return False, [], search_queue, seen
def search_for_kevin_bacon(start):
"""
Creates a dictionary of queues starting with a given user and executes a
search. If Kevin Bacon is found return the search results.
Args:
start: a twitter user to start searching for Kevin Bacon from
Returns:
The path to get to Kevin Bacon unless none is found
"""
search_queue = {
VERIFIED: deque(),
UNVERIFIED: deque()
}
search_queue[UNVERIFIED].append(start)
seen = {start: None}
found, search_results, search_queue, seen = \
__search_queue__(search_queue, seen)
if found:
return search_results
print 'No connection to Kevin Bacon'
sys.exit(0)
def main():
""" main function to execute to run agent """
if len(sys.argv) != 2:
sys.exit("Invalid Argument Exception\n" + \
"Usage: python2 kb.py <twitter_user>")
# connection to Twitter API
TWITTER.connect_to_twitter()
# prints resutls of search
for tweet in search_for_kevin_bacon(sys.argv[1]):
user, tweet_id, tweet_text = tweet
print "%s, %d, %s" % (user, tweet_id, tweet_text)
if __name__ == '__main__':
main()
|
c9583f57f600802c839958bd95f4117e3af42347 | nsanthony/super-fortnight | /wwk/py/actions/attack.py | 1,326 | 3.703125 | 4 | #! /Users/nsanthony/miniconda3/bin/python
from people.people_list import people_list
def attack(location,option=None):
"""Used to attack, still needs definitions other than text out."""
pc = people_list['pc']
if option == None:
print()
print('You are able to attack:')
for keys in location.people:
print(location.people[keys].name)
print()
print('What would you like to attack?')
k = input()
for keys in people_list:
if people_list[keys].name == k:
opponent = people_list[keys]
else:
for keys in people_list:
if people_list[keys].name == option:
opponent = people_list[keys]
damage = pc.weapon.damage
print()
# print('raw',damage)
opp_dam_red = opponent.armor
# print('damage reduction',opp_dam_red)
dam_delt = damage - opp_dam_red
# print('actual damage delt',dam_delt)
if dam_delt <= 0:
dam_delt = 0
print('Weapon Ineffective')
if opponent.health <= 0:
dam_delt = 0
print(opponent.name,'is already dead')
else:
opponent.health -= dam_delt
print(opponent.name,'took',dam_delt,'damage')
if opponent.health == 0:
print(opponent.name,'died')
return location |
073b4a8e0206680a53bd12611753eb972aa1bd1d | dgeoffri/adventofcode | /2021/day01a.py | 395 | 3.6875 | 4 | #!/usr/bin/python3
with open('day01.txt', 'r') as inputfile:
increased_count = 0
last_measurement = int(inputfile.readline())
for measurement_line in inputfile:
measurement = int(measurement_line)
if measurement > last_measurement:
increased_count += 1
last_measurement = measurement
print("Depth increased {} times".format(increased_count))
|
7986307e06c8ba03dba143839e323a41d2d1ac70 | vintage-coder/Python-Learning-Codes | /Algorithms/Sorting/mergesort.py | 941 | 4 | 4 | import random
def mergeSort(alist):
print("Spiliting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf=alist[:mid]
righthalf=alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
# alist =[13,2,17,76,82,12,7]
randomlist=random.sample(range(1,100),50)
print('before sorting: ',randomlist)
mergeSort(randomlist)
print('after sorting: ',randomlist)
|
25a8a822e27b9f5be016dcd7aff6b58acea66fd1 | slavafive/Algorithms | /python/codeforces_itmo/z_function/practice1/B.py | 487 | 3.6875 | 4 | def is_prefix(pattern, str):
return pattern == str[0:len(pattern)]
def is_suffix(pattern, str):
return pattern == str[len(str) - len(pattern):len(str)]
def get_answer(str):
answer = 0
for i in range(len(str)):
for j in range(i + 1, len(str) + 1):
pattern = str[i:j]
if is_prefix(pattern, str) != is_suffix(pattern, str):
answer += 1
return answer
n = int(input())
for i in range(n):
print(get_answer(input())) |
a75e429c725b67aecdd7382ed5dfe09694e0de1c | eempc/PythonScripts | /imageResize.py | 461 | 3.515625 | 4 | #!python3.7
import os
from PIL import Image
imageFiles = ('.png', 'jpg', 'jpeg', 'gif')
def resizeAllImagesInDir(dir):
entriesList = os.listdir(dir)
for entry in entriesList:
fullPath = dir + "/" + entry
if os.path.isfile(fullPath) and entry.lower().endswith(imageFiles):
print("Image file found: " + fullPath)
image = Image.open(fullPath)
width, height = image.size
print(width, height) |
9e08a2479dcbff18f253e232a84ea8a5810e32f1 | yeonsooSo/python_study | /week1.py | 758 | 3.796875 | 4 | from random import *
a = randint(1, 6)
b = randint(1, 6)
print("주사위 던지기")
print(f"주사위 1: {a}")
print(f"주사위 2: {b}\n")
print("실행할 연산의 종류를 입력하세요.")
print("1. 덧셈 2. 뺄셈 3. 곱셈 4. 나눗셈 5. 나머지 구하기")
option = input("연산 종류: ")
if(option == "1"):
ans = a + b
print(f"덧셈 결과 : {ans}")
elif(option == "2"):
ans = a - b
print(f"뺄셈 결과 : {ans}")
elif(option == "3"):
ans = a * b
print(f"곱셈 결과 : {ans}")
elif(option == "4"):
ans = a / b
print(f"나눗셈 결과 : {ans}")
elif(option == "5"):
ans = a % b
print(f"나머지 구하기 결과 : {ans}")
print("\n별찍기")
for i in range(ans):
print("*"*(i+1))
|
c6e6946fba40ab8e8149ffdbed0cf1ed517fd947 | CarolShiny/Estudo-Python | /lista.py | 511 | 3.609375 | 4 | import bibListas
##numeros = [-40,-8,-5,-9]
##resultado = bibListas.somaLista(numeros)
##
##print("o resultado da soma é", resultado)
##
##for i in numeros:
## resultado = bibListas.maiorLista(numeros)
##
##print("O maior número é", resultado[-1])
Idade = []
quant = int(input("Quantas idades vai colocar?"))
for i in range (quant):
idades = int(input("Digite uma idade:"))
Idade.append(idades)
resultado = bibListas.somaLista(Idade)
media = resultado / quant
print(media)
|
ad14dc6c682493bda752117510be77bc14c16db2 | xander27481/informatica5 | /07b - iteraties Fortus/Hoger lager (zonder seed).py | 526 | 3.546875 | 4 | ############################### SEED WAS ANDERS ###########################
import random
random.seed(1)
# start waarden
getal = 18
gok = 0
gok_keer = 0
van = 1
tot = 100
gokken = [73, 9, 26, 13, 21, 20, 17, 19, 18]
# programma
while gok != getal:
gok = gokken[gok_keer]
print('[{},{}] --> computer gokt {}'.format(van, tot, gok))
if gok < getal:
van = gok + 1
else:
tot = gok - 1
gok_keer += 1
print('computer had {} pogingen nodig om het getal {} te raden.'.format(gok_keer, getal))
|
a8ae135a0ae1cb6aee564c754b20e4cb6542aace | Aikyo/python | /python_interview/basic_conception/b13_set.py | 302 | 3.8125 | 4 |
"""
set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
参数说明
• iterable – 可迭代对象对象;
"""
x = set("iamkiko")
y = set("heisherman")
print(x)
print(y)
print(x&y)
print(x|y)
print(x-y)
|
020ce18c50018d43de2710eb5fe540049aed142d | Techdread/python-course | /mprogram.py | 78 | 3.625 | 4 | age = input("Enter your age: ")
new_age = int(age) + 50
print(new_age)
|
be8f8b23ebe79b3d782a2b1ff04e20936ead98fb | monkey-hjy/LeetCode | /4-寻找两个有序数组的中位数/寻找两个有序数组的中位数.py | 837 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/3/14 21:24
# @Author : Monkey
# @File : ClassCreate.py
# @Software: PyCharm
# @Demand :
'''
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
nums = sorted(nums1 + nums2)
if len(nums) % 2 == 0:
# return float((nums[len(nums)//2-1] + nums[len(nums)//2]) / 2)
print((nums[len(nums)//2-1] + nums[len(nums)//2]) / 2)
else:
# return float(nums[len(nums) // 2])
print(nums[len(nums) // 2])
|
b83f9096eddbfd0717a8f9c65d9ddb18d7b8e95f | alexandraback/datacollection | /solutions_5738606668808192_0/Python/Orangerobber/q3.py | 889 | 3.6875 | 4 | import sys
from math import sqrt
T = int(sys.stdin.readline().strip())
def divisor(n):
for j in range(2,int(sqrt(n))+1):
if n % j == 0:
return j
return None
def bin2base(bin,base):
return sum([base**i * bin[i] for i in range(len(bin))])
def check_coin(coin):
isGood = True
divisors = []
for base in range(2, 11):
d = divisor(bin2base(coin,base))
if d is None:
return None
divisors.append(d)
return divisors
def loop_coins(N,J):
count = 0
current = 0
while count < J:
binary = ('1{0:0%db}1'%(N-2)).format(current)
coin = [int(x) for x in reversed(binary)]
divisors = check_coin(coin)
if divisors is None:
current += 1
continue
else:
count += 1
print binary,
for d in divisors:
print d,
print ""
current += 1
for t in range(T):
N,J = [int(x) for x in sys.stdin.readline().strip().split()]
print "Case #1:"
loop_coins(N,J)
|
490e2d8ed45a282fb57982d5c82d48338926b27c | prasoonsoni/Python-Questions-1st-Semester | /Strings/python programme to form a new string made of first 2 and last 2 characters .py | 106 | 3.984375 | 4 | """python program to check if string is a panagram orr not"""
a = "my name is prasoon"
a.replace(" ", "") |
a1ee54e5683c682d89179d279cd04640fbb631f2 | devndevs/crash_course | /Chapter_4/4-3.py | 308 | 4.34375 | 4 | odd_numbers = range(1, 21, 2)
for odd in odd_numbers:
print(odd)
print()
by_three = range(3, 31, 3)
for three in by_three:
print(three)
print()
squares = []
for value in range(1, 11):
squares.append(value ** 3)
print(squares)
print()
cubes = [value ** 3 for value in range(1, 11)]
print(cubes) |
6e8b69a898226abb4a4afbfa075e7aa62ff1acbe | Python-aryan/Hacktoberfest2020 | /Python/rollingTheDice.py | 242 | 4.15625 | 4 | import random
minNumber = 1
maxnumber = 6
emptyString = ""
while emptyString == "":
print ("the number is:");
print (random.randint(minNumber,maxnumber));
emptyString = input("would you like to roll the dice again? Press enter") |
82ce3692cbcbbcffd80a4c6ed62b016b97dbb9ca | juliaodds18/PythonTest | /DistanceFromARectangle.py | 3,866 | 4.0625 | 4 | import math
class Point(object):
def __init__(self, init_x=0.0, init_y=0.0):
self.x = init_x
self.y = init_y
class Rectangle(object):
def __init__(self, bottom_left_x=0.0, bottom_left_y=0.0, init_width=0.0, init_height=0.0):
self.bottom_left = Point(bottom_left_x, bottom_left_y)
self.width = init_width
self.height = init_height
def is_point_within_dist_of_rect(rect=Rectangle(), point=Point(), dist=0.0):
# TO DO: implement
# Return value should be True or False.
# TO DO: Check if point falls within dist of rec
# Check if point is within dist of rectangle's x-coordinates
dist_left = Point(rect.bottom_left.x - dist, rect.bottom_left.y)
dist_right = Point(rect.bottom_left.x + rect.width + dist, rect.bottom_left.y)
if (point.x >= dist_left.x and point.x <= dist_right.x):
# Point is definitely within the x-coordinate bound, need edge cases to check distance for corner points
# First, check point outside left x-boundary
if (point.x <= rect.bottom_left.x):
# Need to find the point with the minimum and maximum y-values possible
# Using a variant of the formula to find distance between points: Sqrt((x2 - x1)^2 + (y2 - y1)^2)
x_dist = rect.bottom_left.x - point.x
min_y = rect.bottom_left.y - math.sqrt(dist**2 - x_dist**2)
max_y = rect.bottom_left.y + rect.height + math.sqrt(dist**2 - x_dist**2)
if (point.y >= min_y and point.y <= max_y):
return True
else:
return False
# Next, check point outside right x-boundary
elif (point.x >= rect.bottom_left.x + rect.width):
# Again, find points with maximum and minimum y-values possible
x_dist = point.x - rect.bottom_left.x - rect.width
min_y = rect.bottom_left.y - math.sqrt(dist**2 - x_dist**2)
max_y = rect.bottom_left.y + rect.height + math.sqrt(dist**2 - x_dist**2)
if (point.y >= min_y and point.y <= max_y):
return True
else:
return False
# Lastly, check if the point is within x-boundaries
else:
x_dist = rect.bottom_left.x + rect.width - point.x
min_y = rect.bottom_left.y - dist
max_y = rect.bottom_left.y + dist
if (point.y >= min_y and point.y <= max_y):
return True
else:
return False
else:
return False
# Test cases
rect = Rectangle(0.0, 0.0, 1.0, 1.0)
point = Point(0.0, 0.0)
print("Point: (0.0, 0.0), Expected: True")
print(is_point_within_dist_of_rect(rect, point, 1.0))
point = Point(1.0, 1.0)
print("Point: (1.0, 1.0), Expected: True")
print(is_point_within_dist_of_rect(rect, point, 1.0))
point = Point(0.5, 0.5)
print("Point: (0.5, 0.5), Expected: True")
print(is_point_within_dist_of_rect(rect, point, 1.0))
point = Point(2.0, 2.0)
print("Point: (2.0, 2.0), Expected: False")
print(is_point_within_dist_of_rect(rect, point, 1.0))
point = Point(-0.7, -0.7)
print("Point: (-0.7, -0.7), Expected: True")
print(is_point_within_dist_of_rect(rect, point, 1.0))
point = Point(-0.8, -0.8)
print("Point: (-0.8, -0.8), Expected: False")
print(is_point_within_dist_of_rect(rect, point, 1.0))
point = Point(1.7, -0.7)
print("Point: (1.7, -0.7), Expected: True")
print(is_point_within_dist_of_rect(rect, point, 1.0))
point = Point(1.8, -0.8)
print("Point: (1.8, -0.8), Expected: False")
print(is_point_within_dist_of_rect(rect, point, 1.0))
point = Point(1.7, 1.7)
print("Point: (1.7, 1.7), Expected: True")
print(is_point_within_dist_of_rect(rect, point, 1.0))
point = Point(1.8, 1.8)
print("Point: (1.8, 1.8), Expected: False")
print(is_point_within_dist_of_rect(rect, point, 1.0))
point = Point(-0.7, 1.7)
print("Point: (-0.7, 1.7), Expected: True")
print(is_point_within_dist_of_rect(rect, point, 1.0))
point = Point(-0.8, 1.8)
print("Point: (-0.8, 1.8), Expected: False")
print(is_point_within_dist_of_rect(rect, point, 1.0))
|
91c9551c4084591d74a33e72799dc6424933175e | Mr-Monster-0248/Hangman | /Text Files/functions.py | 2,097 | 4.4375 | 4 | import random
#Display the number of words and the number of characters in a file
def numberOfWords():
"""Display the number of words and the number of characters in a file"""
characters = 0
number_w = 0
with open("test.txt", "r") as my_file:
for word in my_file:
characters = characters + len(word[:-1]) #to avoid \n character
number_w += 1
print("There is {} words and {} characters in the file".format(number_w, characters))
#This function will be used in the next one
def occurences(my_list, toFind):
occu = 0
for word in my_list:
if(word == toFind):
occu += 1
return occu
#Display all the words in the alphabetical order,
#each followed by its number of occurences in the file
def display_word_and_occurrences():
"""
Display all the words in the alphabetical order,
each followed by its number of occurences in the file
"""
with open("test.txt", "r") as my_file:
wordList = my_file.read().strip().split("\n")
wordList.sort()
for word in wordList:
print("{word} : {occu}".format(word = word, occu = occurences(wordList, word)))
#Convert the letters of the file to all uppercase
def uppercase():
"""Convert the letters of the file to all uppercase"""
with open("test.txt", "r") as my_file:
wordList = my_file.read().strip()
with open("test2.txt", "w") as my_file:
my_file.write(wordList.upper())
#Randomly chose a word from the file
def randWord():
with open("test.txt", "r") as my_file:
wordList = my_file.read().strip().split("\n")
return random.choice(wordList)
#From a given word w1, get a letter from the user and search it in the word.
#If the letter exist, the program then display a word w2 of the same length as w1
#where w2[i] = _ if w1[i] != l
#and w2[i] = l if w1[i] == l
def displayLetter(word, letter):
toDisp = list()
for i in range(len(word)):
if(word[i] == letter):
toDisp.append(letter)
else:
toDisp.append("_")
return "".join(toDisp)
|
40aa4689761dff267ddf8779a9ad0da890994305 | ahmadfaig/UdemyML | /Machine Learning A-Z Template Folder/Other/House/regression.py | 650 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('data.csv',header=None)
dataset_test = pd.read_csv('test.csv',header=None)
X = dataset.iloc[:, 0:2].values
y = dataset.iloc[:, 2].values
X_test = dataset_test.iloc[:, 0:2].values
#F,N = map(int, input().split())
#train = np.array([input().split() for _ in range(N)], float)
#T = int(input())
#test = np.array([input().split() for _ in range(T)], float)
#
#X = train[:, :-1]
#y = train[:, -1]
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X, y)
y_pred = regressor.predict(X_test)
|
672d71e172c973a2834edd44acd70924651e0520 | kmid5280/python_pirate_drink | /python_pirate_drink.py | 2,696 | 3.84375 | 4 | from questions import questions
from ingredients import ingredients
responses = {}
ingredient_results = []
def pirate_drink():
"""This function asks the user questions about their drink from the questions dictionary, and if the user answers yes, will output the drink's ingredients according to the ingredients dictionary."""
strong = ''
salty = ''
bitter = ''
sweet = ''
fruity = ''
while strong not in ("y","n", "yes", "no"):
strong = input(questions["strong"])
if strong == 'y' or strong == 'yes':
responses['strong'] = True
print("Adding strong ingredients then.")
elif strong == 'n' or strong == 'no':
responses['strong'] = False
print('No strong then.')
else:
print("y or n")
while salty not in ("y","n", "yes", "no"):
salty = input(questions["salty"])
if salty == 'y' or salty == 'yes':
responses['salty'] = True
print("Adding salty ingredients then.")
elif salty == 'n' or salty == 'no':
responses['salty'] = False
print('No salty then.')
else:
print("y or n")
while bitter not in ("y","n", "yes", "no"):
bitter = input(questions["bitter"])
if bitter == 'y':
responses['bitter'] = True
print("Adding bitter ingredients then.")
elif bitter == 'n':
responses['bitter'] = False
print('No bitter then.')
else:
print("y or n")
while sweet not in ("y","n", "yes", "no"):
sweet = input(questions["sweet"])
if sweet == 'y':
responses['sweet'] = True
print("Adding sweet ingredients then.")
elif sweet == 'n':
responses['sweet'] = False
print('No sweet then.')
else:
print("y or n")
while fruity not in ("y","n", "yes", "no"):
fruity = input(questions["fruity"])
if fruity == 'y':
responses['fruity'] = True
print("Adding fruity ingredients then.")
elif fruity == 'n':
responses['fruity'] = False
print('No fruity then.')
else:
print("y or n")
def return_ingredients():
"""This function adds necessary ingredients to the drink based on the user's responses."""
if responses['strong'] == True:
ingredient_results.extend(ingredients['strong'])
if responses['salty'] == True:
ingredient_results.extend(ingredients['salty'])
if responses['bitter'] == True:
ingredient_results.extend(ingredients['bitter'])
if responses['sweet'] == True:
ingredient_results.extend(ingredients['sweet'])
if responses['fruity'] == True:
ingredient_results.extend(ingredients['fruity'])
print("Your total ingredients are: ", ingredient_results)
if __name__ == '__main__':
pirate_drink()
return_ingredients() |
4e06132826171e4ebb3e464137d8c02e44d84d5e | dbialon/LeetCode | /length_of_last_word.py | 540 | 4.03125 | 4 | # https://leetcode.com/problems/length-of-last-word/
# given a string s consists of upper/lower-case alphabets
# and empty space characters ' ', return the length of
# last word (last word means the last appearing word
# if we loop from left to right) in the string.
# if the last word does not exist, return 0.
def lengthOfLastWord(s: str) -> int:
while len(s) > 0 and s[-1] == " ":
s = s[:-1]
if len(s) == 0:
return 0
aString = s.split(' ')
return len(aString[-1])
my_string = "a b "
print(lengthOfLastWord(my_string)) |
a64017d90ac942c1039805a7461e91a7fd49ea25 | yoonj98/python-for-coding-test | /Chapter12/String_Resort.py | 259 | 3.5 | 4 | # 문자열 재정렬 (322p)
data = input()
res = []
value = 0
for i in data:
if i.isalpha(): # 알파벳인 경우
res.append(i)
else:
value += int(i)
res.sort()
if value != 0:
res.append(str(value))
print(''.join(res)) |
e10af7dfce52fef593a6cfd47778938b41542499 | yuchien302/LeetCode | /leetcode291.py | 1,178 | 3.65625 | 4 | class Solution(object):
def wordPatternMatchHelper(self, pattern, s, dict, words):
if pattern == "" and s == "":
return True
elif pattern == "" or s == "":
return False
elif pattern[0] in dict:
if not s.startswith(dict[pattern[0]]):
return False
else:
return self.wordPatternMatchHelper(pattern[1:], s[len(dict[pattern[0]]):], dict, words)
else:
for i in range(1, len(s)+1):
if s[:i] not in words:
dict[pattern[0]] = s[:i]
words.add(s[:i])
if self.wordPatternMatchHelper(pattern[1:], s[len(dict[pattern[0]]):], dict, words):
return True
else:
words.remove(s[:i])
del dict[pattern[0]]
return False
def wordPatternMatch(self, pattern, s):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
dict = {}
words = set()
return self.wordPatternMatchHelper(pattern, s, dict, words)
|
c49cd211dfd0fe3e16ccaa5ebf48d2ed32c21bb6 | dengxiaohao/Sword-refers-to-offer | /剑指offer/字符串/1.py | 456 | 3.640625 | 4 | '''
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
'''
class Solution:
def StrToInt(self, s):
try:
return int(s)
except Exception as e:
return 0 |
1019b5d0a833dfb438b13c45a0e2d98811cd4c9e | kouritron/parkinglot_problem | /parkinglot.py | 14,232 | 3.734375 | 4 |
import time
# utility time reading functions
class TimeHelper(object):
# this helps us do things like advance time by an hour, instead of singleton just use class vars and methods.
_simulated_elapsed_time = 0
@classmethod
def get_time(cls):
""" Return the number of seconds that have passed since Jan 1 1970 as an int. """
seconds_since_jan1_1970 = int(time.time())
return seconds_since_jan1_1970 + cls._simulated_elapsed_time
@classmethod
def advance_time(cls, seconds_to_advance_by):
""" Advance time by as many seconds as the supplied argument. so that a future call to get_time()
returns time values advanced by this much.
"""
assert isinstance(seconds_to_advance_by, int)
cls._simulated_elapsed_time += seconds_to_advance_by
class LotSize(object):
""" Enumerate different lot sizes. Python 2.7 does not have built in enums,
so this is the closest thing I could find. """
# maintain increasing order for easy comparison (i.e. assert small < medium)
SMALL = 1
MEDIUM = 2
LARGE = 3
Sizes = {SMALL, MEDIUM, LARGE}
class Car(object):
def __init__(self, plate, model, size):
""" Initialize a new car with the given, plate, model, and size information """
super(Car, self).__init__()
assert isinstance(plate, str)
assert isinstance(model, str)
assert size in LotSize.Sizes
self._plate = plate
self._model = model
self._size = size
def get_size(self):
return self._size
def __str__(self):
result = "Car with plate: " + str(self._plate) + " model: " + str(self._model)
if LotSize.SMALL == self._size:
return "Small " + result
elif LotSize.MEDIUM == self._size:
return "Medium " + result
elif LotSize.LARGE == self._size:
return "Large " + result
else:
return "Unknown sized " + result
class LotGroup(object):
""" Track a group of lots of the same size. handle allocating/free lots from this group. """
def __init__(self, lots_count, size, hourly_rate):
""" Initialize a new lot group with the given number of lots of the given size with the hourly price. """
super(LotGroup, self).__init__()
assert isinstance(lots_count, int)
assert isinstance(hourly_rate, int)
assert (size in LotSize.Sizes)
# we can allow empty lot group even though it probably has no use.
assert lots_count >= 0
self._lot_count = lots_count
self._size = size
self._hourly_rate = hourly_rate
# lot allocation table: sparse hash table of (lot_id, car object)
# lot_id is just an int in xrange(0, lot_count)
# if a lot_id does not exist as a key in this table, then that lot_id is free.
# when a car leaves a lot that row should be deleted from this table. so that len(self.lots) returns
# the number of cars in this lot group.
self._lots = {}
def __str__(self):
""" Return a string representation of this lot group. """
size_class_str = None
if self._size == LotSize.SMALL:
size_class_str = "Small"
elif self._size == LotSize.MEDIUM:
size_class_str = "Medium"
elif self._size == LotSize.LARGE:
size_class_str = "Large"
else:
size_class_str = "Unknown size"
lg_state = "********** lot group with size class: " + size_class_str + "\n"
lg_state += "with number of spots: " + str(self._lot_count) + "\n"
lg_state += "with rate of: " + str(self._hourly_rate) + " dollar(s) per hour. \n"
if len(self._lots):
lg_state += "cars parked in this lot group are: \n"
for car in self._lots.itervalues():
lg_state += "++" +str(car) + "\n"
else:
lg_state += 'no cars parked in this lot group. \n'
return lg_state
def get_spot_count(self):
return self._lot_count
def get_size_class(self):
return self._size
def has_space(self):
""" Return True if this lot group has space for at least one more car that can fit in this group.
Otherwise return False. """
if len(self._lots) < self._lot_count:
return True
else:
return False
def can_fit(self, car):
""" Return True if the given car can potentially fit in lots owned by this lot group.
Else return False. """
if car.get_size() <= self._size:
return True
else:
return False
def find_spot_and_park(self, car):
""" Find an empty lot, save the car there, and Return its lot_id if possible.
Return None if no spot is available. """
assert self.can_fit(car)
# we could also save the last index and start the search from where we left of last time.
for lot_id in xrange(0, self._lot_count):
if not self._lots.has_key(lot_id):
# found first non-existent lot_id
self._lots[lot_id] = car
return lot_id
return None
def get_car(self, lot_id):
""" Return a reference to the car object at lot_id in this lot group. Does not remove the car object. """
assert lot_id >= 0
assert lot_id < self._lot_count
if self._lots.has_key(lot_id):
return self._lots[lot_id]
# if there is no car at lot_id
return None
def remove_car(self, lot_id):
""" Remove and return a the car object at lot_id in this lot group. """
assert lot_id >= 0
assert lot_id < self._lot_count
if self._lots.has_key(lot_id):
car = self._lots[lot_id]
del self._lots[lot_id]
return car
# if there is no car at lot_id
return None
def get_hourly_rate(self):
""" Return the the hourly price of parking a car in this lot group. """
return self._hourly_rate
class Ticket(object):
def __init__(self, lot_group, lot_id):
""" Create a new Ticket for a car parked at lot_group and lot_id. """
super(Ticket, self).__init__()
assert isinstance(lot_group, LotGroup)
assert isinstance(lot_id, int)
assert (0 <= lot_id) and (lot_id < lot_group.get_spot_count())
self._lot_id = lot_id
self._lot_group = lot_group
self._cost_so_far = 0
# time ticket was issued, this is only necessary if we need to print when this ticket was issued or something
# like that. not needed for calculating cost.
self._start_time_ticket_issue = TimeHelper.get_time()
# time car is been resident in its current lot group. (this get reset when car is relocated to better spot)
self._start_time_current_spot = TimeHelper.get_time()
def get_current_car_spot(self):
""" Return the spot as a 2-tuple of (lot_group, lot_id) for the car associated with this ticket"""
return (self._lot_group, self._lot_id)
def update_car_location(self, new_lot_id, new_lot_group):
""" Update the location information for the car associated with this Ticket and handle counting the
cost of the ticket. """
assert isinstance(new_lot_group, LotGroup)
assert isinstance(new_lot_id, int)
assert (0 <= new_lot_id) and (new_lot_id < new_lot_group.get_spot_count())
# calculate the incurred cost so far on the existing lot group before updating location.
hourly_rate = self._lot_group.get_hourly_rate()
now = TimeHelper.get_time()
seconds_in_this_lg = now - self._start_time_current_spot
self._cost_so_far += (seconds_in_this_lg / 3600.0) * hourly_rate
# now update location to new spot.
self._start_time_current_spot = now
self._lot_id = new_lot_id
self._lot_group = new_lot_group
def get_cost(self):
""" Return the costs ran up on this ticket so far. s"""
# calculate the incurred cost so far on the existing lot group before updating location.
hourly_rate = self._lot_group.get_hourly_rate()
now = TimeHelper.get_time()
seconds_in_this_lg = now - self._start_time_current_spot
return self._cost_so_far + ((seconds_in_this_lg / 3600.0) * hourly_rate)
class ParkingLotController(object):
def __init__(self, small_count, small_rate, medium_count, medium_rate, large_count, large_rate):
""" Initialize a new parking lot controller. """
super(ParkingLotController, self).__init__()
self._lot_groups = []
self._lot_groups.append( LotGroup(lots_count=small_count, size=LotSize.SMALL, hourly_rate=small_rate) )
self._lot_groups.append( LotGroup(lots_count=medium_count, size=LotSize.MEDIUM, hourly_rate=medium_rate) )
self._lot_groups.append( LotGroup(lots_count=large_count, size=LotSize.LARGE, hourly_rate=large_rate) )
# table of ticket id to ticket objects. -- a ticket has:
# lot_id of where the car is at right now
# arrival time. total cost so far.
self._tickets_table = {}
# use this to implement an auto increment like ticket id allocation
self._next_ticket_id = 1000
def _allocate_new_ticket_id(self):
""" Return a new unique ticket id while keeping track of previously allocated ticket ids so as to not
re-use them. """
tid = self._next_ticket_id
self._next_ticket_id +=1
return tid
def _get_best_spot(self, car):
""" Given a car find and return a suitable spot as a 2-tuple (lot_group, lot id) for it to park in.
return (None, None) if no such spot exists.
"""
# lot groups are ordered from smallest to largest.
for lot_group in self._lot_groups:
if lot_group.can_fit(car) and lot_group.has_space():
# this code is not multi thread in general, so presumably we don't deal with possibility that
# space can be exhausted underneath us, just after we check for existence of empty space.
return (lot_group, lot_group.find_spot_and_park(car))
return (None, None)
def _relocate_car_to_best_spot(self, ticket):
""" Given a ticket for a car, see if we can park this car in a better location and do so if possible. """
assert isinstance(ticket, Ticket)
existing_lot_group, existing_lot_id = ticket.get_current_car_spot()
car = existing_lot_group.get_car(lot_id=existing_lot_id)
assert isinstance(car, Car)
for lot_group in self._lot_groups:
if (lot_group.can_fit(car) and lot_group.has_space() and
(lot_group.get_size_class() < existing_lot_group.get_size_class())):
car2 = existing_lot_group.remove_car(lot_id=existing_lot_id)
assert car == car2
new_lot_id = lot_group.find_spot_and_park(car=car)
ticket.update_car_location(new_lot_id=new_lot_id, new_lot_group=lot_group)
def __str__(self):
parking_lot_state = "--------------------------- Parking lot has " + str(len(self._lot_groups)) + " lot groups"
for lot_group in self._lot_groups:
parking_lot_state += "\n" + str(lot_group)
if len(self._tickets_table):
parking_lot_state += "--------------------------- Tickets table has these entries \n"
parking_lot_state += "########################### Tickets table (Ticket no -- cost so far -- Car):\n"
for tid, ticket in self._tickets_table.iteritems():
lot_group, lot_id = ticket.get_current_car_spot()
car = lot_group.get_car(lot_id=lot_id)
parking_lot_state += str(tid) + " -- " + "{:16.6f}".format(ticket.get_cost()) + " -- " + str(car) + '\n'
parking_lot_state += "########################### End Tickets table\n"
return parking_lot_state
#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------- Public API
def compactify_parking_lot(self):
for ticket in self._tickets_table.itervalues():
self._relocate_car_to_best_spot(ticket)
def park_car_and_return_ticket_number(self, car):
""" Given a Car object park it in the cheapest spot, and give back a string with ticket number
that can be used to retrieve the car. Returns None if no spot is available. """
lot_group, lot_id = self._get_best_spot(car=car)
if lot_group == None or lot_id == None:
return None
ticket = Ticket(lot_group=lot_group, lot_id=lot_id)
ticket_id = self._allocate_new_ticket_id()
# save it into allocated tickets
self._tickets_table[ticket_id] = ticket
return ticket_id
def return_car_and_get_cost_for_ticket_number(self, ticket_no):
""" Given a ticket number previously given out by this parking lot controller, find and return
the original car object as well as the total cost incurred so far as 2-tuple (car, cost) . """
if not self._tickets_table.has_key(ticket_no):
return (None, None)
ticket = self._tickets_table[ticket_no]
del self._tickets_table[ticket_no]
cost = ticket.get_cost()
current_lot_group, current_lot_id = ticket.get_current_car_spot()
car = current_lot_group.remove_car(lot_id=current_lot_id)
return car, cost
def get_cost_for_ticket_number(self, ticket_no):
""" Return the total cost of a ticket so far, or None if invalid ticket no supplied. """
if not self._tickets_table.has_key(ticket_no):
return None
return self._tickets_table[ticket_no].get_cost()
|
b9a68a2abf2a27d9d7ca460e660f96a22ab5eabc | niyati2k/SSL | /180050078_InLab3/Q2.py | 381 | 3.75 | 4 | fl=0
try:
pin=int(input("Enter the pin: "))
if(pin==4949):
print("Lock Opened")
fl=1
elif(pin>9999 or pin<0):
exit()
# exit()
else:
print("Wrong PIN! Try again")
pass
except:
print("Full alarm")
exit()
if(fl==1):
exit()
try:
pin=int(input("Enter the pin: "))
if(pin==4949):
print("Lock Opened")
else:
print("Full alarm")
pass
except:
print("Full alarm") |
fbb782563da941f0321d1101a2265e1c01404909 | cristianlepore/python_exercises | /Lesson3/decimalToBinary.py | 422 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 8 12:09:59 2016
@author: ericgrimson
"""
num = 19
startingNum = num
if num < 0:
isNeg = True
num = abs(num)
else:
isNeg = False
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num % 2) + result
num = num // 2
if isNeg:
result = '-' + result
print("The binary representation of", end=' ')
print(startingNum, "is: ", result)
|
1214a19f0436b790960678c3de92333401ced52b | kookkig11/Python_Language | /date of jan.py | 828 | 4.21875 | 4 | day = input()
date = int(input())
if day == 'Sunday' :
num = 1
elif day == 'Monday' :
num = 2
elif day == 'Tuesday' :
num = 3
elif day == 'Wednesday' :
num = 4
elif day == 'Thursday' :
num = 5
elif day == 'Friday' :
num = 6
elif day == 'Saturday' :
num = 7
else :
num = 0
if num == 0 :
print("ERROR")
elif date < 1 or date > 31 :
print("ERROR")
else :
while date >= 7 :
date = date - 7
out = (date - 1) + num
if out > 7:
out = out - 7
if out == 1 :
print("Sunday")
elif out == 2 :
print("Monday")
elif out == 3 :
print("Tuesday")
elif out == 4 :
print("Wednesday")
elif out == 5 :
print("Thursday")
elif out == 6 :
print("Friday")
elif out == 7 :
print("Saturday") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.