blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
c9fb8bf999abb5e8ab4d611967e2b7dd45d28ad5 | ralic/Note | /Algorithms/ClouldClass/week2/reversinglinkedlist.py | 635 | 3.734375 | 4 | class Node(object):
def __init__(self, address, data, node=None):
self.data = data
self.address = address
self.next = node
def create_node(self, nodelist):
while nodelist:
result = filter(lambda address: address == self.next.address, nodelist)
def __str__(self):
print self.next
if self.next is not None:
return "%s %d %s" % (self.address, self.data, self.next.address)
else:
return "%s %d None" % (self.address, self.data)
if __name__ == '__main__':
n1 = Node("00100", 6, None)
l2 = Node("00000", 4, n1)
print l2
|
45de0a7e1f53ca3214b1d6533c26938a0e1e2e9a | ChrisAHolland/Kattis-Solutions | /ReverseBinary.py | 103 | 3.59375 | 4 | #!/usr/bin/env python3
x = bin(int(input()))
x = x.strip("0b")
x = x[::-1]
x = int(x,2)
print(x) |
0553c938ad254ebcbc895e347ca33adf7dd85941 | JohnnyDeuss/minesweeper-solver | /minesweeper_solver/policies/selection_methods.py | 3,017 | 3.546875 | 4 | """ This file defines a number of selection methods that can be used in `policies.make_policy`. """
from random import randrange
import numpy as np
from scipy.ndimage.morphology import binary_dilation
def nearest(preferred, prob):
""" Select a square that is nearest, as defined by the Manhattan distance, to an already opened square. """
# Nearest only works if an opened square exists to be near, otherwise just return without selecting.
if np.isnan(prob).any():
# Keep looking further and further until a `preferred` square is found. We do this by dilating the mask of the
# known squares until it overlaps with the `preferred` mask.
search_mask = binary_dilation(np.isnan(prob))
while not (search_mask & preferred).any():
search_mask = binary_dilation(search_mask)
return search_mask & preferred
else:
return preferred
def random(preferred, prob):
""" Select a random square. """
ys, xs = preferred.nonzero()
# Pick a random action from the best guesses.
idx = randrange(len(xs))
x, y = xs[idx], ys[idx]
selected = np.zeros(preferred.shape)
selected[y, x] = 1
return selected
def centered(preferred, prob):
""" Select squares that are as much in the center as possible. """
# Start at the center.
search_mask = np.zeros(preferred.shape, dtype=bool)
search_mask[search_mask.shape[0]//2, search_mask.shape[1]//2] = True
# Keep looking further and further until a `preferred` square is found. We do this by dilating the mask over the
# known squares until it overlaps with the `preferred` mask.
while not (search_mask & preferred).any():
search_mask = binary_dilation(search_mask)
return search_mask & preferred
def inward(preferred, prob):
""" Select cells that are as much on the outer edge as possible. """
# Start at the edge.
search_mask = np.zeros(preferred.shape, dtype=bool)
search_mask[[0, search_mask.shape[0]-1], :] = True
search_mask[:, [0, search_mask.shape[1]-1]] = True
# Keep looking further and further until a `preferred` square is found. We do this by dilating the mask over the
# known squares until it overlaps with the `preferred` mask.
while not (search_mask & preferred).any():
search_mask = binary_dilation(search_mask)
return search_mask & preferred
def inward_corner(preferred, prob):
""" Select cells that are as near to a corner as possible. """
# Start at the center.
search_mask = np.zeros(preferred.shape, dtype=bool)
search_mask[[0, 0, search_mask.shape[0]-1, search_mask.shape[0]-1], [0, search_mask.shape[1]-1, 0, search_mask.shape[1]-1]] = True
# Keep looking further and further until a `preferred` square is found. We do this by dilating the mask over the
# known squares until it overlaps with the `preferred` mask.
while not (search_mask & preferred).any():
search_mask = binary_dilation(search_mask)
return search_mask & preferred
|
da240d2c009162d6ec9eccf8b0801dbe3373262e | DanKirby1996/Software-Engineering-Final-Project | /cse416-master/data/scripts/verify_neighbors.py | 843 | 3.90625 | 4 | #!/usr/bin/env python3
#
# Used to verify neighbors file.
# Checks that any given entry should have a returning edge.
import sys
import json
from collections import defaultdict
if len(sys.argv) != 2:
print(f"{sys.argv[0]} [neighbors file to check]")
sys.exit(0)
neighbors_file = sys.argv[1]
neighbors_dict = defaultdict(dict)
with open(neighbors_file, 'r') as f:
data = json.load(f)
for neighbor in data:
if len(data[neighbor]['neighbors']) == 0:
print(f"{neighbor} has no neighbors!")
for adj in data[neighbor]['neighbors']:
neighbors_dict[neighbor][adj] = 1
if adj in neighbors_dict:
try:
temp = neighbors_dict[adj][neighbor]
except Exception:
print(f"Missing returning edge: {neighbor}->{adj}")
|
8f3091c519db1ef737291f844ad1c5a984ca120c | xukangjune/Leetcode | /solved/241. 为运算表达式设计优先级.py | 1,278 | 4.125 | 4 | """
分治算法。就是“分而治之”,将一个大问题分解成小问题,然后解决小问题的后,再解决大问题。这题就是分治算法。首先,如果字符串中含有运算符,那么对于每个
运算符都可以将字符串分成两部分,左边和右边。递归返回的左边和右边都是数字,然后根据运算符的不同,将数字两两运算。递归到最后,如果最后的字符串只含有
数字,那么就直接返回数字。
"""
class Solution:
def diffWaysToCompute(self, input):
if input.isdigit():
return [int(input)]
ret = []
for i in range(len(input)):
if input[i] in "+-*":
left = self.diffWaysToCompute(input[:i])
right = self.diffWaysToCompute(input[i+1:])
for leftNum in left:
for rightNum in right:
if input[i] == '+':
ret.append(leftNum + rightNum)
elif input[i] == '-':
ret.append(leftNum - rightNum)
else:
ret.append(leftNum * rightNum)
return ret
solve = Solution()
input = ""
print(solve.diffWaysToCompute(input)) |
3290cd16f7ef5ff39e9479067c5ec8886ab1443d | Sniperhorus/Python | /Ejercicios_basicos.py | 1,252 | 4.40625 | 4 | """
Los siguientes, son una serie de ejercicios que tienen como
finalidad el que tu practiques los conocimientos adquiridos a
lo largo de este segundo bloque.
"""
# Dado de los valores ingresados por el usuario (base, altura)
# Calcular y mostrar en pantalla el área de un triángulo.
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
base = int(input("Ingresa la base\n"))
altura = int(input("Ingresa la altura\n"))
print("Resultado: ",(base*altura)/2)
# Convertir la cantidad de dólares ingresados por un usuario
# A pesos colombianos y mostrar el resultado en pantalla.
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
cantidad = int(input("Cantidad a recibir en pesos?\n"))
PRECIO_DOLAR = 20
print("Conversion a dolares: ", cantidad/PRECIO_DOLAR)
# Convertir los grados centígrados ingresados por un
# usuario a grados Fahrenheit y mostrar el resultado en pantalla.
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
temp1 = float(input("Ingresa temperatura en celsius\n"))
print("Grado F: ", (temp1*1.8)+32)
# Mostrar en pantalla la cantidad de segundos que tiene un lustro.
segundos = 5*(((60*60)*24)*365)
print ("Segundos en un lustro: ",segundos) |
da032d5c0780a41d86d09dbe0d7f23ecc350a7c1 | XinWei-Yang/algorithms | /algorithms/search/first_occurrence.py | 663 | 4.0625 | 4 | """
Find first occurance of a number in a sorted array (increasing order)
Approach- Binary Search
T(n)- O(log n)
"""
def first_occurrence(array, query):
"""
Returns the index of the first occurance of the given element in an array.
The array has to be sorted in increasing order.
"""
low, high = 0, len(array) - 1
while low <= high:
mid = low + (high-low)//2 #Now mid will be ininteger range
#print("lo: ", lo, " hi: ", hi, " mid: ", mid)
if low == high:
break
if array[mid] < query:
low = mid + 1
else:
high = mid
if array[low] == query:
return low
|
96dd434c558242f717dcfa0832727dd73bcf9bd6 | Sashlin-Dean-Moonsamy/FInance-Calculator | /finance_calculators.py | 2,125 | 4.40625 | 4 | import math
#Set boolean values
investment= False
bond= False
#request that user choose which type of calculation they want to do
print("""Chooose either 'Investment' or 'Bond' from the menu below to proceed:
Investment - to calculate the amount of interest you'll earn on an interest
Bond - to calculate the amount you'll have to pay on a home loan
""")
#store input in variable
calculator= input("Calculator: ").lower()
#if statements that allow user to proceed based on input
#investment calculator
if calculator == "investment":
#request information from user
deposit = float(input("Enter the ammount that are you depositing: "))
interest_rate = float(input("Enter the inerest rate ('%' Sybmol Not Required): "))
num_of_years = float(input("Enter the number of years you plan on investing for: "))
interest = input("Do you want 'Simple' or 'Compound' interest: ").lower()
#simple interest calculation
if interest == "simple":
r = interest_rate / 100
total_with_interest= deposit * (1 + r * num_of_years)
print(f"R{total_with_interest}")
#compound interest calculation
elif interest == "compound":
r = interest_rate / 100
total_with_interest = deposit * math.pow((1+r),num_of_years)
print(f"R{total_with_interest}")
#incorrect choice entered
else:
print("You have entered an inccorect opption!")
#Bond calculator
elif calculator == "bond":
present_value = float(input("Enter the present value of the house: R"))
interest_rate = float(input("Enter the inerest rate ('%' Sybmol Not Required): "))
num_of_months = float(input("Enter the amount of months you plan to take to repay the bond: "))
#calculations
monthly_interest = (interest_rate / 100) / 12
monthly_repayment = (monthly_interest* present_value)/(1 - (1+monthly_interest)**(-num_of_months))
#print out monthly repayment
print(f"R{monthly_repayment}")
#incorret option entered
else:
print("You have entered an icorrect option.") |
a9df2657b8a200508690c173bb6196c91ffae411 | oxhead/CodingYourWay | /src/lt_344.py | 677 | 4.03125 | 4 | """
https://leetcode.com/problems/reverse-string
Related:
- lt_345_reverse-vowels-of-a-string
- lt_541_reverse-string-ii
"""
"""
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
"""
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
if __name__ == '__main__':
test_cases = [
('hello', 'olleh')
]
for test_case in test_cases:
print('case:', test_case)
output = Solution().reverseString(test_case[0])
print('output:', output)
assert output == test_case[1]
|
583c14ea3b009c8e4b6ffa4aa12920ac073bbfe4 | roger6blog/LeetCode | /SourceCode/Python/Problem/00218.The_Skyline_Problem.py | 4,148 | 3.875 | 4 | '''
Level: Hard
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city
when viewed from a distance.
Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo
(Figure A),
write a program to output the skyline formed by these buildings collectively (Figure B).
"../../../Material/merged.jpg"
Buildings Skyline Contour
The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi],
where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively,
and Hi is its height. It is guaranteed that 0 <= Li, Ri <= INT_MAX, 0 < Hi <= INT_MAX, and Ri - Li > 0.
You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.
For instance,
the dimensions of all buildings in Figure A are recorded as:
[ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .
The output is a list of "key points" (red dots in Figure B) in the format of
[ [x1,y1], [x2, y2], [x3, y3], ... ]
that uniquely defines a skyline.
A key point is the left endpoint of a horizontal line segment. Note that the last key point,
where the rightmost building ends,
is merely used to mark the termination of the skyline,
and always has zero height.
Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.
For instance,
the skyline in Figure B should be represented as:
[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].
Notes:
The number of buildings in any input list is guaranteed to be in the range [0, 10000].
The input list is already sorted in ascending order by the left x position Li.
The output list must be sorted by the x position.
There must be no consecutive horizontal lines of equal height in the output skyline.
For instance,
[...[2 3], [4 5], [7 5], [11 5], [12 7]...]
is not acceptable;
the three lines of height 5 should be merged into one in the final output as such:
[...[2 3], [4 5], [12 7], ...]
'''
import heapq
class Solution(object):
def getSkyline(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
i = 0
length = len(buildings)
liveBuildings = []
skyline = []
# Define
Li = 0
Ri = 1
Hi = 2
liveHi = 0
liveRi = 1
skyHi = 1
while i < length or len(liveBuildings) > 0:
# Check if Ri of this building small than max high live building's Ri
# It means checking current building is covered by current max high live building or not
if len(liveBuildings) == 0 or (i < length and buildings[i][Li] <= -liveBuildings[0][liveRi]):
# Building's left side
start = buildings[i][Li]
while i < length and buildings[i][Li] == start:
# Welcome to live buildings!
heapq.heappush(liveBuildings, [-buildings[i][Hi], -buildings[i][Ri]])
i += 1
# Else, it means this building not be covered by live building's range of landing
else:
# Live building's right side
start = -liveBuildings[0][liveRi]
while len(liveBuildings) > 0 and -liveBuildings[0][liveRi] <= start:
# Remove building which right side is covered by other live buildings
# If all live building are removed, it means currHeight will become 0
heapq.heappop(liveBuildings)
currHeight = len(liveBuildings) and -liveBuildings[0][liveHi]
if len(skyline) == 0 or skyline[-1][skyHi] != currHeight:
skyline.append([start, currHeight])
return skyline
buildings = [
[2, 9, 10],
[3, 7, 15],
[5, 12, 12],
[15, 20, 10],
[19, 24, 8]
]
buildings2 = [
[2, 9, 10],
[3, 7, 15],
[5, 12, 12],
[15, 20, 10],
[19, 24, 8]
]
print Solution().getSkyline(buildings)
# Output is [ [2, 10], [3, 15], [7, 12], [12, 0], [15, 10], [20, 8], [24, 0] ]
|
0b530a2fc6b9bf0b91f0fbb6dc14b1218fbc758a | sairina/python-practice | /scratch.py | 1,763 | 3.5625 | 4 | import json
import requests
''' All from realpython.com/python-json/'''
response = requests.get("https://jsonplaceholder.typicode.com/todos")
todos = json.loads(response.text)
# json.loads turns the response into a dictionary
todos == response.json()
''' MANIPULATE JSON DATA AS NORMAL PYTHON OBJECT '''
# map of userId to number of complete TODOs for that user
todos_by_user = {}
# get a list of completed todos for each user
for todo in todos:
if todo['completed']:
try:
todos_by_user[todo['userId']] += 1
except KeyError:
todos_by_user[todo['userId']] = 1
# create a SORTED list of pairs with .items() for (userId, num_complete)
top_users = sorted(todos_by_user.items(),
key=lambda x: x[1], reverse=True)
# get the maximum number of completed todos
max_complete = top_users[0][1]
# create a list of all users who have completed the maximum number
# of todos
users = []
for user, num_complete in top_users:
if num_complete < max_complete:
break
users.append(str(user))
max_users = " and ".join(users)
s = "s" if len(users) > 1 else ""
print(f"user{s} {max_users} completed {max_complete} TODOS")
# users 5 and 10 completed 12 TODOs
'''CREATE A JSON FILE THAT CONTAINS THE COMPLETED TODOS for
each of the users who completed the maximum number of TODOs'''
# define a function to filter out completed TODOs
# of users with max completed TODOs
def keep(todo):
is_complete = todo['completed']
has_max_count = str(todo['userId']) in users
return is_complete and has_max_count
# write filtered todos to file
with open('filtered_data_file', 'w') as data_file:
filtered_todos = list(filter(keep, todos))
json.dump(filtered_todos, data_file, indent=2)
|
e3c4d95831d4500ffe64f1e56d29daf9e3ee1b95 | juanma414/ayedd-if | /ejercicio7.py | 547 | 4.03125 | 4 | t = str(input("Ingresar tipo de pieza (a/b): "))
if (t != "a" and t !="b"):
print ("el valor ingresado no es un tipo de pieza válido")
else:
m = int(input("Ingresar la medida: "))
if t=="a":
if m >= 163 and m <= 167:
print("Cumple con las especificaciones")
else:
print("No cumple con las especificaciones")
if t=="b":
if m >= 177 and m <= 183:
print("Cumple con las especificaciones")
else:
print("No cumple con las especificaciones")
|
c5b912b33cefe3bd0401847395bd9767b4ac19ce | RiyaGaur/Python-Programming | /Shape and Reshape/solution.py | 91 | 3.640625 | 4 | import numpy
n=input()
list=(n.split( ))
arr=numpy.array(list,int)
print(arr.reshape(3,3))
|
939693a0da8197861ec5cc1eb10764239e02a131 | panarnold/python-projects | /python-theory/inheritance-and-composition.py | 3,046 | 3.8125 | 4 | # inheritance: dziedziczy, rozszerza, czerpie (derive) np Horse IS Animal
# composition: relacja 'has' CompositeClass HAS a ComponentClass, Horse HAS a Tail
#composition umozliwia reuzywanie kodu przez dodawanie ich do innych obiektów
#wszystko w python jest obiektem: moduły, definicje klas i funkcji są obiektami, obiekty z klas też
#kazda klasa w python derives from object
#wszystkie klasy czerpią z object, poza exceptionami - bo te czerpią z BaseException
# BaseException provides, dlatego errory deriwujemy tak:
class MyError(Exception):
pass
raise MyError()
class PayrollSystem:
def calculate_payroll(self, employees):
print('calculating payroll')
print('====================')
for employee in employees:
print(f'Payroll for: {employee.id} - {employee.name}')
print(f'- check amount: {employee.calculate_payroll()}')
print('')
#w takim wypadku lepiej robić interfejsy czy klasy abstrakcyjne
# klasy abstrakcyjne istnieją, by z nich dziedziczyc, lecz by ich nie instajcjować
# underscore, ale raczej abc module
from abc import ABC, abstractmethod
class Employeee(ABC):
def __init__(self, id, name):
self.id = id
self.name = name
@abstractmethod #pokazuje ze TRZEBA nadpisać
def calculate_payroll(self):
pass
# nowoczesne języki pozwalają dziedziczyc z jednej klasy, ale implementować wiele interfejsów
# w pythonie nie trzeba explicitnie deklarować interfejsów tylko tzw 'duck typing' -> jesli zachowuje sie jak kaczka, jest to kaczka np
class DisgruntledEmployee(self, id, name):
self.id = id
self.name = name
def calculate_payroll(self):
return 10000 # nie derivuje z Employee, ale spelnia te same wymagania do Payroll System
#def calculate_payroll(self, employees):
# print('calculating payroll')
# print('====================')
# for employee in employees:
# print(f'Payroll for: {employee.id} - {employee.name}')
# print(f'- check amount: {employee.calculate_payroll()}')
# print('')
# wymaga: listy obiektów, które implementuja id, name,
# dlaczego nie inheretencja? np Customer moze miec id i name, tak jak Employee, ale nie moga dziedziczyc z jednego, dlatego interfejs
# jesli klasa ma byc reused -> implementuj interfejs
import productivity, hr, employees
manager = employees.Manager(1, 'Mary Poppins', 3000)
secretary = employees.Secretary(2, 'John Smith', 1500)
sales_guy = employees.SalesPerson(3, 'Kurwa Jebana', 1000, 250)
factory_worker = employees.FactoryWorker(2, 'Jane Doe', 40, 15)
temporary_secretary = employees.TemporarySecretary(5, 'Adam Małysz', 40, 9)
employees = [manager, secretary, sales_guy, factory_worker, temporary_secretary]
productivity_system = productivity.ProductivitySystem()
productivity_system.track(employees, 40)
payroll_system = PayrollSystem()
payroll_system.calculate_payroll(employees)
#program działa,
#kompozycja: kompozyt składający się z komponentów
|
02d11f6137dcb7598db370dfa175157f2b65ab26 | waltman/advent-of-code-2017 | /day23/coprocessor_conflag2.py | 390 | 3.5 | 4 | #!/usr/bin/env python3
MIN = 108100
MAX = 125100
STRIDE = 17
# sieve
isPrime = set()
for i in range(MAX+1):
isPrime.add(i)
for i in range(2, MAX+1):
if i in isPrime:
for j in range(i*2, MAX+1, i):
if j in isPrime:
isPrime.remove(j)
cnt = 0
for i in range(MIN, MAX+1, STRIDE):
if i not in isPrime:
cnt += 1
print("result2:", cnt)
|
52b128155e9de0e9808da669d8854534c900d4c9 | TesterCC/Python3Scripts | /mooc_python/programming/practice4_sum_prime_number.py | 1,412 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '2019-04-12 16:26'
"""
100以内素数之和
描述
求100以内所有素数之和并输出。
素数指从大于1,且仅能被1和自己整除的整数。
提示:可以逐一判断100以内每个数是否为素数,然后求和。
https://www.jb51.net/article/133459.htm
"""
value=2
num=0
for i in range(3,100):
for k in range(i-1,1,-1):
if i%k==0:
num=0
break
else:
num=1
if num==1:
value=value+i
print(value)
# Method 2 素数相加
N = 100
i = 2
num = 2
s = 0
for i in range(2, 100):
for num in range(2, i):
if (i % num == 0): # 在非1和非自身的数中还有能整除的数,就说明这个是合数
break
else:
s += i
print(s)
|
660ea6f06891d603654c2d7d9535a41acffd7f86 | yenpinchiu/Eight-Legged-Essay | /LeetCode19_Remove_Nth_Node_From_End_of_List.py | 1,651 | 3.953125 | 4 | '''
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x, next_node):
self.val = x
self.next = next_node
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
cur_node = head
index = 1
node_dict = {index:head}
while cur_node.next != None:
cur_node = cur_node.next
index += 1
node_dict.update({index:cur_node})
if index - n + 2 not in node_dict:
r_node = None
else:
r_node = node_dict[index - n + 2]
if index - n in node_dict:
l_node = node_dict[index - n]
else:
l_node = None
if r_node is not None and l_node is not None:
l_node.next = r_node
return head
elif r_node is not None and l_node is None:
return r_node
elif r_node is None and l_node is not None:
l_node.next = None
return head
else:
return None
def printList(self, head):
cur_node = head
result = ""
while cur_node != None:
result += str(cur_node.val) + " -> "
cur_node = cur_node.next
return result |
ec0e09f2db2f1e440f07047824f75f56186d521a | bfirner/armada-player-demo | /base_agent.py | 1,312 | 3.625 | 4 | #! /usr/bin/python3
#
# Copyright Bernhard Firner, 2019
#
# The agent must choose which actions to take. An agent takes the form of:
# (world state, current step, active player) -> action
#
# There are quite a few steps in Armada.
class BaseAgent:
"""The base agent. Replace the internal functions to implement your own agent."""
def __init__(self, handlers):
"""Initialize state handler table.
Arguments:
handlers (Table(str, function)): A table that maps from phase names to a handler
function.
"""
self.handlers = handlers
def default_handler(self, worldl_state):
"""The default handler called when a phase is not matched in the handlers table."""
raise RuntimeError("Unhandled phase: {}", world_state["phase"])
def handle(self, world_state):
"""Handles the given world state by passing it off to an internal function.
Arguments:
world_state (table): The collection of game state information.
Returns:
action to take
"""
if world_state.full_phase in self.handlers.keys():
return self.handlers[world_state.full_phase](world_state)
else:
return default_handler(world_state)
|
1553d2cb3364bbbadcd20e41bd0385448a09865c | Bao-Learning-School/Tutorial | /image_lib.py | 8,654 | 3.515625 | 4 | """Manages pygame images"""
import collections
import os
from typing import List, Optional, Tuple
import pygame
class Animator(object):
"""Animates a sequence of images."""
def __init__(self, owner: Optional[pygame.sprite.Sprite]=None):
"""Creates an image animator.
Args:
owner: Owner of this animator class.
"""
self._owner = pygame.sprite.GroupSingle(owner)
self._rect = None
@property
def owner(self):
"""Owner of this animator."""
return self._owner.sprite
@property
def image(self) -> pygame.Surface:
"""Image of current state."""
raise NotImplementedError('Derived class should override this property')
@property
def rect(self) -> Optional[pygame.Rect]:
"""Rect of this animator."""
return self._rect
@property
def size(self) -> Optional[Tuple[int, int]]:
"""Size of current image."""
if self.image is None:
return None
return self.image.get_size()
@property
def is_active(self) -> bool:
"""Whether the animator is active."""
return self.image is not None
class FilesAnimator(object):
"""Animator for a sequence of image files."""
def __init__(self,
image_files: List[str],
size: Optional[Tuple[int, int]],
display_time: int,
transition_time: int,
loops: Optional[int]):
"""Create an image sequence animator.
Args:
image_files: List of image files to be animated.
size: Image size.
display_time: How long (in frames, and include transition time) an image
should be displayed.
transition_time: How long is the image transition time.
interval: Intervals (frames) between two images.
loops: Number of loops of the images. None: no loop, -1: infinite loops.
"""
self._image_files = image_files
self._image=None
self._next_image = None
self._size = size
self._display_time = display_time
self._index = None
self._transition_time = transition_time
self._transition_index = None
self._loops = loops
@property
def image(self):
"""Current image of this animator."""
return self._image
'''
# Need to figure a way to blend two images.
if self._next_image is None:
return self._image
# Merge two images
alpha2 = self._transition_index / self._transition_time
alpha1 = 1.0 - alpha2
image = self._image.convert()
image.set_alpha(alpha1)
self._next_image.set_alpha(alpha2)
image.blit(self._next_image, (0, 0))
image.set_alpha(1.0)
return image
'''
def blit(self, surface, position):
"""Blit image into the surface."""
if self._next_image is None:
surface.blit(self._image, position)
return
# Merge two images
alpha2 = self._transition_index / self._transition_time
alpha1 = 1.0 - alpha2
self._image.set_alpha(alpha1)
self._next_image.set_alpha(alpha2)
surface.blit(self._image, position)
surface.blit(self._next_image, position)
def start(self):
"""Starts the animation."""
self._image = scale_image(pygame.image.load(self._image_files[0]),
self._size)
self._size = self._image.get_size()
self._index = 0
def update(self):
"""Update the animator."""
self._index += 1
if self._index % self._display_time == 0:
# Transition begins
image_index = self._index // self._display_time % len(self._image_files)
self._next_image = scale_image(
pygame.image.load(self._image_files[image_index]), self._size)
self._transition_index = 0
return
if self._transition_index is None:
return
self._transition_index += 1
if self._transition_index >= self._transition_time:
# Transition done
self._image = self._next_image
self._next_image = None
self._transition_index = None
class SequenceAnimator(Animator):
"""Animator for a sequence of images."""
def __init__(self,
owner: Optional[pygame.sprite.Sprite],
image_iterator: collections.abc.Iterator,
interval: int):
"""Create an image sequence animator.
Args:
owner: Owner of this animator class.
image_iterator: Iterator of the images to be animated.
interval: Intervals (frames) between two frames.
"""
super().__init__(owner)
self._images_iterator = image_iterator
self._index = None
self._image = None
self._interval = interval
self._rect = None
self.shift_up_factor = 0.2
@property
def image(self):
"""Current image."""
return self._image
@property
def is_active(self):
"""Whether the sprite is dying."""
return self._image is not None
@property
def rect(self):
return self._rect
@rect.setter
def rect(self, rect):
if not self._image:
return
self._rect = self._image.get_rect()
self._rect.center = (
rect.centerx,
rect.centery + rect.height // 2 - self._rect.height * (1 - self.shift_up_factor) // 2)
def start(self):
"""Starts the animation."""
self._index = -1 # The update function below will increment the index.
self.update()
def update(self):
"""Update dying stage."""
if self._index is None:
return
self._index += 1
self._index %= self._interval
if self._index != 0:
return
self._image = next(self._images_iterator, None)
if self._image is None:
self.owner.kill()
class SequenceAnimatorFactory(object):
"""Factory class that create SequenceAnimator."""
def __init__(self,
images: List[pygame.Surface],
interval: int):
"""Create a sequence animator factory.
Args:
images: List of images for SequenceAnimator.
interval: Interval between neighboring images.
"""
self._images = images
self._interval = interval
def create(self, owner: Optional[pygame.sprite.Sprite]=None):
"""Creates a SequenceAnimator."""
return SequenceAnimator(owner, iter(self._images), self._interval)
def split_image(image: pygame.Surface,
rows: int,
columns: int,
target_size: Optional[Tuple[int, int]]=None) -> List[pygame.Surface]:
"""Split an image evenly into pieces.
Args:
image: The original image.
rows: Number of rows.
columns: Number of columns
target_size: Output sub-image size.
Returns:
A list of sub-images.
"""
piece_width = image.get_width() // columns
piece_height = image.get_height() // rows
images = []
for row in range(rows):
for col in range(columns):
rect = pygame.Rect(col * piece_width, row * piece_height, piece_width, piece_height)
surface = pygame.Surface((piece_width, piece_height), pygame.SRCALPHA, 32)
surface.blit(image, (0,0), rect)
if target_size is not None:
surface = pygame.transform.scale(surface, target_size)
images.append(surface)
return images
def scale_image(image: pygame.Surface,
size: Tuple[Optional[int], Optional[int]]) -> pygame.Surface:
"""Scale an image.
If one of the size dimension is None, scale proportionally.
Args:
image: The original image.
size: Target size.
"""
x_size, y_size = size
if x_size is None and y_size is None:
return image
if x_size is None:
x_size = image.get_width() * y_size // image.get_height()
elif y_size is None:
y_size = image.get_height() * x_size // image.get_width()
return pygame.transform.scale(image, (x_size, y_size))
def images_from_file(
image_path: str,
grid_size: Optional[Tuple[int, int]]=None,
size: Optional[Tuple[int, int]]=None) -> List[pygame.Surface]:
if grid_size is None:
# Infer grid size from file name
file_name_pieces = os.path.splitext(image_path)[0].rsplit('_', 1)
if len(file_name_pieces) == 2:
grid_size = file_name_pieces[1].split('x')
if len(grid_size) == 2:
row = int(grid_size[0])
col = int(grid_size[1])
return split_image(pygame.image.load(image_path), row, col, size)
def sequence_animator_factory_from_file(
image_path: str,
grid_size: Optional[Tuple[int, int]],
size: Tuple[int, int],
interval: int) -> SequenceAnimatorFactory:
"""Create an sequence image animator from a file.
Args:
image_path: Image file path.
grid_size: Number of rows/columns of sub-images.
size: Size of each sub-image.
interval: Intervals (frames) between two frames.
"""
images = images_from_file(image_path, grid_size, size)
return SequenceAnimatorFactory(images, interval) |
7b52d3a00b7dadb17cad1a2ac047e69a09201402 | rockomatthews/Dojo | /Python/toinCoss.py | 369 | 3.53125 | 4 | import random
def toss(Amount):
heads = 0
tails = 0
for x in range(1, Amount):
new_toss = random.randint(0,1)
if round(new_toss) == 1:
heads += 1
else:
tails += 1
print "There were " + str(heads) + " heads and " + str(tails) + " tails flips. (tails always fails)"
toss(5000)
|
726cd8906ae7a849b83127d0e08bfac4f177f46b | szabgab/slides | /python/examples/csv/count_csv_rows.py | 1,089 | 3.75 | 4 | import csv
import sys
from collections import defaultdict
def check_rows(filename):
rows = []
widthes = defaultdict(int)
with open(filename) as fh:
rd = csv.reader(fh, delimiter=';')
for row in rd:
width = len(row)
rows.append(width)
widthes[width] += 1
#print(widthes)
if len(widthes.keys()) > 1:
print("Not all the rows have the same number of cells")
cell_counts = sorted(widthes.keys(), key=lambda x: widthes[x], reverse=True)
print(f"Most common number of cells is {cell_counts[0]} with {widthes[ cell_counts[0] ]} rows")
for count in cell_counts[1:]:
print(f" Cells: {count}")
print(f" Rows:")
for row, cells in enumerate(rows):
if cells == count:
print(f" {row}")
else:
values = list(widthes.values())
print(f"All rows have the same number of cells: {values[0]}")
if len(sys.argv) != 2:
exit(f"Usage: {sys.argv[0]} FILENAME")
filename = sys.argv[1]
check_rows(filename)
|
10fa0843d587069d75986bd5eeec3c307ed33efa | chanrl/bettingmodel | /knn.py | 9,970 | 3.921875 | 4 | """
Functions and classes to complete non-parametric-learners individual exercise.
Implementation of kNN algorithm modeled on sci-kit learn functionality.
TODO: Improve '__main__' to allow flexible running of script
(different ks, different number of classes)
"""
import numpy as np
import pandas as pd
from collections import Counter
from sklearn.datasets import make_classification
import matplotlib.pyplot as plt
import sys
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
#from src.knn_ploting import plot_distances
def plot_decision_boundary(clf, X, y, n_classes):
"""Plot the decision boundary of a kNN classifier.
Plots decision boundary for up to 4 classes.
Colors have been specifically chosen to be color blindness friendly.
Assumes classifier, clf, has a .predict() method that follows the
sci-kit learn functionality.
X must contain only 2 continuous features.
Function modeled on sci-kit learn example.
Parameters
----------
clf: instance of classifier object
A fitted classifier with a .predict() method.
X: numpy array, shape = [n_samples, n_features]
Test data.
y: numpy array, shape = [n_samples,]
Target labels.
n_classes: int
The number of classes in the target labels.
"""
mesh_step_size = .1
# Colors are in the order [red, yellow, blue, cyan]
cmap_light = ListedColormap(['#FFAAAA', '#FFFFAA', '#AAAAFF', '#AAFFFF'])
cmap_bold = ListedColormap(['#FF0000', '#FFFF00', '#0000FF', '#00CCCC'])
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
feature_1 = X[:, 0]
feature_2 = X[:, 1]
x_min, x_max = feature_1.min() - 1, feature_1.max() + 1
y_min, y_max = feature_2.min() - 1, feature_2.max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, mesh_step_size),
np.arange(y_min, y_max, mesh_step_size))
dec_boundary = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
dec_boundary = dec_boundary.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, dec_boundary, cmap=cmap_light)
# Plot also the training points
plt.scatter(feature_1, feature_2, c=y, cmap=cmap_bold)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
# plt.title(
# "{0}-Class classification (k = {1}, metric = '{2}')"
# .format(n_classes, clf.k, clf.distance))
plt.show()
def euclidean_distance(a, b):
"""Compute the euclidean_distance between two numpy arrays.
Parameters
----------
a: numpy array
b: numpy array
Returns
-------
numpy array
"""
return np.sqrt(np.dot(a - b, a - b))
def cosine_distance(a, b):
"""Compute the cosine_distance between two numpy arrays.
Parameters
----------
a: numpy array
b: numpy array
Returns
-------
"""
return 1 - np.dot(a, b) / np.sqrt(np.dot(a, a) * np.dot(b, b))
class KNearestNeighbors(object):
"""Classifier implementing the k-nearest neighbors algorithm.
Parameters
----------
k: int, optional (default = 5)
Number of neighbors that get a vote.
distance: function, optional (default = euclidean)
The distance function to use when computing distances.
"""
def __init__(self, k=5, distance=euclidean_distance):
"""Initialize a KNearestNeighbors object."""
self.k = k
self.distance = distance
def fit(self, X, y):
"""Fit the model using X as training data and y as target labels.
According to kNN algorithm, the training data is simply stored.
Parameters
----------
X: numpy array, shape = [n_samples, n_features]
Training data.
y: numpy array, shape = [n_samples,]
Target labels.
Returns
-------
None
"""
self.X_train = X
self.y_train = y
def predict(self, X):
"""Return the predicted labels for the input X test data.
Assumes shape of X is [n_test_samples, n_features] where n_features
is the same as the n_features for the input training data.
Parameters
----------
X: numpy array, shape = [n_samples, n_features]
Test data.
Returns
-------
result: numpy array, shape = [n_samples,]
Predicted labels for each test data sample.
"""
num_train_rows, num_train_cols = self.X_train.shape
num_X_rows, _ = X.shape
X = X.reshape((-1, num_train_cols))
distances = np.zeros((num_X_rows, num_train_rows))
for i, x in enumerate(X):
for j, x_train in enumerate(self.X_train):
distances[i, j] = self.distance(x_train, x)
# Sort and take top k
top_k = self.y_train[distances.argsort()[:, :self.k]]
result = np.zeros(num_X_rows)
for i, values in enumerate(top_k):
top_voted_label, _ = Counter(values).most_common(1)[0]
result[i] = top_voted_label
return result
def score(self, X, y_true):
"""Return the mean accuracy on the given data and true labels.
Parameters
----------
X: numpy array, shape = [n_samples, n_features]
Test data.
y_true: numpy array, shape = [n_samples,]
True labels for given test data, X.
Returns
-------
score: float
Mean accuracy of self.predict(X) given true labels, y_true.
"""
y_pred = self.predict(X)
score = y_true == y_pred
return np.mean(score)
def plot_mult_decision_boundary(ax, X, y, k, scaled=True,
title='Title', xlabel='xlabel',
ylabel='ylabel', hard_class = True):
"""Plot the decision boundary of a kNN classifier.
Builds and fits a sklearn kNN classifier internally.
X must contain only 2 continuous features.
Function modeled on sci-kit learn example.
Parameters
----------
ax: Matplotlib axes object
The plot to draw the data and boundary on
X: numpy array
Training data
y: numpy array
Target labels
k: int
The number of neighbors that get a vote.
scaled: boolean, optional (default=True)
If true scales the features, else uses features in original units
title: string, optional (default = 'Title')
A string for the title of the plot
xlabel: string, optional (default = 'xlabel')
A string for the label on the x-axis of the plot
ylabel: string, optional (default = 'ylabel')
A string for the label on the y-axis of the plot
hard_class: boolean, optional (default = True)
Use hard (deterministic) boundaries vs. soft (probabilistic) boundaries
Returns
-------
None
"""
x_mesh_step_size = 0.1
y_mesh_step_size = 0.01
#Hard code in colors for classes, one class in red, one in blue
bg_colors = np.array([np.array([255, 150, 150])/255, np.array([150, 150, 255])/255])
cmap_light = ListedColormap(bg_colors)
cmap_bold = ListedColormap(['#FF0000', '#0000FF'])
#Build a kNN classifier
clf = neighbors.KNeighborsClassifier(n_neighbors=k, weights='uniform')
if scaled:
#Build pipeline to scale features
clf = make_pipeline(StandardScaler(), clf)
clf.fit(X, y)
else:
clf.fit(X, y)
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
x_min, x_max = 45, 85
y_min, y_max = 2, 4
xx, yy = np.meshgrid(np.arange(x_min, x_max, x_mesh_step_size),
np.arange(y_min, y_max, y_mesh_step_size))
if hard_class:
dec_boundary = clf.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
ax.pcolormesh(xx, yy, dec_boundary, cmap=cmap_light)
ax.scatter(X[:, 0], X[:, 1], c='black', cmap=cmap_bold)
else:
dec_boundary = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])
colors = dec_boundary.dot(bg_colors)
ax.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
ax.imshow(colors.reshape(200, 400, 3), origin = "lower", aspect = "auto", extent = (x_min, x_max, y_min, y_max))
ax.set_title(title + ", k={0}, scaled={1}".format(k, scaled))
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_xlim((x_min, x_max))
ax.set_ylim((y_min, y_max))
if __name__ == '__main__':
X, y = make_classification(n_classes=3, n_features=2, n_redundant=0,
n_informative=2, n_clusters_per_class=1,
class_sep=1, random_state=5)
print(y.shape)
knn = KNearestNeighbors(4, cosine_distance)
knn.fit(X, y)
print("Accuracy: {}".format(knn.score(X, y)))
print("\tactual\tpredict\tcorrect?")
for i, (actual, predicted) in enumerate(zip(y, knn.predict(X))):
print("{}\t{}\t{}\t{}".format(i,
actual,
int(predicted),
int(actual == predicted)))
# This loop plots the decision boundaries for different decision metrics
for metric in [euclidean_distance, cosine_distance]:
# we create an instance of Neighbours Classifier and fit the data.
clf = KNearestNeighbors(k=3, distance=metric)
clf.fit(X, y)
plot_decision_boundary(clf, X, y, n_classes=3)
|
49c1984dd1ed9e587758a8d7d248af1e5f11e4e8 | DSR1505/Python-Programming-Basic | /02. For loops/2.03.py | 133 | 3.546875 | 4 | """ Write a program that outputs 100 lines, numbered 1 to 100, each with
your name on it. """
for i in range(100):
print(i+1,'DSR') |
2416bb2ff294f45b1c3fb45633c79de43b251531 | thrishik7/ML-algos | /linear_regression.py | 2,063 | 3.671875 | 4 | import pandas as pd
from pandas import DataFrame
import numpy as np
import matplotlib.pyplot as plt
#LINEAR REGRESSION
def initialize_parameters(lenw, b=0):
w= np.random.randn(1,lenw)
return w,b
def forward_prop(X,w,b):
z=np.dot(w,X) +b #hypothesis
return z
def cost_function(z,y):
m= y.shape[0]
J=(1/(2*m))*np.sum(np.square(z-y)) #cost function
return J
def back_prop(X,y,z):
m=y.shape[0]
dz=(1/m)*(z-y)
dw=np.dot(dz,X.T)
db=np.sum(dz)
return dw,db
def gradient_descent_update(w,b,dw,db,learning_rate=10):
w= w-learning_rate*dw
b= b-learning_rate*db
return w,b
def linear_regression_model(x_train,y_train,x_val,y_val,epochs,learning_rate=10):
lenw=x_train.shape[0]
lenw2=x_val.shape[0]
w,b=initialize_parameters(lenw)
costs_train =[]
m_train = y_train.shape[0]
m_val=y_val.shape[0]
for i in range(1,epochs+1):
z_train= forward_prop(x_train,w,b)
cost_train=cost_function(z_train,y_train)
dw,db=back_prop(x_train,y_train,z_train)
w,b=gradient_descent_update(w,b,dw,db,learning_rate)
if i%10==0:
costs_train.append(cost_train)
#MAE_train
MAE_train=(1/m_train)*np.sum(np.abs(z_train-y_train))
#cost_val, MAE_VAL
w2,b2=initialize_parameters(lenw2)
z_val =forward_prop(x_val,w2,b2)
cost_val = cost_function(z_val,y_val)
MAE_val=(1/m_val)*np.sum(np.abs(z_val-y_val))
print('Epochs '+str(i)+'/'+str(epochs)+':')
print('Training cost '+str(cost_train)+'|'+'Validation cost '+str(cost_val))
print('Training MAE '+str(MAE_train)+'|'+'Validation MAE'+str(MAE_val))
plt.plot(costs_train)
plt.xlabel('Iterations(per tens)')
plt.ylabel('Training Cost')
plt.title('Learning rate'+str(learning_rate))
plt.show()
df= pd.read_csv("Salary_Data.csv")
x_train=df['YearsExperience']
y_train=df['Salary']
plt.plot(x_train,y_train)
vf=df.iloc[:10]
x_val=vf['YearsExperience']
y_val=vf['Salary']
linear_regression_model(x_train,y_train,x_val,y_val,2,0.01)
|
5870ceb75f5842badd837fed1931aadcfd18ff92 | skellykiernan/pylearn | /VI/ch29/specialize.py | 924 | 3.734375 | 4 | class Super(object):
"""Top class"""
def method(self):
"""example method"""
print("in Super.method")
def delegate(self):
"""call a action if defined in subclass"""
self.action()
class Inheritor(Super):
"""all methods in Super"""
pass
class Replacer(Super):
"""Overrides Super.method"""
def method(self):
print("in Replacer.method")
class Extender(Super):
"""extend Super's Method"""
def method(self):
print("starting Extender.method")
Super.method(self)
print("ending Extender.method")
class Provider(Super):
"""provides an action for delegation"""
def action(self):
print("in Provider.action")
if __name__ == '__main__':
for klass in (Super, Inheritor, Replacer, Extender):
print(klass.__name__, "...")
klass().method()
print("Provider")
x = Provider()
x.delegate()
|
9494ac43f651c653f97ed0337427d2b6cc4edd5b | PJHalvors/Learning_Python | /ZedEx5to8.py | 3,462 | 4.1875 | 4 | #!/bin/env/python
#This program contains exercises Num5 to Num8 from Zed's Book
#Exercise5:Printing with variables
#Set variables to numeric or characters
name = "PJ"
age = 25 #arbitrary number
ht = 68.125 #also arbitrary
wt = 125 #also also arbitrary
eyes = 'Almond'
teeth = 'White'
hair = 'Purple-Undercut' #I totally wish! This would be so cool!!
#Write six strings inserting character or numeric variables
print "Let's talk about %s." % name
print "She's %d inches tall." % ht
print "She's %d pounds heavy." % wt
print "Actually that's not too heavy."
print "She's got %s eyes and %s hair." % (eyes, hair)
print "Those teeth are usually %s depending on the coffee." % teeth
print "If I add %d, %d, and %d I get %d."%(
age, ht, wt, age + ht + wt)
print"";print"";print"";print"";
#Exercise6:Strings and text
#Set variable x to a string containing a numeric insert, variable to character values, and var y to another string
x = "There are %d types of people." % 10
binary = "binary"; do_not = "don't";
y = "Those who know %s and those who %s." % (binary, do_not)
#Display two strings, which contain variables. String within a string. Twice.
print x
print y
#Display a string within a string. Twice.
print "I said: %r." % x
print "I also said: '%s'." % y
#Set variables to alphanumeric values
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
#Display string with the above two variables. String in a string here.
print joke_evaluation % hilarious
#Set variables w and e to strings
w = "This is the left side of..."
e = "a string with a right side."
#Write out both strings. 3 things: 2 strings in a string, and a string in a string twice.
print w + e
#Need Spaces!
print"";print"";print"";print"";
#Exercise7:
#The first three lines each print a string.
print "Mary had a little lamb."
print "Its fleece was white as %s." % 'snow'
print "And everywhere that Mary went."
#Print ten punctuation marks in a row
print "." * 10
#Set twelve variables to twelve character values
#To save space, I'm using a semicolon to place more than one line in the same line.
#This results in two lines with six variables to a character value per variable
end1 = "C";end2 = "h";end3 = "e";end4 = "e";end5 = "s";end6 = "e"
end7 = "B";end8 = "u";end9 = "r";end10 = "g";end11 = "e";end12 = "r";
#Print one whole string with all twelve character values
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 + end12
#Removing the comma at the end of end6 variable yields two lines with six variables each
print end1 + end2 + end3 + end4 + end5 + end6
print end7 + end8 + end9 + end10 + end11 + end12
print"";print"";print"";print"";
#Exercise8:Printing with formatters
#Set a variable formatter to print for values no matter what
#Percent r means values can be alphanumeric or even strings
formatter = "%r %r %r %r"
#Print string where there are numbers inserted in a formatter
print formatter % (1, 2, 3, 4)
#Print string with characters (words as string) inserted
print formatter % ("one", "two", "three", "four")
#Print variable formatter with True or False inserted in
print formatter % (True, False, False, True)
#Print content in the string for formatter times four
print formatter % (formatter, formatter, formatter, formatter)
#Print four strings in the next string
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
|
5142a2061f67f69daa9329dffe5abf27025dd2d8 | wfwf1990/python | /Day2/zuoye.py | 281 | 3.6875 | 4 |
#打印出所有三位数中的水鲜花数
num = 100
while num <= 999:
num1 = num // 100
num2 = num // 10 % 10
num3 = num % 10
if num == num1 ** 3 + num2 ** 3 + num3 ** 3:
print(num)
num += 1
ge = " "
str1 = input("str:")
print(str1.count(" "))
|
97216740dd0b98638ad62846afee34bac659a97f | innalesun/repetition-of-the-material | /функции/les10.07.py | 896 | 3.875 | 4 | '''
p = lambda x=1,y=2:x**y
s = p
print(s(5))
'''
def f_func():
print('test func1')
def sec_func():
print('test func2')
def sim_func(fn):
print('start')
fn()
print('stop')
a = sim_func(f_func())
b = sec_func(sec_func())
'''
def simple_decore(fn):
print('start function')
fn()
print('stop function')
#return wrapper()
@simple_decore
def firs_test():
print('test function1')
'''
'''
def season(a):
if a == 1 or a == 2 or a == 12:
print('зима')
elif a == 3 or a == 4 or a == 5:
print('весна')
elif a == 6 or a == 7 or a == 8:
print('лето')
elif a == 9 or a == 10 or a == 11:
print('осень')
season(int(input('введите номер месяца')))
'''
'''
import random
a = [random.randint(0,100) for i in range(10)]
def sr(a):
return sum(a)/10
print(sr(a))
'''
|
65b5caa728844dec3dd6d38fa7b1242b6d365bb8 | tillderoquefeuil-42-ai/bootcamp-ml | /day04/ex12/polynomial_model.py | 946 | 4.1875 | 4 | import numpy as np
def add_polynomial_features(x, power):
"""
Add polynomial features to vector x by raising its values up to the power given in argument.
Args:
x: has to be an numpy.ndarray, a vector of dimension m * 1.
power: has to be an int, the power up to which the components of vector x are going to be raised.
Returns:
The matrix of polynomial features as a numpy.ndarray, of dimension m * n, containg he polynomial feature values for all training examples.
None if x is an empty numpy.ndarray.
"""
def __isEmpty(*arg):
for data in arg:
if not hasattr(data, 'shape'):
return True
elif data.shape[0] == 0:
return True
return False
if __isEmpty(x):
return None
data = x[:]
for i in range (2, power+1):
data = np.concatenate((data, np.power(x, i)), axis=1)
return data
|
556e3c6a72cc8bcee51baa8a8afa17eb2f90bbad | pjedur/python | /Verkefni1/palindrome.py | 252 | 3.703125 | 4 | def palindrome(n,b):
if n < b:
x = format(n)
return x == x[::-1]
if b == 10:
x = format(n)
return x == x[::-1]
if b == 2:
X = bin(n)[2:]
return X == X[::-1]
return False
|
b10d24079c9637043111c3a74837e10ebe156e1e | Quelklef/gin-bots | /bots/simple/simple_gin.py | 1,007 | 3.71875 | 4 | """ A simple gin bot """
import random
import sys
sys.path.append('../..')
import gin
import client
def choose_draw(hand, history, derivables):
""" choose where to draw a card from """
discard = derivables['discard']
their_hand = derivables['other_hand']
current_points = gin.points_leftover(hand, their_hand)
theoretical_points = gin.points_leftover(hand | {discard[-1]}, their_hand)
if theoretical_points < current_points:
return 'discard'
else:
return 'deck'
def choose_discard(hand, history, derivables):
""" choose which card to discard """
their_hand = derivables['other_hand']
def score_from_removing(discard_choice):
return gin.points_leftover(hand - {discard_choice}, their_hand)
return min(hand, key=score_from_removing)
def should_end(hand, history, derivables):
""" choose whether or not to go down """
return True
simple_bot = client.make_bot(choose_draw, choose_discard, should_end)
if __name__ == '__main__':
client.play_bot(simple_bot)
|
e36ba285d16f0676270d3833d1aa0880e54c8a17 | Llontop-Atencio08/t07_Llontop.Rufasto | /Rufasto_Torres/Bucles.Mientras.py | 1,427 | 3.96875 | 4 | Ejercicio01
#Pedir edad de ingreso a la escuela PNP
edad=10
edad_invalida=(edad<16 or edad >25)
while(edad_invalida):
edad=int(input("ingrese edad:"))
edad_invalida=(edad<16 or edad >25)
#fin_while
print("edad valida:",edad)
#Ejercicio02
#Pedir nota de sustentacion de tesis
nota=0
nota_desaprobada=(nota<12 or edad >20)
while(nota_desaprobada):
nota=int(input("Ingrese nota:"))
nota_desaprobada=(nota<12 or edad >20)
#fin_while
print("Nota aprobada:",nota)
#Ejercicio03
#Pedir puntaje minimo para ingresar a la UNPRG
puntaje=12.20
puntaje_invalido=(puntaje<90.00 or puntaje>300.00)
while(puntaje_invalido):
puntaje=float(input("Ingrese puntaje:"))
puntaje_invalido=(puntaje<90.00 or puntaje>300.00)
#fin_while
print("Puntaje alcanzado:",puntaje)
#Ejercicio04
#Pedir ponderado de un alumno para ver si ocupa el tercio superior
ponderado=9.6
ponderado_no_valido=(ponderado<15.00 or ponderado>20.00)
while(ponderado_no_valido):
ponderado=float(input("Ingrese ponderado:"))
ponderado_no_valido=(ponderado<15.00 or ponderado>20.00)
#fin_while
print("Ponderado valido:",ponderado)
#Ejercicio05
#Pedir temperatura de una persona
temperatura=23.0
temperatura_alta=(temperatura<35.0 or temperatura>38.0)
while(temperatura_alta):
temperatura=float(input("Ingrese temperatura:"))
temperatura_alta=(temperatura<35.0 or temperatura>38.0)
#fin_while
print("Temperatura normal:",temperatura)
|
16a5025f389caa8761f4fd198ddce941d3d6a42c | akarshvs/LOGIC-BUILDING-PYTHON | /reversesent.py | 212 | 3.65625 | 4 | sent = input()
sent = sent[:-1]
count = 0
word_lis = sent.split(' ')
for word in word_lis:
count +=1
print(f'LENGTH : {count}')
print('REARRANGED SENTENCE')
print(*sorted(word_lis),sep=' ',end='.')
|
6123e4f75ef3ab051b9d47c9ca17dcbc566a3e91 | godarderik/projecteuler | /Solved/Problem62.py | 486 | 3.515625 | 4 | cubes = {}
for z in range(10000):
sort = list(str(z**3))
for x,y in enumerate(sort):
sort[x] = int(y)
sort = sorted(sort)
for x,y in enumerate(sort):
sort[x] = str(y)
sort = "".join(sort)
if sort in cubes:
cubes[sort][0] += 1
cubes[sort][1].append(z**3)
if cubes[sort][0] == 5:
print sorted(cubes[sort][1])
else:
cubes[sort] = []
cubes[sort].append(1)
cubes[sort].append([z**3])
|
3dc0655e7b208b9fd45777a4a4125a712f588eae | erjan/coding_exercises | /subsets_ii.py | 562 | 3.765625 | 4 | '''
Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
'''
class Solution(object):
def subsetsWithDup(self, nums):
ret = []
self.dfs(sorted(nums), [], ret)
return ret
def dfs(self, nums, path, ret):
ret.append(path)
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i-1]:
continue
self.dfs(nums[i+1:], path+[nums[i]], ret)
|
c07feb81c09c8a5b4e5d73ed3f4df146413acbde | purnesh42H/algorithms-in-python | /python_modules_and_structures/python_modules_basic.py | 2,210 | 4 | 4 | '''
Note that functions are also treated as objects in python. When def is
executed, a function object is created together with its object reference.
If we do not define a return value, Python automatically returns None
An activation record happens every time we invoke a method: information
is put in the stack to support invocation.
'''
# Default values in module
'''
Whenever you create a module, remember that mutable objects should not
be used as default values in the function or method definition:
'''
#Good
def func(a, b=None):
if b == None:
b = []
b.append(a)
#Bad
def func(a, b=[]):
b.append(a)
# The __init__.py file
'''
A package is a directory that contains a set of modules and a file called
__init__.py . This is required to make Python treat the directories as
containing packages, preventing directories with a common name (such as
“string”) from hiding valid modules that occur later on the module search
path:
'''
# The __name__ variable
'''
Whenever a module is imported, python creates a variable for it called __name__
and store's the module's name in this variable
'''
# Byte-coded Compiled Modules
'''
When the Python interpreter is invoked with the -O flag, optimized
code is generated and stored in .pyo files. The optimizer removes assert
statements. This also can be used to distribute a library of Python code
in a form that is moderately hard to reverse engineer
'''
# sys module
'''
The variable sys.path is a list of strings that determines the interpreter’s
search path for modules. It is initialized to a default path taken from the environment
variable PYTHONPATH, or from a built-in default. You can modify
it using standard list operations:
'''
import sys
import os
sys.path.append(os.path.abspath('../')) # add the parent folder path
'''
The variable sys.argv allows us to use the arguments passed in the
command line inside our programs
'''
import sys
def main():
for arg in sys.argv[1:]:
print(arg)
if __name__ == 'main':
main()
# The dir() method
'''
We can get list of methods and variables of a obeject.
It returns the sorted list all types of names: variables, modules, functions.
'''
import sys
print(dir(sys))
|
d9763ecec0aa411ba014d6fb25e29b0f0273fcb7 | ITlearning/ROKA_Python | /2021_03/03_07/input_error.py | 133 | 3.671875 | 4 | string = input("입력 > ")
print("입력 + 100 : ", string + 100)
# input 함수의 입력은 무조건 문자열 자료형이다. |
5a6647baedeb215e44f993773b29a4aae4c231f7 | rezavai92/leetcode-solution | /24. Swap Nodes in Pairs/python-solution.py | 711 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swap(self,head):
current = head
fakeHead = ListNode()
fakeHead.next=head
prev=fakeHead
while(current and current.next):
prev.next=current.next
current.next= current.next.next
prev.next.next=current
prev=current
current=current.next
return fakeHead.next
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
return self.swap(head)
|
b0f86b213d708b9b91f8d096f83f60853882b08e | ft25/Python-Programming | /codekata/count_no_of_digits.py | 43 | 3.5 | 4 | num=(input("enter a no:"))
print(len(num))
|
94bde5490afe3cbe2205576585ff509d7bc37d00 | wuqunfei/algopycode | /leetcode/editor/en/[1114]Print in Order.py | 2,109 | 4.15625 | 4 | # Suppose we have a class:
#
#
# public class Foo {
# public void first() { print("first"); }
# public void second() { print("second"); }
# public void third() { print("third"); }
# }
#
#
# The same instance of Foo will be passed to three different threads. Thread A
# will call first(), thread B will call second(), and thread C will call third().
# Design a mechanism and modify the program to ensure that second() is executed
# after first(), and third() is executed after second().
#
# Note:
#
# We do not know how the threads will be scheduled in the operating system,
# even though the numbers in the input seem to imply the ordering. The input format
# you see is mainly to ensure our tests' comprehensiveness.
#
#
# Example 1:
#
#
# Input: nums = [1,2,3]
# Output: "firstsecondthird"
# Explanation: There are three threads being fired asynchronously. The input [1,
# 2,3] means thread A calls first(), thread B calls second(), and thread C calls
# third(). "firstsecondthird" is the correct output.
#
#
# Example 2:
#
#
# Input: nums = [1,3,2]
# Output: "firstsecondthird"
# Explanation: The input [1,3,2] means thread A calls first(), thread B calls
# third(), and thread C calls second(). "firstsecondthird" is the correct output.
#
#
#
# Constraints:
#
#
# nums is a permutation of [1, 2, 3].
#
# Related Topics Concurrency 👍 840 👎 149
# leetcode submit region begin(Prohibit modification and deletion)
class Foo:
def __init__(self):
pass
def first(self, printFirst: 'Callable[[], None]') -> None:
# printFirst() outputs "first". Do not change or remove this line.
printFirst()
def second(self, printSecond: 'Callable[[], None]') -> None:
# printSecond() outputs "second". Do not change or remove this line.
printSecond()
def third(self, printThird: 'Callable[[], None]') -> None:
# printThird() outputs "third". Do not change or remove this line.
printThird()
# leetcode submit region end(Prohibit modification and deletion)
|
51f87001e2bf858026345886206cc5489af01f9c | Utugoed/SimpleBankingSystem | /banking.py | 4,837 | 3.640625 | 4 | import random
import sqlite3
def luhn(number):
sum = 0
for i in range(15):
if i % 2 == 0:
k = int(number[i]) * 2
if k > 9:
k -= 9
sum += k
else:
sum += int(number[i])
sum = (10 - sum % 10) % 10
return str(sum)
def create_acc():
number = '400000' + str(random.randint(100000000, 999999999))
number += luhn(number)
pin = str(random.randint(0, 9999)).zfill(4)
balance = 0
cur.execute('''SELECT number FROM card WHERE number={}'''.format(number))
if (cur.fetchone() == None):
cur.execute('''INSERT INTO card(number,pin,balance)
VALUES ({},{},{})'''.format(number, pin, balance))
conn.commit()
print('''Your card has been created
Your card number:
{}
Your card PIN:
{}'''.format(number, pin))
else:
return create_acc()
def log_in():
print('Enter your card number:')
global number
number = input()
print('Enter your PIN:')
pin = str(input())
cur.execute('''SELECT
number,
pin
FROM
card
WHERE
number = {}'''.format(number))
temp = str(cur.fetchone())
if (temp == 'None'):
print('Wrong card number or PIN!')
return False
temp = temp.replace('(', '')
temp = temp.replace(')', '')
temp = temp.replace("'", '')
temp = temp.replace(',', '')
tab_pin = temp.split()[1]
if (tab_pin == pin):
return True
print('Wrong card number or PIN!')
return False
#4000002070779259
#8761
def balance():
global number
cur.execute('''SELECT balance
FROM card
WHERE number = {}'''.format(number))
balance = str(cur.fetchone())[1:-2]
print('Balance: {}'.format(balance))
def add_income():
global number
print('Enter income:')
income = int(input())
cur.execute('''UPDATE card
SET balance = balance + {}
WHERE number = {}'''.format(income, number))
conn.commit()
print('Income was added!')
def transfer():
global number
print('Enter card number:')
number_to = input()
if (number_to == number):
print("You can't transfer money to the same account!")
return False
if (number_to[-1] != luhn(number_to[0:-1])):
print("Probably you made a mistake in the card number. Please try again!")
return False
cur.execute('SELECT number FROM card WHERE number = {}'.format(number_to))
if (cur.fetchone() == None):
print('Such a card does not exist.')
return False
print('Enter how much money you want to transfer:')
sum = int(input())
cur.execute('SELECT balance FROM card WHERE number = {}'.format(number))
if (sum > int(str(cur.fetchone())[1:-2])):
print('Not enough money!')
return False
cur.execute('''UPDATE card
SET balance = balance - {}
WHERE number = {}'''.format(sum, number))
cur.execute('''UPDATE card
SET balance = balance + {}
WHERE number = {}'''.format(sum, number_to))
conn.commit()
return True
def close():
global number
cur.execute('DELETE FROM card WHERE number = {}'.format(number))
conn.commit()
conn = sqlite3.connect('card.s3db')
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS card(
id INTEGER PRIMARY KEY,
number TEXT,
pin TEXT,
balance INTEGER DEFAULT (0))''')
conn.commit()
exit = True
number = 0
while exit:
print('1. Create an account')
print('2. Log into account')
print('0. Exit')
act = int(input())
if act == 1:
create_acc()
if act == 2:
if log_in():
print('You have successfully logged in!')
exit2 = True
while exit2:
print('1. Balance')
print('2. Add income')
print('3. Do transfer')
print('4. Close account')
print('5. Log out')
print('0. Exit')
act_2 = int(input())
if (act_2 == 1):
balance()
if (act_2 == 2):
add_income()
if (act_2 == 3):
if transfer():
print('Success!')
if (act_2 == 4):
close()
exit2 = False
if (act_2 == 5):
exit2 = False
if (act_2 == 0):
print('Bye!')
exit2 = False
exit = False
if (act == 0):
print('Bye!')
exit = False
|
0a32ad2ce7f63f6a610530b4b65d277b45ca8aeb | zmatteson/clrs-algorithm | /chapter_2/exercices/2_1_4.py | 718 | 4.03125 | 4 | #Add 2 n bit binary integers, stored in two n-element arrays
#The sum should be stored in binary form in an (n + 1) array C
#Input 2 Arrays of size n representing binary ints
#Output one array of their sum with size n+1
def add_binary_ints(A,B):
C = []
carry = 0
for i in range(len(A)-1, -1, -1):
s = A[i] + B[i]
if s > 1:
C.insert(0,0)
carry = 1
elif s + carry > 1:
C.insert(0,0)
carry = 1
else:
C.insert(0,s+carry)
carry = 0
if carry == 1:
C.insert(0, carry)
else:
C.insert(0,0)
return C
if __name__ == "__main__":
print(add_binary_ints([1,1,1],[0,0,1])) |
9e5b35dcbef3b32d31df04981e4e1673ca3c7fe0 | angelosuporte/PythonLearning | /app_pyLearning/ClassExample2.py | 542 | 3.8125 | 4 | class Calculadora:
def soma(self, valor_a, valor_b):
return valor_a + valor_b
def subtracao(self, valor_a, valor_b):
return valor_a - valor_b
def multiplicacao(self, valor_a, valor_b):
return valor_a * valor_b
def divisao(self, valor_a, valor_b):
return valor_a / valor_b
if __name__ == '__main__':
calculadora = Calculadora()
print(calculadora.soma(10, 2))
print(calculadora.subtracao(5, 3))
print(calculadora.multiplicacao(100, 2))
print(calculadora.divisao(10, 5)) |
864459b88c5b38c5119e8ef0ef0f4dedf057203d | fengye-lu/python_fullstack_oldboy | /week/day27/threading_test.py | 1,323 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/2/29 15:35
# @Author : Jackey-lu
# @File : threading_test.py
import threading
from time import ctime, sleep
# def music(func):
# for i in range(2):
# print('I was listening to %s. %s'%(func,ctime()))
# sleep(1)
#
# def move(func):
# for i in range(2):
# print('I was at the %s! %s'%(func,ctime()))
# sleep(5)
#
# if __name__ == '__main__':
# music('七里香')
# move('世界末路')
def music(func):
print(threading.current_thread())
for i in range(2):
print('I was listening to %s. %s' % (func, ctime()))
sleep(1)
print('end listening %s'%ctime())
def move(func):
print(threading.current_thread())
for i in range(2):
print('I was watching the %s! %s' % (func, ctime()))
sleep(5)
print('end watching %s'%ctime())
threads = []
t1 = threading.Thread(target=music,args=('七里香',))
threads.append(t1)
t2 = threading.Thread(target=move,args=('世界末路',))
threads.append(t2)
if __name__ == '__main__':
t1.setDaemon(True)
for t in threads:
# t.setDaemon(True) # 守护线程(其他线程一旦结束,守护线程也会立马结束)
t.start()
t.join()
print(threading.current_thread())
print('all over %s'%ctime())
|
aa945ff2466efdb5c73300c1c60f4a844ebac4bb | mrdotb/computor_v1 | /main.py | 461 | 4.09375 | 4 | #!/usr/bin/env python3
import sys
from Equation import Equation
argc = len(sys.argv)
if argc < 2:
sys.exit("Missing argument")
elif argc > 2:
sys.exit("Too much arguments")
e = Equation(sys.argv[1])
print("Input form: ", e.format())
e.simplify()
print("Reduced form: ", e.format())
print("Polynomial degree: ", e.degree())
if e.degree() > 2:
print("The polynomial degree is stricly greater than 2, I can't solve.")
else:
print(e.solve())
|
7383a4bd0d840e2f1aba926361538461e4e182ad | chachout/Python-petits-programmes | /Conversion des degrés en radians.py | 93 | 3.921875 | 4 | d=float(input("angle en degré : "))
r=(d*2.*pi)/360.
print (d,"degrés font",r, "radians") |
22a8a7e7165d12252e040f2632c6fad41ced8727 | aryan-jain/ping-pong-leaderboard | /matchups.py | 1,599 | 3.625 | 4 | import argparse
import itertools
def main():
matchups = []
if args.type == "singles":
for player in itertools.combinations(args.players, 2):
sit_out = tuple([p for p in args.players if p not in player])
matchups.append((player[0], player[1], sit_out))
elif args.type == "doubles":
teams = list(itertools.combinations(args.players, 2))
for team in itertools.combinations(teams, 2):
players = set(team[0]).union(set(team[1]))
if len(players) == 4:
sit_out = tuple([p for p in args.players if p not in players])
matchups.append((team[0], team[1], sit_out))
print(f"There are {len(matchups)} possible games.")
matchups = [
y
for x in zip(
*[
[j for j in i]
for _, i in itertools.groupby(
sorted(matchups, key=lambda x: x[-1]), lambda x: x[-1]
)
]
)
for y in x
]
for match in matchups:
print(f"{match[0]} vs. {match[1]} -- {','.join(match[2])} sits out.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Generate a list of matchups given a list of players."
)
parser.add_argument("--players", "-p", type=str, nargs="+", required=True)
parser.add_argument(
"--type",
"-t",
type=str,
choices=["singles", "doubles"],
help="Game type. [singles, doubles] Default: doubles",
default="doubles",
)
args = parser.parse_args()
main()
|
f6dd03a1c32adcd21f71856c1c51840d0ad1b6d9 | RafaelMri/boolean | /monotone.py | 12,707 | 3.640625 | 4 | """
This code supports functions that are of the form {0,1} ** n ==> {+1, -1}
This has two reasons:
* {0, 1} ** n allows us to use the binary representation which is convenient
* {+1, -1} is better when we want to work with fourier. Note that "+1 < -1" for that matter!
"""
import numpy
import itertools
import random
from utils import popcount, indices_and_n_to_num, num_and_n_to_indices, out
class Point(object):
# TESTED
def __init__(self, n, num):
"""for example: n=5, indices=[0,2] represents 10100"""
self.n = n
self.num = num
self.indices = num_and_n_to_indices(num, n)
self.binary_tuple = tuple(str(bin(self.num))[2:])
self.popcount = popcount(num)
def get_popcount(self):
return self.popcount
# TESTED
def __neg__(self):
return Point(self.n, 2 ** self.n - 1 - self.num)
def __str__(self):
return bin(self.num)[2:].zfill(self.n)
def __hash__(self):
return hash(str(self))
def __eq__(self, other):
return self.n == other.n and self.num == other.num
def __ne__(self, other):
return not self.__eq__(other)
def get_upper_neighbours(point, ctx):
"""gets a Point, returns all neighbors from one level above
all_points is a dictionary from num to point"""
all_points = ctx.NUM_TO_POINT
assert point in all_points.values()
res = []
for i in xrange(point.n):
if point.num ^ 2 ** (point.n - 1 - i) > point.num: # i'th from left is off
neigh = all_points[point.num ^ 2 ** (point.n - 1 - i)]
res.append(neigh)
return res
def get_lower_neighbours(point, ctx):
"""gets a Point, returns all neighbors from one level below
all_points is a dictionary from num to point"""
all_points = ctx.NUM_TO_POINT
assert point in all_points.values()
res = []
for i in xrange(point.n):
if point.num ^ 2 ** (point.n - 1 - i) < point.num: # i'th from left is on
neigh = all_points[point.num ^ 2 ** (point.n - 1 - i)]
res.append(neigh)
return res
def get_all_upper_neighbours(point, ctx):
"""gets a Point, returns all points that are above it
all_points is a dictionary from num to point"""
return get_all_directional_neighbours(point, ctx, direction="UPPER")
def get_all_lower_neighbours(point, ctx):
"""gets a Point, returns all points that are below it
all_points is a dictionary from num to point"""
return get_all_directional_neighbours(point, ctx, direction="LOWER")
def get_all_directional_neighbours(point, ctx, direction):
# If we have k zeros in the point, we expect 2**k points (because we include the point itself).
all_points = ctx.NUM_TO_POINT
one_indices = num_and_n_to_indices(point.num, point.n)
zero_indices = [x for x in xrange(point.n) if x not in one_indices]
indices_to_flip = []
if direction == "UPPER":
indices_to_flip = zero_indices
elif direction == "LOWER":
indices_to_flip = one_indices
else:
print "no direction!!!!!"
exit(1)
res = set()
for num_to_flip in xrange(len(indices_to_flip) + 1):
for indices in itertools.combinations(indices_to_flip, num_to_flip):
num_diff = indices_and_n_to_num(indices, point.n)
new_num = point.num ^ num_diff
res.add(all_points[new_num])
return res
class BooleanFunction(object):
def __init__(self, ctx, points_to_values):
self.ctx = ctx
self.n = ctx.N
self.points_to_values = points_to_values
self.val_array = numpy.array([points_to_values[ctx.NUM_TO_POINT[num]] for num in xrange(2 ** self.n)])
self.val_array = numpy.resize(self.val_array, [2] * self.n)
self.fft_arr = self.calc_fft()
def __str__(self, by_levels=True):
res = []
if by_levels:
for level_num, level in sorted(ctx.LEVEL_TO_POINTS.items()):
res.append("*" * 10 + (" %d " % level_num) + "*" * 10 + "\n")
for point in level:
res.append(str(point) + "\t" + str(self[point]) + "\n")
else:
for num in xrange(2 ** self.n):
point = ctx.NUM_TO_POINT[num]
res.append(str(point) + "\t" + str(self[point]) + "\n")
return "".join(res)
def __setitem__(self, point, val):
self.points_to_values[point] = val
def __getitem__(self, point):
return self.points_to_values[point]
# TESTED
def calc_fft(self):
fft_arr = numpy.fft.fftn(self.val_array) / 2 ** self.n
return map(float, fft_arr.reshape([2 ** self.n]))
def get_fourier_coeff(self, indices):
num = indices_and_n_to_num(indices, self.n)
return self.fft_arr[num]
def is_monotone(self):
for point, val in self.points_to_values.iteritems():
upper_neighs = get_upper_neighbours(point, ctx)
for un in upper_neighs:
if self[un] > val: #reverse because +1,-1
print point, val, un, self[un]
return False
return True
# TESTED
def generate_dual_function(bool_func):
new_points_to_values = {p: - bool_func[-p] for p in bool_func.points_to_values.keys()}
return BooleanFunction(bool_func.ctx, new_points_to_values)
# TESTED
def generate_not_of_function(bool_func):
new_points_to_values = {p: - bool_func[p] for p in bool_func.points_to_values.keys()}
return BooleanFunction(bool_func.ctx, new_points_to_values)
# TESTED
def multiply_functions(bool_func_1, bool_func_2):
new_points_to_values = {p: bool_func_1[p] * bool_func_2[p] for p in bool_func_1.points_to_values.keys()}
return BooleanFunction(bool_func_1.ctx, new_points_to_values)
def sample_monotone_function(ctx):
# This raises a natural question - how to randomly sample a monotone function?
# for now, we will start with the zero function, randomize point, and flip them with some probability
points_to_values = {p: 1 for p in ctx.NUM_TO_POINT.values()}
n = ctx.N
for num_flip in xrange(max(2 ** int(n / 2), 100)): # for now, magic numbers...
num = random.randint(0, 2 ** n - 1)
point = ctx.NUM_TO_POINT[num]
level = popcount(num)
dist_from_mid_level = 1 + abs(level - float(n) / 2)
# TODO - maybe flip with respect to level (extreme levels don't flip
to_flip = random.random() < 0.5 * (1 / dist_from_mid_level) ** 2
if to_flip:
if points_to_values[point] == 1:
all_to_flip = get_all_upper_neighbours(point, ctx)
for p_to_flip in all_to_flip:
points_to_values[p_to_flip] = -1
else:
all_to_flip = get_all_lower_neighbours(point, ctx)
for p_to_flip in all_to_flip:
points_to_values[p_to_flip] = 1
return BooleanFunction(ctx, points_to_values)
def sample_random_function(ctx):
points_to_values = {p: 1 - 2 * random.randint(0, 1) for p in ctx.NUM_TO_POINT.values()}
return BooleanFunction(ctx, points_to_values)
def generate_majority_function(ctx):
assert ctx.N % 2 == 1
new_points_to_values = {p: -1 if (float(p.popcount) / p.n > 0.5) else 1 for p in ctx.NUM_TO_POINT.values()}
return BooleanFunction(ctx, new_points_to_values)
class Level(object):
def __init__(self, ctx, points_to_values):
self.ctx = ctx
self.k = points_to_values.keys()[0].popcount
self.rep_as_num = "".join([str(b) for p, b in sorted(points_to_values.items(), key=lambda (pt, b): pt.num)])
self.points_to_values = points_to_values
def __str__(self):
res_str = ["N=" + str(ctx.N) + ", " + "K=" + str(self.k) + ":"]
res_str.extend([str(p) + " " + str(b) for p, b in sorted(self.points_to_values.items(), key=lambda (pt, b): pt.num)])
return '\n'.join(res_str)
def __hash__(self):
return hash(str(self))
def __eq__(self, other):
return self.rep_as_num == other.rep_as_num
def __ne__(self, other):
return not self.__eq__(other)
# TESTED
def generate_all_levels(ctx):
n = ctx.N
levels = ctx.LEVEL_TO_POINTS
res = [None] * (n + 1)
for level_num, l in levels.iteritems():
all_level_options = []
for num in xrange(2 ** len(l)):
indices = set(num_and_n_to_indices(num, len(l)))
level_option = {}
for idx_p, p in enumerate(l):
level_option[p] = -1 if (idx_p in indices) else 1
all_level_options.append(Level(ctx, level_option))
res[level_num] = all_level_options
return res
def levels_are_consistent(ctx, lower_level, upper_level):
for point, val in lower_level.points_to_values.iteritems():
if val == 1:
continue #no harm can be done
upper_neighbors = get_upper_neighbours(point, ctx)
for upper_neigh in upper_neighbors:
if upper_level.points_to_values[upper_neigh] == 1:
return False #found a counterexample to monotonicity
return True
def generate_all_legal_upgrades(ctx, all_levels):
n = ctx.N
level_option_to_legal_upgrades = {}
for level_num in xrange(n):
levels_lower = all_levels[level_num]
levels_upper = all_levels[level_num + 1]
for lower_level in levels_lower:
lower_level_legal_upgrades = []
for upper_level in levels_upper:
if levels_are_consistent(ctx, lower_level, upper_level):
lower_level_legal_upgrades.append(upper_level)
level_option_to_legal_upgrades[lower_level] = lower_level_legal_upgrades
return level_option_to_legal_upgrades
def generate_all_monotones(ctx, all_levels, level_option_to_legal_upgrades):
#build iteratively, level after level...
n = ctx.N
all_monotones = [[x] for x in all_levels[0]]
for level in xrange(1, n + 1):
new_all_monotones = []
for partial_monotone in all_monotones:
highest_level = partial_monotone[-1]
legal_upgrades = level_option_to_legal_upgrades[highest_level]
for legal_upgrade in legal_upgrades:
new_all_monotones.append(partial_monotone[:] + [legal_upgrade])
all_monotones = new_all_monotones
# TODO - create them as BooleanFunction
res = []
for monotone in all_monotones:
points_to_values = {}
for level in monotone:
points_to_values.update(level.points_to_values)
res.append(BooleanFunction(ctx, points_to_values))
return res
class GlobalContext(object):
def __init__(self, N):
self.N = N
self.NUM_TO_POINT = {}
self.LEVEL_TO_POINTS = {i: [] for i in xrange(N + 1)}
for i in xrange(2 ** N):
self.NUM_TO_POINT[i] = Point(N, i)
curr_level = popcount(i)
self.LEVEL_TO_POINTS[curr_level].append(self.NUM_TO_POINT[i])
for l in self.LEVEL_TO_POINTS.values():
l.sort(key=lambda p: p.num)
def __getitem__(self, item):
return self.NUM_TO_POINT[item]
if __name__ == "__main__":
print "moo main"
N = 3
ctx = GlobalContext(N=N)
all_levels = generate_all_levels(ctx)
legal_upgrades = generate_all_legal_upgrades(ctx, all_levels)
all_monotones = generate_all_monotones(ctx, all_levels, legal_upgrades)
print len(all_monotones)
print all_monotones[14]
assert all([x.is_monotone for x in all_monotones])
"""
a = get_all_upper_neighbours(point, ctx)
b = get_all_lower_neighbours(point, ctx)
c = get_upper_neighbours(point, ctx)
d = get_lower_neighbours(point, ctx)
mon_funcs = [sample_monotone_function(ctx) for i in xrange(100)]
rand_funcs = [sample_random_function(ctx) for i in xrange(1000)]
print sum([bf.is_monotone() for bf in mon_funcs])
for x in [bf for bf in rand_funcs if bf.is_monotone()]:
print x
print "what"
mon_func = sample_monotone_function(ctx)
#print mon_func
maj_bf = BooleanFunction(ctx, {Point(N, num) : val for num, val in zip(range(2**N), 2 * [1, 1, 1, -1, 1, -1, -1, -1])})
print maj_bf
print map(float, maj_bf.fft_arr)
not_maj_bf = generate_not_of_function(maj_bf)
print not_maj_bf
print map(float, not_maj_bf.fft_arr)
mult_func = multiply_functions(maj_bf, not_maj_bf)
print mult_func
print mult_func.fft_arr
print '*'*40
random_func = sample_random_function(ctx)
print random_func
print random_func.fft_arr
dual_func = generate_dual_function(random_func)
print dual_func
print dual_func.fft_arr
"""
|
b1662b04a4b1b8d3ffd1e018abd69f4efcdce832 | colephalen/SP_2019_210A_classroom | /students/TylerRay/session3/mailroom.py | 2,796 | 4.15625 | 4 | #!/usr/bin/env python3
donors = [("Alpha Beta", [1000.21, 250.80]),
("Tucker Jones", [800.33]),
("Vladmir Putin", [500000.12, 250000.55, 750000]),
("Kim Jong Il", [200.80]),
("Tony Robinson", [500000, 1000000, 750000])]
donor = donors[0]
donations = donors[1]
def main_menu():
'''
Main menu for the program.
Will loop through and requests input until 3 is entered and then quits.
1 will allow an addition of a donator, a new donation and the printing of a thank you letter
2 will print a report of the donators and their donations as well as their average donation.
'''
while True:
choice = input("""What would you like to do?
1: Send a thank you
2: Create a Report
3: Quit
>>>""").strip()
if choice == "1":
# leads to the thank_you function
thank_you()
elif choice == "2":
# leads to the report function
for line in report():
print(line)
elif choice == "3":
# breaks the loop effectively exiting the program
print("Quitting...")
break
else:
# if the item is not 1, 2, or 3, will print this and go back to beginning of while loop
print(("You replied {}, please reply with 1, 2 or 3").format(answer))
def thank_you():
donor_input = input("Enter full name of donor else type 'list' to see donor list: ")
if donor_input == 'list':
for donor in donors:
print(donor)
else:
# Search if repeat donor
exists = False
for donor in donors:
if donor[0] == donor_input:
donor_input = donor[0]
exists = True
if exists:
pass
else:
donors.append((donor_input, []))
# Add new donation
donation = int(input("Enter donation amount: "))
for donor in donors:
if donor[0] == donor_input:
donor[1].append(donation)
print("Esteemed Donors", '\n', '------------')
for donor in donors:
print(donor)
print (f"Thank you {donor_input} for your generous donation of ${donation} from a charity")
def report():
"""
return a report by adding a line for every name in the donor dictionary
"""
report_list = ["Donor Name" + " " * 10 + "| Total Given " + "| Num Gifts " + "| Average Gift\n" + "-" * 60]
for donor in donors:
stats = []
donations = donors[1]
total = sum(donations)
num = len(donations)
stats.append((donor[0], total, num. total / num))
print(stats)
return donations
if __name__ == "__main__":
print("Welcome to the Mailroom!")
main_menu() |
04817964cab3a318856299d0422111afe7d53a2c | Darssh/Codewars | /Python-Solutions/first_non_repeating_character.py | 833 | 4.25 | 4 | """
Write a function named firstNonRepeatingCharacter that takes a string input,
and returns the first character that is not repeated anywhere in the string.
For example, if given the input 'stress', the function should return 't',
since the letter t only occurs once in the string, and occurs first in the string.
As an added challenge, upper- and lowercase letters are considered the same character,
but the function should return the correct case for the initial letter.
For example, the input 'sTreSS' should return 'T'.
If a string contains all repeating characters, it should return the empty string ("").
"""
def first_non_repeating_letter(str):
s = str.lower()
for a in s:
if s.count(a) == 1:
return str[s.index(a)]
else:
return ''
print firstNonRepeatingCharacter('stress') |
fc78c8787652766fe6aedad0f9c14214b3865397 | atyndall/cits4211 | /tools/helper.py | 1,143 | 3.703125 | 4 | import collections
UNICODE = True # Unicode support is present in system
# The print_multi_board function prints out a representation of the [0..inf]
# 2D-array as a set of HEIGHT*WIDTH capital letters (or # if nothing is there).
def print_multi_board(a):
for row in a:
print(''.join(['#' if e == 0 else chr(64 + e) for e in row]))
# The print_board function prints out a representation of the [True, False]
# 2D-array as a set of HEIGHT*WIDTH empty and filled Unicode squares (or ASCII if there is no support).
def print_board(a):
global UNICODE
for row in a:
if UNICODE:
try:
print(''.join([unichr(9632) if e else unichr(9633) for e in row]))
continue
except UnicodeEncodeError: # Windows compatibility
UNICODE = False
print(''.join(['#' if e else '0' for e in row]))
# The rall function recursively checks that all lists and sublists of element "a"
# have a True value, otherwise it returns False.
def rall(a):
for i in a:
if isinstance(i, collections.Iterable):
if not rall(i):
return False
elif not i:
return False
return True |
907355b5dd8f493e23dbb249fab31856e78ddf8e | aanchal-jain/ProjectEuler | /euler_12.py | 222 | 3.53125 | 4 | def countDivisors(n):
res=[1,n]
for i in range(2,n//2+1):
if(n%i==0):
res.append(i)
return(len(res))
countDivisors(28)
x = 55
y = 11
while(countDivisors(x)<=500):
x+=y
y+=1
print(x)
|
aa78c514be6b7101575c85689c11b5e13d1cc1c1 | TrellixVulnTeam/pythonProgramming_YW7W | /Chapter10/quiz_4_19.py | 1,542 | 3.8125 | 4 | class Student(object):
def __init__(self, s_name):
self.name = s_name
self.totalQuizScore = 0
self.quizScoreList = []
self.numQuizes = 0
self.classes = []
self.grades = []
self.totalgpa = 0
def getName(self):
return self.name
def getNumQuizes(self):
return self.numQuizes
def addQuiz(self, quizscore):
self.quizScoreList.append(quizscore)
self.totalQuizScore += quizscore
self.numQuizes += 1
def getTotalScore(self):
return self.totalQuizScore
def getAverage(self):
return self.totalQuizScore // self.numQuizes
def addClassAndGPA(self, className, classGrade):
self.classes.append(className)
self.grades.append(classGrade)
def averageGPA(self):
gpa_dict = {"A+": 4.33, "A": 4.00, "A-": 3.67, "B+": 3.33, "B": 3.00, "B-": 2.67, "C+": 2.33,
"C": 2.00, "C-": 1.67, "D+": 1.33, "D": 1.00, "D-": .67, "F": 0.00}
gpa_keys = gpa_dict.keys()
for i in range(len(self.grades)):
one_grade = self.grades[i]
gpa = gpa_dict[one_grade]
self.totalgpa += gpa
return self.totalgpa // len(self.grades)
def testStudent():
Tyler = Student("Tyler")
Tyler.addQuiz(85)
Tyler.addQuiz(72)
Tyler.addQuiz(94)
Tyler.addQuiz(50)
Tyler.addQuiz(68)
print(Tyler.getName())
print(Tyler.getAverage())
print(Tyler.getNumQuizes())
print(Tyler.getTotalScore())
testStudent()
|
4fb3dbc508059d9074042cc185e0512da11aa3c5 | CMetzkes/exercise | /scripts/python_ersteschritte.py | 998 | 3.5625 | 4 | 1
type(1)
1.
type(1.)
1+1.
x = 1.
x
x == 1.
x < 1.
x + 1.
x += 1. # X wird verändert, Ergebnis x=2
x
# Funktionen definieren
def addiere(x, y):
return x+y # einrücken
addiere
addiere(1.,1.)
addiere('a','b')
addiere(1. ,'b')# Fehlermeldung: Lösung: str(1.)
# Klassen: beschreiben, welche Attribute und Methoden Objekte (==Instanzen) der Klasse haben
# Definition der Klasse Zahl1 mit Methoden
# 'self' bezieht sich immer auf die aktuelle Instanz der Klasse
# _init_-Methode dient dem Initialisieren einer automatisch erzeugten Klasse
class Zahl1(object):
def __init__(self, wert): # Methode 'init' weist das Attribut wert zu
self.wert = wert
def addiere(self, wert): # Definition einer Methode 'addiere'
self.wert += wert # addiere bewirkt, dass zu dem wert nochmals der wert addiert wird
Zahl1
x = Zahl1(1.)# erstellt Instanz x der Klasse Zahl1
x
type(x)
x.wert
x.addiere(1.)
x.wert
class Zahl2(Zahl1):
def subtrahiere(self, wert):
self.wert -= wert
|
9999e25883b00195d522aecef1b9dd3e835547c7 | nicohervith/Python | /Test_Funciones.py | 542 | 3.765625 | 4 |
def input_con_confirmacion(pregunta):
confirmacion = False
dato_usuario = ""
while not confirmacion:
dato_usuario = input(pregunta)
seguro = input("Dijiste {}, ¿Estás seguro? [ si / no ]".format(dato_usuario))
if seguro == "si":
confirmacion = True
return dato_usuario
nombre = input_con_confirmacion("¿Cómo te llamás?")
print("Confirmaste que te llamás {}".format(nombre))
numero = input_con_confirmacion("Dime un número")
print("Confirmaste que el numero es {}".format(numero)) |
a366043bb5e6902c35d10a0d2a4c4f20f7c00e59 | kuba332211/gitrepo | /gitrepo/python/potega.py | 700 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# potega.py
# obliczanie potęgi podstawy podniesionej do wykładnika
def potega_it(a, n):
wynik = 1
for i in range(n):
wynik = wynik * a
#print(wynik)
return wynik
def main(args):
#a =int(input("Podaj podstawę: "))
#n =int(input("wykładnik: "))
#print("Potęga {} do {} wynosi {}".format(a,n, potega_it(a, n)))
assert(potega_it(1,1) == 1)
assert(potega_it(2,1) == 2)
assert(potega_it(2,2) == 4)
assert(potega_it(0,4) == 0)
assert(potega_it(1,0) == 1)
assert(potega_it(4,0) == 1)
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
|
7b367a7c664a0da65d56656d613253b6e2483f90 | licaoyuan123/HackerRank | /MaxArraySum.py | 1,190 | 3.84375 | 4 | '''
To address with DP, work through the array, keeping track of the max at each position until you get to the last value of the array. You should start with the base cases defined before iterating through the remainder of the array.
max @ position 0: value @ 0
max @ position 1: either:
value @ 0
value @ 1
from that point forward, the max of the next position is either:
the current value at that position
the max value found so far
the max value from 2 positions back plus the current value
keep track of the max at each position until you get to the last position of the array
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maxSubsetSum function below.
def maxSubsetSum(arr):
if len(arr)<3:
return max(arr)
result = [arr[0], max(arr[0], arr[1])]
for i in range(2, len(arr)):
result.append(max(arr[i], max(result[i-1], result[i-2]+arr[i])))
#pass
return result[-1]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = list(map(int, input().rstrip().split()))
res = maxSubsetSum(arr)
fptr.write(str(res) + '\n')
fptr.close()
|
0355384daee309ee35b9450eebc69ba185803b99 | MaximeMoutet13/Stage_2020 | /tbs/graph/_graph.py | 5,304 | 3.5 | 4 | import json
from ._mixed_graph import MixedGraph, UNDIRECTED_EDGE
class Graph(MixedGraph):
"""Generic undirected Graph class."""
def __init__(self, vertices=tuple(), edges=tuple()):
"""An undirected graph.
Args:
vertices (iterable): each vertex must be *hashable*.
edges(iterable): list of pair (x, y) where *x* and *y* are vertices. Edges whose one end is not
a vertex are discarded.
"""
super().__init__(vertices, undirected_edges=edges)
@classmethod
def from_graph(cls, graph, vertices=None):
"""Create graph from another graph.
Args:
graph(MixedGraph): a graph
vertices(iterable): a subset of vertices. If not set, the whole set of vertices is considered.
If the graph is directed or mixed, only take the undirected edges.
Returns(Graph): A new graph.
"""
undirected, directed = graph._edges
if vertices is None:
vertices = graph.vertices
return cls(vertices, undirected)
@classmethod
def from_json(cls, json_graph, id_to_vertex_conversion=json.loads):
"""jsgongraph to mixed-graph
Args:
json_graph(dict): https://github.com/jsongraph format.
id_to_vertex_conversion(str->object): each id is converterted into a vertex = id_to_vertex_conversion(id).
By defaults, node ids are json.loads() to produce vertices. Thus if the node id is "1"
the associated vertex s the int 1.
Returns(Graph): the graph associated with the json
"""
vertices, undirected, directed = cls._graph_parts_from_json(json_graph, id_to_vertex_conversion)
return cls(vertices, undirected)
@classmethod
def from_neighborhoods(cls, neighbors):
"""Create graph from a neighborhood.
Args:
neighbors(dict): keys are vertices and values iterable of neighbors.
Returns(Graph):
A new graph
"""
return cls().update([(x, y) for x in neighbors for y in neighbors[x]])
@classmethod
def from_edges(cls, edges):
"""Create graph from a set of edges.
Args:
edges(iterable): iterable of edges.
Returns(Graph):
A new graph
"""
return cls().update(edges)
@classmethod
def from_dissimilarity(cls, dissimilarity, threshold=None):
"""Threshold graph of *dissimilarity* at height *threshold*.
:param dissimilarity: to be converted in graph.
:type dissimilarity: :class:`diss.Diss`
:param threshold: If :const:`None`, the maximal value of *dissimilarity* is used.
:type threshold: must be `comparable` with *dissimilarity*'s values
:return: a graph with vertex set equal to the elements of *dissimilarity* and *xy*
is an edge iff *dissimilarity*\ (x, y) <= *threshold*.
:rtype: :class:`Graph`
"""
elems = list(dissimilarity)
self = cls(elems)
for i, x in enumerate(elems):
for y in elems[i+1:]:
if threshold is None or dissimilarity(x, y) <= threshold:
self.update([(x, y)])
self[x, y] = dissimilarity(x, y)
return self
def __repr__(self):
undirected, directed = self._edges
return "".join(["Graph(",
repr(self.vertices),
", ", repr(undirected),
")"])
def update(self, edges, node_creation=True):
"""Add edges.
Each edge in *edges* is added if not already present.
If an edge is already present but not of the same type (undirected or directed), the edge is replaced.
Args:
edges(iterable): Each edge is a pair `(x, y)` where *x* != *y* are vertices (in *vertices* or not).
node_creation(bool): If :const:`False`, edges using vertices not in the graph are discarded. If
:const:`True`, missing vertices are added in the graph.
Raises:
ValueError: if kind is unknown.
Returns:
self (for possible chaining).
"""
return super().update(UNDIRECTED_EDGE, edges, node_creation=node_creation)
@property
def edges(self):
"""All (directed) edges.
returns(frozenset):
A :class:`frozenset` of of 2-element tuples (the directed edges).
"""
return self._edges[0]
def __call__(self, x, closed=False):
"""Neighborhood of vertex x.
Args:
x: a vertex.
closed(bool): if true adds *x* in the returns (closed neighborhood).
Raises:
ValueError: if *x* is not a vertex.
Returns(frozenset):
the neighbors of *x* according to the boolean specifications.
"""
return super().__call__(x, undirected=True, closed=closed)
def isa_edge(self, x, y):
"""test if (x, y) is an edge.
Args:
x: a vertex.
y: a vertex.
Returns(bool):
By default, returns True if (x, y) is an edge, False otherwise.
"""
return super().isa_edge(x, y, UNDIRECTED_EDGE)
|
a1ca6b3f1d873b015d392ea8e699d1ceaef23c40 | pranavgokhale95/alpha_full | /A4/final.py | 1,736 | 3.5625 | 4 | '''
This code works!
I have no idea what is expected in assignment
it writes current state of philosopher and time to mongodb
you should have mongodb server running
follows similar solution : https://www.youtube.com/watch?v=_ruovgwXyYs
'''
import threading
import time
from pymongo import MongoClient
class Philosopher(threading.Thread):
running = True;
connection = MongoClient("localhost",27017);
arr=[0,0,0,0,0];
def __init__(self, i, xname, forkOnLeft, forkOnRight):
threading.Thread.__init__(self);
self.name = xname;
self.index=i;
self.forkOnLeft = forkOnLeft;
self.forkOnRight = forkOnRight;
Philosopher.connection.test.dini.drop();
@staticmethod
def sendToMongo(index, state ):
collection = Philosopher.connection.test.dini;
doc = { "philo": index, "state":state, "time":time.ctime() };
collection.insert_one(doc);
def run(self):
while(self.running):
print("Philosopher " + str(self.name) + " is thinking.\n");
time.sleep(5);
self.forkOnLeft.acquire();
self.forkOnRight.acquire();
print("Philosopher " + str(self.name) + " is eating.\n");
Philosopher.arr[self.index]=1;
Philosopher.sendToMongo(self.index,Philosopher.arr);
time.sleep(5);
Philosopher.arr[self.index]=0;
self.forkOnLeft.release();
self.forkOnRight.release();
def DiningPhilosophers():
forks = [];
for i in range(5):
forks.append(threading.Lock());
#print forks
ps = [];
for i in range(5):
ps.append(Philosopher(i,"Philosopher No. " + str(i), forks[min(i,(i+1)%5)] , forks[max(i,(i+1)%5)] ));
print ps
for p in ps:
p.start();
time.sleep(60);
Philosopher.running = False;
DiningPhilosophers()
|
b0adea411997f2032147b728ccccdf68770b141a | SylphDev/Actividades_Algoritmos | /prepas_ejercicios/2_semana/prepa2.2.py | 1,233 | 3.9375 | 4 | #Ejercicio 2.2: Diseña un programa que determine si un número o palabra ingresados por teclado, son palíndromos o no.
class Word:
def __init__(self):
self.word = ''
def get_input(self):
'''
Obtiene del usuario una palabra o secuencia de numeros
y verifica si es valido
'''
valid = False
while valid is False:
try:
word = input("Escribe una palabra o secuencia de numeros: ")
letter_check = word.isalpha()
number_check = word.isnumeric()
if letter_check is True or number_check is True:
self.word = word
valid = True
except ValueError:
print("Por favor, ingresa una palabra en letras o un numero")
def check_palindrome(self):
'''
Revisa si el input es o no un palindromo
'''
self.get_input()
palindrome = self.word[::-1]
if self.word.lower() == palindrome.lower():
print("El palindromo de", self.word.lower(), "es", palindrome.lower())
else:
print(self.word, "no es un palindromo.")
prueba = Word().check_palindrome()
|
f6ab372bf0cad0f433798a838529de4622c7221b | PiyushChaturvedii/My-Leetcode-Solutions-Python- | /Leetcode 2/Intersection of Two Linked Lists.py | 1,294 | 3.671875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA or not headB:
return None
if headA==headB:
return headA
p=headA
m=1
while p.next:
p=p.next
m+=1
p=headB
n=1
while p.next:
p=p.next
n+=1
p=headA
q=headB
if m>n:
while m>n:
m-=1
p=p.next
elif m<n:
while n>m:
n-=1
q=q.next
while p.next and p!=q:
p=p.next
q=q.next
if p!=q:
return None
return p
headA=ListNode(3)
#headA.next=ListNode(2)
#headA.next.next=ListNode(3)
#headA.next.next.next=ListNode(4)
headB=ListNode(2)
headB.next=headA
#headB.next=ListNode(5)
#headB.next.next=headA.next.next
c=Solution().getIntersectionNode(headA,headB)
|
fb11af4abd0a65bf50bc4712a2f5f265b9663aa5 | EldanGS/patterns | /src/creational_patterns/singleton/singleton_metaclass.py | 943 | 4.15625 | 4 | """ Intent:
Singleton is a creational design pattern that lets you ensure that a class has
only one instance, while providing a global access point to this instance.
"""
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
def __init__(self, my_str: str):
self.my_str = my_str
def some_business_logic(self):
"""There is should be some logic of singleton"""
pass
if __name__ == "__main__":
s1 = Singleton("s1 str")
s2 = Singleton("s2 str")
assert id(s1) == id(s2), "The instances not the same"
print(s1.__dict__) # {'my_str': 's1 str'}
print(s2.__dict__) # {'my_str': 's1 str'}
# The instances the same, because of singleton.
|
fa80d16432ff770487ed942e410e1567e0065bbd | SandeepKumarShaw/python_tutorial | /new folder/nested_if_else.py | 291 | 3.984375 | 4 | winning_number = 4
user = int(input("enter any number between 1 and 10 :-"))
if user == winning_number:
print("you selected a right number")
else:
if user > winning_number:
print("you enter number is too heigh")
else:
print("you enter number is too low")
|
b9f83171f60dd37c145e705eb3f77156a6178538 | kazice/Python-Algorithm | /SortAlgorithm/orientBubbleSort.py | 665 | 3.890625 | 4 | #!/usr/bin/python
# -*- coding:utf8 -*-
# 定向冒泡排序,又叫鸡尾酒排序
# 此算法与冒泡排序的不同处在于从低到高然后从高到低
def orientBubbleSort(num):
length = len(num)
left, right = 0, length-1
while left < right:
i = left
while i < right:
if num[i] > num[i+1]:
num[i],num[i+1] = num[i+1],num[i]
i += 1
right -= 1
j = right
while j > left:
if num[j-1] > num[j]:
num[j-1],num[j] = num[j],num[j-1]
j -= 1
left += 1
print num
return num
orientBubbleSort([6, 5, 3, 1, 8, 7, 2, 4 ]) |
b4a3618f3b9a6cb852c496b19735b62194e71456 | shankarapailoor/Project-Euler | /Project Euler/p10-20/p13.py | 1,018 | 3.6875 | 4 | from copy import deepcopy
def findCollatzSequence(x):
y = deepcopy(x)
collatzsequence = [y]
if x == 1:
return 1
while x > 1:
if x % 2 == 0:
x = x/2
t = 0
t = deepcopy(x)
collatzsequence.append(t)
else:
x = 3*x + 1
z = 0
z = deepcopy(x)
collatzsequence.append(z)
return len(collatzsequence)
def getNext(x):
if x % 2 == 0:
return x/2
else:
return 3*x + 1
def getLength1000():
collatzsequence = {}
for i in range(0, 10001):
collatzsequence[i] = findCollatzSequence(i)
return collatzsequence
def longestCollatzChain():
dicts = getLength1000()
longestnum = 0
maxlength = 0
i = 1001
for i in range(1001, 1000000):
chainlength = 1
j = deepcopy(i)
while j > 1:
if getNext(i) in dicts:
chainlength += dicts[getNext(i)]
j = 1
else:
j = getNext(j)
chainlength += 1
if chainlength > maxlength:
longestnum = deepcopy(i)
maxlength = deepcopy(chainlength)
return longestnum
if __name__=='__main__':
print findCollatzSequence(837799)
|
b6c51a8ba737f755b4e0facdba897a4b14efdbb7 | JATP98/Listas-de-python-recuperacion | /eje3.py | 719 | 4.09375 | 4 | # Dada una lista de números enteros
# (guarda la lista en una variable) y un entero k,
# escribir un programa que:
#Cree tres listas listas, una con los menores, otra con los
#mayores y otra con los iguales a k.
#Crea otra lista lista con aquellos que son múltiplos de k.
listaenteros=[1,2,3,4,5,6,4,6,4,7,8,9,4]
numerok=int(input("Introduce un numero para comprobar: "))
listamenores=[]
listamayores=[]
listaigual=[]
for numeris in listaenteros:
if numeris <numerok :
listamenores.append(numeris)
elif numeris >numerok :
listamayores.append(numeris)
else:
listaigual.append(numeris)
print("numeros iguales: ", listaigual)
print("numeros menores: ", listamenores)
print("numeros mayores: ", listamayores)
|
d05e38034338f47dc92e24394c3c5f43f5ef364c | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/grains/1295ac1334f8416a949638880bbf7117.py | 201 | 3.59375 | 4 | __author__ = 'tracyrohlin'
def on_square(n):
return 2 ** (n-1)
def total_after(num):
if num == 1:
return on_square(num)
else:
return on_square(num) + total_after(num - 1)
|
467409fb46e5d80265b787e211c8c6306fae7eb9 | Anil314/HackerEarth-Solutions | /Implementation/Roy's Life Cycle.py | 2,415 | 3.515625 | 4 | '''
Roy is going through the dark times of his life. Recently his girl friend broke up with him and to overcome
the pain of acute misery he decided to restrict himself to Eat-Sleep-Code life cycle. For N days he did
nothing but eat, sleep and code.
A close friend of Roy kept an eye on him for last N days. For every single minute of the day, he kept
track of Roy's actions and prepared a log file.
The log file contains exactly N lines, each line contains a string of length 1440 ( i.e. number of minutes in 24 hours of the day).
The string is made of characters E, S, and C only; representing Eat, Sleep and Code respectively. ith
character of the string represents what Roy was doing during ith minute of the day.
Roy's friend is now interested in finding out the maximum of longest coding streak of the day - X.
He also wants to find the longest coding streak of N days - Y.
Coding streak means number of C's without any E or S in between.
See sample test case for clarification.
Input:
First line of each file contains N - number of days.
Following N lines contains a string of exactly 1440 length representing his activity on that day.
Output:
Print X and Y separated by a space in a single line.
Constraints:
1 ≤ N ≤ 365
String consists of characters E, S, and C only.
String length is exactly 1440.
Note: The sample test case does not follow the given constraints on string length to avoid large data.
It is meant only for explanation. We assure you that the hidden test files strictly follow the constraints.
SAMPLE INPUT
4
SSSSEEEECCCCEECCCC
CCCCCSSSSEEECCCCSS
SSSSSEEESSCCCCCCCS
EESSSSCCCCCCSSEEEE
SAMPLE OUTPUT
7 9
Explanation
Longest coding streak for each day is as follows:
Day 1: 4
Day 2: 5
Day 3: 7
Day 4: 6
Maximum of these is 7, hence X is 7.
Now in order to find longest coding streak of the all days, we should also check if Roy continued his coding from previous days.
As in the sample test case, Roy was coding for 4 minutes at the end of Day 1 and he continued to code
till 5 more minutes on Day 2. Hence the longest coding streak is 4+5 equals 9. There is no any other
coding streak larger than this. So the longest coding streak of all days is 9.
'''
import re
t= int(input())
l = []
for _ in range(t):
l.append(input())
st = "".join(l)
m = [max(len(s) for s in re.findall(r'C+', x )) for x in l]
x = max(len(s) for s in re.findall(r'C+', st))
print(max(m), x)
|
cbf863520fb8d36ff7eff85b90e0a06f33aec135 | gabrielwallaceBDS/faculdade- | /aula 2 pratica/expressaoAlgebrica.py | 521 | 4.0625 | 4 | """
ESCREVA AS SEGUINTES EXPRESSOES ALGEBRICAS EM LINGUAGEM PYTHON
A)O SOMATORIO DOS 5 PRIMEIROS NUMEROS INTEIROS E POSITIVOS
B) A MEDIA ENTRE 23, 19 E 31
C) O NUMERO DE VEZES QUE 73 CABE EM 403
D) A SOBRA QUANDO 403 É DIVIDIDO POR 73
E) 2 ELEVADO Á DECIMA POTENCIA
F)O VALOR ABSOLUTO DA DIFERENCA ENTRE 54 E 57
G)O MENOR VALOR ENTRE 34, 29 E 31
"""
#A
print(1 + 2 + 3 + 4 + 5)
#B
print ((23 + 19 + 31) //3)
#C
print (403 // 73)
#D
print (403 % 73)
#E
print(2**10)
#F
print(abs(54 - 57))
#G
print(min(34, 29, 31))
|
547af9fb67c9b8719c060dca0d2623911c3819a9 | 1Aanshu/Python01 | /corepython01/my_libs/MyFunctions.py | 494 | 3.84375 | 4 | def f1():
print("Hello from f1 function")
print("My name is Aanshu Dwiwedi")
print("Ktm")
print("Bye")
"""
def f2(num1):
print("Aanshu Sum")
print(num1)
"""
def f3(num1, num2):
num3 = num1 + num2
print("Num1 : ", num1)
print("Num2 : ", num2)
print("Sum :", num3)
def f4():
tmp = int(input("Enter any number : "))
return tmp
def f5():
n1 = 10
n2 = 12
n3 = n1 + n2
return n3
def f6(num1, num2):
num3 = num1 + num2
return num3
|
a579702348c911173956c23180da8dbd5183f34d | Gigio212/Tarea-04 | /Software.py | 1,702 | 4.03125 | 4 | #Encoding: UTF-8
#Autor: Rodrigo Rivera Salinas
#Descripcion: Dependiendo el numero de paquetes que se compro, se aplicara un descuento dependiendo del numero de paquetes y se imprimira el costo total
def descuentoEnPaquetes(paq,precio):
if paq <= 0:
return("Error, ingresar numero de paquetes validos")
elif paq <= 9 and paq >= 1: #si el numero de paquetes es entre 9 y 1 no se aplica el descuento
desc = 1
total = (paq * precio) * desc
desc = 0
return (total)
elif paq <= 19 and paq >= 10: #si el numero de paquetes es entre 19 y 10 se aplica un descuento del 20%
desc = .80
total = (paq*precio)*desc
return(total)
elif paq <= 49 and paq >= 20: #si el numero de paquetes es entre 49 y 20 se aplica un descuento del 30%
desc = .70
total = (paq*precio)*desc
return(total)
elif paq <= 99 and paq >= 50: #si el numero de paquetes es entre 99 y 50 se aplica un descuento del 40%
desc = .60
total = (paq*precio)*desc
return(total)
else:
desc = .50 #si el numero de paquetes es de 100 o mas se aplica un descuento del 50%
total = (paq * precio) * desc
return (total)
def main():
paq = int(input("Ingrese el numero de paquetes a comprar: ")) #pedir numero de pauetes
precio = 1500.00 #precio por paquete
total = descuentoEnPaquetes(paq, precio) #Total de los paquetes
print("numero de paquetes comprados: ", paq) #Imprimir numero de paquetes
print("El descuento es de: $", (precio * paq) - total) #Imprimir el descuento
print("El total menos el descuento es : $", total) #Imprimir el total con descuento
main() |
8224c2897f460d444e8e6dfc22bae47d8e034d17 | zhangzhenyu13/AudioSegmentation | /AudioSubtitleSegmentation/TextNormailzation/normalize_transcription.py | 7,128 | 3.515625 | 4 | import requests
import time
import random
import string
import json
import unicodedata
import regex as re
def _is_whitespace(char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally considered as such.
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
cat = unicodedata.category(char)
if cat == "Zs":
return True
return False
def _is_control(char):
"""Checks whether `chars` is a control character."""
# These are technically control characters but we count them as whitespace
# characters.
if char == "\t" or char == "\n" or char == "\r":
return False
cat = unicodedata.category(char)
if cat.startswith("C"):
return True
return False
def _is_punctuation(char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, for
# consistency.
if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
(cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
return True
cat = unicodedata.category(char)
if cat.startswith("P"):
return True
return False
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens
class BasicTokenizer(object):
def tokenize(self, text):
"""Tokenizes a piece of text."""
text = self._clean_text(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
split_tokens.extend(self._run_split_on_punc(token))
output_tokens = whitespace_tokenize(" ".join(split_tokens))
return output_tokens
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
return "".join(output)
def _run_split_on_punc(self, text):
"""Splits punctuation on a piece of text."""
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return ["".join(x) for x in output]
def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp == 0 or cp == 0xfffd or _is_control(char):
continue
if _is_whitespace(char):
output.append(" ")
else:
output.append(char)
return "".join(output)
class TextNormalizer(object):
__retry_service=5
__TN_type={1:"None", 2:"WfstInverseTextNormalization", 3:"ImplicitPunctuation", 4:"ImplicitPunctuation"}
__tokenizer=BasicTokenizer()
@staticmethod
def itn_response(hyp):
'''
network restAPI service
:param hyp: input raw transcript
:return: normalized text
'''
rawhyp = hyp
url = "http://speech.platform.bing-int.com/internal/dpp/speech/processtext/officedictate/nbest/v1"
payload = "{\r\n\t\"Features\": [{\r\n\t\t\"type\": \"InverseTextNormalization\"\r\n\t}, {\r\n\t\t\"type\": \"Capitalization\"\r\n\t}, {\r\n\t\t\"type\": \"Reformulation\"\r\n\t}, {\r\n\t\t\"type\": \"ImplicitPunctuation\"\r\n\t}, {\r\n\t\t\"type\": \"ExplicitPunctuation\"\r\n\t}, {\r\n\t\t\"type\": \"ProfanityMasking\"\r\n\t}],\r\n\t\"Context\": {\r\n\t\t\"locale\": \"en-us\",\r\n\t\t\"nBest\": [{\r\n\t\t\t\"Text\": \"" + rawhyp + "\"\r\n\t\t}],\r\n\t\t\"positionContext\": {\r\n\t\t\t\"left\": \"\",\r\n\t\t\t\"right\": \"\"\r\n\t\t}\r\n\t}\r\n}"
headers = {
'Content-Type': "application/json",
'Accept': "*/*",
'Cache-Control': "no-cache",
'Host': "speech.platform.bing-int.com",
'accept-encoding': "gzip, deflate",
'content-length': "401",
'Connection': "keep-alive",
'cache-control': "no-cache"
}
response = requests.request("POST", url, data=payload, headers=headers)
return response
@staticmethod
def itn(hyp):
succeeded = False
num_retries = 0
while not succeeded and num_retries<TextNormalizer.__retry_service:
try:
num_retries+=1
response = TextNormalizer.itn_response(hyp)
if response.status_code!=200:
print("response status error:", response)
time.sleep(random.randint(5, 15))
continue
#print(response)
#print(response.text)
response=json.loads(response.text)
#print("stages",response["stages"])
TN=response["stages"][-1]["nBest"][0]["text"]
return {"success":True, "TN":TN}
except:
return {"success":False, "TN":""}
@staticmethod
def remove_punct(text):
return " ".join(
filter( lambda c: len(c)>1 or not _is_punctuation(c), TextNormalizer.__tokenizer.tokenize(text) )
)
@staticmethod
def remove_vivid(text):
return re.sub(r"\[(.*?)\]", "", text)
@staticmethod
def remove_person(text):
words=text.split()
n=4
ngrams = [(s, e + 1)
for s in range(len(words))
for e in range(s, min(s + n, len(words)))
if not words[s:e + 1][-1]==':' ]
return re.sub(r"\s+.*?:\s+", " ", text)
pass
@staticmethod
def normalize_vtt(transcript):
transcript = transcript.replace('\n', ' ')
transcript = transcript.replace(u'\u2013', '-')
transcript = transcript.replace(u'\u2018', '"')
transcript = transcript.replace(u'\u2019', '"')
transcript = transcript.replace(u'\u201c', '\'')
transcript = transcript.replace(u'\u201d', '\'')
transcript = transcript.replace(u'\u2026', '...')
transcript = transcript.replace(u'"', '\'')
transcript = TextNormalizer.itn(transcript)
return transcript
@staticmethod
def endSent(line):
if line:
if line[-1] in ('?','.', '!'):
return True
return False |
926e88c0edd8d8d3a29f528fba82efc0fd1c838e | jambellops/redxpo | /mitx6.00/creditcode.py | 2,643 | 4.28125 | 4 | ##
## Title: Credit statement
## Author: James Bellagio
## Description: Calculation of Credit Statement assignment for edx mit 6.00 week 2
##
##
##
##
##
##
# def balance_unpaid(balance, payment):
# """ function of remaining balance after payment
# parameter: balance = initial balance
# parameter: payment = payment
# return: balance leftover after payment (can be negative)"""
# return balance - payment
# def bal_w_interest(unpaid_balance, mo_interest):
# """ function of balance after interest is applied
# parameter: unpaid_balance = balance left after last payment (can be negative)
# parameter: mo_interest = monthly percentage rate as a decimal
# return: new balance after adding interest accrued (will not accrue interest if negative)"""
# if (unpaid_balance < 0):
# return 0
# else:
# return unpaid_balance + (mo_interest * unpaid_balance)
# monthlyPaymentRate
# annualInterestRate
# balance
def interest_mo(annualInterestRate):
""" function to convert Annual percentage rate to monthly interest
parameter: interest as a decimal
return: interest rate for one month"""
return interest/12.0
def minimo_payment(minim_rate, last_balance):
""" function to determine minimum monthly payment
parameter: minim_rate = decimal value of payment rate. equivalent to percentage balance paid
parameter: last_balance = balance after last payment
return: minimum amount to pay (should never go negative; if last_balance is negative
return zero"""
if (last_balance < 0):
return 0
else:
return minim_rate * last_balance
def mon_unpaid_bal(last_balance, payment):
""" function to determine upaid portion of balance
paremeter: last_balance = balance after last payment
parameter: payment = current payment
return: unpaid balance after payment is applied"""
return last_balance - payment
def unpaid_w_interest(unpaid, interest):
"""function to determine balance after interest is applied
parameter: unpaid = balance after payment is applied
parameter: interest = monthly interest as a decimal
return: new balance with interest"""
return unpaid + unpaid*interest
monInterest = interest_mo(annualInterestRate)
print('balance = '+str(balance))
print('annualInterestRate = '+str(annualInterestRate))
print('monthlyPaymentRate = '+str(monthlyPaymentRate))
for i in range(12):
pay = minimo_payment(monthlyPaymentRate, balance)
print(pay)
newbalance = unpaid_w_interest(mon_unpaid_bal(balance, pay), monInterest)
print(newbalance)
balance = newbalance
|
03a636be3d6264eebd6ba7a29d1b26fb98c3485e | shvekh/Laborator | /Laboratorn 2/Lab2.1(мой).py | 281 | 3.953125 | 4 | my_number=int(input("Задаем число = "))
user_number=int(input('Введите число: '))
while user_number!=my_number:
print("Не совпадает")
user_number=int(input('Введите число повторно: '))
print('Совпадает')
|
c45dd95cb6317c8dcf3724495ad5a1b0f1c59f6d | delete00man/password-generator | /password_generator.py | 7,995 | 3.84375 | 4 | from tkinter import *
from tkinter import Tk
import string
from random import randint,choice
from time import sleep
passwordlogin = ""
usernamelogin = ""
password = ""
def login():
login_infos = open("login.txt", "r")
login_infos = login_infos.read()
list_login_infos = login_infos.split(",")
usernamelogin = username_entry.get()
passwordlogin = password_entry.get()
if usernamelogin == list_login_infos[0] and passwordlogin == list_login_infos[1]:
print_generator_page()
def print_password():
Generator_page.pack_forget()
Password_page.pack(expand=YES)
def sign_in():
user = sign_in_username_entry.get()
password_verify = sign_in_password_entry.get()
if len(user) and len(password_verify) > 0:
with open("login.txt", "w") as login:
login.write(sign_in_username_entry.get())
login.write(",")
login.write(sign_in_password_entry.get())
login.close()
print_generator_page()
else:
sleep(1)
def save_password():
with open("password_list1.txt", "a+") as password_list:
password_list.write("Name Password: ")
password_list.write(name_password_entry.get())
password_list.write(" | Password: ")
password_list.write(password_entry1.get())
password_list.write("\n")
def generate():
password_min = 6
password_max = 15
all_chars = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(all_chars) for x in range(randint(password_min, password_max)))
password_entry1.delete(0, END) # supprime les éventuels caractères dans l'entrée.
password_entry1.insert(0, password) # injecte le password dans l'entrée.
def print_inscription_page():
Accueil_page.pack_forget()
Inscription_page.pack(expand=YES)
def print_generator_page():
Connexion_page.pack_forget()
Inscription_page.pack_forget()
Password_page.pack_forget()
Generator_page.pack(expand=YES)
def print_connexion_page():
Accueil_page.pack_forget()
Connexion_page.pack(expand=YES)
def print_accueil_page():
Connexion_page.pack_forget()
Inscription_page.pack_forget()
Generator_page.pack_forget()
Accueil_page.pack(expand=YES)
window = Tk()
window.title("Générateur de mot de passe")
window.iconbitmap("Password_Générator.ico")
window.geometry("720x480")
window.config(background="#E4E1CF")
Accueil_page = Frame(window, bg='#E4E1CF')
Connexion_page = Frame(window, bg='#E4E1CF')
Inscription_page = Frame(window, bg='#E4E1CF')
Generator_page = Frame(window, bg='#E4E1CF')
Password_page = Frame(window, bg='#E4E1CF')
#accueil
width = 300
height = 300
image = PhotoImage(file="Password_Generator.png").zoom(16).subsample(35)
canvas = Canvas(Accueil_page, width=width, height=height, bg='#E4E1CF', bd=0, highlightthickness=0)
canvas.create_image(width / 2, height / 2, image=image)
canvas.grid(row=0, column=0, sticky=E)
left_frame = Frame(Accueil_page, bg='#E4E1CF')
sign_up_button = Button(left_frame, text="S'inscrire", font=("Arial", 20,), bg="white", command=print_inscription_page)
sign_up_button.pack()
login_button = Button(left_frame, text="Se connecter", font=("Arial", 20,), bg="white", command=print_connexion_page)
login_button.pack()
left_frame.grid(row=0, column=1, sticky=W)
Accueil_page.pack(expand=YES)
#connexion
width = 300
height = 300
image1 = PhotoImage(file="Password_Generator1.png").zoom(16).subsample(35)
canvas = Canvas(Connexion_page, width=width, height=height, bg='#E4E1CF', bd=0, highlightthickness=0)
canvas.create_image(width / 2, height / 2, image=image1)
canvas.grid(row=0, column=0, sticky=E)
connexion_left_frame = Frame(Connexion_page, bg='#E4E1CF')
label_username = Label(connexion_left_frame, text="Username:", font=("Arial", 20,), bg="white")
label_username.pack()
username_entry = Entry(connexion_left_frame, font=("Arial", 20,), bg="white")
username_entry.pack()
label_password = Label(connexion_left_frame, text="Mot de passe:", font=("Arial", 20,), bg="white")
label_password.pack()
password_entry = Entry(connexion_left_frame, font=("Arial", 20,), bg="white")
password_entry.pack()
connexion_button = Button(connexion_left_frame, text="Connexion", font=("Arial", 20,), bg="white", command=login)
connexion_button.pack(fill=X)
home_return = Button(connexion_left_frame, text="Retour Accueil", font=("Arial", 20,), bg="white", command=print_accueil_page)
home_return.pack(fill=X)
connexion_left_frame.grid(row=0, column=1, sticky=W)
#inscription
width = 300
height = 300
image2 = PhotoImage(file="Password_Generator2.png").zoom(16).subsample(35)
canvas = Canvas(Inscription_page, width=width, height=height, bg='#E4E1CF', bd=0, highlightthickness=0)
canvas.create_image(width / 2, height / 2, image=image)
canvas.grid(row=0, column=0, sticky=E)
inscription_left_frame = Frame(Inscription_page, bg='#E4E1CF')
label_username = Label(inscription_left_frame, text="Username:", font=("Arial", 20,), bg="white")
label_username.pack()
sign_in_username_entry = Entry(inscription_left_frame, font=("Arial", 20,), bg="white")
sign_in_username_entry.pack()
label_password = Label(inscription_left_frame, text="Mot de passe:", font=("Arial", 20,), bg="white")
label_password.pack()
sign_in_password_entry = Entry(inscription_left_frame, font=("Arial", 20,), bg="white")
sign_in_password_entry.pack()
sign_in_button = Button(inscription_left_frame, text="Connexion", font=("Arial", 20,), bg="white", command=sign_in)
sign_in_button.pack(fill=X)
home_return = Button(inscription_left_frame, text="Retour Accueil", font=("Arial", 20,), bg="white", command=print_accueil_page)
home_return.pack(fill=X)
inscription_left_frame.grid(row=0, column=1, sticky=W)
#Generateur
width = 300
height = 300
image3 = PhotoImage(file="Password_Generator3.png").zoom(16).subsample(35)
canvas = Canvas(Generator_page, width=width, height=height, bg='#E4E1CF', bd=0, highlightthickness=0)
canvas.create_image(width / 2, height / 2, image=image)
canvas.grid(row=0, column=0, sticky=E)
left_frame = Frame(Generator_page, bg='#E4E1CF')
label_name_password = Label(left_frame, text="Nom du Mot de passe:", font=("Arial", 20,), bg="white")
label_name_password.pack()
name_password_entry = Entry(left_frame, font=("Arial", 20,), bg="white")
name_password_entry.pack()
label_password = Label(left_frame, text="Mot de passe:", font=("Arial", 20,), bg="white")
label_password.pack()
password_entry1 = Entry(left_frame, font=("Arial", 20,), bg="white")
password_entry1.pack()
password_button = Button(left_frame, text="Générer", font=("Arial", 20,), bg="white", command=generate)
password_button.pack(fill=X)
save_button = Button(left_frame, text="Save", font=("Arial", 20,), bg="white", command=save_password)
save_button.pack(fill=X)
print_password_button = Button(left_frame, text="Afficher les mots de passes", font=("Arial", 20,), bg="white", command=print_password)
print_password_button.pack(fill=X)
home_return = Button(left_frame, text="Retour Accueil", font=("Arial", 20,), bg="white", command=print_accueil_page)
home_return.pack(fill=X)
left_frame.grid(row=0, column=1, sticky=W)
#password page
width = 300
height = 300
image4 = PhotoImage(file="Password_Generator4.png").zoom(16).subsample(35)
canvas = Canvas(Password_page, width=width, height=height, bg='#E4E1CF', bd=0, highlightthickness=0)
canvas.create_image(width / 2, height / 2, image=image)
canvas.grid(row=0, column=0, sticky=E)
password_left_frame = Frame(Password_page, bg='#E4E1CF')
print_password_list = open("password_list1.txt","r")
print_password_list = print_password_list.read()
generator_return = Button(password_left_frame, text="Retour", font=("Arial", 20,), bg="white", command=print_generator_page)
generator_return.pack()
label_password_list = Label(password_left_frame, text=print_password_list, font=("Arial", 20,), bg="white")
label_password_list.pack(fill=X)
password_left_frame.grid(row=0, column=1, sticky=W)
window.mainloop()
|
bc1d14c731eedf763741e3e61a94ddaa396f81e4 | skinder/Algos | /PythonAlgos/flattenarray.py | 739 | 4.28125 | 4 | '''
Given a nested array of values, write a function to return a flattened array containing only the integer values.
Ex.
Input: [6, 2, [1, [9, 3], [1, 2], [True], 'hello world', [None] ], 2]
Output: [6, 2, 1, 9, 3, 1, 2, 2]
'''
def flatten(arr):
flattened = []
for i in arr:
if type(i) == list:
child_flatten = flatten(i)
for j in child_flatten:
flattened.append(j)
elif type(i) == int:
flattened.append(i)
return flattened
if __name__ == '__main__':
test_input = [6, 2, [1, [9, 3], [1, 2], [True], 'hello world', [None]], 2]
test_result = sorted([6, 2, 1, 9, 3, 1, 2, 2])
result = sorted(flatten(test_input))
print(flatten(test_input)) |
59521c808d11785066664fcc21a6acb918e8e4f4 | Seowyongtao/turtle-crossing | /car_manager.py | 660 | 3.6875 | 4 | from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager(Turtle):
def __init__(self):
super().__init__()
self.moving_distance = STARTING_MOVE_DISTANCE
self.random_color = random.choice(COLORS)
self.color(self.random_color)
self.penup()
self.setheading(180)
self.shape("square")
self.shapesize(stretch_wid=1, stretch_len=2)
self.random_y = random.randint(-240, 240)
self.goto(300, self.random_y)
def move(self):
self.forward(self.moving_distance)
|
81402bd143d7f66d5a1bbd47b9a40c482c6480fe | hvy/pfi-internship2016 | /assignment1.py | 730 | 4.4375 | 4 | def outer(x, y):
"""Compute the outer product of two one-dimensional lists and return a
two-dimensional list with the shape (length of `x`, length of `y`).
Args:
x (list): First list, treated as a column vector. 1 dimensional.
y (list): Second list, treated as a row vector. 1 dimensional.
Returns:
list: Outer product between x and y.
"""
return [[x_i * y_i for y_i in y] for x_i in x]
if __name__ == '__main__':
# Test the `outer` function.
x = [2, 7, 1, 5]
y = [6, 3, 9]
A = outer(x, y)
assert len(x) == len(A)
assert len(y) == len(A[0])
for i, A_i in enumerate(A):
for j, a_ij in enumerate(A_i):
assert x[i] * y[j] == a_ij
|
36b7eb9438a4edb1eafb53012a3b2a65161fcd73 | ivadimn/py-input | /mthreads/locks/locks2.py | 3,915 | 4.0625 | 4 | import random
from collections import defaultdict
import threading
FISH = (None, 'плотва', 'окунь', 'лещ')
###
# Другая проблема с блокировками: они могут быть взаимными.
# Один поток заблокировал ресурс A и ему нужен ресурс Б, а другой поток наобарот - заблокировал Б и ждет А.
def func_1(n):
global a, b
for i in range(n):
print(f'{i}: func_1 wait lock_A', flush=True)
with lock_A:
print(f'{i}: func_1 take lock_A', flush=True)
a += 1
print(f'{i}: func_1 wait lock_B', flush=True)
with lock_B:
print(f'{i}: func_1 take lock_B', flush=True)
b += 1
def func_2(n):
global a, b
for i in range(n):
print(f'{i}: func_2 wait lock_B', flush=True)
with lock_B:
print(f'{i}: func_2 take lock_B', flush=True)
b += 1
print(f'{i}: func_2 wait lock_A', flush=True)
with lock_A:
print(f'{i}: func_2 take lock_A', flush=True)
a += 1
a = 0
b = 0
lock_A = threading.RLock()
lock_B = threading.RLock()
N = 10
thread_1 = threading.Thread(target=func_1, args=(N,))
thread_2 = threading.Thread(target=func_2, args=(N,))
thread_1.start()
thread_2.start()
thread_1.join()
thread_2.join()
print(a, b)
# Это называется красиво: deadlock - тупик или безвыходное положение.
# Что делать, что бы избежать deadlock-ов?
#
# Вот рецепты, в порядке убывания значимости:
# - стараться как можно меньше использовать общие обьекты (глобальные обьекты состояния)
# - делать как можно меньше вложенных блокировок
# - внимательно обращаться с существующими блокировками
# Вообще, эти рекомендации относятся ко всему асинхронному программированию,
# вот статья для медитации над этой темой: https://dev.by/news/pochemu-oni-ne-umeyut-pisat-mnogopotochnye-programmy
###
# Есть еще несколько способов синхронизировать потоки:
#
# Семафоры (Semaphore) - https://goo.gl/PZFKTu - очень похожи на Lock, но позволяют выполнять критичный код
# нескольким потокам
#
# Барьер (Barrier) - https://goo.gl/9f1MHk - позволяет нескольким потокам продолжить свое выполнение одновременно.
# Если в потоке есть barrier.wait() то поток приостанавливается, пока все остальные потоки не вызовут barrier.wait()
#
# События (Events) - https://goo.gl/ewCFgh - поток(и) могут ждать пока событие не будет установлено,
# а другой поток может устанавливать или сбрасывать это событие.
#
# Условные переменные (Condition) - https://goo.gl/mVF6rw - позволяют потоку ждать, пока другой поток
# подготовит данные и сообщит об этом
#
# Таймер (Timer) - https://goo.gl/TqZXXY - похож на простой Thread, но начинает выполнение через N секуднд
#
# Хорошая статья про примитивы синхронизации: Fredrik Lundh "Thread Synchronization Mechanisms in Python"
# перевод http://www.quizful.net/post/thread-synchronization-in-python
|
51b645e61372ec1d11fff2038286a000dd94684c | mohan1411-qa/TC_PYTHON_1411 | /tic_tac_toe_v1.py | 4,465 | 3.875 | 4 | import random
import emoji
def display_board(board):
print(' ' + board[1] + '||' + board[2] + '||' + board[3])
print('----------')
print(' ' + board[4] + '||' + board[5] + '||' + board[6])
print('----------')
print(' ' + board[7] + '||' + board[8] + '||' + board[9])
print('----------')
def player_input():
marker = ""
while not (marker == 'X' or marker == 'O'):
marker = input("Player 1 choose the X or O: ").upper()
''' Assign the player 2'''
if marker == 'X':
return 'X', 'O'
else:
return 'O', 'X'
def place_marker(board, marker, position):
board[position] = marker
def win_check(board, mark):
if board[1] == board[2] == board[3] == mark:
return True
elif board[4] == board[5] == board[6] == mark:
return True
elif board[7] == board[8] == board[9] == mark:
return True
elif board[1] == board[4] == board[7] == mark:
return True
elif board[2] == board[5] == board[8] == mark:
return True
elif board[3] == board[6] == board[9] == mark:
return True
elif board[1] == board[5] == board[9] == mark:
return True
elif board[3] == board[5] == board[7] == mark:
return True
else:
return False
def choose_first():
player_list = ('player_1', 'player_2')
player = random.choices(player_list)
return player[0]
def space_check(board, position):
if board[position] == ' ':
return True
else:
return False
def full_board_check(board):
for i in range(1, 10):
if board[i] == ' ':
return False
else:
return True
def player_choice(board):
position = 0
while position not in [1, 2, 3, 4, 5, 6, 7, 8, 9] or not space_check(board, position):
try:
position = int(input('Choose your next position: (1-9) '))
except:
print("Integer value can be accepted {}".format("😥:"))
return position
def replay():
return input("Do you want to continue Yes or No: ")
def start_game():
print("Welcome to Tic Tac Toe! {}".format("😎:"))
while True:
test_board = [' '] * 10
print("Start the Game ☺:")
player_1, player_2 = player_input()
print("Player 1 is {}".format(player_1))
print("Player 2 is {}".format(player_2))
play_game = input("Are you ready to start the game: Yes or No 👍:").upper()
print("Let's toss for the chance")
chance = choose_first()
print("{} has won the toss and you can start 😎:".format(chance))
if play_game == 'YES' or 'Y':
game_on = True
else:
game_on = False
while game_on:
if chance == 'player_1':
display_board(test_board)
position = player_choice(test_board)
print(position)
place_marker(test_board, player_1, position)
status = win_check(test_board, player_1)
if status:
display_board(test_board)
print("Congratulations You have Won the game {}".format("✌:"))
game_on = False
else:
space = full_board_check(test_board)
if space:
display_board(test_board)
print("Hey!! Match has drawn {} ".format("😥:"))
break
else:
chance = 'player_2'
else:
display_board(test_board)
position = player_choice(test_board)
print(position)
place_marker(test_board, player_2, position)
status = win_check(test_board, player_2)
if status:
display_board(test_board)
print("Congratulations You have Won the game {}".format("✌:"))
game_on = False
else:
space = full_board_check(test_board)
if space:
display_board(test_board)
print("Hey!! Match has drawn {} ".format("😥:"))
break
else:
chance = 'player_1'
response = replay()
if response == 'Yes':
continue
else:
break
start_game()
|
c367c0fd72392e0e37639897882bb130ea6ad03d | walsh06/sportsanalysis | /premierleague.py | 3,701 | 3.515625 | 4 | headers = ['Pos','Team', 'Pld', 'W', 'D', 'L', 'GF', 'GA', 'GD', 'Pts']
def printHeader(heading):
print "============================"
print heading
print "============================"
def readCSV(filename):
with open(filename) as f:
contents = f.readlines()
seasons = {}
reading = False
year = None
currentSeason = []
for line in contents:
if "Year" in line:
if currentSeason:
seasons[year] = currentSeason
year = line.split(",")[1]
currentSeason = []
else:
currentSeason.append(line.split(','))
seasons[year] = currentSeason
return seasons
def getPointsDifference(seasons, writeToFile=False):
year = 2015
result = {}
while year > 1992:
currentSeason = []
for team in seasons[str(year)]:
name = team[1].replace('(Q)', '').replace('(C)', '').replace('(R)', '').replace('(X)', '').strip()
for prevTeam in seasons[str(year - 1)]:
prevName = prevTeam[1].replace('(Q)', '').replace('(C)', '').replace('(R)', '').replace('(X)', '').strip()
if name == prevName:
currentSeason.append((name, str(int(prevTeam[0]) - int(team[0])), team[0], prevTeam[0]))
result[str(year)] = currentSeason
year -= 1
allDiffs = []
for season in result:
for team in result[season]:
allDiffs.append((season, team[0], team[1], team[2], team[3]))
sortedDiffs = sorted(allDiffs, reverse=True, key=lambda tup: int(tup[2]))
printHeader("Position Difference between Seasons")
for diff in sortedDiffs:
print diff
if writeToFile:
with open("pointsDiff.csv", "w") as f:
for diff in sortedDiffs:
f.write("{}\n".format(",".join(diff)))
def getHighestPoints(seasons, writeToFile=False):
idx = headers.index('Pts')
winners = []
for season in seasons:
winners.append((season, seasons[season][0][1], seasons[season][0][idx]))
sortedWinders = sorted(winners, reverse=True, key=lambda tup: tup[2])
printHeader("Highest Points")
for winner in sortedWinders:
print winner
if writeToFile:
with open("highestPoints.csv", "w") as f:
for winner in sortedWinders:
f.write("{}".format(",".join(winner)))
def getLowestPoints(seasons, writeToFile=False):
idx = headers.index('Pts')
losers = []
for season in seasons:
losers.append((season, seasons[season][19][1], seasons[season][19][idx]))
sortedLosers = sorted(losers, key=lambda tup: tup[2])
printHeader("Lowest Points")
for loser in sortedLosers:
print loser
if writeToFile:
with open("lowestPoints.csv", "w") as f:
for losers in sortedLosers:
f.write("{}".format(",".join(losers)))
def getLowestSurvivingPoints(seasons, writeToFile=False):
idx = headers.index('Pts')
survivors = []
for season in seasons:
surviveIdx = -5 if season == '1994' else -4
survivors.append((season, seasons[season][surviveIdx][1], seasons[season][surviveIdx][idx]))
sortedSurvivors = sorted(survivors, key=lambda tup: tup[2])
printHeader("Lowest Surviving Points")
for loser in sortedSurvivors:
print loser
if writeToFile:
with open("lowestSurvivingPoints.csv", "w") as f:
for survivors in sortedSurvivors:
f.write("{}".format(",".join(survivors)))
seasons = readCSV("premierleague.csv")
#getHighestPoints(seasons)
#getLowestPoints(seasons)
#getLowestSurvivingPoints(seasons)
getPointsDifference(seasons, True) |
aefbde1daef14b3bd4ebc4b073d444d7d37d5848 | danieltavares1301/alunos_matriculados | /tres.py | 632 | 3.640625 | 4 | class Aluno:
# inicializando com nome do aluno e sua matricula
def __init__(self, nome, matricula):
self.nome = nome
self.matricula = matricula
self.nota1 = 0
self.nota2 = 0
self.trabalho = 0
# adicionando notas e trabalhos
def addNotas(self, nota1, nota2, trabalho):
self.nota1 = nota1
self.nota2 = nota2
self.trabalho = trabalho
# calculando média
def media(self):
res = (((self.nota1*2.5)+(self.nota2*2.5)+(self.trabalho*2))/7)
print("%.2f"%res)
#exemplo
a = Aluno("daniel", 2018006886)
a.addNotas(10, 9, 7)
a.media()
|
65ed11c44d0f40c1c7474b0227e65315516c4045 | skulumani/algorithm_practice | /binary_search.py | 1,991 | 4.03125 | 4 | """Binary search of an array in python
Given a sorted array A[] ( 0 based index ) and a key "k" you need to complete
the function bin_search to determine the position of the key if the key is
present in the array. If the key is not present then you have to return -1.
The arguments left and right denotes the left most index and right most index
of the array A[] . There are multiple test cases. For each test case, this
function will be called individually.
Example
Input: The first line contains an integer 'T' denoting the number of test
cases. Then 'T' test cases follow. Each test case consists of 3 lines. First
line of each test case contains an integer N denoting the size of the array .
Second line of each test case consists of 'N' space separated integers denoting
the elements of the array A[]. The third line contains a key 'k' .
Output: Prints the position of the key if its present in the array else print
-1 if the key is not present in the array.
Constraints:
1<=T<=600
1<=N<=200
Example:
Input:
2
5
1 2 3 4 5
4
5
11 22 33 44 55
445
Output:
3
-1
"""
import pdb
#Your task is to complete this function
#Function should return integer denoting the index
# indexing is done according to 0
# Left=0 and High=0
def bin_search(arr, low, high, key):
# assume the array is already sorted
# find the length of the array
n = len(arr)
high = n-1
count = 0
while high-low > 1 and count < 200:
mid = (high + low) // 2
# compare the midpoint to the key
if key >= arr[mid]:
low = mid
else:
high = mid
count = count + 1
# now check the endpoints
if key == arr[low]:
return low
elif key == arr[high]:
return high
else:
return -1
if __name__=='__main__':
t=int(input())
for i in range(t):
n=int(input())
arr=list(map(int, input().strip().split(' ')))
x=int(input())
print (bin_search(arr, 0, 0, x))
|
f6516d5d34bf13f64cc6904a597da004896238f0 | Aasthaengg/IBMdataset | /Python_codes/p02379/s204323871.py | 118 | 3.59375 | 4 | import math
x1,y1,x2,y2=map(float,input().split())
x2=x2-x1
y2=y2-y1
x1,y1=0,0
dis=(x2**2+y2**2)
print(math.sqrt(dis)) |
3279f0cd3a69fc54d618a2dee41034f10e5eddc8 | mallory-jpg/bank | /bank_interface.py | 2,039 | 3.5625 | 4 | """Connect to database & enter into bank simulation"""
import logging
from bank_ops import *
from bank_admin import *
from bank_customers import *
import storage
while __name__ == '__main__':
# configure logs
logging.basicConfig(filename='bank.log', filemode='w',
format=f'%(asctime)s - %(self.name)s - %(levelname)s - %(message)s')
print('Hello! Please wait while we connect...')
# connect to db
conn = storage.connect()
# instantiate admin object
admin = Admin()
yes_no = input('Do you have an account with us? Y or N')
if yes_no =='Y':
admin.login()
else:
name = input('Alrighty then, let\'s create an account for you. What is your name?')
user = Users(name.title)
user.generate_uid()
user.create_login()
admin.login()
account = BankAccount()
print("""MAIN MENU:
1~ Open a new account
2~ Deposit
3~ Withdraw
4~ Check balance
5~ View and modify account
6~ Log off
""")
response = input('Please choose an option (1-6): ')
if response == '1':
account.new_account()
elif response == '2':
account.deposit()
elif response == '3':
account.withdraw()
elif response == '4':
account.check_balance()
elif response == '5':
choice = input('Choose [1] Create new username [2] Create new password [3] View account information')
if choice == '1':
admin.new_user()
admin.login()
elif choice == '2':
admin.new_pw()
admin.login()
elif choice == '3':
print("""User ID: {self.uid}
{self.account}
""")
else:
print('Invalid choice. Please try again.')
elif response == '6':
storage.connect.close()
print('Goodbye')
else:
print('Invalid choice. Please try again.')
# start of the program
|
551240ea9e8bf9c0e6797e4a0e6b038ff56822d8 | lincolnjohnny/py4e | /1 Programming_for_Everybody_(Getting_Started_with_Python)/Week_6/ex_04_06.py | 1,108 | 4.375 | 4 | # Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for
# all hours worked above 40 hours. Put the logic to do the computation of pay in a function
# called computepay() and use the function to do the computation. The function should return
# a value.
#
# Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75).
# You should use input to read a string and float() to convert the string to a number.
# Do not worry about error checking the user input unless you want to -
# you can assume the user types numbers properly.
# Do not name your variable sum or use the sum() function.
# function to compute gross pay
def computepay(h,r):
if h > 40 :
return (h*r) + (h-40) * (r*0.5)
else:
return (h*r)
hrs = input("Enter Hours: ")
rph = input("Enter Rate: ")
try:
h = float(hrs)
r = float(rph)
except:
print('Error, please enter numeric input.')
quit()
p = computepay(h,r)
print("Pay",p) |
36b63aef140dd8cca027d40fd347da0c0136aa76 | Aasthaengg/IBMdataset | /Python_codes/p03803/s686294267.py | 211 | 3.59375 | 4 | a,b =map(int,input().split())
A,B,C =("Alice","Bob","Draw")
if max(a,b) ==13 and min(a,b) ==1:
print(A) if a < b else print(B)
else:
if a > b:
print(A)
elif a < b:
print(B)
else:
print(C) |
7cbdb3e9d2af76b58da792f27e3aa9391caae715 | jill-liu2017/stockPlot | /runPgm.py | 1,745 | 3.65625 | 4 | ##
# File name: main.py
# - This file is the entry program for starting service on command line
#
# This program retrieves stock history date from yahoo finance
# for the provided stock symbol and data range in month or year.
# It then plots price and generates prediction using polynomial regression.
#
# How to start the project:
# ==> Service through command line:
# On command line, issue:
# python runPgm.py
# Then follows the instruction on command prompt
##
from main import *
while True:
stockName = raw_input(">>Enter a valid stock symbol you would like to investigate or 'q' to quit the program: ")
if stockName.lower() == 'q':
break
print("Enter the range of the plotted data in month or year. ")
print("For example: '3m' for 3 months, '3y' for 3 years. ")
stockRange = raw_input(">> Data range: ")
if stockRange[-1] not in ('m', 'y'):
print("Invalid range. Start over.")
continue
a = StockPredictorCmdln(stockName, stockRange)
# Plot
a.createPlot()
# Price Prediction
while True:
predictionDate = raw_input(
"Enter a date in format of YYYYMMDD to predict the stock price on that date or 'n' to move to next symbol:")
if predictionDate.lower() == 'n':
break
try:
validateDate(predictionDate)
except Exception as e:
printException(e, "Invalid date. Start over...")
continue
print("Predicated (linear regression) stock price for '%s'" % (a.getName())),
print("based on %s data" % (a.getRange()))
print(datetime.strptime(predictionDate, '%Y%m%d').strftime("on %b %d, %Y is")),
print(a.getPrediction(predictionDate))
|
3acba645551e37e5fc5e9652856fff08b5427c01 | o-henry-coder/python05_12_2020 | /univer/HW/chapter04/algorithmic trainer/task01.py | 221 | 4.21875 | 4 | max_product = 100
num = int(input('enter any number '))
product = num * 10
while product < max_product:
print(product)
num = int(input('enter any number '))
product = num * 10
print('sorry, this number > 100') |
4ec263c3de49080ee13b72d9cc40bdfcef383377 | bleezmo/projecteuler | /proj5.py | 193 | 3.515625 | 4 | def main():
num = 2520
while True:
isNum = True
for i in range(1,21):
if((num//i)*i != num):
isNum = False
break
if(isNum):
break
num+=10
print("Answer is:",num)
main() |
5020d728d855309f974ffba64e5a0a34e3368742 | osnipezzini/PythonExercicios | /ex027.py | 384 | 4.03125 | 4 | """Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o ultimo nome separadamente .
Ex: Ana Maria de Souza
primeiro = Ana
ultimo = Souza"""
from format import style
nome = str(input('Digite seu nome completo : ')).strip()
n = nome.split()
style()
print('Seu primeiro nome é {}'.format(n[0]))
print('Seu último nome é {}'.format(n[len(n)-1]))
style()
|
a910c343ba6ad76d00574f5cc47c188e78874476 | nirdesh1995/Algorithms | /project2/main.py | 5,555 | 3.75 | 4 | import re
"""Abstract Data Type Edge"""
class edge:
def __init__(self, source, destination, nexts = None):
self._source = node
self._destination = destination
self._next = nexts
def getDest(self):
return self._destination
def getNext(self):
return self._next
"""Abstract Data Type Node"""
class node:
counter = 0
def __init__(self,key):
self._id = key
self._head = None
self._index = node.counter
node.counter += 1
def getId(self):
return self._id
def modNode(self, new_key):
self._id = new_key
def addFirst(self, source, destination):
self._head = edge(source, destination)
self.position = self._head
def addEdge(self, source, destination):
self.element = edge(source, destination)
self.position._next = self.element
self.position = self.element
def firstEdge(self):
return self._head
def getIndex(self):
return self._index
"""Abstract Data Type Graph implementing Node and Edge"""
class graph:
def __init__(self):
self._vertices = {}
self.vertexNum = 0
self.edgeNum = 0
# Method of insert node in the graph
def insert_node(self, key):
self.vertexNum += 1
self._vertices[key] = node(key)
return self._vertices[key]
# Return this list of nodes in the graph
# self.vertice = {(Name: Node)}
def get_vertices(self):
return self._vertices
# Method of search city and return the index of the node
def searchCity(self, city):
if city in self._vertices:
return self._vertices[city].getIndex()
else:
return self.insert_node(city).getIndex()
# Method to insert edge
# Source and destination can be string representing name of the source and destination
# Source and destination can be object of source and destination
# sourcename and destination name not the objects
def insert_edge(self, source, destination):
self.edgeNum += 1
if source in self._vertices:
source = self._vertices[source]
else:
source = self.insert_node(source)
if destination in self._vertices:
destination = self._vertices[destination]
else:
destination = self.insert_node(destination)
if source._head == None:
source.addFirst(source, destination)
else:
source.addEdge(source, destination)
def cyclic_test(self, v, parent):
if v.getDest() not in self.visited:
self.visited.append(v.getDest())
return self.cyclic_test(v.getDest().firstEdge(),v)
next_edge = v.getNext()
if next_edge != None:
if parent != next_edge.getDest():
return True
return self.cyclic_test(next_edge, v)
return False
def cyclic(self):
self.visited = []
for u in self._vertices.values():
#print("aaa", u.getId())
if u not in self.visited:
self.visited.append(u)
v = u.firstEdge()
cycle = self.cyclic_test(v, u)
return cycle
if __name__ == "__main__":
#---------------------------------------BUILDING GRAPH------------------------
filename = input("Enter Filename: ")
if filename != "":
with open(filename) as file:
data1 = file.read().rstrip()
data2 = re.split(r'[\n ' ' -]',data1)
else:
with open("graphSmall1.in") as file:
data1 = file.read().rstrip()
data2 = re.split(r'[\n ' ' -]',data1)
g = graph()
for i in range (0,len(data2) - 1,2):
g.insert_edge(data2[i],data2[i+1])
"""for key,node in g.get_vertices().items():
print ("Source:", key)
print("Destination:")
print(str(node.firstEdge().getDest().getIndex()) + " " + str(node.firstEdge().getDest().getId()))
if node.firstEdge().getNext()!= None:
nextNode = node.firstEdge().getNext()
while (nextNode != None):
print(str(nextNode.getDest().getIndex()) + " " + str(nextNode.getDest().getId()))
nextNode = nextNode.getNext()
print("------------------")"""
#--------------------------------------Connected Components-------------------------------------
def dfs(v):
if v.getDest() not in visited:
connected[connected_component].append(v.getDest().getId())
visited.append(v.getDest())
dfs(v.getDest().firstEdge())
v = v.getNext()
if v != None:
dfs(v)
visited = []
connected = {}
connected_component = 0
for u in g.get_vertices().values():
if u not in visited:
connected_component += 1
connected[connected_component] = [u.getId()]
visited.append(u)
dfs(u.firstEdge())
# ----------------------------OUTPUT-------------------------------------------------------
print("Read", g.vertexNum, "cities", int(g.edgeNum/2), "edges")
print()
print("Number of connected components:", connected_component)
print()
for key, value in connected.items():
print("Connected Component",key,":")
for j in value:
print(j)
print()
if g.cyclic():
print("Graph contains a cycle")
else:
print("Graph doesnot contain a cycle") |
029028d0d119206315f4acdf5343073024a37561 | jeffersonmca/Knights_Tour_Problem | /main.py | 2,596 | 3.90625 | 4 | #######################################
# The Knight's Tour Problem #
#######################################
# Name: Jefferson Marques Costa Alves #
# March 2021 #
#######################################
#
# Constants
#
# Start point of the tour
START_X, START_Y = 0, 0
# Board height and width
BOARD_X, BOARD_Y = 8, 8
# Amount cells of the board
MAX = (BOARD_X * BOARD_Y) - 1
# Empty cell
EMPTY = -1
'''
5 4
6 3
K
7 2
8 1
'''
MOVES = [
# 1
[1, 2],
# 2
[2, 1],
# 3
[2, -1],
# 4
[1, -2],
# 5
[-1, -2],
# 6
[-2, -1],
# 7
[-2, 1],
# 8
[-1, 2],
]
'''
Is it safe to move the knight to [x, y] position ?
True - Yes
False - No
'''
def isSafe(board, x, y):
# x and y do not go out the board and that position is empty
if 0 <= x < BOARD_X and 0 <= y < BOARD_Y and board[x][y] == EMPTY:
return True
return False
'''
Recursive function that solves the problem
'''
def knightsTour(board, cont, cx, cy):
# All the cells were filled ?
if cont > MAX:
# Return the filled board
return board
# If have cells to fill
# Try some moves
for x, y in MOVES:
# Next move
nx, ny = cx + x, cy + y
# is it ok to go to the next move?
if isSafe(board, nx, ny):
# Choose that move
board[nx][ny] = cont + 1
# Calls recursively with the next point
if knightsTour(board, cont + 1, nx, ny):
return True
# Backtracking
board[nx][ny] = EMPTY
# None moves were valid
return False
'''
Receives an empty board and returns a filled board with the solution
'''
def solve(board):
# Initial point
board[START_X][START_Y] = 1
# Counter
cont = 1
# Calls the recursive function
if not knightsTour(board, cont, START_X, START_Y):
print("Doesn't have a solution!")
exit(0)
# Return the filled board
return board
'''
Shows the solution on the console
'''
def printMatrix(board):
for i in range(len(board)):
for j in range(len(board[0])):
print(board[i][j], end=' ')
print()
'''
Main function
'''
def main():
# Create a BOARD_X x BOARD_Y board
board = [[EMPTY for j in range(BOARD_X)] for i in range(BOARD_Y)]
# Solves the problem
result = solve(board)
# Shows the solution on the console.
printMatrix(result)
'''
Initial function of a python program
'''
if __name__ == '__main__':
main() |
9369a09071545312687c95f3dace06d6fa078ce8 | jennyChing/leetCode | /504_convertToBase7.py | 477 | 3.671875 | 4 | '''
504. Base 7
'''
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
sign = -1 if num < 0 else 1
num = abs(num)
res = ""
while num >= 7:
res += str(num % 7)
num //= 7
res += str(num % 7)
res += "" if sign == 1 else "-"
return res[::-1]
if __name__ == '__main__':
res = Solution().convertToBase7(101)
print(res)
|
26ada5ffef929ddd47b3cbd4ed58ebdc831975f4 | ramakrishna227/CorePython | /functionPractice.py | 260 | 3.890625 | 4 | def function(n=-5):
if n > 0:
print(n, end=' ')
function(n - 1)
else:
print(n)
function(3)
x = function()
print(x)
# python has a maximum recursion depth of 996
def doubler(y=1):
return y * 2
z = doubler(10)
print(z)
|
67f1fdc8303f647549fda2ce3df7d8ed8321ada5 | gheorghecalancea/AI-LAB | /C-161/Marjina Alexandru/Lab5/Lab5.py | 1,091 | 3.5 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
#incarcam setul de date
iris = pd.read_csv("dataset/iris.csv")
#despărțim datasetul în vector de caracteristici (features) și vectorul clasă
features = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
X = iris[features] # caracteristicile (atributele pentru X)
y = iris.species # caracteristica clasă
#impartim setul de date integral in date de antranare si date de testare utilizand functia train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)
print("\n70% Antrenare:")
print(X_train)
print(y_train)
print("\n30% Testare:")
print(X_test)
print(y_test)
#cream clasificatorul k-nn
#setam numarul de vecini ca parametru explicit
knn = KNeighborsClassifier(n_neighbors=5)
#antrenam modelul utilizand setul de date de antrenare
knn.fit(X_train, y_train)
#prezicem raspunsul corect pentru setul de destare
print("Raspunsurile date de model:")
y_pred = knn.predict(X_test)
print(y_pred) |
35d82e829d16b1d29938ba3486796cafb3de4759 | 0xNajmul/exercise | /python/loop.py | 114 | 3.9375 | 4 | # print a[0] to a[2]
for x in range(3):
print(x)
# while loop 1 to 10
x=0
while x<10:
print(x)
x+=1
|
9bde3ca1d54501f76844262f163d057e164f4a34 | rchordiya/Academic-and-Self-motivated-Projects | /Python_Library/main.py | 1,462 | 3.59375 | 4 | from SearchEngine import SearchEngine
from Media import Media
def main():
track=True
results = list()
search_obj=SearchEngine()
while track:
print("Enter your choice\n");
print("-------------------------------------\n");
print("1. Search by call number\n");
print("2. Search by title\n");
print("3. Search by subject\n");
print("4. Search Other\n");
print("5.To exit\n");
print("---------------------------------------\n");
results.clear()
n=int(input())
if n==1:
print("Enter the call number\n");
srch_str=input()
results=search_obj.search_by_call_number(srch_str)
for letter in results:
letter.display()
elif n==2:
print("Enter the title\n");
srch_str=input()
results=search_obj.search_by_title(srch_str)
for letter in results:
letter.display()
elif n==3:
print("Enter the subject\n");
srch_str=input()
results=search_obj.search_by_subjects(srch_str)
for letter in results:
letter.display()
elif n==4:
print("Enter to search by other\n");
srch_str=input()
results=search_obj.search_by_other(srch_str)
for letter in results:
letter.display()
else :
track=False
print("---------------------------------------------------------");
print("Total Number of reports found ----------> ",len(results))
print("\n")
if __name__ == "__main__": main()
|
db000019cd1b0cbb4541dcb7b67c5d926a106bed | Dhrumil-Zion/Competitive-Programming-Basics | /Codechef/Practice/Chef And Operator.py | 163 | 3.671875 | 4 | for _ in range(int(input())):
n1,n2 =map(int,input().split())
if n1>n2:
print(">")
elif n1==n2:
print("=")
else:
print("<") |
dde00a57523cbcbd125afa05853eca7674be9c54 | abrahampost/adventofcode | /day1/part1.py | 372 | 3.546875 | 4 | TARGET = 2020
# Adds seen numbers to set.
# If the diff between the target and current num is in set, that is the pair
with open("input.dat", "r") as file:
seen = set()
for line in file.readlines():
num = int(line)
diff = TARGET - num
if diff in seen:
print(num * diff)
break
else:
seen.add(num) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.