blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
bffa6576eebd0343e56aa5344025fd51877f093e | ikhwan/pythonkungfu | /case-study/mass-calc.py | 1,089 | 4.25 | 4 | #!/usr/bin/env python
def arrayOperation(array, operation):
a = int(0)
for x in xrange(0, len(array)):
# Handling error
if type(array[x]) != int:
return "The element is not a number"
else:
a += array[x]
if (operation == "sum"):
return a
if(operation == "avg"):
return float(a) / len(array)
if(operation == "mul"):
a = int(array[0])
for x in xrange(1, len(array)):
# Handling error
if type(array[x]) != int:
return "The element is not a number"
else:
a = a * array[x]
return a
else:
return "Invalid operation!"
myArray = [1, 2, 3, 4]
# Tanyain dia mau ngapain?
# 1. sum
# 2. avg
# 3. mul
# --> 2
# Tanyain, ada berapa angka yang mau dia operasiin
# --> 4
# array.append(angka1)
# array.append(angka2)
# array.append(angka3)
# array.append(angka4)
# print arrayOperation(myArray, "avg")
print arrayOperation(myArray, "sum")
print arrayOperation(myArray, "avg")
print arrayOperation(myArray, "mul")
|
65993600e94e6f1be78c812166982e80d3c511bf | Dub4ek/Mit6.00x | /Week5/L9 Problem 1.py | 263 | 3.921875 | 4 | """
num = 3;
L = [2, 0, 1, 5, 3, 4]
val = 0
for i in range(0, num):
val = L[L[val]]
print val
"""
a = [1, 2, 3, 4, 0]
b = [3, 0, 2, 4, 1]
c = [3, 2, 4, 1, 5]
def foo(L):
val = L[0]
while (True):
print 'a'
val = L[val]
print foo(b) |
a6713ea5a73faf51edfc89bca228702640bbc59b | holzschu/Carnets | /Library/lib/python3.7/site-packages/networkx/algorithms/voronoi.py | 3,392 | 3.875 | 4 | # voronoi.py - functions for computing the Voronoi partition of a graph
#
# Copyright 2016-2019 NetworkX developers.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
"""Functions for computing the Voronoi cells of a graph."""
import networkx as nx
from networkx.utils import groups
__all__ = ['voronoi_cells']
def voronoi_cells(G, center_nodes, weight='weight'):
"""Returns the Voronoi cells centered at `center_nodes` with respect
to the shortest-path distance metric.
If *C* is a set of nodes in the graph and *c* is an element of *C*,
the *Voronoi cell* centered at a node *c* is the set of all nodes
*v* that are closer to *c* than to any other center node in *C* with
respect to the shortest-path distance metric. [1]_
For directed graphs, this will compute the "outward" Voronoi cells,
as defined in [1]_, in which distance is measured from the center
nodes to the target node. For the "inward" Voronoi cells, use the
:meth:`DiGraph.reverse` method to reverse the orientation of the
edges before invoking this function on the directed graph.
Parameters
----------
G : NetworkX graph
center_nodes : set
A nonempty set of nodes in the graph `G` that represent the
center of the Voronoi cells.
weight : string or function
The edge attribute (or an arbitrary function) representing the
weight of an edge. This keyword argument is as described in the
documentation for :func:`~networkx.multi_source_dijkstra_path`,
for example.
Returns
-------
dictionary
A mapping from center node to set of all nodes in the graph
closer to that center node than to any other center node. The
keys of the dictionary are the element of `center_nodes`, and
the values of the dictionary form a partition of the nodes of
`G`.
Examples
--------
To get only the partition of the graph induced by the Voronoi cells,
take the collection of all values in the returned dictionary::
>>> G = nx.path_graph(6)
>>> center_nodes = {0, 3}
>>> cells = nx.voronoi_cells(G, center_nodes)
>>> partition = set(map(frozenset, cells.values()))
>>> sorted(map(sorted, partition))
[[0, 1], [2, 3, 4, 5]]
Raises
------
ValueError
If `center_nodes` is empty.
References
----------
.. [1] Erwig, Martin. (2000),
"The graph Voronoi diagram with applications."
*Networks*, 36: 156--163.
<dx.doi.org/10.1002/1097-0037(200010)36:3<156::AID-NET2>3.0.CO;2-L>
"""
# Determine the shortest paths from any one of the center nodes to
# every node in the graph.
#
# This raises `ValueError` if `center_nodes` is an empty set.
paths = nx.multi_source_dijkstra_path(G, center_nodes, weight=weight)
# Determine the center node from which the shortest path originates.
nearest = {v: p[0] for v, p in paths.items()}
# Get the mapping from center node to all nodes closer to it than to
# any other center node.
cells = groups(nearest)
# We collect all unreachable nodes under a special key, if there are any.
unreachable = set(G) - set(nearest)
if unreachable:
cells['unreachable'] = unreachable
return cells
|
7be82d5767aab87804288a9a45f8c8b7e526dfb8 | AlexandruSerban321/python-beginner-scripts | /password_generatore.py | 958 | 3.984375 | 4 | from string import ascii_letters, punctuation, digits
from random import choice
def password_generatore():
characters = ascii_letters + punctuation + digits
try:
password_range = int(
input("How long do you wish you password to be ( 8-16 recomandet )? "))
password = "".join(choice(characters) for x in range(password_range))+'\n'
save_password = open('passwords.txt', 'a+')
save_password.write(password)
save_password.close()
print(password)
replay = input("Do you wish to try again? y/n ").lower()
if replay[0] == "y":
password_generatore()
else:
print("Thanks for using my small script it means a lot to me ^^")
except ValueError:
print("Please enter a number not a letter or punctuation try again. ")
password_generatore()
except KeyboardInterrupt:
print("\n Thanks for playing")
password_generatore()
|
9441109a2b8c824a9342bdf634721bb7047095cd | Maxim228337/pythonadvanced | /666.py | 1,554 | 3.765625 | 4 | #Настроение
#Свойства
class Critter(object):
#
total = 0
@staticmethod
def status():
print('Общее число зверюшек',Critter.total)
def __init__(self, name, hunger = 0, boredom = 0):
self.__name = name
self.hunger = hunger
self.boredom = boredom
Critter.total += 1
def __str__(self):
ans = "Объект класса Critter\n"
ans += 'имя ' + self.name + "\n"
return ans
@property
def name(self):
return self.__name
@name.setter
def name(self, new_name):
if new_name == "":
print("Имя зверюшки не может быть одной строкой.")
else:
self.__name = new_name
print("имя успешно изминено.")
@property
def mood(self):
unhapiness = self.hunger + self.boredom
if unhapiness < 5:
m = "прекрасно"
elif 5 <= unhapiness <= 10:
m="Неплохо"
elif 11<= unhapiness <= 15:
m = 'Не особо'
else:
m = 'ужасно'
return m
def talk(self):
print('Меня зовут,', self.name)
def main():
print('создание зверушек')
crit1=Critter('Зверушка 1')
crit2=Critter('Зверушка 2')
crit3=Critter('Зверушка 3')
Critter.status()
print('Доступ к свойству объекта:', crit1.mood)
main() |
138a7e932ef8367473bfb0ad3f5112f0bb4a3f0f | edwinnab/python_practice | /project1.py | 390 | 4.21875 | 4 | #imports random module
import random
#generates random number using the random method
num = random.randint(0,35)
print("randomly generated number:",num)
#inputs a number from the user
num1 = input("Guess a number:");
num1 = int()
#loop for wrong input
if num1 > 35 :
print("number guessed is too high.")
elif num1 < 0 :
print("number guessed is too low.")
else :
print("start")
|
c9c580cae58ba610b1d25b393b4174869489c25d | kRituraj/python-programming | /print-square-of-even-and-cube-of-odd.py | 320 | 3.828125 | 4 | from array import *
MyArray = array("i",[1,2,3,4,5,6,7,8,9,10])
i = 0
even = 1
odd = 1
while (i < len(MyArray)):
if (MyArray[i] %2 == 0):
even = MyArray[i] * MyArray[i]
print(even , end = " ")
else:
odd = MyArray[i] * MyArray[i] * MyArray[i]
print(odd , end = " ")
i = i + 1
|
75ac38c7e9d3a56bb1e68cd12b8e2d4a74d6881f | AdamFraserGitHub/heeschProblem | /prototypes/randomShapes/rotate square/server/compute.py | 3,223 | 3.609375 | 4 | from math import ceil
from math import sin
from math import cos
from math import pi
import numpy as np
def matrixToList(matrix2Convert):
'''
funct converts a 2d matrix to a 2d list
'''
listReturn = []
for i in range(len(matrix2Convert)): # handles collums (neccesary to deal with points)
listReturn.append([])
for j in range(2): #handles rows
listReturn[i].append(matrix2Convert.item(j, i)) #gets item row j collumn i
return listReturn
def rotate(shape, angle):
'''
funct rotates a shape made of points by angle
shape is a 2d array of points where shape[0][j] is x
and shape[1][j] is y. each point is the relative displacement.
angles should be in radians
'''
# nVerticies = ceil(len(shape[0]) / 2) # this handles even numbered pointed
# # shapes as well as odd numbered shapes, it
# # represents the number of rotations i.e. the
# # number of verticies (for odd numberes a
# # single point is included in this)
# points2Rotate = []
# verticies2Rotate = []
# #removes the first point if there is an odd number of points (for matrix multiplication)
# if(len(shape[0]) % 2 != 0):
# points2Rotate.append([[shape[0][0]],[shape[1][0]]])
# del shape[0][0]
# del shape[1][0]
# #split shape up into single verticies (sides)
# for i in range(0, len(shape[0]) - 1, 2):
# verticies2Rotate.append([[shape[0][i], shape[0][i + 1]], [shape[1][i], shape[1][i + 1]]])
# #find the rotation matrix for a point and a vertex
pointRotMatrix = np.matrix([[round(cos(angle), 10)],[round(sin(angle), 10)]])
vertexRotMatrix = np.matrix([[round(cos(angle), 10), round(-sin(angle), 10)], [round(sin(angle), 10), round(cos(angle), 10)]])
print(vertexRotMatrix*np.matrix(shape))
# #get the rotated points and verticies and add them to a list
# shapeRot = [[],[]]
# for i in range(len(points2Rotate)):
# pointRot = matrixToList(np.matrix(points2Rotate[i])*pointRotMatrix)
# shapeRot[0] = shapeRot[0] + pointRot[0]
# shapeRot[1] = shapeRot[1] + pointRot[1]
# for i in range(len(verticies2Rotate)):
# print(np.matrix(verticies2Rotate[i])*vertexRotMatrix)
# vertexRot = matrixToList(np.matrix(verticies2Rotate[i])*vertexRotMatrix)
# shapeRot[0] = shapeRot[0] + vertexRot[0]
# shapeRot[1] = shapeRot[1] + vertexRot[1]
return shapeRot
# shape = [[-0.5, 0.5, 0.5, -0.5],[-0.5, -0.5, 0.5, 0.5]] #square
shape = [[0.25, 0.5, 0.25, -0.25, -0.5, -0.25], [-0.433, 0, 0.433, 0.433, 0, -0.433]] #hexagon
# shape = [[0.25, 0.5, 0.7, 0.3,-0.5,0.1],[-0.5,-0.2,0,1,0,-0.5]]
rotated = rotate(shape, pi/4)
# print(rotated)
##############
#SERVER STUFF#
##############
import requests
requestAddress = "http://localhost:80/baseShape"
data = {'x': shape[0], 'y': shape[1]}
requests.post(requestAddress, data)
requestAddress = "http://localhost:80/processRotation"
data = {'x': rotated[0], 'y': rotated[1]}
requests.post(requestAddress, data)
|
bdb1f5f4988e6011c7daa4c72362ee2f885e7212 | Moris-Zhan/Udemy_Course | /Python/Complete Course/PyCharm/Module/guessGame.py | 770 | 3.84375 | 4 | import random
rangeMin = 0
rangeMax = 100
guess = random.randint(rangeMin, rangeMax)
t = (1,2,3,4,5,6,7)
print(len(t))
# while True:
# userGuess = input("Enter your guess number : ")
# PlaceLowRange = "lower , In range %d ~ %d"
# PlaceHighRange = "higher , In range %d ~ %d"
#
# if int(userGuess) > 100 or int(userGuess) < 0:
# print("You have to guessing a range from 0 - 100 \n")
# else:
# if int(userGuess) < guess:
# rangeMin = int(userGuess)
# print(PlaceLowRange % (rangeMin, rangeMax))
# elif int(userGuess) > guess:
# rangeMax = int(userGuess)
# print(PlaceHighRange % (rangeMin, rangeMax))
# else:
# print("You Guess Right")
# break
|
e4b1256d439a2330d7a0fcb1b9f65e72980485cc | HectorIGH/Competitive-Programming | /Leetcode Challenge/07_July_2020/Python/Week 3/7_Word Search.py | 1,843 | 3.75 | 4 | #Given a 2D board and a word, find if the word exists in the grid.
#
#The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
#
#Example:
#
#board =
#[
# ['A','B','C','E'],
# ['S','F','C','S'],
# ['A','D','E','E']
#]
#
#Given word = "ABCCED", return true.
#Given word = "SEE", return true.
#Given word = "ABCB", return false.
#
#
#Constraints:
#
#board and word consists only of lowercase and uppercase English letters.
#1 <= board.length <= 200
#1 <= board[i].length <= 200
#1 <= word.length <= 10^3
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
self.board = board
self.word = word
self.size = len(word) - 1
self.rows = len(board)
self.cols = len(board[0])
for i in range(self.rows):
for j in range(self.cols):
if word[0] == board[i][j] and self.dfs(i, j, 0):
return True
return False
def dfs(self, i, j, idx):
if idx == self.size:
return True
a = self.board[i][j]
self.board[i][j] = '#' #chr(ord(self.board[i][j]) - 65)
if i > 0 and self.board[i - 1][j] == self.word[idx + 1] and self.dfs(i - 1, j, idx + 1):
return True
if j > 0 and self.board[i][j - 1] == self.word[idx + 1] and self.dfs(i, j - 1, idx + 1):
return True
if i < self.rows - 1 and self.board[i + 1][j] == self.word[idx + 1] and self.dfs(i + 1, j, idx + 1):
return True
if j < self.cols - 1 and self.board[i][j + 1] == self.word[idx + 1] and self.dfs(i, j + 1, idx + 1):
return True
self.board[i][j] = a # chr(ord(self.board[i][j]) + 65)
return False |
d9e39c559a151d7c2334a83ad61b59beeade7b8c | arieli13/Practica | /classes/graphics.py | 1,770 | 4.21875 | 4 | """Plots a csv file"""
import matplotlib.pyplot as plt
def separate_csv(path_file, separator):
"""Join each column of the csv in a single list each one."""
lines = []
with open(path_file, "r") as f:
lines = f.readlines()
header = lines[0].split(separator)
lines = lines[1:]
cols = [[]for i in range(len(header))]
lines = list(map(lambda line: [float(i) for i in line.split(separator) if i], lines))
for line in lines:
for i in range(len(line)):
cols[i].append(line[i])
return header, cols
def plot_csv(path_file, separator, x_index, y_indexs, x_label, y_label, title,
printable_lines, show, save=None, return_plot=False):
"""Plot the csv file.
Args:
path_file: Path of the csv file.
separator: Separator of each column of the csv file.
x_index: Int. The index of the x-axis of the function.
y_indexs: A list with the number of the cols that want
to display.
x_label: Label for the x-axis of the function.
y_label: Label for the y-axis of the function.
title: Title for the function.
printable_lines: A list with the type of line for each function.
Example: ["g+", "r-"]
"""
header, lines = separate_csv(path_file, separator)
for i in range(len(lines)):
if i in y_indexs:
plt.plot(lines[x_index], lines[i], printable_lines.pop(),
label=header[i])
plt.title(title)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.legend(loc='best')
plt.grid()
if save is not None:
plt.savefig(save)
if show:
plt.show()
if not return_plot:
plt.close()
else:
return plt
|
0517fddd1e33f3e2a2dc34bc8cb30b91e73b2aa3 | kkelikani/Week1-Project-CIS-Prog5-2020 | /input +1.py | 94 | 3.78125 | 4 | first = int(input("Enter the first number: "))
sum = first + 1
print ("The sum is:", sum )
|
bb3c645a1758f42f56e6078c17e0e228521a9ee8 | luizxx/projetos-git | /PA EM while.py | 659 | 3.859375 | 4 | pa = int (input('Digite a primeira PA ' ))
razao = int (input('Digite a razão ' ))
paf = int(input('Digite o final da sua pa. ' ))
res = 'z'
while res != '1' or res != '2' or res != 'l':
if pa >0 or razao >0 :
for c in range(pa,paf +1,razao):
print(f'{c}',end=' = ')
print('ACABOUU!')
res = input('Voce quer continuar ? \n [1]-SIM \n [2]-NÃO ' )
if res == '1' :
pa1 = int (input('Digite a primeira 1 PA ' ))
razao = int (input('Digite a razão ' ))
paf = int(input('Digite o final da sua pa. ' ))
elif res == '2' :
print('Programa encerrado.')
break
|
4341121e0b2894f972bf3be69d6ebb51563ed533 | ashkan-abbasi66/python-comments | /ml/pandas_simple_examples/pivot_table_3.py | 304 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
read from data file and create a dataframe
"""
import pandas as pd
df = pd.read_csv('./data.csv')
print (df,'\n\n')
# Total sales per employee
pivot = df.pivot_table(index=['Name of Employee'], values=['Sales'], aggfunc='sum')
print (pivot,'\n\n')
|
e8ba826a94dc0cac6b35b77c9a9cfd6615844c3c | danielgunn/CodingBat | /python/Warmup1.py | 5,064 | 3.671875 | 4 | def sleep_in(weekday, vacation):
return not weekday or vacation
def monkey_trouble(a_smile, b_smile):
return a_smile == b_smile
def sum_double(a, b):
if (a==b):
return 2 * (a + b)
return a + b
def diff21(n):
if (n > 21):
return (n - 21) * 2
return (21 - n)
def parrot_trouble(talking, hour):
return talking and (hour < 7 or hour > 20)
def makes10(a, b):
return (a==10 or b==10 or (a+b)==10)
def near_hundred(n):
return abs(100-n) <= 10 or abs(200-n)<=10
def pos_neg(a, b, negative):
if (negative):
return (a < 0 and b < 0)
return (a > 0 and b < 0) or (a < 0 and b > 0)
def not_string(str):
if (str.startswith("not")):
return str
return "not "+str
def missing_char(str, n):
return str[:n] + str[n+1:]
def front_back(str):
if (len(str) == 1):
return str
return str[-1:] + str[1:-1] + str[0:1]
def front3(str):
return 3*str[0:3]
# The following code was generated by the expected_to_assert program
assert sleep_in(False, False) == True
assert sleep_in(True, False) == False
assert sleep_in(False, True) == True
assert sleep_in(True, True) == True
assert monkey_trouble(True, True) == True
assert monkey_trouble(False, False) == True
assert monkey_trouble(True, False) == False
assert monkey_trouble(False, True) == False
assert sum_double(1, 2) == 3
assert sum_double(3, 2) == 5
assert sum_double(2, 2) == 8
assert sum_double(-1, 0) == -1
assert sum_double(3, 3) == 12
assert sum_double(0, 0) == 0
assert sum_double(0, 1) == 1
assert sum_double(3, 4) == 7
assert diff21(19) == 2
assert diff21(10) == 11
assert diff21(21) == 0
assert diff21(22) == 2
assert diff21(25) == 8
assert diff21(30) == 18
assert diff21(0) == 21
assert diff21(1) == 20
assert diff21(2) == 19
assert diff21(-1) == 22
assert diff21(-2) == 23
assert diff21(50) == 58
assert parrot_trouble(True, 6) == True
assert parrot_trouble(True, 7) == False
assert parrot_trouble(False, 6) == False
assert parrot_trouble(True, 21) == True
assert parrot_trouble(False, 21) == False
assert parrot_trouble(False, 20) == False
assert parrot_trouble(True, 23) == True
assert parrot_trouble(False, 23) == False
assert parrot_trouble(True, 20) == False
assert parrot_trouble(False, 12) == False
assert makes10(9, 10) == True
assert makes10(9, 9) == False
assert makes10(1, 9) == True
assert makes10(10, 1) == True
assert makes10(10, 10) == True
assert makes10(8, 2) == True
assert makes10(8, 3) == False
assert makes10(10, 42) == True
assert makes10(12, -2) == True
assert near_hundred(93) == True
assert near_hundred(90) == True
assert near_hundred(89) == False
assert near_hundred(110) == True
assert near_hundred(111) == False
assert near_hundred(121) == False
assert near_hundred(-101) == False
assert near_hundred(-209) == False
assert near_hundred(190) == True
assert near_hundred(209) == True
assert near_hundred(0) == False
assert near_hundred(5) == False
assert near_hundred(-50) == False
assert near_hundred(191) == True
assert near_hundred(189) == False
assert near_hundred(200) == True
assert near_hundred(210) == True
assert near_hundred(211) == False
assert near_hundred(290) == False
assert pos_neg(1, -1, False) == True
assert pos_neg(-1, 1, False) == True
assert pos_neg(-4, -5, True) == True
assert pos_neg(-4, -5, False) == False
assert pos_neg(-4, 5, False) == True
assert pos_neg(-4, 5, True) == False
assert pos_neg(1, 1, False) == False
assert pos_neg(-1, -1, False) == False
assert pos_neg(1, -1, True) == False
assert pos_neg(-1, 1, True) == False
assert pos_neg(1, 1, True) == False
assert pos_neg(-1, -1, True) == True
assert pos_neg(5, -5, False) == True
assert pos_neg(-6, 6, False) == True
assert pos_neg(-5, -6, False) == False
assert pos_neg(-2, -1, False) == False
assert pos_neg(1, 2, False) == False
assert pos_neg(-5, 6, True) == False
assert pos_neg(-5, -5, True) == True
assert not_string('candy') == 'not candy'
assert not_string('x') == 'not x'
assert not_string('not bad') == 'not bad'
assert not_string('bad') == 'not bad'
assert not_string('not') == 'not'
assert not_string('is not') == 'not is not'
assert not_string('no') == 'not no'
assert missing_char('kitten', 1) == 'ktten'
assert missing_char('kitten', 0) == 'itten'
assert missing_char('kitten', 4) == 'kittn'
assert missing_char('Hi', 0) == 'i'
assert missing_char('Hi', 1) == 'H'
assert missing_char('code', 0) == 'ode'
assert missing_char('code', 1) == 'cde'
assert missing_char('code', 2) == 'coe'
assert missing_char('code', 3) == 'cod'
assert missing_char('chocolate', 8) == 'chocolat'
assert front_back('code') == 'eodc'
assert front_back('a') == 'a'
assert front_back('ab') == 'ba'
assert front_back('abc') == 'cba'
assert front_back('') == ''
assert front_back('Chocolate') == 'ehocolatC'
assert front_back('aavJ') == 'Java'
assert front_back('hello') == 'oellh'
assert front3('Java') == 'JavJavJav'
assert front3('Chocolate') == 'ChoChoCho'
assert front3('abc') == 'abcabcabc'
assert front3('abcXYZ') == 'abcabcabc'
assert front3('ab') == 'ababab'
assert front3('a') == 'aaa'
assert front3('') == ''
print('all tests passed successfully') |
d425f5c32e9469f0898891864ed43de17130b3fb | marcelohweb/python-study | /4-variaveis-tipos-de-dados/19-escopo_de_variaveis.py | 531 | 4 | 4 | """
Escopo de variáveis
Dois casos de escopo:
1 - Variáveis globais -> Reconhecidas em todo o programa
2 - Variáveis globais -> Reconhecidas apenas no bloco onde foram declaradas
Para declarar variáveis em python
nome_da_variavel = valor_da_variavel
Obs. Python é uma linguagem de tipagem dinâmica.
Ao declarar uma variável, nós não especificamos o tipo de dado. O tipo é inferido na atribuição do valor
"""
numero = 42 # Exemplo de variável global
print(numero)
print(type(numero))
# print(nao_existe) - error |
ad37ae269ae3ecd7e31f769ffc7c1bd290e26248 | Codeded87/Css_practice | /DataScience/classTest.py | 534 | 3.953125 | 4 | '''class Person:
def __init__(self, first_name, last_name, age):
#instance variable
self.first_name = first_name
self.last_name = last_name
self.age = age
def getData(self):
print(self.first_name)
p1 = Person("shiv","rudra",22)
p1.getData()
print(p1.last_name)'''
'''
class Laptop:
def __init__(self, brand, model_name, price):
self.brand = brand
self.model_name = model_name
self.price = price
l1 = Laptop("hp", "bs", 37000)
print(l1.brand)'''
|
577b4857f10b938f4b86190af1e5cf8d2b6346c7 | jiangshen95/UbuntuLeetCode | /FractiontoRecurringDecimal.py | 1,590 | 3.9375 | 4 | class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator == 0:
return "0"
symbol = ""
if (numerator < 0 or denominator < 0) and (not (numerator < 0 and denominator < 0)):
symbol = "-"
number = ""
decimal = ""
numerator = long(abs(numerator)) #numerator = abs(numerator) in python3
denominator = long(abs(denominator))
if numerator > denominator:
number = str(long(numerator/denominator)) #number = str(numerator//denominator) in python3
if number == "":
number = "0"
numerator = long(numerator%denominator)
dic = {numerator : 0}
while numerator:
next_numerator = numerator * 10
decimal += str(long(next_numerator/denominator))
numerator = next_numerator % denominator
if numerator in dic:
decimal = decimal[0:dic[numerator]] + '(' +decimal[dic[numerator]:] + ')'
break
dic[numerator] = len(decimal)
if decimal == "":
return symbol + number
else:
return symbol + number + '.' + decimal
if __name__=='__main__':
numerator = int(raw_input())
denominator = int(raw_input())
solution = Solution()
print(solution.fractionToDecimal(numerator, denominator))
|
5f1ea480ce74ba1363932cae006ccd2bcb31e411 | theanik/CompetitiveProgramming | /codeforces/PetyaAndStrings.py | 173 | 4 | 4 | str1 = input()
str2 = input()
if str1.lower() == str2.lower():
print(0)
elif str1.lower() > str2.lower():
print(1)
elif str1.lower() < str2.lower():
print('-1') |
5b6d73d1d772a12e78ad82928c31a758036b66b6 | Jackieji00/csci1133 | /repo-ji000011/hw2/ji000011_2D.py | 2,609 | 3.875 | 4 | def check(player):
if player.lower() == 'p' or player.lower() == 'r' or player.lower() == 's':
return True
else:
return False
def rockPaperScissor(player1,player2):
if player1.lower() == 'p':
if player2.lower() == 'p':
result = 'n'
elif player2.lower() == 's':
result = '2'
else:
result = '1'
if player1.lower() == 's':
if player2.lower() == 'p':
result = '1'
elif player2.lower() == 's':
result = 'n'
else:
result = '2'
if player1.lower() == 'r':
if player2.lower() == 'p':
result = '2'
elif player2.lower() == 's':
result = '1'
else:
result = 'n'
return result
def main():
roundcount = 0
last = []
while roundcount < 3:
roundcount += 1
print('Round # ',roundcount)
player1 = input("Player 1's Choice: ")
while check(player1) == False:
player1 = input("Player 1's Choice: ")
player2 = input("Player 2's Choice: ")
while check(player2) == False:
player2 = input("Player 2's Choice: ")
result = rockPaperScissor(player1,player2)
last.append(result)
if result == '1':
print("Player 1 wins this round")
elif result == '2':
print('Player 2 wins this round')
else:
print('No one wins this round')
print('\n')
if last[0] == '1':
if '1' in last[1:]:
print("Player 1 wins the game")
elif 'n' in last[1:]:
if '2' in last[1:]:
print('No one wins the game')
else:
print("Player 1 wins the game")
else:
print("Player 2 wins the game")
elif last[0] == '2':
if '2' in last[1:]:
print("Player 2 wins the game")
elif 'n' in last[1:]:
if '1' in last[1:]:
print('No one wins the game')
else:
print("Player 2 wins the game")
else:
print("Player 1 wins the game")
elif last[0] == 'n':
if '1' in last[1:]:
if '2' in last[1:]:
print("No one wins the game")
else:
print("Player 1 wins the game")
elif '2' in last[1:]:
if '1' in last[1:]:
print('No one wins the game')
else:
print("Player 2 wins the game")
else:
print("No one wins the game")
if __name__ == '__main__':
main()
|
3cc1bc0ab2c42b2eb0728467f90a5f01d0787195 | youkaede77/Data-Structure-and-Algorithm | /剑指offer/24. 反转链表.py | 2,112 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: wdf
# datetime: 2/6/2020 10:07 PM
# software: PyCharm
# project name: Data Structure and Algorithm
# file name: 24. 反转链表
# description: 翻转链表,并输出翻转后链表的头结点
# usage:
class Node():
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class LinkedList():
def __init__(self):
self.head = Node() # 链表初始化,只有一个头结点
self.length = 0
def add_first(self, data):
'''从头添加元素'''
new_node = Node(data)
new_node.next = self.head.next
self.head.next = new_node
self.length += 1
# 打印链表
def print_lkst(self):
node = self.head.next # 不打印头结点
# print("head: ",head_node, head_node.data)
while node != None:
print(node.val, end=' ')
node = node.next
print()
# 翻转链表
def reverse(self):
# 没有节点
if self.head is None:
return None
# 只有一个节点,翻转不反转都一样
elif self.head.next is None:
return self.head
if self.head.next.next is None:
return False
pre, cur = None, self.head.next
while cur:
if cur.next:
nxt = cur.next # 临时保存下一个节点,防止丢失
cur.next = pre
pre = cur
cur = nxt
else: # cur已经到最后一个节点,没有后继节点了
self.head = Node()
self.head.next = cur
cur.next = pre
break
return cur, cur.val # 返回翻转后的头结点(不含head)
def main():
# 新建一个链表
print("新建一个链表")
ll = LinkedList()
for i in range(10):
ll.add_first(i)
ll.print_lkst()
print('翻转链表')
print(ll.reverse())
ll.print_lkst()
if __name__ == '__main__':
main()
|
5c73d167c0d7e55984242caf6c737709479a88a5 | chen-min/learningPython | /nine/c1.py | 518 | 3.671875 | 4 | # coding=UTF-8
class Student():
name = ''
age = 0
def __init__(self, name, age):
#构造函数
#初始化对象的属性
name = name
age = age
print('student')
#行为 与 特征
def do_homework(self):
print('homework')
# 实例化
student1 = Student('tom', 18)
print(student1.name) # 这样打印出来是空值, 为什么
# a = student1.__init__()
# print(a) # 返回为空
# print(type(a))
#构造函数不能强制返回, 只能返回None |
4fd2df836ec1cfd29fb84d8fe5572bb31a5fe719 | sony-zloi/hw_data_packing | /task_3.py | 2,066 | 3.546875 | 4 | import pickle
import json
from dataclasses import dataclass, field
from typing import Dict, Any
@dataclass
class Stadium:
"""
Задание 3
Реализуйте класс «Стадион». Необходимо хранить в полях класса:
- название стадиона,
- дату открытия,
- страну,
- город,
- вместимость.
Реализуйте методы класса для ввода данных, вывода данных, реализуйте доступ к отдельным полям через методы класса.
"""
name: str
year: int
country: str
city: str
capacity: int
def getName(self):
return self.name
def setName(self, value):
if not value:
raise ValueError
self.name = value
def getYear(self):
return self.year
def setYear(self, value):
if not value:
raise ValueError
self.year = value
def getCountry(self):
return self.country
def setCountry(self, value):
if not value:
raise ValueError
self.country = value
def getCity(self):
return self.city
def setCity(self, value):
if not value:
raise ValueError
self.city = value
def getCapacity(self):
return self.capacity
def setCapacity(self, value):
if not value:
raise ValueError
self.capacity = value
def as_dict(self):
return {'name': self.name, 'year': self.year, 'country': self.country, 'city': self.city,
'capacity': self.capacity}
def json_serialize(self) -> str:
return json.dumps(self.as_dict())
@staticmethod
def json_deserialize(value: str) -> Dict[str, Any]:
return json.loads(value)
def pickle_serialize(self) -> bytes:
return pickle.dumps(self)
@staticmethod
def pickle_deserialize(value: bytes) -> "Stadium":
return pickle.loads(value) |
7c91d69eb4f1ce21eea20b5eb4c2c2d62d4234f4 | masonaviles/data-structures-and-algorithms | /python/code_challenges/ll_zip/ll_zip.py | 1,468 | 4.40625 | 4 | def zipLists(list1, list2):
""" a function to zip the two linked lists together into one so that the nodes alternate between the two lists and return a reference to the head of the zipped list.
Args:
list1 (list): a linked list to zip in other ll
list2 (list): a linked list to zip in other ll
Output -> a single linked list
"""
# return = [*transform* *iteration* *filter* ]
# transform -> sub[item]
# iteration -> for item in range
# filter -> (loop) for sub in [list1, list2]
# lst1 = [1, 2, 3]
# lst2 = ['a', 'b', 'c']
return [sub[item] for item in range(len(list2))
for sub in [list1, list2]]
# [ [0] of list1, [0] of list2 ] -> [ 1, 'a' ]
# [ [1] of list1, [1] of list2 ] -> [ 1, 'a', 2, 'b' ]
# [ [2] of list1, [2] of list2 ] -> [1, 'a', 2, 'b', 3]
# [ 1, 'a' ]
# Test code
lst1 = [1, 2, 3]
lst2 = ['a', 'b', 'c']
print(zipLists(lst1, lst2))
# class zipLists(list1, list2):
# list1_curr = list1.head
# list2_curr = list2.head
# # Save Next in Var's
# while list1_curr and list2_curr:
# list1_next = list1_curr.next
# list2_next = list2_curr.next
# # Make list2 current as next of list1
# list1_curr.next = list2_next
# list2_curr.next = list1_next
# # Update current to next iteration
# list1_curr = list2_next
# list2_curr = list1_next
# list1.head = list1_curr |
f9f00fe7de7c666b6ba53daa0be0a2b95edab026 | drlatt/python | /list_comprehension_sample.py | 162 | 4.15625 | 4 | # using a list comprehension to generate a list of the cubes from 3 through 30
threes = [value**3 for value in range(3,31)]
for three in threes:
print(three)
|
47758ad094e8cd5ce8dc25b2e1e22abaf864c485 | vnatesh/Code_Eval_Solutions | /Moderate/reverse_groups.py | 1,052 | 4.125 | 4 | """
REVERSE GROUPS
CHALLENGE DESCRIPTION:
Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time. If the number of elements is not a multiple of k, then the remaining items in the end should be left as is.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Each line in this file contains a list of numbers and the number k, separated by a semicolon. The list of numbers are comma delimited. E.g.
1,2,3,4,5;2
1,2,3,4,5;3
OUTPUT SAMPLE:
Print out the new comma separated list of numbers obtained after reversing. E.g.
2,1,4,3,5
3,2,1,4,5
"""
import sys,math
test_cases=open(sys.argv[1],'r')
for i in test_cases.read().split('\n'):
if i!='':
a=int(i.split(';')[1])
b=i.split(';')[0].split(',')
x=0
s=[]
while x<len(b):
if len(list(reversed(b[x:x+a])))==a:
s.append(','.join(reversed(b[x:x+a])))
else: s.append(','.join(b[x:x+a]))
x+=a
print ','.join(s)
|
0d548a1f792a84cd1264f4904149bf42276ecc60 | ArthurJP/pythonLearning | /venv/OOP/Advanced.py | 11,462 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__arthur__ = "张俊鹏"
# 使用__slots__
class Student(object):
pass
s = Student()
s.name = "Michael"
print(s.name)
def set_age(self, age):
self.age = age
from types import MethodType
s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
s.set_age(25)
print(s.age)
# 但是,给实例绑定的方法,对另一个实例是不起作用的
s2 = Student()
# s2.set_age(25) # 尝试调用方法
# 可以给class绑定方法
def set_score(self, score):
self.score = score
Student.set_score = set_score
s.set_score(100)
print(s.score)
s2.set_score(99)
print(s2.score)
class Student(object):
__slots__ = ('name', 'age')
s = Student()
s.name = "kiven"
s.age = 25
# s.score=100
# 使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:
class GranduatedStudent(Student):
pass
g = GranduatedStudent()
g.score = 100
# 除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。
class UngraduatedStudent(Student):
__slots__ = ()
pass
u = UngraduatedStudent()
# u.score=59
# @property
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0~100!')
self._score = value
s = Student()
s.score = 89
print(s.score)
# s.score=-1
class Student(object):
@property
def birth(self):
return self._birth
@birth.setter
def birth(self, value):
self.birth = value
@property
def age(self):
return 2018 - self._birth
# 上面的birth是可读写属性,而age就是一个只读属性,因为age可以根据birth和当前时间计算出来。
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def resolution(self):
return self._width * self._height
# 测试:
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
print('测试通过!')
else:
print('测试失败!')
# 多重继承
class Animal(object):
pass
class Mammal(Animal):
pass
class Bird(Animal):
pass
class Dog(Mammal):
pass
class Bat(Mammal):
pass
class Parrot(Bird):
pass
class Ostrich(Bird):
pass
class Runnable(object):
def run(self):
print("Running...")
class Flyable(object):
def fly(self):
print("Flying...")
class Dog(Mammal, Runnable):
pass
class Bat(Mammal, Flyable):
pass
# 通过多重继承,一个子类就可以同时获得多个父类的所有功能。
# MixIn
# class MyTCPServer(TCPServer, ForkingMixIn): # 多进程模式的TCP服务
# pass
#
#
# class MyUDPServer(UDPServer, TreadingMixIn): # 多线程模式的UDP服务
# pass
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self): # 改变用户得到的结果
return "Student object (name:%s)" % self.name
__pepr__ = __str__ # 改变程序员看到的结果
print(Student("Michael"))
class Fib(object):
def __init__(self):
self.a, self.b = 0, 1
def __iter__(self):
return self # 实例本身就是迭代对象,故返回自己
def __next__(self): # 用于实现for循环
self.a, self.b = self.b, self.a + self.b
if self.a > 10000:
raise StopIteration()
return self.a
def __getitem__(self, n): # 用于实现获取具体的值
if isinstance(n, int):
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
if isinstance(n, slice):
start = n.start
stop = n.stop
if start is None:
start = 0
a, b = 1, 1
L = []
for x in range(stop):
if x >= start:
L.append(a)
a, b = b, a + b
return L
for n in Fib():
print(n)
f = Fib()
print(f[0])
print(f[1])
print(f[2])
f = Fib()
print(f[0:5])
class Student(object):
def __init__(self):
self.name = "Michael"
def __getattr__(self, item): # 找不到的变量会从该函数寻找
if item == "score":
return 99
if item == "age":
return lambda: 25
raise AttributeError('\'Student\' object has no attribute \'%s\'' % item)
s = Student()
print(s.name)
print(s.score)
print(s.age)
print(s.age())
class Chain(object):
def __init__(self, path=''):
self._path = path
def __getattr__(self, path):
return Chain("%s/%s" % (self._path, path))
def __str__(self):
return self._path
__repr__ = __str__
print(Chain().status.user.timeline.list)
# 任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用。
class Student(object):
def __init__(self, name):
self.name = name
def __call__(self, *args, **kwargs):
print('My name is %s' % self.name)
s = Student("Michael")
s()
print(callable(Student))
print(callable(max))
print(callable([1, 2, 3]))
print(callable(None))
print(callable('str'))
# 枚举类
from enum import Enum
Month = Enum('Mon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name, member in Month.__members__.items():
print(name, '=>', member, ',', member.value)
# 如果需要更精确地控制枚举类型,可以从Enum派生出自定义类
from enum import Enum, unique
@unique # @unique装饰器可以帮助我们检查保证没有重复值。
class Weekday(Enum):
Sun = 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
print(Weekday.Mon)
print(Weekday['Tue'])
print(Weekday(3))
print(Weekday.Sat.value)
@unique
class Gender(Enum):
Male = 0
Female = 1
class Student(object):
def __init__(self, name, gender):
self.name = name
if type(gender) == Gender:
self.gender = gender
else:
raise ValueError("gender type error")
def __str__(self):
return '学生的姓名为:%s,性别为:%s' % (self.name, self.gender)
__repr__ = __str__
# 测试:
bart = Student('Bart', Gender.Male)
if bart.gender == Gender.Male:
print('测试通过!')
else:
print('测试失败!')
# type
from hello import Hello
h = Hello()
h.hello()
print(type(Hello))
print(type(h))
def fn(self, name='world'): # 先定义函数
print('Hello, %s.' % name)
Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class
h = Hello()
h.hello()
print(type(Hello))
print(type(h))
# 要创建一个class对象,type()函数依次传入3个参数:
#
# class的名称;
# 继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
# class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。
# metaclass
# 除了使用type()动态创建类以外,要控制类的创建行为,还可以使用metaclass
# metaclass是类的模板,所以必须从`type`类型派生
class ListMetaclass(type):
# __new__()方法接收到的参数依次是:
# 当前准备创建的类的对象;
# 类的名字;
# 类继承的父类集合;
# 类的方法集合。
def __new__(cls, name, bases, methods):
methods['add'] = lambda self, value: self.append(value)
return type.__new__(cls, name, bases, methods)
class MyList(list, metaclass=ListMetaclass):
pass
L = MyList()
L.add(1)
print(L)
# 自定义ORM Object Relational Mapping
class Field(object):
def __init__(self, name, column_type):
self.name = name
self.column_type = column_type
def __str__(self):
return "%s:%s" % (self.__class__.__name__, self.name)
class StringField(Field):
def __init__(self, name):
super(StringField, self).__init__(name, "varchar(100)")
class IntegerField(Field):
def __init__(self, name):
super(IntegerField, self).__init__(name, "bigint")
class ModelMetaclass(type):
def __new__(cls, name, bases, methods):
if name == 'Model': # 这里是为了防止创建model类型
return type.__new__(cls, name, bases, methods)
print('Found model: %s' % name) # 从这里开始是创建了model的子类
mappings = dict()
for k, v in methods.items():
if isinstance(v, Field):
print('Found mapping: %s ==> %s' % (k, v))
mappings[k] = v
for k in mappings.keys():
methods.pop(k)
methods['__mapping__'] = mappings
methods['__table__'] = name
return type.__new__(cls, name, bases, methods)
class Model(dict, metaclass=ModelMetaclass):
def __init__(self, **kw):
super(Model, self).__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Model' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
def save(self):
fields = []
params = []
args = []
for k, v in self.__mapping__.items():
fields.append(v.name)
params.append('?')
args.append(getattr(self, k, None))
sql = 'replace into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(params))
print("SQL: %s" % sql)
print("ARGS: %s" % str(args))
class User(Model):
# 注意这里都是方法
id = IntegerField("id")
name = StringField("username")
email = StringField("email")
password = StringField("password")
# 创建一个实例:
u = User(id=12345, name='Michael', email='test@orm.org', password='my-pwd')
# 保存到数据库:
u.save()
# 当用户定义一个class User(Model)时,Python解释器首先在当前类User的定义中查找metaclass,如果没有找到,就继续在父类Model中查找metaclass,找到了,就使用Model中定义的metaclass的ModelMetaclass来创建User类,也就是说,metaclass可以隐式地继承到子类,但子类自己却感觉不到。
#
# 在ModelMetaclass中,一共做了几件事情:
#
# 排除掉对Model类的修改;
#
# 在当前类(比如User)中查找定义的类的所有属性,如果找到一个Field属性,就把它保存到一个__mappings__的dict中,同时从类属性中删除该Field属性,否则,容易造成运行时错误(实例的属性会遮盖类的同名属性);
#
# 把表名保存到__table__中,这里简化为表名默认为类名。
#
# 在Model类中,就可以定义各种操作数据库的方法,比如save(),delete(),find(),update等等。
#
# 我们实现了save()方法,把一个实例保存到数据库中。因为有表名,属性到字段的映射和属性值的集合,就可以构造出INSERT语句。
|
96d2f8c59d58b16773cd513ceb9c5a640b91f838 | VaibhavRangare/python_basics_part1 | /Pandas/DFOperations1.py | 735 | 3.671875 | 4 | import numpy as np
import pandas as pd
index = np.array([0,1,2,3,4,5,6])
columns = np.array(['Name','Age','Gender','Show'])
data = [
['John',10,'M','Kidzee'],
['Jinny',10,np.nan,'Kidone'],
['Castor',11,'M','Kidkill'],
['Troy',12,'M','Kidkill'],
['Angel',9,'F','Kidmoon'],
['Gretel',11,'M','Kidhorror'],
['Elv',15,'F','Kidzee'],
]
df = pd.DataFrame(index=index, columns=columns,data=data)
# To drop a row with NaN values
# df = df.dropna(axis=0)
# To drop a columns with NaN values
# df = df.dropna(axis=1)
# To fill any missing value
# df = df.fillna(value='F')
# print(df)
# To apply some change in each in the df
df = df[['Name','Show']].apply(lambda var : var+"AA")
print(df)
|
cde8fbe48b5fd01b0351b64f1b1a9152f8b7d658 | Abdelrahmanrezk/Sentiment-Behind-Reviews | /Sentiment_behind_reviews/features_extractions/categorical_one_hot_encoding.py | 4,162 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # One Hot Encoding
# one hot encoding is used to encode categorical data and working as follow:
# for each catecorial or word of data convert to integer number but binarry classifcation and each word is 0 or 1.
#
# Then, each integer value is represented as a binary vector that is all zero values except the index of the integer, which is marked with a 1.
# also one hot encoding encode in such away:
# - words represent each words even those which are repeated
# - but columns represent unique words of our corps
#
# ### one hot is used for categorical data like colors = 'red', 'green'
# In[1]:
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
import itertools
import sys
import os
sys.path.append(os.path.abspath('../scraping_cleaning'))
from cleaning_data import *
# ### Example of one hot encoding without library "Manual One Hot Encoding"
#
# Function below take an argument as string like "I am learning NLP"
# and return one hot encoding example like:
#
# 
#
# In[2]:
def convert_string_to_one_hot_manual(text):
'''
Argument:
text as string
return:
one hot encoding data frame
'''
one_hot_encoding = []
text_list = text.split() # covert string to list
# make each word as key and integer as value
text_words_as_key = dict((c,i) for i,c in enumerate(text_list))
for key,val in enumerate(text_list):
# list of zeros and for each word will assign one and everyone else 0
words = [0 for i in text_list]
# assign one for the word in our dictionary
words[text_words_as_key[val]] = 1
# append this one_hot_word vector
one_hot_encoding.append(words)
one_hot_encoding = pd.DataFrame(one_hot_encoding, columns=text_list)
return one_hot_encoding
# In[3]:
def convert_string_to_one_hot_using_pannds(text):
'''
Argument:
text as string
return:
apply one hot encoding on text
'''
text_list = text.split() # covert string to list
print(len(text_list))
one_hot_encoding = pd.get_dummies(text_list) # using pandas
return one_hot_encoding
# ## One-Hot Encoding using sklearn
# **To convert one hot with sklearn you first convert to label encoding.**
# In[4]:
def convert_string_to_labelencoder_using_sklearn(text):
'''
Argument:
function take list of strings:
first convert these strings to list of all words of these string
second apply sklearn to one-hot-encoding
return: hot
'''
# using function from data cleaning to convert the list of strings
text = convert_list_of_strings_to_list_of_words(text)
# convert to data frame of pandas
text = pd.DataFrame(text, columns=['reviews_words'])
# creating instance object from labelencoder
labelencoder = LabelEncoder()
text['labels_encode'] = labelencoder.fit_transform(text['reviews_words'])
return text
# In[5]:
text = convert_string_to_labelencoder_using_sklearn(all_arabic_reviews)
text
# ### convert to one hot
# **function above convert first to label encoding then we convert to one hot encoding.**
#
# Though label encoding is straight way but it has the disadvantage that the numeric values can be misinterpreted by algorithms as having some sort of hierarchy/order as above.
#
# OneHotEncoder from SciKit library only takes numerical categorical values, hence any value of string type should be label encoded before one hot encoded. So taking the dataframe from the previous example, we will apply OneHotEncoder.
# In[6]:
def convert_string_to_one_hot_using_sklearn(text):
'''
Argument:
dataframe from the previous example
return:
apply OneHotEncoder on column
'''
one_hot_encod = OneHotEncoder()
one_hot_encod = pd.DataFrame(one_hot_encod.fit_transform(text[['labels_encode']]).toarray(), dtype=int)
return one_hot_encod
# In[7]:
one_hot_encod = convert_string_to_one_hot_using_sklearn(text[:10])
one_hot_encod
# In[ ]:
# In[ ]:
|
39184c74599d7e273f6f06b1cddd0fa47c5d4e08 | 15902276147/my_python_practice | /python_practise/threading/queue_threading.py | 1,733 | 3.703125 | 4 | #coding:utf-8
from threading import Thread
from time import sleep
import queue
"""
def count_task(items,result_queue):
number = 0
for x in items:
number += x
result_queue.put(number)
if __name__ == "__main__":
result_queue = queue.Queue()
number_list = [x for x in range(100000)]
index = 0
threading_list = []
for _ in range(5) :
t = Thread(target=count_task,args=(number_list[index:index+20000],result_queue))
index += 20000
threading_list.append(t)
t.start()
for t in threading_list:
t.join()
result = 0
while not result_queue.empty():
result += result_queue.get()
print (result)
"""
class producer(Thread):
def run(self):
global result_queue
counter = 0
while True:
if result_queue.qsize() < 1000:
for x in range(100):
counter = counter + 1
msg = '生成产品' + str(counter)
result_queue.put(msg)
print (msg)
sleep(0.5)
class consumer(Thread):
def run(self):
global result_queue
while True:
if result_queue.qsize() > 100 :
for x in range(3):
msg = self.name + '消费了' + result_queue.get()
print (msg)
sleep (1)
if __name__ == '__main__' :
result_queue = queue.Queue()
"""
for x in range(500):
result_queue.put('初始产品'+str(x))
"""
for x in range(2):
p = producer()
p.start()
for x in range(5):
c = consumer()
c.start()
|
25017c2178e5cf6613b37136d292e6a490d4d775 | jy-hwang/CodeItPython | /a_i/dictionary.py | 716 | 3.96875 | 4 | lists = [3, 4, 1, 2, 7]
print(lists[1])
# 사전 dict()
# dictionary : key - value
dict1 = {}
print(type(dict1))
dict1[5] = 25
dict1[2] = 4
dict1[3] = 9
print(dict1)
family = {}
family['mom'] = 'grace'
family['dad'] = 'chris'
family['son'] = 'young'
family['daughter'] = 'kay'
print(family)
print(family.keys())
print(family.values())
print('son' in family.keys())
print('uncle' in family.keys())
family_keys = list(family.values())
print(family_keys)
print(type(family_keys))
x = {
"name": "워니",
"age": 20
}
print(x)
print(x["name"])
print(x["age"])
print("age" in x)
for key in family:
print("key : " + str(key))
print("value : " + str(family[key]))
x[0] = "워니"
print(x) |
6bd84d7109af8ad224739cf4a037cd53efb18831 | akaIDIOT/2020-aoc | /07/handy-haversacks.py | 1,252 | 3.515625 | 4 | from collections import defaultdict
import re
def parse_rule(line):
outer, inners = line.split(' bags contain ')
inners = re.split(r' bags?[,\.]\s*', inners)
inners = [inner.split(maxsplit=1) for inner in inners if inner and inner != 'no other']
inners = {color: int(num) for num, color in inners}
return outer, inners
def num_bags(forward, color):
if not forward.get(color):
return 0
inners = forward.get(color)
return sum(inners.values()) + sum(num * num_bags(forward, inner) for inner, num in inners.items())
if __name__ == '__main__':
reverse = defaultdict(set)
forward = {}
with open('input', 'r') as in_file:
for line in in_file:
outer, inners = parse_rule(line.strip())
forward[outer] = inners
for inner, num in inners.items():
reverse[inner].add(outer)
start = 'shiny gold'
known = set(reverse[start])
seen = set()
while fringe := known - seen:
for bag in fringe:
known.update(reverse[bag])
seen.add(bag)
print(f'Number of bags that contain at least one {start} bag: {len(known)}')
print(f'Total number of bags inside the {start} bag: {num_bags(forward, start)}')
|
ce7a26a9b012df814ed5b6c47ee91db79dba1a4c | gabriellaec/desoft-analise-exercicios | /backup/user_352/ch149_2020_04_13_19_58_45_529367.py | 1,075 | 3.9375 | 4 | salario_bruto=float(input("qual o seu salário bruto?"))
numero_dependentes=int(input("quantos dependentes você possui?"))
def calculo_irrf(salario_bruto, numero_dependentes):
if salario_bruto>6101.06:
inss = 671.12
elif salario_bruto<=1045.00:
inss = salario_bruto*0.075
elif salario_bruto>1045.00 and salario_bruto<=2089.60:
inss = salario_bruto*0.12
else:
inss = salario_bruto*0.14
base_de_calculo = salario_bruto - inss - (numero_dependentes*189.59)
if base_de_calculo<=1903.98:
irrf=0
print(irrf)
return irrf
elif base_de_calculo>1903.98 and base_de_calculo<=2826.65:
aliquota=0.075
deducao=142.80
elif base_de_calculo>2826.65 and base_de_calculo<=3751.05:
aliquota=0.15
deducao=354.80
elif base_de_calculo>3751.05 and base_de_calculo<=4664.65:
aliquota=0.225
deducao=636.13
else:
aliquota=0.275
deducao=869.36
irrf = (base_de_calculo*aliquota)-deducao
print(irrf)
return irrf
|
52c9c3a109f4d30380900a929c0e077fcddd9775 | saran87/machine-learning | /Titanic/predict_class.py | 5,563 | 4.0625 | 4 | #The first thing to do is to import the relevant packages
# that I will need for my script,
#these include the Numpy (for maths and arrays)
#and csv for reading and writing csv files
#If i want to use something from this I need to call
#csv.[function] or np.[function] first
import csv as csv
import numpy as np
#Open up the csv file in to a Python object
csv_file_object = csv.reader(open('data/train.csv', 'rb'))
header = csv_file_object.next() #The next() command just skips the
#first line which is a header
data=[] #Create a variable called 'data'
for row in csv_file_object: #Run through each row in the csv file
data.append(row) #adding each row to the data variable
data = np.array(data) #Then convert from a list to an array
#Be aware that each item is currently
#a string in this format
#The size function counts how many elements are in
#in the array and sum (as you would expects) sums up
#the elements in the array.
number_passengers = np.size(data[0::,0].astype(np.float))
number_survived = np.sum(data[0::,1].astype(np.float))
print "number of passengers : " + str(number_passengers)
print "number of survived : " + str(number_survived)
proportion_survivors = number_survived / number_passengers
print "survived % : " + str(proportion_survivors)
fare_ceiling = 40
data[data[0::,9].astype(np.float) >= fare_ceiling, 8] = fare_ceiling-1.0
fare_bracket_size = 10
number_of_price_brackets = fare_ceiling / fare_bracket_size
number_of_classes = 3 #There were 1st, 2nd and 3rd classes on board
# Define the survival table
survival_table = np.zeros((2, number_of_classes, number_of_price_brackets))
for i in xrange(number_of_classes): #search through each class
for j in xrange(number_of_price_brackets): #search through each price
women_only_stats = data[
(data[0::,4] == "female")
&(data[0::,2].astype(np.float)
== i+1)
&(data[0:,9].astype(np.float)
>= j*fare_bracket_size)
&(data[0:,9].astype(np.float)
< (j+1)*fare_bracket_size)
, 1] #in the 1st col
men_only_stats = data[
(data[0::,4] != "female")
&(data[0::,2].astype(np.float)
== i+1)
&(data[0:,9].astype(np.float)
>= j*fare_bracket_size)
&(data[0:,9].astype(np.float)
< (j+1)*fare_bracket_size)
, 1]
survival_table[0,i,j] = np.mean(women_only_stats.astype(np.float)) #Women stats
survival_table[1,i,j] = np.mean(men_only_stats.astype(np.float)) #Men stats
survival_table[ survival_table != survival_table ] = 0
survival_table[ survival_table < 0.5 ] = 0
survival_table[ survival_table >= 0.5 ] = 1
test_file_obect = csv.reader(open('data/test.csv', 'rb'))
fname = "data/genderclasspricebasedmodelpy.csv"
open_file_object = csv.writer(open(fname, "wb"))
header = test_file_obect.next()
for row in test_file_obect: #we are going to loop
#through each passenger in the test set
for j in xrange(number_of_price_brackets): #For each passenger we
#loop thro each price bin
try: #Some passengers have no
#price data so try to make
row[8] = float(row[8]) # a float
except: #If fails: no data, so
bin_fare = 3-float(row[1]) #bin the fare according class
break #Break from the bin loop
if row[8] > fare_ceiling: #If there is data see if
#it is greater than fare
#ceiling we set earlier
bin_fare = number_of_price_brackets-1 #If so set to highest bin
break #And then break bin loop
if row[8] >= j*fare_bracket_size and row[8] < (j+1)*fare_bracket_size:
#If passed these tests
#then loop through each
#bin
bin_fare = j #then assign index
break
print bin_fare
if row[3] == 'female': #If the passenger is female
row.insert(0, #at element 0, insert
int(survival_table[0,float(row[1])-1, #the prediction from
bin_fare])) #Insert the prediciton #survival table
open_file_object.writerow(row) #And write out row
else:
row.insert(0,
int(survival_table[1,float(row[1])-1,
bin_fare]))
open_file_object.writerow(row) |
701e55fe7f01e2587964146accaea8a1da191c8e | c3rberuss/MetodosNumericos | /metodos_numericos/biseccion.py | 2,162 | 3.6875 | 4 | import math
inferior = 0.0
superior = 0.0
ecuacion = ""
tolerancioa = 0.0
resultado = 0.0
x = 0.0
def exp(x, expo):
return math.pow(x, expo)
def raiz(x, expo=2):
return exp(x, 1/expo)
def cos(x):
return math.cos(x)
def sen(x):
return math.sin(x)
def tan(x):
return math.tan(x)
def firstStep(ecu, a, b):
global x
x = a
funcA = float(eval(ecu))
print("paso 1: FuncA = %f"%(funcA))
x = b
funcB = float(eval(ecu))
print("paso 1: FuncB = %f"%(funcB))
if funcA*funcB < 0:
print("Respuesta paso 1: True")
return True
print("Respuesta paso 1: False")
return False
def secondStep(a, b):
res = float((a + b) / 2)
print("Respuesta paso 2: %f" %(res))
return res
def thirdStep(ecu, a, xr):
global x
global superior
global inferior
global resultado
x = a
funcA = float(eval(ecu))
print("paso 3: FuncA = %f"%(funcA))
x = xr
funcXr = float(eval(ecu))
print("paso 3: FuncA = %f"%(funcA))
if float(funcA*funcXr) < 0.0:
print("valor inicial de superior -> %f"%(superior))
superior = xr
print("valor actual de superior -> %f"%(superior))
return False
elif float(funcA*funcXr) > 0.0:
print("valor inicial de inferior -> %f"%(inferior))
inferior = xr
print("valor actual de inferior -> %f"%(inferior))
return False
elif float(funcA*funcXr) == 0.0 :
resultado = xr
return True
def eval_(a, b, ec, tol):
global inferior
inferior = float(a)
global superior
superior = float(b)
global ecuacion
ecuacion = str(ec)
global tolerancioa
tolerancioa = float(tol)
if firstStep(ecuacion, inferior, superior):
finalizado = False
while not finalizado:
p = secondStep(inferior, superior)
print(p)
finalizado = thirdStep(ecuacion, inferior, p)
#print("Resultado: x = %f"%(resultado))
print(float(resultado))
return float(resultado)
else:
print("La Ecucación %s no tiene Raices."%(ecuacion)) |
62cb33844cc9807589e83f21e73f7faaee3856c2 | dictator-x/practise_as | /algorithm/leetCode/0305_numbers_of_islands_II.py | 1,405 | 3.71875 | 4 | """
305. Number of Islands II
"""
from typing import List
class Solution:
def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]:
ret = []
n_dis = [-1] * (m*n)
directions = [(0,1),(0,-1),(1,0),(-1,0)]
count = 0
def findRoot(idx):
return n_dis[idx] if idx == n_dis[idx] else findRoot(n_dis[idx])
for position in positions:
cur_idx = position[0]*n + position[1]
# Important
if n_dis[cur_idx] != -1:
ret.append(count)
continue
# assign default root to itself index
count += 1
n_dis[cur_idx] = cur_idx
# find if it can be an island with neighbour cell
for d in directions:
i, j = position[0] + d[0], position[1] + d[1]
next_idx = i*n + j
if i < 0 or i >= m or j < 0 or j >= n or n_dis[next_idx] == -1:
continue
cur_parent = findRoot(cur_idx)
next_parent = findRoot(next_idx)
print(cur_idx, next_idx)
# key: n_dis[cur_parent] = next_parent will be wrong
if cur_parent != next_parent:
n_dis[next_parent] = cur_parent
count -= 1
ret.append(count)
print(n_dis)
return ret
|
0f29975cfe38fda1dc90024bbf39aa2b797a99d0 | av1234av/hello-world | /linked_list.py | 1,427 | 4.09375 | 4 | class Node(object):
def __init__(self,val):
self.next = None
self.val = val
class LinkedList(object):
def __init__(self):
self.head=None
def add(self,n):
if not self.head:
self.head = n
return
p = self.head
while p.next:
p = p.next
p.next = n
def traverse(self):
p = self.head
pp=[]
while p:
pp.append(p.val)
p = p.next
print pp
def reverse(self):
prev = None
cur=self.head
while cur:
next_node = cur.next
cur.next = prev
prev = cur
cur = next_node
self.head = prev
def find_mid_point(self):
p1=self.head
p2=self.head
while p2 and p2.next:
p1=p1.next
p2=p2.next.next
print 'midpoint {}'.format(p1.val)
return p1
def interweave(self):
p=self.head
p1=self.find_mid_point()
while p1.next:
t=p1.next
p1.next=p.next
p.next=p1
p1=t
self.traverse()
if __name__ == '__main__':
ll = LinkedList()
for i in [10,3,45,2,67,89,3,77,65,34]:
ll.add(Node(i))
print "traversing a list"
ll.traverse()
ll.find_mid_point()
print "reversing a list"
ll.reverse()
ll.traverse()
# ll.interweave() |
019a22fcbea8af03e7ce0c63f8f9470725d87c10 | LeiLu199/assignment6 | /pcl322/assignment6.py | 1,241 | 3.84375 | 4 | #Po-Chih Lin, pcl322
from interval.intervalClass import *
from interval.intervalFunctions import *
from interval.intervalExceptions import *
"""
Accept a list of intervals, and then insert the following inputted intervals
merge any two if neccessary
"""
#Main function
if __name__ == "__main__":
#Input the list of intervals
while True:
#Terminate if the the command is "quit" or keyboardInterrupt
try:
userInput = raw_input("List of intervals? ")
if userInput == "quit":
raise KeyboardInterrupt
intervalList = set_interval_list( userInput )
break
#Invalid intervals appear
except InitErr as err:
print err
except KeyboardInterrupt:
print "\nProgram terminated"
sys.exit(0)
#Input the interval that is going to be inserted
while True:
#Terminate if the the command is "quit" or keyboardInterrupt
try:
userInput = raw_input("Intervals? ")
if userInput == "quit":
raise KeyboardInterrupt
i = interval( userInput )
#Invalid intervals appear
except InitErr as err:
print err
continue
except KeyboardInterrupt:
print ""
break
#Insert the interval
intervalList = insert(intervalList, i)
print_interval_list( intervalList )
print "Program terminated"
|
4ce781a3ff276681467214fa737ebee5342b82a7 | nothingtosayy/Quiz-Using-Python | /main2.py | 825 | 4.03125 | 4 | # Quiz Logic
q1 = """Who is our Prime Minister?
a)Rahul Gandhi
b)Chiranjeevi
c)Narendra Modi"""
q2 = """Whose nickname is king of Cricket?
a)M.s Dhoni
b)Virat Kohli
c)Sachin"""
q3 = """Who is called as Missile Man of India?
a)Dr.A.P.J Abdul Kalam
b)ManMohan Singh
c)Rahul Gandhi"""
marks = 0
questions_dict = {q1:"c",q2:"b",q3:"a"}
for question in questions_dict:
print(question)
user_ans = input("Enter your option : ")
if user_ans == questions_dict[question]:
print("Correct Answer")
marks = marks + 1
else:
print("Wrong Answer")
marks = marks - 1
user_exit_process = input(f"Want to exit(yes/no) : ")
if user_exit_process == 'yes':
break
print(f"Marks you have been awarded are : {marks}")
|
5b38eecd47ce16ab45f8312debf8f1b7fad26b8d | PolishDom/COM411 | /basics/functions/sounds.py | 177 | 3.609375 | 4 | def loudsound():
sound = input("What word would you describe the sound?")
print ("What did you just hear?")
print (sound)
print("That was a loud",sound)
loudsound()
|
f38dc373075807aecaeef4472211b3fd0867ec8b | NeyBrito/Phyton | /Scripts-Python/pythontest/desafio29.py | 267 | 3.671875 | 4 | ca = float(input('Qual sua velocidade?'))
if ca > 80:
n1 = (ca - 80) * 7
print(' Você está acima do limite de velocidade. REDUZA!\n Você está sendo multado em {:.2f}'.format(n1))
else:
print('Você está dentro do limite de velocidade. BOA VIAGEM!')
|
3f18a4c9dbad9d78cc61273876452fd9276c8c69 | Semal80/Courses | /HomeWork6/hw6_4.py | 389 | 4.15625 | 4 | ##################################
# Leap Year #
##################################
while True:
try:
a = int(input("Input a year:"))
except ValueError:
print("This is not number")
continue
if (a % 4 == 0) and (a % 100 != 0) or (a % 400 == 0):
print("This is a leap year")
else:
print("This is not a leap year")
|
7c26da8af224c3c6452198be5a2228fac2a84117 | ezequielfrias20/exam-mutant | /src/mutant.py | 3,210 | 3.796875 | 4 | '''
Funcion que permite ver si una persona es mutante o no,
tiene como parametro una lista y devuelve True si es mutante
o False si no lo es
'''
def Mutant(adn):
try:
'''
Funcion que permite verificar si la matriz es correcta
siendo NxN y que solo tenga las letras A T C G.
Devuelve True si todo esta correcto
'''
def check(adn):
contador=0
verificacion=0
for elemento in adn:
for letra in elemento:
if letra=="A" or letra=="T" or letra=="C" or letra=="G":
contador+=1
if contador!=len(adn):
raise Exception
else:
verificacion+=1
contador=0
return verificacion==len(adn)
'''
Esta funcion permita verificar si es mutante
de manera horizontal
'''
def is_mutant_horizontal(adn):
mutacion=False
for elemento in adn:
for letra in elemento:
if elemento.count(letra)>=4:
mutan=letra+letra+letra+letra
if mutan in elemento:
mutacion= True
break
return mutacion
'''
Esta funcion permite crear una nueva lista con los
valores verticales y se aplica
la funcion is_mutant_horizontal
'''
def is_mutant_vertical(adn):
vertical=""
new_adn=[]
for i in range(len(adn)):
for a in range(len(adn)):
vertical+=adn[a][i]
new_adn.append(vertical)
vertical=""
return is_mutant_horizontal(new_adn)
'''
funcion que permite encontrar las diagonales de la matriz
'''
def get_diagonals(matrix):
n = len(matrix)
# diagonals_1 = [] # lower-left-to-upper-right diagonals
# diagonals_2 = [] # upper-left-to-lower-right diagonals
for p in range(2*n-1):
yield [matrix[p-q][q] for q in range(max(0, p - n + 1), min(p, n - 1) + 1)]
yield [matrix[n-p+q-1][q] for q in range(max(0, p - n + 1), min(p, n - 1) + 1)]
'''
Esta funcion permite crear una nueva lista con los
valores de todas las diagonales y se aplica
la funcion is_mutant_horizontal para ver si es mutante
'''
def is_mutant_oblicua(adn):
new=[]
new_word=""
for i in get_diagonals(adn):
for element in i:
new_word+=element
new.append(new_word)
new_word=""
return is_mutant_horizontal(new)
check(adn)
if is_mutant_horizontal(adn):
return True
elif is_mutant_oblicua(adn):
return True
elif is_mutant_vertical(adn):
return True
else:
return False
except Exception:
return None
|
8fcf842e7d9df99ed8733d737ed68264c6d39616 | zizle/MarketAnalyser | /utils/day.py | 492 | 3.578125 | 4 | # _*_ coding:utf-8 _*_
# @File : day.py
# @Time : 2020-11-27 11:12
# @Author: zizle
import datetime
def generate_days_of_year():
""" 生成一年的每一月每一天 """
days_list = list()
start_day = datetime.datetime.strptime("2020-01-01", "%Y-%m-%d")
end_day = datetime.datetime.strptime("2020-12-31", "%Y-%m-%d")
while start_day <= end_day:
days_list.append(start_day.strftime("%m%d"))
start_day += datetime.timedelta(days=1)
return days_list
|
2db0515918fc48d00d4cb1cb397fbfb3075a5a6f | nurnisi/algorithms-and-data-structures | /leetcode/0-250/275-859. Buddy Strings.py | 688 | 3.65625 | 4 | # 859. Buddy Strings
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B) or len(A) == 1: return False
# create array of indices, where A and B differ
# also count character occurences
dif, count = [], [0] * 26
for i in range(len(A)):
if A[i] != B[i]: dif.append(i)
count[ord(A[i]) - ord('a')] += 1
if len(dif) > 2: return False
elif len(dif) == 2:
if A[dif[0]] != B[dif[1]] or B[dif[0]] != A[dif[1]]: return False
else: return True
else: return any([c > 1 for c in count])
print(Solution().buddyStrings("abcaa", "abcbb")) |
a991c099f3823a5054fd3d2088df7e175f1ba190 | ChangXiaodong/Leetcode-solutions | /4/542-01_Matrix.py | 1,119 | 3.546875 | 4 | class Solution(object):
def dfs(self, matrix, access, res, steps, i, j):
if i >= len(matrix) or j >= len(matrix[0]) or access[i][j] or matrix[i][j] == 0:
return steps
access[i][j] = True
res = min(self.dfs(matrix, access, res, steps + 1, i + 1, j), res)
res = min(self.dfs(matrix, access, res, steps + 1, i - 1, j), res)
res = min(self.dfs(matrix, access, res, steps + 1, i, j + 1), res)
res = min(self.dfs(matrix, access, res, steps + 1, i, j - 1), res)
access[i][j] = False
return res
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
rows = len(matrix)
cols = len(matrix[0])
access = [[False for _ in range(cols)] for _ in range(rows)]
for i in range(rows):
for j in range(cols):
if matrix[i][j] != 0:
matrix[i][j] = self.dfs(matrix, access, float("inf"), 0, i, j)
return matrix
solution = Solution()
print(solution.updateMatrix([[0, 0, 0], [0, 1, 0], [1, 1, 1]]))
|
117d36eda839f670ca87311e52bf28735186e52c | MaiziXiao/Algorithms | /Leetcode 101/千奇百怪的排序算法/堆排序.py | 1,330 | 3.578125 | 4 | # 堆排序
# https://blog.csdn.net/Hk_john/article/details/79888992
# 堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。
# 堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。
# 堆是一种非线性结构,可以把堆看作一个数组,也可以被看作一个完全二叉树,通俗来讲堆其实就是利用完全二叉树的结构来维护的一维数组
# 按照堆的特点可以把堆分为大顶堆和小顶堆
# 大顶堆:每个结点的值都大于或等于其左右孩子结点的值
# 小顶堆:每个结点的值都小于或等于其左右孩子结点的值
# 将初始待排序关键字序列(R1,R2….Rn)构建成大顶堆,此堆为初始的无序区;
# 将堆顶元素R[1]与最后一个元素R[n]交换,此时得到新的无序区(R1,R2,……Rn-1)和新的有序区(Rn),且满足R[1,2…n-1]<=R[n];
# 由于交换后新的堆顶R[1]可能违反堆的性质,因此需要对当前无序区(R1,R2,……Rn-1)调整为新堆,然后再次将R[1]与无序区最后一个元素交换,
# 得到新的无序区(R1,R2….Rn-2)和新的有序区(Rn-1,Rn)。不断重复此过程直到有序区的元素个数为n-1,则整个排序过程完成。 |
c6ae34192fe3596e5ddd6e64a26fb0ab1a6f1368 | Vikas-ML/NUMPUZZ | /Game.py | 755 | 3.859375 | 4 | def numpuz():
print(" ","WELCOME IN OUR GAME")
print()
print(" ","1.PRESS 1 FOR EASY(2X2)")
print(" ","2.PRESS 2 FOR MEDIUM(3X3)")
print(" ","3.PRESS 3 FOR HARD(4X4)")
ch=input("enter your choice= ")
while ch.isdigit() != True:
print("enter in integer format")
ch= input("enter your age")
else:
print()
if ch=='1':
import game1 as g
g.game()
elif ch=='2':
import game2 as g
g.game()
elif ch=='3':
import game3 as g
g.game()
else:
print("YOU HAVE TO CHOOSE ANY ONE TO PLAY THE GAME")
numpuz()
|
e6e1b6c0cf62165d0fb6d36923ca28f6a303e8bb | amarotta1/um-programacion-i-2020 | /59103- Marotta,Alejandro/Tp1/POO/ej18_ob.py | 2,227 | 3.984375 | 4 | """ Ejercicio 18
Modificar el programa del ejercicio 17 agregando un control de datos vacíos.
Si por algún motivo alguno de los datos viene vacío o igual a "" debemos generar una
excepción indicando que ocurrió un problema con la fuente de datos y notificar por pantalla.
La excepción debe ser una excepción propia.
"""
import json
class ValorVacio(ValueError):
def __init__(self):
super(ValorVacio, self).__init__()
class Ventas():
def __init__(self, path):
self.path = path
self.documento = open(self.path,"r")
self.texto = self.documento.read()
self.filas = self.texto.split("\n")
def pasar_JSON(self):
self.datos= {}
self.datos['ventas'] = []
for valor in self.filas :
lista = valor.split(",")
self.datos['ventas'].append({
'nombre': lista[0],
'monto': lista[1],
'descripcion': lista[2],
'formapago': lista[3]})
with open('ARCHIVO_ORIGINAL.json', 'w') as file:
json.dump(self.datos, file, indent=4)
def mostrar(self):
with open('ARCHIVO_ORIGINAL.json') as file:
datos = json.load(file)
for venta in datos['ventas']:
try:
values = venta.values()
if "" in values:
raise ValorVacio()
else:
print('Nombre: ', venta['nombre'])
print('Monto: $', venta['monto'])
print('Descripcion: ', venta['descripcion'])
print('Forma de pago: ', venta['formapago'])
print('')
except ValorVacio:
print ("---------ERROR----------")
print("Error en los datos del cliente: ", venta['nombre'])
print ('Ningun valor puede estar vacio')
print("\n")
""" Ejemplo:
venta = Ventas("c:/Users/amaro/OneDrive/Documents/Programacion 1/TP1/datos_ventas.txt")
venta.pasar_JSON()
venta.mostrar()
"""
|
0659a4828be6a5d60ef0f045e4b64920cc3b56cd | ramasawmy/Python-program | /UserInputVowel.py | 419 | 3.921875 | 4 | y = input("enter a sentence:")
vowels=0
consonant=0
digit=0
specailchar=0
for x in y:
if x.isalpha():
if (x=="a" or x=="e" or x=="i" or x=="o" or x=="u"):
vowels +=1
else:
consonant+=1
elif x.isdigit():
digit+=1
else:
specailchar+=1
print("vowels=",vowels)
print("conspnant=",consonant)
print("digit=",digit)
print("specailchar",specailchar )
|
dee2975eb2b33f6a4a690f1ba1926d6d0e28f7d9 | malewis5/Data-Structures-and-Algorithms-Python | /Fibonacci.py | 710 | 3.921875 | 4 | ## Iterative Solution ##
def iterFibonacci(n):
if n < 0:
return ValueError('Number must be positive.')
fibs_list = [0,1]
if n <= len(fibs_list) - 1:
return fibs_list[n]
else:
while n > len(fibs_list) - 1:
next_fib = fibs_list[-1] + fibs_list[-2]
fibs_list.append(next_fib)
return fibs_list[n]
# test cases
print(iterFibonacci(3) == 2)
print(iterFibonacci(7) == 13)
print(iterFibonacci(0) == 0)
print(iterFibonacci(-1))
## Recursive Solution ##
def recFibonacci(n):
if n < 0:
ValueError("Input 0 or greater only!")
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(recFibonacci(3))
print(recFibonacci(7))
print(recFibonacci(0))
|
02c113d8b593c023e3c3061caf0ee84cc2ed600e | ipableras/PildorasInformaticasPython | /TrabajoConListas.py | 472 | 4.3125 | 4 | # Listas
# doc python
trabajadores =["Ana", "María", "Antonio", "Miguel"]
print(trabajadores)
print(len(trabajadores))
print(trabajadores.index("Antonio"))
trabajadores.append("Juan")
print(trabajadores)
print(trabajadores[2])
print(trabajadores)
print(trabajadores[-2])
print(trabajadores)
print()
# Borrar Maria
print(trabajadores)
del trabajadores[1]
print(trabajadores)
print()
print(trabajadores[0:3])
print(trabajadores[2:3])
print(trabajadores[3:2])
|
31e8b552f313204a6da3d1b29705d51e6ac5bfd9 | anhaidgroup/py_stringmatching | /py_stringmatching/tokenizer/qgram_tokenizer.py | 8,314 | 3.5625 | 4 | from six import string_types
from six.moves import xrange
from py_stringmatching import utils
from py_stringmatching.tokenizer.definition_tokenizer import DefinitionTokenizer
class QgramTokenizer(DefinitionTokenizer):
"""Returns tokens that are sequences of q consecutive characters.
A qgram of an input string s is a substring t (of s) which is a sequence of q consecutive characters. Qgrams are also known as
ngrams or kgrams.
Args:
qval (int): A value for q, that is, the qgram's length (defaults to 2).
return_set (boolean): A flag to indicate whether to return a set of
tokens or a bag of tokens (defaults to False).
padding (boolean): A flag to indicate whether a prefix and a suffix should be added
to the input string (defaults to True).
prefix_pad (str): A character (that is, a string of length 1 in Python) that should be replicated
(qval-1) times and prepended to the input string, if padding was
set to True (defaults to '#').
suffix_pad (str): A character (that is, a string of length 1 in Python) that should be replicated
(qval-1) times and appended to the input string, if padding was
set to True (defaults to '$').
Attributes:
qval (int): An attribute to store the q value.
return_set (boolean): An attribute to store the flag return_set.
padding (boolean): An attribute to store the padding flag.
prefix_pad (str): An attribute to store the prefix string that should be used for padding.
suffix_pad (str): An attribute to store the suffix string that should
be used for padding.
"""
def __init__(self, qval=2,
padding=True, prefix_pad='#', suffix_pad='$',
return_set=False):
if qval < 1:
raise AssertionError("qval cannot be less than 1")
self.qval = qval
if not type(padding) == type(True):
raise AssertionError('padding is expected to be boolean type')
self.padding = padding
if not isinstance(prefix_pad, string_types):
raise AssertionError('prefix_pad is expected to be of type string')
if not isinstance(suffix_pad, string_types):
raise AssertionError('suffix_pad is expected to be of type string')
if not len(prefix_pad) == 1:
raise AssertionError("prefix_pad should have length equal to 1")
if not len(suffix_pad) == 1:
raise AssertionError("suffix_pad should have length equal to 1")
self.prefix_pad = prefix_pad
self.suffix_pad = suffix_pad
super(QgramTokenizer, self).__init__(return_set)
def tokenize(self, input_string):
"""Tokenizes input string into qgrams.
Args:
input_string (str): The string to be tokenized.
Returns:
A Python list, which is a set or a bag of qgrams, depending on whether return_set flag is True or False.
Raises:
TypeError : If the input is not a string
Examples:
>>> qg2_tok = QgramTokenizer()
>>> qg2_tok.tokenize('database')
['#d', 'da', 'at', 'ta', 'ab', 'ba', 'as', 'se', 'e$']
>>> qg2_tok.tokenize('a')
['#a', 'a$']
>>> qg3_tok = QgramTokenizer(qval=3)
>>> qg3_tok.tokenize('database')
['##d', '#da', 'dat', 'ata', 'tab', 'aba', 'bas', 'ase', 'se$', 'e$$']
>>> qg3_nopad = QgramTokenizer(padding=False)
>>> qg3_nopad.tokenize('database')
['da', 'at', 'ta', 'ab', 'ba', 'as', 'se']
>>> qg3_diffpads = QgramTokenizer(prefix_pad='^', suffix_pad='!')
>>> qg3_diffpads.tokenize('database')
['^d', 'da', 'at', 'ta', 'ab', 'ba', 'as', 'se', 'e!']
"""
utils.tok_check_for_none(input_string)
utils.tok_check_for_string_input(input_string)
qgram_list = []
# If the padding flag is set to true, add q-1 "prefix_pad" characters
# in front of the input string and add q-1 "suffix_pad" characters at
# the end of the input string.
if self.padding:
input_string = (self.prefix_pad * (self.qval - 1)) + input_string \
+ (self.suffix_pad * (self.qval - 1))
if len(input_string) < self.qval:
return qgram_list
qgram_list = [input_string[i:i + self.qval] for i in
xrange(len(input_string) - (self.qval - 1))]
qgram_list = list(filter(None, qgram_list))
if self.return_set:
return utils.convert_bag_to_set(qgram_list)
return qgram_list
def get_qval(self):
"""Gets the value of the qval attribute, which is the length of qgrams.
Returns:
The value of the qval attribute.
"""
return self.qval
def set_qval(self, qval):
"""Sets the value of the qval attribute.
Args:
qval (int): A value for q (the length of qgrams).
Raises:
AssertionError : If qval is less than 1.
"""
if qval < 1:
raise AssertionError("qval cannot be less than 1")
self.qval = qval
return True
def get_padding(self):
"""
Gets the value of the padding flag. This flag determines whether the
padding should be done for the input strings or not.
Returns:
The Boolean value of the padding flag.
"""
return self.padding
def set_padding(self, padding):
"""
Sets the value of the padding flag.
Args:
padding (boolean): Flag to indicate whether padding should be
done or not.
Returns:
The Boolean value of True is returned if the update was
successful.
Raises:
AssertionError: If the padding is not of type boolean
"""
if not type(padding) == type(True):
raise AssertionError('padding is expected to be boolean type')
self.padding = padding
return True
def get_prefix_pad(self):
"""
Gets the value of the prefix pad.
Returns:
The prefix pad string.
"""
return self.prefix_pad
def set_prefix_pad(self, prefix_pad):
"""
Sets the value of the prefix pad string.
Args:
prefix_pad (str): String that should be prepended to the
input string before tokenization.
Returns:
The Boolean value of True is returned if the update was
successful.
Raises:
AssertionError: If the prefix_pad is not of type string.
AssertionError: If the length of prefix_pad is not one.
"""
if not isinstance(prefix_pad, string_types):
raise AssertionError('prefix_pad is expected to be of type string')
if not len(prefix_pad) == 1:
raise AssertionError("prefix_pad should have length equal to 1")
self.prefix_pad = prefix_pad
return True
def get_suffix_pad(self):
"""
Gets the value of the suffix pad.
Returns:
The suffix pad string.
"""
return self.suffix_pad
def set_suffix_pad(self, suffix_pad):
"""
Sets the value of the suffix pad string.
Args:
suffix_pad (str): String that should be appended to the
input string before tokenization.
Returns:
The boolean value of True is returned if the update was
successful.
Raises:
AssertionError: If the suffix_pad is not of type string.
AssertionError: If the length of suffix_pad is not one.
"""
if not isinstance(suffix_pad, string_types):
raise AssertionError('suffix_pad is expected to be of type string')
if not len(suffix_pad) == 1:
raise AssertionError("suffix_pad should have length equal to 1")
self.suffix_pad = suffix_pad
return True
|
b935fc6ec8e15cd5bf8b4cfe2210bd8c84f8aec9 | jchooker/py-functions-basic2 | /functions-basic2.py | 2,288 | 3.703125 | 4 | from typing import Match
import numpy as np
#1 - Countdown
def countdown(startNum):
counted=[]
for i in range(startNum,-1,-1):
counted.append(i)
return counted
countVal = input("Enter a positive value from which to count down: ")
print(countdown(int(countVal)))
#2 - Print and return
def printReturn(arr):
print(arr[0])
return arr[1]
arr2 = []
arr2.append(int(input("Please input value 1: ")))
arr2.append(int(input("Please input value 2: ")))
print(printReturn(arr2))
#3 - First Plus Length
def firstPlusLen(arr):
return arr[0] + len(arr)
arrScale = (int(input("Size of array?(1-15): ")))
ronArrTest = [None]*arrScale
for i in range(len(ronArrTest)):
ronArrTest[i] = np.random.randint(-10,200)
print(ronArrTest)
print(firstPlusLen(ronArrTest))
#4 - Values Greater Than Second
def valsGreaterThan2nd(arr):
x = len(arr)
arr2=[]
if x < 2:
return False
elif x == 2:
if arr[0]>arr[1]:
arr2.append(arr[0])
else:
if arr[0]>arr[1]:
arr2.append(arr[0])
for i in range(2,x):
if arr[i]>arr[1]:
arr2.append(arr[i])
# match x:
# case 0:
# return False
# case 1:
# return False
# case 2:
# if arr[0]>arr[1]:
# arr2.append(arr[0])
# case _:
# if arr[0]>arr[1]:
# arr2.append(arr[0])
# for i in range(2,x):
# if arr[i]>arr[1]:
# arr2.append(arr[i])
print(len(arr2))
return arr2
arrScale = (int(input("Size of array?(0 or larger - but the fun starts at 2): ")))
newArr = [None]*arrScale
for i in range(len(newArr)):
newArr[i] = np.random.randint(-200,200)
print(newArr)
print(valsGreaterThan2nd(newArr))
#5 - This Length, That Value
def lengthAndValue(size, val):
x = []
for i in range(size):
x.append(val)
return x
isValidInput = False
arrSize = 0
while not isValidInput:
arrSize = int(input("Enter a valid size for our array: "))
if arrSize > 0:
isValidInput = True
else:
print("PlEaSe provide valid input!")
arrVal = 0
arrVal = int(input("Please provide a number to populate array: "))
print(lengthAndValue(arrSize, arrVal))
|
e65caff977ee78c00d4df4e94006e79bba7f3a4e | Roopa07/Player-Set-1 | /fact.py | 100 | 3.703125 | 4 | n=int(input())
fact=1
if fact==0:
print("1")
else:
for i in range(1,n+1):
fact *=i
print(fact)
|
ba56ae77b75b720b5752ddb3d8bb5e80fd2d0d85 | green-fox-academy/FulmenMinis | /week-03/day-03/triangles.py | 1,177 | 3.875 | 4 | from tkinter import *
root = Tk()
canvas = Canvas(root, width='400', height='600')
canvas.pack()
# 21 db egy oldalon ~25oldalszélesség
# reproduce this:
# [https://github.com/greenfox-academy/teaching-materials/blob/master/workshop/drawing/triangles/r5.png]
def draw_triangles(x, y):
black_line = canvas.create_line(x, y, x + 7.5, y + 15, fill="black")
black_line = canvas.create_line(x, y, x - 7.5, y + 15, fill="black")
black_line = canvas.create_line(x - 7.5, y + 15, x + 7.5, y + 15, fill="black")
x = 200
y = 100
for i in range(22):
y += 15
x -= 7.5
for j in range(i):
x += 15
draw_triangles(x, y)
x -= i * 15
root.mainloop()
#----------------------------------------
from tkinter import *
from math import sqrt
root = Tk()
canvas = Canvas(root, width='600', height='600')
canvas.pack()
rows = int(input("number of rows generated by triangels: "))
a = 600 // rows
h = int(a*sqrt(3)/2)
def tri(x,y, a, h):
tri = canvas.create_polygon(x, y, x + a, y, x + a/2, y - h, outline='black', fill='white', width=1)
for i in range(rows):
for j in range(rows-i):
tri(j*a+i*a/2, 600-(i*h), a, h)
root.mainloop() |
712dbe61a0174df5e61bfd1ee8ffe692064a3703 | gnperdue/Euler | /Code/Python/problem032/euler032.py | 1,657 | 3.640625 | 4 | #!/usr/bin/env python
import numpy as np
def has_unique_digits(num):
list_of_digits = []
temp_num = num
while temp_num > 0:
last_digit = temp_num % 10
temp_num -= last_digit
temp_num /= 10
list_of_digits.append(last_digit)
return len(np.unique(list_of_digits)) == len(list_of_digits)
def is_list_of_unique_digits(list_of_nums):
fullstr = str()
for i in list_of_nums:
fullstr += str(i)
return has_unique_digits(int(fullstr))
def is_pandigital_list(list_of_nums):
fullstr = str()
for i in list_of_nums:
fullstr += str(i)
list_of_chars = list(fullstr)
for c in list_of_chars:
if int(c) == 0:
return False
return has_unique_digits(int(fullstr)) and len(fullstr) == 9
def is_pandigital_group(num):
if not has_unique_digits(num):
return False
for multiplicand in range(2, num):
if num % multiplicand == 0:
multiplier = num / multiplicand
if is_pandigital_list([multiplicand,
multiplier,
num]):
print [multiplicand, multiplier, num]
return True
return False
def get_list_of_pandigitals(max):
list_of_pandigitials = []
for i in range(2, max + 1):
if is_pandigital_group(i):
list_of_pandigitials.append(i)
return list_of_pandigitials
def get_pandigital_sum(max):
pandigital_list = get_list_of_pandigitals(max)
return np.sum(pandigital_list)
def euler():
return get_pandigital_sum(9999)
if __name__ == '__main__':
print euler()
|
25c17300f23f76823cc19a06aafbf973b463a3be | Reetishchand/Leetcode-Problems | /01085_SumofDigitsintheMinimumNumber_Easy.py | 865 | 3.765625 | 4 | '''Given an array A of positive integers, let S be the sum of the digits of the minimal element of A.
Return 0 if S is odd, otherwise return 1.
Example 1:
Input: [34,23,1,24,75,33,54,8]
Output: 0
Explanation:
The minimal element is 1, and the sum of those digits is S = 1 which is odd, so the answer is 0.
Example 2:
Input: [99,77,33,66,55]
Output: 1
Explanation:
The minimal element is 33, and the sum of those digits is S = 3 + 3 = 6 which is even, so the answer is 1.
Constraints:
1 <= A.length <= 100
1 <= A[i] <= 100'''
class Solution:
def findSum(self,num):
s=0
while num>0:
s+=num%10
num=num//10
print(s)
return s
def sumOfDigits(self, A: List[int]) -> int:
# m=min(A)
m=self.findSum(min(A))
# print(m)
return 1 if m%2==0 else 0
|
8d776cda9da24e0f5e5d3daad0b22ad6d437d154 | cjrzs/MyLeetCode | /列表根据指定格式分隔.py | 1,730 | 3.671875 | 4 | '''
coding:utf8
@Time : 2020/3/4 1:58
@Author : cjr
@File : 列表根据指定格式分隔.py
谨以此纪念第一个严格意义上自己开发的算法!
目的:将列表根据指定格式的字符串分隔成子列表并转换成指定格式
例如:
把列表根据以“-”开头的字符串为界限,分隔成不同的子列表,其中以“-”开头的字符串为字典的key,其后的所有元素为value
转换前:["-x", "1", "2", "3", "-q", "4", "5", "6", "-d", "7", "8"]
转换后:[{'-x': ['1', '2', '3']}, {'-q': ['4', '5', '6']}, {'-d': ['7', '8']}]
'''
class Base:
def __init__(self, parm_list: list):
self.parm_list = parm_list
def count_(self):
new_list = []
for item in self.parm_list:
if item.startswith('-'):
new_list.append(self.parm_list.index(item))
return new_list
def list_to_dict(self, l: list):
d = {}
for item in l:
if item.startswith('-'):
key = item
else:
d.setdefault(key, []).append(item)
return d
def parm_to_dict(self) -> list:
parm_index_list = self.count_()
# lst = list(filter(lambda x: parm_index_list[x:x+1], self.parm_list))
result = []
for i in range(len(parm_index_list)):
try:
key_list = self.parm_list[parm_index_list[i]:parm_index_list[i+1]]
new_list = self.list_to_dict(key_list)
result.append(new_list)
except IndexError:
key_list = self.parm_list[parm_index_list[i]:]
new_list = self.list_to_dict(key_list)
result.append(new_list)
return result |
377ca7d7cce5f531895c465566361fe2c7a482fc | nbrahman/Coursera | /Python for everybody/3. Using Python to Access Web Data/Week 6 Assignment 2/geojson.py | 2,701 | 4.3125 | 4 | # Calling a JSON API
# In this assignment you will write a Python program somewhat similar to http://www.pythonlearn.com/code/geojson.py. The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that uniquely identifies a place as within Google Maps.
#
# API End Points
#
# To complete this assignment, you should use this API endpoint that has a static subset of the Google Data:
#
# http://python-data.dr-chuck.net/geojson
#
# This API uses the same parameters (sensor and address) as the Google API. This API also has no rate limit so you can test as often as you like. If you visit the URL with no parameters, you get a list of all of the address values which can be used with this API.
#
# To call the API, you need to provide a sensor=false parameter and the address that you are requesting as the address= parameter that is properly URL encoded using the urllib.urlencode() fuction as shown in http://www.pythonlearn.com/code/geojson.py
#
# Test Data / Sample Execution
#
# You can test to see if your program is working with a location of "South Federal University" which will have a place_id of "ChIJJ8oO7_B_bIcR2AlhC8nKlok".
#
# $ python solution.py
# Enter location: South Federal University
# Retrieving http://...
# Retrieved 2101 characters
# Place id ChIJJ8oO7_B_bIcR2AlhC8nKlok
#
# Turn In
#
# Please run your program to find the place_id for this location:
#
# Institut Superieur de technologies
#
# Make sure to enter the name and case exactly as above and enter the place_id and your Python code below. Hint: The first seven characters of the place_id are "ChIJYdb ..."
#
# Make sure to retreive the data from the URL specified above and not the normal Google API. Your program should work with the Google API - but the place_id may not match for this assignment.
import urllib.request
import urllib.parse
import json
# serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'
serviceurl = 'http://python-data.dr-chuck.net/geojson?'
while True:
address = input('Enter location: ')
if len(address) < 1 : break
url = serviceurl + urllib.parse.urlencode({'sensor':'false', 'address': address})
print ('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read().decode ('utf-8')
print ('Retrieved',len(data),'characters')
try: js = json.loads(str(data))
except: js = None
if (js!= None) and ('status' not in js or js['status'] != 'OK'):
print ('==== Failure To Retrieve ====')
print (data)
continue
print ('Place id ', js["results"][0]["place_id"])
|
f5537c161322a6f9ca9156bf9400a61cc40097fc | KickItAndCode/Algorithms | /Recursion/WordSplit.py | 1,314 | 4.125 | 4 | # # Create a function called word_split() which takes in a string phrase and a set list_of_words. The function will then determine if it is possible to split the string in a way in which words can be made from the list of words. You can assume the phrase will only contain words found in the dictionary if it is completely splittable.
# def word_split(phrase, words, res=None):
# if res is None:
# res = []
# for word in words:
# if phrase.startswith(word):
# res.append(word)
# return word_split(phrase[len(word):], words, res)
# return res
# def word_split(phrase, words, res=None):
# if res is None:
# res = []
# for word in words:
# val = phrase[0: len(word)]
# if val == word:
# res.append(word)
# return word_split(phrase[len(word):], words, res)
# return res
def word_split(phrase, words, res=None):
if res is None:
res = []
for word in words:
if phrase[0: len(word)] == word:
res.append(word)
return word_split(phrase[len(word):], words, res)
return res
word_split('themanran', ['the', 'ran', 'man'])
word_split('ilovedogsJohn', ['i', 'am', 'a', 'dogs', 'lover', 'love', 'John'])
word_split('themanran', ['clown', 'ran', 'man'])
|
1ebcbe231bd4b2209ea54e9182c3dd66712caf46 | RafaelSerrate/C-digos-Python | /Exercicios/Aula 7 - exercicios/Exercicio 005.py | 225 | 4.0625 | 4 | n = int(input('Coloque um numero: '))
ant = n - 1
suc = n + 1
print('O antecessor do {} é {}, e o seu sucessor é {}'.format(n, ant, suc))
print('O antecessor do numero {} é {}, e o seu sucessor é {}'.format(n, n-1, n+1))
|
496f3fc343434dff3f3dde228a9a28595407eefc | subramaniam-kamaraj/codekata_full | /strings/find_non_repeating_character.py | 534 | 4.09375 | 4 | '''
You are given a string ‘S’ consisting of lowercase Latin Letters.
Find the first non repeating character in S.
If you find all the characters are repeating print the answer as -1
Input Description:
You are given a string ‘s’
Output Description:
Print the first non occurring character if possible else -1.
Sample Input :
apple
Sample Output :
a
'''
S=input()
em=[]
if S.islower()==True:
for i in S:
if i not in em:
print(S[0])
else:
em.append(i)
else:
print("-1") |
a26f36c50ca118f6630e32efbcb134abfb27763a | stcybrdgs/myPython-refresher | /pythonEssential/classes_2.py | 1,762 | 4.03125 | 4 | # classes_2.py
# class methods
#
# rem python does not have private variables, so there's no way to actually prevent
# someone from using the class variables, but the self.__ is the conventional way to
# indicate that the variable should be treated as a private variable and that it should
# not be set or retreived outside of a setter or getter
#
class Animal:
# class constructor
def __init__(self, **kwargs):
self._type = kwargs['type'] if 'type' in kwargs else 'dog'
self._name = kwargs['name'] if 'name' in kwargs else 'Jazz'
self._sound = kwargs['sound'] if 'sound' in kwargs else 'bark'
# class methods
# the following methods are both setters and getters
# bc if no value is passed in, then they get the current existing value,
# but if a value is passed in, then they set the value
def type(self, t = None):
if t: self._type = t
return self._type
def name(self, n = None):
if n: self._name = n
return self._name
def sound(self, s = None):
if s: self._sound = s
return self._sound
# the __str__ method is a specially named method which provides the string representation of the object
# (see more such specially named methods under Data Model in the python documentation)
def __str__(self):
return f'The {self.type()} is named "{self.name()}" and says "{self.sound()}".'
def main():
# rem here we are encapsulating variable data, which means that it belongs to the object, not the class
a0 = Animal(type = 'cat', name = 'Garfield', sound = 'meow')
a1 = Animal(type = 'Duck', name = 'Howard', sound = 'Quack')
a2 = Animal()
print(a0)
print(a1)
print(a2)
if __name__ == '__main__': main()
|
01f6e2c889621f3774105906e66fd79b10a20e60 | leeo1116/Algorithms | /LeetCode/Python/Original/039_combination_sum.py | 691 | 3.5 | 4 | class Solution(object):
def combination_sum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
# candidates.sort()
# return self.search(candidates, target)
# def search(self, candidates, target):
if target == 0:
return [[]]
res = []
for i in range(len(candidates)):
if candidates[i] > target:
continue
for r in self.combination_sum(candidates[i:], target-candidates[i]):
res.append([candidates[i]]+r)
return res
s = Solution()
print(s.combination_sum([8, 7, 4, 3], 11))
|
495f26dfbadc0b6a3d820990d02f6c59fa9081a6 | Woosiq92/Pythonworkspace | /4_string.py | 3,527 | 3.9375 | 4 | sentence = '파이썬'
print(sentence)
sentence2 = "파이썬은 쉬워요 "
print(sentence2)
sentence3 = """
나는 파이썬이 ,
쉬워요
""" # 총 네줄 출력 ( 줄바꿈 포함 )
print(sentence3)
# 슬라이싱
woosik = "920308-1234567" # 리스트, 인덱스 개념 필요
print("성별 : " + woosik[7] )
print("년도 : " + woosik[0:2]) # 범위 개념 필요 , 0 ~ 2 직전 까지
print("월 : " + woosik[2:4])
print("일 : " + woosik[4:6])
print("생년 월일 : " + woosik[0:6])
print("생년 월일 : " + woosik[:6]) # 처음부터 6 직전까지
print("뒤 7자리 : " + woosik[7:14])
print("뒤 7자리 : " + woosik[7:]) # 7 부터 끝까지
print("뒤 7자리 : " + woosik[-7:]) # 맨뒤에서 7부터 끝까지
#문자열 처리 함수
python = "Python is Amazing"
print(python.lower())
print(python.upper())
print(python[0].isupper()) # 대문자 확인
print(len(python))
print(python.replace("Python", "java"))
index = python.index("n")
print(index) # n의 인덱스 번호
index = python.index("n", index + 1) # 6번째 부터 탐색
print(index)
print(python.find("n"))
print(python.find("java")) # 포함되어 있지 않으면 -1 반환
# print(python.index("java")) # index함수로 찾으면 원하는 값이 없으면 오류 발생
print(python.count("n"))
# 띄어쓰기를 통해 서로 다른 문자열 합치기
print("a" + " b")
print("a"," b")
# 그외 다양한 문자열 포맷 방법
print(" 나는 %d살 입니다. " % 20 )
print(" 나는 %s을 좋아해요." % "파이썬")
print(" Apple 은 %c로 시작해요 " % "A")
print(" 나는 %s살 입니다. " % 20 )
print(" 나는 %s과 %s을 좋아해요." % ("파란", "빨간"))
print(" 나는 {}살 입니다.".format(20))
print(" 나는 {}과 {}을 좋아해요.".format("파란", "빨간"))
print(" 나는 {0}과 {1}을 좋아해요.".format("파란", "빨간"))
print(" 나는 {1}과 {0}을 좋아해요.".format("파란", "빨간"))
print(" 나는 {age}살이며, {color}을 좋아해요.".format(age = 20, color = "빨간"))
# 파이썬 3. 6~ 부터 가능
age = 20
color = "빨간"
print(f"나는 {age}살이며, {color}을 좋아해요.")
# 탈출 문자
# - 줄바꿈 하고 싶을 때
print("백문이 불여일견 \n 백견이 불여일타")
# - 큰따옴표 사용하고 싶을 떄 \"", \'
print('저는 "최우식"입니다.')
print("저는 \"최우식\"입니다. ")
# \\ : 문장내에서 \ 하나로 인식 - 경로 지정시
print("C:\\Users\\~")
# \r : 커서를 맨앞으로 이동
print("Red Apple\rPine") # 처음으로 가서 Pine 4개의 공간만큼 채움
#\b : 백스페이스 ( 한글자 삭제 )
print("Red\bApple")
# \t : 탭
'''
Quiz) 사이트별로 비밀번호를 만들어 주는 프로그램을 작성하시오
예 ) http://naver.com
규칙 1 : http:// 부분은 제외 => naver.com
규칙 2 : 처음 만나는 점 (.) 이후 부분은 제외 => naver
규칙 3 : 남은 글자 중 처음 세 자리 + 글자 갯수 + 글자 내 'e' 갯수 + "!" 로 구성
예시 ) 생성된 비밀번호 : nav51!
출력문 : print("{0}의 비밀 번호는 {1} 입니다.".format(url, password))
'''
url = "http://naver.com" # google, youtube 등등 바꿔보기..
a = url.replace("http://", "") # 규칙 1
print(a)
a = a[:a.index(".")] # a의 문자열 중에서 .의 위치 직전까지 자르기
# a[6:a.index(".")]
print(a)
password = a[:3] + str(len(a)) + str(a.count("e")) + "!"
print("{0}의 비밀 번호는 {1} 입니다.".format(url, password))
|
6dd41aaba81ad71b85d328bfbea3dc47ece10144 | iverberk/advent-of-code-2018 | /day-07/part1.py | 240 | 3.53125 | 4 | import networkx as nx
G = nx.DiGraph()
with open('input') as f:
for line in f:
instruction = line.strip().split()
G.add_edge(instruction[1], instruction[7])
print("".join(list(nx.lexicographical_topological_sort(G))))
|
30b1efc4b2a8bc2632026f88eafe6322d544e6e5 | is5pz3/automatic-client | /scripts/file_operations.py | 1,012 | 3.59375 | 4 | def read_hosts_from_temp(filename, mode):
""" Retrieves list of hosts that were active in previous iteration of ranking algorithm.
Args:
filename: (str) Name of file to retrieve host names from.
mode: (str) Opening file mode.
Returns:
prev_hosts: List of host names read from file.
"""
try:
f = open(filename, 'r')
except (FileNotFoundError, IOError):
f = open(filename, 'w+')
f = open(filename,mode)
prev_hosts = []
if f.mode == mode:
prev_hosts_str = f.read()
prev_hosts = prev_hosts_str.split('\n')
if len(prev_hosts[-1]) == 0:
del prev_hosts[-1]
return prev_hosts
def write_hosts_to_temp(host_names_set, filename, mode):
""" Writes list of hosts that were active in current iteration of ranking algorithm.
Args:
host_names_set: (list) List of host names to be written to file.
filename: (str) Name of file to write host names to.
mode: (str) Opening file mode.
"""
f = open(filename, mode)
for host_name in host_names_set:
f.write(host_name+"\n")
f.close() |
962ff630d86ec96b83d109ef0e7a6c85f9433d12 | Thijsvanede/elliptic-curves | /ec/curves.py | 6,134 | 4 | 4 | from ec.points import Point
import warnings
class Curve(object):
"""Defines a curve as y² = x³ + a*x + b (mod n)."""
def __init__(self, a, b, n=None):
"""Initialise curve as y² = x³ + a*x + b (mod n).
Parameters
----------
a : float
a value for curve y² = x³ + a*x + b (mod n)
b : float
b value for curve y² = x³ + a*x + b (mod n)
n : int, optional
n value for curve y² = x³ + a*x + b (mod n).
If n is given, the curve is defined as a field and the values
for a and b should be integers as well.
"""
# Check if n None or all values a, b, n are integers
assert n is None or (
isinstance(n, int) and
isinstance(a, int) and
isinstance(b, int)
)
# Set variables
self.a = a
self.b = b
self.n = n
########################################################################
# Define points on curve #
########################################################################
@property
def O(self):
"""Defines the O of the curve as Point(None, None)."""
return Point(None, None, self)
def point(self, x, y):
"""Returns a given point on the curve, specified by x and y.
Parameters
----------
x : float
x coordinate of point on curve.
y : float
y coordinate of point on curve.
Returns
-------
point : Point
Point on curve.
"""
# Initialise point on curve
point = Point(
x = x,
y = y,
curve = self,
)
# Check if point is on curve
if not point in self:
raise ValueError("Point({}, {}) not on curve {}".format(x, y, self))
# Return point
return point
########################################################################
# Get coordinates on curve #
########################################################################
def get_coordinate_y(self, x):
"""Compute the y coordinates for a given value of x
Parameters
----------
x : float
x-coordinate to compute y.
Returns
-------
y2 : float
Value of y²
y : 2-tuple of float
All possible y-coordinates corresponding to x.
"""
# Compute y² using the right hand side of the formula
# y² = x³ + a*x + b (mod n)
y2 = pow(x, 3, self.n) + self.a*x + self.b
# Case where we are in a modular group
if self.n:
# Ensure we are in the group (mod n)
y2 %= self.n
# Case where n ≡ 3 mod 4
if self.n % 4 == 3:
# Compute modular residue using Fermat's little theorem
residue = pow(y2, (self.n+1)//4, self.n)
# Return square, and both roots
return y2, (residue, self.n - residue)
# Case where n ≢ 3 mod 4
else:
# Computing modular residue in case where n ≢ 3 mod 4 is hard
warnings.warn(
"Computing the quadratic residue of n, where n ≢ 3 mod 4 is"
" hard. Returning y², (None, None)."
)
# Only return y²
return y2, (None, None)
# Case where we are not in a modular group is simply the square root
else:
# Compute the square root
sqrt = math.sqrt(y2)
# Return square, and both roots
return y2, (sqrt, -sqrt)
def get_coordinate_x(self, y):
"""Compute the x coordinates for a given value of y
Parameters
----------
y : float
y-coordinate to compute x.
Returns
-------
x : float
x-coordinate corresponding to y.
"""
raise NotImplementedError("Retrieving x is computationally hard.")
########################################################################
# Object methods #
########################################################################
def __eq__(self, other):
"""Check whether two curves are equivalent."""
# Check if curves are equivalent
return isinstance(other, Curve) and\
self.a == other.a and\
self.b == other.b and\
self.n == other.n
def __hash__(self, other):
"""Returns the hash of all parameters of curve."""
# Return the hash of all parameters
return hash((self.a, self.b, self.n))
def __contains__(self, point):
"""Checks if a point is on the curve."""
# Ensure point is of class Point
assert isinstance(point, Point)
# The O point is always on the curve
if point == self.O: return True
# Check if y² = x³ + a*x + b
y2 = pow(point.y, 2, self.n)
rhs = pow(point.x, 3, self.n) + self.a*point.x + self.b
if self.n: rhs %= self.n
# Return whether y² = x³ + a*x + b
return y2 == rhs
########################################################################
# String method #
########################################################################
def __str__(self):
"""Returns the curve as a string."""
# Get curve as string
curve = "y² = x³ + {}x + {}".format(self.a, self.b)
# Add modular if necessary
if self.n is not None:
curve = "{} mod {}".format(curve, self.n)
# Return curve
return curve
|
c76e6a0be071923eaf8d46e5a9c24c07748a177b | raghubegur/PythonLearning | /codeSamples/errorHandling.py | 232 | 3.765625 | 4 | x = 42
y = 0
print()
try:
print(x / y)
except ZeroDivisionError as e:
print('Division by zero not allowed')
else:
print('Something else went wrong')
finally:
print('This is my clean up code')
print() |
d92f79a5ae2acfa74bf210a7df13b081ede7bfe5 | shrivastava-himanshu/Leetcode_practice | /ReverseString.py | 256 | 3.765625 | 4 | def reverseString(s):
# method 1
# return(s.reverse())
# method 2
p1 = 0
p2 = len(s) - 1
while p1 <= p2:
s[p1], s[p2] = s[p2], s[p1]
p1 += 1
p2 -= 1
return s
print(reverseString(["h","e","l","l","o"])) |
dd2719d89c36346de588f97e95ca670175e716b0 | quamejnr/Python | /API/github_stars.py | 438 | 3.53125 | 4 | import requests
import json
# make an API call and store the response
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
headers = {'Accept': 'application/vnd.github.v3+json'}
r = requests.get(url, headers=headers)
print(f'Status code: {r.status_code}\n')
# Convert JSON to python dictionary and store API response in a variable
source = r.text
data = json.loads(source)
print(json.dumps(data, indent=2))
|
761739a3a42fe843a0b1e240c5a785be3d4e3ab1 | sandrastokka/phython | /Homework - 13.12.17/Find the lagrest number in a list.py | 293 | 4.25 | 4 | #Write a Python function to get the largest number from a list.
temperatureThisWeek = [1, 2, 4, 1, 1, 3, 2,]
#define function
def findlargestnumber():
highest = max (temperatureThisWeek)
print "the highest temperature this week is", highest, "celsius degrees"
findlargestnumber()
|
c147550b95527860eb0d3fa7ef5b1ac76a402e32 | Anton-L-GitHub/Learning | /Python/1_PROJECTS/Python_bok/Uppgifter/Kap13/uppg13-15.py | 1,262 | 3.671875 | 4 | class Hus:
def __init__(self, l, b):
self.längd = l
self.bredd = b
def kvadratiskt(self):
return self.längd == self.bredd
def yta(self):
return self.längd * self.bredd
__yta = yta # privat klassvariabel
def __str__(self):
y = self.__yta()
return f'Hus med basytan {y:.1f}'
class Flervåningshus(Hus):
def __init__(self, l, b, v):
super().__init__(l, b)
self.__antal = v # antalet våningar
def höghus(self):
return self.__antal >= 10
def yta(self):
return self.längd * self.bredd * self.__antal
__yta = yta
def __str__(self):
y = self.__yta()
return super().__str__() + \
f' och Flervåningshus med golvytan {y:.1f}'
class Hyreshus(Flervåningshus):
def __init__(self, l, b, v, n):
super().__init__(l, b, v)
self.antal = n # antalet lägenheter
def yta(self):
return super().yta() * 0.95
def __str__(self):
y = self.yta()
return super().__str__() + \
f' och Hyreshus med lägenhetsytan {y:.1f}'
h = Hus(25, 10)
f = Flervåningshus(25, 10, 3)
hy = Hyreshus(25, 10, 3, 15)
print(h)
print(f)
print(hy) |
44772b7ec57885f8472d51d02646c0c348db4396 | Nouseva/proj1_14 | /p1.py | 6,618 | 3.984375 | 4 | from p1_support import load_level, show_level, save_level_costs
from math import inf, sqrt
from heapq import heappop, heappush
def dijkstras_shortest_path(initial_position, destination, graph, adj):
""" Searches for a minimal cost path through a graph using Dijkstra's algorithm.
Args:
initial_position: The initial cell from which the path extends.
destination: The end location for the path.
graph: A loaded level, containing walls, spaces, and waypoints.
adj: An adjacency function returning cells adjacent to a given cell as well as their respective edge costs.
Returns:x
If a path exits, return a list containing all cells from initial_position to destination.
Otherwise, return None.
"""
pathcost = 0
shortest_path = []
tracking = {}
tracking[initial_position] = (0, None)
queue = [(0, initial_position)]
while queue:
currCost, currNode = heappop(queue)
if currNode == destination:
while tracking[currNode][1]:
shortest_path.append(currNode)
currNode = tracking[currNode][1]
shortest_path.append(currNode)
return shortest_path
else:
for cost, node in adj(graph, currNode):
pathcost = cost + tracking[currNode][0]
if node not in tracking:
tracking[node] = (pathcost, currNode)
heappush(queue, (pathcost, node))
elif pathcost < tracking[node][0]:
tracking.pop(node)
tracking[node] = (pathcost, currNode)
heappush(queue, (pathcost, node))
return None
def dijkstras_shortest_path_to_all(initial_position, graph, adj):
""" Calculates the minimum cost to every reachable cell in a graph from the initial_position.
Args:
initial_position: The initial cell from which the path extends.
graph: A loaded level, containing walls, spaces, and waypoints.
adj: An adjacency function returning cells adjacent to a given cell as well as their respective edge costs.
Returns:
A dictionary, mapping destination cells to the cost of a path from the initial_position.
"""
tracking = {}
tracking[initial_position] = 0
queue = [(0, initial_position)]
while queue:
currCost, currNode = heappop(queue)
for cost, node in adj(graph, currNode):
pathcost = cost + tracking[currNode]
if node not in tracking:
tracking[node] = pathcost
heappush(queue, (pathcost, node))
elif pathcost < tracking[node]:
tracking.pop(node)
tracking[node] = pathcost
heappush(queue, (pathcost, node))
return tracking
def navigation_edges(level, cell):
""" Provides a list of adjacent cells and their respective costs from the given cell.
Args:
level: A loaded level, containing walls, spaces, and waypoints.
cell: A target location.
Returns:
A list of tuples containing an adjacent cell's coordinates and the cost of the edge joining it and
originating cell.
E.g. from (0,0):
[((0,1), 1),
((1,0), 1),
((1,1), 1.4142135623730951),
... ]
"""
wall = level['walls']
spaces = level['spaces']
wayp = level['waypoints']
diag = sqrt(2)
# assume that a cell in a wall has no path anywhere
if cell in wall:
return []
weig = spaces.get(cell)
if weig is None:
# cell is not a regular space, it must be a waypoint
weig = wayp.get(cell)
# list of cardinal directions
adj = [
((-1,-1), diag), ((-1, 0), 1), ((0, -1), 1), ((-1, 1), diag),
((1, -1), diag), ((1, 0) , 1), ((0, 1) , 1), ((1, 1) , diag)
]
# build list of points that are adjacent to cell, regardless if they are valid
adj_points = [ ((x + cell[0], y + cell[1]), w) for (x, y), w in adj ]
result = []
for point, dist in adj_points:
point_weight = None
if point in wall:
continue
point_weight = spaces.get(point)
if point_weight is None:
point_weight = wayp.get(point)
# cost of the edge between the two cells
cost = dist * (point_weight + weig) / 2
result.append((cost, point))
return result
def test_route(filename, src_waypoint, dst_waypoint):
""" Loads a level, searches for a path between the given waypoints, and displays the result.
Args:
filename: The name of the text file containing the level.
src_waypoint: The character associated with the initial waypoint.
dst_waypoint: The character associated with the destination waypoint.
"""
# Load and display the level.
level = load_level(filename)
show_level(level)
# Retrieve the source and destination coordinates from the level.
src = level['waypoints'][src_waypoint]
dst = level['waypoints'][dst_waypoint]
# Search for and display the path from src to dst.
path = dijkstras_shortest_path(src, dst, level, navigation_edges)
if path:
show_level(level, path)
else:
print("No path possible!")
def cost_to_all_cells(filename, src_waypoint, output_filename):
""" Loads a level, calculates the cost to all reachable cells from
src_waypoint, then saves the result in a csv file with name output_filename.
Args:
filename: The name of the text file containing the level.
src_waypoint: The character associated with the initial waypoint.
output_filename: The filename for the output csv file.
"""
# Load and display the level.
level = load_level(filename)
# show_level(level)
# Retrieve the source coordinates from the level.
src = level['waypoints'][src_waypoint]
# Calculate the cost to all reachable cells from src and save to a csv file.
costs_to_all_cells = dijkstras_shortest_path_to_all(src, level, navigation_edges)
save_level_costs(level, costs_to_all_cells, output_filename)
if __name__ == '__main__':
filename, src_waypoint, dst_waypoint = 'test_maze.txt', 'a','d'
# Use this function call to find the route between two waypoints.
#test_route(filename, src_waypoint, dst_waypoint)
# Use this function to calculate the cost to all reachable cells from an origin point.
# User maze costs
cost_to_all_cells('my_maze.txt', 'a', 'my_maze_costs.csv')
test_route('test_maze.txt', 'a', 'd')
|
3036f353d0956b61614c15ca8b0d1b4e02f4fa98 | A6h15h3k806/Python | /Expected_WaitTime_Calculator/ExpectedWaitTime Calc.py | 1,616 | 3.796875 | 4 |
import time
average_list = []
t0 = int(time.time())
def timefy(x):
print ('''Your Expected Waiting Time is''')
s = x%60
print(str(s)+" sec")
if x//60 >= 1:
m = (x//60)%60
print(str(m)+" min")
if (x//60)//60 >=1:
h = ((x//60)//60)%60
print(str(h)+" hours")
else:
print(str(s)+" sec")
def mainmodule():
t_n = input('''
Type in your Token Number
''')
c_n = input('''
Type in the Counter Number
''')
def HosptWaitTime():
Token_Number = int(t_n)
Counter_Number = int(c_n)
N = Token_Number - Counter_Number
t00 = int(time.time())
input('''
Press enter when the counter number changes
''')
t1 = int(time.time())
a = t1 - t00
average_list.append(int(a))
average = sum(average_list)/len(average_list)
t3 = N * average
t4 = t0 + t3
t5 = int(time.time())
t6 = t4 - t5
timefy(int(t6))
Terminator = input('''
Press enter to restart the module otherwise press 't' to terminate
''')
if Terminator == '':
HosptWaitTime()
elif Terminator == 't':
print('''
Thank you and GoodBye!''')
quit()
HosptWaitTime()
Terminator = input('''
Press 's' to start the module otherwise press 't' to terminate
''')
if Terminator == 's':
mainmodule()
elif Terminator == 't':
print('''
Thank you and GoodBye!''')
quit()
|
d693a11987b920f073c075fbca1f2f3649040a1b | lirenlin/DSA | /group_anagrams.py | 376 | 4 | 4 | def solution (array):
dict_list = dict ()
for item in array:
target = "".join (sorted (item))
if target in dict_list:
dict_list[target].append (item)
else:
dict_list[target] = [item]
result = []
for value in dict_list.values():
result += [sorted(value)]
print result
array = ["eat", "tea", "tan", "ate", "nat", "bat"]
solution (array)
|
2387de53b769cec983984662a0bf9b3bf7a9bc7d | sriram161/Data-structures | /sort/insertion_sort.py | 387 | 4.0625 | 4 | def insertion_sort(a):
""" Iterative apporach for insertion sort.
"""
n = len(a)
for i in range(n):
for j in range(i, 0, -1):
if a[j-1] > a[j]:
a[j-1], a[j] = a[j], a[j-1]
else:
break
return a
if __name__ == "__main__":
a = [9, 3, -4, 0, 10, 20, -15, 1, 4]
print(a)
print(insertion_sort(a)) |
cf8c7bef193bad6e56f872378ea14b4d1a830783 | adybose/hackerrank | /algorithms/implementation/kangaroo.py | 481 | 3.78125 | 4 | #!/bin/python3
# Link to the problem: https://www.hackerrank.com/challenges/kangaroo
import sys
def kangaroo(x1, v1, x2, v2):
if v1 == v2:
return 'NO' # since x1 < x2
else:
j = (x1 - x2) // (v2 - v1) #
if j > 0 and (x1 + (v1 * j) == x2 + (v2 * j)):
return 'YES'
else:
return 'NO'
x1, v1, x2, v2 = input().strip().split(' ')
x1, v1, x2, v2 = [int(x1), int(v1), int(x2), int(v2)]
result = kangaroo(x1, v1, x2, v2)
print(result)
|
0505be87250bb2965051554cd084659dcbf32d39 | xdc7/pythonworkout | /chapter-03/02-extra-02-sum-numeric.py | 1,872 | 4.25 | 4 | """
Write a function, sum_numeric , which takes any number of arguments. If the argument is or can be turned into an integer, then it should be added to the total. Those arguments which cannot be handled as integers should be ignored. The result is the sum of the numbers. Thus, sum_numeric(10, 20, 'a','30', 'bcd') would return 60 . Notice that even if the string 30 is an element in the list, it’s converted into an integer and added to the total.
"""
import unittest
def sum_numeric(*args):
if not args:
return args
result = 0
for item in args:
try:
item = int(item)
result += item
except Exception as error:
print(f"{error}: {item} is not an integer or couldn't be converted into an integer")
return result
class TeststringListTranspose(unittest.TestCase):
def test_blank(self):
self.assertEqual(sum_numeric(), ())
def test_valid01(self):
self.assertEqual(sum_numeric(10, 20, 'a','30', 'bcd'), 60)
# def test_valid02(self):
# self.assertEqual(mysum_bigger_than('b', 'a' ,'b', 'c'), 'c')
# def test_valid03(self):
# self.assertEqual(mysum_bigger_than([1,2,3] , [1,2,3], [4,5,6], [7, 8, 9]), [4,5,6,7,8,9])
# def test_valid03(self):
# self.assertEqual(mysum(1,2,3), 6)
# def test_valid04(self):
# self.assertEqual(mysum(1), 1)
# def test_valid05(self):
# self.assertEqual(mysum([1], ), [1])
# def test_invalid(self):
# self.assertEqual(mysum(1,2,'d',3), ValueError)
# def test_positive(self):
# self.assertEqual(mysum(1,2,4,3), 10)
# def test_negative(self):
# self.assertEqual(mysum(1,2,-4,3), 2)
# def test_list(self):
# self.assertEqual(mysum(*[1,2,4,3]), 10)
if __name__ == '__main__':
unittest.main()
|
928ae15ac66f5be28a1b695fd803db3d4c1c1ce0 | luismglvieira/Python-and-OpenCV | /00 - Python3 Tutorials/17 - Python slice and negative index.py | 668 | 3.75 | 4 | # -*- coding: utf-8 -*-
a = [0,1,2,3,4,5,6,7,8,9]
b = (0,1,2,3,4,5,6,7,8,9)
c = '0123456789'
print("a[:] = " + str(a[:]))
print("a[slice(0,5)] = " + str(a[slice(0,5)]))
print("a[0:5] = " + str(a[0:5]))
print()
print("b[:] = " + str(b[:]))
print("b[4:] = " + str(b[4:]))
print("b[:6] = " + str(b[:6]))
print()
print("c[:] = " + str(c[:]))
print("c[4:] = " + str(c[4:]))
print("c[:3] = " + str(c[:3]))
print()
print(a[:])
print("a[0:9:2] = " + str(a[0:9:2]))
print("a[::2] = " + str(a[::2]))
print()
print(c[:])
print("c[::-1] = " + str(c[::-1]))
print("c[::-2] = " + str(c[::-2]))
print("c[:-4:-1] = " + str(c[:-4:-1]))
print("c[-3::-1] = " + str(c[-3::-1]))
|
3810f617653938333eaa6527eafbb5fb54da5149 | KotaCanchela/PythonCrashCourse | /8 Functions/8-3 8-4 T-Shirt.py | 1,382 | 4.71875 | 5 | # Write a function called make_shirt()
# that accepts a size and the text of a message that should be printed on the shirt.
# The function should print a sentence summarizing the size of the shirt and the message printed on it.
# Call the function once using positional arguments to make a shirt.
# Call the function a second time using keyword arguments.
def make_shirt(size, text):
"""Print a sentence summarizing the size of the shirt
and the message printed on it."""
print(f"\nI have ordered a size {size} t-shirt.")
print(f"My size {size} t-shirt will have the following text printed on it:\n\t{text.capitalize()}")
make_shirt('medium', 'math is the best')
make_shirt(size='large', text='merry chrysler')
# 8-4. Large Shirts: Modify the make_shirt() function so that shirts are large by default
# with a message that reads I love Python.
# Make a large shirt and a medium shirt with the default message, and a shirt of any size with a different message.
print("\n")
def make_shirt(size='large', text='I love python'):
"""Print a sentence summarizing the size of the shirt
and the message printed on it."""
print(f"\nI have order a size {size} t-shirt.")
print(f"My size {size} t-shirt will have the following text printed on it:\n\t{text.capitalize()}")
make_shirt()
make_shirt(size='medium')
make_shirt(size='small', text='python is weird') |
8a2466eb7505828b1ae566721cdd5d850e7aa695 | sammykol83/UdacityDataScienceNanoDegree | /Project - Array tool/sig_process_arrays/Array.py | 1,450 | 3.546875 | 4 | import numpy as np
class Array:
def __init__(self, num_of_elements = 8, spacing_m = 1e-3,
az_res_deg = 0.5, az_span = np.array([-50, 50])):
""" General 1D array of EQUALLY spaced elements (either UCA/ULA)
Attributes:
d (float) the spacing (in meters) between the elements
n (int) number of elements in array
az_res_deg (float) - Azimuth resolution[deg] we want to build this array with.
az_span (1x2 numpy vector) - Depicts start/end angles for observation
c (int) - Speed of light (m/sec)
"""
self.d = spacing_m
self.n = num_of_elements
self.az_res_deg = az_res_deg
self.az_span = az_span
self.c = 299792458
def __repr__(self):
"""Function to output the characteristics of the array
Args:
Returns:
string: characteristics of the array
"""
return "Array of {} elements with element spacing of {}[m]".\
format(self.n, self.d)
def plot_beampattern(self, fc_hz):
"""Function to plot the beampattern of the array at angle 0.
Args:
fc_hz( float ) - Carrier frequency of waveform arriving to the array.
Returns:
"""
def build_bf_matrix(self, fc_hz, lambda_m):
"""Function holder for implemented classes"""
pass
|
99e7b8c61dc1a7786c31219cd88ebce9cbb2571f | XinJin96/Python-Programming | /guess game.py | 1,095 | 3.890625 | 4 | import random
true=random.randint(0,99)
count=0
left=0
print ("Number(0,100) guess game")
print ("You will have 10 times to guess")
print ("Guess out of range will game over immediately!")
guess = int(input("guess a number:"))
count=count+1
left=10-count
while 0<=guess<=99:
if count==10:
if guess>true:
print("too high, game over!, the true number is :",true)
elif guess<true:
print("too low, game over!, the true number is :",true)
else:
print("you finally got it, the true number is:",true)
break
else:
left=10-count
if guess>true:
print("too high, guess again!")
print("you have ",left,"tries")
elif guess<true:
print("too low, guess again!")
print("you have ",left,"tries")
else:
print("you win!")
print("you take ",count,"try to got it!")
break
guess = int(input("guess a number:"))
count=count+1
else:
print("you number is not correct!game over!!!")
|
ac0fcbac231aa9c094c3ae0fb5659dff9a79d546 | yuanning6/python-exercise | /004.py | 545 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 15 21:20:10 2020
@author: Iris
"""
f = float(input('请输入华氏温度:'))
c = (f - 32) / 1.8
print('%.1f华氏度 = %.1f摄氏度' % (f,c))
print(f'{f:.1f}华氏度 = {c:.1f}摄氏度')
radius = float(input('请输入圆的半径:'))
perimeter = 2 * 3.1416 * radius
area = 3.1416 * radius * radius
print('周长:%.2f' % perimeter)
print('面积:%.2f' % area)
year = int(input('请输入年份:'))
is_leap = year % 4 == 0 and year % 100 != 0 or year % 400 == 0
print(is_leap) |
ae5e1333fb9f6e060d7564cc062257fa3e61b6cd | Sanchi02/Dojo | /PracticeComp/LargestNumber.py | 482 | 3.5 | 4 | def myCompare():
class K(object):
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
a, b = str(self.obj), str(other.obj)
ab = a + b
ba = b + a
return (((int(ba) > int(ab)) - (int(ba) < int(ab))) < 0 )
return K
# driver code
if __name__ == "__main__":
a = [4,2,3,1]
sorted_array = sorted(a, key=myCompare())
number = "".join([str(i) for i in sorted_array])
print(number)
|
e7bc7f8bffdcdd0ab74dfbd9ba9a27a9343fbb2f | S-Radhika/Best-enlist | /day 16.py | 1,097 | 4.1875 | 4 | #multiply argument x with y
a=lambda x,y:x*y
print(a(5,6))
#output
'''
30
'''
#create fibonacci series
from functools import reduce
fib = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]],range(n-2), [0, 1])
print(fib(5))
'''
output
[0, 1, 1, 2, 3]
'''
#counting even numbers in a list
# list of numbers
list1 = [10, 21, 4, 45, 66, 93, 11]
even_count = len(list(filter(lambda x: (x%2 == 0) , list1)))
print("Even numbers in the list: ", even_count)
'''
output
Even numbers in the list: 3
'''
#divisible by 9
num_list = [45, 55, 60, 37, 100, 105, 220]
result = list(filter(lambda x: (x % 9 == 0), num_list))
print("Numbers divisible by 9 are",result)
'''
output
Numbers divisible by 9 are [45]
'''
#multiply each number of a list by a given number
nums = [2, 4, 6, 9 , 11]
n = 2
print("Original list: ", nums)
print("Given number: ", n)
filtered_numbers=list(map(lambda number:number*n,nums))
print("Result:")
print(' '.join(map(str,filtered_numbers)))
'''
output
Original list: [2, 4, 6, 9, 11]
Given number: 2
Result:
4 8 12 18 22
'''
|
c18536b1e7b760c9a8d3f86515a177b9c4a55343 | Sk0uF/Algorithms | /py_algo/arrays_strings/competition/cyclic_shift.py | 3,639 | 4.125 | 4 | """
Codemonk link: https://www.hackerearth.com/problem/algorithm/maximum-binary-number-cb9a58c1/
A large binary number is represented by a string A of size N and comprises of 0s and 1s. You must perform a cyclic shift
on this string. The cyclic shift operation is defined as follows: If the string A is [A0, A1, A2, ..., AN-1], then after
performing one cyclic shift, the string becomes [A1, A2, ..., AN-1, A0]. You performed the shift infinite number of
times and each time you recorded the value of the binary number represented by the string. The maximum binary number
formed after performing (possibly 0) the operation is B. Your task is to determine the number of cyclic shifts that can
be performed such that the value represented by the string A will be equal to B for the Kth time.
Input - Output:
The first line denotes the number of test cases.
For each test case:
First line: Two space-separated integers N and K.
Second line: A denoting the string.
For each test case, print a single line containing one integer
that represents the number of cyclic shift operations performed
such that the value represented by string A is equal to B for the Kth time.
Sample input:
2
5 2
10101
6 2
010101
Sample Output:
9
3
"""
"""
The important think to this problem is how many bits python uses for the binary representation of an integer. The answer
to this question is 32 bits. Thus, the number 10101 when shifted to the left would become 101010 which we is an unwanted
result. We would like to have the number 01011.To do that, we we will be using the mask 11111 in this particular example
but this can be further generalized. To perform a left cyclic shift, meaning that the binary number 1010, after 1 left
cyclic shift, must become 0101 and not 0100. To do that, we use the operation: mask and (bin << i or bin >> (bits - i)).
The "and" operation with the mask is needed as mentioned before to maintain the result in the bits' length range. From
this point there are 2 cases. The first case is if there is no symmetry at all. For example, the binary number 1011 is
not symmetric and will become 0111, 1110, 1101, 1011. After 4 shifts, which is equal to the number of the bits of the
number, we know that the maximum number is the number 1110, thus, from that point, at every 4 shifts we will arrive at
the same number. If there is a symmetry, it means that we will arrive at the maximum number in less than 4 steps (for
our example). For example, if the number is 1010, then after 2 shift we will arrive again at the same number and this
pattern will continue.
The complexity depends on the number of bits, thus it is insignificant.
Final complexity: O(1)
"""
inp_len = int(input())
for _ in range(inp_len):
n, k = map(int, input().rstrip().split())
a = input().rstrip()
bits = len(a)
mask = (1 << bits) - 1 # We find the mask by doing: 2^bits - 1, for example 2^5 - 1 = 31 = 11111.
dec_a = int(a, 2)
max_num = dec_a
index = 0
symmetric = 0
for i in range(1, bits):
temp = mask & (dec_a << i) | (dec_a >> (bits - i))
# If the max is equal to temp then it means that there is some kind of symmetry
# in the binary representation and we don't need full circular shifts to reach
# again the maximum number.
if temp == max_num:
symmetric = i - index
break
if temp > max_num:
max_num = temp
index = i
if symmetric > 0:
print(index + symmetric * (k-1))
else:
print(index + (k-1) * bits)
|
cdb7e1872e1345d3fa00674c21dd607462d7644b | LeoGraciano/python | /FOR RANGE Numero Primo.py | 196 | 3.90625 | 4 | qp = 0
n = int(input("Digite um numero: "))
for p in range(1,n+1):
if n % p == 0:
qp += 1
if qp == 2:
print ("Esse numero é primo")
else:
print ("Esse numero não é primo.") |
81d403b3dc0a6e6ecb0fc74cfb2fe459ce642981 | adsl305480885/leetcode-zhou | /242.有效的字母异位词.py | 1,111 | 3.5 | 4 | '''
Author: Zhou Hao
Date: 2021-02-23 21:15:45
LastEditors: Zhou Hao
LastEditTime: 2021-02-23 21:37:52
Description: file content
E-mail: 2294776770@qq.com
'''
#
# @lc app=leetcode.cn id=242 lang=python3
#
# [242] 有效的字母异位词
#
# @lc code=start
class Solution:
#排序
# def isAnagram(self, s: str, t: str) -> bool:
# return sorted(s) == sorted(t)
#哈希
# def isAnagram(self, s: str, t: str) -> bool:
# if len(s) != len(t):return False
# hashmap = {}
# for i in s:
# if i not in hashmap:
# hashmap[i] = 1
# else:
# hashmap[i] += 1
# for i in t:
# if i not in hashmap or t.count(i) != hashmap[i]:
# return False
# return True
#asci
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):return False
if set(s) != set(t):return False
sum_s,sum_t = 0,0
for i in range(len(s)):
sum_s += ord(s[i])
sum_t += ord(t[i])
return sum_s == sum_t
# @lc code=end
|
ee4492b84507e8311614c571f5df40c17b170ad7 | kleyton67/algorithms_geral | /uri_1032.py | 855 | 3.796875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
'''
Kleyton Leite
Problema do primo jposephus, deve ser considerado a primeira troca
Arquivo uri_1032.py
'''
import math
def isprime(n):
flag = True
if n == 2:
return flag
for i in range(2, int(math.sqrt(n))+1, 1):
if(n % i == 0):
flag = False
break
return flag
def primo(pos):
for i in range(2, 32000, 1):
if(isprime(i)):
pos = pos - 1
if (not pos):
return i
n = 0
n = input("")
pulo = 0
posicao = 0
if n > 0:
lista = list(range(1, n+1, 1))
p_primo = 1
while(len(lista) > 1):
pulo = primo(p_primo)-1
while (pulo):
posicao = (posicao+1) % len(lista)
pulo = pulo - 1
del(lista[posicao])
p_primo = p_primo + 1
print (lista)
|
0bf7865f28e7b41a831c99bfc9cfcefb3d85a2f6 | Vagacoder/PythonStudy | /w3schools/022-numpyArrayIterat.py | 577 | 3.5 | 4 | #
# * Numpy array iterating
#%%
import numpy as np
a1 = np.array([[1, 2, 3, 4],[5, 6, 7, 8]])
for x in a1:
print(x)
for y in x:
print(y)
# %%
# * nditer()
for x in np.nditer(a1):
print(x)
# %%
# * Iterating array with different data types
for x in np.nditer(a1, flags=['buffered'], op_dtypes=['S']):
print(x)
print(type(x))
# %%
for x in np.nditer(a1[:, ::2]):
print(x)
# %%
b1 = np.array([1, 2, 3, 4])
for i, x in np.ndenumerate(b1):
print(i, x)
b2 = a1.reshape(2, 2, 2)
for i, x in np.ndenumerate(b2):
print(i, x)
# %%
|
5105f8ea113d412c48bb880de30f75eed5e1dfa2 | Ricardo-oli/Projeto-3- | /at2.py | 341 | 3.78125 | 4 | print(input('Nome do time: '))
v = int(input('Vitórias: '))
d = int(input('Derrotas: '))
e = int(input('Empates: '))
total = v + d + e
p = v * 3 + e
vitorias = v * 3
pontos_perdidos = d * 3
print('Total de Partidas:', int(total),'Partidas')
print('Total de Pontos:', p,'Pontos')
print('Total de pontos perdidos:', pontos_perdidos) |
114ad272c5959ba819ee1467f3e70243d50bd81e | jaywritescode/projecteuler-python | /tests/test_divisors.py | 2,918 | 3.71875 | 4 | from project import divisors
import unittest
class TestDivisors(unittest.TestCase):
"""
Test the divisors function from the library.
"""
def test_non_perfect_square_even(self):
"""
Test k where k is even and k != n ^ 2 for any integer n
"""
result = divisors.divisors(5678)
self.assertEqual(result, [1, 2, 17, 34, 167, 334, 2839, 5678])
def test_non_perfect_square_odd(self):
"""
Test k where k is odd and k != n ^ 2 for any integer n
"""
result = divisors.divisors(54321)
self.assertEqual(result, [1, 3, 19, 57, 953, 2859, 18107, 54321])
def test_perfect_square_even(self):
"""
Test k where k is even and k = n ^ 2 for some n
"""
result = divisors.divisors(88 ** 2)
self.assertEqual(result, [1, 2, 4, 8, 11, 16, 22, 32, 44, 64, 88, 121, 176, 242, 352, 484, 704, 968, 1936, 3872, 7744])
def test_perfect_square_odd(self):
"""
Test k where k is odd and k = n ^ 2 for some n
"""
result = divisors.divisors(147 ** 2)
self.assertEqual(result, [1, 3, 7, 9, 21, 49, 63, 147, 343, 441, 1029, 2401, 3087, 7203, 21609])
def test_has_consequetive_factors(self):
"""
Test a number k where n * (n + 1) = k for some n
"""
result = divisors.divisors(12)
self.assertEqual(result, [1, 2, 3, 4, 6, 12])
class TestEuclidGCD(unittest.TestCase):
"""
Test the Euclid GCD library.
"""
def test_gcd_multiple_parameters(self):
self.assertEqual(34, divisors.gcd(1530, 1054, 2346))
def test_gcd_single_parameter(self):
self.assertEqual(5678, divisors.gcd(5678))
def test_gcd_zero_parameters(self):
with self.assertRaises(ValueError):
divisors.gcd()
class TestPrimeFactorization(unittest.TestCase):
"""
Test the prime factorization function from the library.
"""
def test_prime(self):
"""
Test a prime number.
"""
result = divisors.prime_factorization(17389)
self.assertEqual(result, {17389: 1})
def test_power_of_prime(self):
"""
Test a number that is p ^ n for some prime p and n > 1
"""
result = divisors.prime_factorization(19 ** 4)
self.assertEqual(result, {19: 4})
def test_product_of_prime_powers(self):
"""
Test a number than is p1 ^ n1 * p2 ^ n2 * ... for primes p1, p2, ...
"""
result = divisors.prime_factorization(2 ** 5 * 11 * 13 ** 2)
self.assertEqual(result, {2: 5, 11: 1, 13: 2})
def test_hash(self):
"""
Test that the hash of a prime factorization p1 ^ n1 * p2 ^ n2 * ...
is in fact p1 ^ n1 * p2 ^ n2 * ...
"""
value = divisors.PrimeFactorization({17: 3, 23: 1, 41: 2})
self.assertEqual(hash(value), 17 ** 3 * 23 * 41 ** 2)
|
f7f835f73b3cf34ae45e40dfea61dea43e46d305 | St3pL3go/in-stock-bot | /src/csv_utils.py | 2,889 | 3.625 | 4 | import time
import csv
import os
class ChatObject:
"""Class that creates an object from csv entry"""
def __init__(self, l: list):
self.id = int(l[0])
self.type = l[1]
self.username = l[2]
self.first_name = l[3]
self.last_name = l[4]
self.first_contact = l[5]
class Writer:
"""
Handles all csv file accesses, like read /write /search
- Hardcoded on telegram chat-objects
"""
def __init__(self, file="data/chats.csv"):
"""
takes filename
"""
self.file = file
self.file_check()
self.entries = self.read()
print(self.entries)
def file_check(self):
"""checks if csv file exists, creates if not"""
if os.path.isfile(self.file):
None
else:
open(self.file, "w").close()
def add(self, content) -> ChatObject:
"""
Handles creation of new ChatObjects no created yet
- Needs a telegram.chat object as input
- Checks if object already exists
- Creates new one of needed
- returns ChatObject
"""
#if entry already exists - breaking
result = self.search_id(content["id"])
if result:
#print(result)
return result[0]
#logging new
#getting content to write
#keys for the telegram.chat object
keys = ["id", "type", "username", "first_name", "last_name"]
line = [] #will contain the row to add
for key in keys: #going trough chat object
line.append(f"{content[key]}")
#adding time to entry
t = time.strftime("%Y-%m-%d %H:%M:%S")
line.append(f"{t}")
new = ChatObject(line)
self.entries.append(new)
self.write()
return new
def read(self):
"""
Reads a whole csv file
Returns a list filled with created 'ChatObject'
"""
self.entries = [] #return list of objects
with open(self.file, "r") as csvfile:
read = csv.reader(csvfile, delimiter=';')
for row in read:
#appending ChatObject to list
self.entries.append(ChatObject(row))
#print("ENTRIES ", self.entries)
return self.entries
def search_id(self, entry: int):
"""Searches for a chat id in whole file"""
results = []
for chat in self.entries:
if chat.id == entry:
results.append(chat)
return results
def write(self):
"""Writes all objects to file"""
text = ""
for o in self.entries:
text += f"{o.id};{o.type};{o.username};{o.first_name};{o.last_name};"
text += f"{o.first_contact};\n"
with open(self.file, "w") as f:
f.write(text)
|
3a3754958ceb8ca684a79cf14547ffd7fad44a3a | carlaoutput/python-class- | /enteros no negativos | 1,755 | 3.875 | 4 | #!/usr/bin/env python
from types import *
from math import *
class IntSet:
def __init__(self): # inicializaci´on
self.c = 0L
def __str__(self): # impresi´on del resultado
c = self.c
s = "{ "
i = 0
while c != 0:
j = 2**long(i)
if c & j:
s = s + str(i) + ’ ’
c = c - j
i = i + 1
s = s + "}"
return s
# insercion de un entero o de una lista de enteros
def insert(self, n):
if type(n) != ListType:
self.c = self.c | 2**long(n)
else:
for i in n:
self.c = self.c | 2**long(i)
def __len__(self):
c = self.c
i = 0
n = 0
while c != 0:
j = 2**long(i)
if c & j:
c = c - j
n = n + 1
i = i + 1
return n
print "A intersecci´on B es", A&B
print "A \\ B es ", A-B
def __getitem__(self, i):
return (self.c & 2**long(i)) != 0
def __setitem__(self, i, v):
s = 2**long(i)
self.c = self.c | s
if v == 0:
self.c = self.c ^ s
def __or__(self, right): # Uni´on
R = IntSet()
R.c = self.c | right.c
return R
def __and__(self, right): # Intersecci´on
R = IntSet()
R.c = self.c & right.c
return R
def __sub__(self, right): # Diferencia
R = IntSet()
R.c = self.c ^ (self.c & right.c)
return R
if __name__ == "__main__":
A = IntSet()
A.insert(10)
A.insert([2, 4, 32])
print "Conjunto A:", A
print "Long: ", len(A)
print "¿Est´a el 2?",A[2], "¿Y el 3?", A[3]
A[3] = 1; A[2] = 0
print "¿Est´a el 2?",A[2], "¿Y el 3?", A[3]
print "Conjunto A:", A
B = IntSet()
B.insert([3,7,9,32])
print "B es", B
print "A uni´on B es ", A|B
print ((A|B) - (A&B)) - A
|
499c5d4ec3af637df1591e5362bfb41984a8b913 | Iturriaga10/TC1028-Python | /Clase8/ej12.py | 707 | 4.3125 | 4 | '''
Ejercicio 12
Escribir un programa en el que se pregunte al usuario por una frase y una letra, y
muestre por pantalla el número de veces que aparece la letra en la frase.
'''
frase = raw_input("Introduce una frase: ").lower()
letra = raw_input("Introduce una letra: ").lower()
contador = 0
for x in frase:
if x == letra:
contador += 1 # contador = contador + 1
if contador == 0:
print("Error: \n \t La frase contiene 0 apariciones")
# \n --> Salto de linea.
# \t --> Tab.
else:
print("La letra \"%s\" aparece %i veces en la frase" %(letra, contador))
# print("La letra '%s' aparece %i veces en la frase" %(letra, contador))
# %s --> string
# %i --> int
|
850c989bd0430a6615beb809b75f443154527bf4 | ptekspy/projects | /atm.py | 2,189 | 3.625 | 4 | import datetime
class Atm:
def __init__(self, name, pin):
self.name = name
self.pin = pin
self.balance = 0
self.transactions = dict()
self.transactions["Deposits"] = {}
self.transactions["Withdrawals"] = {}
if len(str(self.pin)) != 4:
raise ValueError("Pin Number Too Long. Must be 4 digits.")
def deposit(self, amt):
""" Deposits money into account up to $1000 """
current_time = str(datetime.datetime.now())
if amt <= 1000 and amt > 0:
self.balance += amt
self.transactions["Deposits"].update({current_time: (amt)})
else:
raise ValueError("Invalid Amount.")
def withdrawal(self, amt):
""" Withdrawals money from account up to $500 """
current_time = str(datetime.datetime.now())
if amt > 500 or amt < 0:
raise ValueError("Invalid Amount")
elif amt > self.balance:
print("Insufficient Funds")
elif amt <= 500 and amt > 0 and amt <= self.balance:
self.balance -= amt
self.transactions["Withdrawals"].update({current_time: (-amt)})
def check_balance(self):
return self.balance
def get_transactions(self):
for k, v in self.transactions.items():
print(k, v)
def get_deposits(self):
for k, v in self.transactions["Deposits"].items():
print("Deposit", k, v)
def get_withdrawals(self):
for k, v in self.transactions["Withdrawals"].items():
print("Withdrawal", k, v)
def get_name(self):
print(self.name)
def get_pin(self):
print(self.pin)
jameson = atm("Jameson", "1234")
jameson.deposit(1000)
print(jameson.check_balance())
jameson.withdrawal(500)
print(jameson.check_balance())
jameson.deposit(400)
print(jameson.check_balance())
jameson.withdrawal(450)
print(jameson.check_balance())
jameson.withdrawal(400)
print(jameson.check_balance())
print(jameson.get_transactions())
print(jameson.get_deposits())
print(jameson.get_withdrawals())
trish = atm("Trish", "2345")
trish.deposit(1000)
print(trish.check_balance())
print(trish.balance)
|
7b02df05eaabddb8146c8831605e5612218b439d | EndIFbiu/python-study | /20-模块和包/01-导入模.py | 576 | 3.875 | 4 | """
模块(Module),是一个Python 文件,以.py 结尾,包含了Python 对象定义和Python语句
模块能定义函数,类和变量,模块里也能包含可执行的代码
"""
"""
# 1. 导⼊模块
import 模块名
import 模块名1, 模块名2... (不推荐)
# 2. 调用功能
模块名.功能名()
"""
import math
print(math.sqrt(9))
"""
from 模块名 import 功能1, 功能2, 功能3...
"""
from math import sqrt
# 不再需要前面写模块名.方法
print(sqrt(9))
"""
from 模块名 import *
"""
from math import *
print(sqrt(9))
|
68c99cb76a05a0136dfea5ad95b82602766a154a | rosekamallove/OOP | /PYTHON/Basics/b.py | 157 | 3.640625 | 4 | # Object Oriented Programming in Python
string = "hello"
# the .upper(maybeSomeParameter) is a method and anythig with a . is method
print(string.upper())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.