blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1c99e8c0b0d564bc126c4250cde363fcd5230c82 | sharkseba/taller-progra | /Ejercicios Control Flujo-condicionales/ejercicio23-parte1.py | 4,881 | 3.6875 | 4 | # Salida --> El equipo que pasa a la siguiente ronda e indicar motivo,
# 1) paso por mayor puntaje
# 2) paso por mayor cantidad de goles realizados
# 3) pasó por mayor cantidad de goles de visita
# 4) pasó por sorteo
# Grupo AAA
# Equipo A
# Equipo B
# Equipo C
# Partido 1: Equipo A vs Equipo B
# goles_a_local y goles_b_vista
# quien gano, quien perdio, si hubo empate
# puntuacion_equipo_a = 3 si ganó, 0 si perdió y 1 si empato
# goles > goles_otro : 3 , 0, 1
# Partido 2: Equipo B vs Equipo C
# goles_b_lcoal y goles_equipo_v
# Partido 3: Equipo C vd Equipo A
print('Ingrese los resultados del partido 1: Equipo A vs Equipo B')
goles_equipo_a_local = int(input('Ingrese los goles del equipo A: '))
goles_equipo_b_visita = int(input('Ingrese los goles del equipo B: '))
puntos_equipo_a = 0
puntos_equipo_b = 0
puntos_equipo_c = 0
goles_equipo_a = 0
goles_equipo_b = 0
goles_equipo_c = 0
if goles_equipo_a_local > goles_equipo_b_visita:
puntos_equipo_a = 3
elif goles_equipo_a_local < goles_equipo_b_visita:
puntos_equipo_b = 3
else:
puntos_equipo_a = 1
puntos_equipo_b = 1
# Partido 2: Equipo B vs Equipo C
print('Ingrese los resultados del partido 2: Equipo B vs Equipo C')
goles_equipo_b_local = int(input('Ingrese los goles del equipo B: '))
goles_equipo_c_visita = int(input('Ingrese los goles del equipo C: '))
if goles_equipo_b_local > goles_equipo_c_visita:
puntos_equipo_b += 3
elif goles_equipo_b_local < goles_equipo_c_visita:
puntos_equipo_c = 3
else:
puntos_equipo_b += 1
puntos_equipo_c += 1
# Partido 3: Equipo C vs Equipo A
print('Ingrese los resultados del partido 3: Equipo C vs Equipo A')
goles_equipo_c_local = int(input('Ingrese los goles del equipo C: '))
goles_equipo_a_visita = int(input('Ingrese los goles del equipo A: '))
if goles_equipo_c_local > goles_equipo_a_visita:
puntos_equipo_c += 3
elif goles_equipo_c_local < goles_equipo_a_visita:
puntos_equipo_a += 3
else:
puntos_equipo_c += 1
puntos_equipo_a += 1
print('Tabla de puntuación fecha 2')
print('Equipo A ',puntos_equipo_a,'puntos')
print('Equipo B ',puntos_equipo_b,'puntos')
print('Equipo C ',puntos_equipo_c,'puntos')
# Según la FIFA, pasa a la siguiente ronda el equipo con mayor cantidad de puntaje
cantidad_equipos_mayorp = 0
mayor_puntaje = puntos_equipo_a
# Calcular el mayor puntaje
if puntos_equipo_b > mayor_puntaje:
if puntos_equipo_b > puntos_equipo_c:
mayor_puntaje = puntos_equipo_b
else:
mayor_puntaje = puntos_equipo_c
else:
if puntos_equipo_c > puntos_equipo_a:
mayor_puntaje = puntos_equipo_c
# Calcular la cantidad de equipos que logran el mayor puntaje
if mayor_puntaje == puntos_equipo_a:
cantidad_equipos_mayorp += 1
if mayor_puntaje == puntos_equipo_b:
cantidad_equipos_mayorp += 1
if mayor_puntaje == puntos_equipo_c:
cantidad_equipos_mayorp += 1
print('Cantidad de equipos que alcanzaron la puntuación',mayor_puntaje,'son: ',cantidad_equipos_mayorp)
if cantidad_equipos_mayorp == 1:
# Aplicar FIFA 1
if mayor_puntaje == puntos_equipo_a:
print('El equipo A pasó a la siguiente ronda por mayoría de puntos')
elif mayor_puntaje == puntos_equipo_b:
print('El equipo B pasó a la siguiente ronda por mayoría de puntos')
else:
print('El equipo C pasó a la siguiente ronda por mayoría de puntos')
elif cantidad_equipos_mayorp == 2:
# ¿Qué se hace si hay 2 equipos con el mayor puntaje?
# No sabemos cuales son los equipos que alcanzaron el mayor puntaje
# Buscar estos equipos
equipo_mayor1 = ''
equipo_mayor2 = ''
goles_equipo_mayor1 = 0
goles_equipo_mayor2 = 0
goles_visita_equipo_mayor1 = 0
goles_visita_equipo_mayor2 = 0
# Buscar los equipos
if mayor_puntaje == puntos_equipo_a:
equipo_mayor1 = 'Equipo A'
goles_equipo_mayor1 = goles_equipo_a_local + goles_equipo_a_visita
goles_visita_equipo_mayor1 = goles_equipo_a_visita
if mayor_puntaje == puntos_equipo_b:
if equipo_mayor1 == '':
equipo_mayor1 = 'Equipo B'
goles_equipo_mayor1 = goles_equipo_b_local + goles_equipo_b_visita
goles_visita_equipo_mayor1 = goles_equipo_b_visita
else:
equipo_mayor2 = 'Equipo B'
goles_equipo_mayor2 = goles_equipo_b_local + goles_equipo_b_visita
goles_visita_equipo_mayor = goles_equipo_b_visita
if mayor_puntaje == puntos_equipo_c:
equipo_mayor2 = 'Equipo C'
goles_equipo_mayor2 = goles_equipo_c_local + goles_equipo_c_visita
goles_visita_equipo_mayor = goles_equipo_c_visita
print('Equipo mayor 1', equipo_mayor1, 'goles equipo mayor 1', goles_equipo_mayor1)
print('Equipo mayor 2', equipo_mayor2, 'goles equipo mayor 2', goles_equipo_mayor2)
# Aplicar FIFA 2 |
55dc16350267b7fe1302d6cdb24eb433e53ec882 | MH10000/Python_Labs | /python_fundamentals-master/13_modules-and-automation/13_04_get_outta_here.py | 566 | 4.21875 | 4 | # Use the built-in `sys` module to explicitly quit your script.
# Include this functionality into a loop where you're asking the user
# for input in an infinite `while` loop.
# If the user enters the word "quit", you can exit the program
# using a functionality provided by this module.
import sys
password = "greentree"
pword = None
while pword != password:
pword = input("enter the password or type 'quit' to exit: ")
if pword == password:
print("Correct, you may enter")
break
else:
if pword == "quit":
quit()
|
ecdc61c4c3445422937412512d5131346eb8b198 | FlareJia/-Python | /c2.py | 1,525 | 3.859375 | 4 | #-*- coding: utf-8 -*-
#迭代
#dic也可迭代
d={'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
#因为dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样。
#默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.values(),如果要同时迭代key和value,可以用for k, v in d.items()。
#那么,如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:
from collections import Iterable
print(isinstance('abc',Iterable))
print(isinstance([1,2,3],Iterable))
print(isinstance(123,Iterable))
#如果要对list实现类似Java那样的下标循环怎么办?Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:
for i,value in enumerate(['A','B','C']):
print(i,value)
#for中有两个变量,很常见
for x, y in [(1, 1), (2, 4), (3, 9)]:
print(x, y)
#练习
def findMinAndMax(L):
if len(L)==0:
return (None,None)
else:
min=L[0]
max=L[0]
for x in L:
if x<min:
min=x
elif x>max:
max=x
return (min,max)
# 测试
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!') |
d2885acc07206c9dd96f729e9c9a94ff8e45683e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2954/60623/308445.py | 137 | 3.65625 | 4 | a=int(input())
l=[]
for i in range(a):
tL=input()
l.append(tL)
if l==['abcdec', 'cdefead']:
print('noway')
else:
print(l) |
20413e2cbaa1a56efce550f9b5f479300e037e28 | stungkit/Leetcode-Data-Structures-Algorithms | /05 Tree/104. Maximum Depth of Binary Tree.py | 2,253 | 4.0625 | 4 | # Given a binary tree, find its maximum depth.
# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
# Note: A leaf is a node with no children.
# Example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its depth = 3.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Method 1: recursively
class Solution:
def maxDepth(self, root: TreeNode) -> int:
# (0) edge case
if not root:
return 0
# (1) get depth of root.left and root.right
dl = self.maxDepth(root.left)
dr = self.maxDepth(root.right)
# (2) return the final result
return 1 + max(dl, dr)
# Time: O(N)
# Space: O(logN)
# Method 2: iteratively DFS
class Solution:
def maxDepth(self, root):
# (0) edge case
if not root:
return 0
# (1) initialize
depth = 1
stack = [(1, root)]
# (2) update depth
while stack:
curr_depth, root = stack.pop()
depth = max(depth, curr_depth)
if root.left:
stack.append((curr_depth + 1, root.left))
if root.right:
stack.append((curr_depth + 1, root.right))
# (3) return result
return depth
# Time: O(N)
# Space: O(logN)
# Method 2: iteratively BFS
class Solution:
def maxDepth(self, root):
# (0) edge case
if not root:
return 0
# (1) initialize
depth = 0
queue = [root]
# (2) update depth
while queue:
depth += 1
for _ in range(len(queue)):
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# (3) return result
return depth
# Time: O(N)
# Space: O(logN) |
fc500a19b989c27a8ae01515f9eadc11fda60054 | Pierina0410/t10_palacios.salazar | /palacios/app1.py | 576 | 4 | 4 | import libreria
def agregar_nota():
input("Agregar nota1: ")
print("Se ingreso nota2")
def agregar_nota2():
input("Agregar nota2: ")
print("Se ingreso nota2")
opc=0
max=3
while(opc!=max):
print("######### MENU ##########")
print("# 1. agregar nota #")
print("# 2. nota2 #")
print("# 3. salir #")
print("#########################")
opc=libreria.pedir_numero("ingrese opcion:",1,3)
if(opc==1):
agregar_nota()
if(opc==2):
agregar_nota2()
print("Programa finalizado")
# fin_menu
|
b1462c479b92001206d9fe1d51473ab3e2cd5117 | lsteiner9/python-chapters-7-to-9 | /chapter8/windchill.py | 1,006 | 3.78125 | 4 | # windchill.py
def chill(temp, speed):
return 35.74 + (0.6215 * temp) - (35.75 * (speed ** 0.16)) + (
0.4275 * temp * (speed ** 0.16))
def main():
print("This program prints out a table of windchill values from 0-50 mph "
"and -20 to +60 degrees Fahrenheit.\n")
print(" % 3.2f % 3.2f % 3.2f % 3.2f % 3.2f % 3.2f % 3.2f "
"% 3.2f % 3.2f deg. F\n"
% (-20, -10, 0, 10, 20, 30, 40, 50, 60)) # temp labels
print("%2d % 3.2f % 3.2f % 3.2f % 3.2f % 3.2f % 3.2f % 3.2f "
"% 3.2f % 3.2f" %
(0, -20, -10, 0, 10, 20, 30, 40, 50, 60)) # zero wind
for i in range(5, 51, 5):
print("%2d % -3.2f % -3.2f % -3.2f % -3.2f % -3.2f % -3.2f "
"% -3.2f % -3.2f % -3.2f" %
(i, chill(-20, i), chill(-10, i), chill(0, i), chill(10, i),
chill(20, i), chill(30, i), chill(40, i), chill(50, i),
chill(60, i)))
if __name__ == '__main__':
main()
|
33e0b8a739c1fd0990c560477584d41cabd56591 | Sranciato/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 270 | 3.75 | 4 | #!/usr/bin/python3
"""Returns true if obj is an instance of a class"""
def inherits_from(obj, a_class):
"""Returns true if obj is an instance of a class"""
if isinstance(obj, a_class) is True and type(obj) is not a_class:
return True
return False
|
8822e3fe49324c787d950c3a4c4cb9d3c1e99063 | ikim1991/machine-learning-models | /Python/Linear Regression/univariate.py | 1,096 | 4.25 | 4 | # Simple Linear Regression Model
# Import Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Import Dataset
data = pd.read_csv('Salary_Data.csv')
X = data.iloc[:,:-1].values
y = data.iloc[:,-1].values
# Train/Test set split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
# Training the Simple Linear Regression Model
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predict using Test Set
y_pred = regressor.predict(X_test)
# Visualize the Training Set
plt.scatter(X_train, y_train, color='r')
plt.plot(X_train, regressor.predict(X_train), color='b')
plt.xlabel('Years Experience')
plt.ylabel('Salary')
plt.title('Salary vs. Experience (Train set)')
plt.show()
# Visualize the Test Set
plt.scatter(X_test, y_test, color='r')
plt.plot(X_train, regressor.predict(X_train), color='b')
plt.xlabel('Years Experience')
plt.ylabel('Salary')
plt.title('Salary vs. Experience (Test set)')
plt.show() |
2aa50f8d6a0844f68919cf18862c34a45390be28 | lxiaokai/team-learning-python | /取个队名真难-C/day04/logic.py | 815 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
if、while逻辑判断的用法
author: gxcuizy
date: 2018-10-18
"""
# 程序主入口
if __name__ == '__main__':
# 简单if
name = 'big_brother'
if name == 'da_biao_guo':
print('Please take me fly!')
# if……else 的用法
if name == 'da_biao_guo':
print('Please take me fly!')
else:
print('Please take us fly!')
# if……elif……else 的用法
if name == 'da_biao_guo':
print('Please take me fly!')
elif name == 'xiao_biao_mei':
print('Please take us fly!')
else:
print('Please take you fly!')
# while的用法-计算100以内所有偶数的和
sum = 0
n = 0
while n <= 100:
if n % 2 == 0:
sum += n
n += 1
print(sum)
|
66ec7e79c6c6bfc5b684644636aec263d6f11271 | gjersing/interactiveSortVisualizer | /mergeSort.py | 2,439 | 4.125 | 4 | #merge sort implementation for interactiveSorting
import time
def start_mergeSort(data, drawData, speed, size):
merge_sort(data, 0, len(data)-1, drawData, speed, size)
def merge_sort(data, left, right, drawData, speed, size):
if left < right: #Stops when the left index meets the right index (only 1 item left)
#find mid value
mid = (left+right)//2 #Using // returns an integer
#call merge_sort to cut each half into half recursively
merge_sort(data, left, mid, drawData, speed, size)
merge_sort(data, mid+1, right, drawData, speed, size)
#Merge the left and right side of the array together
merge(data, left, mid, right, drawData, speed, size)
def merge(data, left, mid, right, drawData, speed, size):
drawData(data, size, getColorArray(len(data), left, mid, right))
time.sleep(speed)
#Grabs the two halves
leftPart = data[left : mid+1]
rightPart = data[mid+1 : right+1]
leftIndex = rightIndex = 0
#dataIndex points to main array
for dataIndex in range(left, right+1): #For data range
if leftIndex < len(leftPart) and rightIndex < len(rightPart): #if left or right parts out of range
if leftPart[leftIndex] <= rightPart[rightIndex]: #Left < Right then data = left
data[dataIndex] = leftPart[leftIndex]
leftIndex += 1
else: #Right < Left then data = right
data[dataIndex] = rightPart[rightIndex]
rightIndex += 1
elif leftIndex < len(leftPart): #After one of the pointers is OOB finish the non-OOB side
data[dataIndex] = leftPart[leftIndex]
leftIndex += 1
else: #^^ but if right side is non-OOB
data[dataIndex] = rightPart[rightIndex]
rightIndex += 1
drawData(data, size, ["navy" if x >= left and x <= right else "gray65" for x in range(len(data))])
time.sleep(speed)
def getColorArray(length, left, mid, right):
colorArray = []
for i in range(length):
if i>=left and i <=right:
if i >= left and i <= mid:
colorArray.append("red")
else:
colorArray.append("blue")
else:
colorArray.append("gray65")
return colorArray |
0099056db862c0f341bb1097fa5a0dd38c59d740 | Mookiefer/Calculator | /functions.py | 5,082 | 3.5625 | 4 | from decimal import Decimal, getcontext
numbers = {
"-ZERO-": "0", "0": "0",
"-ONE-": "1", "1": "1",
"-TWO-": "2", "2": "2",
"-THREE-": "3", "3": "3",
"-FOUR-": "4", "4": "4",
"-FIVE-": "5", "5": "5",
"-SIX-": "6", "6": "6",
"-SEVEN-": "7", "7": "7",
"-EIGHT-": "8", "8": "8",
"-NINE-": "9", "9": "9",
}
operators = {
"-ADD-": "+", "+": "+",
"-SUBTRACT-": "−", "-": "−",
"-MULTIPLY-": "×", "*": "×",
"-DIVIDE-": "÷", "/": "÷",
"-EQUAL-": "=",
}
def number(eq, ev):
# Append number to current number string being entered
if eq["operator"]:
eq["num2"] = eq["num2"] + numbers[ev]
else:
eq["num1"] = eq["num1"] + numbers[ev]
def operator(eq, result_box, ev):
# Sets or changes the operator being used
if not eq["num1"]:
if result_box:
eq["num1"] = result_box.replace(",", "")
else:
eq["num1"] = "0"
eq["operator"] = operators[ev]
def change_sign(eq, result_box):
# '±' changes the sign of the current number entered
if eq["operator"]:
eq["num2"] = str(-Decimal(eq["num2"]))
else:
if not eq["num1"]:
eq["num1"] = result_box.replace(",", "")
eq["num1"] = str(-Decimal(eq["num1"]))
def decimal_point(eq):
# '.' adds a decimal to the current number entered
if eq["operator"]:
if "." not in eq["num2"]:
eq["num2"] = eq["num2"] + "."
else:
return
else:
if "." not in eq["num1"]:
eq["num1"] = eq["num1"] + "."
else:
return
def equals(eq):
# Performs the selected operation on the entered numbers
getcontext().prec = 17
eq["sign"] = "="
if not eq["num2"] and eq["operator"]:
eq["num2"] = eq["num1"]
if eq["operator"] == "+":
result = Decimal(eq["num1"]) + Decimal(eq["num2"])
elif eq["operator"] == "−":
result = Decimal(eq["num1"]) - Decimal(eq["num2"])
elif eq["operator"] == "×":
result = Decimal(eq["num1"]) * Decimal(eq["num2"])
elif eq["operator"] == "÷":
result = Decimal(eq["num1"]) / Decimal(eq["num2"])
else:
result = Decimal(eq["num1"])
return '{:,}'.format(result)
def complex_op(eq, ev):
# Sets or changes the complex operator being used
getcontext().prec = 17
eq["sign"] = "="
if ev == "-SQUARE-":
result = Decimal(eq["num1"]) ** Decimal("2")
elif ev == "-SQRT-":
result = Decimal(eq["num1"]).sqrt()
elif ev == "-INVERSE-":
result = Decimal("1") / Decimal(eq["num1"])
else:
result = Decimal(eq["num1"])
return '{:,}'.format(result)
def backspace(eq):
# 'Backspace' removes last character entered
if eq["num2"]:
eq["num2"] = eq["num2"][:len(eq["num2"]) - 1]
elif eq["operator"]:
eq["operator"] = ""
elif eq["num1"]:
eq["num1"] = eq["num1"][:len(eq["num1"]) - 1]
else:
return
def clear_entry(eq):
# 'Clear Entry' removes last operand or operator entered
if eq["num2"]:
eq["num2"] = ""
elif eq["operator"]:
eq["operator"] = ""
elif eq["num1"]:
eq["num1"] = ""
else:
return
def clear(eq):
# 'Clear' removes everything entered
return eq.fromkeys(eq, "")
def main_loop(win):
eq = {
"num1": "",
"operator": "",
"num2": "",
"sign": ""
}
result_box = "0"
while True:
ev, val = win.read()
print(ev)
try:
if ev == "-EXIT-" or ev is None:
break
elif ev in numbers:
number(eq, ev)
elif ev in [
"-ADD-", "+",
"-SUBTRACT-", "-",
"-MULTIPLY-", "*",
"-DIVIDE-", "/"
]:
operator(eq, result_box, ev)
elif ev == "-SIGN-":
change_sign(eq, result_box)
elif ev == "-DECIMAL-" or ev == ".":
decimal_point(eq)
elif ev == "-EQUAL-" or ev == "=" or ev == "\r":
result_box = equals(eq)
win["-RESULT-"](result_box)
elif ev in ["-PERCENT-", "-SQRT-", "-SQUARE-", "-INVERSE-"]:
result_box = complex_op(eq, ev)
win["-RESULT-"](result_box)
elif ev == "-BACK-" or ev == "BackSpace:8":
backspace(eq)
elif ev == "-CE-" or ev == "Delete:46":
clear_entry(eq)
elif ev == "-CLEAR-":
eq = clear(eq)
except ZeroDivisionError:
# Catch division by zero error
win["-RESULT-"]("Cannot divide by 0")
# Display the current entered values from 'eq' to the 'Entry' label
win["-ENTRY-"](
eq["num1"]
+ eq["operator"]
+ eq["num2"]
+ eq["sign"]
)
# Reset 'eq' after a result has been shown
if eq["sign"]:
eq = clear(eq)
|
4b0fab15f656c4621673cecc1a024e8d39efe9e8 | LucasLeone/tp2-algoritmos | /cf/cf53.py | 382 | 3.90625 | 4 | '''
Se debe calcular e imprimir el producto de todas las X y de todas las Y
de sesenta y tres pares ordenados de números enteros.
'''
for i in range(0, 63):
print('---- Nuevo par ordenado ----')
x = int(input('Ingrese el primer numero entero: '))
y = int(input('Ingrese el segundo numero entero: '))
print(f'El producto de este par ordenado es: {x * y}') |
78b03cfa5f08b6843ff85b08cd8b54d7fa119c71 | htl1126/leetcode | /60.py | 727 | 3.578125 | 4 | # ref: https://discuss.leetcode.com/topic/37333/python-i-think-this-is-clean
# -code-with-some-of-my-explanation
class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
num = map(str, range(1, n + 1))
k -= 1
factor = 1
for i in xrange(1, n):
factor *= i
res = []
for i in xrange(n - 1, -1, -1):
res.append(num[k / factor])
num.remove(num[k / factor])
if i:
k %= factor
factor /= i
return ''.join(res)
if __name__ == '__main__':
sol = Solution()
print sol.getPermutation(4, 18)
|
080a1a74fe69eca3cf5add4d0200e16d976d1dd7 | protea-ban/LeetCode | /066.Plus One/Plus One.py | 425 | 3.515625 | 4 | class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
# 整数列表转成整数
num = int(''.join([str(t) for t in digits]))
# 加一
num += 1
# 将整数转成列表
return [int(s) for s in str(num)]
if __name__ == '__main__':
so = Solution()
digits = [1,2,3]
print(so.plusOne(digits))
|
8bf37d71fddde157c3a8d959503a491608aec5e9 | juliadejane/CursoPython | /ex005.py | 110 | 4.0625 | 4 | n = int(input('Digite um numero: '))
print('O antecessor é {} e o sucessor é {}'.format((n - 1), (n + 1)))
|
9a052d5dd08938b5d9245865fca79368058fd707 | gabeno/redmond | /problems/sliding_window/4_longest_substring_with_k_distinct_characters.py | 1,841 | 4.28125 | 4 | """
Given a string, find the length of the longest substring in it with no more than
K distinct characters.
Examples:
Input: String="araaci", K=2
Output: 4
Explanation: The longest substring with no more than '2' distinct characters is "araa".
Input: String="araaci", K=1
Output: 2
Explanation: The longest substring with no more than '1' distinct characters is "aa".
Input: String="cbbebi", K=3
Output: 5
Explanation: The longest substrings with no more than '3' distinct characters are "cbbeb" & "bbebi".
Time complexity: O(n)
The `for` loop runs for all elements and the inner `while` loop process each
element only once hence O(n + n) = O(n)
Space complexity: O(K)
We will be storing K + 1 characters in the hashmap
"""
def longest_substring_with_k_distinct(s: str, k: int):
window_start = max_len = 0
found = dict()
for window_end in range(len(s)):
right_char = s[window_end]
if right_char not in found:
found[right_char] = 0
found[right_char] += 1
while len(found) > k:
left_char = s[window_start]
found[left_char] -= 1
if found[left_char] == 0:
del found[left_char]
window_start += 1
max_len = max(max_len, window_end - window_start + 1)
return max_len
if __name__ == "__main__":
s = "araaci"
k = 2
substring_len = longest_substring_with_k_distinct(s, k)
print(f"string: {s}, longest substring={substring_len}")
print("")
s = "araaci"
k = 1
substring_len = longest_substring_with_k_distinct(s, k)
print(f"string: {s}, longest substring={substring_len}")
print("")
s = "cbbebi"
k = 3
substring_len = longest_substring_with_k_distinct(s, k)
print(f"string: {s}, longest substring={substring_len}")
|
f78f62039ae6f8b98c9964327e5a84d4dcfa2336 | LeonildoMuniz/Logica_de_programacao_Python | /Listas/Lista3_Ex49.py | 204 | 3.625 | 4 | a=1
b=1
result=0
num=int(input('Informe o numeros de termos para serie: '))
for i in range(0,num,1):
result+=a/b
print(f'{i+1} - S = {a}/{b}')
a+=1
b+=2
print(f'Soma total de serie: {result:.2f}')
|
0ad250dac56a35abaf0d14f67e297abb721a981e | Deep455/Python-programs-ITW1 | /python_assignment_2/py13.py | 707 | 4.03125 | 4 |
def binarysearch (arr, l, r, x):
if r >= l:
mid = l + (r - l) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarysearch(arr, l, mid-1, x)
else:
return binarysearch(arr, mid + 1, r, x)
else:
return -1
n = int(input("enter size of list : "))
a = []
print("enter numbers in increasing order : ")
for i in range(n):
temp = int(input())
a.append(temp)
x = int(input("enter number you want to search : "))
position = binarysearch(a, 0, len(a)-1, x)
index = position - 1
if position != -1:
print ("{} found at index {}".format(x,index))
else:
print ("{} not found".format(x)) |
c97ca0dbb6d1727593db2c72b4ff89f0cfd96260 | verhovsky/CCC | /contests/2014/juniorSolutions/j4.py | 465 | 3.5 | 4 | how_many_people = int(raw_input())
people = range(1, how_many_people+1) #you're a computer scientist, you should number your friends starting at 0
how_many_rounds = int(raw_input())
rounds = [int(raw_input()) for _ in range(how_many_rounds)]
for round in rounds:
new_people = list()
for i, person in enumerate(people):
if (i+1) % round is not 0:
new_people.append(person)
people = new_people
for person in people:
print person |
62686658d1dfe624428387ce7696da48a81d7377 | swang2000/DSAPractice | /Leet_validParenthesis.py | 287 | 3.59375 | 4 | def minAddToMakeValid(S):
"""
:type S: str
:rtype: int
"""
stack = []
for c in S:
if not stack or c == '(':
stack.append(c)
elif c == ')' and stack[-1] == '(':
stack.pop()
return len(stack)
minAddToMakeValid("()))((") |
3d359283db8549698e8a54b721e354f09f637813 | venkatraj/python-practice | /crash-course/ch03/more_guests_6.py | 539 | 4.53125 | 5 | friends = ['Saravanan', 'Jeevamani', 'Manohar Raja', 'Ravishankar']
for friend in friends:
print(f'Hi {friend}, I would like to invite you to dinner')
print(f'I heard, {friends[-1]} could not make it to dinner!')
friends[-1] = 'Ramlal'
for friend in friends:
print(f'Hi {friend}, I would like to invite you to dinner')
print('Wow! I have found a big dinner table!!')
friends.insert(0, 'Sivakumar M')
friends.insert(3, 'VJ Sivakumar')
friends.append('Govindarajan')
for friend in friends:
print(f'Hi {friend}, I would like to invite you to dinner')
|
8869790c1be7e4b328d7063d38282c2e21d17288 | ArtisticPug/GeekBrains_Python | /GeekBrains_Python_Lesson_8/Homework_5.py | 512 | 3.828125 | 4 | class ComplexNum:
def __init__(self, n1, n2):
self.n1 = n1
self.n2 = n2
def __str__(self):
return str(complex(self.n1, self.n2))
def __add__(self, other):
result = complex(self.n1, self.n2) + complex(other.n1, other.n2)
return str(complex(result))
def __mul__(self, other):
result = complex(self.n1, self.n2) * complex(other.n1, other.n2)
return str(complex(result))
a = ComplexNum(5, 6)
b = ComplexNum(3, 8)
print(a + b)
print(a * b)
|
2b0bab3979926bcb4b6b9a54e9c86689d8edf207 | MohamedSabthar/Algorithms | /Rabin.py | 740 | 3.625 | 4 | def rabin(text,pattern):
textHash = patternHash = 0
prime = 37
dPrime = 13
for i in range(len(pattern)):
textHash = (textHash*prime + ord(text[i]))%dPrime
patternHash = (patternHash*prime + ord(pattern[i]))%dPrime
for i in range(len(text)-len(pattern)+1):
if textHash == patternHash :
j = 0
while j < len(pattern) and text[i+j]==pattern[j] :
j+=1
if j==len(pattern):
print(f'found pattern @ index {i}')
if i < len(text)-len(pattern):
textHash = ((textHash-(ord(text[i])*pow(prime,len(pattern)-1))) * prime + ord(text[i+len(pattern)]))%dPrime
rabin('Can you find me!','ou fi') |
578ae498d163b983385dbd8cbccd9277091d3f1f | aarti98/RockPaperScissor | /rock_paper_scissor.py | 655 | 4.21875 | 4 | from random import choice
print("Welcome to the game. Player chooses first!")
#ASK INPUT FROM USER
player= input("Choose (r) for rock, (p) for paper and (s) for scissor \n")
print("You chose " + player + "\n")
#GENERATE COMPUTER'S CHOICE
computer= choice([1,2,3])
if computer == 1:
computer = 'r'
elif computer == 2:
computer = 'p'
else:
computer = 's'
print("Computer chooses " + str(computer) + "\n")
#COMPARE THE CONDITION
if player == computer:
print("DRAW!")
elif player == 'r' and computer == 's' or player == 'p' and computer == 'r' or player == 'p' and computer == 'r':
print('Player wins!')
else:
print('Computer wins!')
|
1c3b5db0540617e4865d2c4e04dca5765892c29b | edwinsentinel/pythonbots | /webscraper.py | 546 | 3.71875 | 4 | # import libraries
import urllib
from bs4 import BeautifulSoup
#specify the url
quote_page='http://www.bloomberg.com/quote/SPX:IND'
#query the website and return the html to the variable 'page'
page= urllib.urlopen(quote_page)
#parse the html using beatifulsoup and store in variable 'soup'
soup=BeautifulSoup(page,'htm.parser')
#take out the <div> of name and get its value
name_box=soup.find('h1',attrs={'class':'name'})
name = name_box.text.strip() # strip() is used to remove starting and trailing
print (name)
# get the index price
|
ab2b0945daace27741ea4f1b6ec28052f6ad7579 | chayes1987/PythonExercises | /sem2/question_one.py | 1,218 | 4.3125 | 4 | __author__ = 'Conor'
""" 1.
a. Write a Python program that generates 10 random numbers between 1 and 100 (inclusive) and calculates and
displays the average of the generated numbers.
(12 marks)
b. Write a function that takes 3 numbers as arguments and returns the value of the largest of the 3 numbers.
(13 marks)
"""
# A.1 (a)
# Import required package
from random import randint
# Initialize required variables
min_num = 1
max_num = 100
total = 0
# Loop runs 10 times
for num in range(1, 11):
# Generate random number
random_num = randint(min_num, max_num)
print('Random number %s: %s' % (num, random_num))
# Add to total for calculation after
total += random_num
# Print the average
print('Average: %s' % (total/10))
# A.1 (b)
# Fast way
def max_num(num_one, num_two, num_three):
return max(num_one, num_two, num_three)
# Call the function
print(max_num(1, 2, 3))
# Alternative
def my_max_num(num_one, num_two, num_three):
maximum_num = num_one
if num_two > maximum_num:
maximum_num = num_two
if num_three > maximum_num:
maximum_num = num_three
return maximum_num
# Call the function
print(my_max_num(4, 1, 6))
|
86f630cad661a11fa816c62c4a4147835044dbb9 | Aasthaj01/DSA-questions | /array/two_sum.py | 868 | 3.75 | 4 | # Given an array of integers, return indices of the two numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
def summ(nums, target):
listt = []
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i]+nums[j] == target and i!=j:
listt.append(i)
listt.append(j)
return listt
else:
continue
def summi(nums, target):
complements = {}
for i,num in enumerate(nums):
if target - num in complements:
return[complements[target - num], i]
complements[num] = i
return []
target = int(input())
nums = list(map(int, input().split()))
print(summi(nums, target))
print(summ(nums, target))
|
a7ef1113eb1e4e768172fd9063b56b817acc0667 | LalityaSawant/Python | /DS and Algo in Python/Sort algorithms/merge_sort_complete.py | 814 | 3.953125 | 4 | def merge_sorted(arr1,arr2):
sorted_arr = []
i,j =0,0
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
sorted_arr.append(arr1[i])
i += 1
else:
sorted_arr.append(arr2[j])
j += 1
#print(f'sorted arr {sorted_arr}')
while i < len(arr1):
sorted_arr.append(arr1[i])
i += 1
while j < len(arr2):
sorted_arr.append(arr2[j])
j += 1
return sorted_arr
def divide_arr(arr):
if len(arr) < 2:
return arr[:]
else:
middle = len(arr)//2 # gives whole number
l1 = divide_arr(arr[:middle])
l2 = divide_arr(arr[middle:])
# implied return None
return merge_sorted(l1,l2)
#l = [8,6,2,5,7]
l = [6,8,1,4,10,7,8,9,3,2,5]
print(divide_arr(l))
|
01ff49f4c4378db3a1373bbcc1f4aea57386aa0d | melnikovay/U7 | /U7-2v2.py | 1,502 | 3.796875 | 4 | #Отсортируйте по возрастанию методом слияния одномерный вещественный
#массив, заданный случайными числами на промежутке [0; 50).
#Выведите на экран исходный и отсортированный массивы.
import random
MIN1 = 0
MAX1 = 50
SIZE = 10
MASS = [random.randint(MIN1, MAX1) for _ in range (SIZE)]
print(MASS)
def sort_mass (MASS1, MASS2):
sort_mass = []
MASS1_id = MASS2_id = 0
MASS1_len, MASS2_len = len(MASS1), len(MASS2)
for _ in range (MASS1_len + MASS2_len):
if MASS1_id < MASS1_len and MASS2_id < MASS2_len:
if MASS1[MASS1_id] <= MASS2[MASS2_id]:
sort_mass.append(MASS1[MASS1_id])
MASS1_id+=1
else:
sort_mass.append(MASS2[MASS2_id])
MASS2_id+=1
elif MASS1_id == MASS1_len:
sort_mass.append(MASS2[MASS2_id])
MASS2_id+=1
elif MASS2_id == MASS2_len:
sort_mass.append(MASS1[MASS1_id])
MASS1_id+=1
#print (MASS1)
# print (MASS2)
#print (sort_mass)
return sort_mass
def del_mass (MASS):
if len(MASS) <= 1:
return MASS
d = len(MASS)//2
MASS1 = del_mass(MASS[: d])
MASS2 = del_mass(MASS[d :])
# print (MASS1, MASS2)
return sort_mass(MASS1, MASS2)
MASS_sort = del_mass (MASS)
print (MASS_sort)
|
53c8a3a3671988d11bab73a9f6cc3564c458bb98 | JeremiahTee/python-games-sweigart | /pygameHelloWorld.py | 1,944 | 3.765625 | 4 | import pygame, sys
from pygame.locals import *
# Set up pygame.
pygame.init() # must do before anything, initializes pygame so it's read to use
# Set up the window
windowSurface = pygame.display.set_mode((500,400), 0, 32) #500 px wide and 400 px tall by using tuple
#set_mode() returns a pygame.Surface object
pygame.display.set_caption('Hello world')
# Set up the colors
BLACK = (0, 0, 0)
WHITE = (255, 255 ,255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Set up the fonts
basicFont = pygame.font.SysFont(None, 48) #Font object
# Set up the text
text = basicFont.render('Hello world!', True, WHITE, BLUE)
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery
# Draw the white background onto the surface
windowSurface.fill(WHITE)
# Draw a green polygon onto the surface.
pygame.draw.line(windowSurface, BLUE, (60,60), (120,60), 4)
pygame.draw.line(windowSurface, BLUE, (120, 60), (60,120))
pygame.draw.line(windowSurface, BLUE, (60,120), (120,120), 4)
# Draw a blue circle onto the surface.
pygame.draw.circle(windowSurface, BLUE, (300,50), 20, 0)
# Draw a red ellipse onto the surface.
pygame.draw.ellipse(windowSurface, RED, (300, 250, 40, 80), 1)
# Draw the text's background rectangle onto the surface.
pygame.draw.rect(windowSurface, RED, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40))
# Get a pixel array of the surface
pixArray = pygame.PixelArray(windowSurface) #Pixel Array object
pixArray[480][380] = BLACK
del pixArray
# Draw the text onto the surface.
windowSurface.blit(text, textRect)
# Draw the window onto the screen.
pygame.display.update()
# Run the game loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit() #call this before ending program
sys.exit() |
1224c421cf6a2528e3e3d8054afebeda5e401a75 | mananmonga/Applied-Crypto | /Labs/lab2.py | 9,542 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
################################################################## LAB 2 ##################################################################
"""
List you collaborators here:
Jainam Shah
Your task is to fill in the body of the functions below. The specification of each of the functions is commented out, and an example test case is provided for your convenience.
"""
# Feel free to use either of `AES` or `Fernet` below
from Cryptodome.Cipher import AES
import binascii
def aes_encipher(key, plaintext):
"""Performs an AES encipher on the input "plaintext" using the default ECB mode.
Args:
key (str): hex-encoded string of length 16-bytes (default AES block input size).
plaintext (str): hex-encoded string of length 16 bytes (default AES block input size).
Returns:
str: The ciphertext output as a hex-encoded string
Note:
One thing you'll find in cryptography is that tests are your friend. Granted, unit tests are important in all of software
development, but cryptography has two properties that make testing even more important still:
- The output of any cryptosystem is supposed to look random. So spot-checking the output won't help you to distinguish
whether it was implemented correctly or not.
- It is essential that your implementation interoperate with everybody else's implementation of the same cipher,
so that Alice and Bob can produce the same results when one of them uses your code and the other uses someone else's code.
Ergo, it is important that everybody follows the cipher designers' spec exactly, even down to low-level details like whether strings
follow big or little endianness. (Note: if you don't know what `endianness' means, just ignore that last comment.)
For this question, here are some test vectors you can use. I provide an AES-128 key (16 bytes long) and a plaintext (16 bytes long) along with
the associated 16-byte ciphertext for the plaintext.
Test vectors:
aes_encipher(key = "00000000000000000000000000000000", plaintext = "f34481ec3cc627bacd5dc3fb08f273e6") == "0336763e966d92595a567cc9ce537f5e"
aes_encipher(key = "00000000000000000000000000000000", plaintext = "9798c4640bad75c7c3227db910174e72") == "a9a1631bf4996954ebc093957b234589"
aes_encipher(key = "00000000000000000000000000000000", plaintext = "96ab5c2ff612d9dfaae8c31f30c42168") == "ff4f8391a6a40ca5b25d23bedd44a597"
"""
encodedKey = binascii.unhexlify(key)
encodedPlaintext = binascii.unhexlify(plaintext)
aesCipher = AES.new(encodedKey,AES.MODE_ECB)
cipherText = aesCipher.encrypt(encodedPlaintext)
cipherText = cipherText.hex()
return cipherText
def find_key(plaintext, ciphertext):
"""Given a plaintext and a ciphertext, find the 16-bytes key that was used under AES (ECB mode, just like in `aes_encipher`) to produce the given ciphertext.
Args:
plaintext (str): hex-encoded string of length 16 bytes.
ciphertext (str): hex-encoded string of length 16 bytes.
Returns:
str: hex-encoded 16-bytes key used to produce 'ciphertext' given 'plaintext' under AES (ECB-mode)
Note:
Keep in mind that AES keys are 128-bits (16 bytes), and you should assume for this question that the first **108-bits** of the AES key are all zeros.
Hint:
Use brute-force!
Examples:
find_key(plaintext = "f34481ec3cc627bacd5dc3fb08f273e6", ciphertext = "3ed20de893c03d47c6d24f09cb8a7fd2") == "00000000000000000000000000000001"
find_key(plaintext = "f34481ec3cc627bacd5dc3fb08f273e6", ciphertext = "ac021ba807067a148456ffb140cd485f") == "0000000000000000000000000000d7f6"
find_key(plaintext = "f34481ec3cc627bacd5dc3fb08f273e6", ciphertext = "78e7e91df1a6792fce896e3e1925461d") == "0000000000000000000000000001dae9"
"""
encodedPlainTxt = binascii.unhexlify(plaintext)
encodedCipherTxt = binascii.unhexlify(ciphertext)
allKeys = [0] * 0x100000
for i in range(0, 0x100000):
allKeys[i] = hex(i)[2:].zfill(32)
print(allKeys)
for key in allKeys:
candidate_key = binascii.unhexlify(key)
aesDecoder = AES.new(candidate_key,AES.MODE_ECB)
if encodedPlainTxt == aesDecoder.decrypt(encodedCipherTxt):
return key
commonWordList = ['the','be','to','of','and','a','in','that','have','I','it','for','not','on','with','he','as','you','do','at','this','but','his','by','from','they','we','say','here','she','or',
'an','will','my','one','all','would','there','their','what','so','up','out','if','about','who','get','which','go','me','when','make','can','like','time','no','just','him','know','take','people',
'into','year','your','good','some','could','them','see','other','than','then','now','look','only','come','its','over','think','also','back','after','use','two','how','our','work','first','well',
'way','even','new','want','because','any','these','give','day','most','us']
"""the check functions simply xors the candidate string that we pass with the xor(c1,c2) and determnies if
if the ASCII of the resulting characters of the string is part of the commonword list """
def check(string,xord):
print(string)
if len(string) > len(xord):
return False
if len(string) == len(xord):
complete = True
else:
complete = False
new_string = ''.join([chr(ord(string[i]) ^ xord[i]) for i in range(len(string))])
print(new_string)
words = new_string.split()
print(words)
if not complete:
for word in words[:-1]:# by doing this i don't wait for the string to be constructed fully. i check it partially and the last word which i get could be a part of another word.
if not word in commonWordList:
return False
last = words[-1]
for test in commonWordList:
if test.startswith(last):
return True
return False
else:
for word in words:
if not word in commonWordList:
return False
return True
""" the construct funtion contains the words that are valid uptill now .For possible sentences it will call the function check
that will only return true if words we passed and the xor of it with the xor(c1,c2) is part of the list
if it returns true then the constrcut function will call itself again meaning that it should proceed
ahead by creating a possisble candidate substring by adding the previously matched to a new string.
If the check returns false then it means that the we should not search further since none of the characters are part of the list """
def construct(prefix,xord):
if len(prefix) == len(xord):
return prefix
for word in commonWordList:
word = word.lower()
if prefix != "":
new_word = prefix + " " + word
else:
new_word = word
if (check(new_word,xord)):
res = construct(new_word,xord)
if res != None:
return res
if prefix == "":
for word in commonWordList:
word = word.lower().capitalize()
new_word = word
if(check(new_word,xord)):
res = construct(new_word,xord)
if res != None:
return res
return None
def two_time_pad():
"""A one-time pad simply involves the xor of a message with a key to produce a ciphertext: c = m ^ k.
It is essential that the key be as long as the message, or in other words that the key not be repeated for two distinct message blocks.
Your task:
In this problem you will break a cipher when the one-time pad is re-used.
c_1 = 3801025f45561a49131a1e180702
c_2 = 07010051455001060e551c571106
These are two hex-encoded ciphertexts that were formed by applying a “one-time pad” to two different messages with
the same key. Find the two corresponding messages m_1 and m_2.
Okay, to make your search simpler, let me lay out a few ground rules. First, every character in the text is either
a lowercase letter or a space, aside from perhaps the first character in the first message which might be capitalized.
As a consequence, no punctuation appears in the messages. Second, the messages consist of English words in ASCII.
Finally, all of the words within each message is guaranteed to come from the set of the 100 most
common English words: https://en.wikipedia.org/wiki/Most_common_words_in_English.
Returns:
Output the concatenation of strings m_1 and m_2. (Don't worry if words get smashed together as a result.)
"""
c_1 = '3801025f45561a49131a1e180702'
c_2 = '07010051455001060e551c571106'
# converting the hexadecimal representaiton to integers for every 2 bytes since it xor operations become on integers
c_1_int = [int(c_1[i] + c_1[i+1], 16) for i in range(0, len(c_1), 2)]
c_2_int = [int(c_2[i] + c_2[i+1], 16) for i in range(0, len(c_1), 2)]
xord = [c_1_int[i] ^ c_2_int[i] for i in range(len(c_1_int))] #xor of the two lists which are integer representations
result = construct('',xord)
if result == None:
return None
else:
print(result)
new_string = ''.join([chr(ord(result[i]) ^ xord[i]) for i in range(len(result))])
return new_string + result
# f1 = two_time_pad()
# print(f1)
# ans = find_key("f34481ec3cc627bacd5dc3fb08f273e6","3ed20de893c03d47c6d24f09cb8a7fd2")
# print(ans) |
5eb3aa308d30cd26a380758b902d64dc17c6945f | nicolasalliaume/python-bootcamp | /Module_3/exercises/08-big-mess/exercise.py | 698 | 3.984375 | 4 | #############################################
#
# Please help me solve this big mess!!
# Following there's a list containing elements
# of different types.
#
# Print all the elements following this rules:
# - If it is a number or string, just print it
# - If it is a list, print each of the elements
# - If it es a tuple, print each of the elements
# - If it is a dictionary, print each of the values
#
# Tip: remember type() function? It will tell you
# the type of a given variable (list, dict, tuple, ...)
#
#############################################
big_mess = ['Even', ('if', 'you'), ['fall', 'on', 'your'], {1: 'face', 2: "you're", 'other': 'still'}, 'moving', ['forward', '.']]
for : |
6597f928f6d4524628b2c7bfe116212501df6e0b | adrianbartnik/ProjectEuler | /037.py | 1,420 | 3.5 | 4 | """
Project Euler Problem 37
========================
The number 3797 has an interesting property. Being prime itself, it is
possible to continuously remove digits from left to right, and remain
prime at each stage: 3797, 797, 97, and 7. Similarly we can work from
right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left
to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
"""
from itertools import chain
import numpy as np
import timeit
n = 1000000
primes = np.ones(n+1, dtype=np.bool)
for i in np.arange(2, n**0.5 +1, dtype=np.uint32):
if primes[i]:
primes[i*i::i] = False
primes = np.nonzero(primes)[0][2:]
# vfunc = np.vectorize(str)
# primes = vfunc(primes)
def isprime(t):
if t == 1:
return False
if t == 2:
return True
if t % 2 == 0:
return False
i = 3
while i <= math.sqrt(t):
if t % i == 0:
return False
i += 2
return True
def check(n):
n = str(n)
return all(np.in1d([n[i:] for i in xrange(0,len(n))] + [n[:i+1] for i in xrange(0,len(n))], primes, assume_unique=True))
# return set(list(chain.from_iterable((n[i:],n[:i+1]) for i in xrange(0,len(n))))).issubset(primes)
# print check(3797)
# print timeit.timeit(check, number=100)
result = [x for x in primes if check(x)]
print sum(result)
print result
|
400f898d2d23d1d785412275a9a0c25b9c04ec22 | luzi82/AIND-Sudoku | /nrook.py | 2,463 | 4.03125 | 4 | '''
By luzi82@gmail.com, 2017-01-25
N-Rooks problem:
That is something like "N-Queens problem"
In N-Rooks problem, we are required to put N Rook pieces to a NxN grid.
Each row and col should contain exactly one rook.
Examples:
4-rook problem
1 = True = possible location
0 = False = impossible location
Input: (level=1)
+---------+
| 1 0 0 0 |
| 1 1 1 1 |
| 1 1 1 1 |
| 1 1 1 1 |
+---------+
Output:
+---------+
| 1 0 0 0 |
| 0 1 1 1 |
| 0 1 1 1 |
| 0 1 1 1 |
+---------+
Input: (level=2)
+---------+
| 1 1 0 0 |
| 1 1 0 0 |
| 1 1 1 1 |
| 1 1 1 1 |
+---------+
Output:
+---------+
| 1 1 0 0 |
| 1 1 0 0 |
| 0 0 1 1 |
| 0 0 1 1 |
+---------+
WARNING:
The function can only fill the 0 "vertically".
It is not smart enough to handle following case:
+-------+
| 1 1 1 |
| 0 1 1 |
| 0 1 1 |
+-------+
If you want to do this, please transpose the input urself.
'''
import numpy as np
import itertools
def nrook(input_vv,level,min_level=1):
size = len(input_vv)
one_count_v = [np.count_nonzero(input_v) for input_v in input_vv]
suitable_idx_v = [i for i in range(size) if (one_count_v[i] <= level) and (one_count_v[i] >= min_level)]
if len(suitable_idx_v) < level:
return False
combination_vv = itertools.combinations(suitable_idx_v, level)
non_zero_count = np.count_nonzero(input_vv)
for combination_v in combination_vv:
orr = np.zeros(size,dtype=bool)
for combination in combination_v:
orr = np.logical_or(orr,input_vv[combination])
if np.count_nonzero(orr) > level:
continue
orr_not = np.logical_not(orr)
for i in range(size):
if i in combination_v:
continue
np.logical_and(input_vv[i],orr_not,input_vv[i])
return np.count_nonzero(input_vv) != non_zero_count
if __name__ == '__main__':
import unittest
class TestNRook(unittest.TestCase):
def test_n_rook(self):
x = np.array([[1,0,0,0],[1,1,1,1],[1,1,1,1],[1,1,1,1]],dtype=np.bool)
self.assertEqual(nrook(x,1), True)
self.assertEqual(np.logical_xor(x, np.array([[1,0,0,0],[0,1,1,1],[0,1,1,1],[0,1,1,1]],dtype=np.bool)).any(),False)
x = np.array([[1,1,0,0],[1,1,0,0],[1,1,1,1],[1,1,1,1]],dtype=np.bool)
self.assertEqual(nrook(x,2), True)
self.assertEqual(np.logical_xor(x, np.array([[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]],dtype=np.bool)).any(),False)
unittest.main()
|
12ada9468e9f216b2506af7c2eb6f3ac1dfbaae7 | MarFie93/devopsbc | /python.py/comments.py | 439 | 3.90625 | 4 | # This is a single line comment
# You can write comments like this
print("Hello world")
# comments here
print("Another print call")
"""
You are in a multline comment now :)
That means you can hit enter and separate your
comments
Many lines, make sure your code is clean.
"""
print("You can have comments in the middle of the code")
print("Adding one more print to show it in the codecast")
#I am adding one more comment
|
1d1baf0d1e3b7489c8d451e2b8f3ac0c01296c17 | weih1121/Sort | /radixSort.py | 475 | 3.5625 | 4 | import math
import random
def RadixSort(array, radix=10):
k = int(math.ceil(math.log(max(array), radix)))
bucket = [[] for i in range(radix)]
for i in range(k):
for j in array:
bucket[int(j / (radix ** i) % radix)].append(j)
del array[:]
for z in bucket:
array += z
del z[:]
return array
array = []
for i in range(50):
array.append(random.randint(0, 200))
array = RadixSort(array)
print(array) |
22cd96a79d0a22ce120ef3ef5eb6c8ee8dc05197 | Sevendeadlys/leetcode | /108/sortedArrayToBST.py | 721 | 3.796875 | 4 | # 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 sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums: return None
return self.helper(nums,0,len(nums)-1)
def helper(self,nums,lo,hi):
if hi < lo : return None
mid = (hi + lo)/2
node = TreeNode(nums[mid])
node.left = self.helper(nums,lo,mid-1)
node.right = self.helper(nums,mid+1,hi)
return node
if __name__ == "__main__":
so = Solution()
so.sortedArrayToBST([1,2,3,4,5,6,7,8,9]) |
9f61371a9bc27d960b542e079c38ce45cbda03f7 | irvandenata/Metode-Numerik | /simpson1per3.py | 1,023 | 3.921875 | 4 | a = float(input("Masukkan Nilai a : " ))
b = float(input("Masukkan Nilai b : "))
segment = float(input("Masukkan Jumlah Segment : "))
h = (b-a)/segment
xd = []
data = []
f = a
xd.append(f)
for i in range(3):
f += h
xd.append(f)
xd.append(b)
print("Setiap Nilai X : ",xd)
j = lambda x : (((1/4)*-9.1688*10**-6)*(x**4))+((1/3)*2.7961*(10**-3)*(x**3))-((1/2)*2.8487*(10**-1)*(x**2))+(9.6778*x)
g = lambda x: ((-9.1688*10**-6)*(x**3))+(2.7961*(10**-3)*(x**2))-(2.8487*(10**-1)*(x))+9.6778
for x in range(len(xd)):
if xd[x] >123131:
data.append(0)
elif xd[x]<=172:
data.append(g(xd[x]))
elif xd[x] > 172 and xd[x]<200:
data.append(0)
print("Setiap Nilai F(Xi) : ",data)
result = (b-a)/(3*4)*(data[0]+(4*data[1]+4*data[3])+(2*data[2])+data[4])
print("Hasil Perhitungan Simpson : ",result)
print("Hasil Perhitungan Integral Manual : ",j(b)-j(a))
print("Error Et : ", ((j(b)-j(a))-result))
print("Error Absolute : ",(((j(b)-j(a))-result)/(j(b)-j(a)))*100,"%") |
e753dd5d5719e0a80f9e3587b81baf101687ff9d | drahmuty/Algorithm-Design-Manual | /04-04.py | 1,338 | 4.0625 | 4 | """
4-4. Assume that we are given n pairs of items as input, where the first item is a number and the
second item is one of three colors (red, blue, or yellow). Further assume that the items are sorted by number.
Give an O(n) algorithm to sort the items by color (all reds before all blues before all yellows)
such that the numbers for identical colors stay sorted. For example: (1,blue), (3,red), (4,blue),
(6,yellow), (9,red) should become (3,red), (9,red), (1,blue), (4,blue), (6,yellow).
"""
def color_sort(arr):
result = [None for i in range(len(arr))] # Init empty array
r = b = y = 0 # Init color indexes
for i in arr: # Determine color indexes
if i[1] == 'red':
b += 1
y += 1
elif i[1] == 'blue':
y += 1
for i in arr: # Add to next available color index
if i[1] == 'red':
result[r] = i
r += 1
elif i[1] == 'blue':
result[b] = i
b += 1
else:
result[y] = i
y += 1
return result
# Test case
a = [
(1, 'blue'),
(3, 'red'),
(4, 'blue'),
(6, 'yellow'),
(9, 'red'),
(11, 'blue'),
(12, 'yellow'),
(20, 'red')
]
print (color_sort(a))
|
250bb9741af33135f46c5027e03d8f3323f440d4 | Rumaia/pcs2_homework2 | /TIMER.py | 1,389 | 3.515625 | 4 |
import timeit
setup = """
from homework2 import quickSort
from homework2 import mergeSort
import random
lst = random.sample(range(50), 10)
lst1 = random.sample(range(500), 100)
lst2 = random.sample(range(5000), 1000)
lst3 = random.sample(range(50000), 10000)
"""
t=timeit.Timer('quickSort(lst)', setup = setup)
t1=timeit.Timer('quickSort(lst1)', setup = setup)
t2=timeit.Timer('quickSort(lst2)', setup = setup)
t3=timeit.Timer('quickSort(lst3)', setup = setup)
t4=timeit.Timer('mergeSort(lst)', setup = setup)
t5=timeit.Timer('mergeSort(lst1)', setup = setup)
t6=timeit.Timer('mergeSort(lst2)', setup = setup)
t7=timeit.Timer('mergeSort(lst3)', setup = setup)
print('quickSort time:',t.timeit(5))
print('quickSort time:',t1.timeit(5))
print('quickSort time:',t2.timeit(5))
print('quickSort time:',t3.timeit(5))
print('mergeSort time:',t4.timeit(5))
print('mergeSort time:',t5.timeit(5))
print('mergeSort time:',t6.timeit(5))
print('mergeSort time:',t7.timeit(5))
import matplotlib.pyplot as plt
plt.plot([0.0001781684488641163, 0.0020487661749422695, 0.03294748408025583, 0.4855480081895931], 'b-^', label='quicksort')
plt.plot([ 0.00026400392038983256, 0.004112579205450828, 0.06228030308470789, 0.7884880611750431], 'r-*', label= 'mergesort')
plt.xlabel('t, t1, t2, t3, t4, t5, t6, t7')
plt.ylabel('time')
plt.legend()
plt.show()
|
6402ef8bd9c93d30c09627775f457cad12121756 | Niramin/PythonProgrammingTextBookSolutions | /ch7ex6.py | 319 | 4.125 | 4 | def mulist(n):
'''
multiplication tables for 5 multiples for n numbers
'''
l=list()
for i in range(1,n+1):
kl=list()
for k in range(1,6):
kl.append(int(k*i))
l.append(kl)
print(l)
def main():
mulist(5)
if __name__=="__main__":
main() |
3c6b04bed61ac1b17ec3df783d4b94b2e37b8902 | daniel-reich/ubiquitous-fiesta | /g6yjSfTpDkX2STnSX_15.py | 111 | 3.9375 | 4 |
def convert_to_hex(txt):
output=""
for x in txt:
output+=hex(ord(x))[2::] + " "
return output[:-1]
|
e8926b69eb7aa668169a20362b17aaf1c6548c45 | sczhan/wode | /类(class)/str(字符串的简单操作).py | 6,038 | 4.125 | 4 | # + 字符串的连接操作
s1 = "lo"
s2 = "ve"
print(s1+s2)
print("lo"+"ve")
# * 字符串的复制操作
print("#"*20)
# []字符串的索引操作
s3 = "l love you"
print(s3[-1])
print("*"*20)
# [: :] 字符串的切片操作
# [开始索引:结束索引:间隔值] (包含开始,不包含结束)
print(s3[2:6])
print(s3[-8:-4:1])
print(s3[-2:-6:-1])
print("*"*20)
# 切整个字符串
print(s3[:])
print("*"*20)
# 指定开始,不指定结束
print(s3[2:])
print("*"*20)
# 指定结束,不指定开始
print(s3[:6])
print("*"*20)
# 指定开始,不指定结束并给出间隔值
print(s3[2::2])
print("*"*20)
# 指定结束,不指定开始并给出间隔值
print(s3[:6:3])
print("*"*20)
# capitalize() 首字母大写 返回字符串
s = "i love you"
print(s.capitalize())
print("*"*20)
# title() 每个单词的首字母大写 返回字符串
print(s.title())
print("*"*20)
# upper() 将所有字母大写 返回字符串
print(s.upper())
print("*"*20)
# lower() 将所有字母小写 返回字符串
print(s.lower())
print("*"*20)
# swapcase() 大小写互换 返回字符串
s4 = "L Ll"
print(s4.swapcase())
print("*"*20)
# len() 计算字符串长度,不属于字符串的内建函数
print(len(s4))
print("*"*20)
# find() 查找指定字符串,找不到返回-1 第一次找到返回第一次索引值
# index() 查找指定字符串,找不到报错 第一次找到返回第一次索引值
s5 = "akjksdsaaa"
s6 = s5.find("a")
s7 = s5.index("a")
print(s6)
print(s7)
print("#"*20)
s6 = s5.find("w")
# s7 = s5.index("w") 报错
print(s6)
print(s7)
print("#"*20)
s6 = s5.find("a", 2, -1)
s7 = s5.index("a", 8, -1)
print(s6)
print(s7)
print("#"*20)
print("*"*20)
# count() 计算字符串出现的次数
s5 = "akjksdsaaa"
print(s5.count("a"))
print(s5.count("a", 2, 10))
print(s5.count("a", 2, -1)) # -1的a不包括,就会出现2次a
print("*"*20)
# startswith() 检测是否以指定字母开头,返回布尔值
# endswith() 检测是否以指定字母结束,返回布尔值
k = "l like dog"
print(k.startswith("l",-2, -1))
print(k.startswith(("i")))
print(k.startswith(("l")))
print(k.endswith("g"))
print("*"*20)
# isupper() 检测所有字母是否大写字母,返回布尔值
k_upper = "KKK"
k_lower = "ppo"
print(k_upper.isupper())
print(k_lower.isupper())
print("*"*20)
# islower 检测所以字母是否是小写,返回布尔值
print(k_upper.islower())
print(k_lower.islower())
print("*"*20)
# istitle() 检测是否以指定标题显示(每个单词首字母大写),返回布尔值
print(k_upper.istitle())
print(k_lower.istitle())
k2 = "I Like Dog"
print(k2.istitle())
print("*"*20)
# issapce() 检测字符串是否是空字符串 (至少有一个,否则返回False)
k3 = " "
k4 = " l"
print(k3.isspace())
print(k4.isspace())
print("*"*20)
# isalpha() 检测字符串是否是字母组成,返回布尔值
p = "l都dog"
print(p.isalpha())
p1 = "l 都dog"
print(p1.isalpha())
print("*"*20)
# isalnum() 检测字符串是否有字母加数字组成,返回布尔值
p = "l都dog122"
print(p.isalnum())
p1 = "l 都dog112"
print(p1.isalnum())
p2 = "122"
print(p2.isalnum())
p3 = "kk"
print(p3.isalnum())
print("*"*20)
# isdigit()
# isdecimal()
# isnumeric()
"""
isdigit()
True: Unicode数字,byte数字(单字节),全角数字(双字节)
False:汉字数字,罗马数字,小数
Error:无
isdecimal()
True: Unicode数字,全角数字(双字节)
False:罗马数字,汉字数字,小数
Error:byte数字(单字节)isnumeric()
isnumeric()
True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
False:小数
Error;byte数字(单字节)
"""
s5 = "123"
print(s5.isdigit())
print(s5.isdecimal())
print(s5.isnumeric())
print()
print("*"*20)
s8 = b"101100"
print(s8.isdigit())
# print(s8.isdecimal())
# print(s8.isnumeric())
print()
print("*"*20)
s7 = "12.002"
print(s7.isdigit())
print(s7.isdecimal())
print(s7.isnumeric())
print()
print("*"*20)
s8 = "三叁"
print(s8.isdigit())
print(s8.isdecimal())
print(s8.isnumeric())
print()
print("*"*20)
s9 = "Ⅲ"
print(s9.isdigit())
print(s9.isdecimal())
print(s9.isnumeric())
print()
print("*"*20)
# split() 用指定字符切割字符串 返回有字符串组成的列表
u = "日照香炉生紫烟*疑是银河落九天"
u2 = u.split("*")
print(u2)
print("*"*20)
# splitlines() 以换行切割字符串
u4 = "日照香炉生紫烟\n\n疑是银河落九天"
u3 = u4.splitlines()
print(u3)
print("*"*20)
# join() 将列表按照指定字符串连接 返回字符串
list1 = ["日照香炉生紫烟", "疑是银河落九天"]
s10 = "#".join(list1)
print(s10)
print("*"*20)
# ljust() 指定字符串的长度,内容靠左边,不足的位置用指定字符填充,默认空格,返回字符串
s11 = "oopo"
print(len(s11))
print(s11.ljust(7, "."))
print("*"*20)
# center() 指定字符串的长度,内容居中,不足的位置用指定字符填充,默认空格,返回字符串
s12 = "oopop"
print(len(s12))
print(s12.center(8, "."))
print("*"*20)
# rjust() 指定字符串的长度,内容靠右,不足的位置用指定字符填充,默认空格,返回字符串
s12 = "oopop"
print(len(s12))
print(s12.rjust(8, "."))
print("*"*20)
# strip() 去掉左右两边指定字符,默认空格
s13 = " a12 "
print("--" + s13 + "--")
print("--" + s13.strip() + "--")
print("*"*20)
# lstrip() 去掉左侧指定字符,默认空格
s14 = " a12 "
print("--" + s13 + "--")
print("--" + s13.lstrip() + "--")
print(s13.lstrip("a"))
print(s13.lstrip(" a"))
print("*"*20)
# rstrip() 去掉右侧指定字符,默认空格
s14 = " a12 "
print("--" + s13 + "--")
print("--" + s13.rstrip() + "--")
print(s14.rstrip("2"))
print(s14.rstrip("2 "))
print("*"*20)
# zfill() 指定字符串长度,内容靠右边,不足的位置用0填充
s15 = "abc"
print(s15.zfill(7))
print("*"*20)
# maketrans() 生成用于字符串替换的映射表
# translate() 进行字符串替换
s16 = "abcdefg"
s17 = s16.maketrans("c","M")
print(s16)
print(s17)
print(s16.translate(s17))
print("*"*20)
|
eb5a4c8548b3c19137a1e89bbbfeb6e3cc128eb2 | trialnerror404/beginner-projects | /mad lib.py | 736 | 4.59375 | 5 | """
# string concatenation (aka to put strings together)
# suppose we want to create a string that says "susbscribe to an youtuber"
youtuber = "a" # a string variable
# a few ways to do this
print ("subscribe to " + youtuber)
print ("subscribe to {}".format(youtuber))
print (f"subscribe to {youtuber}")
"""
name = input("What is your name?")
adj1 = input("Adjective: ")
verb = input ("Verb: ")
adj2 = input("Adjective: ")
famous_person = input("Famous Person: ")
madlib = f"My name is {name}." \
f"Computer programming is so {adj1}! " \
f"I'm excited to learn more about it all the time." \
f"I love {verb}ing very much!" \
f"Stay hungry and {adj2} like you are {famous_person}"
print (madlib)
|
c5ab7affd22c71fdc4b4396c9e44427c08cf1a6e | Dududenis/pw1-2021-1 | /aula06/01.py | 319 | 4.09375 | 4 | # Listas servem para armazenar um conjunto de dados de mesmo tipo ou nao
notas=[0,0,0] # alternativa: notas = [0] * 3
soma=0
x=0
while x<3:
notas[x]=float(input(f"Nota {x + 1}: "))
soma += notas[x]
x+=1
x=0
while x<3:
print(f"Nota {x + 1}: {notas[x]:6.2f}")
x+=1
print(f"Média: {(soma / x):5.2f}") |
29085ac6e6e31703d9f5ba71600f64e04cece7fd | byungjinku/Python-Base | /11_IF 문/main.py | 1,427 | 3.828125 | 4 | # if 문 : 특정 조건에 만족할 경우 수행되는 조건문
a1 = 10
# if : 만약 ~ 한다면...
if a1 > 5 :
print('a1은 5보다 큽니다')
if a1 < 5 :
print('a1은 5보다 작습니다')
if a1 < 5 :
print('들여쓰기 테스트')
print('이 부분이 수행될까요? 1')
if a1 < 5 :
print('들여쓰기 테스트')
print('이 부분이 수행될까요? 2')
# else : 조건에 만족하지 않을 경우 수행될 부분
# if ~ else : 만약 ~ 한다면... 하고 그렇지 않으면 ... 해라
if a1 > 5 :
print('a1은 5보다 큽니다')
else :
print('a1은 5보다 크지 않습니다')
if a1 > 10 :
print('a1은 10보다 큽니다')
else :
print('a1은 10보다 크지 않습니다')
# 조건이 다수인 경우. 다수의 조건 중에 한군데만
# 수행된다.
if a1 == 1 :
print('a1은 1입니다')
elif a1 == 3 :
print('a1은 3입니다')
elif a1 == 10 :
print('a1은 10입니다')
elif a1 == 20 :
print('a1은 20입니다')
else :
print('a1은 1, 3, 10, 20이 아닙니다다')
# 중첩
a1 = 10
a2 = 20
if a1 == 3 :
if a2 == 5 :
print('a1은 3, a2는 5')
else :
print('a1은 3, a2는 5가 이닙니다')
elif a1 == 10 :
if a2 == 5 :
print('a1은 10, a2는 5')
elif a2 == 20 :
print('a1은 10, a2는 20')
|
d338f61418293de51cca4b019a13b6c18d20aaaa | Aasthaengg/IBMdataset | /Python_codes/p02391/s230482495.py | 134 | 3.875 | 4 | x=raw_input()
list=x.split()
a=int(list[0])
b=int(list[1])
if a<b:
print 'a < b'
elif a>b:
print 'a > b'
elif a==b:
print 'a == b' |
75faade2c33f824bc7c13912cd955cf65d259545 | patriquejarry/Apprendre-coder-avec-Python | /Module_3/3.5.1b.py | 117 | 3.640625 | 4 | t = int(input())
fn1, fn = 0, 1
if t > fn1:
print(fn1)
while t > fn:
print(fn)
fn1, fn = fn, fn + fn1
|
468701c02a16e45423229f90619d1caae60a8dfd | krushnapgosavi/Rock-Paper-Scissor_Game | /rps.py | 1,643 | 3.890625 | 4 | import random
print("Hi , Friends .This is a game of rock-paper-scissor.Which is a popular game.\nSo let's begin the game")
print("Use this shortcuts :\n\t1)Rock-r\n\t2)Paper-p\n\t3)Scissor-s")
c=[]
def gme(x,y):
#x=user y=cpu
if x == 'r' and y == 's':
print('You win!!')
c.append("Win")
if False:
continue
elif x == 'r' and y =='p':
print('You lose!!')
c.append("Lose")
if False:
continue
elif x == 'p' and y == 'r':
print('You win!!')
c.append("Win")
if False:
continue
elif x == 'p' and y == 's':
print('You lose!!')
c.append("Lose")
if False:
continue
elif x == 's' and y == 'r':
print('You lose!!')
c.append("Lose")
if False:
continue
elif x == 's' and y == 'p':
print('You win!!')
c.append("Win")
if False:
continue
elif x==y:
print("It is a tie !!")
c.append("Tie")
else:
print('You choose wrong choice!!')
ch = 1
while ch == 1:
for i in range(1,6):
a = input('Your choice : ')
b = ['r','p','s']
g = b[random.randint(0,2)]
gme(a,g)
print("CPUs'choice : "+ str(g))
d = c.count("Win")
e = c.count("Lose")
f = c.count("Tie")
if d > e:
print("\nYou win " + str(d) + " times\n\nCongratulations !!")
elif d < e:
print("\nOverall You lose !!")
elif d == e:
print("It's a Tie")
ch = int(input('Thanks for playing .Do you want to play again ??(Yes(1),No(0)) : '))
|
24680dd0cc547755a767c168ed3309e9e0386bc2 | pranayknight/WorkedExamples | /TopicsInBasicPython/Giraffe/dicttype.py | 762 | 4.8125 | 5 | dict1={1:"john",2:"bob",3:"bill"} #a dictionary contains keys and values separated by colon within curly brackets
#both keys or values can be of numeric or string data types as desired by user
print(dict1)
print(dict1.items()) #gives all the keys and values of the dictionary
print(dict1.values()) #gives all the values of the dictionary
print(dict1.keys()) #gives all the keys of the dictionary
# we can also use for loops using keys or values to display the keys or values line by line
k=dict1.keys()
for i in k:print(i)
l=dict1.values()
for j in l:print(j)
print(dict1[2]) #printing values from the related keys
del dict1[2] #this way we can delete items from dictionary using the related keys
|
c46257d3f07fa78779e83b034b690be1383a568b | yotkoKanchev/Python-Fundamentals-June-2018 | /02. Lists-and-Dictionaries/5Mixed Phones.py | 340 | 3.75 | 4 | data = input()
dict = {}
while data != "Over":
splited_data = data.split(" : ")
name = splited_data[0]
number = splited_data[1]
if number.isdigit():
dict[name] = number
else:
dict[number] = name
data = input()
for key, value in sorted(dict.items()):
print(f"{key} -> {value}")
|
c9dd911ad7df412cea4ef134b68e9e3fd613b42a | Aasthaengg/IBMdataset | /Python_codes/p03273/s424949097.py | 724 | 3.546875 | 4 | h, w = (int(i) for i in input().split())
list_a = [input() for s in range(0, h)]
list_tmp = []
for i in range(0, h):
for j in range(0, w):
if list_a[i][j] == '#':
list_tmp.append(list(list_a[i]))
break
# 転置... https://note.nkmk.me/python-list-transpose/ 参照
list_tmp_t = [list(x) for x in zip(*list_tmp)]
list_tmp2 = []
for i in range(0, len(list_tmp_t)):
for j in range(0, len(list_tmp_t[i])):
if list_tmp_t[i][j] == '#':
list_tmp2.append(list(list_tmp_t[i]))
break
# 転置... https://note.nkmk.me/python-list-transpose/ 参照
list_ans = [list(x) for x in zip(*list_tmp2)]
for i in range(0, len(list_ans)):
print("".join(list_ans[i])) |
98b5d2f8925aad7f853420a2261030621736ff65 | zhangzongyan/python20180319 | /day0c/w1.py | 614 | 3.515625 | 4 |
'这是一个装饰器(deractor)'
# 函数作为另一个函数的返回值(高阶函数)
def lazy_fun():
def newnow():
print("2018-4-4")
return newnow
import functools
# 装饰器:在函数执行的过程中为函数加功能
def log(fun): # "闭包":内部函数可以保存住外部函数的参数变量
@functools.wraps(fun) # 将fun函数的属性赋值给wrapper 包括__name__
def wrapper(*args, **kw):
print("%s is called" % fun.__name__)
return fun(*args, **kw)
return wrapper
@log # now = log(now)
def now():
print("2018-4-4")
now()
print("%s" % now.__name__)
#print(lazy_fun()())
|
e923ea8dbde6de81d37b2c72751585b95c4f7d82 | aishwarya-g-thoughtworks/Iris-Flower | /rfc_iris.py | 1,910 | 3.59375 | 4 | # Random Forest classifier for Iris Dataset
import matplotlib.pyplot as plt
# Importing the libraries
import pandas as pd
import seaborn as sns
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
# Loading the iris dataset
iris_data = load_iris()
print("dir of iris_data:", dir(iris_data))
print("target names:", iris_data.target_names[:5])
# Creating a dataframe to view the data
data = pd.DataFrame(iris_data.data, columns=iris_data.feature_names)
print("Viewing head of dataframe:\n", data.head())
# Creating a correlation matrix between all the features
corr_matrix = data.corr()
plt.figure(figsize=(10, 8))
sns.heatmap(corr_matrix, annot=True, cmap='cubehelix')
plt.title("correlation matrix")
plt.show()
# Splitting the dataset into training set and testing set
X_train, X_test, y_train, y_test = train_test_split(iris_data.data, iris_data.target, test_size=0.2, random_state=1)
print("length of X_train:", len(X_train))
print("length of X_test:", len(X_test))
# Creating the Random forest classifier object
model = RandomForestClassifier(n_estimators=3)
# Training the model with our training dataset
model.fit(X_train, y_train)
# Checking the accuracy of our model
print("Model score:", model.score(X_test, y_test))
# Predicting the outcome from our model using the testing dataset
predicted = model.predict(X_test)
# Let's build a confusion matrix
cm = confusion_matrix(y_test, predicted)
plt.figure(figsize=(10, 8))
sns.heatmap(cm, annot=True, cmap='GnBu')
plt.xlabel('Predicted')
plt.ylabel('Truth')
plt.title("confusion matrix")
plt.show()
# Some metrics about the mode
print("CLASSIFICATION REPORT CHART FOR RANDOM FOREST CLASSIFIER: ", "\n\n", classification_report(y_test, predicted),
"\n")
|
7ca15d708771c51abfe7e69c5f4640d991127e39 | RameshTarak/python | /duplcate.py | 148 | 3.65625 | 4 | #write a program to remove duplicates from list
names=["abdul","anil","abdul","mohammed","abdul","sunil","abdul","mohammed"]
print(len(names))
|
e0694f1a728ce3caca8fd688d5aa900a75d60399 | ragvri/python-snippets | /tkinter_snippets/eight.py | 804 | 4.125 | 4 | #creating drop down menu
from tkinter import *
def doNothing():
print("Okay")
root=Tk()
menu= Menu(root) #crete a menu , tells where we want to create a menu
root.config(menu=menu) #tells tkinter that a is Menu , it already has knowledge of menus
submenu= Menu(menu) # this menu is going inside the main menu
#implement the drop down functionality
menu.add_cascade(label="file",menu=submenu) # button name, submenu
submenu.add_command(label="New project" , command=doNothing)
submenu.add_command(label="New", command=doNothing)
submenu.add_separator()
#create a separator for different sections
submenu.add_command(label="Exit", command=doNothing)
secondsubmenu=Menu(menu)
menu.add_cascade(label="edit",menu=secondsubmenu)
submenu.add_command(label="Redo" , command=doNothing)
root.mainloop() |
38bc2e330cebb263ea7d6cb17fa2f286008ca8fc | narimiran/AdventOfCode2017 | /python/day03.py | 1,071 | 3.921875 | 4 | PUZZLE = 368078
def find_manhattan(number):
spiral_corner = int(number ** 0.5)
remaining_steps = number % spiral_corner**2
side_length = spiral_corner + 1
towards_middle = remaining_steps % (side_length // 2)
return side_length - towards_middle
first = find_manhattan(PUZZLE)
grid = {(0, 0): 1}
neighbours = lambda x, y: [(x+1, y), (x, y+1), (x+1, y+1), (x-1, y-1),
(x-1, y), (x, y-1), (x+1, y-1), (x-1, y+1)]
def set_value(point):
grid[point] = sum(grid.get(neighbour, 0) for neighbour in neighbours(*point))
return grid[point]
def iterate_through_spiral(ring=0):
while True:
ring += 1
for y in range(-ring + 1, ring): yield set_value((ring, y))
for x in range(ring, -ring, -1): yield set_value((x, ring))
for y in range(ring, -ring, -1): yield set_value((-ring, y))
for x in range(-ring, ring + 1): yield set_value((x, -ring))
for value in iterate_through_spiral():
if value > PUZZLE:
second = value
break
print(first)
print(second)
|
7cea3969ca822d938f23af29e32035a3e8588c98 | ingiestein/dndme | /dndme/gametime.py | 11,549 | 3.859375 | 4 | import math
from collections import namedtuple
Date = namedtuple("Date", "day month year")
Time = namedtuple("Time", "hour minute")
class Clock:
def __init__(self, hours_in_day=24, minutes_in_hour=60, hour=0, minute=0):
self.hours_in_day = hours_in_day
self.minutes_in_hour = minutes_in_hour
self.hour = hour
self.minute = minute
def __str__(self):
return f"{self.hour:02}:{self.minute:02}"
def adjust_time(self, hours=0, minutes=0):
new_minute = (self.minute + minutes) % self.minutes_in_hour
new_hour = (
(self.hour + hours) + ((self.minute + minutes) // self.minutes_in_hour)
) % self.hours_in_day
day_delta = (
(self.hour + hours) + ((self.minute + minutes) // self.minutes_in_hour)
) // self.hours_in_day
orig_time = (self.hour, self.minute)
new_time = (new_hour, new_minute)
self.hour = new_hour
self.minute = new_minute
return day_delta
class Calendar:
def __init__(self, cal_data):
self.cal_data = cal_data
self.date = Date(
cal_data["default_day"], cal_data["default_month"], cal_data["default_year"]
)
def __str__(self):
date = self.date
if self.days_in_month(date.month, date.year) > 1:
return f"{date.day} {date.month} {date.year}"
return f"{date.month} {date.year}"
def days_in_year(self, year):
days = 0
for month in self.cal_data["months"].values():
days += (
month.get("leap_year_days", month["days"])
if self.is_leap_year(year)
else month["days"]
)
return days
def days_in_month(self, month, year):
month = month.lower()
days = self.cal_data["months"][month]["days"]
if self.is_leap_year(year):
return self.cal_data["months"][month].get("leap_year_days", days)
return days
def is_leap_year(self, year):
leap_year_rule = self.cal_data.get("leap_year_rule")
if not leap_year_rule:
return False
# TODO: check validity of leap_year_rule because SECURITY
return eval(leap_year_rule.replace("year", str(year)))
def set_date(self, date):
if not self._date_is_valid(date):
return "lol nope" # TODO: raise an exception here
self.date = date
def _date_is_valid(self, date):
if date.month.lower() not in self.cal_data["months"]:
return False
elif date.day < 1 or date.day > self.days_in_month(date.month, date.year):
return False
return True
def adjust_date(self, days):
new_date = self.date_from_date_and_offset(self.date, days)
self.date = new_date
def date_from_date_and_offset(self, date, days):
month_keys = list(self.cal_data["months"].keys())
day, month, year = date
if days > 0:
while (day + days) > self.days_in_month(month, year):
# bleed off days to the end of the month
days -= self.days_in_month(month, year) - day
# move to the next month
i = month_keys.index(month.lower())
# advancing the month would roll over to next year
if i + 1 == len(month_keys):
i = -1
year += 1
new_month = self.cal_data["months"][month_keys[i + 1]]["name"]
month = new_month
day = 0
day += days
elif days < 0:
days = abs(days)
while (day - days) < 1:
# bleed off days to the beginning of the month
days -= day
# move to the previous month
i = month_keys.index(month.lower())
# going back a month would roll over to the prior year
if i - 1 < 0:
i = 0
year -= 1
new_month = self.cal_data["months"][month_keys[i - 1]]["name"]
month = new_month
day = self.days_in_month(month, year)
day -= days
new_date = Date(day, month, year)
return new_date
def days_since_date(self, date_then, date_now):
days_since = 0
if date_now.year == date_then.year:
days_since += self.day_of_year(date_now) - self.day_of_year(date_then)
elif date_now.year > date_then.year:
# get the days until the end of the year
days_since += self.days_in_year(date_then.year) - self.day_of_year(
date_then
)
year_diff = date_now.year - date_then.year
# get days for intervening years
if year_diff > 1:
for i in range(1, year_diff):
days_since += self.days_in_year(date_then.year + i)
# get elapsed days of current year
days_since += self.day_of_year(date_now)
else:
# "now" is in an earlier year so invert how we count...
# get the days until the end of the year
days_since -= self.days_in_year(date_now.year) - self.day_of_year(date_now)
year_diff = date_then.year - date_now.year
# get days for intervening years
if year_diff > 1:
for i in range(1, year_diff):
days_since -= self.days_in_year(date_now.year + i)
# get elapsed days of current year
days_since -= self.day_of_year(date_then)
return days_since
def day_of_year(self, date):
if not self._date_is_valid(date):
return "lol nope" # TODO: raise an exception here
day_of_year = 0
month = date.month.lower()
for month_key in self.cal_data["months"]:
if month_key == month:
day_of_year += date.day
break
else:
day_of_year += self.days_in_month(month_key, date.year)
return day_of_year
def seasonal_dates_in_month(self, month):
return [
x
for x in self.cal_data["seasons"].values()
if x["month"].lower() == month.lower()
]
# This class is based largely on the awesome Astral library:
# https://github.com/sffjunkie/astral/
# which was great at Earth but not abstract enough for fantasy settings.
class Almanac:
depression_civil = -6
depression_nautical = -12
depression_astronomical = -18
rising = 1
setting = -1
def __init__(self, calendar):
self.calendar = calendar
self.minutes_in_hour = calendar.cal_data["minutes_in_hour"]
self.hours_in_day = calendar.cal_data["hours_in_day"]
self.solar_days_in_year = calendar.cal_data["solar_days_in_year"]
self.axial_tilt = calendar.cal_data["axial_tilt"]
def dawn(self, date, latitude, depression=0):
if not depression:
depression = self.depression_civil
try:
return self.calc_time(depression, self.rising, date, latitude)
except ValueError:
# no "dawn" at this latitude on this date
return None
def sunrise(self, date, latitude):
try:
return self.calc_time(-0.833, self.rising, date, latitude)
except ValueError:
# no sunrise at this latitude on this date
return None
def sunset(self, date, latitude):
try:
return self.calc_time(-0.833, self.setting, date, latitude)
except ValueError:
# no sunset at this latitude on this date
return None
def dusk(self, date, latitude, depression=0):
if not depression:
depression = self.depression_civil
try:
return self.calc_time(depression, self.setting, date, latitude)
except ValueError:
# no "dusk" at this latitude on this date
return None
def calc_time(self, depression, direction, date, latitude):
hour_angle = direction * self.hour_angle(depression, date, latitude)
delta = -hour_angle # longitude would factor in here if we cared
time_diff = 4 * delta
noon_minutes = (self.hours_in_day / 2) * self.minutes_in_hour
time_utc = noon_minutes + time_diff # - eqtime
hour = int(time_utc // self.minutes_in_hour)
minute = int(time_utc % self.minutes_in_hour)
if hour > self.hours_in_day - 1:
hour -= self.hours_in_day
new_date = self.calendar.date_from_date_and_offset(date, 1)
elif hour < 0:
hour += self.hours_in_day
new_date = self.calendar.date_from_date_and_offset(date, -1)
else:
new_date = date
return Time(hour, minute), new_date
def hour_angle(self, depression, date, latitude):
declination = self.solar_declination(date)
# Gotta be in radians for Python's math functions
alt = math.radians(depression) # altitude of center of solar disc
latitude = math.radians(latitude)
declination = math.radians(declination)
cos_hour_angle = (
math.sin(alt) - math.sin(latitude) * math.sin(declination)
) / (math.cos(latitude) * math.cos(declination))
hour_angle = math.degrees(math.acos(cos_hour_angle))
return hour_angle
def solar_declination(self, date):
# Get the solar declination in degrees...
# Figure out days since the previous winter solstice
# TODO: this section should be extracted into the Calendar?
ws = self.calendar.cal_data["seasons"]["winter_solstice"]
ws_year = (
date.year
if date.month == ws["month"] and date.day >= ws["day"]
else date.year - 1
)
ws_date = Date(ws["day"], ws["month"].lower(), ws_year)
days_since_ws = self.calendar.days_since_date(ws_date, date)
# Figure out how much rotation has happened since the winter solstice
deg_per_day = 360 / self.solar_days_in_year
rotation = days_since_ws * deg_per_day
# Calculate the declination
declination = -self.axial_tilt * math.cos(math.radians(rotation))
return declination
def moon_phase(self, moon_key, date):
moon_data = self.calendar.cal_data["moons"][moon_key]
ref_day, ref_month, ref_year = moon_data["full_on"].split()
ref_date = Date(int(ref_day), ref_month, int(ref_year))
day_diff = self.calendar.days_since_date(ref_date, date)
period = moon_data["period"]
period_percentage = round((day_diff / period) - int(day_diff / period), 3)
phases = {
(0.99, 0.02): "full",
(0.02, 0.218): "waning gibbous",
(0.218, 0.25): "third quarter",
(0.25, 0.467): "waning crescent",
(0.467, 0.50): "new",
(0.50, 0.72): "waxing crescent",
(0.72, 0.75): "first quarter",
(0.75, 0.99): "waxing gibbous",
}
phase = None
for (p_start, p_end), p in phases.items():
if p_start > p_end:
if period_percentage >= p_start or period_percentage < p_end:
phase = p
break
elif p_start <= period_percentage < p_end:
phase = p
break
return phase, period_percentage
|
b5100a15ec90079d3e63358e4e3d15b92d2ddef3 | sketchyfish/exercises | /challenge4-easy.py | 529 | 3.59375 | 4 | #!/usr/bin/python
"""
You're challenge for today is to create a random password generator!
For extra credit, allow the user to specify the amount of passwords to generate.
For even more extra credit, allow the user to specify the length of the strings he wants to generate!
"""
import random
c = int(raw_input("Number of characters? "))
for each_item in range(int(raw_input("How many passwords would you like to make?"))):
print ''.join(random.sample("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"*k,k)) |
a946f65417cbb79750a67142f094bc5982173f42 | JasonXJ/algorithms | /kmp.py | 4,345 | 3.671875 | 4 | # An implementation of the KMP string matching algorithm.
# NOTE `test_random` might not pass in python2 environment.
def kmp_transition_table(pattern):
# ``table[x]`` is "the position of the last character of the longest
# proper suffix" of "the prefix of the pattern whose last character
# located at x". More formally, ``pattern[:table[x]+1]`` is the longest
# proper suffix of string ``pattern[:x+1]``.
table = [-1] * len(pattern)
k = -1
for i in range(1, len(pattern)):
c = pattern[i]
# Upon here, we have loop invariant ``k == table[i-1]``.
while k > -1 and pattern[k+1] != c:
k = table[k]
if pattern[k+1] == c:
k += 1
table[i] = k
return table
def kmp(text, pattern):
if text == '' or pattern == '' or len(pattern) > len(text):
return []
if len(pattern) == len(text):
return [0] if pattern == text else []
transition_table = kmp_transition_table(pattern)
match = -1
rv = []
for i, x in enumerate(text):
# Upon here, ``pattern[:match+1]`` matches ``text[i-(match+1):i]``. We
# can also say that ``pattern[match]`` is the last character of the
# current matching pattern prefix.
while match > -1 and pattern[match + 1] != x:
match = transition_table[match]
if pattern[match + 1] == x:
match += 1
if match == len(pattern) - 1:
# An result found
rv.append(i+1-len(pattern))
match = transition_table[match]
return rv
def test():
assert kmp('', '') == []
assert kmp('acacacacac', 'acac') == [0, 2, 4, 6]
assert kmp('bacbababaabcbaba', 'aba') == [4, 6, 13]
assert kmp('bacbababaabcbaba', 'ababaca') == []
assert kmp('bacbababaabcbaba', 'bac') == [0]
assert kmp('bacbababaabcbabac', 'bac') == [0, 14]
assert kmp('bacbababaabcbabac', 'bak') == []
assert kmp('bacbababaabcbabac', 'a') == [1,4,6,8,9,13,15]
assert kmp('bacbababaabcbabac', 'k') == []
assert kmp('bac', 'bacbababaabcbabac') == []
assert kmp('bac', 'bac') == [0]
assert kmp('bac', 'bdc') == []
for pattern_length in range(1, 20):
assert kmp('a'*20, 'a'*pattern_length) == list(range(20-pattern_length+1))
for pattern_length in range(1, 20):
assert kmp('ac'*20, 'ac'*pattern_length) == list(range(0, 40-2*(pattern_length-1), 2))
for pattern_length in range(1, 20):
assert kmp('abc'*20, 'abc'*pattern_length) == list(range(0, 60-3*(pattern_length-1), 3))
def test_random():
import random
import string
from random import choice
from io import StringIO
random.seed(0)
def generate_test_case(text_length, pattern_length, characters, insert_pattern_prob):
pattern_io = StringIO()
for _ in range(pattern_length):
pattern_io.write(random.choice(characters))
pattern = pattern_io.getvalue()
text_current_length = 0
text_io = StringIO()
while text_current_length < text_length:
if random.random() < insert_pattern_prob:
text_io.write(pattern)
text_current_length += len(pattern)
else:
text_io.write(random.choice(characters))
text_current_length += 1
text = text_io.getvalue()
# Generate result using naive algorithm
matches = []
for i in range(len(text)-len(pattern)+1):
if text[i:i+len(pattern)] == pattern:
matches.append(i)
return text, pattern, matches
def check(text_length, pattern_length, characters=string.printable, insert_pattern_prob=0.1):
text, pattern, matches = generate_test_case(text_length,
pattern_length, characters,
insert_pattern_prob)
assert kmp(text, pattern) == matches
for _ in range(500):
check(20, 2, string.digits)
check(1000, 10, string.printable)
check(1000, 10, string.printable, 0.5)
check(10000, 100, string.printable)
if __name__ == "__main__":
print(kmp_transition_table('acac'))
print(kmp('acacacac', 'acac'))
print(kmp_transition_table('aaaa'))
print(kmp('aaaaa', 'aaa'))
|
c7f350f6777f244d39e2139c65f858f86080e500 | yannickkiki/programming-training | /Leetcode/python3/3_longuest_substring.py | 585 | 3.625 | 4 | def lengthOfLongestSubstring(s):
result, current_substring_size, last_cut_idx = 0, 0, 0
char_last_idx = dict()
for idx, c in enumerate(s):
c_last_idx = char_last_idx.get(c, -1)
if c_last_idx == -1:
current_substring_size += 1
else:
last_cut_idx = max(c_last_idx, last_cut_idx)
current_substring_size = idx-last_cut_idx
char_last_idx[c] = idx
result = max(result, current_substring_size)
return result
if __name__ == "__main__":
assert lengthOfLongestSubstring("abbaabcabba") == 3
|
4ebf29fb90ffbf313308a21bf2584543995fcdeb | tmcclintock/MonopolyMath | /monopolymath/monopolyroller.py | 3,718 | 4.03125 | 4 | """
The rules for moving a monopoly player via rolling.
This allows for simulating the roll and action matrices.
"""
import numpy.random as rand
class MonopolyRollMover(object):
"""
An object for moving monopoly players via rolling.
Args:
diceroller (:obj: DiceRoller): object for rolling dice
"""
def __init__(self, diceroller):
self.diceroller = diceroller
#Keep track of the number of consecutive doubles rolled
self.N_doubles = 0
self.in_jail = False
self.time_in_jail = 0
def update_position(self, current_position: int,
spaces: List[MonopolySpace],
number_of_spaces=40) -> int:
#The variable to be output
new_position = None
#Roll the dice roller
roll, dice_rolls, doubles = self.diceroller.roll()
#Rule - getting out of jail on doubles or time
if self.in_jail:
self.time_in_jail += 1
#Roll doubles and you are out now
if doubles:
self.N_doubles += 1
self.in_jail = False
self.time_in_jail = 0
new_position = (10 + roll) % number_of_spaces
#Out on time and you are now just visiting
if (self.time_in_jail >= 3):
self.N_doubles = 0
self.in_jail = False
self.time_in_jail = 0
new_position = 10
else:
new_position = 30 #still in jail
else:
new_position = (current_position + roll) % number_of_spaces
#Determine rules about the new position
#Rule - doubles
if not doubles:
self.N_doubles = 0
else:
self.N_doubles += 1
if self.N_doubles == 3:
new_position = 30 #Go to jail!
self.in_jail = True
#Rule - chance cards
if new_position in [7, 22, 36]:
draw = rand.randint(0, 16)
if draw == 0: #Proceed to Go
new_position = 0
elif draw == 1: #Illinois Ave
new_position = 24
elif draw == 2: #St. Charles Pl.
new_position = 11
elif draw == 3: #Nearest Utility
if new_position == 7:
new_position = 12
else:
new_position = 28
elif draw == 4: #Nearest Railroad
if new_position == 7:
new_position = 5
elif new_position == 22:
new_position = 25
else:
new_position = 35
elif draw == 7: #Back 3 spaces
new_position -= 3
elif draw == 8: #Go to jail
new_position = 30
elif draw == 11: #Reading Railroad
new_position = 5
elif draw == 12: #Boardwalk
new_position = 39
#else do nothing
#Rule - community chest cards
if new_position in [2, 17, 33]:
draw = rand.randint(0, 16)
if draw == 0: #Proceed to Go
new_position = 0
elif draw == 5: #Go to Jail
new_position = 30
#else do nothing
#Rule - going into jail
if new_position == 30:
self.in_jail = True
self.N_doubles = 0
if (new_position < 0) or (new_position > 40):
raise Exception("Something went wrong. "+\
"Roller position = %d."%new_position)
#Return the new position
return new_position
|
ed8e35fa3b7e57c7b91f683bd896d7753f28d230 | VieetBubbles/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 142 | 3.703125 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
sum = 0
set_list = set(my_list)
for _ in set_list:
sum += _
return sum
|
4687224d00852e27f12e32c3168677c98a5912b2 | ucsd-cse-spis-2020/-spis20-lab04-Sidharth-Theodore | /recursive_tree.py | 1,676 | 3.78125 | 4 | import turtle
t = turtle.Turtle()
turtle.screensize(10000,10000)
t.setheading(90)
t.speed(0)
t.pd()
t.hideturtle()
def tree(trunk_length, height):
"""if(height == -1):
t.setposition(0,0)
t.setheading(90)
t.backward()"""
if height == 0:
return
else:
#making a Y
t.width(1)
angle = t.heading()
t.pu()
t.backward(trunk_length)
t.pd()
t.forward(trunk_length)
t.left(40)
t.forward(trunk_length)
tree(trunk_length/1.5, height-1)
t.backward(trunk_length)
t.right(80)
t.forward(trunk_length)
tree(trunk_length/1.5, height-1)
t.backward(trunk_length)
t.setheading(angle)
'''def treeAngle(trunk_length, height, angle = 0):
if height == 0:
return
else:
#making a v
angleX = t.heading()
t.left(angle)
t.forward(trunk_length)
treeAngle(trunk_length//2, height-1,angle//2+30)
t.backward(trunk_length)
t.right(2*angle)
t.forward(trunk_length)
treeAngle(trunk_length//2, height-1,angle//2+30)
t.backward(trunk_length)
t.setheading(angleX)
def treeHeight(trunk_length, height, initHeight = 0):
if height == 0:
return
else:
#making a v
angle = t.heading()
t.left(30)
t.forward(trunk_length)
tree(trunk_length//2, height-1, initHeight+1)
t.backward(trunk_length)
t.right(90)
t.forward(trunk_length)
tree(trunk_length//2, height-1 , initHeight+1)
t.backward(trunk_length)
t.setheading(angle)
'''
|
9245121ae48b7453e4281481c0e4d6e29ad3cf56 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4000/codes/1798_2564.py | 308 | 3.5625 | 4 | from numpy import*
cont = zeros(3, dtype=int)
gm = array(eval(input("Gols marcados: ")))
gs = array(eval(input("Gols sofridos: ")))
for i in range(size(gm)):
if(gm[i] > gs[i]):
cont[0] = cont[0] + 1
elif(gm[i] == gs[i]):
cont[1] = cont[1] + 1
elif(gm[i] < gs[i]):
cont[2] = cont[2]+1
print(cont)
|
3e20833c3dd45c1ce59cf7ab61462ae087e9831f | IlPakoZ/Uniroma1-Informatica | /Fondamenti di Programmazione 1° semestre/Programmi Python/Lezione5/perallenarsi1.py | 554 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 13 21:18:16 2019
@author: xJ0T3
"""
def check_date(g,m,a):
if (m < 1 or m > 12):
return False
if (m<8 and m%2 == 1) or (m>7 and m%2 == 0):
if(g>31):
return False
else:
if(m == 2):
if(a%4 == 0):
if(g>29):
return False
else:
if(g>28):
return False
else:
if(g>30):
return False
return True
|
dddb2c1036add043b059cf71ec571566a3786918 | aeberspaecher/simple_cache | /simple_cache/simple_cache.py | 5,387 | 3.890625 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
"""Simple caching functionality using decorated functions.
Cached values are stored in a dicitonary. The keys are generated by a callable
given to the decorator. This can e.g. be used to cache expensive calculations
that depend on an object's state. In that case, the key generating-function
needs to be made aware of all relevant state attributes.
"""
# TODO: testing concept?
# TODO: for caches, rather use __getitem__() etc?
# this could allow to make all interface-specifics disappear and could finally
# allow to use a simple dict as a cache.
from functools import wraps
cache_registry = []
class NotInCacheError(Exception):
"""Exception to be thrown when a key that is not present in cache is read.
"""
pass
class Cache(object):
"""Base class for caches.
"""
def get(self, key):
"""Get a cached value from key.
Parameters
----------
key : string
Raises
------
NotInCacheError
In case key does not exist in cache.
"""
raise NotImplementedError()
def set(self, key, value):
"""Set a key/value pair in cache.
Parameters
----------
key : string
value : object
"""
raise NotImplementedError()
def clear(self):
"""Clean out all cached items.
"""
raise NotImplementedError()
@property
def keys(self):
"""Keys stored.
"""
raise NotImplementedError()
# TODO: is it reasonable to add a keys member, a delete() function?
class FiniteCache(Cache):
"""Implements a cache that can only hold a given number of elements.
Uses a dict, but watches out for the number of keys in dict. If the maximum
size is reached, the oldest key/value pair needs to go. This can be used
for computations that return large objects.
"""
def __init__(self, max_size):
"""Create a cacher that behaves much like a dictionary with a finite
number of entries.
Parameters
----------
max_size : int
Maximum number of entries.
"""
self.max_size = max_size
self.cache = {} # dicts are not ordered, so...
self.keys_in_order = [] # lists are ordered!
def get(self, key):
"""Get a cached value from key.
Parameters
----------
key : string
Raises
------
NotInCacheError
In case key does not exist in cache.
"""
try:
cached_val = self.cache[key]
return cached_val
except KeyError:
raise NotInCacheError
def set(self, key, value):
"""Set a key/value pair in cache.
Parameters
----------
key : string
value : object
"""
self.keys_in_order.append(key)
self.cache[key] = value
# if cache has grown too big (i.e. has too many cached items): clean
# out oldest cached item
if len(self.cache) > self.max_size:
oldest_key = self.keys_in_order[0] # first item is oldest key
self.cache.pop(oldest_key)
self.keys_in_order.pop(0)
def clear(self):
"""Clean out all cached items.
"""
self.cache.clear()
for key in self.keys_in_order:
del key
self.keys_in_order = []
@property
def keys(self):
return self.cache.keys()
def cacher(key_template=None, get_cacher=lambda: FiniteCache(5)):
"""Decorator that wraps a class member function with caching capabilities.
Parameters
----------
key_template : string
A string that describes the class' state at runtime. The string needs
to be such that .format() could be called on it.
get_cache : callable, optional
A callable to return an object with get(), set() and clear() methods.
Default to `lambda: FiniteCache(5)`. The callable approach is used to
ensure caches will be local to each decorated function.
"""
if key_template is None:
raise ValueError("A key_template must be given")
cache = get_cacher()
cache_registry.append(cache)
# TODO: can we always do that? what a the requirements for this to work?
# is a common interface enough?
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
# bare-metal convert all positional arguments to keyword arguments:
# this allows to refer to positional arguments by name (as if they
# were keyword arguments). this is more convenient for the user in
# key creation.
kwargs.update(dict(zip(func.func_code.co_varnames, args)))
key = key_template.format(**kwargs) # evaluate key
try:
ret = cache.get(key)
except NotInCacheError:
ret = func(**kwargs)
# TODO: call like that or use previously generated copy of kwargs together with args? are there any edge cases that do not work like that?
cache.set(key, ret)
return ret
return wrapper
return decorate
def clear_all_registered_caches():
"""Clear all caches registered.
"""
for cache in cache_registry:
cache.clear()
|
9542aeafbb336724537d31c6b8ece42a963555ba | shahed-swe/python_practise | /condition.py | 2,424 | 4.28125 | 4 | #if statement
#syntax of if statement
#if <condition>:
#statement
#example
if int(input("Enter your age: ")) >= 14:
print("You are above 14")
# or
age = int(input("Enter another age: "))
if age >= 18:
print(f"You are above {14}.")
#pass statement
#this use to pass the condition in if or else statement
#example
age = int(input("Enter your age: "))
if age == 18:
pass
elif age > 18:
print("You are above 18")
else:
print("You are under 18")
#using random number
import random
print(random.randint(1,10))
# syntax of random package using
#random.randint(starting point,endpoint)
#exercise with nested if else
import random
winner_number = random.randint(10,20)
guess_number = int(input("Enter the number you have guessed: "))
if guess_number == winner_number:
print("YOU WIN!!!")
else:
if guess_number < winner_number:
print("too low!!")
else:
print("too high!!")
#and, or operator in python
user_name = "shahed"
pass_word = "32100505"
if (input("Enter your user name:") == user_name) and (input("Enter your password:") == pass_word):
print("You are now logged in!!!")
else:
print("Your input is wrong!!!")
#that was for (and) operator
#now let's see (or) operator
if (input("Enter your user name:") == user_name or (input("Enter your password:") == pass_word)):
print("Your are now logged in!!!")
else:
print("Your input is wrong!!!")
#exercise of (and,or) operator
user_name = input("Enter your user name:")
user_age = int(input("Enter your age:"))
if (user_name[0] == 'A' or user_name[0] == 'a') and user_age >= 10:
print("You can watch coco movie!!")
else:
print("Sorry, you can't watch coco movie!!")
age = int(input("Enter your age:"))
if age >= 1 and age <=3:
print("Your ticket price is tottaly free!!")
elif age >= 4 and age <= 10:
print("Your ticket price is 150 tk only!!")
elif age >= 11 and age <= 60:
print("Your ticket price is 250 tk only!!")
elif age > 60:
print("Your ticket price is 200 tk only!!")
else:
pass
#in keyword working with in
#in keyword search for a character in string like
user_name = "Shahed Talukder"
char = input()
if char in user_name:
print("{} is in {}".format(char,user_name))
#check empty or not(important)
name = input("Enter you name here:")
if name: #True if string is not empty
print("Your name is: {}".format(name))
else:
print("You did't enter your name yet!!!")
|
044fcabdbb871fa37561680e492244c386c0d3f0 | Felix-xilef/Curso-de-Python | /Desafios/Desafio28.py | 297 | 3.796875 | 4 | from os import system
from random import randint
numero = randint(0, 5)
tentativa = int(input('\n\tAdivinhe um número de 0 a 5: '))
if numero == tentativa:
print('\n\tParabéns! Você Acertou!\n')
else:
print('\n\tVocê Errou!\n\tNúmero sorteado: {}\n'.format(numero))
system('pause')
|
c9620627368b67731fc56b08c3d2df4e36fe7f92 | SWE2020/monopoly | /die.py | 521 | 3.609375 | 4 | from random import randrange
import pygame
class Die:
#initializes first roll to [1,1]
def __init__(self):
self.numberRolls = [1,1]
self.double_counter = 0
#randomly selects two numbers between 1-6 to simulate two die rolling and returns the number
def roll(self):
self.numberRolls[0] = randrange(1,6,1)
self.numberRolls[1] = randrange(1,6,1)
if self.numberRolls[0] == self.numberRolls[1]:
self.double_counter += 1
return self.numberRolls
|
e9d04d51f14d2440cfbadc91eec45fde0908d0f5 | AndrewMicallef/utilitybelt | /time.py | 416 | 3.5625 | 4 | import datetime as dt
import numpy as np
def _timedelta(t0, t1):
"""
uses dummy dates to perform a time
delta operation on two times,
returns number of seconds in interval
"""
dummydate = dt.date(2000,1,1)
try:
t0 = dt.datetime.combine(dummydate,t0)
t1 = dt.datetime.combine(dummydate,t1)
return (t0 - t1).total_seconds()
except:
return np.nan |
fc1f0e984dbc203852d921a6065af86139f3fb52 | rafaelperazzo/programacao-web | /moodledata/vpl_data/148/usersdata/271/108779/submittedfiles/testes.py | 363 | 3.921875 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
a = float(input('Digite o valor de a : '))
b = float(input('Digite o valor de b : '))
precisão
#ARIT
def arit (a,b) :
while (a>b) and (a-b>precisão) :
a1 = (1/2) * (a+b)
b1 = (a*b)**(0.5)
a = a1
b = b1
arit = a1
return(arit)
print(arit(a,b))
|
61fca475e214061ab6f7c4ee86f34f2982458827 | lechodiman/IIC2233-Learning-Stuff | /EDD/defaultdicts.py | 353 | 3.53125 | 4 | from collections import defaultdict
class Integer:
def __init__(self, num=0):
self.num = num
def __call__(self):
return self.num
def __str__(self):
return str(self.num)
dos = Integer(2)
# argument must be callable, eg, int, str, dos, etc
d = defaultdict(list)
if __name__ == '__main__':
print(d['holi'])
|
eb2fb4346ad4597ca6f8f62e5a558302bf5d6159 | zhuiyun/python-2 | /propertyTest2.py | 241 | 3.640625 | 4 | class Money(object):
def __init__(self):
self.__money=100
@property
def money(self):
return self.__money
@money.setter
def money(self,num):
self.__money=num
m=Money()
m.money=1000
print(m.money) |
03bd85ae40d2254e38e9671ca680dd644e3e82a5 | pangfeiyo/PythonLearn | /甲鱼python/课程代码/第11讲/列表(数组)2.py | 1,106 | 4.34375 | 4 | #讲列表中的两个元素调换位置
member = ['小甲鱼','牡丹','水仙','花']
print(member)
temp = member[0]
member[0] = member[1]
member[1] = temp
print(member)
#删除元素 .remove
member.remove('牡丹')
print(member)
member.remove(member[1])
print(member)
#删除元素 del语句
del member[1]
print('del:',member)
del member[0]
print('del:',member)
#删除元素 pop() 删除最后一个元素
#也可以pop(1)
print()
print("pop")
member = ['小甲鱼','牡丹','水仙','花']
print(member)
print(member.pop())
print(member)
print(),print('分片')
#列表分片(切片)
#一次获取多个元素
member = ['小甲鱼','牡丹','水仙','花']
print(member)
print(member[1:3]) #从1开始,到3之前,不包换3 不会原列表造成改变
print(member[:3]) #省去从0开始
print(member[:]) #省去开始到结尾,拷贝完整列表
print(),print("切片 步长")
#切片 步长
list2 = [1,3,2,9,7,8]
print(list2[::2]) #从开始到结束,每次加2
#步长可以为负,改变方向(从尾部开始向左走)
print(list2[::-2])
|
21311fd1ed2245bef4cb7e17c261dd8b2276abac | IvanChen008/PythonLearnProject | /ControlOfFlow.py | 5,040 | 4.09375 | 4 | # -----------------
# if语句
# 也许最有名的是if语句
# -----------------
# D:\GitHub\PythonLearnProject>python
# Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
# Type "help", "copyright", "credits" or "license" for more information.
# >>> x = int(input("Please enter an integer:"))
# Please enter an integer:42
# >>> x
# 42
# >>> if x < 0:
# ... x = 0
# ... print("Negative changed to zero")
# ... elif x == 0:
# ... print("Zero")
# ... elif x == 1:
# ... print('Single')
# ... else:
# ... print('More')
# ...
# More
# >>>
# 关键字‘elif’是‘else if’的缩写,这个可以有效地避免过深的缩进。
# if...elif...elif...序列用于替代其他语言中的 switch 或 case 语句。
#---------------------
# For语句
#---------------------
# Python 中的for语句和 C 或 Pascal 中的略有不同。
# 通常的循环可能会依据一个等差数值步进过程(如Pascal),或由用户来定义迭代步骤和终止条件(如C),
# Python 的for语句依据任意序列(链表或字符串)中的子项,按它们在序列中的顺序来进行迭代。
# >>> Measure some strings:
# ... words = ['cat','window','defenestrate']
# >>> for w in words:
# ... print(w,len(w))
# ...
# cat 3
# window 6
# defenestrate 12
#
# 在迭代过程中修改迭代序列不安全(只有在使用链表这样的可变序列时才会有这样的情况)。
# 如果你想要修改你迭代的序列(例如,复制选择项),你可以迭代它的复本。
# 使用切割标识就可以很方便的做到这一点。
#
#-----------------
# range()函数:产生一个数值序列,生成一个等差级数链表。
#-----------------
# >>> for i in range(5):
# ... print(i)
# ...
# 0
# 1
# 2
# 3
# 4
# >>>range(5,10)
# range(5, 10)
# >>> for i in range(5,10):
# ... print(i)
# ...
# 5
# 6
# 7
# 8
# 9
# >>> range(0,10,3)
# range(0, 10, 3)
# >>> for i in range(0,10,3):
# ... print(i)
# ...
# 0
# 3
# 6
# 9
# >>> range(-10,-100,-30)
# range(-10, -100, -30)
# >>> for i in range(-10,-100,-30):
# ... print(i)
# ...
# -10
# -40
# -70
# >>>
# 需要迭代链表索引的话,可以如下结合使用 range() 和 len()
# >>> a = ['Mary','had','a','little','lamb']
# >>> for i in range(len(a)):
# ... print(i,a[i])
# ...
# 0 Mary
# 1 had
# 2 a
# 3 little
# 4 lamb
# >>>
# 但是这种场合可以方便的使用 enumerate()
# >>> print(range(10))
# range(0, 10)
# >>>
#----------------
# range()函数返回的对象有时表现为它是一个列表,但事实上他并不是。当你迭代它时,
# 它是能够返回一个期望的序列的连续项对象;但实质上,他又不是真正的构造列表。
# 我们把它称为 可迭代的。即适合作为那些期望从某些东西中获得连续项直到结束的函数或结构的一个目标。
# 我们已经见过的for语句就是这样一个迭代器。list()函数是另外一个(迭代器),它从可迭代(对象)中创建列表。
#----------------
# >>> list(range(5))
# [0, 1, 2, 3, 4]
# >>>
#-----------------------------------------------------
# >>> for n in range(2,10):
# ... for x in range(2,n):
# ... if n % x == 0:
# ... print(n,"equals",x,'*',n//x)
# ... break
# ... else:
# ... print(n,'is a prime number')
# ...
# 2 is a prime number
# 3 is a prime number
# 4 equals 2 * 2
# 5 is a prime number
# 6 equals 2 * 3
# 7 is a prime number
# 8 equals 2 * 4
# 9 equals 3 * 3
# >>>
# break 语句和C中的类似,用于跳出最近的一级for或while循环。
# 循环可以有一个 else 子句;它在循环迭代完整个列表(对于for)
# 或执行条件为false(对于while)时执行,但是循环被break中止的情况下不会执行。
#
# Tips:
# 与循环一起使用时,else 子句与try语句的 else 子句比与if语句的else子句具有更多的共同点:
# try语句的else子句在未出现异常时运行,循环的else子句在未出现break时运行。
#-----------------
# continue 语句是从C语言借鉴过来的,他表示循环继续执行下一次迭代。
#-----------------
# >>> for num in range(2,10):
# ... if num % 2 == 0:
# ... print("Found an even number:",num)
# ... continue
# ... print("Found a number",num)
# ...
# Found an even number: 2
# Found a number 3
# Found an even number: 4
# Found a number 5
# Found an even number: 6
# Found a number 7
# Found an even number: 8
# Found a number 9
# >>>
#----------------
# pass语句
#----------------
#>>> while True:
# ... pass
# ...
# >>> class MyEmptyClass:
# ... pass
# ...
# pass 语句什么也不做。它用于那些语法上必须要有什么语句,但程序什么也不做的场合。
# 通常用于创建最小结构的类。
# 另一方面,pass 可以在创建新代码的时候用来做函数或控制体的占位符。可以让我们在更加抽象的级别上思考。 |
4138de4ff165d173ba7fd491cda629aae9860bc5 | gjq91459/mycourse | /_Exercises/src/Basic/ex2-3.py | 316 | 4 | 4 | """
Write a program that prints out the square, cubes and fourth
power of the first 20 integers.
"""
format = "%6s"
print (format % "N"),(format % "N**2"),(format % "N**3"),(format % "N**4")
format = "%6i"
for i in range(1,21):
print (format % i),(format % i**2),(format % i**3),(format % i**4)
1 |
948103463469fc6da37381e2f8db879194382f6e | LOG-INFO/PythonStudy | /4_io/3_file_read_write.py | 1,499 | 3.6875 | 4 | # 파일 생성하기
# open('name','mode') mode : ['w', 'w+', 'r', 'r+', 'a', 'a+']
# file.write('str')
# 기존에 파일이 있다면 덮어쓰니 주의!!
print("#" * 50)
print("file.write(data)")
print("#" * 50)
f = open("새파일.txt", 'w')
for i in range(1, 11):
data = "%d ) \n" % i
f.write(data)
print()
f.close()
# file.readline()
# 파일의 내용 중 현재 커서의 위치 한 줄을 문자열로 리턴
print("#" * 50)
print("file.readline()")
print("#" * 50)
f = open("example_file.txt", 'r')
while True:
line = f.readline()
if not line:
break
print(line, end='')
print()
f.close()
# file.readlines()
# 파일의 내용 전체를 '한 줄 단위'로 문자열'리스트'로 리턴
print("#" * 50)
print("file.readlines()")
print("#" * 50)
f = open("example_file.txt", 'r')
lines = f.readlines()
print(lines)
for line in lines:
print(line, end='')
print()
f.close()
# file.read()
# 파일의 내용 전체를 문자열로 리턴
print("#" * 50)
print("file.read()")
print("#" * 50)
f = open("example_file.txt", 'r')
data = f.read()
print(data)
print()
f.close()
# 'a'모드에서의 file.write()
# 파일의 뒤쪽에 이어서 입력
print("#" * 50)
print("file.write() in mode 'a'")
print("#" * 50)
f = open("example_file.txt", 'a+') # a+
data = "// This is example file for Python study.\n"
f.write(data)
# 파일을 읽기 위해 파일의 맨 처음으로 이동
f.seek(0)
print(f.read())
print()
f.close()
|
bff18f57884b57ebbc6d2e8d22f12e64a4d5a404 | sreekripa/core2 | /list.py | 388 | 4.03125 | 4 | # list1=["a","b","c",1,2,3,4,5,"apple","mango","grapes"]
# # # # # print(list1)
# # # # print(list1[8])
# # # list1[3]="fruits"
# # # print(list1)
# # list2=["banana","orange"]
# # print(list1+list2)
# print("apple" in list1)
list1=["apple","banana","orange"]
# list1.append("xyz")
# print(list1)
# list1.insert(1,"egg")
# print(list1)
# print(len(list1))
# print(list1.index("apple"))
|
37c2f76f88902c70c4d5e2c2d833556388abcfa2 | abalulu9/Sorting-Algorithms | /CombSort.py | 967 | 3.96875 | 4 | # An implementation of the comb sort algorithm
# Comb sort compares elements with a certain gap between them and swaps if neccessary
# Repeat this process shrinking the gap until it is of size 1
def combSort(vector, ascending = True, k = 1.3):
# Store the length of the vector
n = len(vector)
# Initialise the length of the gap between elements to be compared
gap = n
# Initialise the number of swaps
noSwaps = 0
# Repeat until a pass with no swaps occured
while True:
# Reduce the gap by a factor of k
gap = int(gap/k)
# For every pair of elements that is a distance of k apart
for i in range(n - gap):
# Does a swap need to occur
if (vector[i] > vector[i + gap] and ascending) or (vector[i] < vector[i + gap] and not ascending):
# Compute the swap
vector[i], vector[i + gap] = vector[i + gap], vector[i]
# Increase the number of swaps
noSwaps += 1
# If no swaps occured
if swaps == 0:
return vector |
2937b48cac60e7835d285248795d3c8ba02e1d18 | Pabitra-26/Problem-Solved | /LeetCode/Maximum_Subarray.py | 527 | 3.859375 | 4 | # Problem name: Maximum subarray
# Description: Given an integer array nums, find the contiguous subarray (containing at least one number)
# which has the largest sum and return its sum.
# Strategy: Dynamic programming
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_so_far = nums[0]
curr_max = nums[0]
for i in range(1, len(nums)):
curr_max = max(nums[i], nums[i] + curr_max)
max_so_far = max(max_so_far, curr_max)
return max_so_far
|
7067840a01ff242ae523924c0290d7a6990fd1f6 | victor-erazo/ciclo_python | /Mision-TIC-GRUPO-09-master(16-06-21)/Semana 1/ejercicio5.py | 572 | 3.703125 | 4 | # crear una variable de tipo diccionario
info_persona = {
'nombre':'',
'pr_apellido':'',
'sg_apellido':''
}
info_persona['nombre'] = input("ingrese el nombre ")
info_persona['pr_apellido'] = input("ingresar el primer apellido ")
info_persona['sg_apellido'] = input("ingresar el segundo apellido ")
info_persona['edad'] = 25
def mostrar_info_personal(var_dict):
respuesta = "el nombre completo es :" + var_dict['nombre'] + " " + var_dict['pr_apellido'] + " " + var_dict['sg_apellido']
return respuesta
print(mostrar_info_personal(info_persona))
|
3a986edaeb318445653a66b35627b0c853afb20b | kyeeh/holberton-system_engineering-devops | /0x16-api_advanced/0-subs.py | 576 | 3.515625 | 4 | #!/usr/bin/python3
"""
Function that queries the Reddit API and returns the number of subscribers
(not active users, total subscribers) for a given subreddit
"""
from requests import get
def number_of_subscribers(subreddit):
"""
Suscribers by subreddit
"""
headers = {"user-agent": "kyeeh"}
url = "https://www.reddit.com/r/{}/about.json".format(subreddit)
try:
req_data = get(url, headers=headers).json()
subscriber_count = req_data["data"]["subscribers"]
return (subscriber_count)
except Exception:
return 0
|
d47fa7aff3869b2c9a1cb52edcf1740b3132fc88 | aaronthebaron/triple | /triple.py | 3,792 | 3.8125 | 4 | import sys
import string
def clean_string(input_string):
"""We can't simply remove punctuation. We need there to be a count difference in the position because one of the rules is that pairs only count if separated by white space."""
removal_map = str.maketrans({
'\n': ' ignr ',
'\r': ' ignr ',
'.': ' ignr ',
'$': None,
'#': None,
'@': None,
'?': ' ignr ',
'!': ' ignr ',
',': ' ignr ',
'(': None,
')': None,
':': ' ignr ',
';': ' ignr '
})
output_string = input_string.translate(removal_map).lower()
return output_string
def find_sequential_duplicates(input_string):
"""Need to find duplicates in the string, remove non-dupes, remove dupes not next to other dupes and their pair dups."""
strings_list = clean_string(input_string).split(' ')
duplicates = []
positions = []
words = []
for i, word in enumerate(strings_list):
if word != 'ignr' and word != '' and strings_list.count(word) > 1:
positions.append(i)
words.append(word)
zipped = zip(positions, words)
list_length = len(positions)
"""Remove non-sequential entries since they can't be pairs"""
for i, word in zipped:
current_index = positions.index(i)
last_num = None
next_num = None
remove_item = False
if current_index > 0:
last_num = positions[current_index - 1]
if current_index < list_length - 1:
next_num = positions[current_index + 1]
if next_num != None and last_num != None:
if i - last_num != 1 and next_num - i != 1:
remove_item = True
else:
if next_num and next_num - i != 1:
remove_item = True
if last_num and i - last_num != 1:
remove_item = True
if remove_item:
del positions[current_index]
del words[current_index]
list_length = list_length - 1
"""Remove dupes that were orphaned by removing non-sequential dupes"""
for i, word in enumerate(words):
if words.count(word) == 1:
del positions[i]
del words[i]
if len(positions) == len(words):
duplicates.append(positions)
duplicates.append(words)
else:
raise ValueError('Words and positions lists are unequal length. Something bad has happened.')
return duplicates
def find_pairs(input_string):
"""Iterate across list and increment extant pairs and reverse pairs. Then clean out single pairs."""
duplicates = find_sequential_duplicates(input_string)
positions = duplicates[0]
words = duplicates[1]
pairs = {}
length = len(positions)
for i, word in enumerate(words):
if (i + 1) < length and positions[i + 1] - positions[i] == 1:
pair = '{} {}'.format(word, words[i + 1])
pair_reversed = '{} {}'.format(words[i + 1], word)
if pair not in pairs and pair_reversed not in pairs:
pairs[pair] = 1
else:
if pair_reversed in pairs:
pairs[pair_reversed] = pairs[pair_reversed] + 1
else:
pairs[pair] = pairs[pair] + 1
pairs = dict((k, v) for k, v in pairs.items() if v > 1)
return pairs
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: python {} "<input string>"'.format(str(sys.argv[0])))
exit(1)
else:
input_string = str(sys.argv[1])
pairs = find_pairs(input_string)
if pairs:
for pair, num in pairs.items():
print('{}: {}'.format(pair, num))
else:
print("No pairs found in string.")
|
8a8b2623567dddc7197ccc6ad06c6989e54d7b0c | joooooonson/LOGICnPROG_2017_Fall | /2dchallenge/joonson_w0410150_702_boxOrDiamond.py | 1,864 | 4.1875 | 4 | # Author: Joon Son
# Date: 2017-11-29
# Description: Nested 2D List challenge!
# use nested loop and create 2-D list
size = 0
character = "X"
shape = "box"
def drawing_box(size, character):
side = size + size -1
drawing = []
for i in range(side):
line = [" "] * side
for j in range(side):
if i == 0 or i == side-1:
line[j] = character
else:
if j==0 or j==side-1:
line[j]=character
drawing.append(line)
return drawing
def drawing_diamond(size, character):
side = size + size -1
drawing = []
for i in range(size):
line = [" "]*side
for j in range(side):
cen = size - 1
if j >= cen-i and j <=cen+i:
line[j]=character
drawing.append(line)
for i in range(side - size):
line = [" "] * side
for j in range(side):
if j>=i+1 and j<side-1-i:
line[j]=character
drawing.append(line)
return drawing
while True:
shape = input("Choose one of the shape box or diamond: ").lower()
if shape != 'box' and shape != 'diamond':
print("please choose a BOX or DIAMOND")
continue
else:
break
while True:
character = input("Enter one character to draw: ").upper()
if len(character) != 1 and character.isprintable():
print("please enter A CHARACTER")
continue
else:
break
while True:
try:
size = int(input("Enter a number of size: "))
except ValueError:
print("Please enter a integer!!:")
continue
break
if shape == 'box':
drawing = drawing_box(size, character)
elif shape == "diamond":
drawing = drawing_diamond(size, character)
for line in drawing:
for ch in line:
print(ch,end=" ")
print()
|
999087b8c1a10c85cc7033c6c56a546be83aa989 | Mifaou/HackerRank_Solution | /HackerRank/Python/Write a function.py | 278 | 3.875 | 4 | def is_leap(year):
leap = False
if not year%4==0:
return leap
else :
if not year%100==0:
return not leap
else :
if year%400==0:
return not leap
else :
return leap |
f461db4904e95aa11695bfeea6dc1b6fc69cafd3 | marshalloffutt/functions | /user_albums.py | 639 | 4.21875 | 4 | # 8-8
def make_album(artist_name, album_title, number_of_tracks):
"""Return a dictionary"""
album = {'Artist': artist_name, 'Title': album_title, 'No of Tracks': number_of_tracks}
return album
while True:
print("\nEnter artist name, and album title, and number of tracks: ")
print("(enter 'q' to to quit)")
a_name = input("Artist name: ")
if a_name == 'q':
break
a_title = input("Album title: ")
if a_title == 'q':
break
num_of_tracks = input("No. of tracks: ")
if num_of_tracks == 'q':
break
album = make_album(a_name, a_title, num_of_tracks)
print(album) |
69a0d8b929df48b531cc89776084b00c62372f9e | chlos/exercises_in_futility | /misc/anagrams.py | 516 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
def get_anagrams(words):
word_groups = collections.defaultdict(list)
for word in words:
word_sorted = ''.join(sorted(word))
word_groups[word_sorted].append(word)
return word_groups
def main():
words = ['a', 'b']
print get_anagrams(words)
words = ['a', 'b', 'ab', 'ba']
print get_anagrams(words)
words = ['a', 'b', 'aab', 'ba']
print get_anagrams(words)
if __name__ == "__main__":
main()
|
88e94b4e5d6c3e8855af7159c674f2b489e15325 | sjlarrain/Herramientas | /P03/solucionP03.py | 1,057 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
from copy import deepcopy as dp
def problemaP03(lista,buscado):
def sumar(a,b):
return b+a
def restar(a,b):
return b-a
def numero(a,buscado,b=0):
sol=0
if sumar(a,b)==buscado:
sol+=1
if restar(a,b)==buscado:
sol+=1
solution.append(sol)
return [sumar(a,b),restar(a,b)]
def cont(lt,buscado,res=0):
if len(lt)>=1:
sol=res+numero(lt[0],buscado)
konts=cont(lt[1:],sol[0])
kontr=cont(lt[1:],sol[1])
def solver(arbol,lista,buscado):
ltCN=dp(arbol)
ltCN.append(lista[0])
ltSN=dp(arbol)
if len(lista[1:])>0:
cont(ltCN,buscado,lista[1:])
cont(ltSN,buscado,lista[1:])
global solution
solution=[]
arbol=[]
solver(arbol,lista,buscado)
return solution
# In[6]:
lista=[4, 8, -4, 1]
print(problemaP03(lista,4))
# In[ ]:
|
18d011df4badddb575d549f17afe53f15a0683a8 | marwafar/Python-practice | /solve.py | 1,683 | 4.09375 | 4 | """
Instructions:
- Implement the function `path_exists` below.
- Save this file as `{first_name}_{last_name}_solve.py`.
Constraints:
- Your solution will be run in a Python2.7 environment.
- Only python standard library imports can be used and they must be imported within `path_exists`.
- The function signature of `path_exists` cannot be modified.
- Additional functions can be included, but must be defined within `path_exists`.
- There will be two sets of input, small and large, each with different time limits.
"""
def path_exists(grid, queries):
"""
Determines whether for every start=(i1, j1) -> end=(i2, j2) query in `queries`,
there exists a path in `grid` from start to end.
The rules for a path are as follows:
- A path consists of only up-down-left-right segments (no diagonals).
- A path must consist of the same values. i.e. if grid[i1][j1] == 1, the path is comprised of only 1's.
Examples:
grid (visual only)
1 0 0
1 1 0
0 1 1
start end answer
(0, 0) -> (2, 2) True
(2, 0) -> (0, 2) False
:param grid: The grid on which `queries` are asked.
:type grid: list[list[int]], values can only be [0, 1].
:param queries: A set of queries for `grid`. Queries will be non-trivial.
:type queries: Iterable, contains elements of type tuple[tuple[int, int]].
:return: The result for each query, whether a path exists from start -> end.
:rtype: list[bool]
"""
raise NotImplementedError
|
fa0470db97174305cb1ea00849c30bc9fbf927fb | ZYZhang2016/think--Python | /chapter18/Exercise18.2CardGame.py | 1,777 | 3.875 | 4 | #coding:utf-8
import random
class Card(object):
'''reprensts a card game
'''
def __init__(self,suit=0,rank=2):
self.suit = suit
self.rank = rank
suits_name = ['Club','Diamond','Hearts','Spades']
rank_name = [None,'1','2','3','4','5','6','7','8','9','10','Jack','Queen','King']
def __str__(self):
return '{} of {}'.format(self.rank_name[self.rank],self.suits_name[self.suit])
def __cmp__(self, other):
t1 = self.rank,self.suit
t2 = other.rank,other.suit
return cmp(t1,t2)
class Deck(object):
'''create a set of cards
'''
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1,14):
card = Card(suit,rank)
self.cards.append(card)
def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return '\n'.join(res)
def pop_card(self):
return self.cards.pop()
def add_card(self,card):
self.cards.append(card)
def shuffle(self):
random.shuffle(self.cards)
def sort(self):
self.cards.sort(cmp=Card.__cmp__())
def move_cards(self,hand,num_cards):
for i in range(num_cards):
hand.add_card(self.pop_card())
def deal_hand(self,num_hands,num_per_hand):
for hand in range(num_hands):
hand_name = 'Hand: '+str(hand+1)
hand = Hand(hand_name)
print hand_name+' is created'
for num_cards in range(num_per_hand):
hand.add_card(self.pop_card())
print 'Hand has cards'
print '#######################'
hands = []
hands.append(hand)
return hands
class Hand(Deck):
'''手牌类,继承自桌面牌,
'''
def __init__(self,lable=''):
self.cards = []
self.lable = lable
def main():
#拿出一刀牌
card = Card()
deck = Deck()
#洗牌
deck.shuffle()
#发牌,两人,每人17张
deck.deal_hand(2,17)
if __name__=='__main__':
main() |
2443c5b9dd8e7dd49f14e93d1b2857886ff87647 | amirabed2024/Python_Teacher | /Teach33.py | 687 | 4.03125 | 4 | # Inheritance => class Motor(Car)
class Car:
wheels = 4
def __init__(self, name, speed, price):
self.name = name # Atribute
self.speed = speed # Atribute
self.price = price # Atribute
def show(self): # Method
print(f'{self.name} cost {self.price} and top speed is {self.speed}')
class Motor(Car):
wheels = 2
def __init__(self, name, speed, price, helmet): # Method
super().__init__(name, speed, price)
self.helmet = helmet
def show(self): # Method
super().show()
print(f'hello, we are riding {self.name}.')
m1 = Motor('honda', 200, '500$', 'hat')
m1.show()
#help(m1) # method resolution order! |
4f6ac4a480ca8e166c17d6d86e48beecc3ca37e6 | zision/Sort-Python | /insert_sort.py | 1,450 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : insert_sort.py
# Author: ZhouZijian
# Date : 2018/9/21
"""插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法。
它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
1、从第一个元素开始,该元素可以认为已经被排序;
2、取出下一个元素,在已经排序的元素序列中从后向前扫描;
3、如果该元素(已排序)大于新元素,将该元素移到下一位置;
4、重复步骤3,直到找到已排序的元素小于或者等于新元素的位置;
5、将新元素插入到该位置后;
6、重复步骤2~5。
"""
import rdlist
# 插入排序算法实现1
def insert_sort1(arr):
for i in range(1, len(arr)):
key = arr[i]
for j in range(i - 1, -1, -1):
if arr[j] > key:
arr[j + 1] = arr[j]
arr[j] = key
return arr
# 插入排序算法实现2
def insert_sort2(arr):
for i in range(1, len(arr)):
for j in range(i - 1, -1, -1):
if arr[j] > arr[i]:
arr[j], arr[i] = arr[i], arr[j]
i -= 1
j -= 1
return arr
# 检测
if __name__ == "__main__":
print("排序后列表:", insert_sort1(rdlist.rdlist(int(input("输入待检测列表长度:")))))
|
855b6dd08bc7b5251aa045c131fbbd0b69187624 | 1505069266/python- | /函数式编程匿名函数,高阶函数,装饰器/优化装饰器.py | 375 | 3.734375 | 4 | # 优化装饰器
import time
def decorator(func):
# key word
def wrapper(*args, **kw):
print(time.time())
func(*args, **kw)
return wrapper
@decorator
def f1(func_name):
print('this is function' + func_name)
@decorator
def f2(func_name1, func_name2):
print('this is a function' + func_name1 + func_name2)
f2('朱晓乐', '笨蛋') |
8e2b5c36a5cac7f4ea616373976d8dc5d70a617b | vykee/-Porta3 | /bono6.py | 167 | 3.765625 | 4 | #Sum of two numbers
n = 0
list = []
sum = 0
n=(input("Digite dos numeros: "))
list=n.split(',')
for i in list:
sum = int(sum) + int(i)
print(sum)
|
98085a43da10432fad1190b96b51414df35f976a | KuR0uSaGi/datatrucgrader | /63010852_Lab04_5.py | 3,826 | 3.78125 | 4 | class Queue:
def __init__(self, ls = None):
self.count = 0
self.count1 = 0
if ls == None:
self.items = []
else:
self.items = ls
self.getTripleCharactor()
def enqueue(self, val):
self.items.append(val)
return ("Add {} index is {}".format(val, len(self.items) - 1))
def dequeue(self):
return self.items.pop(0)
def __str__ (self):
self.items.reverse()
if self.isEmpty(): return ("Empty")
tmp = ""
for i in range(self.size()):
tmp += self.items[i][0]
return tmp
def isEmpty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def getTripleCharactor(self):
i = 0
check = False
while(True):
if i < len(self.items) - 2:
if self.items[i][0] == self.items[i+1][0] == self.items[i+2][0]:
if self.items[i][1] or self.items[i+1][1] or self.items[i+2][1]: self.count1 += 1
self.items.pop(i+2)
self.items.pop(i+1)
self.items.pop(i)
self.count += 1
check = True
i = -1
if i == len(self.items) and check:
i = 0
check = False
elif (i == len(self.items) and check == False) or self.size() < 3: break
i += 1
class Stack:
def __init__(self, ls = None):
self.stack = []
self.items = []
self.count = 0
if ls != None:
for i in range(len(ls)):
lsss = [ls[len(ls) - 1 - i], True]
self.push(lsss)
self.getTripleCharactor()
self.items.reverse()
def push(self, val):
self.stack.append(val)
def pop(self):
return self.items.pop()
def __str__ (self):
self.stack.reverse()
if self.is_empty(): return ("ytpmE")
tmp = ""
for i in range(self.size()):
tmp += self.stack[i][0]
return tmp
def size(self):
return len(self.stack)
def is_empty(self):
return len(self.stack) == 0
def getTripleCharactor(self):
i = 0
check = False
while(True):
if i < self.size() - 2:
if self.stack[i][0] == self.stack[i+1][0] == self.stack[i+2][0]:
self.items.append(self.stack[i])
self.stack.pop(i+2)
self.stack.pop(i+1)
self.stack.pop(i)
self.count += 1
check = True
i = -1
if i == len(self.stack) and check:
i = 0
check = False
elif (i == len(self.stack) and check == False) or self.size() < 3: break
i += 1
inp = input("Enter Input (Normal, Mirror) : ").split()
s = Stack(inp[1])
ls_l = []
ls_l2 = []
ls_l3 = []
tmp = [0, 0, 0]
for i in range(len(inp[0])):
if i < len(inp[0]) - 2:
if inp[0][i] == inp[0][i+1] == inp[0][i+2]:
ls_l2.append(i)
lllll = [inp[0][i], False]
ls_l.append(lllll)
ls_l3 = ls_l
for i in range(len(ls_l)):
if tmp[0] <= len(ls_l2) - 1 and s.count > tmp[2]:
if ls_l2[tmp[0]] == i:
ls_l3.insert(i + 2 + tmp[0], s.pop())
tmp[0] += 1
tmp[2] += 1
q = Queue(ls_l)
print("NORMAL : \n{}".format(q.size()))
print(q)
print("{} Explosive(s) ! ! ! (NORMAL)".format(q.count - q.count1))
if q.count1 > 0: print("Failed Interrupted {} Bomb(s)".format(q.count1))
print("------------MIRROR------------\n: RORRIM\n{}".format(s.size()))
print(s)
print("(RORRIM) ! ! ! (s)evisolpxE {}".format(s.count))
|
ade159980337c30b61cf662106bcca38c7926993 | itsdddaniel/POO | /II Parcial/main2.py | 176 | 3.578125 | 4 | #-*- coding: utf-8 -*-
import rep
number = input("")
number = re.sub(r"\D+","",number)
if len(number)==0: number=1
else: number = int(number)
print("Hola Mundo\n"*number) |
9c11c6064853db7bc29c9dc6e354d184dcabf6a8 | miikanissi/python_course_summer_2020 | /week2_nissi_miika/week2_ass4_nissi_miika.py | 1,437 | 4.375 | 4 | print("BMI Calculator")
unit = input("Choose the unit of measure: 1 for Metric, 2 for Imperial: ")
while (unit != "1" and unit != "2"):
unit = input("Choose the unit of measure: 1 for Metric, 2 for Imperial: ")
if (unit == "1"):
while True:
weight = input("Enter weight in kg: ")
try:
x = float(weight)
if x < 0: raise ValueError("Weight must be positive.")
except ValueError:
print("Try entering again...")
else:
break
while True:
height = input("Enter height in m: ")
try:
y = float(height)
if y < 0: raise ValueError("Height must be positive.")
except ValueError:
print("Try entering again...")
else:
break
bmi = x / (pow(y, 2))
else:
while True:
weight = input("Enter weight in lbs: ")
try:
x = float(weight)
if x < 0: raise ValueError("Weight must be positive.")
except ValueError:
print("Try entering again...")
else:
break
while True:
height = input("Enter height in inches: ")
try:
y = float(height)
if y < 0: raise ValueError("Height must be positive.")
except ValueError:
print("Try entering again...")
else:
break
bmi = 703 * x / (pow(y, 2))
print('%.01f'%(bmi))
|
8857cbfed8645e5c742f828b0a356532cecf0608 | dmelles/ChessLab | /ChessGUI.py | 7,903 | 3.640625 | 4 | # ChessGUI.py
# Written by: Shasta Ramachandran
# Date: 2/5/2016
# Creates a GUI object for use with Chess
from Square import *
from graphics import *
from Button import *
class ChessGUI:
def __init__(self):
"""Creates a GUI object for use with Chess, complete with Mouse, Square, and Message functionality."""
# Determining the width and length
self.width = 1000
self.height = 700
# Create the square colors
self.darkSquareColor = "LightSteelBlue1"
self.darkSquareColorHighlighted = "blue2"
self.lightSquareColor = "MistyRose2"
self.lightSquareColorHighlighted = "maroon1"
# Create the line color
self.lineColor = "black"
# Creating the graphics window
self.window = GraphWin("Chess!!!", self.width, self.height)
# Creating the background color
self.background = "honeydew2"
# Filling in the background color
self.window.setBackground(self.background)
# Set the size of the chess board
self.boardLength = self.height * 7 / 8
# Creating the interaction options
self.messageBox = Text(Point(self.width * 10 / 12, self.height * 1 / 4), "")
self.messageBox.draw(self.window)
self.messageBox.setFace("times roman")
self. moveBox = Text(Point(self.width * 10 / 12, self.height * 1 / 2), "")
self.moveBox.draw(self.window)
self.moveBox.setFace("times roman")
self.quitButton = Button(self.window, Point(self.width * 10 / 12, self.height * 2 / 3), 70, 40, "Quit", "CadetBlue1")
self.resetButton = Button(self.window, Point(self.width * 10 / 12, self.height * 5 / 6), 70, 40, "New Game!", "CadetBlue1")
self.quitButton.activate()
# Create the squared grid
self.listOfSquares = [[],[],[],[],[],[],[],[]]
alpha = ["a","b","c","d","e","f","g","h"]
numbers = ["1","2","3","4","5","6","7","8"]
labelsX,labelsY = [],[]
for i in range(8):
for j in range(8):
if(i % 2 == 0 and j % 2 != 0) or (i % 2 != 0 and j % 2 == 0):
self.listOfSquares[i].append(Square(self.darkSquareColor, self.darkSquareColorHighlighted, self.lineColor, self.boardLength * i / 8 + self.width * 1 / 18, self.boardLength * j / 8 + self.height * 1/18, self.boardLength / 8))
else:
self.listOfSquares[i].append(Square(self.lightSquareColor, self.lightSquareColorHighlighted, self.lineColor, self.boardLength * i / 8 + self.width * 1 / 18, self.boardLength * j / 8 + self.height * 1/18, self.boardLength / 8))
labelsY.append(Text(Point(self.width * 1 / 18 + self.boardLength + 15, self.boardLength * j / 8 + self.height * 1/18 + self.boardLength / 16), numbers[7-j]))
labelsX.append(Text(Point(self.boardLength * i / 8 + self.width * 1 / 18 + self.boardLength / 16, self.height * 1/18 - 14), alpha[i]))
# Draw the squares
for squareList in self.listOfSquares:
for square in squareList:
square.draw(self.window)
# Draw the labels
for i in range(8):
labelsX[i].draw(self.window)
labelsY[i].draw(self.window)
# Create the border lines
self.borderLine1 = Line(Point(self.width * 1 / 18, self.height * 1/18), Point(self.boardLength + self.width * 1 / 18, self.height * 1/18))
self.borderLine2 = Line(Point(self.width * 1 / 18, self.height * 1/18), Point(self.width * 1 / 18, self.boardLength + self.height * 1/18))
self.borderLine3 = Line(Point(self.boardLength + self.width * 1 / 18, self.height * 1/18), Point(self.boardLength + self.width * 1 / 18, self.boardLength + self.height * 1/18))
self.borderLine4 = Line(Point(self.width * 1 / 18, self.boardLength + self.height * 1/18), Point(self.boardLength + self.width * 1 / 18, self.boardLength + self.height * 1/18))
# Draw the border lines
self.borderLine1.draw(self.window)
self.borderLine2.draw(self.window)
self.borderLine3.draw(self.window)
self.borderLine4.draw(self.window)
# Change the color of the border lines
self.borderLine1.setFill(self.lineColor)
self.borderLine2.setFill(self.lineColor)
self.borderLine3.setFill(self.lineColor)
self.borderLine4.setFill(self.lineColor)
# Create a list of highlighted squares to reduce lag
self.highlightedSquares = []
def getSquare(self, requestedSquare):
"""Returns the square requested by the format of either[letter,number] or [number,number]. Works with Tuples too."""
# Two branches in case the protocol is changed
if(type(requestedSquare[0]) == int):
return self.listOfSquares[requestedSquare[0]][requestedSquare[1]]
else:
# Use .index to convert letter to number
return self.listOfSquares[["a","b","c","d","e","f","g","h","i"].index(requestedSquare[0])][requestedSquare[1] - 1]
def getClickedSquare(self, point):
"""Returns the the square at the given point, or returns false."""
# Set a default return value
returnValue = False
# Cycle through all squares to find the clicked square
for squareList in self.listOfSquares:
for square in squareList:
if square.clicked(point):
returnValue = square
return returnValue
def getInput(self):
"""Validates input, waiting until a square is clicked or the quitButton is quit and returning the selected square or a QuitError."""
while True:
clickPoint = self.window.getMouse()
# Test the point
if(self.getClickedSquare(clickPoint)):
squareToReturn = self.getClickedSquare(clickPoint)
return(self.getIndex(squareToReturn))
break
elif(self.quitButton.clicked(clickPoint)):
raise NotImplementedError("Quit by user.")
def getIndex(self, square):
"""Gets the X and Y of a given squarem, or returns to False, False for an error."""
# Scan all squares to check for a match
x = False
y = False
for i in range(8):
for j in range(8):
if(self.listOfSquares[i][j] == square):
x = i
y = j
# Format the return
tupleToReturn = (x,y)
return(tupleToReturn)
def getMouse(self):
"""Gets a mouse in the window and returns the given point."""
mouseClick = self.window.getMouse()
return(mouseClick)
def printMessage(self, Message):
"""Prints a message on screen."""
# Make sure the message ends in a period
if(Message[-1] != "." and Message[-1] != "!"):
Message += "."
self.messageBox.setText(Message)
def draw(self, objectToBeDrawn):
"""Draws and object with proper encapsulation."""
objectToBeDrawn.draw(self.window)
def highlightSelectedSquare(self, requestedSquare):
"""Highlights the square at a given coordinate."""
# Add the square to highlighted squares and highlight it
squareToHighlight = self.getSquare(requestedSquare)
self.highlightedSquares.append(squareToHighlight)
squareToHighlight.highlight()
def unHighlightSelectedSquare(self, requestedSquare):
"""Unhighlights the square at a given coordinate."""
self.getSquare(requestedSquare).unHighlight()
def unHighlightAllSquares(self):
"""Unhighlights all squares."""
# Use selected squares to reduce lag
for square in self.highlightedSquares:
square.unHighlight()
self.highlightedSquares = []
def clearMessage(self):
"""Clears the message being displayed."""
self.messageBox.setText("")
def printMoves(self, message):
"""Prints the move message on screen."""
# Add a period to the end if needed
if(message[-1] != "."):
message += "."
# Print the message
self.moveBox.setText(message)
def clearMoves(self):
"""Clears the move message."""
self.moveBox.setText("")
def closeWindow(self):
"""Closes the window."""
self.window.close()
def reset(self):
"""Resets the GUI window for a new game."""
# Wait for the reset button to be clicked
self.resetButton.activate()
while True:
clickPoint = self.window.getMouse()
# Check input
if(self.resetButton.clicked(clickPoint)):
break
elif(self.quitButton.clicked(clickPoint)):
raise NotImplementedError("Quit by user.")
# Unhighlight all Squares
for squareList in self.listOfSquares:
for square in squareList:
square.unHighlight()
# Reset the GUI Message
self.messageBox.setText("New game! White goes first.")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.