blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
6e8522cc26db3a4746c2d3bac5119cf139970be8 | asheed/tryhelloworld | /excercise/ex029.py | 1,021 | 3.796875 | 4 | # 029 도메인 추출
#
# 사용자로부터 웹 페이지 주소를 입력 받은 후 도메인을 출력하라.
# 도메인은 .com, .net, .org 만 지원한다. www는 반드시 입력된다.
#
# 실행 예:
# address: http://www.wikidocs.net/edit/page/7022
# domain: net
domain_list = ['.com', '.net', '.org']
address = input('address: ')
# 방법1
# found_domain = [domain for domain in domain_list if domain in address]
# print('domain:', found_domain[0][1:])
# 방법2
# found_domain = []
# for domain in domain_list:
# if domain in address:
# found_domain.append(domain)
#
# if not found_domain: # domain 정보를 찾지못했다..가 참이면
# print('입력한 주소에서 도메인 정보를 찾을 수 없습니다!!!')
# else:
# print('domain:', found_domain[0][1:])
## 방법3 : http://www. 가 반드시 입력된다고 가정했을때
domain_list2 = ['com', 'net', 'org']
domain = address.split('/')[2].split('.')[2]
if domain in domain_list2:
print('domain:', domain)
|
6e74b963ef803e4a70869bee244cd7ec1ecd351a | ericrochow/AoC_20 | /solutions/day2.py | 823 | 3.6875 | 4 | #!/usr/bin/env python3
from utils import read_input, read_template
def part_one(parsed_input):
count = 0
for entry in parsed_input:
occurances = entry[3].count(entry[2])
if int(entry[0]) <= occurances <= int(entry[1]):
count += 1
return count
def part_two(parsed_input):
count = 0
for entry in parsed_input:
# zero-indexify
a_position = int(entry[0]) - 1
b_position = int(entry[1]) - 1
# XOR positional matches
if (entry[3][a_position] == entry[2]) ^ (entry[3][b_position] == entry[2]):
count += 1
return count
if __name__ == "__main__":
TEMPLATE = read_template(2)
PARSED_INPUT = [TEMPLATE.ParseText(x) for x in read_input(2)].pop()
print(part_one(PARSED_INPUT))
print(part_two(PARSED_INPUT))
|
ee2286aad54be602323a6df2089e6e4467df4752 | byrage/algorithm | /src/main/python/q2920.py | 498 | 3.71875 | 4 | """
1 2 3 4 5 6 7 8
ascending, descending, mixed
"""
scale = list(map(int, input().split()))
if scale[0] == 1:
arrange = "ascending"
for index, elem in enumerate(scale):
if elem != index + 1:
arrange = "mixed"
print(arrange)
exit(0)
elif scale[0] == 8:
arrange = "descending"
for index, elem in enumerate(scale):
if elem != 8 - index:
arrange = "mixed"
print(arrange)
exit(0)
print(arrange)
|
ccafc93af2353ee72888360fdf2c598e835f9e3c | isaac88/PCAP | /Module2/2.1.4.7-lab-variables.py | 162 | 3.65625 | 4 |
juan = 3
maria = 5
adan = 6
print(juan,",",maria,",",adan)
totalApples = juan + maria + adan
print(totalApples)
print("Total Number of Apples:", totalApples)
|
9d7ecdfbcf44fc0d5bec643063475d6020a89707 | shgy/code-snippet | /python/gui-tk/Tkinter_helloworld.py | 1,852 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
本代码是 python library文档中的Hello World程序.
麻雀虽小, 五脏俱全.
如果已经有简单的GUI程序开发经验,比如html/css, bootstrap, java的awt/swing; 或者eclipse的swt/jface
那么理解起来就容易多了, 它们有很多相通的地方.
Tkinter的所有可视化部件都有一个共同的名字Widget, 其中Tk是最顶层的widget.
本程序用到了3个widget, 分别是: Tk, Frame, Button
如果使用HTML中的标签类比, 那么
Tk -- body
Frame -- div ; 它们都是容器
Button -- input[type='button']
可能到这里, 会有个疑问: Tkinter中都有哪些Widget呢?
GUI程序设计无法绕开的一个主题就是布局方式(Geometry manager). Tkinter一共有3种布局方式: pack/grid/place, 本程序用到的是pack方式.
self.hi_there.pack({"side": "left"})
pack 默认是从上到下排列, 设置了参数 side="left"后, 则变成了水平排列. 自己修改参数, 运行代码即可看到效果 .
"""
from Tkinter import *
class Application(Frame):
def say_hi(self):
print "hi there, everyone!"
def createWidgets(self):
self.QUIT = Button(self)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"] = "red"
self.QUIT["command"] = self.quit
self.QUIT.pack({"side": "left"})
self.hi_there = Button(self)
self.hi_there["text"] = "Hello",
self.hi_there["command"] = self.say_hi
self.hi_there.pack({"side": "left"})
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
root = Tk() # The Tk class is meant to be instantiated only once in an application.
app = Application(master=root)
app.mainloop()
# root.destroy() 这句代码是不需要的, 不然会报异常. "application has been destroyed" |
a257aba02b7459bb32f06c6bc3fa9c4ec1676460 | seanlab3/algorithms | /algorithms_practice/19.strings/12.Strings_int_to_roman.py | 189 | 3.8125 | 4 | """
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
"""
from algorithms.strings import int_to_roman
n=34
print(int_to_roman(n)) |
f4b68d61ce700619f9cf0feaa069a69f938e8cf4 | kazemicode/AdventOfCode | /2019/3/day3-part2.py | 1,096 | 3.78125 | 4 | def manhattan(pos):
return abs(pos[0]) + abs(pos[1])
def storePos(path):
positions = {}
x = 0
y = 0
steps = 0
for item in path:
direction = item[0]
amount = int(item[1:])
for i in range(amount):
if direction == 'U': y += 1
elif direction == 'D': y -= 1
elif direction == 'R': x += 1
elif direction == 'L': x -= 1
steps += 1
pos = (x,y)
if pos not in positions: # only store first time reached
positions[pos] = steps
return positions
with open("input.txt", 'r') as f:
w1 = f.readline().strip().split(',')
w2 = f.readline().strip().split(',')
wire1 = storePos(w1)
wire2 = storePos(w2)
cross = set(wire1.keys()).intersection(set(wire2.keys()))
leastSteps = float('inf')
for position in cross:
if wire1[position] + wire2[position] < leastSteps:
leastSteps = wire1[position] + wire2[position]
intersection = position
print("Least amount of steps to intersection %s is %d steps" %(intersection, leastSteps))
|
89a134eb8ce3aa49fe2e89ddc1faee2a9bc03207 | pauliwu/Introduction-to-programming-in-python | /Laboratory 10/wdp_ftopt_l10z03pr.py | 911 | 3.96875 | 4 | '''
Napisz program, który poprosi użytkownika o podanie imion i nazwisk, następnie wyświetli na
ekranie napis zawierający stosowne inicjały. Postaraj się zwrócić inicjały w postaci dużych
liter. W przypadku posiadania kilku imion/nazwisk, np. Jan Maciej Karol Wścieklicy, wypisz
ich liczbę.
'''
def main():
imiona = input("Podaj swoje imiona: ")
nazwiska = input("Podaj swoje nazwiska: ")
print(imiona[0], end='. ')
licznik_imion = 1
for i in range(len(imiona)-1):
if imiona[i] == ' ':
print(imiona[i+1], end = '. ')
licznik_imion += 1
print(nazwiska[0], end='. ')
licznik_nazwisk = 1
for i in range(len(nazwiska)-1):
if nazwiska[i] == ' ':
print(nazwiska[i+1], end = '. ')
licznik_nazwisk += 1
print("\nLiczba imion",licznik_imion)
print("Liczba nazwisk", licznik_nazwisk)
main()
|
e747eb577c77a2f6a831715ae5357721fc7c243c | NikDestrave/GeekBrains_Python | /lesson_2_dz3.py | 940 | 4 | 4 | # 3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.
seasons_list = ['', 'Зима', 'Зима', 'Весна', 'Весна', 'Весна', 'Лето', 'Лето', 'Лето', 'Осень', 'Осень', 'Осень', 'Зима']
seasons_dict = {12:'Зима', 1:'Зима', 2:'Зима', 3:'Весна', 4:'Весна', 5:'Весна', 6:'Лето', 7:'Лето', 8:'Лето', 9:'Осень', 10:'Осень', 11:'Осень'}
month = int(input('Введите номер месяца: '))
# Решение через list
print('Ваше время года:', seasons_list[month])
# Решение через dict
print('Ваше время года:', seasons_dict.get(month))
|
bbf16b7d1b9e62813f7c7a409f52b62a532198e0 | Guilherme-Galli77/Curso-Python-Mundo-2 | /Exercicios/Ex039 - Alistamento Militar.py | 855 | 4.15625 | 4 | #Exercício Python 39: Faça um programa que leia o ano de nascimento de um jovem
# e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar,
# se é a hora exata de se alistar ou se já passou do tempo do alistamento.
# Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.
from datetime import date
ano = int(input("Ano de nascimento: "))
idade = date.today().year - ano
print("Quem nasceu em {} tem {} anos em {} ".format(ano, idade, date.today().year))
if idade < 18:
print("Ainda faltam {} anos para o alistamento".format(18-idade))
print("Seu alistamento será em {}".format(date.today().year + (18-idade)))
elif idade == 18:
print("Você tem {} anos e está na hora de se alistar! ".format(idade))
else:
print("Você passou em {} anos o prazo de se alistar".format(idade-18))
|
796c4002bdc8c862c6eb21802f0baf8414a09630 | maheshmnj/POPULAR_CODING_Questions_Solution | /leetcode/problem_215.py | 1,493 | 3.734375 | 4 | # Problem 215: Kth Largest Element in an Array (Medium): https://leetcode.com/problems/kth-largest-element-in-an-array/
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
sorted_array = self.merge_sort(nums)
return sorted_array[len(sorted_array) - k]
def mergeHalves(self,left,right):
len_left = len(left)
len_right = len(right)
merged = []
ldx = 0
rdx = 0
for i in range(0, (len_left+len_right)):
if(ldx>=len_left):
merged.append(right[rdx])
rdx+=1
elif(rdx >= len_right):
merged.append(left[ldx])
ldx+=1;
else:
if(left[ldx]< right[rdx]):
merged.append(left[ldx])
ldx+=1
else:
merged.append(right[rdx])
rdx+=1
return merged
def merge_sort(self, array):
start = 0
end = len(array) - 1
if(len(array) <= 1):
return array
else:
mid = (end - start) // 2
left_array = array[start : mid + 1]
right_array = array[mid+1 : end + 1]
left_half = self.merge_sort(left_array) # left_half
right_half = self.merge_sort(right_array) # right_half
return self.mergeHalves(left_half,right_half) |
3e8a4b71c755a134b628f9c81c2ec4a49234be77 | swoogles/RoundToNearestX | /rounder.py | 1,458 | 3.796875 | 4 | # Test data defined in assignment
# This is stored in unorderd maps, since I don't feel that the order of testing
# is significant.
values50 = {
54:50,
75:100,
98:100,
119:100,
}
values22 = {
22:22,
29:22,
33:44,
47:44,
}
fullData = {
50: values50,
22: values22,
}
"""
Return number rounded to nearest multiple of base
Per the assignment:If the result is 0, return the base, as it will have to be
the next closest multiple.
Arguments:
startNum -- Number to be rounded
base -- Base to determine rounding values
"""
def round_to_base(startNum, base):
assert base > 0, "Invalid base for rounding"
# Left side of the decimal point is the number of times the base
# can be divided into the number.
# Right hand side determines whether you will go up or down for
# nearest multiple.
firstDiv = (float(startNum)/base)
result = int(base * round(firstDiv))
if result == 0:
result = base
return result
# Iterate through maps of test data with corresponding base
for base, testData in fullData.items():
# num is the starting value
# roundedTarget is what it should be rounded to
for num, roundedTarget in testData.items():
roundedActual = round_to_base(num, base)
assert roundedTarget == roundedActual, (
"Expected: %r Got: %r" % (roundedTarget, roundedActual))
print("Number: ", num, " Rounded: ", roundedTarget)
|
c09a301039654ddd8849df2c69271f623e56463b | fxy1018/Leetcode | /513_FindBottomLeftTreeValue.py | 1,138 | 4.03125 | 4 | '''
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input:
2
/ \
1 3
Output:
1
Example 2:
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return(None)
queue=[(root, 1)]
res = []
p = 0
while queue:
node, level = queue[0]
queue = queue[1:]
if node.left:
queue.append((node.left,level+1))
if node.right:
queue.append((node.right,level+1))
if len(res) < level:
res.append([node.val])
else:
res[level-1].append(node.val)
return(res[-1][0])
|
d26bd99cb98051b1dd8cfffb66a4b4a439ce580f | DeadSoul-Zh/LeetCode | /258-AddDigits.py | 384 | 3.65625 | 4 | class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
n = 0
while num >= 0:
n += (num % 10)
num /= 10
if num == 0 :
break;
if n == 0 :
return 0
elif n % 9 != 0:
return n % 9
else:
return 9
|
af5a71efa227d8f2cdf5e309327cffdbfc19ee30 | adebayo5131/Python | /selectionSort.py | 324 | 3.5625 | 4 | import time
start_time = time.time()
def selectionSort(a):
for i in range(len(a)):
j=i+1
for j in range(len(a)):
if a[j] > a[i]:
a[j], a[i] = a[i],a[j]
return a
arr=[7, 8, 3, 11, 43, 55]
print(selectionSort(arr))
print("--- %s seconds ---" % (time.time() - start_time))
|
3901bfba1951eed6c885eac6bb804f98a9532ea6 | suchismitarout/pythonpractice | /emp_sort.py | 1,161 | 3.734375 | 4 | def merge_sort(list1, r):
if len(list1) > 1:
mid = len(list1)//2
left = list1[:mid]
right = list1[mid:]
merge_sort(left, r)
merge_sort(right, r)
i = j = k = 0
while i < len(left) and j < len(right):
if left[i].__getattribute__(r) < right[j].__getattribute__(r):
list1[k] = left[i]
i += 1
else:
list1[k] = right[j]
j += 1
k += 1
while i < len(left):
list1[k] = left[i]
i += 1
k += 1
while j < len(right):
list1[k] = right[j]
j += 1
k += 1
return list1
class Employee:
def __init__(self, id, sal):
self.id = id
self.sal = sal
def __repr__(self):
return "id:{}, sal:{}".format(self.id, self.sal)
e1 = Employee(2,30000)
e2 = Employee(15, 45558)
e3 = Employee(3, 25000)
e4 = Employee(7, 27000)
e5 = Employee(1, 24000)
# print(dir(e5))
# print(e5.__getattribute__("sal"))
def emp_sort(em_list, sal):
return merge_sort(em_list, sal)
print(emp_sort([e1,e2,e3,e4,e5],'sal')) |
7b348e11a87a9a970ea2a67c884e7be663194e81 | lirui-boom/Python | /20190402/5.Transform.py | 222 | 3.921875 | 4 | ascii = ord(input("请输入一个大写字母:"))
if ascii <=90 and ascii >= 65:
ascii = ascii + 32
c = chr(ascii)
print("小写字母是:",c)
else :
print("输入的字符不是一个大写字母!") |
259a83d5e08ae020ae186b301cfb86747d88742d | Nikunj-kumar/Fizzbuzz | /Fizzbuzz.py | 314 | 4.09375 | 4 | def fizzbuzz(n):
if n%3==0 and n%5==0:
print("Fizzbuzz")
elif n%5==0:
print("buzz")
elif n%3==0:
print("Fizz")
else:
print("Enter valid number")
fizzbuzz(8)
#execute it here fizzbuzz(21)
#or go to the line then enter fizzbuzz(enter the number)
|
1d6d3bd7b870bd1b8be8a262659f0456a1640fac | GuilhermeCarrato/cine_system- | /apdtrab/sessao.py | 1,872 | 3.703125 | 4 | import controle_sessao
#import é salvo nesta variavel para ser usado somente nesse modulo com esse nome
cs = controle_sessao
def imprimir_sessao(lista_sessao):
print("codigo sessão",lista_sessao[0],"Codigo do filme ",lista_sessao[1]," ","Codigo da Sala ",lista_sessao[2]," ","Horario ",lista_sessao[3])
print("")
def criar_sessao ():
cod_sessao = str(input("Digite o cod da sessao"))
cs.criar_sessao(cod_sessao)
def deletar_sessao():
cod = str(input("Digito o codigo da sessão a ser deletada"))
result= cs.remover_sessao(cod)
if (result == True):
print("A sessão foi deletada")
else:
print("Sessão não encontrada!!")
def listar_sessao():
sessoes = cs.lista_sessao()
for s in sessoes:
imprimir_sessao(s)
def buscar_sessao():
print("Buscar por codigo de sessão")
cod = str (input("Digite o codigo da Sessão"))
s = cs.buscar_sessao(cod)
if ( s == None ):
print("Sessão n encontrada")
else:
imprimir_sessao(s)
def remover_todas_sessoes():
cs.remover_todas_sessoes()
def mostrar_sessao():
run_sessao = True
menu =("\n----------------\n"+
"(1) Adicionar nova sessão \n" +
"(2) Listar Sessão \n" +
"(3) Buscar Sessão \n" +
"(4) Remover Sessão \n" +
"(5) Remover Todas as sessões \n"+
"(0) Sair\n"+
"----------------")
while(run_sessao == True):
print(menu)
op = int (input("Escolha uma opção "))
if (op == 1):
criar_sessao()
elif (op == 2):
listar_sessao()
elif (op == 3):
buscar_sessao()
elif (op == 4):
remover_sessao()
elif (op == 5):
remover_todas_sessoes()
elif (op == 0):
run_sessao = False
mostrar_sessao() |
f87ea988843b54e8060eb1157ab27fbe55ee976a | TheDesTrucToRR/Hacktoberfest-2021 | /Python/subnet_calculator/subnetting_function.py | 1,542 | 3.578125 | 4 | from ip_addition import ip_addition
from network_functions import broadcast
from ip_conversions import slash_mask_to_ip
def subnetting(ipaddr, mask, host_count, file_name):
"""
Function creates a markdown table from given values and adds them to a file
Parameters:
-----------
ipaddr:
dec IP-address
mask:
subnet mask
host_count:
amount of useable hosts
file_name:
name of the file where tables are saved
Returns:
--------
"""
mask_slash = "/" + str(mask)
bc = broadcast(ipaddr, mask)
start = ip_addition(ipaddr, 1)
stop = ip_addition(bc, -1)
mask_ip = slash_mask_to_ip(mask)
filename = "{}.txt".format(file_name)
file = open(filename, "a")
file.write("| Specification | Subnet info |\n")
file.write("|-------------------------------------------|--------------------|\n")
file.write("| New subnet mask | {0: <18} |\n".format(mask_ip + mask_slash))
file.write("| Number of usable hosts in the subnet | {0: <18} |\n".format(host_count))
file.write("| Network address | {0: <18} |\n".format(ipaddr + mask_slash))
file.write("| First IP Host address | {0: <18} |\n".format(start))
file.write("| Last IP Host address | {0: <18} |\n".format(stop))
file.write("| Broadcast address | {0: <18} |\n".format(bc))
file.write("\n")
file.close() |
797e73c0e182ca479711e818d7c083d64c3a6987 | Aravind2595/MarchPythonProject | /collections/list/demo10.py | 245 | 3.890625 | 4 | #1 to 100
#add even number to new list
#add odd number to list
lst=[]
even=[]
odd=[]
for i in range(1,101):
lst.append(i)
print(lst)
for j in lst:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print(even)
print(odd) |
d0438108ab4614562a25b5bae0617ac5f2b6c821 | johnellis1392/programming_problems | /hackerrank/python/problem_solving/insert_node_at_head_of_linked_list/main.py | 669 | 3.796875 | 4 | class SinglyLinkedListNode():
data: int
next = None
def __init__(self, v) -> None:
self.data = v
class LinkedList():
head: SinglyLinkedListNode = None
def insertNodeAtHead(head, data):
node = SinglyLinkedListNode(data)
if head is None:
return node
else:
node.next = head
return node
def printAll(node):
n = node
while n is not None:
print(n.data)
n = n.next
if __name__ == '__main__':
filename = './input.txt'
with open(filename) as f:
n = int(f.readline().rstrip())
ll = LinkedList()
for _ in range(n):
v = int(f.readline().rstrip())
ll.head = insertNodeAtHead(ll.head, v)
printAll(ll.head) |
cd3270e1617c9cbf41e41510024f57592b78479d | MLL1228/mycode | /leetcode/88Merge Sorted Array.py | 995 | 3.859375 | 4 | class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
# 对 nums2 里的每一个元素,在 nums1 里面进行二分查找,返回索引值,插在返回值的右侧
for i in range(len(nums2)):
index = self.binary_search(nums1, m+i, nums2[i])
for j in range(m+i, index, -1):
nums1[j] = nums1[j-1]
nums1[index+1] = nums2[i]
print(nums1)
def binary_search(self, nums, m, target):
for i in range(m):
if nums[i] == target:
return i
elif nums[i] > target:
return i - 1
else:
return m-1
s = Solution()
nums1 = [4, 0, 0, 0, 0, 0]
nums2 = [1, 2, 3, 5, 6]
s.merge(nums1, 1, nums2, 5)
|
4b82be6c2ccad170d64a45c048e0a6036c59eacf | zoeny/test_commit | /算法/双指针/7、最长子序列.py | 1,193 | 3.671875 | 4 | # -*- coding: utf-8 -*-
'''
@project: Pycharm_project
@Time : 2019/6/19 18:40
@month : 六月
@Author : mhm
@FileName: 7、最长子序列.py
@Software: PyCharm
'''
'''
eg:Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
Output:
"apple"
'''
'''
思路:
1)先把d中的元素按长度排序;
2)将满足条件的且最长的字符串存在res中。引入flag变量和maxlen变量,来判断是否应该存入res中。
3)如果len(res)为1,则输出。如果>1,则再将res进行排序,输出res[0].
'''
def findLongestWord(s,d):
d.reverse()
res = []
maxlen = 0
flag = 0
d = sorted(d,key=lambda x:len(x))
for item in d[::-1]:
if flag == 1 and len(item) < maxlen:
break
i = j = 0
while i < len(item) and j < len(s):
if item[i] == s[j]:
i += 1
j += 1
if i == len(item):
flag = 1
maxlen = len(item)
res.append(item)
if res == []:
return ''
elif len(res) == 1:
return res[0]
res.sort()
return res[0]
print(findLongestWord(s = "abpcplea", d = ["ale","apple","monkey","plea"]))
|
aa7c4519b4d6c2ca342d07b1166482b1ecc988a1 | jmery24/python | /ippython/funciones_inversion_305.py | 648 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 26 09:52:29 2013
@author: daniel
"""
#programa: funciones_inversion_305.py
#escribe un procedimiento para invertir un numero entero
#ejemplo: input = 324, output = 4 2 3 en lineas diferentes
#ejercicio 305
#definir el procedimiento <inversion>
def inversion(num):
invertido = 0
while num > 0:
invertido = invertido * 10 + num % 10
num = num / 10
cadena = str(invertido)
for i in range(0, len(cadena)):
print cadena[i]
#cuerpo general del programa
#data input
numero = int(raw_input('Escribe un numero entero: '))
#activa el procedimiento
inversion(numero) |
637ca3bd451e6d4654988e62564cedb406c36442 | A-khateeb/Full-Stack-Development-Path | /Python/PCC/Chapter11/TestClasses/test_classes.py | 1,090 | 3.921875 | 4 | """
assertEqual(a,b) a == b
assertNotEqual(a,b) a != b
assertTrue(x) x is true
assertFalse(x) x is false
assertIn(item, list) item is in the list
assertNotIN(item, list) item is not in the list
"""
import unittest
from classes import AnonymousSurvey
class TestAnonSurvey(unittest.TestCase):
def setUp(self):
question = "What languages did you first learn to speak"
self.my_survey = AnonymousSurvey(question)
self.responses = ["English","Spanish","Arabic"]
def test_store_single_response(self):
# question = "What langauge did you first learn to speak?"
# my_survey = AnonymousSurvey(question)
# my_survey.store_response("English")
# self.assertIn('English', my_survey.responses)
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0],self.my_survey.responses)
def test_three_responses(self):
for i in self.responses:
self.my_survey.store_response(i)
for i in self.responses:
self.assertIn(i, self.my_survey.responses)
unittest.main()
|
0de0a6821c76d4c410ce659c1eae5dedb34da327 | defpearlpilot/pychallenges | /easy/counting_valleys.py | 1,007 | 3.796875 | 4 |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
level = 0
valleys = 0
maybe_valley = False
for step in s:
if step == 'D':
level -= 1
if level < 0:
maybe_valley = True
elif step == 'U':
level += 1
if level == 0 and maybe_valley:
valleys += 1
maybe_valley = False
return valleys
def solve(reader, solution):
n = int(reader())
ar = reader()
return solution(n, ar)
def solve_std_in():
fptr = open(os.environ['OUTPUT_PATH'], 'w')
result = solve(lambda: input(), countingValleys)
fptr.write(str(result) + '\n')
fptr.close()
def solve_from_file(file):
with open(file, 'r') as f:
result = solve(lambda: f.readline(), countingValleys)
print(result)
if __name__ == '__main__':
solve_from_file("counting_valleys.txt")
|
90ed31aa52087c168cea37e14abbba767ced076d | cajakey/cryptogra.py | /cryptogra.py | 4,750 | 3.8125 | 4 | import os
def generateKey(string, key):
key = list(key)
if len(string) == len(key):
return(key)
else:
for i in range(len(string) - len(key)):
key.append(key[i % len(key)])
return("" . join(key))
while True:
# settings
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
beta = "SUBDERMATOGLYPHICFJKNQVWXZ"
rotate = 9
row = 4
vinegar = "DADOJULIESITTINGONTHETREEKISSING"
# main menu
print("Type [exit] to close the program")
print(" [encr] to encrypt a plaintext")
print(" [decr] to decrypt a ciphertext")
selected = input()
os.system("cls")
if selected == "exit" or selected == "EXIT":
break
elif selected == "encr" or selected == "ENCR":
plain = input("Type your plain text: ")
# character count
count = 0
for x in plain:
if x.isalpha():
count += 1
if all(x.isalpha() or x.isspace() for x in plain) and count % 12 == 0:
plain = plain.upper()
# encryption
encrypted = ""
for x in range(len(plain)):
for y in range(len(alpha)):
if plain[x] == alpha[y]:
encrypted += beta[y]
if plain[x] != " ":
# left rotation
beta = beta[rotate:] + beta[:rotate]
# matrix transfer
z = 0
w, h = int(len(encrypted) / row), row
matrix = [['' for x in range(w)] for y in range(h)]
for x in range(h):
if z != 0:
z += 1
for y in range(w):
matrix[x][y] = encrypted[y + z]
z += y
# transposition
encrypted = ""
for y in range(w):
for x in range(h):
encrypted += matrix[x][y]
# vigenere
cipher_text = []
key = generateKey(encrypted, vinegar)
for i in range(len(encrypted)):
x = (ord(encrypted[i]) + ord(key[i])) % 26
x += ord('A')
cipher_text.append(chr(x))
encrypted = "" . join(cipher_text)
# result display
print("\nEncrypted text: ", end="")
print(*[encrypted[x:x + 3] for x in range(0, len(encrypted), 3)])
input("\nPress any key to continue...")
os.system("cls")
# entry restriction
else:
os.system("cls")
print("Alphabetical letters and spaces only")
print("Character count must be a multiple of 12\n")
elif selected == "decr" or selected == "DECR":
cipher = input("Type your cipher text: ")
# character count
count = 0
for x in cipher:
if x.isalpha():
count += 1
if all(x.isalpha() or x.isspace() for x in cipher) and count % 12 == 0:
cipher = cipher.upper()
cipher = cipher.replace(" ", "")
# vigenere
orig_text = []
key = generateKey(cipher, vinegar)
for i in range(len(cipher)):
x = (ord(cipher[i]) - ord(key[i]) + 26) % 26
x += ord('A')
orig_text.append(chr(x))
cipher = "" . join(orig_text)
# matrix transfer
z = 0
w, h = row, int(len(cipher) / row)
matrix = [['' for x in range(w)] for y in range(h)]
for x in range(h):
if z != 0:
z += 1
for y in range(w):
matrix[x][y] = cipher[y + z]
z += y
# transposition
cipher = ""
for y in range(w):
for x in range(h):
cipher += matrix[x][y]
# decryption
decrypted = ""
for x in range(len(cipher)):
for y in range(len(alpha)):
if cipher[x] == beta[y]:
decrypted += alpha[y]
beta = beta[rotate:] + beta[:rotate]
# result display
print("\nDecrypted text: ", end="")
print(*[decrypted[x:x + 3] for x in range(0, len(decrypted), 3)])
input("\nPress any key to continue...")
os.system("cls")
# entry restriction
else:
os.system("cls")
print("Alphabetical letters and spaces only")
print("Character count must be a multiple of 12\n")
else:
print("Please try again\n")
|
203fe94fede25f5ca3ed26bb33f036294ad23420 | JoElleBall/learn-python | /task_06.py | 542 | 3.8125 | 4 | """
Iterate over the list below, and print out the value of the key "size".
"""
vehicles = [
{
"make": "Vauxhall",
"model": "Astra",
"engine": {
"size": "1.0l",
"cylinders": 4,
},
},
{
"make": "BMW",
"model": "i5",
"engine": {
"size": "2.5l",
"cylinders": 6,
},
},
{
"make": "Audi",
"model": "R8",
"engine": {
"size": "4.8l",
"cylinders": 8,
}
},
]
|
02ca5e65a52681a94ffc6d59d7022755533bedbd | rosalFernando/Python | /bucleWhile.py | 877 | 3.890625 | 4 | """
i=1
while i<=10:
print("ejecucion" + str(i))
i=i+1
print("fin ejecucion")
"""
#programa para introducir una edad correcta con bucle while
"""
edad=int(input("introduce la edad: "))
while edad<5 or edad>100:
print("edad incorrecta, vuelve a intentarlo")
edad=int(input("introduce la edad: "))
print("edad correcta.")
print("edad del aspirante " + str(edad))
"""
#hayar raiz cuadrada de un numero.
import math
print("programa de calculo de raiz cuadrada")
numero=int(input("introduce un numero: "))
intentos=0
while numero<0:
print("no se puede hayar la raiz de un nuemero negativo")
if intentos==2:
print("has consumidos demasiados intentos. programa finalizado")
break
numero=int(input("introduce un numero: "))
if numero<0:
intentos=intentos+1
if intentos<2:
solucion=math.sqrt(numero)
print("solucion de " + str(numero)+ "es " + str(solucion))
|
689d56995e18771360d75ae4b0efaee3d61d2a05 | shruthilayaj/aoc2020 | /09/main.py | 1,279 | 3.59375 | 4 | import os
class SumNotFound(Exception):
pass
def read_input():
filename = os.path.join(os.path.dirname(__file__), "input.txt")
with open(filename) as f:
data = f.readlines()
return data
def encoding_error(records):
sliding_window = records[:25]
def get_sum(target):
for i, x in enumerate(sliding_window):
remainder = target - x
if remainder in sliding_window[i:]:
return
else:
raise SumNotFound
for num in records[25:]:
try:
get_sum(num)
except SumNotFound:
return num
else:
sliding_window.pop(0)
sliding_window.append(num)
def encoding_error_2(target):
sliding_window = records[:2]
i = 2
while True:
if sum(sliding_window) == target:
return min(sliding_window) + max(sliding_window)
if sum(sliding_window) < target:
sliding_window.append(records[i])
i += 1
elif sum(sliding_window) > target:
sliding_window.pop(0)
if __name__ == "__main__":
records = [int(x) for x in read_input()]
target = encoding_error(records)
print(f"Part 1: {target}")
print(f"Part 2: {encoding_error_2(target)}")
|
d387fb023955057b4710e7a3341c2965627434c0 | gschen/sctu-ds-2020 | /1906101087-钟欣洋/day0225/作业6.py | 197 | 3.625 | 4 | #选做6
def wyh(x):
R=0
n=1
m=2
if x%2>0:
while n<=x:
R=R+1/n
n=n+2
else:
while n<=x:
R=R+1/m
m=m+2
print(R) |
64c3b90568e5fe2f993d5dea26444a0ac47d6240 | tjoloi/CTF | /UnitedCTF/2020/Crypto/Le flag de Jules/solve.py | 360 | 3.609375 | 4 | import string
def caesar(word, shift, alphabet=string.ascii_lowercase):
decoded = ''
for c in word:
try:
decoded += alphabet[(alphabet.index(c) + shift) % len(alphabet)]
except:
decoded += c
return decoded
for i in range(26):
dec = caesar("IODJ-YHQLYLGLYLFL", i, string.ascii_uppercase)
if 'FLAG-' in dec:
print(dec, '\nWith n =', i)
break |
d407a67a55872a2c027a9682b99f6e937184cb1b | bizzcat/codeguild | /python/builtin_functions_list.py | 1,376 | 3.90625 | 4 | len([1, 2, 3, 4, 6, 7, 10]) # 7 - for seven values in list
reversed([1, 2, 5, 3]) # [3, 5, 2, 1]
sorted([5, 3, 1, 2]) # [1, 2, 3, 5]
set([1, 2, 2]) # {1, 2}
list({1, 2}) # [1, 2]
tuple([1, 2, 2])
product_to_price_cents = {
'apple': 99,
'pear': 150
}
product_to_price_dollars = {
product: price_cents / 100
for product, price_cents
in product_to_price_cents.items()
}
{value: key for key, value in d.items()}
prices_in_dollars = [1.50, 0.75]
prices_in_cents = [dollar_val * 100 for dollar_val in prices_in_dollars]
words_in_document = {'the', 'cat', 'hat'}
uppercase_words_in_document = {word.upper() for word in words_in_document}
(1, 2) + (3, 4) == (1, 2, 3, 4)
len([1, 2, 3]) # 3
reversed([1, 2, 2]) # [2, 2, 1]
sorted([5, 3, 1, 2]) # [1, 2, 3, 5]
set([1, 2, 2]) # {1, 2}
list({1, 2}) # [1, 2]
tuple([1, 2, 2]) # (1, 2, 2)
dict([('apple', 99), ('pear', 150)])
dict.items()
dict(somedict.items()) == somedict
enumerate(['a', 'b', 'c']) # [('a', 0), ('b', 1), ('c', 2)]
# (item, index)
names = ['Al', 'Alice']
for name, i in enumerate(names):
print('Name #{}: {}'.format(i, name))
zip(['apple', 'pear'], [99, 150]) # [('apple', 99), ('pear', 150)]
range(5) # [0, 1, 2, 3, 4]
for i in range(5):
whatever
|
79fae85ed900e52e39ac372f5be2c5ca4830a57b | SAI-VARMA427/coder-in-future | /example 2805.py | 610 | 4 | 4 | """
num=int(input())
for i in range(num):
for j in range(num):
print("*",end="")
print()
"""
"""
num=int(input())
for i in range(1,num+1):
for j in range(1,num+1):
print(j,end="")
print()
"""
"""
num=int(input())
for i in range(num):
for j in range(num):
print("*",end="")
print()
"""
num=int(input())
for i in range(1,num+1):
if i%2:
x=1
y=num
d=1
else:
x=num
y=1
d=-1
for j in range(x,y+d,d):
print(j,end="")
print()
|
e0451ae999e6d689ec473893c60463dc7a6b4402 | xharaken/random | /dfs_expected.py | 4,378 | 3.90625 | 4 | #! /usr/bin/python3
import collections
# An example graph structure
links = {"A": ["B","E","G"],
"B": ["C"],
"C": ["D"],
"D": ["E"],
"E": ["B","F"],
"F": [],
"G": ["F"]}
# A helper function to find a path.
def find_path(goal, previous):
path = []
node = goal
path.append(node)
while previous[node]:
node = previous[node]
path.append(node)
path.reverse()
return path
# dfs_with_recursion finds A -> B -> C -> D -> E -> F first.
def dfs_with_recursion(start, goal):
print("dfs_with_recursion:")
visited = {}
previous = {}
visited[start] = True
previous[start] = None
recursion(start, goal, visited, previous)
if goal in previous:
print(" -> ".join(find_path(goal, previous)))
else:
print("Not found")
def recursion(node, goal, visited, previous):
if node == goal:
return True
for child in links[node]:
if not child in visited:
visited[child] = True
previous[child] = node
if recursion(child, goal, visited, previous):
return True
return False
# dfs_with_stack finds A -> G -> F first.
def dfs_with_stack(start, goal):
print("dfs_with_stack:")
stack = collections.deque()
visited = {}
previous = {}
stack.append(start)
visited[start] = True
previous[start] = None
while len(stack):
node = stack.pop()
if node == goal:
break
for child in links[node]:
if not child in visited:
stack.append(child)
visited[child] = True
previous[child] = node
if goal in previous:
print(" -> ".join(find_path(goal, previous)))
else:
print("Not found")
# Challenge quiz: Implement DFS using a stack that visits nodes and edges
# in the same order as dfs_with_recursion. In other words, implement DFS that
# finds A -> B -> C -> D -> E -> F first using a stack.
# Solution 1
def dfs_with_stack_in_the_recursion_order_1(start, goal):
print("dfs_with_stack_in_the_recursion_order_1:")
stack = collections.deque()
visited = {}
previous = {}
stack.append(start)
previous[start] = None
while len(stack):
node = stack.pop()
visited[node] = True
if node == goal:
break
for child in reversed(links[node]):
if not child in visited:
stack.append(child)
previous[child] = node
if goal in previous:
print(" -> ".join(find_path(goal, previous)))
else:
print("Not found")
# Solution 2
def dfs_with_stack_in_the_recursion_order_2(start, goal):
print("dfs_with_stack_in_the_recursion_order_2:")
stack = collections.deque()
visited = {}
previous = {}
stack.append((start, 0))
visited[start] = True
previous[start] = None
while len(stack):
(node, index) = stack.pop()
if node == goal:
break
if index < len(links[node]):
stack.append((node, index + 1))
child = links[node][index]
if not child in visited:
stack.append((child, 0))
visited[child] = True
previous[child] = node
if goal in previous:
print(" -> ".join(find_path(goal, previous)))
else:
print("Not found")
# Solution 3
def dfs_with_stack_in_the_recursion_order_3(start, goal):
print("dfs_with_stack_in_the_recursion_order_3:")
stack = collections.deque()
visited = {}
previous = {}
current = None
child = start
while True:
if not child in visited:
visited[child] = True
previous[child] = current
for i in reversed(range(len(links[child]))):
stack.append((child, i))
if len(stack) == 0:
break
(current, index) = stack.pop()
if current == goal:
break
child = links[current][index]
if goal in previous:
print(" -> ".join(find_path(goal, previous)))
else:
print("Not found")
dfs_with_recursion("A", "F")
dfs_with_stack("A", "F")
dfs_with_stack_in_the_recursion_order_1("A", "F")
dfs_with_stack_in_the_recursion_order_2("A", "F")
dfs_with_stack_in_the_recursion_order_3("A", "F")
|
d7cc6c948dd1d2befd4d4ff421500ac04083c629 | KevinPan0508/crypto-HW | /hw1/release/rsa/server.py | 2,879 | 3.5625 | 4 | #! /usr/bin/env python3
import os
from Cryptodome.Util.number import getStrongPrime
from secret import *
class rsa_key:
def __init__(self):
self.e = 3
self.p = getStrongPrime(512, 3)
self.q = getStrongPrime(512, 3)
self.n = self.p * self.q
self.phi = (self.p-1) * (self.q-1)
self.d = pow(self.e, -1, self.phi)
def encrypt(m, key):
return pow(m, key.e, key.n)
def decrypt(c, key):
return pow(c, key.d, key.n)
def valid_input():
while True:
num = input('Please give me a positive integer: ')
try:
num = int(num)
return num%(1<<1024)
except:
pass
def getflag1():
key = rsa_key()
c = encrypt(int.from_bytes(flag1.encode(), 'big'), key)
print('This is the first encrpyted flag. Oops! It seems too short!')
print(f'encrypted flag: {c}')
return
def getflag2():
key = rsa_key()
c = encrypt(int.from_bytes(flag2.encode(), 'big'), key)
print('This is the second encrypted flag. This time, I made the flag long enough. HAHAHA!!!')
print(f'encrypted flag: {c}')
print(f'Umm... let me give you the modulus n: {key.n}')
return
def getflag3():
key = rsa_key()
flag = int.from_bytes(flag3.encode(), 'big')
print('Let me encrypt something for you~')
m1 = valid_input()
c1 = encrypt(m1, key)
print(f'Here is your encrypted number: {c1}')
print('This is the third encrypted flag. Can you get it?')
c = encrypt(flag, key)
print(f'encrypted flag: {c}')
return
def getflag4():
key = rsa_key()
flag = int.from_bytes(flag4.encode(), 'big')
print('Since e is so small, let\'s use d to encrypt.')
print('Let me encrypt something for you~')
m1 = valid_input()
c1 = decrypt(m1, key)
print(f'Here is your encrypted number: {c1}')
print('I can encrypt another one~')
m2 = valid_input()
c2 = decrypt(m2, key)
print(f'Here is your decrypted number: {c2}')
print('This is the last encrypted flag. Can you get it?')
c = decrypt(flag, key)
print(f'encrypted flag: {c}')
return
def menu():
print('===================')
print(' 1. flag1(2%) ')
print(' 2. flag2(3%) ')
print(' 3. flag3(5%) ')
print(' 4. flag4(bonus 5%)')
print(' 5. exit ')
print('===================')
if __name__ == '__main__':
while True:
menu()
choice = input('Your choice: ').strip()
try:
choice = int(choice)
except:
print('Invalid Choice')
continue
if choice == 1:
getflag1()
elif choice == 2:
getflag2()
elif choice == 3:
getflag3()
elif choice == 4:
getflag4()
elif choice == 5:
break
else:
print('Invalid Choice')
|
bc0c89e1f40592a0a142cd24e1dd31960f732b11 | joseph-chetta/2348_homeworks | /homework3/zylabs_10_19/main.py | 4,850 | 3.609375 | 4 | # Joseph Chetta 1640405
class ItemToPurchase:
def __init__(self, item_name='none', item_description='none', item_price=0, item_quantity=0):
self.item_name = item_name
self.item_description = item_description
self.item_price = item_price
self.item_quantity = item_quantity
def total_cost(self):
return self.item_price * self.item_quantity
def print_item_cost(self):
total = self.total_cost()
print('{} {} @ ${} = ${}'.format(self.item_name, self.item_quantity, self.item_price, total))
def print_item_description(self):
print('{}: {}'.format(self.item_name, self.item_description))
class ShoppingCart:
def __init__(self, customer_name='none', current_date="January 1, 2016"):
self.customer_name = customer_name
self.current_date = current_date
self.cart_items = []
def add_item(self, item):
self.cart_items.append(item)
def remove_item(self, item_name):
item_in_cart = False
for item in self.cart_items:
if item.item_name == item_name:
item_in_cart = True
self.cart_items.remove(item)
if not item_in_cart:
print('Item not found in cart. Nothing removed.')
def modify_item(self, item_name, quantity):
item_in_cart = False
for item in self.cart_items:
if item_name == item.item_name:
item_in_cart = True
modified_item = ItemToPurchase(item_name, item.item_description, item.item_price, quantity)
item.item_quantity = modified_item.item_quantity
if not item_in_cart:
print('Item not found in cart. Nothing modified.\n')
def get_num_items_in_cart(self):
total = 0
for item in self.cart_items:
total += item.item_quantity
return total
def get_cost_of_cart(self):
total = 0
for item in self.cart_items:
total += item.total_cost()
return total
def print_total(self):
print("{}'s Shopping Cart - {}".format(self.customer_name, self.current_date))
num_items = self.get_num_items_in_cart()
print('Number of Items: {}\n'.format(num_items))
if self.cart_items:
for item in self.cart_items:
item.print_item_cost()
print()
total = self.get_cost_of_cart()
print('Total: ${}\n'.format(total))
else:
print('SHOPPING CART IS EMPTY\n')
print('Total: $0\n')
def print_descriptions(self):
print("{}'s Shopping Cart - {}".format(self.customer_name, self.current_date))
print('\nItem Descriptions')
for item in self.cart_items:
item.print_item_description()
print()
def print_menu_options():
print('MENU')
print('a - Add item to cart')
print('r - Remove item from cart')
print('c - Change item quantity')
print("i - Output items' descriptions")
print('o - Output shopping cart')
print('q - Quit\n')
def print_menu(cart):
print_menu_options()
option = None
while option != 'q':
option = input('Choose an option:')
print()
if option == 'q':
break
elif option == 'a':
print('ADD ITEM TO CART')
item_name = input('Enter the item name:\n')
description = input('Enter the item description:\n')
price = int(input('Enter the item price:\n'))
quantity = int(input('Enter the item quantity:'))
print()
print()
item = ItemToPurchase(item_name, description, price, quantity)
cart.add_item(item)
print_menu_options()
elif option == 'r':
print('\nREMOVE ITEM FROM CART')
item_name = input("Enter name of item to remove:")
print()
cart.remove_item(item_name)
print()
print_menu_options()
elif option == 'c':
print('CHANGE ITEM QUANTITY')
item_name = input('Enter the item name:\n')
quantity = int(input('Enter the new quantity:\n'))
cart.modify_item(item_name, quantity)
print_menu_options()
elif option == 'i':
print("OUTPUT ITEMS' DESCRIPTIONS")
cart.print_descriptions()
print_menu_options()
elif option == 'o':
print('OUTPUT SHOPPING CART')
cart.print_total()
print_menu_options()
if __name__ == '__main__':
cust_name = input("Enter customer's name:\n")
date = input("Enter today's date:\n")
print()
cart = ShoppingCart(cust_name, date)
print('Customer name: {}'.format(cust_name))
print("Today's date: {}\n".format(date))
print_menu(cart)
|
f7b437badd0b99abefbab9b01333f24845c8fe2c | Celot1979/ClasesDaniel | /Solucion_5ºAsignacion.py | 6,761 | 4.03125 | 4 | #1º Ejercicio
class Alumno:
def inicializar(self,nom):
self.nombre=nom
print("Nombre: ",self.nombre)
""" Primero creo una inicializacion de el atributo con el nombre del alumno.
Como puedes ver arriba. Podríamos poner el nombre que deseemos."""
def evaluacion(self,eva):
self.nota = eva
if self.nota > 4:
print("El alumno {} ha aprobado con la nota {}".format(self.nombre,self.nota))
else:
print("El alumno {} ha suspendido".format(self.nombre))
""" En esté método doy a elegir la nota que ha sacado el alumno.
Si es mayor que 5, tendrá que salir impreso el 1º mensaje, si
no el segundo"""
persona1 = Alumno()
persona1.inicializar("Marcos")
persona1.evaluacion(3)
#Se imprime los correspondiente al método
#--------------------------------------------------------------------------------------------
#2º Ejercicio
class Persona:
def __init__(self, nombre:str, edad:str):
self.nombre=nombre
self.edad=edad
def mayor (self):
if self.edad >"18":
print("{} es mayor de edad".format(self.nombre))
else:
print("{} es menor de edad".format(self.nombre))
persona1=Persona("Juan","16")
persona2=Persona('Evaristo','20')
persona1.mayor()
persona2.mayor()
#--------------------------------------------------------------------------------------------
# 3º Ejercicio
class Triangulo:
def __init__(self, lado1,lado2,lado3):
self.a=lado1
self.b=lado2
self.c=lado3
"""En primer lugar creo un método constructor que es el primer
método que se ejecuta cuando se crea un objeto"""
def operacion(self):
if self.a != self.b:
if self.c != self.a:
print("Triangulo escaleno")
elif self.c == self.a:
print("Triangulo isosceles")
else:
print("Triangulo Equilatero")
""" En esté método simplemente utilizo los operadores de lógica para que
cuando sean llamados, realicen la operación exacta"""
primero = Triangulo(13,12,10)
primero.operacion()
#--------------------------------------------------------------------------------------------
# 4º Ejercicio
class Operaciones :
""" Tras probar diferentes posibilidades para introduccir el input,
busqué por internet, y la que me funcionó fue dando valor NONE."""
def obterner_datos(self):
self.x = input("Digito 1: ")
self.y = input("Digito 2: ")
#Luego cree un método para preguntar al usuario los digitos
def sumar(self):
print( int(self.x) + int(self.y))
def restar(self):
print( int(self.x) - int(self.y))
def multiplicar(self):
print( int(self.x) * int(self.y))
def dividir(self):
print( int(self.x) / int(self.y))
""" En el metodo de operaciones tuve algún que otro problemilla.
Te comento, en un editor no me daba problemas, pero en otros si. Encontré
que debía designar que era numero entero, introduciendo int en las impresiones"""
a = Operaciones()
a.obterner_datos()
a.sumar()
a.restar()
a.multiplicar()
a.dividir()
#--------------------------------------------------------------------------------------------
# 5º Ejercicio
class Menu:
def imprime(self):
print("añadir contacto")
print("Lista contactos")
print("buscar contacto")
print("Cerrar agenda")
class Trabajo :
def __init__(self):
self.nombre = None
self.telefono = None
self.email= None
def obtener_datos(self):
self.nombre=str(input("Introduzca su nombre completo: "))
self.telefono=str(input("Introduzca su numero de telefono: "))
self.email=str(input("Introduzca su email: "))
def guardar(self):
self.contactos= []
self.contactos.append(self.nombre)
self.contactos.append(self.telefono)
self.contactos.append(self.email)
print(self.contactos)
a=Menu()
a.imprime()
a=Trabajo()
a.obtener_datos()
a.guardar()
#--------------------------------------------------------------------------------------------
# 6º Ejercicio
""" En está parte tuve que guiarme por la solución del ejercicio. Porque al estar trabajando
la idea de hacerlo con input, no supe relazionar una clase con otra clase"""
class Banco:
# inicializamos
def __init__(self):
self.cliente1=Cliente("Ivan")
self.cliente2=Cliente("Marcos")
self.cliente3=Cliente("Juan")
# función para operar
def operacion(self):
self.cliente1.depositar(1000)
self.cliente2.depositar(300)
self.cliente3.depositar(43)
self.cliente1.extraer(400)
# función para obtener los depósitos totales
def depositos(self):
total=self.cliente1.devolver_cantidad()+self.cliente2.devolver_cantidad()+self.cliente3.devolver_cantidad()
print("El total de dinero del banco es: ",total)
self.cliente1.imprimir()
self.cliente2.imprimir()
self.cliente3.imprimir()
"""Esta parte la pude desarrollar sin mcuhas dificultad.De gecho la estaba preparando
en otra versión, pidiendo input. Pero luego no sabía enlarzarla con la clase banco"""
class Cliente:
# inicializamos
def __init__(self,nombre):
self.nombre=nombre
self.cantidad=0
# función para depositar dinero
def depositar(self,cantidad):
self.cantidad+=cantidad
# función para extraer dinero
def extraer(self,cantidad):
self.cantidad-=cantidad
# función para obtener el total de dinero
def devolver_cantidad(self):
return self.cantidad
# función para imprimir los datos del cliente
def imprimir(self):
print(self.nombre, " tiene depositada una cantidad de ",self.cantidad)
# bloque principal
banco1=Banco()
banco1.operacion()
banco1.depositos()
#--------------------------------------------------------------------------------------------
# 6º Ejercicio(mi manera)
""" Esta es la versión del ejercicio 6 que no supe relacionar ,después de probar varias
cosas con la clase banco"""
class Operacion:
def __init__(self):
self.nombre=str(input("Ingrese su nombre: :"))
self.cuenta=int(input("En la cuenta hay :"))
self.depo=int(input("Ingrese su deposito:"))
self.ext=int(input("Ingrese la cantidad que quiere extraer:"))
self.mostrar()
def mostrar(self):
print("Tu nombre:", self.nombre)
mostrar=self.cuenta+self.depo-self.ext
print("El total en la cuenta es: ",mostrar)
def devolver_cantidad(self)
return self.mostrar
class Banco:
"""docstring for Banco"""
def __init__(self):
total=self.total.devolver_cantidad +1
operacion1=Operacion()
#--------------------------------------------------------------------------------------------
|
29a7995cbcc3b97977d131d32c291444b9100aeb | andresr27/hackerrank-python | /Preparation Kit/Searching/iceCreamParlor_HashMap.py | 1,537 | 3.515625 | 4 | #!/usr/bin/python3
def build_dict_table(keys,values):
hash_map = {}
for key,value in zip(keys,values):
hash_key = key
if key in hash_map:
values = [hash_map[hash_key],value]
hash_map[hash_key] = values
else:
hash_map[hash_key] = value
return hash_map
def get_value(hash_map, key):
if key in hash_map:
values = hash_map[key]
return values
else:
return None
def whatFlavors(costs,money):
indexes = range(len(costs))
table = build_dict_table(costs,indexes)
sorted_costs = sorted(costs)
for a in costs:
b = money - a
f1 = get_value(table, a)
f2 = get_value(table, b)
if (f1 is not None) and (f2 is not None):
if f1 is not f2:
x = f1 + 1
y = f2 + 1
z = (min(x,y),) + (max(x,y),)
#print (str(z[0]+str(z[1])))
return z
elif (len(str(f1)) > 1):
x = f1[0] + 1
y = f1[1] + 1
z = (min(x,y),) + (max(x,y),)
#print (str(z[0]+str(z[1])))
return z
def main():
t = int(input())
stacks = []
for t_itr in range(t):
money = int(input())
n = int(input())
cost = list(map(int, input().rstrip().split()))
stack = whatFlavors(cost, money)
print("{} {}".format(stack[0], stack[1]))
stacks.append(stack)
return stacks
if __name__ == '__main__':
main()
|
b5bed5a8424607c118e21e0b01e5f94cbfdc442d | lovely7261/Dictionary_and_file | /file/assici.py | 110 | 3.609375 | 4 | i=0
while i <=5:
j=0
while j<=i:
print(chr(i+65),end=" ")
j=j+1
i=i+1
print() |
a9d3c1a1b1542d9ce50c8880aceba195986d2211 | simba-axin/2019ComputerGameChess | /huanying/go_train/game_go.py | 24,230 | 3.96875 | 4 | '''
A board is a NxN numpy array.
A Coordinate is a tuple index into the board.
A Move is a (Coordinate c | None).
A PlayerMove is a (Color, Move) tuple
(0, 0) is considered to be the upper left corner of the board, and (18, 0) is the lower left.
'''
from collections import namedtuple
import copy
import itertools
import numpy as np
import logging
logger = logging.getLogger("phantom_go")#调用日志
# Represent a board as a numpy array, with 0 empty, 1 is black, -1 is white.
# This means that swapping colors is as simple as multiplying array by -1
# -1 0 1 2 3 4
WHITE, EMPTY, BLACK, FILL, KO, UNKNOWN = range(-1, 5)
KO_TIMES = 0 # 打劫,可以反复提子几次。标准规则不能立刻提回来,顾默认为0
#函数链接:https://blog.csdn.net/ben1122334/article/details/102303946
#PlayerMove该函数没有什么作用
class PlayerMove(namedtuple('PlayerMove', ['color', 'move'])):
pass
# Represents "group not found" in the LibertyTracker object
MISSING_GROUP_ID = -1
#合法的移动
class IllegalMove(Exception):
#默认的函数,构造函数
def __init__(self, group=None, move=None):
self.illegal_group = group
self.last_move = move
#获得illegal_group的值
def get_illegal_group(self):
return self.illegal_group
#获得last_move的值
def get_last_move(self):
return self.last_move
# these are initialized by set_board_size
N = None
ALL_COORDS = []#同等物,一维数组,用来存储棋盘上所有的点的坐标
EMPTY_BOARD = None #设置一个nXn的空棋盘,是一个二维列表,每一行为一个n个0的列表
NEIGHBORS = {}#邻居节点,相连的点,十字形 neighbors,数组表示
DIAGONALS = {}#对角节点,斜线上的点,X字形 diagonals,数组表示
def set_board_size(n):
"""
Hopefully nobody tries to run both 9x9 and 19x19 game instances at once.
Also, never do "from go import N, W, ALL_COORDS, EMPTY_BOARD".
"""
#global的用法:https://blog.csdn.net/weixin_40894921/article/details/88528159
#定义在函数内部,将对全局变量进行修改其值
global N, ALL_COORDS, EMPTY_BOARD, NEIGHBORS, DIAGONALS
if N == n:
return #N开始时等于None
N = n
#创建一个棋盘的一维数组,(0,0)(0,1)...(0,n-1),(1,0)....(n-1,n-1)
ALL_COORDS = [(i, j) for i in range(n) for j in range(n)]
#设置一个nXn的空棋盘,是一个二维列表,每一行为一个n个0的列表
# numpy的zeros函数:https://blog.csdn.net/DocStorm/article/details/58599124
EMPTY_BOARD = np.zeros([n, n], dtype=np.int8)
#检查边界情况,改下棋点的位置情况,来判断邻接点和对角线点的位置
def check_bounds(c):
return c[0] % n == c[0] and c[1] % n == c[1]
#获得neighbors 和 diagonals的 结点位置,用一个数组表示
NEIGHBORS = {(x, y): list(filter(check_bounds, [(x+1, y), (x-1, y), (x, y+1), (x, y-1)])) for x, y in ALL_COORDS}
DIAGONALS = {(x, y): list(filter(check_bounds, [(x+1, y+1), (x+1, y-1), (x-1, y+1), (x-1, y-1)])) for x, y in ALL_COORDS}
#放置棋子,并在指定该地方的颜色,stones棋子的位置???
def place_stones(board, color, stones):
for s in stones:
board[s] = color
#发现能到达的位置
def find_reached(board, c):
#set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。数组{}表示
#c应该是一个位置信息。PS:(1,1)
color = board[c]
chain = set([c])#数组列表{}
reached = set()#数组{}
frontier = [c]#前沿
while frontier:
current = frontier.pop()
chain.add(current)#加入点C
for n in NEIGHBORS[current]:#n为该点c的邻接点
if board[n] == color and not n in chain:#如果邻接点同色并且不是c点,则扩充棋子的范围
frontier.append(n)
elif board[n] != color:#邻接点不同色或者为空,已到达的点位置数加一???
reached.add(n)#数组的方法扩展元素
return chain, reached
# 查找提子周围的点
def find_take_stones_around_points(points, color):
around_points = set()#数组{},points是点的坐标
for point in points:
for around in NEIGHBORS[point]:
around_points.add(around)
for point in points:
if around_points.__contains__(point):
#如果包含相同的点,那么就去除该点
around_points.remove(point)
#返回列表数组[{ }]
return list(around_points)
#下棋的顺序,翻转颜色进行下棋
def flip_color(color):
if color == BLACK:
return WHITE
elif color == WHITE:
return BLACK
else:
return EMPTY
#吃棋的规则
#board[n]是一种颜色,c是一个坐标,返回一个颜色
def is_koish(board, c):
'Check if c is surrounded on all sides by 1 color, and return that color'
if board[c] != EMPTY: return None
neighbors = {board[n] for n in NEIGHBORS[c]}
#数组列表,是一种颜色WHITE BLACK EMPTY,c点后面只有一种颜色,所以就可以吃棋
if len(neighbors) == 1 and not EMPTY in neighbors:
#not EMPTY in neighbors,没有空的棋盘,只有一个元素
return list(neighbors)[0]
else:
return None
#眼,如果是眼那么就返回颜色
def is_eyeish(board, c):
'Check if c is an eye, for the purpose of restricting(限制) MC rollouts.'
color = is_koish(board, c)#判断该点是不是吃棋位置,并且获得该点眼的颜色
if color is None:
return None
diagonal_faults = 0
diagonals = DIAGONALS[c]#对角线上的点,用列表表示
if len(diagonals) < 4:
diagonal_faults += 1
for d in diagonals:
if not board[d] in (color, EMPTY):
diagonal_faults += 1
if diagonal_faults > 1:
return None
else:
return color
#namedtuple函数链接:https://blog.csdn.net/ben1122334/article/details/102303946
#判断是不是一个整体,这范围内的棋子
class Group(namedtuple('Group', ['id', 'stones', 'liberties', 'color'])):
"""
stones: a set of Coordinates(坐标) belonging to this group
liberties: a set of Coordinates that are empty and adjacent(相邻) to this group.
color: color of this group
"""
def __eq__(self, other):
return self.stones == other.stones and self.liberties == other.liberties and self.color == other.color
#自由跟踪器
class LibertyTracker():
@staticmethod
def from_board(board):
board = np.copy(board) #复制棋盘并将其赋值给board
curr_group_id = 0
lib_tracker = LibertyTracker()#递归?? 对象
for color in (WHITE, BLACK):#for循环遍历元祖,第一个颜色为WHITE 第二个为BLACK
while color in board:#遍历整个棋盘
curr_group_id += 1
found_color = np.where(board == color)
# np.where 的用法https://www.cnblogs.com/massquantity/p/8908859.html
coord = found_color[0][0], found_color[1][0]
chain, reached = find_reached(board, coord)
#获得能够到达的点的坐标和不能够到达的点或者棋盘上为空的坐标,并用chain和reached保存
liberties = set(r for r in reached if board[r] == EMPTY)#数组表示{},表示棋盘上为空的点
new_group = Group(curr_group_id, chain, liberties, color)#对象
##true或者false,判断是不是一个群体(错)
lib_tracker.groups[curr_group_id] = new_group#是字典类型的变量
for s in chain:
lib_tracker.group_index[s] = curr_group_id
place_stones(board, FILL, chain)
#def place_stones(board, color, stones): for s in stones: board[s] = color
## 并将相邻的位置填充color为FILL
lib_tracker.max_group_id = curr_group_id
# 设置一个nXn的空棋盘,是一个二维列表,每一行为一个n个0的列表
# numpy的zeros函数:https://blog.csdn.net/DocStorm/article/details/58599124
liberty_counts = np.zeros([N, N], dtype=np.uint8)
for group in lib_tracker.groups.values():#遍历字典的值,是一个Group得对象实例
num_libs = len(group.liberties)#liberties 数组表示{},表示棋盘上为空的点,num_lib为点的个数
for s in group.stones:
liberty_counts[s] = num_libs
lib_tracker.liberty_cache = liberty_counts
return lib_tracker
def __init__(self, group_index=None, groups=None, liberty_cache=None, max_group_id=1):
# group_index: a NxN numpy array of group_ids. -1 means no group
# groups: a dict of group_id to groups
# liberty_cache: a NxN numpy array of liberty counts
self.group_index = group_index if group_index is not None else -np.ones([N, N], dtype=np.int16)
self.groups = groups or {}
self.liberty_cache = liberty_cache if liberty_cache is not None else np.zeros([N, N], dtype=np.uint8)
self.max_group_id = max_group_id
#返回一个LibertyTracker的对象
def __deepcopy__(self, memodict={}):
new_group_index = np.copy(self.group_index)
new_lib_cache = np.copy(self.liberty_cache)
new_groups = {
group.id: Group(group.id, set(group.stones), set(group.liberties), group.color)
for group in self.groups.values()
}
return LibertyTracker(new_group_index, new_groups, liberty_cache=new_lib_cache, max_group_id=self.max_group_id)
def add_stone(self, color, c):
## Represents "group not found" in the LibertyTracker object MISSING_GROUP_ID=-1
assert self.group_index[c] == MISSING_GROUP_ID
captured_stones = set()#捕获的棋子??
opponent_neighboring_group_ids = set()#敌对的邻居节点
friendly_neighboring_group_ids = set()#友好的邻居节点
empty_neighbors = set()#为空的邻居节点
#判断邻居节点所对应的棋子群的标号,字典类型表示群组编号和群组
for n in NEIGHBORS[c]:
neighbor_group_id = self.group_index[n]
if neighbor_group_id != MISSING_GROUP_ID:
neighbor_group = self.groups[neighbor_group_id]#是一个Group的对象
if neighbor_group.color == color:
friendly_neighboring_group_ids.add(neighbor_group_id)
else:
opponent_neighboring_group_ids.add(neighbor_group_id)
else:
empty_neighbors.add(n)
new_group = self._create_group(color, c, empty_neighbors)#其实也是一个Group的对象
for group_id in friendly_neighboring_group_ids:
new_group = self._merge_groups(group_id, new_group.id)#合并两个相同的颜色且相连的棋组群
for group_id in opponent_neighboring_group_ids:
neighbor_group = self.groups[group_id]
if len(neighbor_group.liberties) == 1:
captured = self._capture_group(group_id)#返回的是棋组里面的坐标点
captured_stones.update(captured)
#数组的更新方法,把captured放到captured_stones里面,且没有重复
else:
self._update_liberties(group_id, remove={c})
self._handle_captures(captured_stones)#更新棋群
# suicide is illegal
if len(new_group.liberties) == 0:
#该棋群没有气了,则会被提子
raise IllegalMove
return captured_stones
def _create_group(self, color, c, liberties):
self.max_group_id += 1
new_group = Group(self.max_group_id, set([c]), liberties, color)
self.groups[new_group.id] = new_group
self.group_index[c] = new_group.id
self.liberty_cache[c] = len(liberties)
return new_group
#合并两个相同的组群
def _merge_groups(self, group1_id, group2_id):
group1 = self.groups[group1_id]#Group的对象
group2 = self.groups[group2_id]#Group的对象
group1.stones.update(group2.stones)
del self.groups[group2_id]
for s in group2.stones:
self.group_index[s] = group1_id
self._update_liberties(group1_id, add=group2.liberties, remove=(group2.stones | group1.stones))
return group1
#返回死棋的位置???
def _capture_group(self, group_id):
dead_group = self.groups[group_id]#Group对象实例
del self.groups[group_id]
for s in dead_group.stones:
self.group_index[s] = MISSING_GROUP_ID
self.liberty_cache[s] = 0
return dead_group.stones
#更新棋组气的数量
def _update_liberties(self, group_id, add=None, remove=None):
group = self.groups[group_id]
if add:
group.liberties.update(add)
if remove:
group.liberties.difference_update(remove)
new_lib_count = len(group.liberties)
for s in group.stones:
self.liberty_cache[s] = new_lib_count
#更新棋组气的数量
def _handle_captures(self, captured_stones):
for s in captured_stones:
for n in NEIGHBORS[s]:
group_id = self.group_index[n]
if group_id != MISSING_GROUP_ID:
self._update_liberties(group_id, add={s})
class Position():
def __init__(self, board=None, n=0, komi=7.5, caps=(0, 0), lib_tracker=None,
ko=None,ko_times=0, recent=tuple(),
to_play=BLACK, my_color=BLACK):
'''
board: a numpy array
n: an int representing moves played so far
komi: a float, representing points given to the second player.
caps: a (int, int) tuple of captures for B, W.
lib_tracker: a LibertyTracker object
ko: a Move
recent: a tuple of PlayerMoves, such that recent[-1] is the last move.
to_play: BLACK or WHITE
'''
self.board = board if board is not None else np.copy(EMPTY_BOARD)
self.n = n # 到现在我方的行棋数
self.komi = komi # 贴目数
self.caps = caps # 存储黑棋白棋的目数的数组。0为白棋,1为黑棋
self.lib_tracker = lib_tracker or LibertyTracker.from_board(self.board)#a LibertyTracker object
self.ko = ko # 一个劫的眼位,对面的眼
self.ko_times = ko_times
self.recent = recent # 最后一次行棋
self.to_play = to_play #我方行棋颜色
self.my_color = my_color
#深拷贝,返回一个Position对象实例
def __deepcopy__(self, memodict={}):
new_board = np.copy(self.board)
new_lib_tracker = copy.deepcopy(self.lib_tracker)
return Position(new_board, self.n, self.komi, self.caps, new_lib_tracker, self.ko, self.ko_times, self.recent, self.to_play, self.my_color)
def __str__(self):
pretty_print_map = {
WHITE: 'O',
EMPTY: '.',
BLACK: 'X',
FILL: '#',
KO: '*',
}
board = np.copy(self.board)
captures = self.caps# 存储黑棋白棋的目数的数组。0为白棋,1为黑棋
if self.ko is not None:#对面的眼不为空
place_stones(board, KO, [self.ko])#在指定的位置填充颜色“KO”
raw_board_contents = []
for i in range(N):
row = []#棋盘行
for j in range(N):
appended = '<' if (self.recent and (i, j) == self.recent[-1].move) else ' '
row.append(pretty_print_map[board[i,j]] + appended)
raw_board_contents.append(''.join(row))
row_labels = ['%2d ' % i for i in range(N, 0, -1)]
annotated_board_contents = [''.join(r) for r in zip(row_labels, raw_board_contents, row_labels)]
header_footer_rows = [' ' + ' '.join('ABCDEFGHJKLMNOPQRST'[:N]) + ' ']
annotated_board = '\n'.join(itertools.chain(header_footer_rows, annotated_board_contents, header_footer_rows))
details = "\nMove: {}. Captures X: {} O: {}\n".format(self.n, *captures)
return annotated_board + details
def set_my_color(self, color):
self.my_color = color
#返回一个可以合法移动的棋群
def get_illegal_move_group(self, illegal_move):
"""
获取幻影围棋非法猜测对方落子周围的群
:param illegal_move: 猜测点最后非法位置
:return: 群
"""
n = NEIGHBORS[illegal_move][0]#用数组表示,里面是(x,y)
neighbor_group_id = self.lib_tracker.group_index[n]
if neighbor_group_id == -1:
return None
return self.lib_tracker.groups[neighbor_group_id]
#自杀式的下棋,move是一个棋盘上点的坐标
def is_move_suicidal(self, move):
potential_libs = set()#数组表示,其实是集合{}不能有重复元素
for n in NEIGHBORS[move]:
neighbor_group_id = self.lib_tracker.group_index[n]
if neighbor_group_id == MISSING_GROUP_ID:
# at least one liberty after playing here, so not a suicide
#至少有一个口气存在要不然为自杀
#MISSING_GROUP_ID=-1
return False
neighbor_group = self.lib_tracker.groups[neighbor_group_id]
#返回地neighbor_group_id个棋群,neighbor_group是Group的一个实例
if neighbor_group.color == self.to_play:
potential_libs |= neighbor_group.liberties
elif len(neighbor_group.liberties) == 1:
# would capture an opponent group if they only had one lib.
return False
# it's possible to suicide by connecting several friendly groups
# each of which had one liberty.
potential_libs -= set([move])
#潜在的气,防止自杀行为,利用集合的差集,减少重复的点
return not potential_libs
#move是一个棋盘上点的坐标
def is_move_legal(self, move, color=None):
"""Checks that a move is on an empty space, not on ko(劫眼), and not suicide"""
# logger.error("判断行棋是否合法:")
# logger.error(move)
# logger.error(color)
if move is None:
return True
if self.board[move] != EMPTY:
return False
# 我们是幻影围棋,故在此做规定:我们只对自己的棋子才进行打劫判断
if move == self.ko and color != (self.my_color*-1):
# logger.error("进入ko判断,ko_times = ")
# logger.error(self.ko_times)
if self.ko_times >= KO_TIMES:
# self.ko_times = 0
# self.ko = None
return False
else:
return True
if self.is_move_suicidal(move):
return False
return True
def pass_move(self, mutate=False):
pos = self if mutate else copy.deepcopy(self)
pos.n += 1
pos.recent += (PlayerMove(pos.to_play, None),)
pos.to_play *= -1
pos.ko = None
return pos
def flip_playerturn(self, mutate=False):
pos = self if mutate else copy.deepcopy(self)
# pos.ko = None
pos.to_play *= -1
return pos
def get_liberties(self):
return self.lib_tracker.liberty_cache
def play_move(self, c, color=None, mutate=False):
# Obeys CGOS Rules of Play. In short:
# No suicides
# Chinese/area scoring
# Positional superko (this is very crudely approximate at the moment.)
if color is None:
color = self.to_play
pos = self if mutate else copy.deepcopy(self)
if c is None:
pos = pos.pass_move(mutate=mutate)
return pos
if not self.is_move_legal(c, color):
raise IllegalMove(self.get_illegal_move_group(c), c)
place_stones(pos.board, color, [c])
captured_stones = pos.lib_tracker.add_stone(color, c)
place_stones(pos.board, EMPTY, captured_stones)
opp_color = color * -1
if c == self.ko and color == self.my_color:
self.ko_times += 1
if (len(captured_stones) == 1) and (is_koish(self.board, c) == opp_color) and (color == (-1*self.my_color)):
new_ko = list(captured_stones)[0]
else:
new_ko = self.ko
# logger.error("new_ko是:ko_times是:")
# logger.error(new_ko)
# logger.error(self.ko_times)
# logger.error("captured_stones的信息为:")
# logger.error(len(captured_stones))
# logger.error(is_koish(self.board, c))
# logger.error(color)
# logger.error(self.my_color)
if pos.to_play == BLACK:
new_caps = (pos.caps[0] + len(captured_stones), pos.caps[1])
else:
new_caps = (pos.caps[0], pos.caps[1] + len(captured_stones))
pos.n += 1
pos.caps = new_caps
pos.ko = new_ko
pos.ko_times = self.ko_times
pos.recent += (PlayerMove(color, c),)
pos.to_play *= -1
return pos
'''
对点A落下那粒子的位置进行判断
1.这个位置是否可以落子
2.当A落子后,是否能吃掉部分黑棋.让黑棋提掉.(要提掉那些子)
3.当A落子后,没有想到黑棋没有提掉,倒形成了自提.(如果自提,要提掉那些子)
判断能否做活、设置两个真眼、做活棋的方法:
对该群周围全赋值为A颜色
把该群全部赋值为B颜色
for i in group
把i点设置为空点
for j in group and i !=j
把j点设置为空点
然后对这两个点行棋
当切仅当着两个点行棋都不合法时,返回这两个点
这样这两个点设置为空,这样此处就是两个真眼活棋了
'''
def deal_illegal_move_group(self, points, last_move):
opp_color = flip_color(self.to_play)
tmp_pos = copy.deepcopy(self)
tmp_pos.board[last_move] = opp_color
for i in range(len(points)):
tmp_pos.board[points[i]] = EMPTY
for j in range(len(points)-1):
tmp_pos.board[points[j]] = EMPTY
if not tmp_pos.is_move_legal(points[i]) and not tmp_pos.is_move_legal(points[j]):
self.board[points[i]] = EMPTY
self.board[points[j]] = EMPTY
self.board[last_move] = opp_color
tmp_pos.board[points[j]] = opp_color
tmp_pos.board[points[i]] = opp_color
def score(self):
'Return score from B perspective(正数). If W is winning, score is negative(负数).'
#territory 领土,占位置的面积
working_board = np.copy(self.board)
while EMPTY in working_board:
unassigned_spaces = np.where(working_board == EMPTY)
c = unassigned_spaces[0][0], unassigned_spaces[1][0]
territory, borders = find_reached(working_board, c)
border_colors = set(working_board[b] for b in borders)
X_border = BLACK in border_colors
O_border = WHITE in border_colors
if X_border and not O_border:
territory_color = BLACK
elif O_border and not X_border:
territory_color = WHITE
else:
territory_color = UNKNOWN # dame, or seki
place_stones(working_board, territory_color, territory)
return np.count_nonzero(working_board == BLACK) - np.count_nonzero(working_board == WHITE) - self.komi
def result(self):
score = self.score()
if score > 0:
return 'B+' + '%.1f' % score
elif score < 0:
return 'W+' + '%.1f' % abs(score)
else:
return 'DRAW'
set_board_size(9)
|
2e6546b7f58a499a94403845deea3adc1da162ac | profepato/clases_estructura_2018 | /clase_230418/ejercicio_5.py | 239 | 3.875 | 4 | def ciclo(limite, mensaje):
# ciclo(3, "hola") --> hola hola hola
# ???????????
vueltas = 0
while(True):
vueltas += 1
print(mensaje)
if(limite == vueltas):
break
ciclo(12, "puntos")
|
3aa09b8f2dfdba83f3f5dd59997d65b2480acabc | ALICE5/U-PLAN | /0822/work2.py | 392 | 4.21875 | 4 | # 依次输入你的姓名、单位,分别以列表、元组、和字典的方式输出结果
# name = "闫涵"
# company = "联通系统集成"
name = input("Please input name:")
company = input("Please input company:")
# 列表
listWords = [name,company]
print(listWords)
# 元组
tupleWords = (name,company)
print(tupleWords)
# 字典
dictWords = {name:company}
print(dictWords) |
5e7b6e9233abfdbcfcaa1c167ac755ef7126125d | JoaoZati/ListaDeExerciciosPythonPro | /ExerciciosListas/Ex_16.py | 2,666 | 4.03125 | 4 | #%% 16 - Vendedores x Comissões
"""
Utilize uma lista para resolver o problema a seguir. Uma empresa paga
seus vendedores com base em comissões. O vendedor recebe $200 por semana
mais 9 por cento de suas vendas brutas daquela semana. Por exemplo, um
vendedor que teve vendas brutas de $3000 em uma semana recebe $200 mais
9 por cento de $3000, ou seja, um total de $470. Escreva um programa
(usando um array de contadores) que determine quantos vendedores
receberam salários nos seguintes intervalos de valores:
$200 - $299
$300 - $399
$400 - $499
$500 - $599
$600 - $699
$700 - $799
$800 - $899
$900 - $999
$1000 em diante
Desafio: Crie uma fórmula para chegar na posição da lista a partir do
salário, sem fazer vários ifs aninhados.
"""
def input_salario_vendedor(menssagem):
while True:
try:
num = float(input(menssagem))
if num < 200:
print('Favor inseir um numero maior igual que 200')
continue
return num
except ValueError:
print('Favor inseir um numero')
def input_numero_vendedores():
while True:
try:
num = int(input(f'Insira o numero de vendedores: '))
if num <= 0:
print('Favor inseir um numero maior que zero')
continue
return num
except ValueError:
print('Favor inseir um numero inteiro')
lista_menores = [200,
300 ,
400 ,
500 ,
600 ,
700 ,
800 ,
900 ,
1000]
vendedores = input_numero_vendedores()
salarios = []
for i in range(vendedores):
salarios.append(input_salario_vendedor(f'Insira o salário do vendedor {i+1}: R$ '))
array_contador = [0 for _ in range(len(lista_menores))]
for salario in salarios:
for j in range(len(lista_menores)):
if j == len(lista_menores) - 1:
if salario >= lista_menores[j]: array_contador[j] += 1
else:
if salario >= lista_menores[j] and salario < lista_menores[j+1]: array_contador[j] += 1
print('')
for i in range(len(lista_menores)):
if array_contador[i] == 0: continue
if array_contador[i] == 1:
if i == len(lista_menores) - 1: print(f'{array_contador[i]} vendedor ganha acima de {lista_menores[i]-1}')
else: print(f'{array_contador[i]} vendedor ganha entre {lista_menores[i]} e {lista_menores[i+1]-1}')
continue
if i == len(lista_menores) - 1: print(f'{array_contador[i]} vendedores ganham acima de {lista_menores[i]-1}')
else: print(f'{array_contador[i]} vendedores ganham entre {lista_menores[i]} e {lista_menores[i+1]-1}')
|
53d59c87ffcf8b854691e3139b77ece4ce03a7bf | M45t3rJ4ck/Py-Code | /HD - Intro/Task 4/Examples/exampleVariables.py.py | 1,491 | 4.6875 | 5 |
# This is an additional example file.
# ========= Variables ===========
# We can imagine that a variable is a place-holder which holds certain things on-demand.
# We use variables to store data in a program.
num = 2
num = 3
# We assigned the number 2 to the variable 'num'.
# Then we overwrite num with the value of 3 and 2 is automatically 'forgotten'.
# When coding in Python, you can call variables anything you want, but try using descriptive variable names.
myName = "Tom"
variableOne = "Tom"
# myName is a good variable name.
# variableOne is not a good variable name, as it doesn't give a description of what would be stored inside it.
# Thus a good variable name is one that describes the data that is stored inside it.
# Variables can store different Data Types.
numTwo = 3
nameTwo = "John"
numThree = 0.5
# The variable numTwo stores an integer value.
# The variable nameTwo stores a String value.
# The variable numThree stores a double, or real number, value.
# We can output the value of variables as follows:
print numTwo
print nameTwo
print numThree
# Run this program and take a look at the output. The three lines above generated that output.
# They printed out the VALUES of each variable.
# We can overwrite variables, as shown above with the num variable and below with the abc variable:
abc = "A"
abc = "B"
# A variable always stores the LAST value that was stored in it.
# Thus the abc variable stores the "B" value.
|
77674fe9c3cdfaf7d9d1bebb9f43c55c6b505b8e | ivadimn/py-input | /skillbox-async-chat/src/day_01/04_list_operations.py | 626 | 4.09375 | 4 | """
Пример программы для работы со списками
Данные
- есть список из 6 чисел [4, 8, 15, 16, 23, 42]
Сделать
- добавить число 108 в конец списка
- удалить число 15
- вывести длину списка
- вывести сумму всех значений
- вывести последний элемент
- вывести срез элементов с 2 по 4
"""
numbers = [4, 8, 15, 16, 23, 42]
numbers1 = [89, 90, 101, 105]
numbers.append(108)
print(sum(numbers))
print(numbers[2:4])
print(numbers + numbers1)
|
0ede3a4eb959e91db152675fa96c9c9def059b92 | wudongdong1000/Liaopractice | /practice_2.py | 219 | 3.640625 | 4 | #小明的成绩从去年的72分提升到了今年的85分,计算小明成绩提升的百分点,并用字符串格式化显示出’xx.x%'
s1 = 72
s2 = 85
r = (s2-s1)/s2*100
print('小明成绩提升了%.1f%%' % r) |
02eb9fa807541dd8e057483879381be1647184cf | Dukedog23/ia241 | /lec7.py | 256 | 3.671875 | 4 | """
lec7 while loop
"""
i = 5
while i >=0:
try:
print(1/(i-3))
except:
continue
i=i-1
#try:
# print(1/0)
#except ZeroDivisionError:
# print('zero division error')
#except:
# print('other errrors')
|
1bf0bb32dc333edf47e0c16c2283c077e4b85c93 | usyeimar/python-platzi | /funtions_probe.py | 215 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*
def Hello(name,ip):
print("Hello " + name)
print("Your ip is " + ip)
Hello("Yeimar","192.168.1.61") # Le damos los datos que la funcion va aprocesar
|
c578080dda516e3c8475048c4ad7ca8c16f65338 | assassint2017/leetcode-algorithm | /Insert Interval/Insert_Interval.py | 1,536 | 3.984375 | 4 | # 思路二的py代码
# 这样的代码,会导致列表中的对象是共享的,所以还是有一点问题的,但是懒得修改了
# Runtime: 56 ms, faster than 86.15% of Python3 online submissions for Insert Interval.
# Memory Usage: 15.8 MB, less than 100.00% of Python3 online submissions for Insert Interval.
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
res = []
insert = False
index = 0
while index != len(intervals):
if intervals[index].end < newInterval.start:
res.append(intervals[index])
elif intervals[index].start > newInterval.end:
insert = True
res.append(newInterval)
res.append(intervals[index])
break
else:
newInterval.start = min(intervals[index].start, newInterval.start)
newInterval.end = max(intervals[index].end, newInterval.end)
index += 1
if not insert:
res.append(newInterval)
else:
index += 1
while index != len(intervals):
res.append(intervals[index])
index += 1
return res |
cc280b124247a52a16e635e20f8e50038692e484 | ArvidQuarshie/Introtopython | /MultipleParameters.py | 445 | 4.09375 | 4 | #!usr/bin/pyhton
#function that takes 2 strings 1 dictionary to n arguments
#takes multiple parameters
x=raw_input("name")
y=raw_input("age")
#this is the list
z={"school":"Moringa"}
#function that takes more than three parameters
def show(x,y,z,*extra):
def double age(y):
return y*2
for key in z :
if [key]=="school"
print "Moringa School"
show("Arvid",40,Moringa,female)
|
4f1a2cbef3e2b5d3b3f6cb4978cb481722eeb8e3 | BhushanTayade88/Core-Python | /Feb/day 1/calculator.py | 399 | 3.75 | 4 | a=30
b=20
def add():
c=a+b
print(c)
def sub():
c=a-b
print(c)
def mul():
c=a*b
print(c)
def div():
c=a/b
print(c)
def expo():
c=a**2
print(c)
def mod():
c=a%b
print(c)
def floor():
c=a//b
print(c)
add()
sub()
mul()
div()
expo()
floor()
mod()
print("end of Program")
|
f2fb6cc061cca8240fc4d579a166b22d042ff077 | walkerrandolphsmith/pyscore | /test/test_map.py | 487 | 3.515625 | 4 | import unittest
from _.main import map_
class Sut(unittest.TestCase):
def setUp(self):
self.sut = map_
def test_map_from_one_domain_to_another(self):
expected = [2, 5, 8, 11]
actual = self.sut([1, 2, 3, 4], lambda e, i: e * 2 + i)
self.assertEqual(expected, actual)
def test_map_iteratee_has_one_arg(self):
expected = [2, 4, 6, 8]
actual = self.sut([1, 2, 3, 4], lambda e: e * 2)
self.assertEqual(expected, actual) |
2c9fe9727d30b444ec3c01f28289372b7abd8cf1 | rahulkmr/python3_musings | /tkinter/hello2.py | 464 | 3.640625 | 4 | #!/usr/bin/env python
from tkinter import *
class App(object):
def __init__(self, master):
frame = Frame(master, bg='white')
frame.pack()
self.button = Button(frame, text='Quit' ,command=frame.quit)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text='Hello', command=self.hi)
self.hi_there.pack(side=LEFT)
def hi(self):
print("Hi there!")
root = Tk()
app = App(root)
root.mainloop()
|
e2910809458c6aa75aab2e469bba258ab3ac4faf | Nitesh101/python_files | /regular/count_da.py | 233 | 3.78125 | 4 | def count_len(input1):
global count
count = 0
dict = {}
for i in input1:
keys = dict.keys()
if i in keys:
dict[i] +=1
count += 1
else:
dict[i] = 1
count +=1
return dict
print count_len('ggole.com')
print count
|
d91f4bee9b086a286685d2dcb2555778a7d7e506 | calangueras/Vem-ser-Tech-Lets-Code-Python-Basics | /phyton basics.py | 3,716 | 3.921875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
#!/usr/bin/env python
# coding: utf-8
# In[1]:
print("Helho, World")
#aula_02
# In[10]:
preco = 19.99
print(preco, type(preco))
#aula_03
# In[21]:
cidade = 'Uberaba'
print(cidade, type(cidade))
#aula_03
# In[23]:
disponivel = True
print(disponivel, type(disponivel))
#aula_03
# In[27]:
disponivel = False
print(disponivel)
print(disponivel, type(disponivel))
#aula_03
# In[2]:
x = 5
# In[7]:
print(x)
# In[30]:
x = 50
y = 2
print(x + y)
print(x - y)
print(x / y)
print(x * y)
#aula_04
print(type(x))
#aula_03
# In[31]:
print(x // y)
print(x % y)
print(x ** y)
#aula_04
# In[32]:
a = 2 + 3 # Soma
b = 2 - 3 # Subtração
c = 2 * 3 # Multiplicação
d = 2 / 3 # Divisão
e = 2 // 3 # Divisão inteira
f = 2 ** 3 # Potência
g = 2 % 3 # Resto de divisão
print (a, b, c, d, e, f, g)
#aula_04
# In[40]:
temCafe = True
TemPao = False
print(not temCafe) #not = conectivo nao inversao
print(temCafe or TemPao) #or = conectivo ou pelo menos 1 condição tem que ser verdadeira
print(temCafe and TemPao) # and do conectivo e as duas condições tem que ser verdadeiras
#aula_04
# In[44]:
dolar = 7.00
real = 1
print(dolar > real)
print(real < dolar)
print(real > dolar)
print(dolar < real)
print(dolar == real)
print(dolar<=real)
print(dolar>=real)
print(dolar!=real)
#aula_04
# In[48]:
idade = input("Informe sua idade: ")
print("A sua idade é: ", idade, " anos", type(idade))
#aula05
# In[49]:
idade = int(idade)
print(idade, type(idade))
#aula05
# In[52]:
salario_mensal = input("Digite seu salario mensal: ")
salario_mensal = float(salario_mensal)
gasto_mensal = input("Digite seu gasto mensal: ")
gasto_mensal = float(gasto_mensal)
salario_total = salario_mensal * 12
gasto_total = gasto_mensal * 12
montante_economizado = salario_total - gasto_total
print("O valor do seu salario anual é: ", salario_total, "E o seu gasto anual é de: ", gasto_total, "E o valor total economizado é :", montante_economizado)
#aula05
valor_passagem = 5.40
valor_corrida = input("Qual o valor da corrida: ")
if float(valor_corrida) <= valor_passagem * 5:
print("Pague a corrida")
if float(valor_corrida) >= valor_passagem * 5:
print("Pegue o ônibus")
valor_passagem = 5.40
valor_corrida = input("Qual o valor da corrida: ")
if float(valor_corrida) <= valor_passagem * 5:
print("Pague a corrida")
else:
print("Pegue o ônibus")
#aula06
# In[18]:
valor_passagem = 5.40
valor_corrida = input("Qual o valor da corrida: ")
if float(valor_corrida) <= valor_passagem * 5:
print("Pague a corrida")
else:
if float(valor_corrida) <= valor_passagem * 6:
print("Aguarde um instante, o valor pode abaixar")
else:
print('Pegue o ônibus')
#aula06
# In[25]:
valor_passagem = 5.40
valor_corrida = input("Qual o valor da corrida: ")
if float(valor_corrida) <= valor_passagem * 5:
print("Pague a corrida")
elif float(valor_corrida) <= valor_passagem * 6:
print("Aguarde um instante, o valor pode abaixar")
else:
print('Pegue o ônibus')
#aula06
# In[3]:
contador = 0
while contador < 10:
contador = contador + 1
if contador == 1:
print(contador, "item limpo")
else:
print(contador, "itens limpos")
print("Todas as louças limpas")
#aula7
# In[8]:
contador = 0
while contador < 10:
contador = contador + 1
if contador == 1:
continue
print(contador, "itens limpos")
print("Todas as louças limpas")
#aula7
# In[7]:
texto = input("Digite uma senha")
while texto != 'abc':
texto = input("Senha invalida. Tente novamente")
print("Acesso permitido")
#aula7
|
0f0ef9c4bf031d50f6117359e665499f427ddccf | ashco/leetcode | /2020-10/16-meeting-rooms-2.py | 704 | 3.53125 | 4 | # Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
import heapq
def minMeetingRooms(intervals):
if not intervals: return 0
intervals.sort(key = lambda x: x[0])
end_times = []
heapq.heappush(end_times, intervals[0][1])
for start, end in intervals[1:]:
if end_times[0] <= start:
heapq.heappop(end_times)
heapq.heappush(end_times, end)
return len(end_times)
print(minMeetingRooms([[0, 30],[5, 10],[15, 20]])) # 2
print(minMeetingRooms([[7, 10],[2, 4]])) # 1
# --------------------------
# [ ] [ ]
# [ ]
# [ ] |
2c46dd4d48506b136b366504bec0545200248349 | ArhamChouradiya/Python-Course | /20decorator.py | 428 | 3.984375 | 4 | """ONE WAY TO DECORATE FUNCTION
def decor(fun):
def inner():
result=fun()
return result*2
return inner
def num():
return 5
resultfun=decor(num)
print(resultfun())
"""
def decor(fun):
def inner():
result=fun()
return result*2
return inner
@decor #ANOTHER WAY IS TO THROUGH @ decor function name above the function you want to decorate
def num():
return 5
print(num()) |
ec6826fb79f9353d1d150462aa197ae3a6b9961d | 00214/Actividad-09 | /particulas.py | 783 | 3.59375 | 4 | from particula import Particula
# Administrador de Particulas
class Particulas:
def __init__(self):
self.__parti = [] # Lista
def agregar_inicio(self, particula:Particula):
self.__parti.insert(0, particula)
def agregar_final(self, particula:Particula):
self.__parti.append(particula)
def mostrar(self):
for particula in self.__parti:
print(particula)
p01 = Particula(id="14", origen_x="2", origen_y="2", destino_x="4", destino_y="4", velocidad="100", red="12", green="54", blue="15", distancia="")
p02 = Particula("13", "2", "2", "4", "4", "101", "15", "16", "17", "")
particulas = Particulas()
particulas.agregar_inicio(p01)
particulas.agregar_final(p02)
particulas.agregar_inicio(p01)
particulas.mostrar()
|
761949ff44b6edcf4878ce40ec2d7c1f7ec5efa1 | LittleSquirrel00/118-classic-Questions-of-LeetCode | /7.堆/215_findKthLargest.py | 1,494 | 3.6875 | 4 | """数组中的第K个最大元素
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
说明:
你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
"""
# 堆
class Solution:
"""
方法一:堆
思路是创建一个大顶堆,将所有数组中的元素加入堆中,并保持堆的大小小于等于 k。这样,堆中就保留了前 k 个最大的元素。这样,堆顶的元素就是正确答案。
像大小为 k 的堆中添加元素的时间复杂度为 {O}(\log k)O(logk),我们将重复该操作 N 次,故总时间复杂度为 {O}(N \log k)O(Nlogk)。
在 Python 的 heapq 库中有一个 nlargest 方法,具有同样的时间复杂度,能将代码简化到只有一行。
本方法优化了时间复杂度,但需要 {O}(k)O(k) 的空间复杂度。
"""
def findKthLargest(self, nums, k):
import heapq
return heapq.nlargest(k, nums)[-1]
# 排序
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
sort_nums = sorted(nums, reverse=True)
idx = 0
for i in sort_nums:
idx += 1
if idx == k:
return i
|
1c4352a78d50b14356b14116aa8cc9b620cddc7d | revathigit98/revathi | /hellopy/23jan.py | 473 | 4 | 4 | # x=[1,2,3,4,5]
# y=[1,2,3]
# z=[j*i for i in y for j in x]
# print(z)
# z=[lambda a:a**2,x]
# print(list(z))
#reverse a string without using a slicing
#using join
# str = 'helloworld'
# reversed=''.join(reversed(str))
# print(reversed)
# with using join
# str='Helloworld'
# rev=[]
# index=len(str)
# while index >0:
# rev+=str[index-1]
# index=index-1
# print(rev)
# #print commmon element in list
# x=[1,2,3,4,5,6]
# y=[1,2,3,4,8,9]
# print(set(x)&set(y))
|
73993d4b04e321d1b83398128780bae161f5c326 | zarbiaa/Mastering-Python-for-Finance-source-codes | /B03898_03_codes/newton.py | 887 | 3.609375 | 4 | """"
README
======
This file contains Python codes.
======
"""
""" The Newton-Raphson method """
def newton(f, df, x, tol=0.001, maxiter=100):
"""
:param f: The function to solve
:param df: The derivative function of f
:param x: Initial guess value of x
:param tol: The precision of the solution
:param maxiter: Maximum number of iterations
:return: The x-axis value of the root,
number of iterations used
"""
n = 1
while n <= maxiter:
x1 = x - f(x)/df(x)
if abs(x1 - x) < tol: # Root is very close
return x1, n
else:
x = x1
n += 1
return None, n
if __name__ == "__main__":
y = lambda x: x**3 + 2*x**2 - 5
dy = lambda x: 3*x**2 + 4*x
root, iterations = newton(y, dy, 5.0, 0.00001, 100)
print "Root is:", root
print "Iterations:", iterations
|
98523b06807c7d1a4bbd48199033a3db0bb1102b | shj594/CS1001-Asgn7 | /main.py | 2,695 | 3.75 | 4 | import random
EXIT = "q"
ROCK = "rock"
PAPER = "paper"
SCISSORS = "scissors"
LIZARD = "lizard"
SPOCK = "spock"
# must return True if the first throw wins or tie; False otherwise
def compare(first_throw, second_throw):
# TODO: implement; use get_message to determine the rules
return True
def get_message(winning_throw, losing_throw):
if winning_throw == losing_throw:
return "It's a tie!"
if winning_throw == SCISSORS and losing_throw == PAPER:
return SCISSORS + " cuts " + PAPER
if winning_throw == PAPER and losing_throw == ROCK:
return PAPER + " covers " + ROCK
if winning_throw == ROCK and losing_throw == SCISSORS:
return ROCK + " crushes " + SCISSORS
if winning_throw == SCISSORS and losing_throw == LIZARD:
return SCISSORS + " decapitates " + LIZARD
if winning_throw == LIZARD and losing_throw == SPOCK:
return LIZARD + " poisons " + SPOCK
if winning_throw == SPOCK and losing_throw == SCISSORS:
return SPOCK + " smashes " + SCISSORS
if winning_throw == SPOCK and losing_throw == ROCK:
return SPOCK + " vaporizes " + ROCK
if winning_throw == ROCK and losing_throw == LIZARD:
return ROCK + " crushes " + LIZARD
if winning_throw == LIZARD and losing_throw == PAPER:
return LIZARD + " eats " + PAPER
if winning_throw == PAPER and losing_throw == SPOCK:
return PAPER + " disproves " + SPOCK
return "N/A"
def main():
# prompt with exit instructions
print("\nYou can enter q at any time to exit!\n")
while True:
# prompt for first throw; retrieve user input
first_throw = input("Type rock, paper, scissors, lizard, or spock: ")
first_throw = first_throw.strip().lower()
# check for exit
if first_throw == EXIT:
break
# prompt for second throw; retrieve user input
second_throw = input("Type rock, paper, scissors, lizard, spock or hit ENTER: ")
second_throw = second_throw.strip().lower()
# check for exit
if second_throw == EXIT:
break
# check for random throw; randomly generate throw if needed
if second_throw == "":
possible = [ ROCK, PAPER, SCISSORS, LIZARD, SPOCK ]
second_throw = possible[int(len(possible)*random.random())]
# compare the two throws
first_throw_wins = compare(first_throw, second_throw)
# print result
if first_throw_wins:
print(get_message(first_throw, second_throw))
else:
print(get_message(second_throw, first_throw))
return
if __name__ == "__main__":
main() |
af1a1c65a4e036d0daae865763fd9531a26967e4 | Aasthaengg/IBMdataset | /Python_codes/p02910/s979330972.py | 256 | 3.796875 | 4 | s = list(input())
odd = ['R', 'U', 'D']
even = ['L', 'U', 'D']
ret = 'Yes'
for i, j in enumerate(s):
if (i+1)%2 == 1 and j not in odd:
ret = 'No'
break
elif (i+1)%2 == 0 and j not in even:
ret = 'No'
break
print(ret) |
f5c7baaebe3c10e5d2edde804d8d25e3207f6e4b | Andrea-Wu/brains | /Ass2/neuron.py | 761 | 3.71875 | 4 | class neuron:
"""
needs:
array of forward connected neuron objects (synapse)
separate array of backward connected neurons
-corresponding connection values for each connected neuron
a "stabilizer?" that keeps the neuron's spike active for a while (because they're not all going to spike at exactly the same time)
-or rather, each neuron keeps an internal clock. We can hack it so that it seems like the computations are acting in parallel, but they're actually not.
threshold for spike
spike must propagate forward to connected neurons
every time a neuron fires, it's backwards neurons are checked to see if they fire too
"""
def __init__(self):
|
f1b02096d8c57d33ff420253cdd73ebece049338 | 18242360613/leetcode | /leetcode/77_Combinations.py | 440 | 3.65625 | 4 | class Solution:
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
if k==0:return [[]]
if k==n:return [[i for i in range(1,n+1)]]
ans1 = self.combine(n-1,k)
ans2 = self.combine(n-1,k-1)
for a in ans2:
a.append(n)
ans1.append(a)
return ans1
s = Solution()
ans = s.combine(3,2)
print(ans) |
56800cc40b95b26f1d2feafb861985dd7f465615 | Max23Esau/python_basico | /bucles/eliminar_vocales.py | 245 | 3.75 | 4 | def disemvowel():
string = input('Escribe la frase que tu quieras:\n')
for i in "aeiouAEIOU":
# print(i)
string = string.replace(i,'')
# print(string)
print(string)
if __name__ == "__main__":
disemvowel() |
2433b4535738969910b450ab30e01297be63c280 | ryanchang1005/ALG | /tree/LeetCode 339 Nested List Weight Sum.py | 607 | 3.890625 | 4 | """
加總權重
1.
[[1,1],2,[1,1]]
4個1在第2層 4 x 2 = 8
1個2在第1層 2 x 1 = 2
結果 = 10
2.
[1,[4,[6]]]
1 x 1 = 1
4 x 2 = 8
6 x 3 = 18
結果 = 27
思路
回圈
ret += 如是list則遞迴
ret += 如是int則回傳該值
ret
"""
def solve(data):
return dfs(data, 0)
def dfs(data, level):
if isinstance(data, int):
return data * level
if isinstance(data, list):
ret = 0
for val in data:
ret += dfs(val, level + 1)
return ret
if __name__ == "__main__":
print(solve([[1, 1], 2, [1, 1]]))
print(solve([1, [4, [6]]]))
|
bb6c2d58386efee13f009053fd07a4fc6331ff49 | gabrielruiz21/codeCademyProject | /Restaurant.py | 4,468 | 4 | 4 | #This program could be implemented on a travel agency. This whole program will recommend user attractions to visit according to the place they want to go and their interests.
#destinations and test traveler are just for testing purposes. In the future i would like to gather this information from an API or the user's profile.
#this list contains some famous destinations
destination = ['Paris, France','Shanghai, China', 'Los Angeles, USA','Sao Paulo, Brazil','Cairo, Egypt']
#this list will be populated with the recommended attractios the user should visit according to his interest and his destination.
attractions_with_interest = []
#I will be using this list to recommend the user attractions accroding to his interests.
attractions = [[], [], [], [], []]
#the objective of this class is to make the proccess of adding destinations and attraction to the attraction list.
def add_attraction(destination, attraction):
try:
destination_index = get_destination_index(destination)
attractions_for_destination = attractions [destination_index]
attractions_for_destination.append(attraction)
except ValueError:
return 0
#this function will just gather the destination index which will be use to find the attractions on it.
def get_destination_index(name):
destination_index = destination.index(name)
return destination_index
#this will gather the users's destination to visit and associate with our destination list
def get_traveler_location(traveler):
traveler_destination = traveler[1]
traveler_destination_index = get_destination_index(traveler_destination)
return traveler_destination_index
#this function is in charge of looping throught the attractions list and compare where the attractions in the user's destination match his interests.
def find_attractions(destination,interests):
destination_index = get_destination_index(destination)
attractions_in_city = attractions[destination_index]
possible_attraction = ""
attraction_tags = ""
for items in attractions_in_city:
possible_attraction = items
attraction_tags = items[1]
for tags in attraction_tags:
if tags in interests:
attractions_with_interest.append(possible_attraction[0])
return attractions_with_interest
#This function is the main. This will use the previous functions, collect the data and present it to the user in a friendly way.
def get_attractions_for_traveler(traveler):
traveler_destination = traveler[1]
traveler_interests = traveler[2]
traveler_attractions = find_attractions(traveler_destination,traveler_interests)
interests_string = "Good choice " + traveler[0] + ", we think you'll like these places around " + traveler_destination + ": "
for item in traveler_attractions:
interests_string += item + ", "
return interests_string
#This lines are just so i can populate the attractions list with real data.
add_attraction("Los Angeles, USA",['Venice Beach', ['beach']])
add_attraction("Paris, France", ["the Louvre", ["art", "museum"]])
add_attraction("Paris, France", ["Arc de Triomphe", ["historical site", "monument"]])
add_attraction("Shanghai, China", ["Yu Garden", ["garden", "historcical site"]])
add_attraction("Shanghai, China", ["Yuz Museum", ["art", "museum"]])
add_attraction("Shanghai, China", ["Oriental Pearl Tower", ["skyscraper", "viewing deck"]])
add_attraction("Los Angeles, USA", ["LACMA", ["art", "museum"]])
add_attraction("Sao Paulo, Brazil", ["Sao Paulo Zoo", ["zoo"]])
add_attraction("Sao Paulo, Brazil", ["Patio do Colegio", ["historical site"]])
add_attraction("Cairo, Egypt", ["Pyramids of Giza", ["monument", "historical site"]])
add_attraction("Cairo, Egypt", ["Egyptian Museum", ["museum"]])
#here i am using a user data so i can test the program. You will fin the user's name, folow by the place he wants to go and his interests.
user_name = input("Hello there, thanks for chosing us for your next adventure. Let's know each other firt. What is your name: ")
print(f'It is nice to meet you {user_name}, Here is a list of attractions you might be interested on {destination}')
user_destination = input("Which one you fancy the most ? ")
user_interests = input("Lasly, what are your interests? \n beach,art,museum,historical site,monument,garden,skyscraper,viewing deck \n")
user_interests = user_interests.split(',')
# print(user_interests)
smills_france = get_attractions_for_traveler([user_name, user_destination, user_interests])
print(smills_france) |
415c6668d4fc614bbc917791db0ce6d1bdb17dea | justinglobal/codeguild | /4-guess.py | 1,279 | 4.1875 | 4 | #
# import random
#
# answer = random.randint(1, 2)
#
# print('This is a guessing game')
# print('Guess a number:')
#
# guess = int(input())
#
# while guess != answer:
# if guess > answer:
# print('Too high, dude.')
# elif guess < answer:
# print('Too low, yo.')
# print('Guess again:')
# guess = int(input())
# if guess == answer:
# print('Correct! You are a winner!')
########
import random
def generate_answer():
"""Generate random number within specified range."""
return random.randint(1,2)#this is set to a small set of integers for testing
def input_guess():
"""Prompts user to input text as their guess for the answer."""
print('Guess a number:')
return int(input())
def compute_response(guess, answer):
"""Computes response for incorrect guess."""
if guess > answer:
print('Too high, duuude.')
elif guess < answer:
print('Too low, yo.')
def correct_answer(guess, answer):
"""Computes response for correct answer."""
if guess == answer:
print('Correct! You are a winner!')
#return guess == answer
answer = generate_answer()
guess = input_guess()
while guess != answer:
compute_response(guess, answer)
guess = input_guess()
correct_answer(guess, answer)
|
68f4d1ca78ebe400bf4d454a3b93beba8a3e1236 | octavio-navarro/ObjectOrientedThinking | /CodeSamples/PythonCode/01. helloName.py | 302 | 3.8125 | 4 | import math
# Comentarios
def hello(nombre):
print("Hello", nombre)
def main():
print("Hola Python!")
nombre = input("Dame tu nombre: ")
edad = int(input("Dame tu edad: "))
print(f"Hola {nombre}! En 20 años tendras {edad+20}")
main()
# none, int, float, string, boolean |
83f3e5700009bf7df8addeb5988fa2173152e94c | GustavoGajdeczka/DAD | /exemplo_objeto.py | 1,844 | 3.875 | 4 | import datetime
class Pessoa:
def __init__(self, nome, nascimento, cpf):
self.__nome = nome
self.__nascimento = datetime.datetime.strptime(nascimento, '%d/%m/%Y')
self.__cpf = cpf
def def_nome(self, nome):
self.__nome = nome
def set_nascimento(self, nascimento):
self.__nascimento = nascimento
def set_cpf(self, cpf):
self.__cpf = cpf
def get_nome(self):
return self.__nome
def get_nascimento(self):
return self.__nascimento
def get_cpf(self):
return self.__cpf
def main():
operacao = 0
lista = []
while True:
operacao = int(input("== Options \n= 1 - Insert \n= 2 - Print\n= 3 - Sort\n= 4 - Exit\n= "))
if operacao == 1:
nome = input("Informe o nome da pessoa: ")
nascimento = input("Informe o nascimento da pessoa: ")
cpf = input("Informe o CPF: ")
lista.append(Pessoa(nome, nascimento, cpf))
elif operacao == 2:
for pessoa in lista:
pessoa_nascimento = '{}/{}/{}'.format(pessoa.get_nascimento().day, pessoa.get_nascimento().month, pessoa.get_nascimento().year)
print(pessoa.get_nome() + " - " + pessoa_nascimento + " - " + str(pessoa.get_cpf()))
elif operacao == 3:
n = len(lista) - 1
for index in range(n):
for aux in range(n):
if lista[aux].get_nascimento() > lista[aux + 1].get_nascimento():
auxiliar = lista[aux]
lista[aux] = lista[aux + 1]
lista[aux + 1] = auxiliar
n -= 1
elif operacao == 4:
break
else:
print("=== Operação Invalida ===")
if __name__ == '__main__':
main() |
399e0931e0e0fc7104796c160474cbe5308bddec | Iris0609/Leetcode | /Linkedlist/86_Partition_List.py | 1,026 | 3.578125 | 4 | #medium
#40ms, 71.45%
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
if not head:
return
dummyhead=ListNode(x-1)
pre=dummyhead
pre.next=head
flag=head
while flag:
if flag.val <x:
pre=flag
flag=flag.next
else:
break
pre2=flag
if flag and flag.next:
cur=flag.next
else:
return dummyhead.next
while cur:
if cur.val>=x:
pre2=cur
cur=cur.next
else:
pre.next=cur
pre2.next=cur.next
cur.next=flag
pre=cur
cur=pre2.next
return dummyhead.next
|
a522d91d9a5266c171cb93297b8a53ee1fb776c8 | answerrrrrrrrr/leetcode | /22*.Medium.GenerateParentheses_default-argument_generator.py | 1,593 | 3.515625 | 4 | class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
# https://leetcode.com/discuss/43122/4-7-lines-python
# about the default argument
# https://leetcode.com/discuss/43122/4-7-lines-python?show=56258#c56258
# DFS rcs
# default arg: list
# 48ms
def gp(p, left, right, res=[]):
if left:
gp(p+'(', left-1, right)
if right > left:
gp(p+')', left, right-1)
if not right:
res += p, # res.append(p)
return res
return gp('', n, n)
# res = []
# def gp(p, left, right, res):
# if left:
# gp(p+'(', left-1, right, res)
# if right > left:
# gp(p+')', left, right-1, res)
# if not right:
# res += p, # res.append(p)
# gp('', n, n, res)
# return res
# generator
def generate(p, left, right):
if right >= left >= 0:
if not right:
yield p
for q in generate(p + '(', left-1, right): yield q
for q in generate(p + ')', left, right-1): yield q
return list(generate('', n, n))
# amended func
# default arg: int
def generateParenthesis(self, n, open=0):
if n > 0 <= open:
return ['(' + p for p in self.generateParenthesis(n-1, open+1)] + \
[')' + p for p in self.generateParenthesis(n, open-1)]
return [')' * open] * (not n)
|
b7075e89e513254d9cd85eddb9023b1285c6ffd6 | bobcaoge/my-code | /python/leetcode/125_Valid_Palindrome.py | 1,584 | 3.84375 | 4 | # /usr/bin/python3.6
# -*- coding:utf-8 -*-
import re
class Solution(object):
pattern = re.compile(r"([a-zA-Z\d])")
def manage(self, s):
"""
:type s: str
:param s:
:return:
"""
if 'a' <= s <= 'z':
return s
elif 'A' <= s <= 'Z':
return s.lower()
elif '0' <= s <= '9':
return s
else:
return ""
def isPalindrome1(self, s):
"""
:type s: str
:rtype: bool
"""
start = 0
end = len(s) - 1
while start < end:
s_start = self.manage(s[start])
s_end = self.manage(s[end])
if s_end and s_start:
if s_end == s_start:
start += 1
end -= 1
else:
return False
elif s_start:
end -= 1
elif s_end:
start += 1
else:
start += 1
end -= 1
return True
def isPalindrome(self, s):
result = "".join(self.pattern.findall(s)).lower()
print(result)
start = 0
end = len(result) - 1
while start < end:
if result[start] != result[end]:
return False
start += 1
end -= 1
return True
def main():
s = Solution()
print(s.isPalindrome("A man, a plan, a canal: Panama"))
print(s.isPalindrome("race a car"))
print(s.isPalindrome("0P"))
if __name__ == "__main__":
main()
|
4311af316df47c3ee4d4d99b65030362178b7158 | chenchiyuan/zoneke | /recommendation/similarily.py | 1,630 | 3.65625 | 4 | # -*- coding: utf-8 -*-
__author__ = 'chenchiyuan'
from math import sqrt, pow
def euclid(item_a, item_b):
'''
simple complete euclid distance
'''
item_a_likes, item_b_likes = __get_same(item_a, item_b)
sum_pow = 0
for i in len(item_a_likes):
sum_pow += pow(item_a_likes[i].score - item_b_likes[i].score)
return 1/ 1 + sqrt(sum_pow)
def pearson(item_a, item_b):
'''
pearson algorithm of distance
list_a is User A likes tags
list_b is User B likes tags
only calculate the same one
the more ,see algorithm,
http://baike.baidu.com/albums/779030/779030/0/0.html#0$d0526df02bf26bbca50f5220
'''
item_a_likes, item_b_likes = __get_same(item_a, item_b)
num = len(item_a_likes)
if num == 0:
return 1
sum1 = sum([item_a_likes[i].socre for i in range(num)])
sum2 = sum([item_b_likes[i].socre for i in range(num)])
sum1_sq = sum([pow(item_a_likes[i].score, 2) for i in range(num)])
sum2_sq = sum([pow(item_b_likes[i].score, 2) for i in range(num)])
p_sum = sum([(item_a_likes[i].score*item_b_likes[i].score) for i in range(num)])
mol = p_sum - sum1*sum2/num
den = sqrt(sum1_sq - pow(sum1, 2)/num)*(sum2_sq - pow(sum2, 2)/num)
if den == 0:
return 0
return mol/den
def __get_same(item_a, item_b):
item_a_likes = []
item_b_likes = []
tmp = [b.item_id for b in item_b.likes]
for like in item_a.likes:
if like.item_id in tmp:
item_a_likes.append(like)
item_b_likes.append(like)
return item_a_likes, item_b_likes
|
ad7cab95e6d87d22041887fd1ed3f7e22f665de8 | Shimul-ostfold/Learn-python-the-hard-way | /ex13.py | 349 | 3.828125 | 4 | # Parameters, Unpacking, variable
from sys import argv
script, first, second, third = argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
food = input("Which food you like most?",)
print(f"My favorit food is {food}.")
|
4554d4360cb250e93d0e47f65285889cf51e399a | herry28/spiders | /testcase/Commonlib/readcsv.py | 231 | 3.515625 | 4 | import csv
class readcsv():
def read_csv(self):
mylist=[]
con=csv.reader(open('../DataXml/data.csv','r'))
for cons in con:
mylist.append(cons)
print(mylist)
return mylist
|
69f0dd49c87cecd71aed87a8adc5aa648c08d46c | felipesch92/PythonExercicios | /ex029.py | 417 | 3.8125 | 4 | #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.
v = int(input('Informe a velocidade do carro: '))
if v > 80:
m = (v - 80) * 7
print('Você foi multado em R$ {:.2f} reais.'.format(m))
else:
print('Parabéns você está andando no limite da velocidade permitida')
|
e1baea651392b13d38563bcf70f1dab2ae704ecd | shaabyn/Exo-TSRS13 | /Ex01.py | 593 | 3.875 | 4 | #!/usr/bin/python3
'''
#text = "Je dois faire des sauvegardes régulières de mes fichiers."
#print (text*500)
'''
'''
pair =[]
for a in range (0,1000, 2):
pair.append(a)
print(pair)
impair = [n + 1 for n in pair ]
print (impair)
'''
'''
def table(nb, max=10):
1 * nb
i = 0
while i < max:
print(i + 1, "*", nb, "=", (i + 1) * nb)
i += 1
if __name__ == "__main__":
table(13)
'''
'''
name = input('Entrez un mot: ')
a = 0
b = 0
while a < len(name):
if name[a] == 'e':
b = b + 1
a = a + 1
print(a)
''' |
4dfdb0321f2d156544fbe79dd07d53e1bd247aa0 | adityakoushik11/XCDIFY | /PYTHON/programs/Class.py | 137 | 3.625 | 4 | class Person:
def __init__(self,name):
self.name=name
def display(self):
print("HELLO " +self.name)
p1=Person("LION")
p1.display()
|
0b8fba1fe994e4bbfb9b725ed746fed505849b13 | asad632/Python | /map_function.py | 327 | 3.734375 | 4 | # map is iteretor
# numbers = [1,2,3,4]
# def sqr(l):
# return l**3
# sqre= list(map(sqr, numbers))
# print(sqre)
#
# def inde(g):
# return g%2==0
# num = [1,3,4,5,6]
#
# ind = list(map(inde, num))
# print(ind)
# name = ['asad', 'asada', 'abcd']
# def nam(l):
# return len(l)
# sd = list(map(nam, name))
# print(sd) |
3e35cff56199b7360006eab955b0a37934db0fe3 | dvelasquev/ST0245-008 | /Taller6Ordenacion/Punto7.py | 423 | 3.6875 | 4 | import time
def lista_negativa(lista):
listan = []
for i in range (0,len(lista)):
if lista[i] < 0:
listan.append(lista[i])
return listan
n = [-1,-4,-33,-5,-4,-5,-7,-8,-9,8,5,6,5,4,8,9,5,4,5,-5,-4,-4,-4,-14,-656565,-4,-8,8,5,7,5,7,6,5,4,5,4,9]
print (lista_negativa(n))
start_time = time.time()
lista_negativa(n)
print("Tiempo --- %s seconds ---" % (time.time() - start_time)) |
6b110a27fa30970dbda1e7cc18b29dd1dad1b2ea | sanaltsk/my_python | /HackerRank/HelpSnippets/permuation.py | 290 | 3.6875 | 4 | __author__ = 'san'
__hacker_rank = 'https://www.hackerrank.com/sanaltsk'
def permute(s,i):
if i==len(s)-1:
print s
else:
for j in range(i,len(s)):
s[i],s[j]=s[j],s[i]
permute(s,i+1)
s[i],s[j] = s[j],s[i]
permute(list('abc'),0) |
bdeaac4fbbb37640926d6265713843da9fb87405 | bickerton/python-challenge | /pybank/pybankmain.py | 2,043 | 3.59375 | 4 | import csv
import os
file_to_load = os.path.join("pybank", "Resources", "budget_data.csv")
# Set Variables
total_months = 0
month_of_change = []
net_change_list = []
greatest_increase = ["", 0]
greatest_decrease = ["", 0]
total_net = 0
prev_net = 0
# Open CSV
with open(file_to_load) as financial_data:
reader = csv.reader(financial_data)
# Iterate over headers
header = next(reader)
# Track total months
for row in reader:
total_months = total_months + 1
total_net = total_net + float(row[1])
if total_months > 1:
# Track the net change
net_change = float(row[1]) - prev_net
net_change_list = net_change_list + [net_change]
month_of_change = month_of_change + [row[0]]
# Calculate the greatest increase
if net_change > greatest_increase[1]:
greatest_increase[0] = row[0]
greatest_increase[1] = net_change
# Calculate the greatest decrease
if net_change < greatest_decrease[1]:
greatest_decrease[0] = row[0]
greatest_decrease[1] = net_change
prev_net = float(row[1])
# Track net monthly averages
net_monthly_avg = sum(net_change_list)/(len(net_change_list))
#Output a summary of the analysis:
print()
print(f'Financial Analysis')
print(f'__________________')
print(f'Total Months: {total_months}')
print(f'Total:{total_net}')
print(f'Average Change: ${(round(net_monthly_avg, 2))}')
print(f'Greatest Increase in Profits: {greatest_increase[0:]}')
print(f'Greatest Decrease in Profits: {greatest_decrease[0:]}')
import sys
sys.stdout = open('PyBank_Output.txt', 'w')
print(f'Financial Analysis')
print(f'__________________')
print(f'Total Months:{total_months}')
print(f'Total:{total_net}')
print(f'Average Change: ${(round(net_monthly_avg, 2))}')
print(f'Greatest Increase in Profits: {greatest_increase[0:]}')
print(f'Greatest Decrease in Profits: {greatest_decrease[0:]}')
|
9fa19a091e8526d9401178256a2ebd6b4fdb1318 | andhy-gif/diya_challenge1 | /mencarisuku.py | 115 | 3.8125 | 4 | suku =int(input('masukkan suku yang anda ingin cari:'))
hasil = 0
for i in range(suku):
hasil += i
print(hasil)
|
b5e30f6bd380e968c3c42c7062088a4d5f90d98c | elchananvol/IntrotoCS | /ex7/ex7.py | 2,495 | 3.6875 | 4 | def print_to_n(n):
if n < 1:
return
print_to_n(n-1)
print(n)
def digit_sum(n):
num_string= str(n)
if len(num_string)== 0:
return 0
return int(num_string[-1]) + int(digit_sum(num_string[:-1]))
def is_prime(n):
if n <= 1:
return False
if is_prime_helper(n, (int(n**0.5))):
return True
return False
def is_prime_helper(n, g):
if g == 1:
return True
if n < 2 or n % g == 0:
return False
return is_prime_helper(n, g - 1)
def play_hanoi(hanoi,n,src,dest,temp):
if n==1:
hanoi.move(src,dest)
else:
play_hanoi(hanoi, n-1, src, temp, dest)
play_hanoi(hanoi, 1, src, dest,temp)
play_hanoi(hanoi, n-1, temp, dest, src)
def print_sequences(char_lst,n):
print_sequences_helper(char_lst, "", n)
def print_sequences_helper(char_lst, option, n):
if n==0:
print(option)
return
for letter in range(len(char_lst)):
a = str(char_lst[letter])
option = option + a
print_sequences_helper(char_lst, option, n - 1)
option = option[:-1]
def print_no_repetition_sequences(char_lst,n):
print_no_repetition_sequences_helper(char_lst,"", n)
def print_no_repetition_sequences_helper(char_lst, option, n):
if n==0:
print(option)
return
for index in range(len(char_lst)):
the_letter = char_lst[index]
a = str(the_letter)
option = option + a
char_lst.remove(the_letter)
print_no_repetition_sequences_helper(char_lst, option, n-1)
char_lst.insert(index,the_letter)
option = option[:-1]
lst_to_print = []
def parentheses(n):
parentheses_helper(["(", ")"], 0, n)
return lst_to_print
def parentheses_helper(base_stone, indicator, n):
x1,x2= "(",")"
if len(base_stone) == n*2:
list_to_str = "".join(i for i in base_stone)
lst_to_print.append(list_to_str)
return
for i in range(indicator, len(base_stone)):
base_stone.insert(i + 1, x2)
base_stone.insert(i + 1, x1)
parentheses_helper(base_stone, i + 1, n)
base_stone.pop(i + 1)
base_stone.pop(i + 1)
def flood_fill(image,start):
if image[start[0]][start[1]]== "*":
return
image[start[0]][start[1]] = "*"
flood_fill(image, (start[0],start[1]-1))
flood_fill(image, (start[0], start[1] +1))
flood_fill(image, (start[0]-1, start[1]))
flood_fill(image, (start[0]+1, start[1])) |
505e1ed5e6876d9a3f9f4027a0e820d65a48e89f | davidlpotter59/la | /typecasting.py | 604 | 4.03125 | 4 | name = input("Enter your name: ").title()
color = input("What is your favorite color? ").title()
age = int(input("What is your age? "))
nameSplit = name.split()
print(nameSplit)
outStr = f'Hello, my name is {name}.', f'I go by {nameSplit[1]}.', f'My favorite color is {color}.', f'I am {age} years old.'
print(f'{outStr}', end="\t")
print(f'Hello, my name is {name}.', f'I go by {nameSplit[1]}.', f'My favorite color is {color}.', f'I am {age} years old.', sep="\t")
outStr = f'Hello, my name is {name}. I go by {nameSplit[0]}. My favorite color is {color}. I am {age} years old.'
print(outStr) |
d7d6b08c60c8eda0f1bd58912b8767eb6ee57b7c | owsorber/MIT_6.00.2x_Coursework | /Final Project/PerformancePlotting.py | 1,158 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
def getPerformanceData(fname):
training_lengths = []
accuracies = []
times = []
num_trials = []
file = open(fname, "r")
for line in file.read().splitlines()[1:]:
tl, acc, time, trials = line.split(", ")
training_lengths.append(float(tl))
accuracies.append(float(acc))
times.append(float(time))
num_trials.append(float(trials))
return training_lengths, accuracies, times, num_trials
training_lengths, accuracies, times, num_trials = getPerformanceData("PerformanceData.txt")
def plotAccuracy():
plt.figure("Accuracy")
plt.plot(training_lengths, accuracies, "b")
plt.title("Prediction Accuracy vs. Size of Training Data")
plt.xlabel("# of Digits Trained On")
plt.ylabel("Percent Correct")
plt.show()
def plotTimes():
plt.figure("Time")
plt.plot(training_lengths, times, "r")
plt.title("Prediction Time vs. Size of Training Data")
plt.xlabel("# of Digits Trained On")
plt.ylabel("Time per Prediction")
plt.show()
plotAccuracy()
plotTimes()
|
c1328ecb4133c4701cb7de27e4019e0e49c7752f | Tanmay12123/-100-day-code-challange | /challange_5/main.py | 1,962 | 3.84375 | 4 | from turtle import Turtle, Screen
import random
tamy = Turtle()
tamy.shape("turtle")
# colours = ["sandybrown", "green", "yellow",
# "black", "orange", "purple", "blue", "red"]
# def five_ten():
# for t in range(3):
# random.choice(colours)
# tamy.forward(100)
# tamy.right(120)
# random.choice(colours)
# for s in range(4):
# random.choice(colours)
# tamy.forward(100)
# tamy.right(90)
# random.choice(colours)
# for p in range(5):
# random.choice(colours)
# tamy.forward(100)
# tamy.right(72)
# for h in range(6):
# random.choice(colours)
# tamy.forward(100)
# tamy.right(60)
# for f in range(7):
# random.choice(colours)
# tamy.forward(100)
# tamy.right(51.42)
# for o in range(8):
# random.choice(colours)
# tamy.forward(100)
# tamy.right(45)
# for n in range(9):
# random.choice(colours)
# tamy.forward(100)
# tamy.right(40)
# for h in range(10):
# random.choice(colours)
# tamy.forward(100)
# tamy.right(36)
# five_ten()
# num = [0,1]
colours = ["CornflowerBlue", "DarkOrchid", "IndianRed", "DeepSkyBlue", "LightSeaGreen", "wheat", "SlateGray", "SeaGreen"]
# def returner():
# if random.choice(num) == 0:
# return tamy.right(90)
# else:
# return tamy.left(90)
# def draw_shape():
# for _ in range(100):
# tamy.color(random.choice(colours))
# tamy.pensize(10)
# tamy.forward(30)
# returner()
# tamy.speed("fastest")
# def size(size):
# tamy.pensize(3)
# for l in range(int(360/size)):
# tamy.color(random.choice(colours))
# tamy.circle(100)
# current = tamy.heading()
# tamy.setheading(current+10)
# tamy.circle(100)
# size(2)
screen = Screen()
screen.exitonclick()
|
97f969890f8861ce8bf26511388de0053bffe5f5 | ummmh/price_comparer | /04_find recommendations.py | 839 | 3.734375 | 4 | """Component 4 of Price Comparer
Compare each item - find cheapest, most expensive and recommendation
Created by Janna Lei Eugenio
9/08/2021
"""
# List from sample data
product_list = [['Sea Salt Crackers', (185.0, 'g'), 2.0],
['Griffin Snax', (250.0, 'g'), 2.5],
['Pizza Shapes', (190.0, 'g'), 3.3],
['Arnotts Cheds', (250.0, 'g'), 3.99],
['Rosemary Wheat', (170.0, 'g'), 2.0],
['Original Rice Crackers', (100.0, 'g'), 1.65]]
# Component 4 - compare each product
product_list.sort(key=lambda row: row[2]) # sorts the list by price
cheapest = product_list[0] # cheapest is at start of list
expensive = product_list[-1] # most expensive is last
# print for testing
print("Cheapest: {}\nMost Expensive: {}".format(cheapest, expensive))
|
c40dec8a0154dc341a1677ed3d3636988e253e04 | arifkhan1990/Competitive-Programming | /Data Structure/Linked list/Singly Linked List/implementation/singly_linked_list.py | 3,967 | 3.8125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return f"Node({self.data})"
class SinglyLinkedList:
def __init__(self):
self.head = None
def __iter__(self):
node = self.head
while node:
yield node.data
node = node.next
def __len__(self) -> int:
return len(tuple(iter(self)))
def __repr__(self):
return "->".join([str(item) for item in self])
def __getitem__(self, idx):
# Indexing Support. Used to get a node at particular position
if not 0 <= idx < len(self):
raise ValueError("list index out of range.")
for i, node in enumerate(self):
if i == idx:
return node
def __setitem__(self, idx, data):
# Used to change the data of a particular node
if not 0 <= idx < len(self):
raise ValueError("list index out of range.")
current = self.head
for _ in range(idx):
current = current.next
current.data = data
def insert_head(self, data) -> None:
self.insert_nth(0, data)
def insert_tail(self, data) -> None:
self.insert_nth(len(self), data)
def insert_nth(self, idx: int, data) -> None:
if not 0 <= idx <= len(self):
raise ValueError("List index out of range.")
new_node = Node(data)
if self.head is None:
self.head = new_node
elif idx == 0:
new_node.next = self.head
self.head = new_node
else:
temp = self.head
for _ in range(idx - 1):
temp = temp.next
new_node.next = temp.next
temp.next = new_node
def print_list(self) -> None:
print(self)
def delete_head(self):
return print(self.delete_nth(0))
def delete_tail(self):
return print(self.delete_nth(len(self) - 1))
def delete_nth(self, idx: int = 0):
if not 0 <= idx <= len(self) - 1:
raise IndexError("list index out of range.")
delete_node = self.head
if idx == 0:
self.head = self.head.next
else:
temp = self.head
for _ in range(idx - 1):
temp = temp.next
delete_node = temp.next
temp.next = temp.next.next
return delete_node.data
def is_empty(self) -> bool:
return self.head is None
def reverse(self):
prev = None
current = self.head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
self.head = prev
if __name__ == "__main__":
linked_list = SinglyLinkedList()
linked_list.insert_head(input("Inserting 1st at head ").split())
linked_list.insert_head(input("Inserting 2nd at head ").split())
print("\nPrint list: ")
linked_list.print_list()
linked_list.insert_tail(input("Inserting 1st tail ").strip())
linked_list.insert_tail(input("Inserting 2nd at tail ").strip())
print("\nPrint list: ")
linked_list.print_list()
linked_list.insert_nth(3, input("Inserting nth at position ").split())
print("\nPrint list: ")
linked_list.print_list()
print("\nDelete head ")
linked_list.delete_head()
print('\nDelete tail ')
linked_list.delete_tail()
print('\nPrint linked list ')
linked_list.print_list()
print('\nReverse linked list ')
linked_list.reverse()
linked_list.print_list()
print('\nString representation of linked list: ')
print(linked_list)
print('\nReading /changing Node data using indexing: ')
print(f"Element at Position 1: {linked_list[1]}")
linked_list[1] = input("Enter New Value: ").strip()
print("New List: ")
print(linked_list)
print(f"Length of linked list is: {len(linked_list)}")
|
9670c493a71009f4a58885c64c64946c82320f26 | majestic905/algorithms-methods | /23_gcd.py | 135 | 3.5 | 4 | a, b = map(int, input().split())
while b:
a, b = b, a % b
print(a)
# from math import gcd
# print(gcd(*map(int, input().split()))) |
4538d01c2068081eeafb612f3c6dec5b527af5bf | sjayster/Leetcode | /230-kth-smallest-element-in-a-bst.py | 1,672 | 3.6875 | 4 | """
Solutions: Inorder traversal will get the elements in increasing order. The kth element can be found from the list.
Recursion:
1. Helper function that populates the list from the tree using in order traversal.
2. Once the list is populated and the control returns to the main function,
return result[k-1]
Iterative:
1. Use the inorder traversal iterative method.
2. When current node is None and we pop the element from the stack, check to see if k-1 == 0, if so that is our kth smallest element
else, decrement k by 1 and set current to current.right
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
if not root:
return
stacks = []
current = root
while current or stacks:
if current:
stacks.append(current)
current = current.left
else:
current = stacks.pop()
if k - 1 == 0:
return current.val
k -= 1
current = current.right
"""
def inorder(self, root, stacks):
if not root:
return
self.inorder(root.left, stacks)
stacks.append(root.val)
self.inorder(root.right, stacks)
return stacks
def kthSmallest(self, root, k):
stacks = []
stacks = self.inorder(root, stacks=[])
return stacks[k-1]
"""
|
f57e1066790801c6e74a10cd128424cbf9716be1 | tb1over/datastruct_and_algorithms | /graph/Dijkstr.py | 1,682 | 3.609375 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# 计算最短路径(类似于Prim算法),图最好用邻接矩阵表示
INF = 65535
class Graph(object):
def __init__(self, vsize):
self.vsize = vsize
self.matrix = [[0 for _ in range(self.vsize)] for x in range(self.vsize)]
def find_min_dist(self, distance, visit):
u = -1
mindist = INF
for v in range(self.vsize):
if distance[v] < mindist and not visit[v]:
mindist = distance[v]
u = v
return u
def echo(self, distance):
print("Vertex tDistance from Source")
for u in range(self.vsize):
print(u, "t", distance[u])
def dijkstra(self, src):
distance = [INF]*self.vsize
distance[src] = 0
visit = [False]*self.vsize
for _ in range(self.vsize):
u = self.find_min_dist(distance, visit)
visit[u] = True
for v in range(self.vsize):
if self.matrix[u][v] > 0 and distance[v] > (distance[u] + self.matrix[u][v]) and not visit[v]:
distance[v] = distance[u] + self.matrix[u][v]
self.echo(distance)
if __name__ == '__main__':
g = Graph(9)
g.matrix = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
];
g.dijkstra(0)
|
64b38467625efcc6ad8a31e67b93434ae30ddb94 | Aasthaengg/IBMdataset | /Python_codes/p02865/s350324085.py | 66 | 3.546875 | 4 | n=int(input())
cnt=0
if n %2==0:
print(n//2 -1)
else:print(n//2) |
f020d6aba3a73696a286ad3b6b937e1276dd1ad6 | alexanu/sitc_to_oenace_mapper | /src/utils.py | 1,413 | 3.6875 | 4 | import csv
from typing import Dict, List
def sort_by_similarity(matching_list: List[dict], descending: bool = True) -> List[dict]:
return sorted(matching_list, key=lambda x: x['similarity'], reverse=descending)
def load_csv(path_to_file: str) -> Dict:
with open(path_to_file, 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
rows = {row['ID']: row['Title'] for row in csv_reader}
return rows
def load_correspondence_tables(path_to_file: str, system: str) -> Dict:
system = system.upper()
with open(path_to_file, 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
rows = {row['SITC2']: row[system] for row in csv_reader}
return rows
def load_enriched_sitc_codes(path_to_file: str) -> Dict:
with open(path_to_file, 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
rows = {row['ID']: row["Mapping"].split('~') for row in csv_reader}
return rows
def find_matching_intersections(oeance_candidates: Dict) -> List:
"""
Returns a list of intersection from oenace_candidates of different approaches (currently using text_similarities
and inverted_index)
"""
all_matchings = []
for method, matchings in oeance_candidates.items():
all_matchings.append([(item['oenace_code'], item['oenace_title']) for item in matchings])
return list(set.intersection(*map(set, all_matchings)))
|
3bdbf0a3a1c0655afcd3513792a21cb1add71b5a | beckz87/learn_programming | /youtube-gravitar_pythonuebungen/3-Reiskörner-Schachbrett-zählung_dar-grafisch.py | 1,010 | 3.75 | 4 | import matplotlib.pyplot as plt # matplotlib.pyplot geladen und als "plt" aufrufbar
summe = 0
feldListe = []
for feld in range(64):
reiskorn = 2**feld # Aus doppelt * wird hoch
feldListe.append(reiskorn)
summe += reiskorn # Durch "+=" werden der bestehenden Summme weitere Körner hinzugefügt
print(f"Feld {feld+1}. = {reiskorn:>30,} Reiskörner und damit insgesamt"
f"{summe:>30,} Reiskörner")
gewicht = summe * 0.02 / 1000 / 1000
print()
print("Wenn ein Reiskorn 0,02 Gramm wiegt, wiegen die gesamten"
f" Reiskörner {gewicht:,.0f} Tonnen")
plt.title("Anzahl von Reiskörner auf jeweiligen Feldern")
plt.xlabel("Anzahl der Schachfelder")
plt.ylabel("Anzahl der Reiskörner [in Trillionen]")
plt.grid(True) # Hilfgitter ein-/ausblenden
plt.yscale('log') # Achsenausrichtung an X oder Y logharithmisch ausrichten
# Syntax: plt.axis([xmin, xmax, ymin, ymax]) - eigene Skalierung festlegen
#plt.axis([0, 63, 0, 10**18])
plt.plot(feldListe, color="#1abc9c")
plt.show()
|
cc0ef130ead0b9557e2d9c03ec25a31d0fba24e1 | MatthewRueben/multiple-explorers | /classes/geography.py | 3,081 | 3.59375 | 4 | #!/usr/bin/env python
import random
class Bounds2D():
def __init__(self, (x_lower, x_upper), (y_lower, y_upper)):
self.x_lower = x_lower
self.x_upper = x_upper
self.y_lower = y_lower
self.y_upper = y_upper
def random_within_bounds(self):
x_choice = random.uniform(self.x_lower, self.x_upper)
y_choice = random.uniform(self.y_lower, self.y_upper)
# total hack below for testing purposes, puts them all in a corner
# choice = random.random()
# if choice < .25:
# # top middle
# x_choice = 50.
# y_choice = 100.
# elif choice < .5:
# # bottom middle
# x_choice = 50.
# y_choice = 0.0
# elif choice < .75:
# # left middle
# x_choice = 0.0
# y_choice = 60.0
# else:
# # right middle
# x_choice = 100
# y_choice = 60
# x_choice = 0.0 #self.x_lower
# y_choice = 60.0 #self.y_upper - self.y_lower
return (x_choice, y_choice)
def get_center(self):
x_center = (self.x_lower + self.x_upper) / 2
y_center = (self.y_lower + self.y_upper) / 2
return (x_center, y_center)
def __str__(self):
return str(((self.x_lower, self.x_upper),
(self.y_lower, self.y_upper)))
import random
class POI():
def __init__(self, V, d_min):
self.V = V # POI value
self.d_min = d_min
def place_randomly(self, bounds):
x, y = bounds.random_within_bounds()
# print 'POI location, ', x, y
self.location = Location(x, y)
def place_location(self, location):
self.location = location
def __str__(self):
return 'POI: Value: ' + str(self.V) + ', ' + str(self.location)
def __sub__(self, subtrahend):
""" Subtraction for POIs = Euclidean distance between the POI and the subtrahend.
Only works if the subtrahend class has attribute "location" of class "Location". """
return self.location - other_poi.location
import math
class Location:
""" A point in 2D Euclidean space. """
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'Location: (' + str(self.x) + ',' + str(self.y) + ')'
def __eq__(self, other):
if isinstance(other, Location):
if self.x == other.x and self.y == other.y:
return True
return False
def __sub__(self, subtrahend):
""" Subtraction for Locations = Euclidean distance between the Location and the subtrahend.
Only works if the subtrahend class is "Location". """
if isinstance(subtrahend, Location):
dx = subtrahend.x
dy = subtrahend.y
else: # assume the other class has an attribute "location" of class "Location"
dx = subtrahend.location.x
dy = subtrahend.location.y
return math.sqrt((self.x - dx) ** 2 + (self.y - dy) ** 2)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.