blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1e7958e906bb13b7235984e30e5afa2b0278c7b7 | ChampionZA/School_ict_backup | /Complete/Python/IGCSE computer science paper 2 october-november 2021.py | 4,370 | 3.625 | 4 | import re
homeToStartStation = {'c1':1.50, 'c2':3.00, 'c3':4.50, 'c4':6.00, 'c5':8.00}
startStationToEndStation = {'m1':5.75,'m2':12.50,'m3':22.25,'m4':34.50, 'm5':45.00}
endStationToDestination = {'f1':1.50,'f2':3.00,'f3':4.50,'f4':6.00,'f5':8.00}
bookingDetails = {}
accounts = {}
stageCodes = []
generatingNumbers = 0
stageOneSet = False
stageTwoSet = False
stageThreeSet = False
exitVarEnterAccNum = False
def discount(percent, total):
return '{0:.2f}'.format(total * (percent/100))
def account_creation():
global personalAccNum
name = input("Please enter your name [LETTERS ONLY]: ")
if name == "exit":
return
personalAccNum = int(input('Please create your personal account number [NUMBERS ONLY]: '))
if personalAccNum in accounts:
print('That account number already exists!!')
account_creation()
return
else:
pass
accounts[personalAccNum] = name
print(f"Thank you, your accounts number is {personalAccNum}")
def making_a_booking():
global passengerAccountNumber
global startTime
global stageCodes
global stageOne
global stageTwo
global stageThree
global totalCost
global generatingNumbers
global areUSure
global exitVarEnterAccNum
while True:
passengerAccountNumber = int(input("Please enter your account NUMBER: "))
if passengerAccountNumber in accounts:
break
else:
print('That account does not exist (Type "exit" to return)')
if exitVarEnterAccNum:
return
print(f'Welcome {accounts[passengerAccountNumber]}')
while True:
startTime = input('Please enter the start time of your journey: ')
if re.match(r'\d\d:\d\d', startTime):
break
else:
continue
while True:
stageOne = input('Please enter the first stage of your journey: ')
if stageOne in homeToStartStation:
totalCost += homeToStartStation[stageOne]
break
else:
print("That is not a valid code for stage one!")
while True:
stageTwo = input('Please enter the second stage of your journey: ')
if stageTwo == "" or stageTwo in startStationToEndStation:
break
else:
print('You can only enter a valid code or nothing to only use stage one')
if stageTwo == '':
stageThree = ''
pass
else:
totalCost += startStationToEndStation[stageTwo]
while True:
stageThree = input('Please enter the third stage of your journey: ')
if stageThree == '' or stageThree in endStationToDestination:
break
else:
print('You can only enter a valid code or leave blank if you only need stage one and two')
if stageThree == '':
pass
else:
totalCost += endStationToDestination[stageThree]
print(f"Your unique booking number is {generatingNumbers+1}")
if int(startTime.split(':')[0]) > 10 or int(startTime.split(':')[0]) == 00:
totalCost = discount(40, totalCost)
print('A 40% discount has been applied to the total price')
bookingDetails[generatingNumbers+1] = [startTime, stageOne, stageTwo, stageThree, passengerAccountNumber, totalCost]
if bookingDetails[generatingNumbers+1][2] == '' and bookingDetails[generatingNumbers+1][3] == '':
print(f"It's going to cost you ${totalCost} to go from home to start station")
elif bookingDetails[generatingNumbers+1][3] == '':
print(f"It's going to cost you ${totalCost} to go from home to end station")
else:
print(f"It's going to cost you ${totalCost} to go from home to destination")
while True:
areUSure = int(input('Are you sure the details are correct? [1] yes or [2] no: '))
if areUSure == 1:
print('Details have been saved, have a nice day')
generatingNumbers += 1
break
elif areUSure == 2:
print('No problem, just restart the booking process')
del bookingDetails[generatingNumbers+1]
print('Previously entered information has been deleted')
break
else:
print('please enter a valid option')
while True:
# dev note: you can type 69 to get the stored booking details and accounts
totalCost = 0
exitVarEnterAccNum = False
choice = int(input("Would you like to Create a new account [1] or make a booking [2]: "))
if choice == 1:
account_creation()
elif choice == 2:
making_a_booking()
elif choice == 69:
print(f"Booking Details - {bookingDetails}")
print(f"Accounts - {accounts}") |
71c20f15c95626ddf7801ce2b18d6679eaf61b07 | cfawcett100/Trust_Scrape | /csv_handler.py | 8,159 | 3.890625 | 4 | import csv
import datetime
class csv_handler(object):
def __init__(self, file_name):
print(datetime.datetime.now())
self._csv_file = file_name
print("LOADING FILE...")
csv_reader = self.open_csv()
self._trust_list = self.create_list(csv_reader)
self.to_upper()
print("FILE LOADED!")
print(datetime.datetime.now())
def run_tests(self):
self.trustee_search()
location = int(input("Enter location: "))
self.get_first_cons(location)
def open_csv(self):
"""Opens the csv file and returns the csv reader"""
input_file = open(self._csv_file, "r")
reader = csv.reader(input_file)
return reader
def create_list(self, csv_reader):
"""Takes the items in the file and puts them into a list"""
new_list = []
count = 1
first = True
for row in csv_reader:
# A horrible piece of code to break if the first row is an int
# Continues if it's the first line
if first == True:
if not isinstance(row[0], str):
return []
first = False
continue
new_list.append(row)
return new_list
def to_upper(self):
"""Turns all names into upper case"""
for i in self._trust_list:
i[1] = i[1].upper() # Changes name to all upper case
def trustee_search(self):
"""Searches for all appearances of a string"""
name = input("Enter trustee name: ")
name = name.upper()
trustee_list = []
for i in range(0, len(self._trust_list)):
try:
if name in self._trust_list[i][1]:
trustee_list.append([i, self._trust_list[i][0], self._trust_list[i][1]])
except:
print(self._trust_list[i])
self.print_search(trustee_list)
def print_search(self, trustee_list):
"""Prints the search results from trustee_search"""
if len(trustee_list) > 20:
choice = input("More than 20 matches found. Do you wish to print?(y/n) ")
if choice == "y":
self.printf(trustee_list)
else:
self.printf(trustee_list)
def printf(self, trustee_list):
"""Formatted print function for the trustee list"""
print("Location, Trust, Trustee")
for i in trustee_list:
print(i[0], i[1], i[2])
def get_trustee(self, location):
"""Given a position in the _trust_list, returns the trustee name"""
return self._trust_list[location][1]
def get_trust(self, location):
"""Given a position in the _trust_list, returns the trust number"""
return self._trust_list[location][0]
def get_trustees_trusts(self, name):
"""Takes a trustee name and returns a list of associated trusts"""
trust_list = []
for i in self._trust_list:
if name == i[1] and i[0] not in trust_list:
trust_list.append(i[0])
return trust_list
def get_trust_trustees(self, trust):
"""Takes a trust number and returns a list of associated trustees"""
name_list = []
for i in self._trust_list:
if trust == i[0] and i[1] not in name_list:
name_list.append(i[1])
return name_list
def get_first_cons(self, location):
"""Given a location in the list of trustees, it will find that trustees first hand connections"""
trustee = self.get_trustee(location)
trustees_trusts = self.get_trustees_trusts(trustee)
cons = []
print("Trustee name: ", trustee)
print("Trustee's trusts: ")
self.print_list(trustees_trusts)
for i in trustees_trusts:
cons = cons + self.get_trust_trustees(i)
print("\n", i)
self.print_list(self.get_trust_trustees(i))
#cons = list(set(cons)) In case of duplicates
def print_list(self, input_list):
"""Formatted printing for outputting connections"""
for i in input_list:
print(i)
def lget_trust_trustees(self, trust):
"""Takes a trust number and returns a list of associated trustees"""
if not isinstance(trust, int):
print("Input to lget_trust_trustees must be an int!")
exit()
trustName = self._trust_list[trust][0]
loc_list = []
for i in range(0, len(self._trust_list)):
if trustName == self._trust_list[i][0] and i not in loc_list:
loc_list.append(i)
return loc_list
def lget_trustees_trusts(self, trustee):
"""Takes a trust number and returns a list of associated trustees"""
if not isinstance(trustee, int):
print("Input to lget_trustees_trusts must be an int!")
exit()
trusteeName = self._trust_list[trustee][1]
trust_list = []
for i in range(0, len(self._trust_list)):
if trusteeName == self._trust_list[i][1] and i not in trust_list:
trust_list.append(self._trust_list[i][0])
loc_list = []
for i in range(0, len(self._trust_list)):
if self._trust_list[i][0] in trust_list and i not in loc_list:
loc_list.append(i)
return loc_list
def list_of_lists_join(self, a):
oldList = list(a)
newList = []
for i in oldList:
for q in i:
newList.append(q)
return newList
def connections(self, degree, location):
"""Takes a number and a location and finds all connections at the degree entered"""
sum_list = []
sum_list.append([location])
if degree == 0:
return sum_list
cons = self.lget_trustees_trusts(location)
print("Degree: ", degree)
print("Location: ", location)
trustees = []
for i in cons:
trustees += self.lget_trust_trustees(i)
# Need to remove duplicates here from trustees
trustees = list(set(trustees))
print("Trustees: ", trustees)
new_list = []
if degree > 0:
for i in trustees:
new_list += self.connections(degree-1, i)
new_list = self.list_of_lists_join(new_list)
sum_list.append(new_list)
print("Sum_list: ", sum_list)
return sum_list
def fail(self, n):
print("TEST ", n, " FAILED!!!")
exit()
def eq(self, n, a, b):
"""General function to see if two things are equal"""
n += 1
if a == b:
return n
else:
self.fail(n)
return n
def list_sub(self, a, b):
if len(a) < len(b):
return []
return [x for x in a if x not in b]
def list_comp(self, a, b):
for i in a:
if i not in b:
return False
return True
def eq1(self, n, inp, exp):
count = 1
while count <= len(exp) - 1:
inpComp = self.list_sub(inp[-count], inp[-count - 1])
expComp = self.list_sub(exp[-count], exp[-count - 1])
inpComp = sorted(inpComp)
expComp = sorted(expComp)
if inpComp != expComp:
self.fail(n)
count += 1
return n
def tests(self):
"""Tests some other functions in the class"""
n = 0
n = self.eq(n, self.connections(0,0), [["A"]])
n = self.eq1(n, self.connections(1,0), [["A"], ["A", "B", "C", "D", "E", "F", "G"]])
n = self.eq1(n, self.connections(2,0), [["A"], ["A", "B", "C", "D", "E", "F", "G"], ["A", "B", "C", "D", "E", "F", "G", "H", "I"]])
# Used for testing
def main():
file_name = "test_data.csv"
new_handler = csv_handler(file_name)
new_handler.eq1(1, [["A"], ["D", "A", "F", "I"]], [["A"], ["I", "F", "D", "A"]])
# print(new_handler.lget_trustees_trusts(0))
# print(new_handler.lget_trust_trustees(3))
print(new_handler.connections(2, 0))
# new_handler.tests()
main()
|
c053696a0c48e52a2431232d7c53968a58076ba0 | nikesh610/Guvi_Codes | /Set5_2.py | 79 | 3.8125 | 4 | x=input().split()
if(x[0]==x[1] or x[0]>x[1]):
print(x[0])
else:
print(x[1])
|
b87961f70df8cdb6e0f11b3fd6e8844dc81ab536 | aguecida/python-playground | /algorithms/binarysearch/binarysearch.py | 1,445 | 4.15625 | 4 | from random import randint
def binary_search(range_min, range_max):
'''
Performs a binary search to find a randomly selected number between a range of two integers.
Args:
range_min: The lowest possible value of the randomly selected integer.
range_max: The highest possible value of the randomly selected integer.
Returns:
guess: The correct guess.
tries: The number of tries it took to find the number.
'''
random_num = randint(range_min, range_max)
tries = 0
prev_guess = None
while True:
guess = int((range_min + range_max) / 2)
tries += 1
# Make sure we don't get stuck in a loop since guess operation is always rounded down
if guess == prev_guess:
guess += 1
if guess > random_num:
range_max = guess
elif guess < random_num:
range_min = guess
else:
break
prev_guess = guess
return guess, tries
if __name__ == '__main__':
try:
range_min = int(input('Enter min range: '))
range_max = int(input('Enter max range: '))
except:
print('Received bad input, exiting...')
quit()
correct_guess, num_tries = binary_search(range_min, range_max)
if num_tries == 1:
print(f'Found number {correct_guess} in {num_tries} try!')
else:
print(f'Found number {correct_guess} in {num_tries} tries!')
|
d26f9687fd955bb3464eb512ad3f13b2595d01a1 | lw2000017/python | /绿城融合系统/测试练习.py | 171 | 3.578125 | 4 | # a={1,2,3,4}
# b={1,2,3,4}
# c={1,2,3,4}
# for j in a:
# for k in b:
# for l in c:
# if j!=k and k!=l and j!=l:
# print(j,k,l)
#
|
d7d39535e12121eadbb7f02b23324ff9520610a8 | houhailun/algorithm_code | /链表中环的入口结点.py | 1,861 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
题目:链表中环的入口结点
题目描述:给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null
解题思路:对于找链表公共节点,入口节点等问题可以用两个一快一慢的指针
方法1:p1每次走一步,p2循环链表,第一个相同的结点就是入口结点 时间复杂度O(N*N)
方法2:遍历链表,第一个重复的结点就是入口结点 时间复杂度:O(N) 空间复杂度:O(N)
方法3:假设环中有n个结点,那么p1先走n步,然后两个结点一起走,相遇的结点就是入口结点,问题是如何获取环中结点个数:
p1每次走1步,p2走两步,相遇的地方就是环中某个结点,此时p1不动,p2循环,可以知道环中的结点个数
"""
class Solution:
def entry_node_of_loop(self, pHead):
node = self.meet_nodes(pHead)
if node is None:
return None
# 环中结点数
slow = node
cnt = 1
while slow.next != node:
cnt += 1
slow = slow.next
# fast先走cnt步
fast = pHead
for i in range(cnt):
fast = fast.next
# 一起走
slow = pHead
while slow != fast:
slow = slow.next
fast = fast.next
return slow
def meet_nodes(self, pHead):
# 查找环中的结点
if pHead is None:
return None
slow = pHead.next
if slow is None:
return None
fast = slow.next
while not slow and not fast:
if slow == fast:
return slow
slow = slow.next
fast = fast.next
if slow != fast:
fast = fast.next
return None |
c2fec868f5d3e6ada009f6708c25207be6d6193e | nithin-kumar/clrs_algorithms | /stackandQ/queue.py | 908 | 3.703125 | 4 | class Queue:
def __init__(self):
self.a=[0]*10
self.head=0
self.tail=0
self.length=len(self.a)
def queue_full(self):
if self.tail+1==self.head:
return True
return False
def queue_empty(self):
if self.head==self.tail:
return True
return False
def enqueue(self,x):
if self.queue_full():
return "Que is Full"
self.a[self.tail]=x
if (self.tail==self.length-1):
self.tail=0
else:
self.tail+=1
def dequeue(self):
if self.queue_empty():
return "Queue is Empty"
x=self.a[self.head]
if self.head==self.length-1:
self.head=0
else:
self.head+=1
return x
def display(self):
#for i in range(self.head,self.tail+1):
#return self.a[i]
return self.a
q1=Queue()
q1.enqueue(4)
q1.enqueue(7)
q1.enqueue(7)
q1.enqueue(7)
q1.enqueue(7)
q1.enqueue(7)
#print q1.dequeue()
#print q1.head
print q1.tail
#print q1.queue_empty()
print q1.display()
|
ff090f5f30811d98c6df19dd4ffeb037d4eb0a44 | keshamin/sort-algorithms | /common_sort_utils.py | 504 | 3.5625 | 4 | from collections import Iterable
from functools import wraps
def iterables_only(func):
"""
Decorator validates that first argument is iterable
:param func: sorting function taking iterable as a first argument
:return: decorated function
"""
@wraps(func)
def wrapper(iterable, *args, **kwargs):
if not isinstance(iterable, Iterable):
raise ValueError('Cannot sort non-iterable object!')
return func(iterable, *args, **kwargs)
return wrapper
|
227bca03f7069184ca0375edc3ece2bb567549f5 | neternefer/codewars | /python/longest.py | 317 | 4.09375 | 4 | def longest(s1, s2):
"""Given two strings, return the longest possible
string with each letter from s1 and s2 appearing only
once. Sort alphabetically.
"""
new_str = ''
for letter in s1 + s2:
if letter not in new_str:
new_str += letter
return ('').join(sorted(new_str)) |
fd2096519d43927e9351140271a5431817bd0a2b | adoption-loli/pygame_data_visualization | /readcsvfile.py | 1,471 | 3.546875 | 4 | import csv
from pprint import *
class data_list():
def __init__(self, filename):
self.filename = filename
self.datas = []
with open(filename, 'r', encoding='utf-8') as csv_file:
self.reader = csv.reader(csv_file)
for cell in self.reader:
self.datas.append(cell)
def analyze(self):
'''
[
[
date,
[name, value],
[name, value],
],
[
date,
[name, value],
[name, value],
],
]
'''
information = {}
for cell in self.datas:
try:
c_name = cell.index('name')
c_value = cell.index('value')
c_date = cell.index('date')
except:
try:
information[cell[c_date]].append([cell[c_name], int(cell[c_value])])
except:
information[cell[c_date]] = []
information[cell[c_date]].append([cell[c_name], int(cell[c_value])])
result = []
# pprint(information)
for cell in information:
temp = [cell]
temp.extend(information[cell])
# pprint(temp)
result.append(temp)
# pprint(result)
return result
if __name__ == '__main__':
test = data_list('danmu_an.csv')
test.analyze()
|
ead1e27717db743fbfa14b232a1ca9ef2b0b4895 | opedro-c/calculadora | /utilitarios.py | 731 | 3.75 | 4 | from tkinter import messagebox as msg
def formatar_expressao(expressao):
if '**' in expressao:
return expressao.replace('**', '^')
elif '*' in expressao:
return expressao.replace('*', 'x')
return expressao
def expressao_ok(expressao):
if expressao.find('-') == 0:
somente_num_negativo = expressao.replace('-', '', 1).replace('.', '').isnumeric()
return not somente_num_negativo
somente_num = expressao.replace('.', '').isnumeric()
return not somente_num
def verificar_colar(texto):
texto_tratado = texto.replace('.','').strip()
if texto_tratado.isnumeric():
return texto_tratado
msg.showinfo(title='Calculadora', message='Só pode colar números!')
|
fb36aa0e7e65c887559631f20b73b63e7642af42 | ArthurSpillere/AulaEntra21_ArthurSpillere | /Exercícios Resolvidos/Aula10/exercicios/exercicio03.py | 2,250 | 4.03125 | 4 | # """Exercício 03
# 3.1) Crie um programa que cadastre o id, nome, sexo e a idade de 5 clientes.
# 3.2) Depois mostre os dados dos 5 clientes.
# 3.3) Peça para que o usuário escolha um id de um cliente e mostre as informações deste cliente.
# 3.4) Crie um filtro que ao digitar um id de um cliente mostre as seguintes informações:
# - Para menores de 17 anos: Entrada Proibida
# - Para maiores de 17 anos: Entrada Liberada
# - Para o sexo Feminino: 50% de desconto
# - Para o sexo Masculino: 5% de desconto
# """
##############################################################################
#CADASTRO DO CLIENTE:
ids=[]
nomes=[]
sexos=[]
idades=[]
rang=5
for i in range(rang):
ids.append(i+1)
nomes.append(str(input(f"Insira o nome do {i+1}º cliente: ").title()))
while True:
sexo_cliente=str(input(f"Insira o sexo do {i+1}º cliente: [M/F] ").strip().upper()[0])
if sexo_cliente in "MF":
sexos.append(sexo_cliente)
break
idades.append(int(input(f"Insira a idade do {i+1}º cliente: ")))
#APRESENTAÇÃO DOS USUÁRIOS CADASTRADOS
print("\n")
print("=+"*20)
print(f"{'Usuários Registrados':^40}")
print("=+"*20)
for j in range(rang):
print(f"""
Usuário: {nomes[j]}
ID: {ids[j]}
Sexo: {sexos[j]}
Idade: {idades[j]}""")
#OPÇÃO DE ESCOLHER UM ID
print("")
while True:
while True:
print(f"Escolha uma ID para mais informações: [IDs: {min(ids)}-{max(ids)}] ")
resp=int(input())
if min(ids)<=resp<=max(ids):
break
print(f"""\033[1;34m
Usuário: {nomes[resp-1]}
ID: {ids[resp-1]}
Sexo: {sexos[resp-1]}
Idade: {idades[resp-1]}\033[m""")
#FILTRO - MENSAGEM FINAL PARA O USUÁRIO
if idades[resp-1]<17:
print("\n\033[1;31mEntrada Proibida!\033[m\n")
else:
print("\n\033[1;32mEntrada Liberada!\033[m\n")
if sexos[resp-1] == "M":
print("Você ganhou 5% de desconto!\n")
elif sexos[resp-1] == "F":
print("Você ganhou 50% de desconto!\n")
resp2="L"
while resp2 not in "SN":
resp2=str(input("Você gostaria de ver outro ID? [S/N] ").strip().upper()[0])
if resp2=="N":
break
|
a8eade4329bbcfa12a1d9392b87ca4c1087c9eeb | Roc-J/LeetCode | /300~399/problem349.py | 496 | 4 | 4 | # -*- coding:utf-8 -*-
# Author: Roc-J
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = []
nums1 = list(set(nums1))
nums2 = list(set(nums2))
for item in nums2:
if item in nums1:
result.append(item)
return result
if __name__ == '__main__':
print Solution().intersection([1, 2, 1], [])
|
db7239c12cf0f22c61df82e08b5ac75f2300d0ee | Rutrle/python-tryouts | /sorting.py | 240 | 4.03125 | 4 | my_list = ['Praha', 'Brno', 'Ostrava']
# sort by second letter
my_dict = {}
'''
for i in range(len(my_list)):
print(my_dict[my_list[i][2]]=)
'''
my_list.sort()
sorted_vals = sorted(my_list, reverse=True)
print(my_list, sorted_vals)
|
edbe8ec7edd5aa6cc3e30df534ebf942beeacf94 | thomascottendin/GeeksforGeeks | /Medium/multiply2Strings.py | 562 | 4.25 | 4 | #Given two numbers as stings s1 and s2 your task is to multiply them. You are required to complete the function multiplyStrings which takes two strings s1 and s2 as its only argument and returns their product as strings.
{
#Initial Template for Python 3
if __name__ == "__main__":
t=int(input())
for i in range(t):
a,b=input().split()
multiply(a,b)
}
''' This is a function problem.You only need to complete the function given below '''
#User function Template for python3
def multiply(a,b):
return print (int(a)*int(b)) |
56a10323c5ab97bafbecc24bf0a20059a47f0711 | randyarbolaez/codesignal | /daily-challenges/validTime.py | 210 | 3.84375 | 4 | # Check if the given string is a correct time representation of the 24-hour clock.
def validTime(time):
hours = int(time[:2])
minutes = int(time[3:])
return hours < 24 > hours and minutes < 60 > minutes
|
d78c8dcdf8d0a666cbcd2a842ead27f1df53369a | vishnoiprem/pvdata | /lc-all-solutions-master/039.combination-sum/combination-sum.py | 820 | 3.5625 | 4 | class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def dfs(nums, target, path, res):
if target == 0:
res.append(path + [])
return
for i in range(0, len(nums)):
if path and nums[i] < path[-1]:
continue
if target - nums[i] < 0:
return
path.append(nums[i])
dfs(nums, target - nums[i], path, res)
path.pop()
candidates.sort()
res = []
dfs(candidates, target, [], res)
return res
arr=[2, 3, 6, 7]
target=7
print(Solution().combinationSum(arr,target)) |
f1740d35afe605a24f251cb478cf8edc05fe25f4 | EdwardTatchim/PythonProjects | /hw7_final.py | 2,259 | 3.953125 | 4 | import random
class Player:
def __init__(self,name):
self.name = name
self.position = 0
self.playerList = []
self.playerList.append(name)
#self.red_start = int(input("How many red players do you want? "))
#self.blue_start = int(input("How many blue players do you want? "))
class RedPlayer(Player):
#self.red_start = int(input("How many red players do you want? "))
def __init__(self,name):
Player.__init__(self,name)
#self.playerList.append(name)
self.rname = str()
self.position1 = 0
def play(self):
for w in self.playerList:
while self.position1 < 100:
#print(w + " is walking")
self.position1 += self.walk()
self.rname = w
print("\nnRedPlayer winner is " + self.rname + " with distance covered " +str(self.position1)+ " miles.\n")
def walk(self):
self.position = random.randint(1,10)
return self.position
class BluePlayer(Player):
#self.blue_start = int(input("How many blue players do you want? "))
def __init__(self,name):
Player.__init__(self,name)
#self.playerList.append(name)
self.bname = str()
self.position2 = 0
def walk(self):
self.position = random.randint(2,6)
return self.position
def play(self):
for z in self.playerList:
while self.position2 < 100:
#print(z + " is walking")
self.position2 += self.walk()
self.bname = z
print("\nBluePlayer winner is " + self.bname + " with distance covered " +str(self.position2)+ " miles.")
red_start = int(input("How many red players do you want? "))
while True:
if red_start == 0:
break
for i in range (1,red_start+1):
red_name = input("Name for red player " + str(i) + ": ")
#self.playerList.append(self.red_name)
r = RedPlayer(red_name)
#Player.playerList.append(r)
#print(playerList[1])
red_start-=1
#r.playerList()
blue_start = int(input("How many blue players do you want? "))
while True:
if blue_start == 0:
break
for i in range (1,blue_start+1):
blue_name = input("Name for blue player " + str(i) + ": ")
b = BluePlayer(blue_name)
#Player.playerList.append(b)
#print(playerList[1])
blue_start-=1
r.play()
b.play()
|
f080018db0b2ddf2b1604974417db175a2d852c9 | dkarthicks27/ML_Database | /codeforces/rewards.py | 752 | 4.09375 | 4 | from math import ceil
if __name__ == '__main__':
# lets find out the number of shelves available
# so we know the number of medals and number of number of cups
# first we check if there are atleast 2 shelves, one for each type
# now we first calculate the number of medals, if
# if medals = 15
# no. of rows = math.ceil(18 / 10) = 2
# so now if this is greater than n: print(no) else check if
# remaining rows >= math.ceil(cups/5)
cups = list(map(int, input().split()))
medals = list(map(int, input().split()))
k = int(input())
num_cup_rows = ceil(sum(cups)/5)
num_medal_rows = ceil(sum(medals)/10)
if num_cup_rows + num_medal_rows <= k:
print('YES')
else:
print('NO')
|
56d4eb892050e457cfaae7e78a0d2a9803ed2aa3 | mhcrnl/Phonebook-20 | /db_phonebook.py | 1,301 | 4.125 | 4 | import sqlite3
class Contact:
def __init__(self):
self.contact = input('Enter username: ')
self.number = input('Enter phone number: ')
class Phonebook:
db = sqlite3.connect('Phonebook.sqlite3')
c = db.cursor()
def __init__(self):
pass
#self.contacts = Phonebook.c.execute('select * from PhoneBook')
#def __repr__(self):
#return repr(self.contacts)
#def __str__(self):
#return '{}'.format(self.contacts)
@staticmethod
def create_table():
Phonebook.c.execute('create table PhoneBook (id integer primary key autoincrement,'
' name varchar(20), number integer)')
def add_contact(self, Contact):
Phonebook.c.execute("insert into PhoneBook (name, number) values ('{}', '{}')"
.format(Contact.contact, Contact.number))
def show_contacts(self):
#by row
print(Phonebook.c.execute("select * from PhoneBook"))
print(Phonebook.c.fetchall())
def delete_contact(self):
input_contact = input("What contact do u want do delete? ")
Phonebook.c.execute("delete from PhoneBook where name='{}'".format(input_contact))
a = Contact()
b = Phonebook()
b.add_contact(a)
b.show_contacts()
b.delete_contact()
|
e31aa8252c0fbb783203e317fb7adc26ec5a88c2 | hakanguner67/class2-functions-week04 | /reading_number.py | 525 | 4.3125 | 4 | '''
Write a function that gives the reading of entered any two-digit number.
For example: 28---------------->Twenty Eight
'''
small_numbers = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine"]
big_numbers = ["Ten","Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety"]
def reading_number(number) :
first = number % 10
second = number // 10
return big_numbers[second] + " " + small_numbers[first]
number = int(input("Enter a Two Digit Number : "))
print(reading_number(number)) |
9a5c7031c81722f2c910d31c5be7c1c2f4925caf | choroba/perlweeklychallenge-club | /challenge-181/lubos-kolouch/python/ch-1.py | 906 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def order_sentence(paragraph: str) -> str:
sentences = paragraph.split(".")
ordered = []
for sentence in sentences:
if sentence.strip() == "":
continue
words = sorted(sentence.split())
ordered.append(" ".join(words) + ".")
return " ".join(ordered)
# Tests
assert (
order_sentence("All he could think about was how it would all end.")
== "All about all could end he how it think was would."
)
assert (
order_sentence(
"There was still a bit of uncertainty in the equation, but the basics were there for anyone to see."
)
== "There a anyone basics bit but equation, for in of see still the the there to uncertainty was were."
)
assert (
order_sentence("The end was coming and it wasn't going to be pretty.")
== "The and be coming end going it pretty to was wasn't."
)
|
4f8d091dff68c6b6ffc80142fd838d5fbe73a1bc | TheAlgorithms/Python | /strings/boyer_moore_search.py | 2,742 | 4.125 | 4 | """
The algorithm finds the pattern in given text using following rule.
The bad-character rule considers the mismatched character in Text.
The next occurrence of that character to the left in Pattern is found,
If the mismatched character occurs to the left in Pattern,
a shift is proposed that aligns text block and pattern.
If the mismatched character does not occur to the left in Pattern,
a shift is proposed that moves the entirety of Pattern past
the point of mismatch in the text.
If there no mismatch then the pattern matches with text block.
Time Complexity : O(n/m)
n=length of main string
m=length of pattern string
"""
from __future__ import annotations
class BoyerMooreSearch:
def __init__(self, text: str, pattern: str):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(text), len(pattern)
def match_in_pattern(self, char: str) -> int:
"""finds the index of char in pattern in reverse order
Parameters :
char (chr): character to be searched
Returns :
i (int): index of char from last in pattern
-1 (int): if char is not found in pattern
"""
for i in range(self.patLen - 1, -1, -1):
if char == self.pattern[i]:
return i
return -1
def mismatch_in_text(self, current_pos: int) -> int:
"""
find the index of mis-matched character in text when compared with pattern
from last
Parameters :
current_pos (int): current index position of text
Returns :
i (int): index of mismatched char from last in text
-1 (int): if there is no mismatch between pattern and text block
"""
for i in range(self.patLen - 1, -1, -1):
if self.pattern[i] != self.text[current_pos + i]:
return current_pos + i
return -1
def bad_character_heuristic(self) -> list[int]:
# searches pattern in text and returns index positions
positions = []
for i in range(self.textLen - self.patLen + 1):
mismatch_index = self.mismatch_in_text(i)
if mismatch_index == -1:
positions.append(i)
else:
match_index = self.match_in_pattern(self.text[mismatch_index])
i = (
mismatch_index - match_index
) # shifting index lgtm [py/multiple-definition]
return positions
text = "ABAABA"
pattern = "AB"
bms = BoyerMooreSearch(text, pattern)
positions = bms.bad_character_heuristic()
if len(positions) == 0:
print("No match found")
else:
print("Pattern found in following positions: ")
print(positions)
|
294b3b0f33fa9441c74e627c64478d2a6fb9762e | phillipad7/RideCrossRiver | /start_search_ui.py | 2,731 | 3.921875 | 4 |
import bunch_outputs
def get_num_of_addresses() -> int:
'''
Return the number of addresses the search will encounter
'''
while True:
try:
num_of_addresses = int(input())
if num_of_addresses > 1:
return num_of_addresses
else:
print('You must specify at least two locations')
except:
print('The first line must specify a positive integer number of locations.')
def get_addresses(this_many: int) -> list:
'''
Return a list of addresses with this_many from user input
'''
add_list = []
for number in range(this_many):
add_list.append(input())
return add_list
def get_num_of_outputs() -> int:
'''
Return the number of desired outputs the search would like to show
'''
try:
num_of_addresses = int(input())
if num_of_addresses > 0:
return num_of_addresses
else:
print('ERROR10: There must be a positive integer number of generators.')
except ValueError:
print('ERROR12: There must be a positive integer number of generators.')
def get_desired_outputs(add_list: [], this_many: int):
'''
Print out the search result with user desired categories,
'''
output_choices = {'STEPS': bunch_outputs.STEPS(),
'TOTALTIME': bunch_outputs.TOTALTIME(),
'LATLONG': bunch_outputs.LATLONG(),
'ELEVATION': bunch_outputs.ELEVATION(),
'TOTALDISTANCE': bunch_outputs.TOTALDISTANCE()
}
desired_output = []
if _is_int(this_many):
try:
for number in range(this_many):
t = input()
desired_output.append(output_choices[t])
except KeyError:
if t == '':
print('Invalid output type: undefined')
else:
print('invalid output type: {}'.format(t))
else:
for i in desired_output:
i.print_out(add_list)
def display_copyright() -> None:
'''
Print copyright statement
'''
print('\nDirections Courtesy of MapQuest; Map Data Copyright OpenStreetMap Contributors')
def _is_int(numb) -> bool:
'''
Return True if the given parameter is integer, return False if not
'''
if type(numb) == int:
return True
else:
return False
if __name__ == '__main__':
try:
address_list = get_addresses(get_num_of_addresses())
num_of_output = get_num_of_outputs()
get_desired_outputs(address_list, num_of_output)
except:
print('\nNO ROUTE FOUND')
else:
display_copyright()
|
b145b007ce225549565552ec9848af78d752f5a6 | venkatmanisai/Sosio_tasks | /Sosio/find_angle_MBC.py | 119 | 3.6875 | 4 |
import math
a = float(input())
b = float(input())
print(str(int(round(math.degrees(math.atan2(a,b)))))+'°')
|
f3dcd01e01a9b4f5b10b4194793102223ae5b842 | jim-huang-nj/BeginningPython | /MagePython/Chapter3/3-9.py | 446 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Jim Huang
@contact:Jim_Huang@trendmicr.com
@version: 1.0.0
@license: Apache Licence
@file: 3-9.py
@time: 2020/12/1 16:31
"""
import random
import string
words = []
counter = {}
alpha = string.ascii_lowercase
for _ in range(100):
words.append(random.choice(alpha) + random.choice(alpha))
for i in words:
counter[i] = counter.get(i,0) + 1
print(counter)
print(sorted(counter.items(),reverse=True)) |
d6fc9277b1232dd4823bd7b8e583ad36e35dff29 | friedlich/python | /19年7月/7.13/实例037:排序.py | 383 | 3.71875 | 4 | # 题目 对10个数进行排序。
# 程序分析 同实例005。
raw = []
for i in range(10):
num = int(input('int{}:'.format(i)))
raw.append(num)
for i in range(len(raw)):
for j in range(i,len(raw)):
if raw[i] > raw[j]: # raw[i]要放前面,因为第一个raw[i]是raw[0],是依照raw[i]来排序的
raw[i],raw[j] = raw[j],raw[i]
print(raw)
|
8175002f0a03ba19ac5fd536af4d62fc58938555 | whywhs/Leetcode | /Leetcode409_E.py | 493 | 3.734375 | 4 | # 最长回文串。这个题目就是需要统计偶数次的个数,但是注意的是对于奇数次的不是不统计而是减一即可。
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
l = 0
for i in set(s):
num = s.count(i)
if num%2==0:
l += num
else:
l += num-1
if l>=len(s):
return l
return l+1 |
9be652ba391fc654c3df3cb454ce2f6c293992c9 | Rickym270/rickym270.github.io | /data/projects/InterviewStudying/DailyCodingChallenge/April202022.py | 2,491 | 4.21875 | 4 | '''
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ \
1 0
/ \
1 0
/ \
1 1
'''
# TODO: Define the Node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.root = None
# TODO: Define a function that takes in a root and count
def count_unival_subtrees_helper(root, count):
# TODO: Perform base check
if not root:
return 0
left = count_unival_subtrees_helper(root.left, count)
right = count_unival_subtrees_helper(root.right, count)
# TODO: Check if unival
if left and root.left.data != root.data:
return False
if right and root.right.data != root.data:
return False
count[0] += 1
return True
# TODO: Define a function that takes in a root
def count_unival_subtrees(root):
count = [0]
if not root:
return 0
count_unival_subtrees_helper(root, count)
return count[0]
class Node:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
def count_unival_subtrees_helper(root, count):
# TODO: Check root is not None
if root is None:
return 0
# TODO: Search left and right
left = count_unival_subtrees_helper(root.left, count)
right = count_unival_subtrees_helper(root.right, count)
# TODO Check if left or right exist
if left == None or right == None:
return False
# TODO: Check left side matches current
if left and root.left.data != root.data:
return False
if right and root.right.data != root.data:
return False
count[0] += 1
return True
def count_unival_subtrees(root):
# TODO: Start the count
count = [0]
# TODO: Call helper function
count_unival_subtrees_helper(root, count)
return count[0]
if __name__ == "__main__":
"""Let us construct the below tree
5
/ \
4 5
/ \ \
4 4 5
"""
root = Node(5)
root.left = Node(4)
root.right = Node(5)
root.left.left = Node(4)
root.left.right = Node(4)
root.right.right = Node(5)
count_unival_subtrees(root)
print("Count of Single Valued Subtrees is", count_unival_subtrees(root))
|
882a93ac2d818ba1faa047660a5b3045842811a1 | adilshivakumar/Raspberry-Pi | /clock.py | 503 | 3.78125 | 4 | import time
from datetime import datetime
def clock():
"""
Display current time on device.
"""
interval = 0.5
seconds = 5
cl = ""
for i in range(int(seconds / interval)):
now = datetime.now()
cl = cl + now.strftime("%H-%M-%S") + "\n"
# calculate blinking dot
if i % 2 == 0:
cl = cl + now.strftime("%H-%M-%S") + "\n"
else:
cl = cl + now.strftime("%H %M %S") + "\n"
time.sleep(interval)
return cl
|
42e3403c5f66f88146b568daf3da2a879e17fa9f | lokesh-rajendran/python-datastructures-algorithms | /arrays/sorted_squared_array.py | 877 | 4.15625 | 4 | """
Write a function that takes in a non-empty array of integers that are sorted in ascending order and returns a new array of the same length with the squares of the original integers also sorted in ascending order.
Sample Input
array = [1, 2, 3, 5, 6, 8, 9]
Sample Output
[1, 4, 9, 25, 36, 64, 81]
"""
import pytest
def sorted_squared_array(arr):
"""Squares the elements of given array and sorts the squared elements
in ascending order.
Args:
arr (list): given list of elements to be sorted
"""
squared_list = list(map(lambda x: x*x, arr))
squared_list.sort()
return squared_list
@pytest.mark.parametrize("arr, expected", [
([-7,1,2,3,-1, -2, -3], [1, 1, 4, 4, 9, 9, 49]),
([1, 2, 3, 5, 6, 8, 9], [1, 4, 9, 25, 36, 64, 81])
])
def test_sorted_squared_array(arr, expected):
assert sorted_squared_array(arr) == expected |
42e811965908b4f58f0f52d91f9f32c470564b8c | ysung/UCD | /Algorithm/python/twoSum.py | 2,811 | 3.5 | 4 | #!/usr/bin/python
Two Sum,
Complexity: O(N log N)
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
#targetList = [i for i in num if i <= target]
numbers = sorted(num)
head = 0
tail = len(num)-1
while (numbers[head] + numbers[tail]) != target:
# or head < tail
if (numbers[head] + numbers[tail]) > target:
tail -= 1
elif (numbers[head] + numbers[tail]) < target:
head += 1
else:
break
# find out the original index
num1 = [i for i, x in enumerate(num, start=1) if x == numbers[head]][0]
num2 = [i for i, x in enumerate(num, start=1) if (x == numbers[tail] and i != num1)][0]
# decide the smaller index
if num1 < num2:
return (num1, num2)
else:
return (num2, num1)
## Two Sum,
## Complexity: O(N), still working
# class Solution:
# # @return a tuple, (index1, index2)
# def twoSum(self, num, target):
# targetNum = [target - i for i in num]
# targetDict = {x: targetNum.count(x) for x in targetNum}
# if (target//2) in targetDict and targetDict[target//2] == 2:
# num1 = [key for key, value in targetDict.items() if value == 2]
# index1, index2 =[i for i, x in enumerate(num, start=1) if x == num1[0]]
# print(index1, index2)
# else:
# for i in range(len(targetNum)):
# if targetNum[i] != target / 2 and targetNum[i] in num:
# index1 = num.index(num[i])
# index2 = num.index(targetNum[i])
# break
# if index1 < index2:
# return (index1, index2)
# else:
# return (index2, index1)
## Sample Solution ##
# Complexity: O(N log N)
# class Solution:
# # @return a tuple, (index1, index2)
# def twoSum(self, num, target):
# numbers = sorted(num)
# length = len(num)
# left = 0
# right = length - 1
# index = []
# while left < right:
# sums = numbers[left] + numbers[right]
# if sums == target:
# for i in range(length):
# if num[i] == numbers[left]:
# index.append(i + 1)
# elif num[i] == numbers[right]:
# index.append(i + 1)
# if len(index) == 2:
# break
# break
# elif sums > target:
# right -= 1
# else:
# left += 1
# result = tuple(index)
# return result |
cdef74d4bebe249c2603bee436a215a6302681ea | parveez1shariff/Python-Testing | /Infi_arug.py | 315 | 3.8125 | 4 | # This code is to create a function with infinite parameter/arguments
def mean(*arg):
Mn = sum(arg)/len(arg)
return Mn
print(mean(2,4,9,8))
def str_infi(*arg):
st = []
for temp in arg:
st.append(str(temp).capitalize())
st.sort()
return st
print(str_infi("hello", "apple")) |
e68c9c91b2204fd09c20beb88acb6d0649655636 | hanzhi713/thinkcs-python3-solutions | /Chapter 18/1.py | 503 | 3.59375 | 4 | import turtle
Tom = turtle.Turtle()
Tom.speed(0)
Tom.hideturtle()
sc = turtle.Screen()
def koch(t, order, size):
if order == 0:
t.forward(size)
else:
for angle in [60, -120, 60, 0]:
koch(t, order - 1, size / 3)
t.left(angle)
def shape(t, order, size, sides):
for i in range(sides):
koch(t, order, size)
t.right(360 / sides)
size = 400
Tom.penup()
Tom.goto(-size / 2, size / 2)
Tom.pendown()
shape(Tom, 3, size, 3)
sc.mainloop()
|
a77746a03ea733d9dcd85830d5ef0bdfdbfe2165 | joaopedropinheiro12/IntroPython | /aula8_Joao_Pedro.py | 964 | 3.734375 | 4 | #AULA 8
#JOÃO PEDRO GOMES PINHEIRO
#03 de novembro de 2018
import math
#EXERCÍCIO 1
print('Exercício 1: ')
n = 600
while (n>1):
print(n)
if n % 2 == 0:
n = n/2
elif n % 2 == 1 and n != 1:
n=3*n+1
print(n)
#EXERCÍCIO 2
print('Exercício 2: ')
def counter(n):
count = 0
while n!=0:
if n % 5 == 0:
count = count + 1
n = n // 10
return count
print(counter(710580))
#EXERCÍCIO 3
print('Exercício 3: ')
def par_impar(lista):
for i in range(len(lista)):
if lista[i] % 2 == 1: # If the number is odd
print(lista[i], 'é ímpar')
elif lista[i] % 2 == 0: # If the numbar isn't odd
print(lista[i], 'é par')
lista = [3,6,4,56,12,75,2,8,13,65,87]
par_impar(lista)
#EXERCÍCIO 4
print('Exercício 4: ')
def raiz_quadrada(lista):
for i in range(len(lista)):
n = lista[i]/2
while (n**2 - lista[i]) > 0.001:
n = n - (n**2-lista[i])/(2*n)
print('a raiz quadrada de ', lista[i], 'é: ', n)
lista = [6, 16, 19, 25, 36]
raiz_quadrada(lista) |
034fe0cbde4c81adda986b9ec3955acd08aab48b | Kanino19/LearnPython | /operadores.py | 885 | 4.0625 | 4 | # OPERADORES
# ----- Datos -----
a = 3
b = 4
c1 = 'Hola'
c2 = 'Comida'
bT = True
bF = False
# == : Igualdad
# = es de asignación (Guardar información)
# La igualdad me brinda boleanos (es decir True o False)
print(a==b)
print(c1 == c2)
print(c1 == 'Hola')
print(bT == bF)
# Notita: estos pueden ser usados con if, else o elif.
# +,-,*,/ : Operaciones básicas
print(a+b,a-b,a*b,a/b)
print(a/b) # división real
print(a//b) # división entera
print(4/2)
print(4/2== 2)
print(4//2)
arr = range(10)
print (arr[10//2])
print (c1 + c2)
#print (c1 - c2) #no se puede restar cadena con cadena
#print (c1*c2) # no se puede multiplicar cadena con cadena
#print (c1/c2) #no se puede divider cadena con cadena
print (a*c1)
# **, % : Exponenciación y módulo
print(a**b) # a: base, b: exponente
x = 3
y = 10
for i in range(y):
print('%i = %i (mod %i)'%(i,i%x,x))
|
77acd760c52a24aaf2d9b8d733d681ae6b3f114f | zongyi2020/CMEECourseWork | /week2/code/cfexercises1.py | 1,270 | 4.1875 | 4 | #~!/usr/bin/env python3
"""Some functions doing arithmatic."""
__appname__ = 'cfexercises1'
__author__ = 'Zongyi Hu (zh2720@ic.ac.uk)'
__version__ = '0.0.1'
import sys
"""function sqrt"""
def foo_1(x = 1):
return x ** 0.5
foo_1(3)
foo_1(9)
foo_1(49)
"""function compare two numbers"""
def foo_2(x=1, y=1):
if x > y:
return x
return y
foo_2(2,3)
foo_2(3,2)
"""bubble sort"""
def foo_3(x=1, y=1, z=1):
if x > y:
tmp = y
y = x
x = tmp
if y > z:
tmp = z
z = y
y = tmp
return [x, y, z]
foo_3(1, 3, 2)
"""factorial"""
def foo_4(x=1):
result = 1
for i in range(1, x + 1):
result = result * i
return result
"""factorial"""
def foo_5(x=1):# a recursive function that calculaes the facrotial of x
if x == 1:
return 1
return x * foo_5(x - 1)
"""factorial"""
def foo_6(x=1): # Calculate the factorial of x in a different way
facto = 1
while x >= 1:
facto = facto * x
x = x - 1
return facto
"""main function"""
def main(argv):
print(foo_1())
print(foo_2())
print(foo_3())
print(foo_4())
print(foo_5())
print(foo_6())
return(0)
if __name__ == "__main__":
status = main(sys.argv)
sys.exit(status) |
bc2e151f43088a16e74f43fa5f5c46ddf7e0ce78 | redx14/LeftOrRightArrow | /LeftorRightArrow.py | 1,420 | 4.15625 | 4 | #Andrey Ilkiv midterm exam question 2
direction = input("Please enter a direction ( l / r ): ")
cols = int(input("Please enter an integer (>=0): "))
while(direction != "l" and direction != "r"):
print("Invalid Entry! Try Again!")
direction = input("Please enter a direction ( l / r ): ")
while(cols < 0):
print("Invalid Entry! Try Again!")
cols = int(input("Please enter an integer (>=0): "))
cols = cols - 1
if cols != 0:
if direction == "r" :
#upper
for i in range(0 , cols):
for j in range(0 , i):
print(" ", end="")
for k in range(1 , 2):
print("*" , end="")
print()
#lower
for i in range(0 , cols + 1):
for j in range(0 , cols - i):
print(" " , end="")
for k in range(1 , 2):
print("*" , end="")
print()
if direction == "l" :
#lower
for i in range(0 , cols + 1):
for j in range(0 , cols - i):
print(" " , end="")
for k in range(1 , 2):
print("*" , end="")
print()
#upper
for i in range(1 , cols+1):
for j in range(0 , i):
print(" ", end="")
for k in range(1 , 2):
print("*" , end="")
print()
|
c686a5ca1fc60b2a9f1de02c1694edc2c5df9eb3 | mankamolnar/python-4th-tw-mentors-life-crazy-edition | /llama.py | 1,105 | 3.6875 | 4 | import random
from codecool_class import *
class Llama:
def __init__(self, name, color):
self.name = name
self.color = color
self.softness = 10
def pet(self):
self.softness -= 1
self.check_if_dead()
def ride(self):
self.softness -= 2
self.check_if_dead()
def got_massage(self):
self.softness += 3
def introduce_llama(self):
print("Hi, I am %s the llama. You can pet me, or ride me to gain some energy!\nBe careful, if you ride or pet me too much, I may die!" % self.name)
print()
def check_if_dead(self):
if self.softness < 1:
print("%s is dead :(" % self.name)
def llama_goes_insane(self, codecool_class):
if random.choice([1, 2]) == 2:
codecool_class.mentors = []
codecool_class.students = []
print("%s goes insane!! It killed the whole class!" % self.name)
print("There are %d mentors and %d students left." %
(len(codecool_class.mentors), len(codecool_class.students)))
print()
|
c8943c684bb5f4f0cdbed7f513ee9e01fbb55e1a | csbuja/myCipher | /p1_robot.py | 2,906 | 3.96875 | 4 | import sys
class Robot(object):
def __init__(self):
self.inputString = ''
self.x = 0
self.y = 0
self.direction = 'N'
def printBot(self):
print (str(self.x) + ' ' + str(self.y) + ' ' + self.direction)
def readIn(self):
self.inputString = sys.stdin.readline().rstrip('\n')
def followInputDirections(self):
for val in self.inputString: #make the robot move!
self.movePosition(val)
def movePosition(self, char):
if char == 'C': #clockwise
if self.direction == 'N':
self.direction = 'NE'
elif self.direction == 'NE':
self.direction = 'E'
elif self.direction == 'E':
self.direction = 'SE'
elif self.direction == 'SE':
self.direction = 'S'
elif self.direction == 'S':
self.direction = 'SW'
elif self.direction == 'SW':
self.direction = 'W'
elif self.direction == 'W':
self.direction = 'NW'
elif self.direction == 'NW':
self.direction = 'N'
else:
# This is where an error message would go.
return
elif char == 'A': #counter-clockwise
if self.direction == 'N':
self.direction = 'NW'
elif self.direction == 'NE':
self.direction = 'N'
elif self.direction == 'E':
self.direction = 'NE'
elif self.direction == 'SE':
self.direction = 'E'
elif self.direction == 'S':
self.direction = 'SE'
elif self.direction == 'SW':
self.direction = 'S'
elif self.direction == 'W':
self.direction = 'SW'
elif self.direction == 'NW':
self.direction = 'W'
else:
# This is where an error message would go.
return
elif char == 'S': #step
if self.direction == 'N':
self.y += 1
elif self.direction == 'NE':
self.x += 1
self.y += 1
elif self.direction == 'E':
self.x += 1
elif self.direction == 'SE':
self.x += 1
self.y -= 1
elif self.direction == 'S':
self.y -= 1
elif self.direction == 'SW':
self.x -= 1
self.y -= 1
elif self.direction == 'W':
self.x -= 1
elif self.direction == 'NW':
self.x -= 1
self.y += 1
else:
# This is where an error message would go.
return
else:
# This is where an error message would go.
return
|
48e69d600998dd9721c49840fd3da124ee6ed3c1 | qianlongzju/project_euler | /python/PE055.py | 392 | 3.546875 | 4 | #!/usr/bin/env python
def isPalindrome(n):
if str(n)[::-1] == str(n):
return True
return False
def isLychrel(n):
count = 49
while count > 0:
n += int(str(n)[::-1])
if isPalindrome(n):
return False
count -= 1
return True
def main():
print sum(1 for i in range(10000) if isLychrel(i))
if __name__ == '__main__':
main()
|
125b8eac6b573eaa1095fcd47aa1be16d690d813 | Nedashkivskyy/NedashkivskyyV | /Лабараторна 3 Недашківський.py | 446 | 4.03125 | 4 | height = int(input("Ваш рост"))
weight = int(input("Ваш вес"))
bmi = (weight/height**2)*10000
bmi2 = round(bmi,2)
print('Ваш индекс массы тела:',bmi2)
if bmi2 < 18.5:
print('Ваш индекс массы тела ниже нормы')
elif bmi2 > 24.9:
print('Ваш индекс массы тела выше нормы')
else:
print('Ваш индекс массы тела в норме')
|
426e2da138f2a8536ba201d2100fd5ce9f87ea5d | yiflylian/pythonstuday | /pythonstudy/basic/forandwhile.py | 2,599 | 3.953125 | 4 | #https://www.liaoxuefeng.com/wiki/1016959663602400/1017100774566304
print(r'''
Python的循环有两种,一种是for...in循环,依次把list或tuple中的每个元素迭代出来,看例子:
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
执行这段代码,会依次打印names的每一个元素:
Michael
Bob
Tracy
所以for x in ...循环就是把每个元素代入变量x,然后执行缩进块的语句。
再比如我们想计算1-10的整数之和,可以用一个sum变量做累加:
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)
如果要计算1-100的整数之和,从1写到100有点困难,幸好Python提供一个range()函数,可以生成一个整数序列,再通过list()函数可以转换为list。比如range(5)生成的序列是从0开始小于5的整数:
>>> list(range(5))
[0, 1, 2, 3, 4]
range(101)就可以生成0-100的整数序列,计算如下:
# -*- coding: utf-8 -*-
sum = 0
for x in range(101):
sum = sum + x
print(sum)
''')
names=['michael','Bob','tracy']
for name in names:
print(name)
print(r''' range()函数 比如range(5)生成的序列是从0开始小于5的整数''')
print(r'''
for i in range(101):
sum+=i
print(sum)
''')
sum =0
for i in range(101):
sum+=i
print(sum)
print(r'''
第二种循环是while循环,只要条件满足,就不断循环,条件不满足时退出循环。比如我们要计算100以内所有奇数之和,可以用while循环实现:
sum =0
n=99
while n>0:
sum = sum+n
n=n-2
print(sum)
''')
sum =0
n=99
while n>0:
sum = sum+n
n=n-2
print(sum)
print(r'''
L = ['Bart', 'Lisa', 'Adam']
for name in L:
print('Hello,',name,'!')
''')
L = ['Bart', 'Lisa', 'Adam']
for name in L:
print('Hello,',name,'!')
print(r'''
循环是让计算机做重复任务的有效的方法。
break语句可以在循环过程中直接退出循环,而continue语句可以提前结束本轮循环,并直接开始下一轮循环。这两个语句通常都必须配合if语句使用。
要特别注意,不要滥用break和continue语句。break和continue会造成代码执行逻辑分叉过多,容易出错。大多数循环并不需要用到break和continue语句,上面的两个例子,都可以通过改写循环条件或者修改循环逻辑,去掉break和continue语句。
有些时候,如果代码写得有问题,会让程序陷入“死循环”,也就是永远循环下去。这时可以用Ctrl+C退出程序,或者强制结束Python进程。
请试写一个死循环程序。
''') |
ab3022f2d490978ad29a13b9d619d95559c1d0df | sandeepsharma1190/Numpy | /Numpy.py | 2,491 | 4.09375 | 4 | import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.array([1,3,5], dtype = 'int16')
print(a)
a.ndim #to check dimension
a.shape #to check shape
a.dtype #to check datatype
a.itemsize # for item size
a.size #to get full size
a = np.array([[1,2,3,4], [5,6,7,8]])
print(a)
# to get a specific element [Rows, columns]
a[1,2]
a[0,:] #to get specific row (row 1)
a[:,2] #to get specific row (column 3)
a[0,1:4:2] # start, end, step
my_list = [1,2,3,4,5,6]
array = np.array(my_list, dtype = int) #dtype not mendatory, but we can explicitly assign datatype using this
print(array)
print(type(array))
array2 = array.reshape(3,2)
print(array2)
array2.shape #will return the shape of an array
array3 = array.reshape(3,-1)
# 2d array
list1 = [[1,1,1],[2,2,2],[3,3,3]]
arr2d = np.array(list1)
type(arr2d)
print (arr2d[0]) #[1 1 1] first line of matrix
print (arr2d[0][0]) #to pull 1 value in 1 line
#[0][0] rows- [0] and columns - [0]
print(arr2d.dtype)
# Boolean
boolarr = arr2d<3
print (boolarr)
arr2d[boolarr]
# will show true bools
# for 1-d array single round bracket
# for 2-d array double round bracker
# for 3-d array three round bracker
np.zeros((3,3))
np.zeros(((3,3,3,)))
np.zeros((3,3)) + 5
arr2d_2 = np.array(list1, dtype = float)
print (arr2d_2)
'''to convert dtype'''
arr2d_2.astype('int')
'''to convert into list'''
arr2d_2.tolist()
#to reverse
arr2d[::-1]
arr2d[::-1, ]
arr2d[::-1, ::-1]
'''Nested python lists'''
#my_list1 = [1,2,3,4,5]
#my_list2 = [2,3,4,5,6]
#my_list3 = [9,5,7,3,4]
#
#new_array = np.array[my_list1, my_list2, my_list3]
#print(new_array)
#print(new_array.shape)
# 3d array
x = [[[1,2,3],[1,2,3],[1,2,3]], [[1,2,3],[1,2,3],[1,2,3]], [[1,2,3],[1,2,3],[1,2,3]]]
y = np.array(x)
print (y)
# question
r = range(0, 24)
a = np.arange(24)
print (a)
print (a.ndim)
b = a.reshape(6,4,1)
# to create a 3d array
import array as arr
import numpy as np
arr1 = np.array([[1,2,3,4,5,6], [4,5,6,7,8,9]])
# for 2d
arr2 = arr1.reshape(3,4)
# for 3d
arr3d = arr1.reshape(3,2,2)
'''(in (3,2,2) - we have three 3d array, each with 2 rows
(1-d array) and 2 columns (each 1-d array with 2 values))'''
# 3x3 numpy array of all values equal = true
np.full((3,3), True)
# By using which syntax you can replace all odd number in the given array with -1
arr[arr%2 ==1] = -1
|
3ac21d578e22c759c0a97b5beaec624333f236f9 | abhi1540/PythonConceptExamples | /getter_setter.py | 2,953 | 4.0625 | 4 |
class Employee(object):
def __init__(self, emp_id, first_name, last_name, salary, age):
self._emp_id = emp_id
self._first_name = first_name
self._last_name = last_name
self._salary = salary
self._age = age
@property
def emp_id(self):
return self._emp_id
@emp_id.setter
def emp_id(self, emp_id):
self._emp_id = emp_id
@property
def first_name(self):
return self._first_name
@first_name.setter
def first_name(self, first_name):
self._first_name = first_name
@property
def last_name(self):
return self._last_name
@last_name.setter
def last_name(self, last_name):
self._last_name = last_name
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, salary):
self._salary = salary
@property
def age(self):
return self._age
@age.setter
def age(self, age):
if age > 18:
self._age = age
else:
raise ValueError("Enter age greater than 18")
def __str__(self):
return '{}-{}-{}-{}-{}'.format(self._emp_id, self._first_name, self._last_name, self._salary, self._age)
obj = Employee(1, 'abhisek', 'gantait', 10000, 28)
obj.__age = 30
print(obj) ## it will print 28 because you can't set the value outside
# output: 1-abhisek-gantait-10000-28
# MyClass.__private just becomes MyClass._MyClass__private
class A(object):
def __method(self):
print("I'm a method in A")
def method(self):
self.__method()
class B(A):
def __method(self):
print("I'm a method in B")
a = A()
a.method() #I'm a method in A
b = B()
b.method() #I'm a method in A
# def our_decorator(func):
# def function_wrapper(x):
# print("Before calling " + func.__name__)
# func(x)
# print("After calling " + func.__name__)
#
# return function_wrapper
#
#
# def foo(x):
# print("Hi, foo has been called with " + str(x))
#
#
# print("We call foo before decoration:")
# foo("Hi")
#
# print("We now decorate foo with f:")
# foo = our_decorator(foo)
#
# print("We call foo after decoration:")
# foo(42)
def log_instance(my_log):
def outerwrapper(cls_):
def wrapper_method(self):
my_log.info(
'Instance of {name} @ {id:X}: {dict}'.format(name=cls_.__name__, id=id(self), dict=repr(self.__dict__)))
cls_.log_instance = wrapper_method
cls_.log_instance.__name__ = 'log_instance'
cls_.log_instance.__doc__ = 'Generate log message with the details of this instance'
return cls_
return outerwrapper
import logging
mylog = logging.getLogger('my_logger')
mylog.setLevel(logging.INFO)
@log_instance(mylog)
class Hello(object):
def __init__(self, str):
self.str = str
def speak(self):
print('Hello {}'.format(self.str))
inst = Hello('Tony')
inst.speak() |
5b436941757a98c7bc3977f0ac5ac2ba153b881c | RunningLeon/ud120-projects | /text_learning/nltk_stopwords.py | 380 | 3.578125 | 4 | #!/usr/bin/python
###import nltk package and find how many stopwords
from nltk.corpus import stopwords
# import nltk
# nltk.download()
sw = stopwords.words("english")
print len(sw)
# for s in sw :
# print s
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer( "english")
print stemmer.stem( "responsiveness" )
print stemmer.stem("germany")
|
e6cd92c79492d26c64a03e7b61ab7bed21204655 | jennyChing/leetCode | /90_subsets2_recursive.py | 1,596 | 3.78125 | 4 | '''
90. Subsets II
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
'''
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
index = i + 1 (index - 1 is the last one you select)
"""
# [Idea:] if you skip this one, if next one is duplicate one, you cannot choose it. So sort it and while recursing check if the current one is same as the last one, then skip it
res = []
# sort it to better check the duplication
nums = sorted(nums)
def __directed_dfs(level, path):
# complete a path whenever recursive is called
res.append(path)
# start for loop from new level
for i in range(level, len(nums)):
# [Special case to handle:] if the next one is a duplicated value and previous wan't selected: cannot select it! (must skip case)
if i > level and nums[i] == nums[i - 1]: # i > level: skipped
print(level, i, nums[i], nums[i - 1])
continue # need to skip this duplicate value as well
__directed_dfs(i + 1, path + [nums[i]]) # new level is (i + 1) not (level + 1)!
__directed_dfs(0, [])
return res
if __name__ == '__main__':
nums = [1, 2, 2]
res = Solution().subsetsWithDup(nums)
print(res)
|
cbf1c010f7f496445febe0561ef4945c1893ed90 | JordanVScher/Hangman-Text | /getWords.py | 2,057 | 3.5625 | 4 | #reads the json file and chooses a word
#also responsible for difficulty and category
from colorama import *
import json
import random
import sys
def getWords(dif = 0, cat = 0):
if dif is 0:
dif = askDifficulty()
if cat is 0:
cat = askCategory()
return openFile(dif, cat)
def openFile(dif, cat):
try:
file = "normalWords.json" # if difficulty equals 1
if dif == 2:
file = "hardWords.json"
mode = "cinema" # if category equals 1
if cat == 2:
mode = "literature"
with open(file + "") as data_file:
jsondata = json.load(data_file)
for i in jsondata[mode]:
print(i['word'])
# print(data)
a = random.choice(jsondata[mode])
print("O random é:" + a['word'])
return a, dif, cat
except: # catch every exception
e = sys.exc_info()[0]
print(Fore.LIGHTRED_EX, "Error : %s" % e)
print("Check if the json files are in the root with the proper name!")
def askCategory(): # asks for category
cat = 0
choice = False
while not choice:
try:
print(Fore.LIGHTCYAN_EX, "Choose your category:")
cat = input("1 - Cinema\n2 - Literature\n-->")
if int(cat) == 1 or int(cat) == 2:
choice = True
print("OK!\n")
else:
print(Fore.LIGHTRED_EX, "Invalid input!")
except:
print(Fore.LIGHTRED_EX, "Invalid input!")
return int(cat)
def askDifficulty(): # asks for difficulty
dif = 0
choice = False
while not choice:
try:
print(Fore.LIGHTCYAN_EX, "Choose your difficulty level:")
dif = input("1 - Normal\n2 - Hard\n-->")
if int(dif) == 1 or int(dif) == 2:
choice = True
print("OK!\n")
else:
print(Fore.LIGHTRED_EX, "Invalid input!")
except:
print(Fore.LIGHTRED_EX, "Invalid input!")
return int(dif)
|
bdbfc08945c47886350754ec91bbcfdb35a41851 | justinm0rgan/python_work | /chp6/polling.py | 784 | 3.9375 | 4 | # Use the code in fav_languages.py
# Make a list of people who should take the favorite languages poll.
# Include some names that are already in the dictionary and some that are not.
# Loop through the list of people who should take the poll.
# If they have already taken the poll, print a message thanking them for responding.
# If they have not yet taken the poll, print a message inviting them to take the poll.
fav_lang = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
'ryan': 'rust'
}
poll = {'jen', 'justin', 'edward', 'ryan', 'lou'}
for name in poll:
if name in fav_lang.keys():
print(f"{name.title()}, thanks for responding!")
if name not in fav_lang.keys():
print(f"{name.title()}, please take our poll by clicking on the link below!")
|
bb714a76db3bc5ad360b5eed7e1920d030f2fc11 | TsaiRenkun/coffee_machine_python | /Problems/Count up the squares/task.py | 208 | 3.78125 | 4 | # put your python code here
number = []
num = 0
squareSum = 0
while True:
num = int(input())
squareSum = squareSum + (num ** 2)
number.append(num)
if sum(number) == 0:
print(squareSum)
break
|
6618b693a1d0232df8c02aa63a3ad531ca296da1 | madanreddygov/Python-WorkSpace | /Dictionaries and Sets/challenge.py | 123 | 3.71875 | 4 |
myText = input("Please enter some text: ")
myList = set(myText).difference("aeiou")
print(myList)
print(sorted(myList)) |
1202b7d083debdfc861f8a1fc63a0c63c2c860dd | Krushnarajsinh/MyPrograms | /VariableTypesInOops.py | 2,035 | 4.40625 | 4 | #Two types of variables:-(1)class variable AND (2)Instance variable
class Student:
class_name="A" #The variables define outside the __init__() is called as class or static variables
def __init__(self,roll_no,marks):
self.roll_no=roll_no #instance variables always define inside __init__()method
self.marks=marks #Here self.roll_no and self.marks are instance variable
def show(self):
print(self.roll_no," Roll_Number get {} marks:".format(self.marks),"From class",Student.class_name)
s1=Student(12,88)
s2=Student(1,90)
s1.marks=92 #We can Access instance variable by using object, here we cange the value of mark for s1 student then it will not affects to s2 student's marks it remain same
s1.show()
s2.show()
#class variable can be accessed by class name as well as instance name but mostly we use class name to access class variable
#this calss variable is same for all the instances(s1,s2) that are created for the class(Student)
#If we change the value for class variable then it will affected for all the objects because it is class variable
print(id(s1.class_name)) #here both having same id because this class variable is created only once for all objects
print(id(s2.class_name))
s1.class_name="B"
print(s1.class_name) #when we change the value using object then it's changes only for that object
print(s2.class_name)
#Here Intially s1->A and s2->A but when we change class_name for s1 then s1->B but s2 still pointing s2->A
#But if we change the value using class name then it will change for both objects
Student.class_name="C" #It will not affects s1 class_name value because this s1 is now pointing s1->B
print(Student.class_name)
print(s2.class_name)
print(s1.class_name) #here value for s1=B because new memory is allocated to the s1->class_name
#We have two types of namespace in memory
#class namespace and instrance namespace
#class namespace is an area that store all the class variables
#instance namespace is an area that store all the instance variables |
f8c16333890a876379ed0675e6e552bcb9ce5478 | HRDI0/This_is_coding_test | /#This is coding test-imp_6.py | 533 | 3.828125 | 4 | #문자열 재정렬
#알파벳 대문자와 숫자(0~9)가 섞여서 입력된다. 이때 모든 알파벳을 오름차순으로 출력한후 모든 숫자를 더한 값을 뒤에 출력한다.
word = input()
alpha = []
num = 0
for char in word:
if char.isalpha():
alpha.append(char)
else:
num +=int(char)
alpha = sorted(alpha)
# print(''.join(alpha),num,sep='') #숫자가 없는 경우 이렇게 하면 뒤에 0이 출력된다.
if num != 0:
alpha.append(str(num))
print(''.join(alpha))
|
ac335d464c0ad3fc2b5168e83771284cf67f4c2d | ConorODonovan/pa2-elevator-project | /Elevator_Project/Building.py | 1,606 | 4.15625 | 4 | from Elevator import Elevator
from Customer import Customer
import random
class Building:
def __init__(self, floors):
self._floors = floors
self._customers_waiting = []
self._customers_arrived = []
def __str__(self):
return "Building with {} floors".format(self.floors)
@property
def floors(self):
"""Returns number of floors of Building instance"""
return self._floors
@floors.setter
def floors(self, new_value):
"""Allows user to change the number of floors to new_value"""
self._floors = new_value
@property
def customers_waiting(self):
"""Returns list of customers currently waiting for elevator"""
return self._customers_waiting
@property
def customers_arrived(self):
"""Returns list of customers that have arrived at their floor"""
return self._customers_arrived
# Create elevator
def create_elevator(self):
"""Creates an instance of Elevator"""
elevator_start_floor = random.randint(1, self._floors)
elevator = Elevator(elevator_start_floor, self._floors)
return elevator
def create_customers(self, num_customers):
"""Creates the specified number of customers and adds them to the customers_waiting list"""
for i in range(num_customers):
customer = Customer(random.randint(1, self.floors), random.randint(1, self.floors))
# For testing
print(customer)
self.customers_waiting.append(customer)
|
468f499b2240e3dde1ca3122b4ec8e27f5b87c4a | massey-high-school/2020-91896-7-assessment-phamm72230 | /04_Rectangle_Solver.py | 500 | 4 | 4 | # Rectangle
def arearectangle(w, l):
# Calculate the area
arearectangle = w * l
return arearectangle
def perimeterrectangle(w, l):
# Calculate the perimeter
perimeterrectangle = 2 * (w + l)
return perimeterrectangle
def mainrectangle():
w = float(input('Enter width of Rectangle: '))
l = float(input('Enter length of Rectangle: '))
print("Area of Rectangle:", arearectangle(w, l))
print("Perimeter of Rectangle:", perimeterrectangle(w, l))
mainrectangle()
|
39504847f097369fa955ac01c62abe446eb12f5b | LennyDuan/AlgorithmPython | /56. Merge Intervals/answer_po.py | 1,434 | 3.640625 | 4 | ## Possible but too much if else
def merge(self, intervals):
res = [intervals[0]]
for interval in intervals[1:]:
c_start, c_end = interval[0], interval[1]
for merged in res:
print('current: {}'.format(interval))
print('merged: {}'.format(merged))
m_start, m_end = merged[0], merged[1]
if m_start < c_start < m_end < c_end:
merged[1] = c_end
elif c_start < m_start < c_end < m_end:
merged[0] = c_start
elif c_start < m_start < c_end < m_end:
merged[0] = c_start
elif c_start < m_start < m_end < c_end:
merged[0], merged[1] = interval[0], interval[1]
elif c_start == m_start:
merged[1] = max(m_end, c_end)
elif c_start == m_end:
merged[1] = c_end
elif c_end == m_start:
merged[0] = c_start
elif c_end == m_end:
merged[0] = min(m_start, c_start)
elif m_start < c_start < c_end < m_end:
break
else:
res.append(interval)
break
return res
intervals = [[1, 4], [0, 5]]
# [[1,4],[0,2]]
# [[1,4],[0,1]]
# [[1,4],[4,5]]
# [[1,4],[1,5]]
# [[1, 3], [2, 6], [8, 10], [15, 18]]
# intervals = [[2, 6], [1, 3], [8, 10], [15, 18]]
# [[1,6],[8,10],[15,18]]
print(merge(None, intervals))
|
8e68038743d336dbc4808e603a4fc808d6466f91 | kienvu98/thuc_tap | /100 bài code/50_59ex/ex50.py | 1,518 | 3.515625 | 4 | import re
import sys
import os
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
def sent_segment(a_string):
sentences = []
regx = re.compile(r'([\.;:\?!])\s+([A-Z])')
m = regx.search(a_string)
last_pos = 0
pos = m.start() if m != None else None
while ( pos != None ):
s = a_string[last_pos:pos+1]
sentences.append(s)
last_pos = last_pos + m.end() - 1 if m != None else None
m = regx.search(a_string[last_pos:])
pos = last_pos + m.start() if m != None else None
return sentences
def unit_test():
a_string = 'Natural language processing (NLP) is a field of computer science, artificial intelligence, and linguistics concerned with the interactions between computers and human (natural) languages. As such, NLP is related to the area of humani-computer interaction; Many challenges in NLP involve natural language understanding, that is, enabling computers to derive meaning from human or natural language input, and others involve natural language generation. ABD? Minh! Yeu.'
print a_string
print
sentences = sent_segment(a_string)
print '\n'.join(sentences)
if __name__ == '__main__':
os.system('cls' if os.name == 'nt' else 'clear')
with open('../data/nlp.txt', 'rU') as f:
for line in f:
line = line.strip()
if line == '':
continue
sentences = sent_segment(line)
for s in sentences:
print s |
2d1c32c717a4c2483a7ef71cb0582351f47b94bd | jjst/advent-of-code-2017 | /day8/day8.py | 734 | 3.5625 | 4 | #!/usr/bin/python3
from collections import defaultdict
def execute_instruction(instruction, registers):
instr, condition = instruction.split(" if ")
condition_register = condition.split(" ")[0]
if eval(condition.replace(condition_register, str(registers[condition_register]))):
register_to_change, inc_or_dec, value = instr.split(" ")
if inc_or_dec == "inc":
registers[register_to_change] += int(value)
else:
registers[register_to_change] -= int(value)
if __name__ == '__main__':
registers = defaultdict(int)
with open('input.txt') as f:
for instruction in f:
execute_instruction(instruction, registers)
print(max(registers.values()))
|
a36e80908a5509eb95316bb0ef3741716c5fe69e | aslastin/Python-Stepik | /04-namespaces/main.py | 545 | 3.5 | 4 | def createNs(d, ns, parent=None):
d[ns] = {'Vars': set(), 'Parent': parent}
def getNs(d, ns, var):
if ns in d:
cur = d[ns]
if var in cur['Vars']:
return ns
return getNs(d, cur['Parent'], var)
return None
n = int(input())
d = {}
for i in range(n):
op, ns, arg = input().split()
if op == 'create':
createNs(d, ns, arg)
elif op == 'add':
if ns not in d:
createNs(d, ns)
d[ns]['Vars'].add(arg)
elif op == 'get':
print(getNs(d, ns, arg))
|
0c1069a8bcdf0080df86f31608a22c6749187f06 | tiscal404/PyPNB | /Aula02/exercicio-06.py | 364 | 3.609375 | 4 | #! /usr/bin/python3.6
def calctempoviagem(s,vm):
try:
t = float(s) / float(vm)
return 'Tempo estimado da viagem: {}h'.format(t)
except:
return 'Algo deu errado. Por favor tente novamente!'
dist = input('Qual distância irá percorrer?(Km)')
vm = input('Qual a velocidade média estimada? (Km/h)')
print(calctempoviagem(dist,vm))
|
be76fab871ad656d0e22374116d1fb3a9370be08 | LongNguyen1984/biofx_python | /01_dna/solution5_dict.py | 1,835 | 3.703125 | 4 | #!/usr/bin/env python3
""" Tetranucleotide frequency """
import argparse
import os
from typing import NamedTuple, Dict
class Args(NamedTuple):
""" Command-line arguments """
dna: str
# --------------------------------------------------
def get_args() -> Args:
""" Get command-line arguments """
parser = argparse.ArgumentParser(
description='Tetranucleotide frequency',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('dna', metavar='DNA', help='Input DNA sequence')
args = parser.parse_args()
if os.path.isfile(args.dna):
args.dna = open(args.dna).read()
return Args(args.dna)
# --------------------------------------------------
def main() -> None:
""" Make a jazz noise here """
args = get_args()
counts = count(args.dna)
print('{} {} {} {}'.format(counts['A'], counts['C'], counts['G'],
counts['T']))
# --------------------------------------------------
def count(dna: str) -> Dict[str, int]:
""" Count bases in DNA """
counts = {'A': 0, 'C': 0, 'G': 0, 'T': 0}
for base in dna:
if base in counts:
counts[base] += 1
return counts
# --------------------------------------------------
def test_count() -> None:
""" Test count """
assert count('') == {'A': 0, 'C': 0, 'G': 0, 'T': 0}
assert count('123XYZ') == {'A': 0, 'C': 0, 'G': 0, 'T': 0}
assert count('A') == {'A': 1, 'C': 0, 'G': 0, 'T': 0}
assert count('C') == {'A': 0, 'C': 1, 'G': 0, 'T': 0}
assert count('G') == {'A': 0, 'C': 0, 'G': 1, 'T': 0}
assert count('T') == {'A': 0, 'C': 0, 'G': 0, 'T': 1}
assert count('ACCGGGTTTT') == {'A': 1, 'C': 2, 'G': 3, 'T': 4}
# --------------------------------------------------
if __name__ == '__main__':
main()
|
f6e6c3ed2e0cb328177a8b16076b5138b4819533 | JonWofr/nst-methods-quantitative-comparison | /scripts/helper/resize-images.py | 2,501 | 3.65625 | 4 | import os
from PIL import Image
import argparse
parser = argparse.ArgumentParser(description='Script to resize the images. If only one of the two options --smaller-side-size, --larger-side-size is provided the size of the other side will be calculated according to the aspect ratio. If both are provided the smaller side of the image will be resized to the smaller size and the larger side will be resized to the larger size (effectively preserving the images orientation).')
parser.add_argument('--images-dir-url', required=True, help='The image directory in which the images are located which should be resized.')
parser.add_argument('--resized-images-dir-url', required=True, help='The image directory in which the resized images should be stored.')
parser.add_argument('--smaller-side-size', type=int, default=None, help='By defining this the images smaller side (i.e. either width or height) will be resized to the given value and the other side will be resized respecting the aspect ratio. Either this option or --larger-side-size has to be defined or both.')
parser.add_argument('--larger-side-size', type=int, default=None, help='By defining this the images larger side (i.e. either width or height) will be resized to the given value and the other side will be resized respecting the aspect ratio. Either this option or --smaller-side-size has to be defined or both.')
args = parser.parse_args()
os.makedirs(args.resized_images_dir_url, exist_ok=True)
image_filenames = os.listdir(args.images_dir_url)
for image_filename in image_filenames:
image_file_url = os.path.join(args.images_dir_url, image_filename)
with Image.open(image_file_url) as image:
aspect_ratio = image.width / image.height
if aspect_ratio >= 1: # Image is square or horizontal
new_width = args.larger_side_size if args.larger_side_size else int(args.smaller_side_size * aspect_ratio)
new_height = args.smaller_side_size if args.smaller_side_size else int(args.larger_side_size / aspect_ratio)
else: # Image is vertical
new_width = args.smaller_side_size if args.smaller_side_size else int(args.larger_side_size * aspect_ratio)
new_height = args.larger_side_size if args.larger_side_size else int(args.smaller_side_size / aspect_ratio)
resized_image = image.resize((new_width, new_height))
resized_image_file_url = os.path.join(
args.resized_images_dir_url, image_filename)
resized_image.save(resized_image_file_url)
|
83dcb07649e99b9714bee231748bedd26cbd916c | ArnaudBD/pythonModule00 | /ex06/recipe.py | 2,933 | 4.125 | 4 | import sys
cookbook = {
'sandwich': {"ingredients": ["ham", "bread", "cheese", "tomatoes"], "course": "lunch", "cookingTime": 10},
'cake': {"ingredients": {"floor", "sugar", "eggs"}, "course": "dessert", "cookingTime": 60},
'salad': {"ingredients": {"avocado", "arugula", "tomatoes", "spinach"}, "course": "lunch", "cookingTime": 15},
}
def printCookbook():
for name, recipe in cookbook.items():
print("Recipe for {}".format(name))
print("Ingredient list {}".format(recipe["ingredients"]))
print("To be eaten for {}".format(recipe["course"]))
print("Takes {} minutes of cooking\n".format(recipe["cookingTime"]))
def addRecipe():
print("What is the name of the recipe you want to add?")
recipeName = input('>>')
print("What is the first ingredient of {}?".format(recipeName))
i = 0
while True:
ing = input('>>')
if ing == "":
break
# ing.format(cookbook[recipeName[i]])
i += 1
cookbook[recipeName] = ing
print("{} is added, what is the next ingredient?\nif there is no more ingredients just press ENTER".format(ing))
printCookbook()
print("You're doing a great job!\nNow can you please tell me how many minutes are needed to prepare {}?".format(recipeName))
print("Last question: can you tell me the meal or the course in wich you eat {}?".format(recipeName))
def printRecipe(thing):
for name, recipe in cookbook.items():
if name == thing:
print("Recipe for {}".format(name))
print("Ingredient list {}".format(recipe["ingredients"]))
print("To be eaten for {}".format(recipe["course"]))
print("Takes {} minutes of cooking".format(recipe["cookingTime"]))
def main():
# for i in cookbook.keys():
# print(i)
# for j in cookbook.items():
# print(j)
# for k in cookbook.values():
# print(k['ingredients'])
# print("{}\n".format(cookbook.items()))
# for name, recipe in cookbook.items():
# # print(type(name))
# # print(type(recipe))
# if name == "sandwich":
# print("Recipe for {}".format(name))
# print("Ingredient list {}".format(recipe["ingredients"]))
# print("To be eaten for {}".format(recipe["course"]))
# print("Takes {} minutes of cooking".format(recipe["cookingTime"]))
print("Please select an option by typing the corresponding number:\n1: Add a recipe\n2: Delete a recipe\n3: Print a recipe\n4: Print the cookbook\n5: Quit")
userChoice = input('>>')
if userChoice == '1':
addRecipe()
elif userChoice == '2':
deleteRecipe()
elif userChoice == '3':
printRecipe(input('>>'))
elif userChoice == '4':
printCookbook()
elif userChoice == '5':
exit
if __name__ == '__main__':
main() |
5fbf63b1c2cc91a5f96d1cc240fd51d9f3f0df92 | arthurdamm/algorithms-practice | /interview/fields_and_towers_3.py | 794 | 4.03125 | 4 | #!/usr/bin/env python3
"""
Field and Towers interview question algorithm
O(n*log(m)) time complexity implementation
"""
def max_field_3(fields, towers):
"""
Finds minimum-distant tower for each field with binary search and
returns the max of these
"""
return max([min([abs(field - tower) for tower in towers]) for field in fields])
def test_max_field(fields, towers):
"""Runs a test of max_field() for given fields and towers"""
print("max_field where fields:", fields, "and towers:", towers)
print(max_field_3(fields, towers))
print()
test_max_field([1, 2, 3], [2])
test_max_field([1, 2, 3, 4], [1, 4])
test_max_field([1, 4], [10])
test_max_field([1, 10, 100], [2, 11])
test_max_field([0, 2, 232, 999], [1, 11, 20, 300, 1001])
test_max_field([0], [0]) |
967425469f06205a8fff3b3852a231c4bb1d735b | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/alhada001/question4.py | 357 | 3.921875 | 4 | number = input("Enter the starting point N:\n")
number2 = input("Enter the ending point M:\n")
print("The palindromic primes are:")
for i in range(eval(number)+1,eval(number2)):
f = len(str(i))
number3 = str(i)
tnum = ""
for p in range (f):
tnum = tnum + number3[(f-1)-p]
if str(i)== tnum:
print(i) |
1962d5604182bc7c8b4b236d54274987230e34fb | SergeiLSL/PYTHON-cribe | /PyCharm на русском/Быстрые клавиши.py | 3,121 | 3.5 | 4 | """
Сочетания клавиш PyCharm
Последнее изменение: 9 июня 2021 г.
Все сочетания клавиш для распечатки
https://resources.jetbrains.com/storage/products/pycharm/docs/PyCharm_ReferenceCard.pdf?_ga=2.62503919.219908342.1625490948-2092108925.1610216984
"""
"""
PyCharm имеет сочетания клавиш для большинства команд,
связанных с редактированием, навигацией, рефакторингом,
отладкой и другими задачами. Запомнив эти горячие клавиши,
вы сможете работать более продуктивно, удерживая руки на клавиатуре.
В следующей таблице перечислены некоторые из наиболее полезных
горячих клавиш для изучения:
Ярлык Действие
Двойной Shift Искать везде
Быстро находите любой файл, действие, класс,
символ, окно инструмента или настройку в PyCharm,
в вашем проекте и в текущем репозитории Git.
Ctrl+E Посмотреть последние файлы
Выберите из списка недавно открытый файл.
Ctrl+Shift+A Найти действие
Найдите команду и выполните ее, откройте окно
инструмента или найдите параметр.
Alt+Enter Показать действия контекста
Быстрые исправления выделенных ошибок и предупреждений,
намеренные действия по улучшению и оптимизации вашего кода.
Ctrl+/
Ctrl+Shift+/ Добавить / удалить строку или заблокировать комментарий
Закомментируйте строку или блок кода.
Alt+F7 Найти использование
Покажите все места, где элемент кода используется
в вашем проекте.
F2
Shift+F2 Переход между проблемами кода
Переход к следующей или предыдущей выделенной ошибке.
Ctrl+W
Ctrl+Shift+W Расширить или сузить выделение
Увеличивайте или уменьшайте объем выбора в соответствии
с конкретными конструкциями кода.
""" |
d0c7bcfcc8d3ca4a00617de032012e13a5e7f47d | morzianka/FirstRepo | /venv/common/Main.py | 1,540 | 3.828125 | 4 | from common import AddCommand,Command,DeleteCommand,ShowAllCommand,\
ShowByCategoryCommand,ShowByMinMaxCommand,ShowForDateCommand,ExitCommand
import datetime
def askOperation():
print("1 - ADD\n" +
"2 - SHOW ALL\n" +
"3 - SHOW FOR DATE\n" +
"4 - SHOW BY CATEGORY\n" +
"5 - SHOW BY MIN MAX\n" +
"6 - DELETE\n" +
"0 - EXIT");
operationNum = int(input("What would you like to do?"));
command = None
if (operationNum == 1):
command = AddCommand.AddCommand(
user = {"Category":input("Category:"), "Product":input("Product:"), "Cost":float(input("Cost:")), "Date":input("Date:")})
if (operationNum == 2):
command = ShowAllCommand.ShowAllCommand()
if (operationNum == 3):
try:
date = datetime.datetime.strptime(input("Date in format YYYY-MM-DD:"), "%Y-%m-%d")
except:
print("Wrong data format")
return -1
command = ShowForDateCommand.ShowForDateCommand(date)
if (operationNum == 4):
command = ShowByCategoryCommand.ShowByCategoryCommand(input("Category:"))
if (operationNum == 5):
command = ShowByMinMaxCommand.ShowByMinMaxCommand(input("Sort descending(yes/no)?:"))
if (operationNum == 6):
command = DeleteCommand.DeleteCommand()
if (operationNum == 0):
command = ExitCommand.ExitCommand()
command.execute()
return operationNum
print("Hello")
operationNum = None
while(operationNum != 0):
operationNum = askOperation()
|
47a42ccb4b92175e93f6da724cae41b965f6a094 | vids2397/vids2397 | /Day 1/exercise7.py | 151 | 3.90625 | 4 | my_list = ["ramu", "shyamu", "kanu", "manu","ramu","radha", "manu"]
print("The given list is" +str(my_list))
my_list = my_list(set(my_list))
print("
|
fcd088e9290335be0a5fc9efb277757f92f62031 | Wangsherpa/data-structures---algorithms | /0-Unscramble Computer Science Problems/Task4.py | 1,424 | 4.1875 | 4 | """
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
import csv
with open('data/texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('data/calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
# This function set of telemarketers numbers
def get_telemarketers(calls):
tele_list = set()
for row in calls:
if '140' in row[0][:3]:
tele_list.add(row[0])
return tele_list
def possible_telemarketers(calls, texts):
possible_teles = set()
for row in calls:
possible_teles.add(row[0])
for row in calls:
if row[1] in possible_teles:
possible_teles.remove(row[1])
for row in texts:
if row[0] in possible_teles:
possible_teles.remove(row[0])
if row[1] in possible_teles:
possible_teles.remove(row[1])
return possible_teles
possible_teles = possible_telemarketers(calls, texts)
confirm_teles = get_telemarketers(calls)
tele_list_sorted = sorted(possible_teles.union(confirm_teles))
print("These numbers could be telemarketers: ")
for no in tele_list_sorted:
print(no)
|
12ae99a77abfca6c7634c7b005a2879cf23c0ea5 | mag389/holbertonschool-higher_level_programming | /0x06-python-classes/100-singly_linked_list.py | 1,913 | 3.84375 | 4 | #!/usr/bin/python3
"""file for sinlgy linked lists """
class Node:
"""" Node class for linked lists"""
def __init__(self, data, next_node=None):
"""initializer for node"""
self.sdata(data)
self.snext_node(next_node)
def gdata(self):
""" getter for data"""
return self.__data
def sdata(self, value):
"""setter for data"""
if type(value) is not int:
raise TypeError("data must be an integer")
self.__data = value
def gnext_node(self):
"""getter for next node"""
return self.__next_node
def snext_node(self, value):
"setter for next node"
if type(value) is not Node and value is not None:
raise TypeError("next_node must be a Node object")
self.__next_node = value
class SinglyLinkedList:
""" the linked list class """
def __init__(self):
""" initializr for linked list"""
self.__head = None
def sorted_insert(self, value):
""" insert new node"""
if self.__head is None:
self.__head = Node(value)
elif (self.__head).gdata() > value:
self.__head = Node(value, self.__head)
else:
temp = self.__head
while temp is not None:
if temp.gnext_node() is None:
temp.snext_node(Node(value))
break
if (temp.gnext_node()).gdata() < value:
temp = temp.gnext_node()
else:
temp.snext_node(Node(value, temp.gnext_node()))
break
def __str__(self):
retstr = ""
temp = self.__head
while temp is not None:
retstr = retstr + str(temp.gdata())
temp = temp.gnext_node()
if temp is not None:
retstr = retstr + "\n"
return retstr
|
e0a2a9f73df458f0aa6b3f7c0d61359cb4395639 | doingmathwithpython/code | /chapter7/solutions/length_curve.py | 812 | 4.09375 | 4 | '''
length_curve.py
Find the length of a curve between two points
'''
from sympy import Derivative, Integral, Symbol, sqrt, SympifyError, sympify
def find_length(fx, var, a, b):
deriv = Derivative(fx, var).doit()
length = Integral(sqrt(1+deriv**2), (var, a, b)).doit().evalf()
return length
if __name__ == '__main__':
f = input('Enter a function in one variable: ')
var = input('Enter the variable: ')
l = float(input('Enter the lower limit of the variable: '))
u = float(input('Enter the upper limit of the variable: '))
try:
f = sympify(f)
except SympifyError:
print('Invalid function entered')
else:
var = Symbol(var)
print('Length of {0} between {1} and {2} is: {3} '.
format(f, l, u, find_length(f, var, l, u)))
|
c07a761b82c38b92dc8228afaf33990dc834293e | ZenSorcere/ITC255-SystemsAnalysis-Kiosk-Code | /Kiosk/itemclass.py | 1,037 | 3.578125 | 4 | class Item():
#constructor taking in initial values
def __init__(self, name, number, price, weight, restricted):
self.name=name
self.number=number
self.price=price
self.weight=weight
self.restricted=False #boolean somehow? should it be in init?
#get methods to return (see) the class variables
def getName(self):
return self.name
def getNumber(self):
return self.number
def getPrice(self):
return self.price
def getWeight(self):
return self.weight
def getRestricted(self):
return self.restricted
""" def __bool__(self):
# This returns true only if value is 1.
if self.value == 1:
return True
else:
return False """
#to string method determines what to return
#when the class is cast to string
#str(item)
def __str__(self):
return self.name + ' ' + str(self.number) + ' ' + str(self.price)
|
06573cdd63ffa43e19dd4944e5cd0ae0c3455a7c | jaford/thissrocks | /Python_Class/py3intro3day/EXAMPLES/getting_dict_values.py | 736 | 3.671875 | 4 | #!/usr/bin/env python
d1 = dict()
airports = {'IAD': 'Dulles', 'SEA': 'Seattle-Tacoma',
'RDU': 'Raleigh-Durham', 'LAX': 'Los Angeles'}
d2 = {}
d3 = dict(red=5, blue=10, yellow=1, brown=5, black=12)
pairs = [('Washington', 'Olympia'), ('Virginia', 'Richmond'),
('Oregon', 'Salem'), ('California', 'Sacramento')]
state_caps = dict(pairs)
print(d3['red'])
print(airports['LAX'])
airports['SLC'] = 'Salt Lake City'
airports['LAX'] = 'Lost Angels'
print(airports['SLC']) # <1>
key = 'PSP'
if key in airports:
print(airports[key]) # <2>
print(airports.get(key)) # <3>
print(airports.get(key, 'NO SUCH AIRPORT')) # <4>
print(airports.setdefault(key, 'Palm Springs')) # <5>
print(key in airports) # <6>
|
316ce359249231c99fbe511ce0518e2cc4374815 | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Trees/Binary_Trees/Summation/20_difference_of_sum_between_even_and_odd_levels.py | 1,039 | 3.984375 | 4 | ''' Difference between sums of odd level and even level nodes of a Binary Tree '''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# Idea is to do level order traversal
def diff_odd_even_levels(root):
if not root:
return 0
q = []
q.append(root)
odd = even = level = 0
while len(q) > 0:
size = len(q)
level += 1
while size > 0:
node = q.pop(0)
if level % 2 == 0:
even += node.val
else:
odd += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
size -= 1
return odd - even
root = Node(5)
root.left = Node(2)
root.right = Node(6)
root.left.left = Node(1)
root.left.right = Node(4)
root.left.right.left = Node(3)
root.right.right = Node(8)
root.right.right.right = Node(9)
root.right.right.left = Node(7)
print diff_odd_even_levels(root) |
4d46dadf5fedf347b129825382c86d6bad8a7705 | StudyForCoding/BEAKJOON | /30_UnionFind/Step03/wowo0709.py | 688 | 3.546875 | 4 | import sys
input = sys.stdin.readline
def find(x):
if not isinstance(parent[x],str) and parent[x] < 0:
return x
p = find(parent[x])
parent[x] = p
return p
def union(x,y):
x = find(x)
y = find(y)
if x == y: return
if parent[x] < parent[y]:
parent[x] += parent[y]
parent[y] = x
else:
parent[y] += parent[x]
parent[x] = y
# main
for _ in range(int(input())):
F = int(input())
parent = {}
for _ in range(F):
a,b = input().rstrip().split()
if a not in parent.keys(): parent[a] = -1
if b not in parent.keys(): parent[b] = -1
union(a,b)
print(-parent[find(a)])
|
b284b2a58e1e27fb765601054577d3ed50751b37 | deepakjain61/dj_private | /database.py | 654 | 3.953125 | 4 | import sqlite3
conn = sqlite3.connect('user.db')
"""
print "Opened database successfully";
conn.execute('''CREATE TABLE user_info
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_name TEXT NOT NULL,
age INT,
country CHAR(50),
email_id TEXT,
phone_no TEXT,
password TEXT);''')
print "Table created successfully";
"""
conn.execute('''INSERT INTO user_info (user_name,age,country,email_id,phone_no,password)
VALUES ( 'Paul', 32, 'California', 'deepakjain61@gmail.com','7768981551', '123' );''')
conn.commit()
for row in conn.execute('SELECT * FROM user_info'):
print row
print "main hun hero ...tera"
conn.close()
|
b120c6b11b399427775891db4fc59f7f35d49081 | DomainRain/civsim | /person.py | 5,041 | 3.734375 | 4 | import names
import random
import sqlite3
import resources
from sqlalchemy import Column, Integer, String
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from base import Base
class Person(Base):
__tablename__ = 'people'
children = relationship("Children")
resources = relationship("Resources")
pid = Column(Integer, primary_key=True)
firstName = Column(String)
lastName = Column(String)
sex = Column(Integer) #0 for female, 1 for male
age = Column(Integer)
desperation = Column(Integer)
gay = Column(Integer)
strength = Column(Integer)
dexterity = Column(Integer)
constitution = Column(Integer)
intelligence = Column(Integer)
wisdom = Column(Integer)
charisma = Column(Integer)
priorityStat = Column(String)
married = Column(Integer)#person name who is married might look into muiltple marriages
fatherID = Column(Integer)
motherID = Column(Integer)
resourceID = Column(Integer, ForeignKey('resources.id'))
def __init__(self, lastName=None):
"""The standard constructor will create an average person that has
no parents. This is used soley during world creation.
If the lastName argument is supplied, then this new person is assumed
to have been born though parents, and will inherit the last name
supplied.
@args
lastName(optional): Will give the new person the last name supplied.
"""
random.seed()
stats = list(("strength",
"dexterity",
"constitution",
"intelligence",
"wisdom",
"charisma"))
self.priorityStat = stats[random.randint(0,5)]
#Select the stat to prioritize from the list of possible stats
self.sex = random.randint(0,1)
#The person will be either a male or female
if (self.sex == 0):
self.firstName = names.get_first_name(gender='female')
elif (self.sex == 1):
self.firstName = names.get_first_name(gender='male')
#Select a first name based on thier sex
if(random.randint(1,100) == 1):
self.gay = 1
else:
self.gay = 0
if(lastName == None):
self.age = random.randint(18,30)
self.lastName = names.get_last_name()
if self.age >= 18 and self.age <= 21:
self.desperation = 0
elif self.age >= 22 and self.age <= 25:
self.desperation = 1
elif self.age >=26:
self.desperation = 2
else:
self.age = 0
self.lastName = lastName
p3.desperation = 0
self.strength = random.randint(9,12)
self.dexterity = random.randint(9,12)
self.constitution = random.randint(9,12)
self.intelligence = random.randint(9,12)
self.wisdom = random.randint(9,12)
self.charisma = random.randint(9,12)
#Let the stats get generated randomly evertime, the fuck method will modify them afterwards.
self.resources = resources.Resources() #initialize the resources table
self.resourceID = self.resources.id
def fuck(self, p2):
"""Two people engage in the art of babymaking to create a new person.
@args
p2: The lucky person who's getting thier night rocked.
"""
p3 = Person(self.lastName)
if(self.sex == 1):
p3.fatherID = self.pid
p3.motherID = p2.pid
else:
p3.fatherID = p2.pid
p3.motherID = self.pid
self.children = Children(pid=self.pid, childID=p3.pid)
p2.children = Children(pid=self.pid, childID=p3.pid)
#create entries in the children database for both parents and add the child to the ChildID field
p3.strength = random.randint(min(self.strength, p2.strength), max(self.strength, p2.strength))
p3.dexterity = random.randint(min(self.dexterity, p2.dexterity), max(self.dexterity, p2.dexterity))
p3.constitution = random.randint(min(self.constitution, p2.constitution), max(self.constitution, p2.constitution))
p3.intelligence = random.randint(min(self.intelligence, p2.intelligence), max(self.intelligence, p2.intelligence))
p3.wisdom = random.randint(min(self.wisdom, p2.wisdom), max(self.wisdom, p2.wisdom))
p3.charisma = random.randint(min(self.charisma, p2.charisma), max(self.charisma, p2.charisma))
return p3
#Modify the stats of the new person such that it is between the parents' stats
class Children(Base):
"""Keeps track of a parent's child. Is called automatically when a child
is born, and should not be called manually.
"""
__tablename__ = 'children'
tid = Column(Integer, primary_key=True) #unique id for this table. Is not needed for anything else
pid = Column(Integer, ForeignKey('people.pid')) #the ID of the parent
childID = Column(Integer) #the ID of the child
|
25afdb4439dbc9173dda71117f164cdc59409dd4 | jujujuanpi/Programacion2020-2 | /Talleres/Taller3.py | 2,980 | 4.0625 | 4 | # FUNCIONES DE NÚMERO MAYOR
a = int (input ("Ingrese el primer número: "))
b = int (input ("Ingrese el segundo número: "))
def numero (numero1, numero2):
if a > b:
print (f"El primer número, {a}, es mayor que el primer número, {b}.")
elif b > a:
print (f"El segundo número, {b} es mayor que el primer número, {a}.")
else:
print ("Los números son iguales.")
numero (a, b)
# LISTADO DE NOMBRES
nombresLista = []
nombresLista = ["Juan Pablo", "Melany", "Daniel", "Valeria", "Mario", "Karla"]
size = len (nombresLista)
def listado (nombresIngresados):
for i in range (size):
print (f"Hola! Soy {nombresLista [i]}.")
listado (nombresLista)
# IMC
peso = int (input ("Ingrese el peso: "))
estatura = float (input ("Ingrese la estatura: "))
def imcFuncion (a, b):
return round(a / b**2, 3)
imc = imcFuncion (peso, estatura)
print (f"El IMC calculado es de {imc}")
# FUNCIÓN QUE RECIBE OTRA
pesoB = int (input ("Ingrese el peso: "))
estaturaB = float (input ("Ingrese la estatura: "))
def imcs (imcFuncion, a, b):
imc = imcFuncion (a, b)
print (f"El IMC calculado es de {imc}")
imcs (imcFuncion, pesoB, estaturaB)
# Clase y Objetos de Personas
class Humanos:
def __init__ (self, z, y, x, w, v, u):
self.nombre = z
self.edad = y
self.id = x
self.peso = w
self.altura = v
self.sexo = u
print ("Se ha creado una nueva persona.")
def atributos (self):
print (f"Hola! Mi nombre es {self.nombre}, soy de sexo {self.sexo}, tengo {self.edad} años, mi ID es {self.id}, peso {self.peso} kg y mido {self.altura} metros.")
humano1 = Humanos ("Andres", 19, 1122334455, 70, 1.80, "Masculino")
humano2 = Humanos ("David", 23, 5497255, 90, 1.70, "Masculino")
humano3 = Humanos ("Andrea", 21, 57385893, 67, 1.50, "Femenino")
listaAtr = ("Andres", 19, 1122334455, 70, 1.80, "Masculino")
humano1.atributos()
humano2.atributos()
humano3.atributos()
# CLASE HEREDADA
class Estudiante (Humanos):
def __init__ (self, z, y, x, w, v, u, t, s, r):
Humanos.__init__(self, z, y, x, w, v, u)
self.semestre = t
self.universidad = s
self.carrera = r
print ("Se ha creado un nuevo estudiante.")
def atributoss (self):
print(f"Hola! Mi nombre es {self.nombre}, soy de sexo {self.sexo}, tengo {self.edad} años, mi ID es {self.id}, peso {self.peso} kg y mido {self.altura} metros. Estudio en {self.universidad} en el {self.semestre} semestre y la carrera {self.carrera}.")
def clase (self, materia):
print (f"Hola soy {self.nombre} y voy a asistir a la clase de {materia}.")
estudiante1 = Estudiante ("Maria", 20, 58374, 60, 1.60, "Femenino", 5, "CES", "Ingeniería Biomédica")
estudiante2 = Estudiante ("Jesus", 23, 65392, 70, 1.76, "Masculino", 3, "CES", "Medicina")
estudiante1.atributoss()
estudiante1.clase("Programación")
estudiante2.atributoss()
estudiante2.clase("Morfofisiología") |
c9dd47ec1ab9c69276462e79dcf18a91ac3ecd28 | keagyy/tictactoe-xtream | /tictactoe3.py | 4,522 | 3.53125 | 4 | def tic_tac_toe():
board = [1, 2, 3, 11, 12, 13, 21, 22, 23, 4, 5, 6, 14, 15, 16, 24, 25, 26, 7, 8, 9, 17, 18, 19, 27, 28, 29,
31, 32, 33, 41, 42, 43, 51, 52, 53, 34, 35, 36, 44, 45, 46, 54, 55, 56, 37, 38, 39, 47,
48, 49, 57, 58, 59, 61, 62, 63, 71, 72, 73, 81, 82, 83, 64, 65, 66, 74, 75, 76, 84, 85,
86, 67, 68, 69, 77, 78, 79, 87, 88, 89]
end = False
win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
def draw():
print(board[0], "|", board[1],"|", board[2], "|", board[3], "|",board[11],"|", board[12],"|",board[21], "|", board[22] ,"|", board[23], board[10])
print ("__________|______________|______________")
print(board[9], "|", board[10], "|", board[11], "|", board[12], "|", board[13], "|", board[14], "|", board[15], "|", board[16], "|", board[17])
print ("__________|______________|______________")
print(board[18],"|", board[19],"|", board[20], "|", board[21],"|", board[22],"|", board[23], "|", board[24],"|", board[25],"|", board[26])
print ("__________|______________|______________")
print(board[27], "|", board[28],"|", board[29],"|", board[30], "|", board[31],"|", board[32], "|", board[33], "|", board[34],"|", board[35])
print ("__________|______________|______________")
print(board[36],"|", board[37],"|", board[38], "|", board[39], "|", board[40],"|", board[41], "|", board[42], "|", board[43],"|", board[44])
print ("__________|______________|______________")
print(board[45],"|", board[46],"|", board[47], "|", board[48], "|", board[49],"|", board[50], "|", board[51], "|", board[52],"|", board[53])
print ("__________|______________|______________")
print(board[54], "|", board[55],"|", board[56],"|",board[57], "|",board[58],"|", board[59],"|",board[60], "|", board[61] ,"|", board[62])
print ("__________|______________|______________")
print(board[63], "|", board[64], "|", board[65],"|", board[66], "|", board[67], "|", board[68], "|", board[69], "|", board[70], "|", board[71])
print ("__________|______________|______________")
print(board[72],"|", board[73],"|", board[74], "|", board[75],"|", board[76],"|", board[77], "|", board[78],"|", board[79],"|", board[80])
print()
def p1():
n = choose_number()
if board[n] == "X" or board[n] == "O":
print("\nYou can't go there. Try again")
p1()
else:
board[n] = " X "
def p2():
n = choose_number()
if board[n] == "X" or board[n] == "O":
print("\nYou can't go there. Try again")
p2()
else:
board[n] = " O "
def choose_number():
while True:
while True:
a = input()
try:
a = int(a)
a -= 1
if a in range(0, 81):
return a
else:
print("\nThat's not on the board. Try again")
continue
except ValueError:
print("\nThat's not a number. Try again")
continue
def check_board():
count = 0
for a in win_commbinations:
if board[a[0]] == board[a[1]] == board[a[2]] == "X":
print("Player 1 Wins!\n")
print("Congratulations!\n")
return True
if board[a[0]] == board[a[1]] == board[a[2]] == "O":
print("Player 2 Wins!\n")
print("Congratulations!\n")
return True
for a in range(9):
if board[a] == "X" or board[a] == "O":
count += 1
if count == 9:
print("The game ends in a Tie\n")
return True
while not end:
draw()
end = check_board()
if end == True:
break
print("Player 1 choose where to place a cross")
p1()
print()
draw()
end = check_board()
if end == True:
break
print("Player 2 choose where to place a nought")
p2()
print()
if input("Play again (y/n)\n") == "y":
print()
tic_tac_toe()
tic_tac_toe()
|
2abd3789db22f7bc936aa42a352651c04ef2d454 | mithro/scheduler-simulator | /scheduler.py | 29,531 | 3.515625 | 4 | #!/bin/env python3
import unittest
from collections import deque
infinity = float("inf")
class bdeque(deque):
def front(self):
return self[0]
def front_pop(self):
return self.popleft()
def back(self):
return self[-1]
def back_pop(self):
return self.pop()
def back_push(self, x):
return self.append(x)
class bdequeTestCase(unittest.TestCase):
def basic(self):
q = bdeque()
self.assertEqual(len(q), 0)
a = []
b = []
c = []
q.back_push(a)
self.assertEqual(len(q), 1)
self.assertIs(q.back(), a)
self.assertIs(q.front(), a)
q.back_push(b)
self.assertEqual(len(q), 2)
self.assertIs(q.back(), b)
self.assertIs(q.front(), a)
self.assertIs(q.front_pop(), a)
self.assertEqual(len(q), 1)
self.assertIs(q.back(), b)
self.assertIs(q.front(), b)
q.back_push(c)
self.assertEqual(len(q), 2)
self.assertIs(q.back(), c)
self.assertIs(q.back_pop(), c)
self.assertIs(q.front(), b)
self.assertEqual(len(q), 1)
self.assertIs(q.back(), b)
self.assertIs(q.front(), b)
self.assertIs(q.back_pop(), b)
self.assertEqual(len(q), 0 )
class Task:
def __repr__(self):
extra = ""
if self.deadline:
extra += ", %s" % self.deadline
return "Task(%r, %i%s)" % (self.name, self.length, extra)
def __init__(self, name, length, deadline=None, run_early=False, discardable=False):
"""
Args:
name (str): Name of the task.
length (int): How long the task will take to run.
Kwargs:
deadline (int): When the task must be finished by.
run_early (bool): Allow the task to run early.
"""
self.name = name
self.length = length
self.deadline = deadline
self.deadline_adjustment = 0
assert run_early == False or deadline != None, "run_early only makes sense with a deadline."
self.run_early = run_early
self.discardable = discardable
def adjust(self, adjustment):
"""Adjust the deadline by an amount."""
if adjustment is None:
self.deadline_adjustment = 0
else:
self.deadline_adjustment += adjustment
def run(self, scheduler, now):
"""
Args:
now (int): Current time.
Returns:
int. The time on finishing the task.
"""
assert self.should_run(now)
self.on_run(scheduler, now)
return now + self.length
def discard(self, scheduler, now):
assert not self.should_run(now)
self.on_discard(scheduler, now)
@property
def start_before(self):
"""Time this task must start at to meet deadline."""
if not self.deadline:
return 0
return self.deadline + self.deadline_adjustment - self.length
@property
def finish_latest(self):
"""Time this task would finish if started at self.start time."""
return self.deadline
def earlist_run(self, now):
"""Time this task can start from."""
if self.run_early:
return now
else:
return max(now, self.start_before)
def earlist_finish(self, now):
"""Time this task can finish by if started at earlist_run time."""
return self.earlist_run(now) + self.length
def should_run(self, now):
if not self.discardable:
return True
else:
return now + self.length <= self.finish_latest
# Methods which should be overridden
# -------------------------------------------------
def on_run(self, scheduler, now):
pass
def on_discard(self, scheduler, now):
pass
# -------------------------------------------------
class TaskTestCase(unittest.TestCase):
def test_start_before(self):
t = Task("A", 10)
self.assertEqual(t.start_before, 0)
t = Task("A", 10, deadline = 20)
self.assertEqual(t.start_before, 10)
def test_finish_latest(self):
t = Task("A", 10)
self.assertEqual(t.finish_latest, None)
t = Task("A", 10, deadline = 20)
self.assertEqual(t.finish_latest, 20)
def test_earlist_run(self):
t = Task("A", 10)
self.assertEqual(t.earlist_run(1), 1)
t = Task("A", 10, deadline = 20)
self.assertEqual(t.earlist_run(1), 10)
t = Task("A", 10, deadline = 20, run_early = True)
self.assertEqual(t.earlist_run(1), 1)
def test_earlist_finish(self):
t = Task("A", 10)
self.assertEqual(t.earlist_finish(1), 11)
t = Task("A", 10, deadline = 20)
self.assertEqual(t.earlist_finish(1), 20)
t = Task("A", 10, deadline = 20, run_early = True)
self.assertEqual(t.earlist_finish(1), 11)
def test_adjust(self):
t = Task("A", 10, deadline = 20)
t.adjust(-2)
self.assertEqual(t.start_before, 8)
self.assertEqual(t.finish_latest, 20)
self.assertEqual(t.earlist_run(1), 8)
self.assertEqual(t.earlist_finish(1), 18)
t.run_early = True
self.assertEqual(t.start_before, 8)
self.assertEqual(t.finish_latest, 20)
self.assertEqual(t.earlist_run(1), 1)
self.assertEqual(t.earlist_finish(1), 11)
def test_discard(self):
t = Task("A", 10, deadline = 20)
self.assertTrue(t.should_run(1))
self.assertTrue(t.should_run(10))
self.assertTrue(t.should_run(11))
t = Task("A", 10, deadline = 20, discardable = True)
self.assertTrue(t.should_run(1))
self.assertTrue(t.should_run(10))
self.assertFalse(t.should_run(11))
t = Task("A", 10, deadline = 20, discardable = True)
t.adjust(-2)
self.assertTrue(t.should_run(1))
self.assertTrue(t.should_run(10))
self.assertFalse(t.should_run(11))
class SchedulerBase:
sentinel_task = Task("sentinel", 0, deadline=infinity, run_early=False)
def __init__(self):
self.tracer = lambda *args, **kw: None
def _pending_tasks(self):
raise NotImplemented()
def _remove_task(self, task):
raise NotImplemented()
def _next_task(self, now):
raise NotImplemented()
def _add_task(self, new_task):
raise NotImplemented()
def add_task(self, new_task):
self.tracer.task_add(self, None, new_task)
self._add_task(new_task)
def run_next(self, now):
task = self._next_task(now)
assert task != self.sentinel_task
assert task.start_before != infinity
# Advance the time if the next task can't run right now.
run_early = task.earlist_run(now)
if run_early > now:
self.tracer.idle_for(self, now, run_early - now)
now = run_early
self._remove_task(task)
if task.should_run(now):
self.tracer.task_start(self, now, task)
now = task.run(self, now)
self.tracer.task_finish(self, now, task)
else:
self.tracer.task_discard(self, now, task)
task.discard(self, now)
return now
def run_all(self, initial_time = 0, maximum_tasks = 100):
ran_tasks = 0
now = initial_time
while self._pending_tasks() > 0:
now = self.run_next(now)
ran_tasks +=1
if ran_tasks > maximum_tasks:
raise SystemError()
assert now != infinity
return now
class SchedulerTracer:
def idle_for(self, scheduler, now, amount):
pass
def task_add(self, scheduler, now, task):
pass
def task_discard(self, scheduler, now, task):
pass
def task_start(self, scheduler, now, task):
pass
def task_finish(self, scheduler, now, task):
pass
class SchedulerTracerForTesting(SchedulerTracer):
def __init__(self, scheduler):
self.events = []
self.schedulers = 0
self.trace(scheduler)
def trace(self, scheduler):
if scheduler.tracer != self:
scheduler.tracer = self
self.schedulers += 1
def get_str(self, scheduler, name, task):
prefix = ""
if self.schedulers > 1:
prefix = scheduler.name + ' @ '
if not hasattr(self, '_now'):
now = "XXXXX"
else:
now = "%05i" % self._now
return "%s%s: %s %s" % (prefix, now, name, task)
def set_now(self, n):
#assert not hasattr(self, '_now') or self._now <= n, "%s %s" % (getattr(self, '_now', None), n)
self._now = n
def idle_for(self, scheduler, now, amount):
assert scheduler.tracer == self
self.set_now(now)
self.events.append(self.get_str(scheduler, "Idle", "for %i" % amount))
def task_add(self, scheduler, now, task):
assert scheduler.tracer == self
if now:
self.set_now(now)
self.events.append(self.get_str(scheduler, "Adding", task))
def task_discard(self, scheduler, now, task):
assert scheduler.tracer == self
self.set_now(now)
self.events.append(self.get_str(scheduler, "Discarding", task))
def task_start(self, scheduler, now, task):
assert scheduler.tracer == self
self.set_now(now)
self.events.append(self.get_str(scheduler, "Running", task))
def task_finish(self, scheduler, now, task):
assert scheduler.tracer == self
self.set_now(now)
if task.deadline and now > task.deadline:
self.events[-1] += " MISSED"
def clear(self):
self.events = []
@property
def runs(self):
return [x for x in self.events if "Running" in x or "Discarding" in x or "Idle" in x]
@property
def adds(self):
return [x for x in self.events if "Adding" in x]
class SchedulerTestBase(unittest.TestCase):
maxDiff = None
@classmethod
def setUpClass(cls):
if cls is SchedulerTestBase:
raise unittest.SkipTest("Skip BaseTest tests, it's a base class")
super(SchedulerTestBase, cls).setUpClass()
def setUp(self):
self.s = self.SchedulerClass()
self.t = SchedulerTracerForTesting(self.s)
def add_task(self, task):
self.s.add_task(task)
def assertAdds(self, first, *expected):
if isinstance(first, int):
assert not expected, repr([first]+list(expected))
self.assertEqual(first, len(self.t.adds))
else:
self.assertEqual("\n".join(self.t.adds)+"\n", "\n".join([first]+list(expected))+"\n")
self.t.clear()
def assertRun(self, *expected, start_at=None, end_at=None):
now_at_end = self.s.run_all(start_at or 0)
self.assertEqual("\n".join(self.t.runs)+"\n", "\n".join(expected)+"\n")
if end_at:
self.assertEqual(end_at, now_at_end)
self.t.clear()
def test_simple_tasks_without_deadlines(self):
self.add_task(Task("A", 30))
self.add_task(Task("B", 20))
self.add_task(Task("C", 10))
self.assertAdds(3)
self.assertRun(
"00000: Running Task('A', 30)",
"00030: Running Task('B', 20)",
"00050: Running Task('C', 10)",
end_at=60)
def test_single_deadline_without_run_early(self):
self.add_task(Task("A", 10, deadline=50, run_early=False))
self.assertAdds(1)
self.assertRun(
"00000: Idle for 40",
"00040: Running Task('A', 10, 50)",
end_at=50)
def test_single_deadline_with_run_early(self):
self.add_task(Task("A", 10, deadline=50, run_early=True))
self.assertAdds(1)
self.assertRun(
"00000: Running Task('A', 10, 50)",
end_at=10)
def test_multiple_deadline_without_run_early(self):
self.add_task(Task("A", 10, deadline=50))
self.add_task(Task("B", 10, deadline=100))
self.assertAdds(2)
self.assertRun(
"00000: Idle for 40",
"00040: Running Task('A', 10, 50)",
"00050: Idle for 40",
"00090: Running Task('B', 10, 100)",
end_at=100)
class FIFOScheduler(SchedulerBase):
"""Simple first in, first out task scheduler."""
def __init__(self, *args, **kw):
SchedulerBase.__init__(self, *args, **kw)
self.task_queue = bdeque()
def _pending_tasks(self):
return len(self.task_queue)
def _next_task(self, now):
return self.task_queue.front()
def _remove_task(self, task):
assert task == self.task_queue.front()
self.task_queue.front_pop()
def _add_task(self, task):
self.task_queue.back_push(task)
class FIFOSchedulerTestCase(SchedulerTestBase):
SchedulerClass = FIFOScheduler
def test_simple_add_tasks_out_of_order_with_deadlines(self):
self.add_task(Task("A", 10, deadline=100))
self.add_task(Task("B", 10, deadline=50))
self.add_task(Task("C", 10, deadline=20))
self.assertAdds(3)
self.assertRun(
"00000: Idle for 90",
"00090: Running Task('A', 10, 100)",
"00100: Running Task('B', 10, 50) MISSED",
"00110: Running Task('C', 10, 20) MISSED",
end_at=120)
def test_multiple_deadline_with_run_early(self):
self.add_task(Task("A", 10, deadline=50, run_early=True))
self.add_task(Task("B", 10, deadline=100, run_early=True))
self.assertAdds(2)
self.assertRun(
"00000: Running Task('A', 10, 50)",
"00010: Running Task('B', 10, 100)",
end_at=20)
def test_multiple_deadline_overlap(self):
self.add_task(Task("A", 10, deadline=50))
self.add_task(Task("B", 10, deadline=55))
self.assertAdds(2)
self.assertRun(
"00000: Idle for 40",
"00040: Running Task('A', 10, 50)",
"00050: Running Task('B', 10, 55) MISSED",
end_at=60)
def test_multiple_deadline_overlap_with_run_early(self):
self.add_task(Task("A", 10, deadline=50, run_early=True))
self.add_task(Task("B", 10, deadline=55))
self.assertAdds(2)
self.assertRun(
"00000: Running Task('A', 10, 50)",
"00010: Idle for 35",
"00045: Running Task('B', 10, 55)",
end_at=55)
def test_mixed_simple(self):
self.add_task(Task("A", 10))
self.add_task(Task("B", 10, deadline=50))
self.add_task(Task("C", 10))
self.add_task(Task("D", 50))
self.assertAdds(4)
self.assertRun(
"00000: Running Task('A', 10)",
"00010: Idle for 30",
"00040: Running Task('B', 10, 50)",
"00050: Running Task('C', 10)",
"00060: Running Task('D', 50)",
end_at=110)
def test_mixed_too_large(self):
self.add_task(Task("A1", 5, deadline=10))
self.add_task(Task("A2", 5, deadline=20))
self.add_task(Task("B", 20))
self.add_task(Task("A3", 5, deadline=30))
self.add_task(Task("A4", 5, deadline=40))
self.add_task(Task("A5", 5, deadline=50))
self.add_task(Task("A6", 5, deadline=60))
self.add_task(Task("A7", 5, deadline=70))
self.assertRun(
"00000: Idle for 5",
"00005: Running Task('A1', 5, 10)",
"00010: Idle for 5",
"00015: Running Task('A2', 5, 20)",
"00020: Running Task('B', 20)",
"00040: Running Task('A3', 5, 30) MISSED",
"00045: Running Task('A4', 5, 40) MISSED",
"00050: Running Task('A5', 5, 50) MISSED",
"00055: Running Task('A6', 5, 60)",
"00060: Idle for 5",
"00065: Running Task('A7', 5, 70)",
end_at=70)
def test_mixed_discardable(self):
self.add_task(Task("A1", 5, deadline=10, discardable=True))
self.add_task(Task("A2", 5, deadline=20, discardable=True))
self.add_task(Task("B", 20))
self.add_task(Task("A3", 5, deadline=30, discardable=True))
self.add_task(Task("A4", 5, deadline=40, discardable=True))
self.add_task(Task("A5", 5, deadline=50, discardable=True))
self.add_task(Task("A6", 5, deadline=60, discardable=True))
self.add_task(Task("A7", 5, deadline=70, discardable=True))
self.assertRun(
"00000: Idle for 5",
"00005: Running Task('A1', 5, 10)",
"00010: Idle for 5",
"00015: Running Task('A2', 5, 20)",
"00020: Running Task('B', 20)",
"00040: Discarding Task('A3', 5, 30)",
"00040: Discarding Task('A4', 5, 40)",
"00040: Idle for 5",
"00045: Running Task('A5', 5, 50)",
"00050: Idle for 5",
"00055: Running Task('A6', 5, 60)",
"00060: Idle for 5",
"00065: Running Task('A7', 5, 70)",
end_at=70)
class DeadlineOrderingScheduler(FIFOScheduler):
"""Scheduler which orders runs by deadlines (then FIFO)."""
def __init__(self, *args, **kw):
self.deadline_queue = bdeque()
FIFOScheduler.__init__(self, *args, **kw)
def _pending_tasks(self):
return len(self.deadline_queue) + FIFOScheduler._pending_tasks(self)
def _next_task(self, now):
task = self.sentinel_task
# Do we have a deadline tasks that might need to run?
if self.deadline_queue:
task = self.deadline_queue.front()
# Do we have any non-deadline tasks?
if FIFOScheduler._pending_tasks(self):
next_fifo = FIFOScheduler._next_task(self, now)
# Can we run the non-deadline task before any other task?
if task.start_before >= next_fifo.earlist_finish(now):
task = next_fifo
assert task != self.sentinel_task
return task
def _remove_task(self, task):
if task in self.deadline_queue:
self.deadline_queue.remove(task)
return
FIFOScheduler._remove_task(self, task)
def _add_task(self, new_task):
assert new_task
# If it's a normal task, just FIFO scheduler it
if not new_task.start_before:
FIFOScheduler._add_task(self, new_task)
return
# Else it's a deadline task, so schedule it specially.
new_task.adjust(None) # Clear any previous adjustments
self._add_deadline_task(new_task)
def _add_deadline_task(self, new_task):
assert new_task
self.deadline_queue.back_push(new_task)
# Restore the queue, so deadline_queue is ordered
self.deadline_queue = bdeque(sorted(self.deadline_queue, key=lambda t: t.start_before))
class DeadlineOrderingSchedulerTestCase(SchedulerTestBase):
SchedulerClass = DeadlineOrderingScheduler
def test_simple_add_tasks_out_of_order_with_deadlines(self):
self.add_task(Task("A", 10, deadline=100))
self.add_task(Task("B", 10, deadline=50))
self.add_task(Task("C", 10, deadline=20))
self.assertAdds(3)
self.assertRun(
"00000: Idle for 10",
"00010: Running Task('C', 10, 20)",
"00020: Idle for 20",
"00040: Running Task('B', 10, 50)",
"00050: Idle for 40",
"00090: Running Task('A', 10, 100)",
end_at=100)
def test_multiple_deadline_with_run_early(self):
self.add_task(Task("A", 10, deadline=50, run_early=True))
self.add_task(Task("B", 10, deadline=100, run_early=True))
self.assertAdds(2)
self.assertRun(
"00000: Running Task('A', 10, 50)",
"00010: Running Task('B', 10, 100)",
end_at=20)
def test_multiple_deadline_overlap(self):
self.add_task(Task("A", 10, deadline=50))
self.add_task(Task("B", 10, deadline=55))
self.assertAdds(2)
self.assertRun(
"00000: Idle for 40",
"00040: Running Task('A', 10, 50)",
"00050: Running Task('B', 10, 55) MISSED",
end_at=60)
def test_multiple_deadline_overlap_with_run_early(self):
self.add_task(Task("A", 10, deadline=50, run_early=True))
self.add_task(Task("B", 10, deadline=55))
self.assertAdds(2)
self.assertRun(
"00000: Running Task('A', 10, 50)",
"00010: Idle for 35",
"00045: Running Task('B', 10, 55)",
end_at=55)
def test_multiple_deadline_overlap_ripple(self):
self.add_task(Task("A", 10, deadline=50))
self.add_task(Task("B", 10, deadline=60))
self.add_task(Task("C", 10, deadline=65))
self.assertAdds(3)
self.assertRun(
"00000: Idle for 40",
"00040: Running Task('A', 10, 50)",
"00050: Running Task('B', 10, 60)",
"00060: Running Task('C', 10, 65) MISSED",
end_at=70)
def test_multiple_deadline_adjustment_with_run_early(self):
self.add_task(Task("A", 10, deadline=50, run_early=True))
self.add_task(Task("B", 10, deadline=55))
self.assertAdds(2)
self.assertRun(
"00000: Running Task('A', 10, 50)",
"00010: Idle for 35",
"00045: Running Task('B', 10, 55)",
end_at=55)
def test_multiple_deadline_adjustment_with_run_early_and_ripple(self):
self.add_task(Task("A", 10, deadline=50, run_early=True))
self.add_task(Task("B", 10, deadline=60))
self.add_task(Task("C", 10, deadline=65))
self.assertAdds(3)
self.assertRun(
"00000: Running Task('A', 10, 50)",
"00010: Idle for 40",
"00050: Running Task('B', 10, 60)",
"00060: Running Task('C', 10, 65) MISSED",
end_at=70)
def test_mixed_simple(self):
self.add_task(Task("A", 10))
self.add_task(Task("B", 10, deadline=50))
self.add_task(Task("C", 10))
self.add_task(Task("D", 50))
self.assertAdds(4)
self.assertRun(
"00000: Running Task('A', 10)",
"00010: Running Task('C', 10)",
"00020: Idle for 20",
"00040: Running Task('B', 10, 50)",
"00050: Running Task('D', 50)",
end_at=100)
def test_mixed_too_large(self):
self.add_task(Task("A1", 5, deadline=10))
self.add_task(Task("A2", 5, deadline=20))
self.add_task(Task("B", 20))
self.add_task(Task("A3", 5, deadline=30))
self.add_task(Task("A4", 5, deadline=40))
self.add_task(Task("A5", 5, deadline=50))
self.add_task(Task("A6", 5, deadline=60))
self.add_task(Task("A7", 5, deadline=70))
self.assertRun(
"00000: Idle for 5",
"00005: Running Task('A1', 5, 10)",
"00010: Idle for 5",
"00015: Running Task('A2', 5, 20)",
"00020: Idle for 5",
"00025: Running Task('A3', 5, 30)",
"00030: Idle for 5",
"00035: Running Task('A4', 5, 40)",
"00040: Idle for 5",
"00045: Running Task('A5', 5, 50)",
"00050: Idle for 5",
"00055: Running Task('A6', 5, 60)",
"00060: Idle for 5",
"00065: Running Task('A7', 5, 70)",
"00070: Running Task('B', 20)",
end_at=90)
def test_mixed_discardable(self):
self.add_task(Task("A1", 5, deadline=10, discardable=True))
self.add_task(Task("A2", 5, deadline=20, discardable=True))
self.add_task(Task("B", 20))
self.add_task(Task("A3", 5, deadline=30, discardable=True))
self.add_task(Task("A4", 5, deadline=40, discardable=True))
self.add_task(Task("A5", 5, deadline=50, discardable=True))
self.add_task(Task("A6", 5, deadline=60, discardable=True))
self.add_task(Task("A7", 5, deadline=70, discardable=True))
self.assertRun(
"00000: Idle for 5",
"00005: Running Task('A1', 5, 10)",
"00010: Idle for 5",
"00015: Running Task('A2', 5, 20)",
"00020: Idle for 5",
"00025: Running Task('A3', 5, 30)",
"00030: Idle for 5",
"00035: Running Task('A4', 5, 40)",
"00040: Idle for 5",
"00045: Running Task('A5', 5, 50)",
"00050: Idle for 5",
"00055: Running Task('A6', 5, 60)",
"00060: Idle for 5",
"00065: Running Task('A7', 5, 70)",
"00070: Running Task('B', 20)",
end_at=90)
class DeadlineOrderingWithAdjustmentScheduler(DeadlineOrderingScheduler):
"""Scheduler which orders by deadlines but adjusts them to meet requirements."""
def _next_task(self, now):
task = self.sentinel_task
# Do we have a deadline tasks that might need to run?
if self.deadline_queue:
task = self.deadline_queue.front()
# Do we have any non-deadline tasks?
if FIFOScheduler._pending_tasks(self):
next_fifo = FIFOScheduler._next_task(self, now)
# Can we run the non-deadline task before any other task?
if task.start_before >= now + next_fifo.length:
task = next_fifo
# Else keep running deadline tasks early until we can fit this task.
elif self.deadline_queue:
task.adjust(now - task.start_before)
assert task != self.sentinel_task
return task
def _add_deadline_task(self, new_task):
assert new_task
# Unqueue any deadline task which will occur after this task
previous_task = None
tasks_after_new_task = []
while self.deadline_queue:
previous_task = self.deadline_queue.back()
if previous_task.start_before < new_task.start_before:
break
self._remove_task(previous_task)
tasks_after_new_task.append(previous_task)
if self.deadline_queue and previous_task and previous_task.finish_latest >= new_task.start_before:
# To allow this task to meet the deadline, we need to make the task
# before this one run earlier.
# We remove the previous task from the queue, adjust the deadline and try
# adding it back. This is because the new deadline on this task could
# cause the task before it to also need adjustment.
# Effectively their will be a ripple effect moving the deadline of all
# earlier tasks forward.
self._remove_task(previous_task)
previous_task.adjust(new_task.start_before - previous_task.finish_latest)
self._add_deadline_task(previous_task)
self.deadline_queue.back_push(new_task)
# We need to add all deadline tasks after the new one which we unqueue. We
# can't add them directly back to the queue because the new task could cause
# these tasks to miss their deadline. Instead we add them just like being a
# new task.
for task in tasks_after_new_task:
self._add_deadline_task(task)
class DeadlineOrderingWithAdjustmentSchedulerTestCase(SchedulerTestBase):
SchedulerClass = DeadlineOrderingWithAdjustmentScheduler
def test_simple_tasks_without_deadlines(self):
self.add_task(Task("A", 30))
self.add_task(Task("B", 20))
self.add_task(Task("C", 10))
self.assertAdds(3)
self.assertRun(
"00000: Running Task('A', 30)",
"00030: Running Task('B', 20)",
"00050: Running Task('C', 10)",
end_at=60)
def test_single_deadline_without_run_early(self):
self.add_task(Task("A", 10, deadline=50, run_early=False))
self.assertAdds(1)
self.assertRun(
"00000: Idle for 40",
"00040: Running Task('A', 10, 50)",
end_at=50)
def test_single_deadline_with_run_early(self):
self.add_task(Task("A", 10, deadline=50, run_early=True))
self.assertAdds(1)
self.assertRun(
"00000: Running Task('A', 10, 50)",
end_at=10)
def test_multiple_deadline_without_run_early(self):
self.add_task(Task("A", 10, deadline=50))
self.add_task(Task("B", 10, deadline=100))
self.assertAdds(2)
self.assertRun(
"00000: Idle for 40",
"00040: Running Task('A', 10, 50)",
"00050: Idle for 40",
"00090: Running Task('B', 10, 100)",
end_at=100)
def test_simple_add_tasks_out_of_order_with_deadlines(self):
self.add_task(Task("B", 10, deadline=100))
self.add_task(Task("A", 10, deadline=50))
self.add_task(Task("C", 10, deadline=20))
self.assertAdds(3)
self.assertRun(
"00000: Idle for 10",
"00010: Running Task('C', 10, 20)",
"00020: Idle for 20",
"00040: Running Task('A', 10, 50)",
"00050: Idle for 40",
"00090: Running Task('B', 10, 100)",
end_at=100)
def test_multiple_deadline_with_run_early(self):
self.add_task(Task("A", 10, deadline=50, run_early=True))
self.add_task(Task("B", 10, deadline=100, run_early=True))
self.assertAdds(2)
self.assertRun(
"00000: Running Task('A', 10, 50)",
"00010: Running Task('B', 10, 100)",
end_at=20)
def test_multiple_deadline_adjustment_1(self):
self.add_task(Task("A", 10, deadline=50))
self.add_task(Task("B", 10, deadline=55))
self.assertAdds(2)
self.assertRun(
"00000: Idle for 35",
"00035: Running Task('A', 10, 50)",
"00045: Running Task('B', 10, 55)",
end_at=55)
def test_multiple_deadline_adjustment_ripple(self):
self.add_task(Task("A", 10, deadline=50))
self.add_task(Task("B", 10, deadline=60))
self.add_task(Task("C", 10, deadline=65))
self.assertAdds(3)
self.assertRun(
"00000: Idle for 35",
"00035: Running Task('A', 10, 50)",
"00045: Running Task('B', 10, 60)",
"00055: Running Task('C', 10, 65)",
end_at=65)
def test_multiple_deadline_adjustment_with_run_early(self):
self.add_task(Task("A", 10, deadline=50, run_early=True))
self.add_task(Task("B", 10, deadline=55))
self.assertAdds(2)
self.assertRun(
"00000: Running Task('A', 10, 50)",
"00010: Idle for 35",
"00045: Running Task('B', 10, 55)",
end_at=55)
def test_multiple_deadline_adjustment_with_run_early_and_ripple(self):
self.add_task(Task("A", 10, deadline=50, run_early=True))
self.add_task(Task("B", 10, deadline=60))
self.add_task(Task("C", 10, deadline=65))
self.assertAdds(3)
self.assertRun(
"00000: Running Task('A', 10, 50)",
"00010: Idle for 35",
"00045: Running Task('B', 10, 60)",
"00055: Running Task('C', 10, 65)",
end_at=65)
def test_mixed_simple(self):
self.add_task(Task("A", 10))
self.add_task(Task("B", 10, deadline=50))
self.add_task(Task("C", 10))
self.add_task(Task("D", 50))
self.assertAdds(4)
self.assertRun(
"00000: Running Task('A', 10)",
"00010: Running Task('C', 10)",
"00020: Running Task('B', 10, 50)",
"00030: Running Task('D', 50)",
end_at=80)
def test_mixed_too_large(self):
self.add_task(Task("A1", 5, deadline=10))
self.add_task(Task("A2", 5, deadline=20))
self.add_task(Task("A3", 5, deadline=30))
self.add_task(Task("A4", 5, deadline=40))
self.add_task(Task("A5", 5, deadline=50))
self.add_task(Task("A6", 5, deadline=60))
self.add_task(Task("A7", 5, deadline=70))
self.add_task(Task("B", 20))
self.add_task(Task("C", 10))
self.assertRun(
"00000: Running Task('A1', 5, 10)",
"00005: Running Task('A2', 5, 20)",
"00010: Running Task('A3', 5, 30)",
"00015: Running Task('B', 20)",
"00035: Running Task('A4', 5, 40)",
"00040: Running Task('A5', 5, 50)",
"00045: Running Task('C', 10)",
"00055: Running Task('A6', 5, 60)",
"00060: Idle for 5",
"00065: Running Task('A7', 5, 70)",
end_at=70)
if __name__ == '__main__':
unittest.main()
|
56b21160ce35e6053c0df0abaa44ff38853c2ab1 | librallu/uqac-visu-projet | /test.py | 1,855 | 3.53125 | 4 | file_name = 'off'
class Data:
"""
extracts data from csv.
"""
def __init__(self, filename):
"""
filename: string for the csv file
"""
self.data_fields = {} # name -> int
self.data_fields_order = []
self.data = []
with open(filename) as f:
names = f.readline().split('\t')
for i,name in enumerate(names):
self.data_fields[name] = i
self.data_fields_order.append(name)
for a in f.readlines():
fields = [b.replace('\n', '') for b in a.split('\t')]
if len(fields) == len(names):
self.data.append(fields)
def get_row(self, i):
"""
:param i: row number in data
:return: list of field values
"""
return self.data[i]
def get_nblines(self):
""" :return: number of lines in the record """
return len(self.data)
def get_row_dict(self, i):
res = {}
for pos, val in enumerate(self.data_fields_order):
res[val] = self.data[i][pos]
return res
def get_headers(self):
return self.data_fields.keys()
def get_fields(self, name):
res = []
i = self.data_fields[name]
for a in self.data:
res.append(a[i])
return res
def eliminate_nodes(self, fun_check):
""" if fun_check returns false, eliminate node from data """
tmp = []
for i in range(len(self.data)):
if fun_check(self.get_row_dict(i)):
tmp.append(self.data[i])
self.data = tmp
off = Data(file_name+'.csv')
def check_name(row):
return row['product_name'] != ''
print(off.get_nblines())
off.eliminate_nodes(check_name)
print(off.get_nblines())
|
180d141afcf454a45d851523b6dd33f1d7cd0a72 | eessm01/100-days-of-code | /e_bahit/closures.py | 2,657 | 4.40625 | 4 | """The Original Hacker No.3. Closures
Un closure es una función que define otra
función y la retorna al ser invocado.
Un closure DEBE tener una razón de ser. De hecho, mi consejo
es evitarlos toda vez que sea posible resolver el planteo sin
utilizarlos. Pues dificulta la lectura del código y su
entendimiento, cuando en realidad, debería estar ahí para
facilitarlo.
Se justifica el uso de closures cuando su finalidad consista
en evitar la redundancia y la sobrecarga de parámetros.
La MEJOR IMPLEMENTACIÓN de un closure no será la que haya
sido perfectamente planificada sobre un papel en blanco, sino
aquella alcanzada tras un cuidadoso refactoring.
"""
def closure1():
def funcion_interna():
return 1
return funcion_interna
variable1 = closure1()
print(variable1())
def closure2(parametro):
def funcion():
return parametro + 1 # parametro es de la función closure2()
return funcion
variable2 = closure2(parametro=1)
print(variable2())
# Un ejemplo bien implementado
def calcular_iva(alicuota):
def estimar_neto(importe_bruto):
return importe_bruto + (importe_bruto * alicuota / 100)
return estimar_neto
# Productos gravados con el 21%
get_neto_base_21 = calcular_iva(21)
harina = get_neto_base_21(10)
arroz = get_neto_base_21(8.75)
azucar = get_neto_base_21(21.5)
# Productos gravados con el 10.5
get_neto_base_105 = calcular_iva(10.5)
tv = get_neto_base_105(12700)
automovil = get_neto_base_105(73250)
# El requerimiento anterior, podría haber requerido definir dos
# funciones independientes (get_neto_base_21 y get_neto_base_105)
# con prácticamente el mismo algoritmo y una importante redundancia.
# En su defecto, podría haberse resuelto mediante una única función
# con 2 parámetros, la cual hubiese requerido replicar el valor de
# uno de los parámetros incansablemente, en las reiteradas llamadas.
# Otras opciones
# redundancia de funciones
def get_neto_base_21(importe_bruto):
return importe_bruto + (importe_bruto * 21 / 100) # linea redundante
def get_neto_base_105(importe_bruto):
return importe_bruto + (importe_bruto * 10.5 / 100) # linea redundante
harina = get_neto_base_21(10)
arroz = get_neto_base_21(8.75)
azucar = get_neto_base_21(12.5)
tv = get_neto_base_105(12700)
automovil = get_neto_base_105(73250)
# redundancia de parámetros
def get_neto(alicuota_iva, importe_bruto):
return importe_bruto + (importe_bruto * alicuota_iva / 100)
harina = get_neto(21, 10)
arroz = get_neto(21, 8.75)
azucar = get_neto(21, 12.5)
tv = get_neto(10.5, 12700)
tv = get_neto(10.5, 73250)
# qué pasaría con 1000 productos?? |
98191417bad7ee69c480cbf8ff9d24956c9783b0 | Shakar-Gadirli/hyperskill | /Tic-Tac-Toe/tictactoe/tictactoe.py | 2,482 | 3.859375 | 4 | temp_moves = list(input("Enter cells:"))
rows = [[temp_moves[j] for j in range(i, i + 3)] for i in range(0, len(temp_moves), 3)]
class Game:
def __init__(self, cells):
self.cells = cells
self.is_finished_state = True
self.x_win = False
self.y_win = False
self.x_count = 0
self.y_count = 0
self.is_possible_state = True
self.is_draw_state = False
def draw(self):
print("---------" + '\n' +
f"| {self.cells[0][0]} {self.cells[0][1]} {self.cells[0][2]} |" + '\n' +
f"| {self.cells[1][0]} {self.cells[1][1]} {self.cells[1][2]} |" + '\n' +
f"| {self.cells[2][0]} {self.cells[2][1]} {self.cells[2][2]} |" + '\n' +
"---------")
self.game_state()
def game_state(self):
self.winner_state()
self.is_possible()
self.is_finished()
if not self.is_finished_state:
print("Game not finished")
elif not self.is_possible_state:
print("Impossible")
elif self.is_draw_state:
print("Draw")
elif self.x_win:
print("X wins")
elif self.x_win:
print("O wins")
def winner_state(self):
for i in range(len(rows)):
if rows[i][0] == 'X' and rows[i][1] == 'X' and rows[i][2] == 'X':
self.x_win = True
break
if rows[i][0] == 'O' and rows[i][1] == 'O' and rows[i][2] == 'O':
self.y_win = True
break
if rows[i].count('X') == 3:
self.x_win = True
break
if rows[i].count('O') == 3:
self.y_win = True
break
def is_draw(self):
if not self.is_finished_state and not self.x_win or not self.y_win:
self.is_draw_state = True
def is_finished(self):
if not self.x_win or not self.y_win:
for row in self.cells:
if '_' in row:
self.is_finished_state = False
def count_items(self):
for i in range(len(rows)):
self.x_count += rows[i].count('X')
self.y_count += rows[i].count('O')
def is_possible(self):
if self.x_win and self.y_win:
self.is_possible_state = False
if self.x_count > self.y_count + 1 or self.y_count > self.x_count + 1:
self.is_possible_state = False
game = Game(rows)
game.draw()
|
a302b17af34912d4c12fac477398b821c2affd72 | Ahm36/pythonprograms | /CO1/program6.py | 168 | 3.8125 | 4 | #6numofa
li=[]
c=0
for i in range (3):
x=input("enter first names:")
li.append(x)
for i in li:
for j in i:
if 'a' in j:
c=c+1
print("number of a's :",c) |
9470bb76e7432edcf89f5f7a3c78a9e9d63e5da4 | Aasthaengg/IBMdataset | /Python_codes/p02263/s396876043.py | 238 | 3.5625 | 4 | data = input().split()
operator = ["+", "*", "-"]
stack = []
for x in data:
if x in operator:
a = stack.pop()
b = stack.pop()
stack.append(str(eval(b + x + a)))
else:
stack.append(x)
print(stack[0]) |
212ee04b83e8c9c97d42f5eafb4155c4cdb1e02a | rockchalkwushock/pdx-code-labs | /average_numbers.py | 429 | 4.09375 | 4 | nums = []
def avg_nums(nums):
running_sum = 0
for num in nums:
running_sum += num
print(f'The new sum is: {running_sum}.')
print(f'The average is: {running_sum / len(nums)}.')
while True:
query = int(input('1: Enter a number\n2: Average\n\n'))
if query == 1:
num = int(input('Enter a number: '))
nums.append(num)
elif query == 2:
avg_nums(nums)
quit()
|
d79d49b2d719168e64ec938a290afdb28fd3ee02 | Sh2rif/python | /condtions.py | 190 | 3.734375 | 4 | username = input ('Please insert your username')
password = input ('Please insert your password')
if username == 'sharif' and password == '123':
print('welcome')
else:
print('Error') |
d81dc05cd8afa0ddec68ffe058a8e44ab4b7e643 | DCUniverse1990/01_Recipes | /04_Ingredients_List.py | 1,356 | 4.125 | 4 | # Ingredients list
# Not blank Function goes here
def not_blank(question, error_msg, num_ok):
error = error_msg
valid = False
while not valid:
response = input(question)
has_errors = ""
if num_ok != "yes":
# look at each character in sting and if its a number, complain
for letter in response:
if letter.isdigit() == True:
has_errors = "yes"
break
if response == "":
print(error)
continue
elif has_errors != "":
print(error)
continue
else:
return response
# Main Routine goes here
# Main Routine...
# Set up empty ingredient list
Ingredients = []
# Loop to ask users to enter an ingredient
stop = ""
while stop != "xxx":
# Ask user for ingredient (Via not blank function)
get_Ingredient = not_blank("Please type in an ingredient name: ",
"This cant be blank",
"yes")
# If exit code is typed...
if get_Ingredient.lower()=="xxx" and len(Ingredients) > 1:
break
# Check that list contains at least two items
# If exit code is not entered, add to ingredient list
else:
Ingredients.append(get_Ingredient)
# Output list
print(Ingredients) |
7f43a201f237f0e05ea8470f3691dec182e47f45 | wonanut/LeetCode-2020 | /src/2020-01/week4/46-permutations.py | 555 | 3.84375 | 4 | """
46:全排列
链接:https://leetcode-cn.com/problems/permutations/
难度:中等
标签:dfs
评价:dfs模板,必须掌握!
"""
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(nums, path):
if not nums:
ans.append(path)
return
for i in range(len(nums)):
dfs(nums[:i] + nums[i + 1:], path + [nums[i]])
ans = []
dfs(nums, [])
return ans
|
3787c9aa583d24e924b56df40752ec1eb436cdb9 | 4evernewb/ReLU-function | /main.py | 117 | 3.78125 | 4 | def relu(a):
return max(a,0)
i = int(input("Enter a number to find the relu function of it. "))
print(relu(i))
|
1979004da4a8da3f91a1f07212bb0b5a8d5e00a4 | matthew-david-hawkins/python-challenge | /PyBank/main.py | 3,218 | 4.15625 | 4 | # To add a new cell, type '#%%'
# To add a new markdown cell, type '#%% [markdown]'
#%%
#Overview:
# In this challenge, you are tasked with creating a Python script for
# analyzing the financial records of your company. You will give a
# set of financial data called budget_data.csv. The dataset is composed
# of two columns: Date and Profit/Losses.
#Calculate:
# The total number of months included in the dataset
# The net total amount of "Profit/Losses" over the entire period
# The average of the changes in "Profit/Losses" over the entire period
# The greatest increase in profits (date and amount) over the entire period
# The greatest decrease in losses (date and amount) over the entire period
#References:
# Creating directories https://stackabuse.com/creating-and-deleting-directories-with-python/
#%%
#Import Dependencies
import csv
import os
#%%
# Define the path to the dataset
csv_path = "Resources/budget_data.csv"
#%%
#initialize
months = 0
account = 0
greatest_loss = 0
greatest_profit = 0
greatest_loss_month =""
greatest_profit_month =""
#%%
# Read the dataset into a file stream objects
with open(csv_path, newline='') as csv_file:
#Define reader object delimited by ","
csv_reader = csv.reader(csv_file, delimiter=",")
#Define the header
csv_header = next(csv_reader)
#print(csv_header)
#Loop over the number of lines
for row in csv_reader:
#Sum the months
months = months + 1
#Define the current profit/loss
pl = int(row [1])
#Sum the Profit/losses
account = account + pl
#track the greatest profit by comparing current profit to greatest profit
if pl > greatest_profit:
greatest_profit_month = row[0]
greatest_profit = pl
#track the greatest loss by comparing current loss to greatest loss
elif pl < greatest_loss:
greatest_loss_month = row[0]
greatest_loss = pl
#print(f"{row} months = {months} account = {account} greatest profit = {greatest_profit} greatest loss = {greatest_loss}")
#print(greatest_loss_month)
#%%
#Calculate the average profit and loss
mean_pl = account / months
mean_pl
#%%
#Define messages
messages = []
messages.append("Finanacial Analysis")
messages.append("-------------------------------------------------------------------------")
messages.append(f"Total Months: {months}")
messages.append(f"Total: ${account}")
messages.append(f"Average Change: ${round(mean_pl,2)}")
messages.append(f"Greatest Increase in Profits: {greatest_profit_month} ({greatest_profit})")
messages.append(f"Greatest Decrease in Profits: {greatest_loss_month} ({greatest_loss})")
#%%
#print messages to the terminal
for message in messages:
print(message)
#%%
#create an output folder if one doesn't already exist
try:
os.mkdir("Output")
except OSError:
print ("Matt's Warning: Creation of the directory 'Output' failed")
#%%
#Export the analysis to a text file
with open("Output/financial_analysis.txt", 'w+') as output:
for message in messages:
output.write(message)
output.write("\n")
|
ace32b1335f1b0e9e4acdc0e64338799a6bd5ea4 | jianhanghp/LeetCode | /102. Binary Tree Level Order Traversal.py | 1,664 | 3.9375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# my sol1, using queue
# class Solution:
# def levelOrder(self, root: TreeNode) -> List[List[int]]:
# q = collections.deque()
# if root:
# q.append(root)
# res = []
# while len(q)!= 0:
# res.append([])
# l = len(q)
# for _ in range(l):
# p = q.popleft()
# if p.left:
# q.append(p.left)
# if p.right:
# q.append(p.right)
# res[-1].append(p.val)
# return res
# sol2, using list in python
# from https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/33464/5-6-lines-fast-python-solution-(48-ms)
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
level = [root]
while root and level:
res.append([node.val for node in level])
# 2.1
# temp = []
# for node in level:
# if node.left:
# temp.append(node.left)
# if node.right:
# temp.append(node.right)
# level = temp
# 2.2
# level = [leaf for node in level for leaf in (node.left, node.right) if leaf]
# 2.3
LRpairs = [(node.left, node.right) for node in level]
level = [leaf for pair in LRpairs for leaf in pair if leaf]
return res
|
5eb2cb4485a3c3088ae0c3fce1c9483f7820f371 | Coliverfelt/Desafios_Python | /Desafio029.py | 493 | 4.15625 | 4 | # Exercício Python 029: Escreva um programa que leia a velocidade de um carro.
# Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado.
# A multa vai custar R$7,00 por cada Km acima do limite.
velocidade = float(input('Digite a velocidade (KM): '))
if velocidade > 80:
print('Você foi multado por exceder 80 Km/h!')
kmmais = velocidade - 80.0
print('A multa será no valor de R${:.2f}.'.format(kmmais * 7))
print('Tenha um bom dia! Dirija com segurança!') |
765bb20874de208036e97675cf90edf5552b3bd0 | tmeasday/phd-code | /Tournaments/Data/Synthetic/edge_crossings.py | 1,237 | 3.609375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
edge_crossings.py
Created by Tom Coleman on 2007-08-29.
Copyright (c) 2007 The University of Melbourne. All rights reserved.
"""
import sys
import os
import random
def main():
n_0 = int (sys.argv[1])
m = int (sys.argv[2])
p = float (sys.argv[3])
n_1 = n_0 # could do something different here...
random.seed ()
for run in range (m):
# construct the bipartite graph to be 'crossed'
graph = []
for i in range (n_0):
row = []
for j in range (n_1):
row.append (random.random () < p)
graph.append (row)
#print graph
# now make the tournament out of it...
top_weight = 0
tourn = []
for i in range (n_0):
row = []
for j in range (i+1, n_0):
weight = 0
for k in range (n_1):
if graph[i][k]:
weight -= sum ([1 for b in graph[j][:k] if b])
weight += sum ([1 for b in graph[j][k+1:] if b])
row.append (weight)
top_weight = max (abs(weight), top_weight)
tourn.append (row)
# print tourn
# now scale the tourn to look like one of ours
if top_weight != 0:
a = top_weight # shorter line
tourn = map (lambda l: map (lambda w: (w + a) / (2.0*a), l), tourn)
print tourn
if __name__ == '__main__':
main()
|
531d02c12a5beaa55b156528fee372ace35edd19 | AnshumaJain/MasteringPython | /Data_structures/add_two_numbers.py | 1,720 | 3.703125 | 4 | """
LeetCode Problem #2. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single
digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num1 = 0
i = 0
temp = l1
while temp:
num1 += temp.val * 10 ** i
i += 1
temp = temp.next
num2 = 0
i = 0
temp = l2
while temp:
num2 += temp.val * 10 ** i
i += 1
temp = temp.next
add = num1 + num2
count = 0
temp = add
while 1:
temp = temp // 10 ** 1
count += 1
if temp == 0:
break
l3 = None
temp = add
while count != 0:
digit = temp // (10 ** (count - 1))
temp = temp % (10 ** (count - 1))
count -= 1
l3 = ListNode(digit, l3)
return l3
if __name__ == "__main__":
sol = Solution()
list_node1 = ListNode(2, ListNode(4, ListNode(3, None)))
list_node2 = ListNode(5, ListNode(6, ListNode(4, None)))
list_node3 = sol.add_two_numbers(list_node1, list_node2)
print(list_node3.val)
print(list_node3.next.val)
print(list_node3.next.next.val) |
0e52ac561374d89cd4dee17a130416fdd2e9da5a | Andrey-A-K/hw_python_oop | /homework.py | 3,625 | 3.5 | 4 | import datetime as dt
class Record:
def __init__(self, amount, comment, date=None):
self.amount = amount
self.comment = comment
if date is None:
self.date = dt.datetime.now().date()
else:
self.date = dt.datetime.strptime(date, '%d.%m.%Y').date()
class Calculator:
"""
родительский класс калькулятора,
хранит записи (о еде или деньгах, но по сути - всё числа и даты),
знает дневной лимит
(сколько в день можно истратить денег или сколько калорий можно получить)
и суммирует записи за конкретные даты
"""
def __init__(self, limit):
self.limit = limit
self.records = []
def add_record(self, record): # добавляет новые записи в БД
self.records.append(record)
@staticmethod
def date_now(): # обновляет дату каждый день
return dt.datetime.now().date()
def get_stats(self, date): # возвращает сумму за указанную дату
return sum(record.amount for record in self.records
if record.date == date)
def get_today_stats(self): # возвращает сумму за сегодня
today = self.date_now()
return self.get_stats(today)
def today_remained(self): # возвращает остаток на сегодня
return abs(self.limit - self.get_today_stats())
def get_week_stats(self): # возвращает сумму за 7 дней
return sum(n.amount for n in self.records if self.date_now()
>= n.date > self.date_now() - dt.timedelta(days=7))
class CaloriesCalculator(Calculator):
"""
Калькулятор калорий, считает, превышен ли суточный лимит
и, в зависимости от этого, выводит сообщение на экран
"""
def get_calories_remained(self):
comparison = self.get_today_stats() >= self.limit
if comparison:
return 'Хватит есть!'
else:
return ('Сегодня можно съесть что-нибудь ещё, '
'но с общей калорийностью не более '
f'{self.today_remained()} кКал')
class CashCalculator(Calculator):
"""
Калькулятор денег, сравнивает потраченную сумму с лимитом
и выводит на экран результат и текстовое сообщение-комментарий
"""
USD_RATE = 60.0
EURO_RATE = 70.0
RUB_RATE = 1
lists = {'rub': ['руб', RUB_RATE],
'usd': ['USD', USD_RATE],
'eur': ['Euro', EURO_RATE]}
def remains(self, currency):
return round((self.today_remained() / self.lists[currency][1]), 2)
def get_today_cash_remained(self, currency):
comparison = self.limit - self.get_today_stats()
money = self.lists[currency][0]
if comparison == 0:
return ('Денег нет, держись')
elif comparison > 0:
return ('На сегодня осталось '
f'{self.remains(currency)} {money}')
else:
return (f'Денег нет, держись: твой долг '
f'- {self.remains(currency)} {money}')
|
ca93590acafd4fe2998867e3d48d2cbbc7c07bb6 | badordos/Doliner-labs-Python-2018 | /3) Ветвление/task9.py | 537 | 4.15625 | 4 | #Дано трехзначное число.
#Cоставьте программу, которая определяет, есть ли среди его цифр одинаковые.
x = int(input('Введите трехзначное число'))
xn = str(x)
res = list(xn)
res[0] = int(res[0])
res[1] = int(res[1])
res[2] = int(res[2])
if (res[0]==res[1] or res[0]==res[2] or res[1]==res[2]):
print ('В числе есть одинаковые цифры')
else: print ('В числе нет одинаковых цифр')
|
c3fb934aeaf8e5e96b2695f7969ce0ad1ae2a20b | dannycrief/full-stack-web-dev-couse | /Web/B/5/5.10/first.py | 743 | 4.125 | 4 | class Node(object):
def __init__(self, value=None, next_node=None):
self.value = value
self.next = next_node
def __str__(self):
return f"[Node with value {self.value}]"
def print_linked_list(head):
cur = head
while cur is not None:
cur = cur.next
return head
def reversed_linked_list(head):
cur = head
prev = None
while cur is not None:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
head = prev
return head
h, a, b, c, d = Node(1), Node(2), Node(3), Node("Внезапно"), Node(5)
h.next = a
a.next = b
b.next = c
c.next = d
print(print_linked_list(h))
h = reversed_linked_list(h)
print("---")
print(print_linked_list(h))
|
8f0c5da89cd31caa7e91268ca9b74c3a08dae54c | hminah0215/pythonTest | /day0420/ex06.py | 1,047 | 3.71875 | 4 |
""" n = 0
while True :
print("hello")
n = n + 1
if n == 3 :
break """
# 연습
# 사용자에게 정수를 입력받아 그 수가 몇자리 수 인지 판별하여 출력합니다(이번엔 반복문이용)
n = int(input("숫자를 입력하세요 ==> "))
cnt = 0
while True :
n = n // 10
cnt = cnt + 1
if n == 0 :
break
print (cnt)
# 연습
# 0~9999 사이의 정수를 입력받아 그 수가 몇자리 수 인지 판별하여 출력합니다.
# n = int(input("0~9999 사이의 숫자를 입력해주세요. ==>"))
""" if 0 <= n <= 9999 :
if n < 10 :
print(1)
elif n < 100 :
print(2)
elif n < 1000 :
print(3)
elif n < 10000 :
print(4)
else :
print("숫자를 다시 입력해주세요.") """
""" if 0 <= n <= 9999 :
if 0 <= n <= 9 :
print(1)
if 10 <= n <= 99 :
print(2)
if 100 <= n <= 999 :
print(3)
if 1000 <= n <= 9999 :
print(4)
else :
print("숫자를 다시 입력해주세요.") """ |
643eef8ce7622e1546cdee2f32dfbc1a43223035 | tengzejun508/pytestActualCombat | /pythoncode/calculator.py | 388 | 3.6875 | 4 | class Calculator():
def add(self, a, b):
return a+b
def sub(self, a, b):
return a - b
def mult(self, a, b):
return a * b
def divid(self, a, b):
try:
return a / b
except ZeroDivisionError as e:
return "除数不能为0"
# if __name__ == '__main__':
# calc = Calculator()
# print(calc.divid(2,0))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.