blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
dd57652f40ff2722ce0399af6d3eb240901f89b2 | zhangwei1989/algorithm | /Python/1-two_sum_first.py | 434 | 3.671875 | 4 | # Difficulty - Easy
# Url - https://leetcode.com/problems/two-sum/
# Time complexity: O(N2);
# Space complexity: O(1);
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(0, (len(nums)-1)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target: return [i, j]
|
cdb6c7bc8d2c4b93f5d45f0498ae6ed71930aba1 | FranMZA/NumericMatricProcessor | /domain/MatrixBuilder.py | 1,159 | 3.671875 | 4 | class MatrixBuilder:
def build(self, m_dim=None, m_val=None):
print(f'{m_dim}')
dim_matrix = self.dim_input()
print(f'{m_val}')
values = list()
for row_index in range(dim_matrix[0]):
values.append(self.row_input(dim_matrix[1]))
return dim_matrix, values
@staticmethod
def dim_input():
# check if dims are positive integers
dims = [int(dim) for dim in input().split()]
if len(dims) != 2:
raise IndexError('Wrong number of dimensions')
for i in range(len(dims)):
if dims[i] <= 0:
dims[i] = 1
return dims
@staticmethod
def row_input(num_cols):
# check if the row has the correct number of elements
# num elements given by dim_matrix[1] (num of columns)
row = [float(num) for num in input().split()]
if len(row) != num_cols:
if len(row) > num_cols:
raise IndexError('Length of row is bigger than dimension of matrix')
else:
raise IndexError('Length of row is smaller than dimension of matrix')
return row
|
22016138907f3567e29a8c80a769c89b6ff4d7dc | anniequasar/session-summaries | /Red_Hat/sess_8/s8b_functions.py | 5,971 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Functions - Beginners Python Session 8 - s8b_function.py
@author: Tim Cummings
Demonstrates: Logging, Exceptions, Testing
"""
import logging
import datetime
import decimal
# Can be useful to include logging in function
# Challenge set logging level to DEBUG and confirm that logging output
logging.basicConfig(level=logging.DEBUG) # plain python, PyCharm
logging.getLogger().setLevel(logging.DEBUG) # Spyder, Jupyter, PyCharm, probably plain Python too
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")
# Challenge: Add logging to td_time_left and dt_same_time_tomorrow
def td_time_left():
"""Calculate time from now until 8pm tonight and return it as a datetime.timedelta"""
time_finish = datetime.datetime.combine(datetime.datetime.today(), datetime.time(hour=20))
time_now = datetime.datetime.now()
time_delta = time_finish - time_now
logging.debug("Time left in session is {} (hh:mm:ss.ssssss)".format(time_delta))
return time_delta
def dt_same_time_tomorrow():
"""Returns the date and time one day after this function is called"""
time_today = datetime.datetime.now()
one_day = datetime.timedelta(days=1)
time_tomorrow = time_today + one_day
logging.debug("Time now {}, same time tomorrow {}".format(time_today, time_tomorrow))
return time_tomorrow
td_time_left()
dt_same_time_tomorrow()
# Log at ERROR level if an exception. Otherwise log at DEBUG level
def flt_f_from_c(c):
"""Returns the temperature in Fahrenheit given the temperature in Celsius"""
try:
f = c * 1.8 + 32
logging.debug("Celsius {:.2f}, Farhenheit {:.2f}".format(c, f))
return f
except TypeError:
# exc_info=True outputs a stack trace
logging.error("flt_f_from_c({!r})".format(c), exc_info=True)
flt_f_from_c(0)
flt_f_from_c(100)
flt_f_from_c(-40)
flt_f_from_c("20°C")
# Challenge: error level log if price_incl_gst throws an exception, otherwise debug level
def price_incl_gst(price_excl_gst, gst_rate=0.1):
"""Calculates price including GST
Parameters
----------
price_excl_gst : decimal.Decimal or float or int or str
The price excluding GST
gst_rate : decimal.Decimal or float or int or str
The GST rate as a fraction (not a percent). gst_rate=0.1 is equivalent to a GST rate of 10%
Returns
-------
decimal.Decimal
The price including GST
Raises
------
decimal.InvalidOperation
If either price_excl_gst or gst_rate is a str which cannot go to decimal.Decimal eg "one"
TypeError
If either price_excl_gst or gst_rate is a type which cannot go to decimal.Decimal eg {1}
ValueError
If either price_excl_gst or gst_rate is a value which cannot go to decimal.Decimal eg [1]
"""
try:
lcl_price_incl_gst = round(decimal.Decimal(price_excl_gst) * decimal.Decimal(1 + gst_rate), 2)
logging.debug("price_incl_gst(price_excl_gst={!r}, gst_rate={!r}) -> {!r}".format(price_excl_gst, gst_rate, lcl_price_incl_gst))
return lcl_price_incl_gst
except (ValueError, TypeError, decimal.InvalidOperation) as e:
# we are only catching 3 exception types. To catch all use 'except Exception as e:'
# logging.exception can only be called within 'except' code block
logging.exception("Here is the stack trace")
# format strings !r equivalent to caling repr(value)
logging.error("price_incl_gst(price_excl_gst={!r}, gst_rate={!r}) produces exception {!r}"
.format(price_excl_gst, gst_rate, e))
# re-raise the exception if you don't want to swallow it
raise e
# Challenge: Modify test_price_incl_gst to ensure correct exceptions are raised.
# Hint: Can't use assert. Can use python's built-in exception handling
# Hint: Can raise an AssertionError the same as if assert had failed
def test_price_incl_gst():
D = decimal.Decimal
assert price_incl_gst(10) == D("11")
assert price_incl_gst(0) == 0
assert price_incl_gst(-2.2, 0.1) == D("-2.42")
assert price_incl_gst(D("1.1")) == D("1.21")
assert price_incl_gst(D("1.10")) == D("1.21")
assert price_incl_gst(D("1.1"), D("0.15")) == D("1.26")
# When calling a function you can supply parameters in a different order by using their names
assert price_incl_gst(gst_rate=D("0.15"), price_excl_gst=D("1.1")) == D("1.26")
# When calling a function you can supply parameters by expanding a list of the parameters
my_list = [12.345, 0.125]
assert price_incl_gst(*my_list) == D("13.89")
# When calling a function you can supply parameters by expanding a dict of the named parameters
my_dict = {'gst_rate': 1/3, 'price_excl_gst': 6.0}
assert price_incl_gst(**my_dict) == D("8.00")
try:
price_incl_gst("one")
raise AssertionError('price_incl_gst("one") should raise a decimal.InvalidOperation exception but raised nothing')
except decimal.InvalidOperation:
pass
except Exception as e:
raise AssertionError('price_incl_gst("one") should raise a decimal.InvalidOperation exception but raised {!r}'.format(e))
try:
price_incl_gst({1})
raise AssertionError('price_incl_gst({1}) should raise a TypeError exception but raised nothing')
except TypeError:
pass
except Exception as e:
raise AssertionError('price_incl_gst({{1}}) should raise a TypeError but raised {!r}'.format(e))
try:
price_incl_gst([1])
raise AssertionError('price_incl_gst([1]) should raise a ValueError exception but raised nothing')
except ValueError:
pass
except Exception as e:
raise AssertionError('price_incl_gst([1]) should raise a ValueError but raised {!r}'.format(e))
test_price_incl_gst()
|
ed9008fadbd117482229ffe9e0479051640eba15 | karandevgan/Algorithms | /StringMatch.py | 1,754 | 3.6875 | 4 | class Solution:
# @param haystack : string
# @param needle : string
# @return an integer
def strStr(self, haystack, needle):
#import pdb; pdb.set_trace()
if len(haystack) == len(needle):
if haystack == needle:
return 0
else:
return -1
elif len(haystack) < len(needle):
return -1
elif len(needle) == 0:
return -1
i = 0
j = 0
start_index = -1
another_index = -1
while i < len(haystack) and j < len(needle):
remaining_haystack = len(haystack) - i - 1
remaining_needle = len(needle) - j - 1
if remaining_needle > remaining_haystack:
return -1
if haystack[i] == needle[0] and another_index <= start_index:
another_index = i
if haystack[i] == needle[j]:
if j == 0:
start_index = i
i += 1
j += 1
else:
j = 0
# start_index != 1 checks for the case when first character is
# also not matched atleast for once
if another_index > start_index and start_index != -1:
i = another_index
else:
i += 1
# Start index should become -1 after every non match character
start_index = -1
if j != len(needle):
start_index = -1
return start_index
sol = Solution()
haystack = "babbaaabaaaabbababaaabaabbbbabaaaabbabbabaaaababbabbbaaabbbaaabbbaabaabaaaaababbaaaaaabababbbbba"
needle = "bababbbbbbabbbaabbaaabbbaababa"
print sol.strStr(haystack, needle)
|
f1e13b8fb7cb01f43bc90dba091c7bca5f311865 | vsdrun/lc_public | /string/67_Add_Binary.py | 891 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/add-binary/description/
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
"""
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if len(a) == 0:
return b
if len(b) == 0:
return a
if a[-1] == '1' and b[-1] == '1':
return self.addBinary(self.addBinary(a[0:-1], b[0:-1]), '1') + '0'
if a[-1] == '0' and b[-1] == '0':
return self.addBinary(a[0:-1], b[0:-1]) + '0'
else:
return self.addBinary(a[0:-1], b[0:-1]) + '1'
def build():
return "101", "1"
if __name__ == "__main__":
s = Solution()
result = s.addBinary(*build())
print(result)
|
c911452b9df135a5fe2638a2730536525c375264 | xcsp3team/pycsp3 | /problems/csp/complex/StableMarriage.py | 2,020 | 3.90625 | 4 | """
Consider two groups of men and women who must marry.
Consider that each person has indicated a ranking for her/his possible spouses.
The problem is to find a matching between the two groups such that the marriages are stable.
A marriage between a man m and a woman w is stable iff:
- whenever m prefers an other woman o to w, o prefers her husband to m
- whenever w prefers an other man o to m, o prefers his wife to w
In 1962, David Gale and Lloyd Shapley proved that, for any equal number n of men and women,
it is always possible to make all marriages stable, with an algorithm running in O(n^2).
Nevertheless, this problem remains interesting
as it shows how a nice and compact model can be written.
Execution:
python3 StableMarriage.py -data=StableMarriage-example.json
"""
from pycsp3 import *
w_rankings, m_rankings = data # ranking by women and men
n = len(w_rankings)
Men, Women = range(n), range(n)
# wf[m] is the wife of the man m
wf = VarArray(size=n, dom=Women)
# hb[w] is the husband of the woman w
hb = VarArray(size=n, dom=Men)
satisfy(
# spouses must match
Channel(wf, hb),
# whenever m prefers an other woman o to w, o prefers her husband to m
[(m_rankings[m][o] >= m_rankings[m][wf[m]]) | (w_rankings[o][hb[o]] < w_rankings[o][m]) for m in Men for o in Women],
# whenever w prefers an other man o to m, o prefers his wife to w
[(w_rankings[w][o] >= w_rankings[w, hb[w]]) | (m_rankings[o][wf[o]] < m_rankings[o][w]) for w in Women for o in Men]
)
""" Comments
1) one could add two redundant constraints AllDifferent on wf and hb
2) one could replace Channel(wf, hb) with:
# each man is the husband of his wife
[hb[wf[m]] == m for m in Men],
# each woman is the wife of her husband
[wf[hb[w]] == w for w in Women],
3) global constraints involved in general expressions are externalized by introducing
auxiliary variables. By using the compiler option, -useMeta, this is no more the case
but the generated instance is no more in the perimeter of XCSP3-core
""" |
fe684d9664f0bf4ffe279d7632f15b0076aa2d74 | nicktheo59/eulerPy | /21-40/36.py | 400 | 3.625 | 4 |
def IsPallindromic( number ):
number = str(number)
if len(number) == 0 or len(number) == 1:
return True
elif number[0] == number[-1]:
return IsPallindromic( number[1:-1] )
else:
return False
print IsPallindromic( 13111 )
sum = 0
i = 0
for num in range(1000000):
if IsPallindromic( num ) == True and IsPallindromic( bin(num)[2:]) == True:
sum += num
i += 1
print i
print sum
|
7404646dd3bf2ef7344a7ba11b985bbac58ef4f5 | ming-log/Multitasking | /01 多线程/07 通过继承Thread重写run方法来创建线程.py | 453 | 3.828125 | 4 | # !/usr/bin/python3
# -*- coding:utf-8 -*-
# author: Ming Luo
# time: 2020/9/4 11:55
from threading import Thread
import time
class MyThread(Thread):
# 重写run()方法
def run(self):
for i in range(3):
time.sleep(1)
msg = "I'm " + self.name + ' @ ' + str(i)
print(msg)
if __name__ == '__main__':
t = MyThread()
t.start() # start()会自动调用run(),run()方法执行完,线程结束
|
ef1fbbd2a78c688aa9262470107b3d31c0e57ad0 | bezerrasara/programacao-orientada-a-objetos | /listas/lista-de-exercicio-02/questao07.py | 114 | 3.84375 | 4 | lado = float(input('medida do lado: '))
area = lado**2
print(f'area = {area}' )
print(f'dobro da area = {area*2}') |
5868f83d57d24064dc30eb4a999ee3b7e5700527 | MathMS/atividadesPython | /Mundo 02 - Estruturas de Controle/Atividade 050 - Estrutura For.py | 336 | 4.03125 | 4 | """Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles que
forem pares. Se o valor digitado for ímpar, desconsidere-o"""
soma = 0
for c in range(0,6):
numero = int(input('Digite o número: '))
if numero%2 == 0:
soma += numero
print('\nA soma dos números pares deu: {}'.format(soma)) |
dbf58cf62057e821c559bfec8d0d5148bfa1029b | vitaliipazhbekov/challenges | /codewars/is_this_a_triangle.py | 122 | 3.921875 | 4 | def is_triangle(a, b, c):
if a + b > c and b + c > a and a + c > b:
return True
else:
return False |
e73a0185387440dab199a5cf3f9519350b2a5efa | Abel3581/Practicas_Python_UNGS | /practica_3_Ciclos_For_While_Range_Cadenas.py | 25,230 | 4.1875 | 4 | ##Realizar un programa que solicite dos números y realice la división entre ellos, no se debe permitir que el denominador sea 0.
##Realizar un programa que imprima la tabla del 2 (desde el 1 al 10).
##Modificar el programa anterior, para que pida al usuario un número entero e imprima la tabla de multiplicar de dicho número.
##Realizar un programa que sume los primeros n números naturales. (n lo indica el usuario)
##Realizar un programa que sume los primeros números impares hasta n. (n lo indica el usuario)
##Realizar un programa que sume los primeros n números impares. (n lo indica el usuario)
# 1
##numerador=float(input("Ingrese un numero:"))
##denominador=float(input("Ingrese un numero:"))
##while denominador==0:
## denominador=float(input("Ingrese un numero distinto de ¡0!:"))
##division=(numerador/denominador)
##print(division)
# 2
##cont=1
##while cont <=10:
## print(2,"x",cont,"=",2*cont)
## cont=cont+1
# 3
##n=int(input("Que tabla desea calcular:"))
##cont=1
##while cont<=10:
## print(n,"x",cont,"=",n*cont)
## cont=cont+1
# 4
##n=int(input("Ingrese un numero:"))
##suma=0
##cont=1
##while cont<=n:
## suma=suma+cont
## cont=cont+1
##print("La suma de los primeros",n,"naturales es:",suma)
#suma primeros numeros impares hasta n
##n=int(input("ingrese un numero: "))
##i=1
##suma=0
##while(i<=n):
## suma=suma+i
## print(i,suma)
## i=i+2
##n=int(input("ingrese un numero: "))
##cont=1
##suma=0
##impares=1
##while cont<=n:
## suma=suma+impares
## impares=impares+2
## print(cont,impares,suma)
## cont=cont+1
# Ciclos for
#1
#Realizar un programa que imprima la tabla del número que el usuario desee (desde el 1 al 10). Hacer ahora una versión con ciclos for.
##n=int(input("Ingrese un numero:"))
##for i in range(1,10+1):
## print(n,"x",i,"=",n*i)
# 2
##Escribir un programa que le pregunte al usuario un número entero positivo N, y que calcule su factorial ( N! )
## (ej: 5!=5*4*3*2*1)
##N=int(input("Ingrese un entero positivo:"))
##factorial=1
##for i in range(1,N+1):
## factorial=factorial*i
## print(i,factorial)
# 3
##Escribir un programa que le pida al usuario dos números. Devuelve el primer número elevado al segundo. ()
##n=int(input("Ingrese un numero:"))
##m=int(input("Ingrese un numero:"))
##print(m**2)
## 4
##Escribir un programa que le pida al usuario números (la cantidad que el usuario desee) y calcule el promedio
##cantidad=int(input("Ingrese la cantidad de numeros:"))
##suma=0
##for i in range(1,cantidad+1):
## numero=int(input("Ingrese numeros:"))
## suma=suma+numero
##print(suma/cantidad)
## 5
##Escribir un programa que le pregunte al usuario un número entero positivo n y que calcule la parte entera de
##import math
##print ("Este programa calcula parte entera de la raiz cuadrada")
##n=int(input("Ingrese un numero"))
##i=1
##while(i*i<=n):
## i=i+1
##
##print("La parte entera de la raiz cuadrada de",n,"es: ",i-1)
##
##if(int(math.sqrt(n))==i-1):
## print("Bien resuelto")
##else:
## print("ERROR"
##(solo para ingeniosos) Escribir un programa que le pregunte al usuario un número entero positivo N, y que
##muestre por pantalla la cantidad de cifras que tiene. (Ej: 1492 tiene 4 cifras)
##print ("Este programa calcula la cantidad de cifras de un numero")
##n=int(input("Ingrese un numero"))
##if n==0:
## print("El numero tiene 1 cifra")
##else:
## if n<0:
## n=n*(-1)
## cont=0
## while(n>=1):
## n=n/10
## cont=cont+1
## print("El numero tiene",cont,"cifras")
##n=int(input("Ingrese un numero"))
##cantCifras=len(str(n))
##print(n,"Tiene:",cantCifras,"cifras")
# Pracica 3
##Ejercicio 1 F
##a) Hacer un programa que muestre, mediante un ciclo, los primeros 5 números naturales
##(1, 2, 3, 4 y 5).
##b) Hacer un programa que permita al usuario elegir un número n y luego muestre los
##primeros n números naturales (1, 2, · · · , n).
##inicio=1
##while inicio<=5:
## print(inicio,end="")
## inicio=inicio+1
##for i in range(1,5+1):
## print(i,end=",")
#b
##n=int(input("Ingrese un numero:"))
##for i in range(1,n+1):
## print(i,end=",")
##Ejercicio 2 F
##a) Hacer un programa que muestre, mediante un ciclo, los números desde el 4 hasta el
## 7 (4, 5, 6 y 7).
##b) Hacer un programa que permita al usuario elegir un número m y un n y luego
##muestre todos los naturales entre m y n (m, m + 1, m + 2, · · · , n − 1, n). ¾Qué pasa
##si n es menor que m?
##inicio=4
##while inicio<=7:
## print(inicio,end=",")
## inicio=inicio+1
##m=int(input("Ingrese un numero:"))
##n=int(input("Ingrese un numero:"))
##inicio=m
##while inicio<=n:
## print(inicio,end=",")
## inicio=inicio+1
## Ejercicio 3 F
## a) Hacer un programa que muestre, mediante un ciclo, los 5 números naturales que le
## siguen al 10 (11, 12, · · · , 15).
## b) Hacer un programa que permita al usuario elegir un número n y luego muestre los
## 5 números naturales que le siguen a n (n + 1, n + 2, · · · , n + 5).
## c) Hacer un programa que permita al usuario elegir un número n y un número c, y
## luego muestre los c números naturales que le siguen a n (n + 1, n + 2, · · · , n + c).
##inicio=10
##while inicio<=15:
## print(inicio,end=",")
## inicio=inicio+1
##n=int(input("Ingrese un numero:"))
##inicio=n
##fin=n+5
##while inicio<=fin:
## print(inicio,end=",")
## inicio=inicio+1
##n=int(input("Ingrese un numero:"))
##c=int(input("Ingrese un numero:"))
##inicio=n
##fin=c
##while inicio<=fin:
## print(inicio,end=",")
## inicio=inicio+1
##n=int(input("Ingrese un numero:"))
##c=int(input("Ingrese un numero:"))
##for i in range(n,c+1):
## print(i,end=",")
##Ejercicio 4 F
##a) Hacer un programa que muestre, mediante un ciclo, los números desde el 5 hasta el
##11 salteando de a 2 elementos (5, 7, 9 y 11)
##b) Hacer un programa que permita al usuario elegir un número m y un n y luego
##muestre todos los naturales entre m y n, pero salteando de a 3. Por ejemplo, si el
##usuario ingresara un n igual a 2 y un m igual a 14, el programa deberá mostrar
##2, 5, 8, 11, 14.
##c) Hacer un programa que permita al usuario elegir un número n, un m y un p y
##luego muestre todos los naturales entre m y n, pero salteando de a p números. Por
##ejemplo, si el usuario ingresara un n igual a 2 y un m igual a 14, y un p igual a 4,
##el programa deberá mostrar 2, 6, 10, 14.
##inicio=5
##fin=11
##while inicio<=fin:
## print(inicio,end=",")
## inicio=inicio+2
##Ejercicio 8
##a) Hacer un programa que reciba un número n y muestre todas las potencias de 2
##menores a n. Por ejemplo, si el usuario ingresa 20, el programa mostrará: 1 2 4 8
##16. Ayuda: pensar primero si sería más práctico utilizar la sentencia while o for.
##b) Hacer un programa que reciba un número n (n > 0) y muestre las n primeras
##potencias de 2. Por ejemplo, si el usuario ingresa 6, el programa mostrará: 1 2 4 8
##16 32.
##c) Hacer un programa que reciba un número n (n > 0) y muestre las n primeras
##potencias de n. Por ejemplo, si el usuario ingresa 4, el programa mostrará: 1 4 27
##256. Es decir, 1**1 2**2 3**3 4**4
#a)
##n=int(input("Ingrese un numero:"))
##inicio=1
##while inicio<=n:
## print(inicio)
## inicio=inicio*2
#b)
##n=int(input("Ingrese un numero:"))
##potencia=1
##cont=1
##while cont<=n:
## print(potencia)
## potencia=potencia*2
## cont=cont+1
# c
##n=int(input("Ingrese un numero:"))
##potencia=1
##inicio=1
##while inicio<=n:
## print(potencia**potencia)
## potencia=potencia+1
## inicio=inicio+1
##Ejercicio 9
##a) Hacer un programa que permita al usuario elegir un número positivo n y luego
##muestre en pantalla todos los divisores de n
##n=int(input("Ingrese un numero:"))
##for i in range(1,n+1):
## if n%i==0:
## print(i)
##b) Hacer un programa que permita al usuario elegir un número positivo n y luego
##muestre en pantalla todos los divisores pares de n.
##n=int(input("Ingrese un numero:"))
##for i in range(1,n+1):
## if n%i==0 and i%2==0:
## print(i)
##n=int(input("Ingrese un numero:"))
##cont=1
##while cont<=n:
## if n%cont==0 and cont%2==0:
## print(cont,end=",")
## cont=cont+1
##c) Hacer un programa que permita al usuario elegir un número positivo n y luego
##muestre en pantalla la cantidad de divisores de n
##n=int(input("Ingrese un numero:"))
##cant=0
##for i in range(1,n+1):
## if n%i==0:
## cant=cant+1
##print("La cantidad de divisores de",n,"es:",cant)
##d) Hacer un programa que permita al usuario elegir un número positivo n y luego
##muestre en pantalla la suma de los divisores de n.
##n=int(input("Ingrese un numero:"))
##suma=0
##for i in range(1,n+1):
## if n%i==0:
## suma=suma+i
##print("La suma de los divisores de",n,"es",suma)
##e) Hacer un programa que permita al usuario elegir dos números positivos c y n y luego
##muestre en pantalla los primeros c divisores de n
##n=int(input("Ingrese un numero:"))
##c=int(input("Ingrese un numero:"))
##k=0
##i=1
##while k<c and i<=n:
## if n%i==0:
## k=k+1
## print (k,"- divisor de ",n,"es ",i)
## i=i+1
##if k<c:
## print("No hay mas divisores")
##f) Hacer un programa que permita al usuario elegir dos números positivos c y n y luego
##muestre en pantalla los últimos c divisores de n
##n=int(input("Ingrese un numero:"))
##c=int(input("Ingrese un numero:"))
##k=0
##i=1
##Ejercicio 10
##Hacer un programa que permita al usuario elegir un número positivo n y luego muestre en
##pantalla el producto (es decir, la multiplicación) de los numeros entre 1 y n.
##n=int(input("Ingrese un numero:"))
##cont=1
##producto=1
##while cont<=n:
## producto=producto*cont
## cont=cont+1
## print(producto)
##Ejercicio 11
##Hacer un programa que reciba un número m y determine el primer n para el cual la suma
##1+2+...+n > m. Por ejemplo, si el usuario ingresa 11 se deberá retornar 5 ya que 1+2+3+4 =
##10 < 11 y 1 + 2 + 3 + 4 + 5 = 15 > 11
##m=int(input("Ingrese un numero:"))
##suma=0
##i=0
##while suma<=m:
## i=i+1
## suma=suma+i
##print("El primer n para el cual la suma supera a",m,"es",i)
##Ejercicio 12
##a) Hacer un programa que permita al usuario elegir un número positivo n y luego
##muestre en pantalla los n primeros términos de la sucesión an = 2n. Es decir 2, 4,
##6...
##n=int(input("Ingrese un numero:"))
##for i in range(1,n+1):
## sucesion=2*i
## print(sucesion,end=", ")
##b) Idem anterior para la sucesión an = 2n − 1.
##n=int(input("Ingrese un numero:"))
##for i in range(1,n+1):
## sucesion=(2*i)-1
## print(sucesion,end=", ")
##c) Idem anterior para la sucesión an = n**2
##n=int(input("Ingrese un numero:"))
##for i in range(1,n+1):
## sucesion=i**2
## print(sucesion,end=", ")
##d) Idem anterior para la sucesión an = n**3 − n**2
##n=int(input("Ingrese un numero:"))
##for i in range(1,n+1):
## sucesion=(i**3) - (i**2)
## print(sucesion,end=", ")
##e) Idem anterior para la sucesión an =1/n**2
##n=int(input("Ingrese un numero:"))
##for i in range(1,n+1):
## sucesion= 1/i**2
## print(sucesion,end=", ")
##Ejercicio 13
##a) Hacer un programa que permita al usuario elegir un número positivo n y luego
##muestre en pantalla las n primeras sumas parciales de la sucesión an = 2n. Es decir,
##2 6 12 20...
##n=int(input("Ingrese un numero:"))
##suma=0
##for i in range(1,n+1):
## suma=suma+2*i
## print(suma,end=", ")
##b) Idem anterior para la sucesión an = n**2
##n=int(input("Ingrese un numero:"))
##for i in range(1,n+1):
## suma=suma+i**2
## print(suma,end=", ")
##Ejercicio 14 F
##El logaritmo natural de 2 (ln(2)) se puede aproximar de la siguiente manera:
##ln(2) = 1 − 1/2 + 1/3 − 1/4 + 1/5
##n=int(input("Ingrese un numero:"))
##suma=0
##for i in range(1,n+1):
## if i%2!=0:
## suma=suma+1/i
## else:
## suma=suma-1/i
##print("La suma de los",n,"terminos es:",suma)
## Ejercicio 15 F
## El número 1/4 π se puede aproximar de la siguiente manera: 1/4π =
## 1 − 1/3 + 1/5 − 1/7 + 1/9 − 1/11 + 1/13 − 1/15
##n=int(input("Ingrese un numero:"))
##suma=0
##signo=1
##var=1
##for i in range(1,n+1):
## suma=suma+signo*(1/var)
## var=var+2
## signo=signo*-1
##print(suma)
##Ejercicio 16 F
##Escribir un programa que solicite al usuario un número positivo y aproxime
##el valor del número e de la siguiente manera: (ejemplo para 7 términos)
#1/0!+1/1!+1/2!+1/3!+1/4!+1/5!+1/6!
##n=int(input("Ingrese un numero:"))
##suma=1
##factorial=1
##for i in range(1,n):
## factorial=factorial*i
## suma=suma+1/factorial
##print(suma)
##Ejercicio 17
##a) Hacer un programa que permita al usuario elegir un número m y un n y muestre
##pares de numeros complementarios, o sea (m, n)(m + 1, n − 1)(m + 2, n − 2). . .(n −
##1, m + 1)(n, m). Por ejemplo, el usuario ingresa 5 y 10, 5 será el complementario de
##10, 6 el de 9 y 7 el de 8, y deberá mostrarse:
## 5 10
## 6 9
## 7 8
## 8 7
## 9 6
## 10 5
##m=int(input("Ingrese un numero:"))
##n=int(input("Ingrese un numero:"))
##
##aux=n
##cont=m
##while cont<=n:
## print(cont,aux)
## aux=aux-1
## cont=cont+1
##Ejercicio 18 F ♣
##a) Escribir un programa que permita al usuario elegir un número m y un n y muestre
##todos los pares de numeros que se pueden formar con los números que están entre
##ellos. Por ej. si el usuario ingresara 4 y 6, el programa deberá mostrar
## 4 4
## 4 5
## 4 6
## 5 4
## 5 5
## 5 6
## 6 4
## 6 5
## 6 6
##m=int(input("Ingrese un numero:"))
##n=int(input("Ingrese un numero:"))
##for i in range(m,n+1):
## for j in range(m,n+1):
## print(i,j)
##Ejercicio 19 ♣
##a) Escribir un programa que permita al usuario elegir un número m y un n y muestre
##todos los pares de numeros que se pueden formar con los números que están entre
##ellos, pero esta vez que lo haga sin repetir inversos. Por ej. si el usuario ingresara 4
##y 6, el programa deberá mostrar
##4 4
##4 5
##4 6
##5 5
##5 6
##6 6
##m=int(input("Ingrese un numero:"))
##n=int(input("Ingrese un numero:"))
##
##for i in range(m,n+1):
## for j in range(i,n+1):
## print(i,j)
## Ejercicio 20 F
## Hacer un programa que simule el juego de la quiniela. El usuario debe elegir un número del
## 0 al 99 y un monto a apostar, si acierta el número gana 70 veces lo apostado. (El número de la
## suerte debe ser elegido al azar)
##import random
##
##numero=int(input("Ingrese un numero:"))
##monto=float(input("Ingrese su monto a apostar:"))
##aleatorio=random.randint(1,99)
##print(aleatorio)
##if numero==aleatorio:
## gana=True
##else:
## gana=False
##
##if gana:
## print("Usted gano:",monto*70)
##else:
## print("Gracis por participar")
## Ejercicio 21 F
## Hacer un programa que permita al usuario jugar al piedra, papel o tijera contra
## la computadora. Se debe jugar al mejor de 5, es decir, si uno de los participantes
## consigue 3 victorias el juego termina.
##import random
##
##piedra = 0
##papel = 1
##tijera = 2
##
##seguirJugando = True
##while(seguirJugando):
##
## print("Piedra Papel Tijera")
## print("Seleccione una opcion valida")
## print("0 ) Piedra\n")
## print("1 ) Papel\n")
## print("2 ) Tijera\n")
##
## opcion = int(input("Piedra Papel Tijera\n Ingrese Opcion:\n 0 ) Piedra\n 1 ) Papel\n 2 ) Tijera\n"))
##
## opcionPC = random.randrange(0,3,1)
##
## if(opcion == piedra):
##
## if(opcionPC == piedra):
## print("Vos elegiste piedra y yo tambien")
## print("Empatamos")
## else:
## if(opcionPC == papel):
## print("Vos elegiste piedra y yo papel")
## print("Gane yo !!")
## else:
## if(opcionPC == tijera):
## print("Vos elegiste piedra y yo tijera")
## print("Ganaste vos !!")
## else:
## if(opcion == papel):
## if(opcionPC == piedra):
## print("Vos elegiste papel y yo piedra")
## print("Ganaste vos !!")
## else:
## if(opcionPC == papel):
## print("Vos elegiste papel y yo papel")
## print("Empatamos")
## else:
## if(opcionPC == tijera):
## print("Vos elegiste papel y yo tijera")
## print("Gane yo !!")
## else:# if(opcion == tijera):
## if(opcionPC == piedra):
## print("Vos elegiste tijera y yo piedra")
## print("Gane yo !!")
## else:
## if(opcionPC == papel):
## print("Vos elegiste tijera y yo papel")
## print("Ganaste vos !!")
## else:
## if(opcionPC == tijera):
## print("Vos elegiste tijera y yo tijera")
## print("Empatamos")
##
## print("Presiona 1 para salir y cualquier otra para seguir jugando\n")
## respuesta = int(input("Presiona 1 para salir y cualquier otra para seguir jugando\n"))
## if(respuesta == 1):
## seguirJugando = False
##
##print("Juego Finalizado")
##Ejercicio 22 F
##¾Para qué números enteros distintos de cero es cierto que A + B + C = A x B x C ? (lo
##curioso es que sólo hay una solución)
##a=int(input("Ingrese un numero !=0: "))
##b=int(input("Ingrese un numero !=0: "))
##c=int(input("Ingrese un numero !=0: "))
##if (a+b+c) == (a*b*c):
## print("Es cierto para A=",A,"B=",b,"C=",c)
##else:
## print("a+b+c no es igual que a*b*c")
# CADENAS ACTVIDADES
##1. Hacer un programa que dada una cadena ingresada por el usuario indique la cantidad de apariciones de la letra “a”.
##cadena=input("Ingrese una palabra:")
##cont=0
##for char in cadena:
## if char=="a":
## cont=cont+1
##print("La letra a aparece:",cont,"veces")
##2. Hacer un programa que dada una cadena ingresada por el usuario indique la cantidad de vocales
##cadena=input("Ingrese una palabra:")
##cont=0
##for char in cadena:
## if char == "a" or char == "e" or char == "i" or char == "o" or char == "u":
## cont=cont+1
##print("La cantidad de vocales que tiene la palabra:",cadena,"es:",cont)
##3. Hacer un programa que dados un caracter y una cadena indique la cantidad de apariciones de dicho caracter en la cadena.
##cadena=input("Ingrese una cadena:")
##caracter=input("Ingrese un caracter:")
##cont=0
##for char in cadena:
## if caracter == char:
## cont=cont+1
##print(cont)
##4. Hacer un programa que dados un caracter y una cadena muestre la misma
## cadena con un * en lugar de dicho carácter.
## Ejemplo: programador r
## p*og*amado*
##cadena="Programador"
##caracter="r"
##nuevaCadena=""
##for char in cadena:
## if char == caracter:
## nuevaCadena=nuevaCadena+"*"
## else:
## nuevaCadena=nuevaCadena+char
##print(nuevaCadena)
##Como ejercicio, escribí un programa que tome una cadena como parámetro y que imprima
##solo las consonantes de la cadena, en líneas separadas
##cadena="Programador"
##for char in cadena:
## if char != "o" and char != "a":
## print(char)
## Parte 2 Cadenas
## Ejercicio 23 F
## a) Escribir un programa que pida al usuario un número n y muestre una línea de n
## asteriscos. Ejemplo, para n = 8, el programa deberá mostrar:
## ********
##n=8
##for i in range(1,n+1):
## print("*",end="")
##n=8
##cont=1
##while cont<=n:
## print("*",end="")
## cont=cont+1
##b) Escribir un programa que pida al usuario un número n y muestre n líneas de
##1, 2, 3, ...n asteriscos respectivamente. Ejemplo, para n = 5, el programa deberá
##mostrar:
##*
##**
##***
##****
##*****
##n=5
##cont=1
##nueva=""
##while cont<=n:
## nueva=nueva+"*"
## print(nueva)
## cont=cont+1
##n=5
##nueva=""
##for i in range(1,n+1):
## nueva=nueva+"*"
## print(nueva)
## c)Escribir un programa que pida al usuario un número n y muestre n líneas de 2n − 1
## asteriscos respectivamente. Ejemplo, para n = 5, el programa deberá mostrar:
## *
## ***
## *****
## *******
## *********
##n=5
##asterisco="*"
##
##for i in range(1,n+1):
## salida=2*i-1
## print(salida*asterisco)
##Ejercicio 24 F
##a) Sabiendo que la pantalla de la consola tiene 80 caracteres de ancho, hacer un
## programa que, dada una palabra, la escriba en el centro de la pantalla.
##b) Hacer una programa que, dada una palabra, la escriba pegada a la derecha de la
## pantalla.
##cadena = input("ingrese una cadena")
##nuevaCadena=""
##ancho=80-len(cadena)
##mitad=ancho//2
##nuevaCadena=nuevaCadena+(" "*mitad)
##nuevaCadena=nuevaCadena+cadena
##nuevaCadena=nuevaCadena+(" "*mitad)
##print(nuevaCadena)
## b
##cadena = input("ingrese una cadena")
##nuevaCadena=""
##pegada_Derecha=80-len(cadena)
##nuevaCadena=nuevaCadena+(" "*pegada_Derecha)
##nuevaCadena=nuevaCadena+cadena
##print(nuevaCadena)
## Ejercicio 25 F
## Hacer una programa que, dada una palabra, la escriba recuadrada por asteriscos. Por ejemplo,
## si la palabra es "Ganaste", el programa debería escribir:
## ***********
## * Ganaste *
## ***********
##palabra=input("Ingrese una palabra:")
##asterisco=len(palabra)+4
##print(asterisco*"*")
##print("*",palabra,"*")
##print(asterisco*"*")
##Ejercicio 26
##Hacer un programa que dada una palabra y una letra, imprima la cantidad de apariciones de
##esa letra.
##palabra=input("Ingrese una palabra:")
##letra=input("Ingrese un letra:")
##cont=0
##for char in palabra:
## if char==letra:
## cont=cont+1
##print(cont)
##Ejercicio 27
##Escribir un programa que pida al usuario una cadena e indique si esta posee un
##diptongo (dos vocales unidas).
## Ejercicio 28
## Escribir un programa que pida al usuario una cadena y una letra y reemplace las apariciones
## de dicha letra por asteriscos. Por ejemplo, si el usuario ingresa:
## "programador"
## "r"
## el programa debe devolver "p*og*amado*"
##cadena="Programador"
##letra="r"
##nueva=""
##for char in cadena:
## if char==letra:
## nueva=nueva+"*"
## else:
## nueva=nueva+char
##print("cadena vieja:",cadena)
##print("cadena nueva:",nueva)
## Ejercicio 29
## Hacer un programa que genere una clave provisoria para la gestión online de clientes de una
## empresa. El programa le pedirá el apellido y generará una clave de 5 caracteres, tomará las
## primeras 4 consonantes de la palabra ingresada. Cuando las consonantes no alcancen a 4, las
## faltantes las reemplazará por "*". Ejemplos:
## clemente CLMN
## rivera RVR*
## oreo R***
## La clave se completará con 1 dígito generado aleatoriamente entre 0 y 9.
## Ejemplos: CLMN1 RVR*4 R***7
##import random
##apellido=input("Ingrese su apellido:")
##clave=""
##aleatorio=random.randrange(0,9)
##for char in apellido:
## if len(clave) < 4 and char !="a" and char !="e" and char !="i" and char !="o" and char !="u":
## clave=clave+char
##while len(clave)<4:
## clave=clave+"*"
##clave=clave+str(aleatorio)
##
##print(clave)
#
##Ejercicio 30
##Hacer un programa que solicite dos cadenas, nombre y apellido y arme el legajo de estudiantes
##de la universidad de la siguiente manera:
##Los 3 primeros números del legajo coinciden con los primeros del dni luego "_", luego las 3
##primeras letras del apellido y por ultimo la primera y ultima del nombre.
##Por ejemplo:
##Javier Rodriguez 38946702
##Legajo: 389_rodjr
##nombre = input("Ingrese un nombre")
##apellido = input("ingrese un apellido")
##dni = input("Ingrese un DNI")
##
##dni=input("Ingrese un DNI:")
##nombre=input("Ingrese un nombre:")
##apellido=input("Ingrese un apellido:")
##
##legajo=""
##
##for numero in dni:
## if len(legajo) <3:
## legajo=legajo+(numero)
##legajo=legajo+"_"
##cont=0
##for char in apellido:
## if cont < 3:
## legajo=legajo+char
## cont=cont+1
##
##cont=0
##for char in nombre:
## if cont==0:
## legajo=legajo+char
## if cont == len(nombre)-1:
## legajo=legajo+char
## cont=cont+1
##print(legajo)
##
|
50efc8b8bfcae4bca3c1295e639aa8865d010a00 | mwan780/softconass1 | /demo/demo09.py | 308 | 4.03125 | 4 | #!/usr/bin/python2.7 -u
# Test For Statements
i = 0
array = []
for i in xrange(1, 10) :
print i,
array.append(i)
print
print "Array Default Print"
print array
i = 0
while (i < 9 and i > -1) :
print i,
i += 1
print
print
print "Iterative Array Print"
for i in array :
print i,
print
|
9780ab7151f628558c7ec0597d6f6b7066c3f58e | Ch4uwa/PYpractise | /NameValues/valueofname.py | 968 | 3.828125 | 4 | # 46K text file containing over five-thousand first names,
# begin by sorting it into alphabetical order.
# Then working out the alphabetical value for each name,
# multiply this value by its alphabetical position in the list to obtain a name score.
#
# For example, when the list is sorted into alphabetical order,
# COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53,
# is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
#
# What is the total of all the name scores in the file?
with open('p022_names.txt') as f:
fl = f.readlines()
n = fl[0].split(",")
n = sorted(n)
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
letter_value = {}
for i in range(len(alphabet)):
letter_value[alphabet[i]] = i+1
name_score = 0
for i in range(len(n)):
tmp_score = 0
for j in range(1, len(n[i])-1):
tmp_score += letter_value[n[i][j]]
name_score += tmp_score*(i+1)
print('Total score of all names in list: ', name_score)
|
b8beeac3e320035d4a9420d5a6392cc2642bf46d | teoangelyn/2013pythonlab1 | /validate_mastervisa.py | 1,240 | 4.34375 | 4 | # validate_mastervisa.py
# validate a user input MasterCard or VISA credit card number
import re
def validate(card_no):
''' Function to validate a MasterCard or VISA credit card number'''
total = 0
for a in range(0, 16, 2):
# add value of digit multiplied by 2 to total if digit is less than 4
if int(card_no[a]) <= 4:
total = total + int(card_no[a]) * 2
# minus 9 before adding value of digit multiplied by 2 to total
else:
total = total + int(card_no[a]) * 2 - 9
# add the other digits
for b in range(1, 16, 2):
total = total + int(card_no[b])
print(total)
# modulo 10
if total % 10 == 0:
print("Credit card number is valid.")
else:
print("Credit card number is invalid.")
card_no = input("Enter your 16-digit credit card number: ")
# verify that card number is made up of 16 digits
pattern = re.compile("^[0-9]{16}$")
if not pattern.match(card_no):
print("Credit card number has to be made up of 16 numbers.")
else:
# visa
if card_no[0] == '4':
validate(card_no)
# mastercard
elif card_no[0] == '5' and 0 <= int(card_no[1]) <= 5:
validate(card_no)
|
7e5cbc34dba8ae30e59119dcc4f18a4187782e1e | Minkov/python-oop-2021-02 | /attributes_and_methods/demos_dict.py | 779 | 3.671875 | 4 | class Person:
def __init__(self, name):
self.name = name
def get_attributes_with_prefix(self, prefix):
return [key for (key) in self.__dict__.keys() if key.startswith(prefix)]
def set_later_value(self):
self.age = 17
def set_dict_value(self):
self.__dict__['something'] = 5
def __repr__(self):
return ';'.join(f'{key}={value}' for (key, value) in self.__dict__.items())
pesho = Person('Pesho')
print(pesho.__dict__)
print(pesho)
pesho.set_later_value()
print(pesho.__dict__)
print(pesho)
del pesho.age
print(pesho.__dict__)
print(pesho)
print(pesho.get_attributes_with_prefix('name'))
pesho.name_lower = 'pesho'
print(pesho.get_attributes_with_prefix('name'))
print(pesho)
pesho.set_dict_value()
print(pesho)
|
593f4edce4e6d75f35ca5312a88501fa64310377 | arturoromerou/practice_python3 | /cambio_dolar_soles.py | 216 | 4.09375 | 4 | """Convertir la cantidad de dolares ingresados por un usuario a soles y mostrar el resultado"""
print("")
dolares = 3.30
soles = float(input("Introduzca el monto a cambiar:\n"))
cambio = soles / dolares
print(cambio) |
1707e41c5f578a169cd658448ed436d6ee817a86 | NAMEs/Python_Note | /高级语法/04.py | 350 | 3.828125 | 4 |
# deque与list类似,但是有些区别
from collections import deque
q = deque(['a', 'b'])
l1 = ['a', 'b']
# print(dir(list))
# print()
# print(dir(deque))
print(q)
print(l1)
l1.append('c')
q.append('c')
print(l1)
print(q)
# l1.appendleft('d') # 列表中没有这个内置函数
q.appendleft('d')
print(l1)
print(q)
|
b3207c507ab49ae51f734465dc53e9fa1e48ef05 | johnmontejano/Tweet-Generator | /reaarrange.py | 443 | 3.671875 | 4 | import random
import sys
shuffle_words = []
def shuffle(words):
for _ in range(len(words)):
rando = words[random.randint(0,len(words)-1)]
shuffle_words.append(rando)
words.remove(rando)
return shuffle_words
if __name__ == "__main__":
word_list = sys.argv[1:]
if len(word_list) == 1:
word_list = list(word_list[0])
random_words = shuffle(word_list)
print(random_words)
|
66dd5955023cad4d323b68410cb3f940591fde02 | maykim51/ctci-alg-ds | /sort_and_search/merge_k.py | 2,673 | 3.5 | 4 | '''
!!!!!!!!!!!
part of CTCI 10.6 Big file.
[merge k sorted arrays, external sort 중 앞에꺼]
'''
import unittest
class heapNode: #heap as in ARRAY
def __init__(self, val, i=0, j=0): # i: ix of parent array, j: ix of next var in parent array
self.val = val
self.i, self.j = i, j
class minHeap:
def __init__(self, arr):
self.heap_arr = arr
self.size = len(self.heap_arr)
i = (len(arr)-1) //2
while i >= 0:
self.heapify(i)
i -= 1
def heapify(self, i):
left_ix = 2*i + 1
right_ix = 2*i +2
if left_ix < self.size and self.heap_arr[left_ix].val < self.heap_arr[i].val:
self.replace(left_ix, i)
self.heapify(left_ix)
if right_ix < self.size and self.heap_arr[right_ix].val < self.heap_arr[i].val:
self.replace(right_ix, i)
self.heapify(right_ix)
def replace(self, i, j):
temp = self.heap_arr[i]
self.heap_arr[i] = self.heap_arr[j]
self.heap_arr[j] = temp
def peek_min(self):
if self.size < 1:
return None
else:
return self.heap_arr[0]
def replace_root(self, root):
self.heap_arr[0] = root
self.heapify(0)
def merge_k_sorted_arrays(arrays):
#create minheap with first variables with arrs
k = len(arrays)
heap_arr = []
result_size = 0
for i in range(len(arrays)):
node = heapNode(arrays[i][0], i, 1)
heap_arr.append(node)
result_size += len(arrays[i])
min_heap = minHeap(heap_arr)
#traverse minheap and save min value from the minheap
#replace min with next var from its original array, if next is None, replace it with float('inf')
result = [0]*result_size
##FIX IT
for x in range(result_size):
min = min_heap.peek_min()
result[x]= min.val
if min.j < len(arrays[min.i]):
min.val = arrays[min.i][min.j]
min.j += 1
else:
min.val = float("inf")
min_heap.replace_root(min)
#return the list of result
return result
class Test(unittest.TestCase):
def test_merge_k_sorted_arrays(self):
arrays1 = [
[2, 6, 12, 34],
[1, 9, 20, 1000],
[23, 34, 90, 2000]
]
self.assertEqual(merge_k_sorted_arrays(arrays1), [1, 2, 6, 9, 12, 20, 23, 34, 34, 90, 1000, 2000])
if __name__ == '__main__':
unittest.main() |
932712d72f82365c115df66246fdbc5b9b76e964 | sumanshil/TopCoder | /TopCoder/python/misc/BinaryTreeMaximumPathSum.py | 845 | 3.671875 | 4 | class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
class Solution:
max_value = float('-inf')
def maxPathSum(self, root):
self.recursive(root)
return self.max_value
def recursive(self, root):
if not root:
return 0
l_sum = self.recursive(root.left)
r_sum = self.recursive(root.right)
total_value = root.val + l_sum + r_sum
if total_value < 0:
self.max_value = max(self.max_value, total_value)
return 0
self.max_value = max(self.max_value, total_value)
return root.val + max(l_sum, r_sum)
if __name__ == '__main__':
root = TreeNode(2)
root.left = TreeNode(1)
root.right = TreeNode(3)
sol = Solution()
print(sol.maxPathSum(root)) |
cbb9f7808b544c4b277b832d55bb84b6a2b00293 | rdargali/htx-immersive-08-2019 | /01-week/3-thursday/labs/Rawandlabs/madlib.py | 214 | 4.125 | 4 | print (f'____\'s favorite subject in school is _____!')
name = input ('What is the student\'s name?')
subject = input('What is their favorite subject?')
print (f'{name}\'s favorite subject in school is {subject}!') |
01292a1275b275e9a22acc9acf78f215fb60342c | pichuang/leetcode | /500_Keyboard_Row/Solution.py | 719 | 4.0625 | 4 | import unittest
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
line1, line2, line3 = set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')
answer = []
for word in words:
lower_word = set(word.lower())
if lower_word.issubset(line1) or lower_word.issubset(line2) or lower_word.issubset(line3):
answer.append(word)
return answer
class test_Solution(unittest.TestCase):
def test(self):
s = Solution()
self.assertEqual(s.findWords(["Hello", "Alaska", "Dad", "Peace"]), ["Alaska", "Dad"])
if __name__ == '__main__':
unittest.main() |
7ae8bf36caf5ccf1e1ba85dd3dbdd01a7978dd06 | kncalderong/codeBackUp | /python/Rosalind_programming/stronghold/expected_offspring.py | 430 | 3.65625 | 4 |
##! entry of dates
values = list()
while len(values) < 6:
entry = int(input('Please enter the number of couples for each genome:'))
values.append(entry)
print(values)
print( '-----------------')
##! probabilities and genomes
prob = [1,1,1,0.75,0.5,0]
##! math
con = 0
total = 0
for n in values:
sum = n * prob[con] * 2
print('n:',n)
print('con',prob[con])
con += 1
total = total + sum
print(total)
|
389e4eacd8a0f5276130a03328340da9cd0f4462 | shyingCy/shying_ML | /others/newTon_test.py | 197 | 3.859375 | 4 | # -*-coding:utf-8-*-
"""
测试用牛顿法求数的平凡根
"""
def newton_sqrt(x):
k = 1.0
while abs(k ** 2 - x) > 1e-10:
k = 0.5 * (k + x/k)
return k
print newton_sqrt(2)
|
851dd921b036db5eafb13fdb6d1cb9ae2778a1a4 | Sreelekshmi-60/Programming-lab | /4.2bank.py | 966 | 4.125 | 4 | class Bank_Account:
def __init__(self,Account_no,Name,Type_of_account):
self.acc_no=Account_no
self.name=Name
self.acc_type=Type_of_account
self.balance=0
def deposit(self):
amount=float(input("Enter an amount to deposit :"))
self.balance+=amount
print("Amount deposited to the account is Rs.",amount)
def display(self):
print("Your account number : ",self.acc_no)
print("Your name : ",self.name)
print("Your account type : ",self.acc_type)
print("Your balance : Rs.",self.balance)
def withdraw(self):
amount=float(input("Enter amount to withdraw : "))
if(self.balance>amount):
self.balance-=amount
print("Amount withdrawn is Rs.",amount)
else:
print("Insufficient Balance!!")
customer=Bank_Account(6021743,"John","Current")
customer.deposit()
customer.display()
customer.withdraw()
customer.display()
|
3ba3100e83278793fcbaf9911d21fa21536f6689 | yimanliu/CS5001-Fall2019-yimanliu | /Assignment-1/format-practice.py | 1,047 | 4.21875 | 4 | # part 1
animal = input("What is your favorite animal? ")
num_animals = int(input("How many {}s would you like? ".format(animal)))
print("I like {}s, too! But, {} is a lot of {}s! Maybe you should just "
"have {:.0f}!".format(animal, num_animals, animal, num_animals / 2))
# part 2
print()
flower = "Daisy"
car = "Volkswagen"
planet = "Earth"
Language = "Python"
pi = 3.1415926535
radius_of_planet_in_km = 6371
tablespoons_per_cup = 16
print("My name is {1} and I drive a {0} with a {1} painted "
"on it.".format(car, flower))
print("The circumference of {} is {:.2f} "
"kilometers.".format(planet, pi * 2 * radius_of_planet_in_km))
a1 = 10
b1 = float(a1 / tablespoons_per_cup)
a2 = 100
b2 = float(a2 / tablespoons_per_cup)
a3 = 1000
b3 = float(a3 / tablespoons_per_cup)
print("tablespoons : cups")
print("%11.0f :%8.2f" % (a1, b1))
print("%11.0f :%8.2f" % (a2, b2))
print("%11.0f :%8.2f" % (a3, b3))
print("In {}, I know how to put two curly braces next to each other, "
"like this {{}}.".format(Language))
|
e2e413c66fc074a99b986cc1e988de8cccfbf976 | atulkukreti/practice-git | /exercise.py | 433 | 3.953125 | 4 | import random
winning = random.randint(1,1000)
guess = 1
number = int(input("enter a number : "))
game_over = False
while not game_over:
if number == winning:
print(f"you win and you guessed this number in {guess} times")
game_over = True
else:
if number < winning:
print("too low")
else:
print("too high")
guess += 1
number = int(input("try again : ")) |
36db50b512d372e4bb12460359321e8ba636b7b5 | wataoka/atcoder | /abc162/b.py | 103 | 3.625 | 4 | n = int(input())
cnt = 0
for i in range(1, n+1):
if i%3!=0 and i%5!=0:
cnt += i
print(cnt) |
6f898986da7bd470f00b72138dbb1feb132ab055 | Hilgon2/prog | /PE7/PE7_5.py | 153 | 3.75 | 4 | list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for getal in list:
for nummer in list2:
print(getal * nummer) |
8ebbfa09c96cf17490e1ecc209dfad24d14f5e62 | DwanW/cohort4 | /01-getting-started/syntax.py | 1,927 | 3.90625 | 4 | # define attributes / variables
# number (int float in python)
# string
# boolean
# array
# dictionary / objects
# None
# if / else
# functions
# parameters
# returns
# arrays
# add to the front
# add to the end
# update values
# loops
# for/in
# Objects / Dictionaries
# declare object
# lookup key to retrieve the value
def define_type(item):
if type(item) is int:
return 'integer'
elif type(item) is float:
return 'float'
elif type(item) is str:
return 'string'
elif type(item) is bool:
return 'boolean'
elif type(item) is dict:
return 'dictionary'
elif type(item) is list:
return 'list'
elif type(item) is tuple:
return 'tuple'
elif type(item) is set:
return 'set'
elif type(item) is None:
return None
def is_over_fifty(num):
if num > 50:
return 'success'
else:
return 'failed'
# list methods
def my_function(num1, num2):
return num1 + num2
def list_add_start(ls, item):
ls.insert(0, item)
return ls
def list_add_end(ls, item):
ls.append(item)
return ls
def list_update_value(ls, item, idx):
ls[idx] = item
return ls
# loop methods
def for_in_loop(str):
new_list = []
for letter in str:
new_list.append(letter)
return new_list
def while_loop(data):
i = 0
my_string = ''
while(i < 3):
my_string += data
i += 1
return my_string
def dict_read_first_key(obj):
my_list = list(obj.items())
return f'the first property is {my_list[0][0]} and the value is {my_list[0][1]}'
def zip_my_lists(list1, list2):
new_list = list(zip(list1, list2))
return new_list
print(zip_my_lists([1,2,3],[4,5,6]))
def merge_sets(set1, set2):
new_set = set1.union(set2)
return new_set
print(merge_sets({1,2},{4,5}))
def email(fname, lname):
return f'{fname.lower()}.{lname.lower()}@evolveu.ca' |
4e149084923960714f994d9c89110a41cb81afe3 | joeaoregan/Python-GamesAndTutorials | /Python3-Sockets/echo_server_3.py | 634 | 3.640625 | 4 | #!/usr/bin/env python3
"""
Joe O'Regan
21/02/2019
Looping TCP Echo Server
"""
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 8888 # Port to listen on (non-privileged ports are > 1023)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
print('Echo Server: Listening for connections on', HOST, ':', PORT)
conn, address = s.accept()
print("Connection from: " + str(address))
while True:
data = conn.recv(1024).decode()
if not data:
break
print('Received from '+str(address)+': '+str(data))
conn.sendall(data.encode())
conn.close()
|
50b50bced6ebae1699f6d9b313c18ad16d9f6040 | nikoWhy/softuniPython | /slojni_proverki/figure.py | 412 | 4.09375 | 4 | h = int(input())
x = int(input())
y = int(input())
if ((x <= 3 * h and x >= 0) and (y <= h and y >= 0)):
if x == 0 or y == 0 or x == 3 * h or y == h:
print('border')
else:
print('inside')
elif ((x <= 2 * h and x >= h) and (y <= 4 * h and y >= h)):
if x == h or x == 2 * h or y == h or y == 4 * h:
print('border2')
else:
print('inside2')
else:
print('outside') |
24c7c7901084412103898f2d96d2c5a71bf07b6f | meemain/tensorflow | /multiclass_classifier_handlanguage.py | 4,195 | 3.5625 | 4 | # download sign mnist data (2 csv files) from here :https://www.kaggle.com/datamunge/sign-language-mnist
import csv
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
def get_data(filename):
# You will need to write code that will read the file passed
# into this function. The first line contains the column headers
# so you should ignore it
# Each successive line contians 785 comma separated values between 0 and 255
# The first value is the label
# The rest are the pixel values for that picture
# The function will return 2 np.array types. One with all the labels
# One with all the images
#
# Tips:
# If you read a full line (as 'row') then row[0] has the label
# and row[1:785] has the 784 pixel values
# Take a look at np.array_split to turn the 784 pixels into 28x28
# You are reading in strings, but need the values to be floats
# Check out np.array().astype for a conversion
with open(filename) as training_file:
csv_reader = csv.reader(training_file, delimiter=',')
first_line = True
temp_images = []
temp_labels = []
for rows in csv_reader:
if first_line:
print('ignore first line that contains column labels')
first_line = False
else:
temp_labels.append(rows[0])
image_data = rows[1:785]
image_data_as_array = np.array_split(image_data, 28)
temp_images.append(image_data_as_array)
images = np.array(temp_images).astype('float')
labels = np.array(temp_labels).astype('float')
return images, labels
training_images, training_labels = get_data('tmp/sign/sign_mnist_train.csv')
testing_images, testing_labels = get_data('tmp/sign/sign_mnist_test.csv')
print(training_images.shape)
print(training_labels.shape)
print(testing_images.shape)
print(testing_labels.shape)
# In this section you will have to add another dimension to the data
# So, for example, if your array is (10000, 28, 28)
# You will need to make it (10000, 28, 28, 1)
# Hint: np.expand_dims
training_images = np.expand_dims(training_images, axis=3)
testing_images = np.expand_dims(testing_images, axis=3)
print(training_images.shape)
print(testing_images.shape)
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest'
)
test_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest'
)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(64, (3, 3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(26, activation='softmax')
])
model.compile(
loss='sparse_categorical_crossentropy',
optimizer='adam',
metrics=['accuracy']
)
model.summary()
# model.fit(train_datagen.flow(training_images, training_labels, batch_size=32),
# steps_per_epoch=len(training_images) / 32,
# epochs=15,
# validation_data=test_datagen.flow(testing_images, testing_labels, batch_size=32),
# validation_steps=len(testing_images) / 32
# )
history = model.fit(train_datagen.flow(training_images, training_labels, batch_size=32),
steps_per_epoch=len(training_images) / 32,
epochs=15,
validation_data=test_datagen.flow(testing_images, testing_labels, batch_size=32),
validation_steps=len(testing_images)/32
)
model.save('sign_alphabets.h5')
model.evaluate(testing_images, testing_labels)
# The output from model.evaluate should be close to:
# [6.92426086682151, 0.56609035]
|
7e9351b102ddba5b3ad9b40171b9ae5031fff25c | IvayloSavov/Fundamentals | /More Exercises_Basic Syntax_Conditional_Statements_and_Loops/how_much_coffee_do_you_need.py | 585 | 3.78125 | 4 | command = input()
needed_coffee = 0
is_break = False
while command != "END":
event = command
is_upper = False
if event.isupper():
is_upper = True
event = event.lower()
events = (
(event == "coding") or
(event == 'dog' or event == 'cat') or
(event == "movie")
)
if events:
needed_coffee += 1
if is_upper:
needed_coffee += 1
if needed_coffee > 5:
print('You need extra sleep')
is_break = True
break
command = input()
if not is_break:
print(needed_coffee) |
8acad694919dd4960936952f06ef62294358dae2 | adonskoi/integrity | /integrity/__main__.py | 666 | 3.6875 | 4 | import sys
from .calculate import is_hash_match
from .parse import parse
def main():
if len(sys.argv) < 2:
print("please enter filename")
return
file_path = sys.argv[1]
path_to_given_files = ""
if len(sys.argv) > 2:
path_to_given_files = sys.argv[2]
try:
with open(file_path) as f:
content = f.readlines()
except:
print("file not found")
return
files = parse(content, path_to_given_files)
for one_file in files:
result = is_hash_match(one_file.path, one_file.alg, one_file.hash)
print(f"{one_file.name} {result}")
if __name__ == "__main__":
main()
|
bbb1e0c7a648c4cbf5ed646ddfcea1927a84046f | soharabhossain/BMU_Placement_Training_Python | /28th July 2021/pickle.py | 1,111 | 3.5 | 4 | # ----------------------------------------------------------------
import pickle as pk
# Serialize
f = open("pic.pk","wb")
dct = {"name":"Raj", "age":23, "Gender":"Male","marks":75}
pk.dump(dct, f)
f.close()
# De-Serialize
f = open("pic.pk","rb")
d = pk.load(f)
print(d)
f.close()
# ----------------------------------------------------------------
class Person:
def __init__(self, name, age):
self.name=name
self.age=age
def show(self):
print ("name:", self.name, "age:", self.age)
p1 = Person('Raj', 35)
print ("\n Pickling data....")
f = open("pickled.pk","wb")
pk.dump(p1,f)
f.close()
print ("\n Pickling completed....")
print ("\n Now Unpickling data....")
f = open("pickled.pk","rb")
p1 = pk.load(f)
p1.show()
# ----------------------------------------------------------------
dictn = {"text": "string", "none": None, "boolean": True, "number": 3.44, "int_list": [1, 2, 3]}
import json
print (json.dumps(dictn))
print (json.dumps(dictn, indent=4))
# ----------------------------------------------------------------
|
32a369bed50eee351aff311120069fed3dbe97d8 | aveedibya/pythonBasics | /Python_Basics.py | 3,544 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 13 11:46:14 2018
@author: Aveedibya Dey
"""
"""PYTHON DATATYPES:
Source: https://www.programiz.com/python-programming/variables-datatypes
Types: int, float, complex
Use type() function to check the type
"""
a = 5
type(a)
print(a, "is of type", type(a))
a = 2.0
type(a)
print(a, "is of type", type(a))
a = 1+2j
type(a)
print(a, "is complex number?", isinstance(1+2j,complex))
#-------------------------------------------------------------
"""Sets: Python Datatype"""
a = {1,2,3,4,5,6}
#Note: We also use curly brackets for dictionaries, but define differently
#Set will always have unique values only
#and they are always ordered in asc order
b = {1,2,2,3,4,3,4,5,6}
b==a
#Should be True
b = {3,2,4,1,2,5,6}
b==a
#Should be False? or True?
#Indexing has no meaning in Sets
#Perform set like operations - Refer 8.7.1 in Documentation
#Source: https://docs.python.org/2/library/sets.html
#-------------------------------------------------------------
"""PYTHON FUNCTIONS"""
"""
Basics of Function:
> Keyword def marks the start of function header.
> A function name to uniquely identify it.
> Parameters (arguments). They are optional.
> A colon (:) to mark the end of function header.
> Optional documentation string (docstring) to describe what the function does.
> One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).
> An optional return statement to return a value from the function.
"""
def greet(name):
"""Function greet:
docstring goes here
print(function_name.__doc___) to see what is written here
Usually write helpful things to understand the function
This function greets to the person passed in as parameter"""
print("Hello, " + name + ". Good morning!")
return None #Optional, if not specified, it returns None!
#----------------------
#Using Return option in the function
def number_to_K(num):
"""This function converts a large number into a condensed format"""
CondensedNumber = str(round(num/1000)) + "K"
return CondensedNumber
# when a function returns values you call it by using a variable
# such as a = number_to_k(num)
#----------------------
"""SCOPE and LIFETIME of variables"""
def my_func():
x = 10
print("Value inside function:",x)
x = 20 #This is the value outside my_func, not altered by value inside
my_func()
print("Value outside function:",x)
#----------------------
#GLOBAL VARIABLE
x = 100 #Outside definition
def foo():
global x #Required to operate on x defined outside the function
x+=1
print("x inside :", x)
foo()
print("x outside:", x)
#----------------------
"""PYTHON FUNCTIONS: DEFAULT ARGUMENT"""
def greetmsg(name, msg = "Good morning!"):
"""This function greets to the person with the provided message.
If message is not provided, it defaults to "Good Morning!
"""
print("Hello",name + ', ' + msg)
# an argument is a defualt argument when you assign
# value to variable in function definition
"""
> In greetmsg, name is a MANDATORY parameter, while msg is optional since
it has a default value.
> Any number of arguments in a function can have a default value
> But once we have a default argument, all the arguments to its right
must also have default values.
"""
#----------------------
"""OPTIONAL: ANONYMOUS FUNCTIONS"""
#Lambda
#Map
#Source: https://www.programiz.com/python-programming/anonymous-function
#----------------------
|
74d3bb780e3362dc16c483b7380d4ff3302c0c2a | Rakshy/coding | /Linkedlists/palindrome.py | 1,287 | 4.09375 | 4 | #logic - use fast/slow runner
#initialize 2 pointers at the head, move one at 1 place per move and the other 2 places per move.
# when the 2nd pointer reaches the end, the 1st will be pointing at the center of the list.
#store values of head 1 in an array and then compare head 2 with the array as it moves
from Linkedlists.single_LL import *
class palindrome(linkedlist):
def is_palindrome(self):
if l2.get_size()%2==0:
print('list is not a palindrome')
else:
head1=head2=self.get_root()
arr=[]
while(head2.get_next()):
arr.insert(0, head1.get_data())
head1=head1.get_next()
head2=head2.get_next()
head2 = head2.get_next()
#setting the head to start comparing
head2=head1.get_next()
for each in arr:
if head2.get_data()==each:
head2=head2.get_next()
else:
print('list is not a palindrome')
return
print('list is a palindrome')
if __name__ == '__main__':
l2=palindrome()
l2.add(1)
l2.add(2)
l2.add(3)
l2.add(4)
l2.add(3)
l2.add(2)
l2.add(1)
l2.printlist()
l2.is_palindrome() |
600c274c6c3c25b04511f8ff27dab34bef6a60fe | SachieTran/easy_sudoku | /sudokugrid.py | 4,159 | 3.84375 | 4 | # sudokugrid.py
#
# Created by: Tran Tran
#
#
# The program implements the SudokuGrid ADT that will be used to represent
# the puzzle grid.
from ezarrays import Array2D
# Values representing the empty cell on the grid.
EMPTY = 0
class SudokuGrid():
# Creates a new Sudoku grid of empty cells.
def __init__(self) :
self._grid = Array2D(9, 9)
self._grid.clear(EMPTY)
# Clears the grid and loads an initial Sudoku puzzle configuration from a
# text file, the name of which is provided as an argument.
def load(self, filename):
infile = open(filename, "r")
for line in infile :
line = line.strip()
puzzleList = line.split()
row = int(puzzleList[0])
col = int(puzzleList[1])
value = int(puzzleList[2])
self._grid[row, col] = value
infile.close()
# Sets the indicated cell to the given digit. The row and col indices
# must be within the valid range.
def setCell(self, row, col, digit):
assert row >= 0 and col >= 0 and row < 9 and col < 9, \
"Invalid cell position."
self._grid[row, col] = digit
# Clears the indicated cell. The row and col indices must be within the
# valid range.
def clearCell(self, row, col):
assert row >= 0 and col >= 0 and row < 9 and col < 9, \
"Invalid cell position."
self._grid[row, col] = EMPTY
# Returns a Boolean that indicates if the given cell is empty. The row
# and col indices must be within the valid range.
def isEmpty(self, row, col):
assert row >= 0 and col >= 0 and row < 9 and col < 9, \
"Invalid cell position."
if self._grid[row, col] == EMPTY :
return True
else :
return False
# Returns a Boolean that indicates if placing the given digit in
# the given cell is a valid move.
def isValid(self, row, col, digit):
assert row >= 0 and col >= 0 and row < 9 and col < 9, \
"Invalid cell position."
assert digit > 0 and digit <= 9, "Invalid digit."
# Check each row and column.
for i in range(9) :
if self._grid[row, i] == digit :
return False
for j in range(9) :
if self._grid[j, col] == digit :
return False
# Check each subsquare by finding its top left value.
topRow = (row // 3) * 3
topCol = (col // 3) * 3
for i in range(topRow, topRow + 3) :
for j in range(topCol, topCol + 3) :
if self._grid[i, j] == digit :
return False
return True
# Searches the grid for an open cell.
def findOpenCell(self):
for i in range(9) :
for j in range(9) :
if self.isEmpty(i, j) :
return (i, j)
return None
# Prints the grid to the terminal in the following format.
def print(self) :
print("", "-" * 23, "")
for i in range(3) :
print("|", end=" ")
for j in range(9) :
if j == 3 or j == 6 :
print("|", end=" ")
print("%d" % self._grid[i, j], end=" ")
else :
print("%d" % self._grid[i, j], end=" ")
print("|")
print("", "-" * 23, "")
for i in range(3, 6) :
print("|", end=" ")
for j in range(9) :
if j == 3 or j == 6 :
print("|", end=" ")
print("%d" % self._grid[i, j], end=" ")
else :
print("%d" %self._grid[i, j], end=" ")
print("|")
print("", "-" * 23, "")
for i in range(6, 9) :
print("|", end=" ")
for j in range(9) :
if j == 3 or j == 6 :
print("|", end=" ")
print("%d" % self._grid[i, j], end=" ")
else :
print("%d" %self._grid[i, j], end=" ")
print("|")
print("", "-" * 23, "")
|
223ebc3168491cb942b1033efcb4bec66022ad07 | altareen/csp | /03Functions/userfunctions.py | 803 | 3.828125 | 4 | def pythagoras(opp, adj, tau, epsilon):
hyp = (opp**2 + adj**2)**0.5
solution = hyp * tau + epsilon
return solution
result = pythagoras(3.2, 4.7, 1.3, 0.57)
print(result)
# a function that takes no parameters and does not return a value
def displayhello():
print("hello")
displayhello()
# a function that takes parameters and does not return a value
def displaygoodbye(note):
print("Message: "+ note)
displaygoodbye("See you later.")
# a function that takes no parameters and returns a value
def greetings():
output = "have a nice day."
return output
result = greetings()
print(result)
# a function that takes parameters and returns a value
def farewell(note, repeat):
outcome = note * repeat
return outcome
result = farewell("Take care.", 5)
print(result)
|
afdb7bacebcbcd5fdccf995a9b8f78776735ce01 | AnushreeGK/anandology-solutions | /chap1&2/wordfreq.py | 170 | 3.640625 | 4 | def word_frequency(words):
frequency = {}
for w in words:
frequency[w] = frequency.get(w, 0) + 1
return frequency
print word_frequency("qw wq qw wq")
|
fa26f280bb90a203fe0722c9d09d19744b1bd086 | jackyyy0228/RL-environment-for-Tetris-Battle | /keyboard.py | 1,456 | 3.625 | 4 | import pygame
from tetris import Tetris
key_actions=['RIGHT','LEFT','DOWN','UP','z','SPACE','LSHIFT']
delay_time= [ 150,150,200,200,200,400,450]
class Keyboard:
def __init__(self):
self.T = Tetris(action_type = 'single',is_display = True)
def run(self):
while True:
state = self.T.reset()
done = False
while not done:
flag = False
for evt in pygame.event.get():
if evt.type == pygame.QUIT:
exit()
if evt.type == pygame.KEYDOWN:
for idx,key in enumerate(key_actions):
if evt.key == eval("pygame.K_"+key):
state,_,done,_,_ = self.T.step(idx)
flag = True
pygame.time.wait(delay_time[idx])
keys_pressed = pygame.key.get_pressed()
if not flag:
for idx,key in enumerate(key_actions):
key = eval("pygame.K_"+key)
if keys_pressed[key]:
state,_,done,_,_ = self.T.step(idx)
if idx == [3,4,5,6]:
pygame.time.wait(delay_time[idx])
pygame.time.wait(10)
if __name__ == "__main__":
K = Keyboard()
K.run()
|
e34426f6a0f2e7fea665bcadddf22df77c9f7dd1 | SvetlanaTsim/python_basics_ai | /lesson_8/task_8_1.py | 1,790 | 3.796875 | 4 | """
Реализовать класс «Дата», функция-конструктор которого должна принимать дату
в виде строки формата «день-месяц-год». В рамках класса реализовать два метода.
Первый — с декоратором @classmethod. Он должен извлекать число, месяц,
год и преобразовывать их тип к типу «Число». Второй — с декоратором @staticmethod,
должен проводить валидацию числа, месяца и года (например, месяц — от 1 до 12).
Проверить работу полученной структуры на реальных данных.
"""
class Date:
#создадим переменную класса, чтобы работало без экземпляра
date = '31-08-2021'
def __init__(self, new_date):
Date.date = new_date
@classmethod
def date_to_number(cls):
day, month, year = cls.date.split('-')
return int(day), int(month), int(year)
@staticmethod
def valid_data():
day, month, year = Date.date_to_number()
if month < 1 or month > 12:
return 'Wrong month'
#для високосного не делала
if not ((day >= 1 and day <= 30 and month in [4, 6, 9, 11]) or (day >= 1
and day <= 31 and month in [1, 3, 5, 7, 8, 10, 12]) or (day >= 1 and day <= 28 and month == 2)):
return 'Wrong day'
if not (year >= 1 and year <= 2021):
return 'Wrong year'
return 'Date is alright'
my_date = Date('30-02-2021')
print(Date.date_to_number())
print(Date.valid_data())
|
d15daf400633a793f939241d3d9b6c68d298c63b | JunaidParacha/python | /raj_chetan/assignments/bubble_sort.py | 395 | 3.671875 | 4 | import random
import time
my_arr = [int(1000*random.random()) for i in xrange(20)]
def bubble_sort(arr):
start = time.time()
counter = 0
for do_times in range(len(arr)):
counter +=1
for count in range(0, len(arr)-counter):
if arr[count] > arr[count+1]:
(arr[count], arr[count+1]) = (arr[count+1], arr[count])
print arr
end = time.time()
print end - start
bubble_sort(my_arr) |
548a966107da3176f1524645f50efd7e3ce632e1 | or0986113303/LeetCodeLearn | /python/599 - Minimum Index Sum of Two Lists/main.py | 1,201 | 3.765625 | 4 | import collections
class Solution(object):
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
list1hash = {}
list2hash = {}
result = {}
for index, parts in enumerate(list1):
list1hash[parts] = index
for index, parts in enumerate(list2):
list2hash[parts] = index
target = collections.Counter(list1) if len(list1) < len(list2) else collections.Counter(list2)
sumresult = len(list1) + len(list2)
for _,key in enumerate(target.keys()):
print(key),
if key in list1 and key in list2:
result[list1hash[key] + list2hash[key]] = key
if sumresult > list1hash[key] + list2hash[key]:
sumresult = list1hash[key] + list2hash[key]
return result[sumresult]
if __name__ == '__main__':
source1 = ["Shogun","Tapioca Express","Burger King","KFC"]
source2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
result = Solution().findRestaurant(source1, source2)
print(result) |
3235cf5a894c4ac9c116a7fcbf1fadf0dfbbd50b | ericxlima/ILoveCoffee | /scrips/jogo_da_forca.py | 3,719 | 3.515625 | 4 | from random import choice
import json
class JodoDaForca:
def __init__(self, nick):
self.categorias = {'animais': ['coelho', 'cavalo', 'coruja', 'gaivota', 'porco', 'galinha',
'macaco', 'baleia', 'golfinho', 'morcego', 'girafa', 'elefante',
'castor', 'calango', 'flamingo', 'guepardo', 'hamster', 'serpente'],
'alimentos': ['pepino', 'graviola', 'espaguete', 'manteiga', 'feijoada', 'lasanha',
'palmito', 'ervilha', 'repolho', 'pamonha', 'caramelo', 'chiclete',
'gengibre', 'gelatina', 'lentilha', 'pimenta', 'sorvete'],
'geral': ['paraquedas', 'lombada', 'ventilador', 'caminhonete', 'violino', 'despertador',
'camisola', 'banheira', 'choveiro', 'mochila', 'computador', 'fotografia',
'brinquedo', 'revolver', 'esquadro', 'monitor', 'pincel', 'vasilhame']
}
self.nick = nick
self.pontuacao = 0
self.exe()
def jogar(self, categoria):
palavra = choice(self.categorias[categoria])
word_hifens = ['-' for _ in palavra]
lifes = 8
list_letters = []
while lifes > 0:
print('\n' + ''.join(word_hifens))
letter = input('Insira uma letra: ')
# Possíveis enganos
if letter in list_letters:
print('Você já digitou esta letra')
elif len(letter) != 1:
print('Você deve inserir uma única letra')
elif not letter.islower() or not letter.isalpha():
print('Você deve inserir uma letra minúscula')
else:
if letter not in palavra:
lifes -= 1
print('Não existe esta letra na palavra')
print(f'Vidas: {lifes}')
if lifes == 0:
print(f'A palavra era {palavra}')
print('Você foi enforcado! :(')
else:
position = [number for number in range(len(palavra)) if palavra[number] == letter]
for x in position:
word_hifens[x] = letter
if '-' not in word_hifens:
print(f'\nParabéns {self.nick}\nVocê adivinhou a palavra {palavra}\nVocê Sobreviveu XD !')
self.pontuacao += 100 * lifes
lifes = 0
list_letters.append(letter)
def salvar(self):
with open('etc/usuarios.json', 'r') as file:
geral = json.load(file)
for idx, pessoa in enumerate(geral['usuarios']):
if pessoa['nome'] == self.nick:
line, user = (idx, geral['usuarios'][idx])
user['pontos'] += self.pontuacao
geral['usuarios'][idx] = user
with open('etc/usuarios.json', 'w') as file2:
geral = json.dumps(geral, indent=4)
file2.write(geral)
def exe(self):
print(f'Seja Bem Vindo(a) {self.nick} ao Jogo da Forca')
user_choice = input('\nEscolha "jogar" ou "sair": ')
while user_choice != 'sair':
cat = input('Escolha uma categoria:\n- Animais\n- Alimentos\n- Geral\n>>> ').lower()
if cat in self.categorias.keys():
self.jogar(cat)
else:
print('Categoria não encontrada :(')
user_choice = input('\nEscolha "jogar" ou "sair":')
else:
self.salvar()
|
71c7dfd1340af498b21f405cb08ac7a9b8a64d2b | DivyaReddyNaredla/python_programs_practice | /constructor.py | 341 | 3.609375 | 4 | class bankaccount:
def __init__(self):#constructor
self.balance=0
def withdraw(self,amount):
self.balance-=amount
return self.balance
def deposit(self,amount):
self.balance+=amount
return self.balance
e=bankaccount()
print(e.deposit(5000)) #5000
print(e.withdraw(1000)) #1000
|
2f13ef171346b673e2acc935a84acb0571f180c9 | Marcus-Mosley/ICS3U-Unit3-01-Python | /adding.py | 551 | 4.15625 | 4 | #!/usr/bin/env python3
# Created by Marcus A. Mosley
# Created on August 2020
# This program adds two user inputted integers
def main():
# This function adds two user inputted integers
# Input
variable_x = float(input("Enter the first integer to be added: "))
variable_y = float(input("Enter the second integer to be added: "))
# Process
total = variable_x + variable_y
# Output
print("")
print("The equation is {0} + {1} = {2}"
.format(variable_x, variable_y, total))
if __name__ == "__main__":
main()
|
d9501c3078f358b0a72d1ebd9c6548f3e32eed9d | sp314/Programming-Challenges | /Challenge Files/A_Real_Challenge.py | 412 | 3.84375 | 4 | '''
Input:
The input consists of a single integer aa (1≤a≤10181≤a≤1018), the area in square meters of Old MacDonald’s pasture.
Output:
Output the total length of fence needed for the pasture, in meters.
The length should be accurate to an absolute or relative error of at most 10−610−6.
'''
import math
def fenceNeeded():
area = int(input())
return 4*math.sqrt(area)
print(fenceNeeded()) |
0cc67fde98911a9ab3890b187ec5266a8d417ebf | KR031994/bch5884 | /Python Projects/temperature/temperature.py | 341 | 4.21875 | 4 | #Python program to convert temperature from Fahrenheit to Kelvin
#Link to Repository Path:https://github.com/KR031994/bch5884.git
import sys
print("Please enter a temperature in Fahrenheit: ")
Fahrenheit=float(sys.stdin.readline())
Kelvin=273.5 + ((Fahrenheit - 32.0) * (5.0/9.0))
print("The corresponding Kelvin temperature is:",(Kelvin))
|
2df28653055e9fe1cadd2fe436547ac159bbc6c7 | jiajiabin/python_study | /day01-10/day07/作业/15_逆序返回.py | 344 | 4.28125 | 4 | # 编写函数※传入一个语句,由单词和空格组成,将每个单词逆序再拼回一个字符串
# 传入:hello world
# 返回:olleh dlrow
def reversed_order(str1):
list1 = str1.split(" ")
str2 = ""
for i in list1:
i = i[::-1] + " "
str2 += i
return str2
print(reversed_order("hello world"))
|
19c968c07f943f73a7c2dbafff00db120f1b8b0b | 7eventhCircle/Python | /dicegame.py | 968 | 4.4375 | 4 | '''This program is a number guessing game, a user will input a guess and the program will see if they are right.'''
from random import randint
from time import sleep
def get_user_guess():
guess = int(input('Guess a number: '))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1,number_of_sides)
second_roll = randint(1,number_of_sides)
max_val = number_of_sides * 2
print ('The maximum value is ',max_val)
user_guess = get_user_guess()
if user_guess > max_val:
print ('Your guess is more than the maximum allowed value, Please try again')
else:
print ('Rolling...')
sleep(2)
print (first_roll)
sleep(1)
print (second_roll)
sleep(1)
total_roll = first_roll + second_roll
print (total_roll)
print ('Result...')
sleep(1)
if user_guess == total_roll:
print ('You guess the correct number, you win!')
else:
print ('Your guess was incorrect, you lost.')
roll_dice(6) |
80b165e68760e15edb251c9d0724081b27cb2e35 | Mozikoff/geekbrains_python1 | /lesson-1/hw01_normal.py | 3,241 | 3.703125 | 4 | import math
import random
__author__ = 'Мозиков Евгений Александрович'
# Задача-1: Дано произвольное целое число, вывести самую большую цифру этого числа.
# Например, дается x = 58375.
# Нужно вывести максимальную цифру в данном числе, т.е. 8.
# Подразумевается, что мы не знаем это число заранее.
# Число приходит в виде целого беззнакового.
# Подсказки:
# * постарайтесь решить задачу с применением арифметики и цикла while;
# * при желании и понимании решите задачу с применением цикла for.
def max_digit(number):
print('The number is: {}'.format(number))
maximum = str(number)[0]
for digit in str(number)[1:]:
if digit > maximum:
maximum = digit
print('Here is the max digit: {}'.format(maximum))
# Задача-2: Исходные значения двух переменных запросить у пользователя.
# Поменять значения переменных местами. Вывести новые значения на экран.
# Решите задачу, используя только две переменные.
# Подсказки:
# * постарайтесь сделать решение через действия над числами;
# * при желании и понимании воспользуйтесь синтаксисом кортежей Python.
def swap_variables():
a = input('Please enter first value: ')
b = input('Please enter second value: ')
print('Here are your variables: a - {}, b - {}'.format(a, b))
a, b = b, a
print('Here are swapped variables: a - {}, b - {}'.format(a, b))
# Задача-3: Напишите программу, вычисляющую корни квадратного уравнения вида
# ax² + bx + c = 0.
# Коэффициенты уравнения вводятся пользователем.
# Для вычисления квадратного корня воспользуйтесь функцией sqrt() модуля math:
# import math
# math.sqrt(4) - вычисляет корень числа 4
def square_equation():
a = int(input('Enter parameter a: '))
b = int(input('Enter parameter b: '))
c = int(input('Enter parameter c: '))
print('Here are the params: a = {}, b = {}, c = {}'.format(a, b, c))
d = b * b - 4 * a * c
if d >= 0:
if d > 0:
x1 = (-b + math.sqrt(d)) / (2 * a)
x2 = (-b - math.sqrt(d)) / (2 * a)
print('Equation has two solutions: x1 = {:.2f}, x2 = {:.2f}'.format(x1, x2))
else:
x = -b / (2 * a)
print('Equation has one solution: x = {:.2f}'.format(x))
else:
print('Equation has no solutions!')
if __name__ == '__main__':
max_digit(random.randrange(999999999))
print('-----------------------------------------------')
swap_variables()
print('-----------------------------------------------')
square_equation()
|
e7fec11f6abfe037f483924d510ed607a3264992 | weiweiECNU/QBUS | /qbus6850_19_1/week6/Lecture06_Example01_Updated.py | 4,212 | 3.578125 | 4 | """
Created on Wed Mar 28 09:34:07 2017
@author: Dr Chao Wang
Revised by: Professor Junbin Gao
"""
from sklearn import tree
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
import pandas as pd
import numpy as np
# Load the dataset, please view the csv file by using excel to
# see what information is in the file
purchase_df = pd.read_csv("Lecture6_Data.csv")
# The three predictors are Income, Education and Marital Status
# which are categorical, so we use hot-one code for them
purchase_df_x = pd.get_dummies(purchase_df.iloc[:, 1:-1])
# Label is categorical too. We also need transform it to
# class label code. If there are 3 classes, the code would be
# 0, 1, or 2.
le = LabelEncoder()
y_train = le.fit_transform(purchase_df['Purchase'])
# Which of these features gives us the best split?
purchase_df_xy = purchase_df_x
purchase_df_xy['y'] = y_train #Check what this variable contains
feature_names = purchase_df_x.columns
# using the Entropy as measurement of impurity
# We assume data D in argument "rows" variable, the last column
# is label code
def h_function_entropy (rows):
classes = np.unique(rows.iloc[:, -1])
entropy_all = []
N_node = len(rows)
for k in classes:
# calcualte the proportion p(x) for each class. Now we
# have only two classes. 1 and 0.
prop_temp= len( rows[purchase_df_xy.iloc[:, -1] == k] )/N_node
entropy_temp = -(prop_temp) *np.log2(prop_temp)
entropy_all.append(entropy_temp)
entropy_all = np.array(entropy_all)
# calculate the entropy for each subset
entropy_final= np.sum(entropy_all)
return entropy_final
loss_list = []
# For each possible split subset, we calculate its entropy
for i in range(purchase_df_xy.shape[1] - 1):
# Find observations falling to the left
left_x = purchase_df_xy[purchase_df_xy.iloc[:, i] == 0]
# Add your code to find observations falling to the right
right_x = purchase_df_xy[purchase_df_xy.iloc[:, i] == 1]
# Calculate the weighted average based on sample size as the loss of this split
N_branch = len(left_x) + len(right_x)
# h_function_entropy(left_x) and h_function_entropy(right_x) are entropies of subsets
loss = (len(left_x) / N_branch) * h_function_entropy(left_x) + (len(right_x) / N_branch) * h_function_entropy(right_x)
loss_list.append(loss)
feature_index = np.argmin(loss_list)
final_left_rows = purchase_df_xy[purchase_df_xy.iloc[:, feature_index] == 0]
final_right_rows = purchase_df_xy[purchase_df_xy.iloc[:, feature_index] == 1]
n_classes = len(np.unique(purchase_df_xy.iloc[:,-1]))
value_left = np.zeros(n_classes)
value_right = np.zeros(n_classes)
for i in final_left_rows.iloc[:, -1]:
value_left[i] = value_left[i] + 1
for i in final_right_rows.iloc[:, -1]:
value_right[i] = value_right[i] + 1
print("Left node: {0}".format(value_left))
print("Right node: {0}".format(value_right))
#################################################
# using sklearn
purchase_df_x = pd.get_dummies(purchase_df.iloc[:, 1:-1])
clf = tree.DecisionTreeClassifier(max_depth = 1)
clf = tree.DecisionTreeClassifier(criterion='entropy', max_depth = 1)
clf = clf.fit(purchase_df_x, y_train)
# sklearn tree class assignment
print(clf.tree_.value[1:3])
clf.feature_importances_
most_likely_class = clf.predict(purchase_df_x.iloc[1,:])
print(most_likely_class)
# visualising trees
# Unless you have installed pydotplus, you can uncomment this
"""
import pydotplus
from sklearn.externals.six import StringIO
from IPython.display import Image, display
# Create a string buffer to write to (a fake text file)
f = StringIO()
# Write the tree description data to the file
tree.export_graphviz(clf, out_file=f)
# Produce a visulation from the file
graph = pydotplus.graph_from_dot_data(f.getvalue())
display(Image(graph.create_png()))
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'
"""
|
6033199b01c20593c1697ab3d2f2dbe9491df78a | alamyrjunior/pythonExercises | /ex019.py | 319 | 3.515625 | 4 | import random
aluno1 = input('Digite o nome do primeiro aluno: ')
aluno2 = input('Digite o nome do segundo aluno: ')
aluno3 = input('Digite o nome do terceiro aluno: ')
aluno4 = input('Digite o nome do quarto aluno: ')
r = random.choice([aluno1, aluno2, aluno3, aluno4])
print('O aluno escolhido foi',r)
|
16c0f3a391c21fbc4a30b97f21f7a60b6dff5fda | riodementa/Python_Michigan-University | /9_1.py | 160 | 3.859375 | 4 | fhand = open("words.txt")
my_dict=dict()
for line in fhand:
for word in line.split():
my_dict[word]=1
print "Rio" in my_dict
print "or" in my_dict
|
1329d04d1c92d7463477aae42b18b8860bcc531f | Exia01/Python | /Self-Learning/Algorithm_challenges/sum_pairs.py | 792 | 3.75 | 4 | # Write a function called sum_pairs which accepts a list and a number and returns the first pair of numbers that sum to the number passed
# to the function
def sum_pairs(val_list, num):
x = 1
list_length = len(val_list) - 1
for index in range(list_length):
temp_sum = val_list[index] + val_list[x]
if temp_sum == num:
return [val_list[index], val_list[x]]
x += 1
return []
#Test Cases
print(sum_pairs([4,2,10,5,1], 6)) # [4,2]
print(sum_pairs([11, 20, 4, 2, 1, 5], 100)) # []
# Refractored
# def sum_pairs(ints, s):
# already_visited = set()
# for i in ints:
# difference = s - i
# if difference in already_visited:
# return [difference, i]
# already_visited.add(i)
# return [] |
c8e357d45a0b6456d6b1a542944d526ec357a557 | flateric94/python | /cupge/tp3/morpion_1ere_version.py | 8,422 | 3.765625 | 4 | #triangle de pascal
def pascal(N): #N:numero de la ligne avec premiere ligne à 1
liste=[[1],[1,1]] #je definie la 1ere et la 2eme ligne
print(liste[0])
print(liste[1])
for i in range(2,N): #je m'occupe des nouvelles lignes
liste.append([1]) #chaque ligne commence par un 1
for j in range(1,i): #je m'occupe des nouveaux termes, en sachant qu'il y a un 1 en debut de ligne
liste[i].append(liste[i-1][j-1] + liste[i-1][j]) #calcul du j^ieme terme
liste[i].append(1) #chaque ligne finie par un 1
print(liste[i])
def pascal(N):
#attention! N commence à 1
#je definie la 1ere et la 2eme ligne
liste=[[1],[1,1]]
# print(liste[0])
# print(liste[1])
if N==1:
return([1])
if N==2:
return([1,1])
if N==3:
return([1,2,1])
#je m'occupe des nouvelles lignes
for i in range(2,N):
#chaque ligne commence par un 1
liste.append([1])
#je m'occupe des nouveaux termes, en sachant qu'il y a un 1 en debut de ligne
for j in range(1,i):
#calcul du j^ieme terme
liste[i].append(liste[i-1][j-1] + liste[i-1][j])
#chaque ligne finie par un 1
liste[i].append(1)
return(liste[i])
print(pascal(3)) #fonctionne pour N>2
for i in range(1,9):
print(pascal(i))
179 cupge/tp3/morpion.py
@@ -0,0 +1,179 @@
""" question1)
créer une classe morpion() et sa fonction init qui définit l'état initial du plateau de jeu.
On notera le plateau par une liste, emplie initialement de zéros 3*3. La classe doit prendre
en argument le nom du joueur qui commence ("humain" ou "ordinateur").
"""
# "apprehendez les classes, openclassroom" :
#https://openclassrooms.com/fr/courses/235344-apprenez-a-programmer-en-python/232721-apprehendez-les-classes
import random as rd
class morpion: #défition de notre classe morpion
"""Classe définissant l'état initial du plateau de jeu par :
- le type de plateau, ici 3*3
- le nom de l'utilisateur"""
def __init__(self, nom): # Notre méthode constructeur
self.plateau=[[0,0,0],[0,0,0],[0,0,0]]
self.nom=nom
if nom != "utilisateur" and nom != "ordinateur":
print("error")
""" question2)
écrire une fonction afficher_plateau() qui permet d'afficher le plateau ligne par ligne avec des
croix à la place des -1, des ronds à la place des 1, et rien à la place des 0.
"""
def afficher_plateau(self):
for i in range(3):
ligne = []
for j in range(3):
if self.plateau[i][j]==1:
ligne.append("o")
elif self.plateau[i][j]==-1:
ligne.append("x")
elif self.plateau[i][j]==0:
ligne.append(" ")
print(ligne)
""" question3)
écrire une fonction joueur_humain() qui vous permet via input() de dire où vous voulez jouer
en numéro de ligne et de colonne. Cette fonction doit gérer le fait que vous n'avez le droit de
jouer que dans une case vide.
"""
def joueur_humain(self):
# choix de la ligne et vérification de son existence
print("choisissez la ligne : ")
ligne=int(input())
if ligne>2 or ligne<0:
print("les lignes existantes sont entres 0 et 2")
joueur_humain(self)
# choix de la colonne et vérification de son existence
print("choisissez la colonne : ")
colonne=int(input())
if colonne>2 or colonne<0:
print("les colonnes existantes sont entres 0 et 2")
joueur_humain(self)
#vérification case vide
if self.plateau[ligne][colonne] != 0:
print("joue dans une case vide")
joueur_humain(self)
#la case se remplit
else:
self.plateau[ligne][colonne]=1
print(afficher_plateau(self))
"""question4)
écrire une fonction trouver_cases_vides() qui renvoie une liste des indices (lignes, colonnes)
des cases vides.
"""
def trouver_cases_vides(self):
liste_indice_cases_vides=[]
for i in range(3):
for j in range(3):
if self.plateau[i][j]==0:
liste_indice_cases_vides.append((i,j))
return(liste_indice_cases_vides)
"""question5)
écrire une fonction joueur_aleatoire() qui joue aléatoirement dans une des cases vides.
"""
def joueur_aleatoire(self):
L=trouver_cases_vides(self)
(i,j)=rd.choice(L)
self.plateau[i][j]=-1
print(afficher_plateau(self))
"""question6)
ecrire une fonction partie_gagnee() qui renvoie le joueur gagnant : None, "humain",
ou "ordinateur", en fonction des règles du jeu du morpion.
"""
def partie_gagnee(self):
resultat = 0
# afficher_plateau(self)
if self.plateau[0][0]==1 and self.plateau[0][1]==1 and self.plateau[0][2]==1:
resultat=1
if self.plateau[1][0]==1 and self.plateau[1][1]==1 and self.plateau[1][2]==1:
resultat=1
if self.plateau[2][0]==1 and self.plateau[2][1]==1 and self.plateau[2][2]==1:
resultat=1
if self.plateau[0][0]==1 and self.plateau[1][0]==1 and self.plateau[2][0]==1:
resultat=1
if self.plateau[0][1]==1 and self.plateau[1][1]==1 and self.plateau[2][1]==1:
resultat=1
if self.plateau[0][2]==1 and self.plateau[1][2]==1 and self.plateau[2][2]==1:
resultat=1
if self.plateau[0][0]==1 and self.plateau[1][1]==1 and self.plateau[2][2]==1:
resultat=1
if self.plateau[0][2]==1 and self.plateau[1][1]==1 and self.plateau[2][0]==1:
resultat=1
else:
if self.plateau[0][0]==-1 and self.plateau[0][1]==-1 and self.plateau[0][2]==-1:
resultat=2
if self.plateau[1][0]==-1 and self.plateau[1][1]==-1 and self.plateau[1][2]==-1:
resultat=2
if self.plateau[2][0]==-1 and self.plateau[2][1]==-1 and self.plateau[2][2]==-1:
resultat=2
if self.plateau[0][0]==-1 and self.plateau[1][0]==-1 and self.plateau[2][0]==-1:
resultat=2
if self.plateau[0][1]==-1 and self.plateau[1][1]==-1 and self.plateau[2][1]==-1:
resultat=2
if self.plateau[0][2]==-1 and self.plateau[1][2]==-1 and self.plateau[2][2]==-1:
resultat=2
if self.plateau[0][0]==-1 and self.plateau[1][1]==-1 and self.plateau[2][2]==-1:
resultat=2
if self.plateau[0][2]==-1 and self.plateau[1][1]==-1 and self.plateau[2][0]==-1:
resultat=2
if resultat==1:
return("humain")
if resultat==2:
return("ordinateur")
else:
return None
"""question8)
mettre tout cela ensemble via une fonction jouer() qui permet effectivement de jouer contre l'ordinateur.
Et battez-le : c'est très facile contre un joueur aléatoire.
Idée : il faut une boucle while qui ne se termine que si partie gagnée ou nulle, et trouver d'alterner
à qui c'est le tour de jouer.
"""
def jouer(self):
afficher_plateau(self)
print("quel joueur commence ? : (U : Utilisateur / O : Ordinateur)")
joueur_qui_commence=str(input())
if joueur_qui_commence != "U" and joueur_qui_commence != "O":
return("veuillez mettre un nom correct")
print("quel autre joueur joue ? : (U : Utilisateur / O : Ordinateur)")
autre_joueur=str(input())
if autre_joueur != "U" and autre_joueur != "O":
return("veuillez mettre un nom correct")
while partie_gagnee(self) != "humain" or partie_gagnee(self) != "ordinateur" or partie_gagnee(self) != None:
for i in range(9):
if (i%2==0):
print(joueur_qui_commence)
if joueur_qui_commence == "U":
joueur_humain(self)
else:
joueur_aleatoire(self)
if (i%2==1):
print(autre_joueur)
if autre_joueur == "U":
joueur_humain(self)
else:
joueur_aleatoire(self)
if partie_gagnee(self)== "humain" or partie_gagnee(self)== "ordinateur":
print(partie_gagnee(self))
print("fin de partie")
return
break
test=morpion("utilisateur")
jouer(test)
|
06d9702c4d44fc06dca98c158e8187fdff8cb0fe | zzy1120716/my-nine-chapter | /ch02/related/0183-wood-cut.py | 1,447 | 3.75 | 4 | """
183. 木材加工
有一些原木,现在想把这些木头切割成一些长度相同的小段木头,需要得到的小段的数目至少为 k。
当然,我们希望得到的小段越长越好,你需要计算能够得到的小段木头的最大长度。
样例
有3根木头[232, 124, 456], k=7, 最大长度为114.
挑战
O(n log Len), Len为 n 段原木中最大的长度
注意事项
木头长度的单位是厘米。原木的长度都是正整数,我们要求切割得到的小段木头的长度也要求是整数。
无法切出要求至少 k 段的,则返回 0 即可。
"""
# 基于答案值域的二分法
class Solution:
"""
@param L: Given n pieces of wood with length L[i]
@param k: An integer
@return: The maximum length of the small pieces
"""
def woodCut(self, L, k):
if not L:
return 0
start, end = 1, max(L)
while start + 1 < end:
mid = (start + end) // 2
if self.get_pieces(L, mid) >= k:
start = mid
else:
end = mid
if self.get_pieces(L, end) >= k:
return end
if self.get_pieces(L, start) >= k:
return start
return 0
def get_pieces(self, L, length):
pieces = 0
for l in L:
pieces += l // length
return pieces
if __name__ == '__main__':
print(Solution().get_pieces([232, 124, 456], 7)) |
bc4e838330af81d19ddd69bfb7de88d64f7f964c | aniketmandalik/ProjectEuler | /Problem053.py | 381 | 3.703125 | 4 | from timeit import default_timer as timer
from math import factorial
def combinatoric_selections(n, a):
total = 0
for i in range(1, n + 1):
for j in range(1, i + 1):
options = factorial(i)/factorial(j)/(factorial(i - j))
if options > a:
total += 1
return total
start = timer()
print(combinatoric_selections(100, 1000000))
end = timer()
print("Time: ", end - start) |
916b03bb93664be3f52471167b1319d61708c28e | OsmanCekin/Programming_V1B_OsmanCekin | /Opdracht 10/Final Assignment.py | 2,692 | 3.9375 | 4 | def inlezen_beginstation(stations):
laatsteHalte = 'maastricht'
invoerBeginstation = input('Wat is je beginstation?: ').lower()
if invoerBeginstation == laatsteHalte:
print(laatsteHalte + ' is de laatste halte. Vul een andere beginstation in.')
elif invoerBeginstation in stations:
return invoerBeginstation
else:
print('Deze trein komt niet in ' + invoerBeginstation)
return inlezen_beginstation(stations)
def inlezen_eindstation(stations, beginstation):
invoerEindstation = input('Wat is je eindstation?: ').lower()
if invoerEindstation in stations:
if is_eindstation_verder_dan_beginstation(stations.index(beginstation), stations.index(invoerEindstation)):
return invoerEindstation
else:
print('Deze trein komt niet in ' + invoerEindstation)
else: print('Station bestaat niet ' + invoerEindstation)
return inlezen_eindstation(stations, beginstation)
def omroepen_reis(stations, beginstation, eindstation):
indexEindstation = (stations.index(eindstation))
indexBeginstation= (stations.index(beginstation))
deHoeveelsteBeginstation = '\n' + 'Het beginstation ' + beginstation + ' is het ' + str(indexBeginstation + 1) + 'e station in het traject.'
deHoeveelsteEindstation = 'Het eindstation ' + eindstation + ' is het ' + (str(indexEindstation + 1)) + 'e station in het traject.'
afstandAantalStations = 'De afstand bedraagt ' + str(indexEindstation - indexBeginstation) + ' station(s)'
prijsPerTreinhalte = int(5)
prijsTreinKaartje = 'De prijs van het kaartje is ' + str((indexEindstation - indexBeginstation) * prijsPerTreinhalte) + ' euro.' + '\n'
waarPersoonInstapt = 'Jij stapt in de trein in : ' + beginstation
tussenStops = stations[(indexBeginstation + 1):indexEindstation]
waarPersoonUitstapt = 'Jij stapt uit de trein in: ' + eindstation
print(deHoeveelsteBeginstation)
print(deHoeveelsteEindstation)
print(afstandAantalStations)
print(prijsTreinKaartje)
print(waarPersoonInstapt)
for stations in tussenStops:
print(str('- ') + stations)
print(waarPersoonUitstapt)
def is_eindstation_verder_dan_beginstation(indexBeginstation, indexEindstation):
return indexBeginstation < indexEindstation
stations = ['schagen', 'heerhugowaard', 'alkmaar', 'castricum', 'zaandam', 'amsterdam sloterdijk', 'amsterdam centraal', 'amsterdam amstel', 'utrecht centraal', "'s-hertogenbosch", 'eindhoven', 'weert', 'roermond', 'sittard', 'maastricht']
beginstation = inlezen_beginstation(stations)
eindstation = inlezen_eindstation(stations, beginstation)
omroepen_reis(stations, beginstation, eindstation) |
d0d2621df97a7eefb4b86d423d62cf0dd90b3045 | AnjuBA99/pythonlab | /Excercise4.py | 145 | 3.796875 | 4 | mvalue=1.8
addvalue=32
cel=int(input("Enter temperature in celsius:"))
fah=(cel*mvalue)+addvalue
print("Temperature in fahrenheit is:",fah)
|
5d2f7f98d7e2ab0ff8346c87ca49169d64c51faa | syurskyi/Python_Topics | /095_os_and_sys/examples/realpython/021_Copying Directories.py | 741 | 3.515625 | 4 | # While shutil.copy() only copies a single file, shutil.copytree() will copy an entire directory and everything
# contained in it. shutil.copytree(src, dest) takes two arguments: a source directory and the destination directory
# where files and folders will be copied to.
#
# Here’s an example of how to copy the contents of one folder to a different location:
#
import shutil
shutil.copytree('data_1', 'data1_backup')
# 'data1_backup'
#
# In this example, .copytree() copies the contents of data_1 to a new location data1_backup and returns the destination
# directory. The destination directory must not already exist. It will be created as well
# as missing parent directories. shutil.copytree() is a good way to back up your files.
|
971aaf789b09ca50fa2d67982deb71646a65a051 | matrix-lab/machine-learning | /jiangruikai/Project/Task0.py | 1,124 | 3.765625 | 4 | #coding:utf-8
"""
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务0:
短信记录的第一条记录是什么?通话记录最后一条记录是什么?
输出信息:
"First record of texts, <incoming number> texts <answering number> at time <time>"
"Last record of calls, <incoming number> calls <answering number> at time <time>, lasting <during> seconds"
"""
def print_text(data, index):
text = data[index]
print(
"First record of texts, {} texts {} at time {}".format(text[0], text[1], text[2]))
def print_call(data, index):
call = data[index]
print(
"Last record of calls, {} calls {} at time {}, lasting {} seconds".format(call[0], call[1],
call[2], call[3]))
print_text(texts, 0)
print_call(calls, -1)
|
dc7803ffb304fdf313a122ae198e601be87e07ca | trevorDarley/BoilerCode2017 | /variables.py | 249 | 3.875 | 4 | age = 16 #Defining age
num1 = 5
num2 = 6
print "I am %d years old" %age #print age in formatted format
print "If I add %d, %d and %d I get %d" % (age, num1, num2, age + num1 + num2) #adds numbers
print "\nHello \t\t world\n" #Tabbed Hello world
|
a14d0a480d79e15d1f7c06ee46f135cb23985bed | Xiristian/infosatc-lp-avaliativo-02 | /atividade05.py | 246 | 4.03125 | 4 | minhalista = [3, 5, 6, 4, 9]
elementoX = int(input("Digite um número inteiro para saber se o item esta na lista: "))
if elementoX in minhalista:
print("O item digitado está na lista")
else:
print("O item digitado não está na lista") |
46584a6bd67011dac3c3873a79c54b6fc2f0336d | rustamiwanttobefree/2lesson-2 | /zadanie2.py | 403 | 3.65625 | 4 | var_count = int(input("Введите количество элементов списка "))
my_list = []
i = 0
var = 0
while i < var_count:
my_list.append(input("Введите следующее значение списка "))
i += 1
for elem in range(int(len(my_list)/2)):
my_list[var], my_list[var+ 1] = my_list [var + 1], my_list[var]
el += 2
print(my_list) |
beb054e4bc8b1408e9d85770dfa9c3cf4f69f186 | excelsky/Leet1337Code | /HackerRank/Hired_balanced_bracket.py | 2,183 | 3.8125 | 4 | # def solution(angles):
# # Type your solution here
# if len(angles) > 1:
# print("if")
# new_angles = []
# for i in range(len(angles)-1):
# print(i)
# if (angles[i] != "<" or angles[i+1] != ">") and i+2 == len(angles):
# print("ifif")
# new_angles.append(angles[i])
# new_angles.append(angles[i+1])
# elif angles[i] != "<" or angles[i+1] != ">":
# print("elif")
# new_angles.append(angles[i])
# else:
# print("else")
# new_angles = list(angles)
# print(new_angles)
# left_cnt = new_angles.count("<")
# right_cnt = new_angles.count(">")
# print(left_cnt)
# print(right_cnt)
# ans = right_cnt * "<" + angles + left_cnt * ">"
# return ans
# def solution(angles):
# # Type your solution here
# bal_cnt = 0
# left_cnt = 0
# right_cnt = 0
# for i in range(len(angles)):
# if angles[i] == "<":
# bal_cnt += 1
# left_cnt += 1
# else:
# bal_cnt -= 1
# right_cnt += 1
# # if balance == -1:
# # balance += 1
# # left_cnt += 1
# # ans += 1
# print(bal_cnt)
# print(left_cnt)
# print(right_cnt)
# ans = right_cnt * "<" + angles + left_cnt * ">"
# return ans
def solution(angles):
# Type your solution here
left_cnt = 0
right_cnt = 0
for i in range(len(angles)):
if angles[i] == "<":
left_cnt += 1
else:
right_cnt += 1
diff = min(left_cnt, right_cnt) - 1
if diff == -1:
diff = 0
to_right_cnt = left_cnt - diff
to_left_cnt = right_cnt - diff
ans = to_left_cnt * "<" + angles + to_right_cnt * ">"
return ans
angles = "<<>>>>><<<>>"
my_output = "<<<<<<<<<>>>>><<<>>>>>>>"
output = "<<<<<>>>>><<<>>>"
assert(solution(angles)) == output
angles = ">"
output = "<>"
assert(solution(angles)) == output
angles = ">>"
output = "<<>>"
assert(solution(angles)) == output
angles = "><<><"
output = "<><<><>>"
assert(solution(angles)) == output |
196cbb127fe0f7309e15341b078c0a532f721a34 | LanyK/TheAngerGames | /bombangerman/client/Sprites.py | 6,597 | 3.609375 | 4 | import pygame
import json
from collections import defaultdict
class Spritesheet(object):
@classmethod
def from_file(cls, filename, sprite_size=(16, 16)):
""" @param sprite_size: Defaults to (16,16)
Load a spritesheet from a file.
This method will load an image file and cut it into a list of pygame images by moving horizontally through the file. If the spritesheet file contains more than one line of images as definied by the comparison of the image size and the sprite_size parameter, the list will be filled row by row from the source image.
"""
try:
image = pygame.image.load(filename).convert_alpha()
name = filename
size = image.get_size() # (int,int)
sprites = []
current_x = 0
current_y = 0
# Check spritesheet cutting operation validity
if sprite_size[0] > size[0] or sprite_size[1] > size[1]:
raise KeyError("Trying to create a spritesheet from an image smaller than the desired sprite_size:",
sprite_size, "out of", size)
# Cut spritesheet to gather sprites
for row in range(0, size[1] // sprite_size[1]):
for column in range(0, size[0] // sprite_size[0]):
top_left = (column * sprite_size[0], row * sprite_size[1])
sprite = Spritesheet.get_image_from_rect(image,
(top_left[0], top_left[1], sprite_size[0], sprite_size[1]))
sprites.append(sprite)
return Spritesheet.from_image_list(sprites, name)
except pygame.error as e:
print("Error when trying to load image:", filename)
raise e
@classmethod
def from_image_list(cls, image_list, name):
""" Create a new Spritesheet from a list of pygame images """
return cls(name, image_list)
def __init__(self, name, sprites):
self.name = name
self.sprites = sprites
@classmethod
def get_image_from_rect(cls, source_image, rectangle, colorkey=None):
""" Extract a new sprite image from the spritesheet
@param source_image: the image to crop from
@param rectangle: Loads sprite from rectangle (x,y,x+offset,y+offset)
@param colorkey: Optional colorkey for image.set_colorkey(..)
"""
rect = pygame.Rect(rectangle)
image = pygame.Surface(rect.size, pygame.SRCALPHA).convert_alpha()
image.blit(source_image, (0, 0), rect)
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image
def __len__(self):
return len(self.sprites)
def __str__(self):
return "<Spritesheet " + str(self.name) + " (len:" + str(len(self)) + ")>"
def num_sprites(self):
return len(self)
def get_sprites(self, index_list):
""" Returns a list of sprites. Equivalent to calling get_sprite multiple times.
"""
return [self.get_sprite(index) for index in index_list]
def get_sprite(self, index):
""" Returns the ith sprite in the spritesheet and it's size (x,y)
"""
try:
sprite = self.sprites[index]
except IndexError as e:
print("Tried to get value at index", index, "in a spritesheet of length", len(self))
raise e
return sprite, sprite.get_size()
class Charsheet():
""" Is a spritesheet wrapper that can hold a horizontal spacing map dictionary that maps sprite_id to horizontal pixel offsets. Use to smoothen text rendering on variable width character fonts.
The mapping can be partial, will default to 0 pixels for unspecified sprite_id values. """
def __init__(self, spritesheet, spacing=None):
self.horizontal_spacing_map = spacing if spacing else dict()
self.spritesheet = spritesheet
def load_spacing_map(self, file_name):
""" expects a json dictionary """
with open(file_name) as fh:
self.horizontal_spacing_map = json.loads(fh.read())
def get_spacing(self, sprite_id):
""" Horizontal offset in pixels, can be negative """
return self.horizontal_spacing_map.get(str(sprite_id), 0)
def get_sprite(self, index):
return self.spritesheet.get_sprite(index)
def num_sprites(self):
return len(self)
def __len__(self):
return len(self.spritesheet)
def __str__(self):
return "<Charsheet " + str(self.spritesheet.name) + " (len:" + str(len(self)) + ")>"
class Animation(object):
""" An animation object points to a list of sprites along with timing information.
The animation can be advanced and will return the current sprite when asked.
"""
def __init__(self, sprites, timing_dict):
""" :param sprites: List of Sprites (pygame surfaces) or Spritesheet instance
:param timing_dict: Dict mapping of animation frame index to tick count;
Frames not specified default to 1 tick.
"""
self.frames = sprites if not isinstance(sprites, Spritesheet) else sprites.sprites
self.timing_dict = defaultdict(lambda: 1)
self.timing_dict.update(timing_dict)
self.current_time_step = 0
self.total_time_steps = sum(self.timing_dict[frame_idx] for frame_idx in range(len(self.frames)))
self.timing_to_frame_map = dict()
next_time_step = 0
for frame_idx, frame in enumerate(self.frames):
time_steps_for_frame = self.timing_dict[frame_idx]
for step in range(time_steps_for_frame):
self.timing_to_frame_map[next_time_step] = frame_idx
next_time_step += 1
def get_next_frame(self):
""" Returns the next frame (sprite/surface) and advances the animation
"""
sprite = self.frames[self.timing_to_frame_map[self.current_time_step]]
self.current_time_step += 1
if self.current_time_step == self.total_time_steps:
self.current_time_step = 0
return sprite
def reset_animation(self):
""" Resets the animation to the first time step
"""
self.current_time_step = 0
def shallow_copy(self):
""" returns an independent animation instance pointing to the same sprite instances.
"""
return Animation(self.sprites, self.timing_dict)
|
798d0bf382c6046ceeb76a5faa19e64362af3465 | anton-perez/graph | /src/directed_graph.py | 3,510 | 3.5625 | 4 | class Node:
def __init__(self, index):
self.index = index
self.children = []
self.parents = []
self.previous = None
self.distance = None
class DirectedGraph:
def __init__(self, edges):
self.edges = edges
self.max_index = self.get_max_index()
self.nodes = [Node(i) for i in range(self.max_index+1)]
self.build_from_edges()
def get_children(self, index):
children = []
for edge in self.edges:
if edge[0] == index:
children.append(edge[1])
return children
def get_parents(self, index):
parents = []
for edge in self.edges:
if edge[1] == index:
parents.append(edge[0])
return parents
def get_max_index(self):
max = self.edges[0][0]
for edge in self.edges:
if edge[0] > max:
max = edge[0]
elif edge[1] > max:
max = edge[1]
return max
def build_from_edges(self):
for node in self.nodes:
children = [self.nodes[i] for i in self.get_children(node.index)]
parents = [self.nodes[i] for i in self.get_parents(node.index)]
node.children = children
node.parents = parents
for child in children:
if node not in child.parents:
child.parents.append(node)
for parent in parents:
if node not in parent.children:
parent.children.append(node)
def nodes_breadth_first(self, index):
queue = [self.nodes[index]]
visited = []
while queue != []:
visiting = queue[0]
queue = queue[1:]
visited.append(visiting)
children = visiting.children
queue = queue + [child
for child in children
if child not in queue and child not in visited]
return visited
def nodes_depth_first(self, index):
stack = [self.nodes[index]]
visited = []
while stack != []:
visiting = stack[0]
stack = stack[1:]
visited.append(visiting)
children = visiting.children
stack = [child
for child in children
if child not in stack and child not in visited] + stack
return visited
def set_breadth_first_distance_and_previous(self, starting_node_index):
self.nodes[starting_node_index].distance = 0
queue = [self.nodes[starting_node_index]]
visited = []
while queue != []:
visiting = queue[0]
current_dist = visiting.distance
queue = queue[1:]
visited.append(visiting)
children = visiting.children
for child in children:
if child not in queue and child not in visited:
child.distance = current_dist + 1
child.previous = visiting
queue = queue + [child
for child in children
if child not in queue and child not in visited]
def calc_distance(self, starting_node_index, ending_node_index):
self.set_breadth_first_distance_and_previous(starting_node_index)
return self.nodes[ending_node_index].distance
def calc_shortest_path(self, starting_node_index, ending_node_index):
self.set_breadth_first_distance_and_previous(starting_node_index)
if self.calc_distance(starting_node_index, ending_node_index) != False:
current_node = self.nodes[ending_node_index]
path_list = [ending_node_index]
while current_node.index != starting_node_index:
current_node = current_node.previous
path_list.append(current_node.index)
return path_list[::-1]
else:
return False |
0cf85e201b73c511eb95bde428083520a7ae4b13 | samisosa20/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/0-positive_or_negative.py | 211 | 4.15625 | 4 | #!/usr/bin/python3
import random
number = random.randint(-10, 10)
if (number < 0):
str = "is negative"
elif (number > 0):
str = "is positive"
else:
str = "is zero"
print("{} {}".format(number, str))
|
04602fea3b2896f619ee3b0c0202d88176e7f14f | hohaidang/Python_Basic2Advance | /ErrorHandling/main.py | 439 | 3.921875 | 4 | import sys
# try:
# print(a)
# except NameError:
# print("Name Error")
# except:
# print("Error")
try:
print(x)
except:
print("Something went wrong")
finally:
# Will print regardless of try is throw error or not
print("The 'try except' is finished")
sys.exit(1)
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close() |
00a89345238f6dfe5b9988207a405231c4c5ea87 | amol10/python_challenge | /7/sol3.py | 951 | 3.5625 | 4 | from zipfile import ZipFile
#unzipped = zipf.read()
#print(unzipped)
#zipf.printdir()
def extract_files_from_zip():
zipf = ZipFile('channel.zip', 'r')
zipf.extractall(path='unzipped')
def follow_the_chain():
n = '90052'
while True:
text = ''
with open('unzipped/' + n + '.txt', 'r') as f:
text = f.read()
if text.find('Next nothing is') > -1:
n = text.split()[-1]
else:
print(n)
break
def extract_comments_from_zip_file():
with open('channel.zip', 'rb') as f:
for line in f.readlines():
hl = line.find(b'#')
if hl > -1:
print_b_line(line[hl : ])
def print_b_line(line):
for c in line:
if c < 32 or c > 126:
print('', end='')
else:
print(chr(c), end='')
print()
#extract_comments_from_zip_file()
def extract_comments_from_zip_file_2():
zipf = ZipFile('channel.zip', 'r')
for zi in zipf.infolist():
print(zi.comment.decode())#, end='')
print()
extract_comments_from_zip_file_2()
|
5f255a17b1d81b1b3edaa2acf2e8222d1deb8750 | Code-Institute-Submissions/portfolio-project-three | /pokergame.py | 2,840 | 4 | 4 | from poker import Poker
from inputhandler import InputHandler
class RunPoker:
"""
This class runs the game Poker and stores information
for use in highscore table
"""
def __init__(self, name='NoName'):
self.name = name
self.games_played = 0
self.games_won = 0
self.games_lost = 0
self.welcome_screen()
def welcome_screen(self):
"""
Method for showing a welcome screen to player with
information about the game and how to play
"""
print()
print('P*O*K*E*R')
print('Welcome to a 5-card poker game,\n' +
'The goal is the get a better hand than the AI.')
print('To do this you get one chance to swap cards' +
'that are in your hand')
print('You swap like this:\n' +
'1. Choose how many cards you want to swap\n' +
'2. Write the number of the card(s) you want to swap, like this:\n' +
'If you want to swap card 2, type in 2.\n' +
'If you want to swap card 1 and 4, type 1,4')
print('Next both your and AI hand is shown,\n' +
'and the winner is declared.')
print('For information on what hand beats what, \n' +
'and what happens when both players have an equally good hand,\n' +
'please follow the link below:\n' +
'https://github.com/oljung/portfolio-project-three\n' +
'NOTE! Ctrl + c will terminate the app, use right click to copy')
message = 'Would you like to play a round? Y(es) or N(o): '
answer = InputHandler.input_bool(message)
if answer:
self.run_game()
def run_game(self):
"""
Method that runs a round of poker and returns winner.
After it updates the scores and ask for another round,
calling itself if yes
"""
game = Poker()
AI_win = game.play_round(self.name)
self.update_scores(AI_win)
message = 'Would you like to play another round? Y(es) or N(o): '
answer = InputHandler.input_bool(message)
if answer:
self.run_game()
def update_scores(self, AI_win):
"""
Updates the scores stored in instance of object
for use in highscore table
"""
self.games_played += 1
if not AI_win:
self.games_won += 1
else:
self.games_lost += 1
def prepare_highscore_item(self):
"""
Prepares an item for use in highscore table
"""
if self.games_played == 0:
return False
else:
win_rate = round(self.games_won/self.games_played, 2) * 100
return [self.name, self.games_played, \
self.games_won, self.games_lost, win_rate]
|
f6f7799574576094164b222751bfa73e9f5e0c92 | Levintsky/topcoder | /python/leetcode/dp/1125_smallest_sufficient.py | 5,170 | 4.03125 | 4 | """
1125. Smallest Sufficient Team (Hard)
In a project, you have a list of required skills req_skills, and a
list of people. The i-th person people[i] contains a list of skills
that person has.
Consider a sufficient team: a set of people such that for every required
skill in req_skills, there is at least one person in the team who has
that skill. We can represent these teams by the index of each person:
for example, team = [0, 1, 3] represents the people with skills
people[0], people[1], and people[3].
Return any sufficient team of the smallest possible size, represented
by the index of each person.
You may return the answer in any order. It is guaranteed an answer exists.
Example 1:
Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]]
Output: [0,2]
Example 2:
Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]]
Output: [1,2]
Constraints:
1 <= req_skills.length <= 16
1 <= people.length <= 60
1 <= people[i].length, req_skills[i].length, people[i][j].length <= 16
Elements of req_skills and people[i] are (respectively) distinct.
req_skills[i][j], people[i][j][k] are lowercase English letters.
It is guaranteed a sufficient team exists.
"""
class Solution(object):
def smallestSufficientTeam(self, req_skills, people):
"""
:type req_skills: List[str]
:type people: List[List[str]]
:rtype: List[int]
"""
memo = {}
for item in req_skills:
memo[item] = len(memo)
p_bit = []
for plist in people:
tmp = 0
for item in plist:
k = memo[item]
tmp += 1 << k
p_bit.append(tmp)
# print(p_bit)
target = 2 ** len(memo) - 1
self.best = [1] * len(people)
p_res = [0] * len(people)
def dfs(p_num, ind, curr):
if curr == target:
if sum(p_res) < sum(self.best):
self.best = [item for item in p_res]
return
if ind == len(people):
return
# dfs
# with ind
new_curr = curr | p_bit[ind]
p_res[ind] = 1
dfs(p_num+1, ind+1, new_curr)
p_res[ind] = 0
dfs(p_num, ind+1, curr)
dfs(0, 0, 0)
res = []
for i, item in enumerate(self.best):
if item == 1:
res.append(i)
return res
def solve2(self, req_skills, people):
n, m = len(req_skills), len(people)
key = {v: i for i, v in enumerate(req_skills)}
dp = {0: []}
for i, p in enumerate(people):
his_skill = 0
for skill in p:
if skill in key:
his_skill |= 1 << key[skill]
res_list = list(dp.items())
for skill_set, need in res_list:
with_him = skill_set | his_skill
if with_him == skill_set: continue
if with_him not in dp or len(dp[with_him]) > len(need) + 1:
dp[with_him] = need + [i]
return dp[(1 << n) - 1]
if __name__ == "__main__":
a = Solution()
print(a.smallestSufficientTeam(["java","nodejs","reactjs"], [["java"],["nodejs"],["nodejs","reactjs"]]))
req_skills = ["algorithms","math","java","reactjs","csharp","aws"]
people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]]
print(a.smallestSufficientTeam(req_skills, people))
req_skills = ["hdbxcuzyzhliwv","uvwlzkmzgis","sdi","bztg","ylopoifzkacuwp","dzsgleocfpl"]
people = [["hdbxcuzyzhliwv","dzsgleocfpl"],["hdbxcuzyzhliwv","sdi","ylopoifzkacuwp","dzsgleocfpl"],["bztg","ylopoifzkacuwp"],["bztg","dzsgleocfpl"],["hdbxcuzyzhliwv","bztg"],["dzsgleocfpl"],["uvwlzkmzgis"],["dzsgleocfpl"],["hdbxcuzyzhliwv"],[],["dzsgleocfpl"],["hdbxcuzyzhliwv"],[],["hdbxcuzyzhliwv","ylopoifzkacuwp"],["sdi"],["bztg","dzsgleocfpl"],["hdbxcuzyzhliwv","uvwlzkmzgis","sdi","bztg","ylopoifzkacuwp"],["hdbxcuzyzhliwv","sdi"],["hdbxcuzyzhliwv","ylopoifzkacuwp"],["sdi","bztg","ylopoifzkacuwp","dzsgleocfpl"],["dzsgleocfpl"],["sdi","ylopoifzkacuwp"],["hdbxcuzyzhliwv","uvwlzkmzgis","sdi"],[],[],["ylopoifzkacuwp"],[],["sdi","bztg"],["bztg","dzsgleocfpl"],["sdi","bztg"]]
print(a.solve2(req_skills, people))
req_skills = ["mwobudvo","goczubcwnfze","yspbsez","pf","ey","hkq"]
people = [[],["mwobudvo"],["hkq"],["pf"],["pf"],["mwobudvo","pf"],[],["yspbsez"],[],["hkq"],[],[],["goczubcwnfze","pf","hkq"],["goczubcwnfze"],["hkq"],["mwobudvo"],[],["mwobudvo","pf"],["pf","ey"],["mwobudvo"],["hkq"],[],["pf"],["mwobudvo","yspbsez"],["mwobudvo","goczubcwnfze"],["goczubcwnfze","pf"],["goczubcwnfze"],["goczubcwnfze"],["mwobudvo"],["mwobudvo","goczubcwnfze"],[],["goczubcwnfze"],[],["goczubcwnfze"],["mwobudvo"],[],["hkq"],["yspbsez"],["mwobudvo"],["goczubcwnfze","ey"]]
print(a.solve2(req_skills, people)) |
2c15bc6624d1e5813fcf3a741f817319e3bcd465 | rafaelblira/python-progressivo | /imprime_n_linha.py | 168 | 4 | 4 | def piramide(n):
for c in range(1, n + 1):
letra = str(c)
print(c * letra)
numero = int(input('Digite um número para imprimir:'))
piramide(numero) |
ae48e16cf504be5f931772fd7cebfd42bca3af80 | skattelmann/myrep | /hacker.org_solver/mortal_coil/mortal_coil.py | 3,931 | 3.5 | 4 | import random
import math
import numpy as np
import time
def recSearch(board, ii, jj, dirs):
# bottom
i = ii+1
j = jj
pos = board[i,j]
if pos == 0:
while pos == 0:
board[i, j] = 1
i += 1
pos = board[i,j]
i -= 1
board[i,j] = 2
dirs.append('d')
result = recSearch(board, i, j, dirs)
if result != False:
return result
else:
dirs.pop()
board[i,j] = 0
pos = board[i,j]
while pos != 2:
board[i,j] = 0
i -= 1
pos = board[i,j]
# top
i = ii-1
j = jj
pos = board[i,j]
if pos == 0:
while pos == 0:
board[i, j] = 1
i -= 1
pos = board[i,j]
i += 1
board[i,j] = 2
dirs.append('u')
result = recSearch(board, i, j, dirs)
if result != False:
return result
else:
dirs.pop()
board[i,j] = 0
pos = board[i,j]
while pos != 2:
board[i,j] = 0
i += 1
pos = board[i,j]
# right
i = ii
j = jj+1
pos = board[i,j]
if pos == 0:
while pos == 0:
board[i, j] = 1
j += 1
pos = board[i,j]
j -= 1
board[i,j] = 2
dirs.append('r')
result = recSearch(board, i, j, dirs)
if result != False:
return result
else:
dirs.pop()
board[i,j] = 0
pos = board[i,j]
while pos != 2:
board[i,j] = 0
j -= 1
pos = board[i,j]
# left
i = ii
j = jj-1
pos = board[i,j]
if pos == 0:
while pos == 0:
board[i, j] = 1
j -= 1
pos = board[i,j]
j += 1
board[i,j] = 2
dirs.append('l')
result = recSearch(board, i, j, dirs)
if result != False:
return result
else:
dirs.pop()
board[i,j] = 0
pos = board[i,j]
while pos != 2:
board[i,j] = 0
j += 1
pos = board[i,j]
#print '.' ,
if np.all(board!=0):
return dirs
else:
return False
def getBoard(raw_board):
htmlCode = raw_board
index = 2
dimx = ""
dimy = ""
board = []
#get x-dimension
while htmlCode[index] != '&':
dimx += htmlCode[index]
index += 1
#get y-dimension
index += 3
while htmlCode[index] != '&':
dimy += htmlCode[index]
index += 1
#get the board
index += 7
while index < len(htmlCode):
if htmlCode[index] == 'X':
board.append( 1 )
else:
board.append( 0 )
index += 1
(dimx, dimy) = (int(dimx),int(dimy))
splitted_board = [ [1] + board[i:i+dimx] + [1] for i in range(0, dimx*dimy, dimx)]
splitted_board.append((dimx+2)*[1])
splitted_board.insert(0, (dimx+2)*[1])
return np.array(splitted_board)
def solve(raw_board, info_flag=False):
board = getBoard(raw_board)
(dimx, dimy) = board.shape
for i in range(1,dimx-1):
for j in range(1,dimy-1):
if board[i,j] == 0:
board[i,j] = 2
new_dirs = recSearch(board, i, j, [])
if new_dirs != False:
sol_string = "".join(new_dirs).upper()
sol_params = {'x': str(j-1), 'y': str(i-1), 'path': sol_string}
return (True, sol_params)
else:
board[i,j] = 0
|
d2b6828f2578a47d77fb1c8fd29a3f89c9a6a5f6 | olegzinkevich/programming_books_notes_and_codes | /numpy_bressert/ch03_sklearn/clustering.py | 1,607 | 3.6875 | 4 | # SciPy has two packages for cluster analysis with vector quantization (kmeans) and hierarchy.
# The kmeans method was the easier of the two for implementing and segmenting
# data into several components based on their spatial characteristics
# DBSCAN algorithm is used in
# the following example. DBSCAN works by finding core points that have many data points
# within a given radius.Once the core is defined, the process is iteratively computed until
# there are no more core points definable within the maximum radius? This algorithm
# does exceptionally well compared to kmeans where there is noise present in the data
import numpy as np
import matplotlib.pyplot as mpl
from scipy.spatial import distance
from sklearn.cluster import DBSCAN
# Creating data
c1 = np.random.randn(100, 2) + 5
c2 = np.random.randn(50, 2)
# Creating a uniformly distributed background
u1 = np.random.uniform(low=-10, high=10, size=100)
u2 = np.random.uniform(low=-10, high=10, size=100)
c3 = np.column_stack([u1, u2])
# Pooling all the data into one 150 x 2 array
data = np.vstack([c1, c2, c3])
# Calculating the cluster with DBSCAN function.
# db.labels_ is an array with identifiers to the
# different clusters in the data.
db = DBSCAN(eps=0.95, min_samples=10).fit(data)
labels = db.labels_
# Retrieving coordinates for points in each
# identified core. There are two clusters
# denoted as 0 and 1 and the noise is denoted
# as -1. Here we split the data based on which
# component they belong to.
dbc1 = data[labels == 0]
dbc2 = data[labels == 1]
noise = data[labels == -1]
print(dbc1)
print(dbc2)
print(noise) |
7c9cd494da22e2ab209287da81e7eaa196d634b1 | Light2077/LightNote | /python/python测试/example/vector/vector.py | 607 | 3.625 | 4 | class Vector:
def __init__(self, x, y):
if isinstance(x, (int, float)) and \
isinstance(y, (int, float)):
self.x = x
self.y = y
else:
raise ValueError("not a number")
def add(self, other):
return Vector(self.x + other.x,
self.y + other.y)
def mul(self, factor):
return Vector(self.x * other.x,
self.y * other.y)
def dot(self, factor):
return self.x * other.x + self.y * other.y
def norm(self):
return (self.x * self.x + self.y * self.y) ** 0.5 |
72d19ed37e40efb5fba000bd7467f25a5163b964 | adebayo5131/Python | /Recursion and Iteration.py | 234 | 4.09375 | 4 | def iteration(low, high):
while low <= high:
print(low)
low = low+1
def Recursive(low, high):
if low <= high:
print(low)
Recursive(low+1, high)
print(iteration(1, 5))
print(Recursive(1, 5))
|
ac59647c0f616345e77c30116cb7cf2c77fc237c | semiramisCJ/practice_python | /binary_search_number_list.py | 783 | 3.8125 | 4 | def binary_search(input_list, start, end, query):
if start >= end:
return False
half = (start + end) // 2
if query == input_list[half]:
return True
elif query > input_list[half]:
start = half
return binary_search(input_list[start:], start, len(input_list[start:]), query)
else:
end = half
return binary_search(input_list[:half], start, len(input_list[:half]), query)
if __name__ == "__main__":
import random
size = 25
input_list = sorted([random.randint(0,100) for i in range(size)])
# input_list = [1, 6, 7, 16, 17, 20, 21, 22, 23, 23, 44, 45, 49, 58, 62, 63, 65, 69, 70, 72, 78, 79, 85, 86, 91]
query = 25
print(input_list)
print(binary_search(input_list, 0, len(input_list), query))
|
f41f1044d0c8ae3c729d3ebe9b747f59d2456f40 | M0GW4I-dev/programming-competition | /qiita/product.py | 170 | 3.75 | 4 | def main():
a, b = [int(i) for i in input().split()]
if a*b%2 == 0:
print("Even")
else:
print("Odd")
if __name__ == '__main__':
main()
|
6a54effc2e9043f8f725a0861dccb54a35003b94 | Pabloitl/data-structures | /Estructuras/src/Presentacion/Ejemplos/BFS.py | 2,617 | 3.703125 | 4 | """
1.- Meta:
Escribir("Encontrar la ruta más corta entre dos nodos")
Escribir("a partir del número de aristas")
2.- Datos:
2.1.- Inicalizar:
visitados = set()
parent = dict()
G = eval(leerGrafo())
2.1.1.- LeerGrafo:
// Lee el grafo de un archivo
Escribir("Archivo: ") file = ?
abrir(file)
s = leerTodo(file)
cerrar(file)
retornar s
2.2.- PedirDatos:
Escribir("Nodo inicio: ") inicio = ?
Escribir("Nodo final : ") final = ?
3.- Calculos:
// Usa G (grafo), inicio (Nodo inicial) y final (Nodo final)
Q = list()
visitados.add(inicio)
Q.append(inicio)
Mientras(Q no esté vacia) entonces
v = Q.pop()
Si(v == final) entonces
retornar v
terminar
Para cada w en G[v] empezar
Si(w no está en visitados) entonces
visitados.add(w)
parent[w] = v
Q.append(w)
terminar
terminar
terminar
4.- Resultados:
count = 1
p = parent[final]
res.append(final)
res.append(p)
Mientras(p != inicio) entonces
p = parent[p]
res.append(p)
count++
terminar
Escribir(count)
Escribir(reverse(res))
5.- Navegabilidad:
No hay
"""
def meta():
s = "Encontrar la ruta más corta entre dos nodos"
s = s + " a partir del número de aristas"
print(s)
def datos():
def _inicializar():
global G, visitados, parent
def __leer_grafo():
file = input("Archivo: ")
with open(file) as f:
return f.read()
G = eval(__leer_grafo())
visitados = set()
parent = dict()
def _pedir_datos():
global inicio, final
inicio = int(input("Nodo inicio: "))
final = int(input("Nodo final : "))
_inicializar()
_pedir_datos()
def calculos(G, inicio, final):
Q = list()
visitados.add(inicio)
Q.append(inicio)
while Q:
v = Q.pop()
if v == final:
return v
for w in G[v]:
if w not in visitados:
visitados.add(w)
parent[w] = v
Q.append(w)
def resultados():
res = list()
count = 1
p = parent[final]
res.append(final)
res.append(p)
while p != inicio:
p = parent[p]
res.append(p)
count = count + 1
print(res[::-1], count, sep = ': ')
if __name__ == "__main__":
meta()
datos()
calculos(G, inicio, final)
resultados()
|
c7a9367bd3e63a97740edb83c1886cd1f03dc831 | filesmuggler/python-code | /transpositionDecrypt.py | 1,704 | 3.765625 | 4 | ## http://inventwithpython.com/hacking (BSD Licensed)
## Krzysztof Stężała (BSD License)
import math,sys,time
## main() is the main function of this script or module.
def main():
# encrypted message and key
myMessage = 'Rg r!ahb itecnssoy td a inrfnieog'
myKey = 8
# getting original message
plaintext = decryptMessage(myKey,myMessage)
print('Key: '+str(myKey)+'; Plain Text: '+plaintext + '|')
## function to decrypt messages ciphered with transposition method
## it puts single characters from encrypted message into matrix of boxes
## which is "message length/key wide" and "key high"
def decryptMessage(key,message):
# displaying loading
for i in range(4):
b="Decrypting with key: " + str(key) + "."*i
print(b,end="\r")
time.sleep(0.2)
print(" ",end='\r')
time.sleep(0.1)
# number of columns rounded up to upper bound (how long is the list of strings)
numOfColumns = math.ceil(len(message)/key)
# number of rows (how long is the string in the list of strings)
numOfRows = key
# determining how many 'boxes' should remain empty ever after
numOfShadedBoxes = (numOfColumns*numOfRows)-len(message)
# creating list with empty strings
plaintext = ['']*numOfColumns
# initial setup
col = 0
row = 0
# main algorithm for decrypting the message
for symbol in message:
plaintext[col] += symbol
col += 1
if(col==numOfColumns) or (col == numOfColumns-1 and row >=numOfRows-numOfShadedBoxes):
col = 0
row += 1
return ''.join(plaintext)
if __name__ == '__main__':
main() |
2248b7332d27942c36deb2dcf834f72a13b541ef | wmm0165/crazy_python | /05/named_param_test.py | 316 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/6/22 22:08
# @Author : wangmengmeng
def girth(width, height):
print("width:", width)
print("height:", height)
return 2 * (width + height)
print(girth(3.5, 4.8))
print(girth(width=3.5, height=4.8))
print(girth(height=4.8, width=3.5))
print(girth(3.5, height=4.8))
|
b5d49fce93f403f4977f19a6b12cd31b3bb778d9 | kaos8192/Freecell-py | /deck.py | 542 | 4.03125 | 4 | import random
def shuffle_deck(Card, seed=None):
'''generates a shuffled deck with the provided Card class
Note that Card should have a constructor that takes two arguments
in (rank, suit) order. rank is in the range [1,13] and suit is [0,3]
If seed is omitted, the generated shuffle will be different each
time.'''
deck = []
for suit in range(4):
for rank in range(1,14):
deck.append(Card(rank, suit))
random.seed(seed)
random.shuffle(deck)
for card in deck:
yield card
|
55fd7ade9f336582bdb3365ca99d8ef8e705b0be | iamSamuelFu/cs177_hw3 | /targaryend.py | 2,706 | 3.90625 | 4 | import sys
import crypt
import itertools
import string
salt = "aa"
real_hash = ".YVJDT1VruA"
# def guess_password(real):
# chars = string.ascii_lowercase + string.digits
# attempts = 0
# for password_length in range(1, 9):
# for guess in itertools.product(chars, repeat=password_length):
# attempts += 1
# guess = ''.join(guess)
# if guess == real:
# return 'password is {}. found in {} guesses.'.format(guess, attempts)
# print(guess, attempts)
# print(guess_password('abc'))
lowercase = string.ascii_lowercase
lowercase = lowercase[::-1]
# printable_str = ""
# for i in range(32,127):
# printable_str += chr(i)
# print(printable_str)
# dictionary = []
# with open('dictionary.txt', 'r') as f:
# for l in f:
# for w in l.split():
# dictionary.append(w)
# print(dictionary)
# wordlist = []
# with open('words.txt', 'r') as f:
# for l in f:
# for w in l.split():
# wordlist.append(w)
# print(wordlist)
def craker():
# for guess in dictionary:
# guess_hash = crypt.crypt(guess, salt)
# guess_hash = guess_hash[2:]
# if(guess_hash == real_hash):
# return 'password is {}.'.format(guess)
# print(guess)
# print("------------dictionary runs out-----------------")
# for guess in wordlist:
# guess_hash = crypt.crypt(guess, salt)
# guess_hash = guess_hash[2:]
# if(guess_hash == real_hash):
# return 'password is {}.'.format(guess)
# print(guess)
# print("------------wordlist runs out-----------------")
for password_length in range(6, 9):
for guess in itertools.product(lowercase, repeat=password_length):
guess = ''.join(guess)
guess_hash = crypt.crypt(guess, salt)
guess_hash = guess_hash[2:]
if(guess_hash == real_hash):
print 'password is {} with hash value {}.'.format(guess, guess_hash)
return
print 'Guess is {} with hash value {}.'.format(guess, guess_hash)
print("------------lowercase runs out-----------------")
# for password_length in range(6, 9):
# for guess in itertools.product(printable_str, repeat=password_length):
# guess = ''.join(guess)
# guess_hash = crypt.crypt(guess, salt)
# guess_hash = guess_hash[2:]
# if(guess_hash == real_hash):
# return 'password is {}.'.format(guess)
# print(guess)
# return '------------nothing matches-----------------'
print("------------Began------------")
craker()
print("------------End------------")
|
bc291c10469285b2d85b8f690532cc3d99c1b764 | Abel2Code/TeachingPython | /Examples/Text-BasedGames/MarioVSSonicFramework.py | 2,235 | 4.21875 | 4 | import # Figure out what to import to generate random numbers
# Mario Stats
marioHealth = 64
marioAttackRange = [6, 8] # When mario attacks, make his attack between 6 and 8 (inclusive)
# By learning how to generate random numbers. you should be able to figure out how to generate a number between 6 and 8
marioHeal = 9 # This will increase Mario's health if he is damaged. Try to figure out how to make him not heal past 64
# Sonic Stats
sonicHealth = 44
sonicMainAttackRange = [7, 10] # When Sonic uses this attack, make his attack between 7 and 10 (inclusive)
sonicQuickAttackRange = [2, 5] # When Sonic uses his quick attack, make his attack between 2 and 5 (inclusiv)
# If we wish to change any of these values later, we just need to tweak the value!
isMarioTurn = True # Will keep track of which player's turn it is
# Since there are only 2 players, we can use a boolean
while not (marioHealth <= 0 or sonicHealth <= 0): # Checks to see that no character is dead
print("\nMario has", marioHealth, "hp!")
print("Sonic has", sonicHealth, "hp!\n")
if isMarioTurn: # This conditional statement check's whos turn it is
print("Mario's Turn!")
# Write Mario's Turn logic here, be sure to ask player which attack they would like to use
# TO make things simple, have them input '1' for attack and '2' for heal
# If you would like a challenge, try writing this logic in a method.
# NOTE The method should be at the top of this file, but under the import statements.
# HINT If using a method, you should have the method return an array with Mario and Sonic's new health
# You will not be able access the MarioHealth variable from the method
isMarioTurn = False # Makes it Sonic's turn
else:
print("Sonic's Turn")
# Write Mario's Turn logic here, be sure to ask player which attack they would like to use
# TO make things simple, have them input '1' for attack and '2' for heal
# Get here once one player has dropped below 1 health
if (marioHealth <= 0):
print("Mario has fainted. Sonic Wins at " + str(sonicHealth) + " hp!")
else:
print("Sonic has fainted. Mario Wins at " + str(marioHealth) + " hp!")
|
a48e91a699fd8c9ce1a217a3a4520ff7683a0620 | chenjinpeng1/python | /day4/JSQ.py | 1,264 | 3.546875 | 4 | #python 3.5环境,解释器在linux需要改变
#作者:S12-陈金彭
import re
def jisuan(num):
num=chengchu(num)
# String=jiajian(num)
return num
def chengchu(num):
# print(num)
# print(re.search('\d+[\.?\d+]?[\*|\/]\d+',num))
if re.search('\-?\d+[\.?\d+]?[\*|\/]\d+',num) is None:
return num
String=re.search('\-?\d+\.?\d+?[\*|\/]\d+',num).group()
print(String)
if '/' in String:
b='%.2f'%(float(re.split('\/',String)[0])/float(re.split('\/',String)[1]))
print('计算结果:%s'%b)
num=num.replace(String,str(b))
elif '*' in String:
b='%.2f'%(float(re.split('\*',String)[0])*float(re.split('\*',String)[1]))
print('计算结果:%s'%b)
num=num.replace(String,str(b))
return chengchu(num)
def jiajian(num):
pass
def Sreach(num):
String=re.search('\(([\+\-\*\/]?\d+){2,}\)',num).group()
String_1=String.strip('\(|\)')
print('匹配到%s'%String_1)
jieguo=jisuan(String_1)
num=num.replace(String,str(jieguo))
num=num.replace('+-','-')
print(num)
return Sreach(num)
Input='1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
print(Input)
String=Input.replace(' ','')
Sreach(String) |
542b814715ea82133e3f084cefc5395324c3326d | jordanNewberry21/python-practice | /lesson19-advanced-string-syntax.py | 1,140 | 4.21875 | 4 | # double quotes avoid messing up with apostraphes
str = "That is Alice's cat."
# escape characters
str2 = 'Say hi to Bob\'s mother!'
# backslash is used before certain characters to denote certain text things for example
# \' = single quote in string
# \" = double quote in string
# \t = tab in string
# \n = new line in string
# \\ = backslash in string
print('Hello there!\nHow are you?\nI\'m fine.')
# raw strings don't treat backslashes as escape characters,
# similar to the template literal in javascript
print(r'Hello')
print(r'That is carol\'s cat.')
# multi-line string
print("""Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob.""")
# in and not in methods are case sensitive
# strings can being and end with double quotes
# escape characters let you put quotes and other characters that are hard to type into strings
# raw strings will literally print any backslashes in the string and ignore escape characters
# multiline strings begin and end with three quotes, and can span multiple lines.
# indexes, slices, and the in and not in operators all work with strings. |
00fd5efa4c66b7bd4617f4c886eddcdf38b951b7 | engineeredtoprogram/my-first-blog | /python_intro.py | 450 | 4 | 4 | print ("Hello, Django girls!")
volume = 57
if volume < 20:
print("It's kinda quiet.")
elif 20 <= volume < 40:
print("It's nice for background music")
elif 40 <= volume < 60:
print("Perfect, I can hear all the details")
elif 60 <= volume < 80:
print("Nice for parties")
elif 80 <= volume < 100:
print("A bit loud!")
else:
print("My ears are hurting! :(")
def hi():
print('Hi there!')
print('How are you?')
hi() |
79f97af923664e035a7d221ece6ec36debba7a5d | awsumal/Python-sem-1 | /ali6.py | 153 | 4.03125 | 4 | a=int(input("Enter a number "))
for i in range(2,a):
if(a%i==0):
print(a,"is not prime \n",i,"times",(a//i),"=",a)
break;
else:
print(a,"is prime") |
e7e6dd3c39ff6c59dd456f0f744086aa34ca9047 | slowy07/crackingPythonInterview | /arrayAndString/rotateMatrix/rotateMatrix_solution.py | 511 | 3.8125 | 4 | def rotateMatrix(matrix):
# Transpose the Matrix
for i in range(len(matrix)):
for j in range(i + 1, len(matrix)):
# Switch the row and column indices
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse every row
for r in range(len(matrix)):
for i in range(len(matrix[r]) // 2):
# oppI is the opposing index to i
oppI = len(matrix[r]) - 1 - i
matrix[r][i], matrix[r][oppI] = matrix[r][oppI], matrix[r][i]
|
a0528579d80039e00011b45d152dbca00415d4c2 | Juozapaitis/CodeWars | /6 kyu/cm7_find_senior_developer.py | 326 | 3.703125 | 4 | def find_senior(lst):
max = -1
answer = []
for i in range(len(lst)):
if lst[i]['age'] == max:
answer.append(lst[i])
if lst[i]['age'] > max:
max = lst[i]['age']
answer.clear()
answer.append(lst[i])
return answer
# your code here |
4b349cb2774e66fdf3bbc597c7c5bf761ba23947 | federix8190/Reactjs | /services/script.py | 90 | 3.546875 | 4 | a = 5;
s = 2;
if a == s: print 'a y s son iguales'
else: print 'nada'
range(1,2)
len(1.2) |
11587eb37af3e8b0b892f2d6866762b3b8c411fb | fengbingchun/Python_Test | /demo/simple_code/test_typing.py | 5,259 | 3.828125 | 4 | from typing import Callable, List, NewType, Any, NoReturn, Union, Optional, Literal, TypeVar, Generic, TypedDict, Dict, Mapping, List, Sequence, Set, Tuple, Iterable
# Blog: https://blog.csdn.net/fengbingchun/article/details/122288737
var = 9
# reference: https://docs.python.org/3/library/typing.html
if var == 1: # Callable
def other_function(x: int, y: float) -> float:
print(f"x: {x}, y: {y}")
return y
def any_function(func: Callable[[int, float], float], x: int, y: float) -> float:
return func(x, y)
any_function(other_function, x=10, y=20)
any_function(other_function, x="abc", y=20) # 注:此条语句可以正常执行,类型提示(type hints)对运行实际上是没有影响的
def get_addr(csdn: str, github: str, port: int=403) -> str:
return f"csdn: {csdn}, github: {github}, port: {port}"
def get_addr() -> Callable[[str, str, int], str]:
return get_addr
elif var == 2: # Type aliases
# Vector和List[float]将被视为可互换的同义词
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4]); print(new_vector) # [2.0, -8.4, 10.8]
elif var == 3: # NewType
UserId = NewType('UserId', int) # 实际上UserID就是一个int类型,可以对其像int一样正常操作
some_id = UserId(524313); print(some_id) # 524313
def get_user_name(user_id: UserId) -> str:
return str(user_id)
user_a = get_user_name(UserId(42351)); print(user_a) # 42351
# 可以对UserId类型的变量执行所有int操作,但结果始终为int类型
output = UserId(23413) + UserId(54341); print(output) # 77754
elif var == 4: # Any
a: Any = None
a = [] # OK
a = 2 # OK
s: str = ""
s = a # OK
print(s) # 2
elif var == 5: # NoReturn
def stop() -> NoReturn:
raise RuntimeError('no way')
stop()
elif var == 6: # Union
# 联合类型的联合类型会被展开(flattened)
Union[Union[int, str], float] == Union[int, str, float]
# 仅有一个参数的联合类型就是该参数自身
Union[int] == int
# 冗余的参数会被跳过(skipped)
Union[int, str, int] == Union[int, str] # == int | str
# 在比较联合类型的时候,参数顺序会被忽略(ignored)
Union[int, str] == Union[str, int]
elif var == 7: # Optional
# 可选类型与含默认值的可选参数不同,含默认值的可选参数不需要在类型注解(type annotation)上添加Optional限定符,因为它仅是可选的
def foo(arg: int = 0) -> None: ...
# 显式应用None值时,不管该参数是否可选,Optional都适用
def foo(arg: Optional[int] = None) -> None: ...
elif var == 8: # Literal
def validate_simple(data: Any) -> Literal[True]: ... # always returns True
MODE = Literal["r", "rb", "w", "wb"]
def open_helper(file: str, mode: MODE) -> str:
return file + ":" + mode
print(open_helper("/some/path", "r")) # /some/path:r
elif var == 9: # TypeVar, Generic
T = TypeVar('T') # Declare type variable, Can be anything
# 泛型类型支持多个类型变量,不过,类型变量可能会受到限制
S = TypeVar('S', int, str) # Must be int or str
class StrangePair(Generic[T, S]): ...
# 泛型类型变量的参数都必须是不同的
#class Pair(Generic[T, T]): ... # TypeError: Parameters to Generic[...] must all be unique
length = "5.5"
Length = TypeVar("Length", int, float, None) # Length可以使用int, float或None来表示
def get_length() -> Length:
return length
print(get_length()) # 5.5
elif var == 10: # TypedDict
class Point2D(TypedDict):
x: int
y: int
label: str
a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
elif var == 11: # Dict
def count_words(text: str) -> Dict[str, int]: ...
x: Dict[str, int] = {"beijing", 1}; print(x) # {"beijing", 1}
elif var == 12: # Mapping
def get_position_in_index(word_list: Mapping[str, int], word: str) -> int:
return word_list[word]
def func(m: Mapping[int, str]) -> List[int]:
return list(m.keys())
print(func({0: "no", 1: "yes"})) # [0, 1]
elif var == 13: # List
T = TypeVar('T', int, float)
def vec2(x: T, y: T) -> List[T]:
return [x, y]
print(vec2(3, 2)) # [3, 2]
def keep_positives(vector: Sequence[T]) -> List[T]:
return [item for item in vector if item > 0]
x: List[int] = [1, 2, 3]; print(x) # [1, 2, 3]
elif var == 14: # Set
x: Set[int] = {1, 2, 3}; print(x) # {1, 2, 3}
elif var == 15: # Tuple
# 指定所有元素的类型
x: Tuple[int, float, str] = (1, 2.1, "beijing"); print(x) # (1, 2.1, "beijing")
# 可变长度的元组
y: Tuple[int, ...] = (1, 2.1, "beijing"); print(y) # (1, 2.1, "beijing")
elif var == 16: # Iterable
def func(l: Iterable[int]) -> List[str]:
return [str(x) for x in l]
print(func(range(1, 5))) # ['1', '2', '3', '4']
print("test finish")
|
bd477fa48b2680e00a1e4bbe3248cd2a479563b2 | jaehojang825/CS-313E | /Spiral.py | 2,924 | 4.15625 | 4 | #File: Spiral.py
#Description: prints surrounding values of central value of spiral
#Student's Name: Jaeho Jang
#Student's UT EID: jj36386
#Course Name: CS 313E
#Unique Number: 50300
#Date Created: 2/17/20
#Date Last Modified: 2/17/20
# Input: dim is a positive odd integer
# Output: function returns a 2-D list of integers arranged
# in a spiral
def create_spiral(dim):
#starting indexs
turning = {(0, -1): (1, 0), (1, 0): (0, 1), (0, 1): (-1, 0), (-1, 0): (0, -1)}
x = dim // 2
y = dim // 2
dx, dy = (0, -1)
#populate spiral
spiral = [[None] * dim for i in range(dim)]
#fill spiral
index = 0
while True:
index += 1
spiral[y][x] = index
turned_dx, turned_dy = turning[dx, dy]
turned_x = x + turned_dx
turned_y = y + turned_dy
if 0 <= turned_x < dim and 0 <= turned_y < dim and spiral[turned_y][turned_x] is None:
x = turned_x
y = turned_y
dx = turned_dx
dy = turned_dy
else:
x += dx
y += dy
if not 0 <= x < dim and 0 <= y < dim:
return spiral
# Input: grid a 2-D list containing a spiral of numbers
# val is a number withing the range of numbers in
# the grid
# Output: sub-grid surrounding the parameter val in the grid
# sub-grid could be 1-D or 2-D list
def sub_grid(grid,val):
x = 0
y = 0
#get center value
for i in range(len(grid)):
for j in range(len(grid)):
if grid[i][j] == val:
x = i
y = j
#get the surrounding values
if x == len(grid) - 1 and y == len(grid) - 1:
val_list = list([x - 1, y - 1, 2, 2])
elif x == len(grid) - 1 and y == 0:
val_list = list([x - 1, y, 2, 2])
elif x == 0 and y == 0:
val_list = list([x, y, 2, 2])
elif x == 0 and y == len(grid) - 1:
val_list = list([x, y - 1, 2, 2])
elif x == 0:
val_list = list([x, y - 1, 2, 3])
elif x == len(grid) - 1:
val_list = list([x - 1, y - 1, 2, 3])
elif y == 0:
val_list = list([x - 1, y, 3, 2])
elif y == len(grid) - 1:
val_list = list([x - 1, y - 1, 3, 2])
else:
val_list = list([x - 1, y - 1, 3, 3])
#print surrounding values
for i in range(val_list[2]):
for j in range(val_list[3]):
print(grid[i + val_list[0]][j + val_list[1]], end=' ')
print('')
def main():
#prompt user to enter dimension of grid
dim = int(input('\nEnter dimensions of the grid:'))
#prompt user to enter value in grid
val = int(input('Enter value in grid:'))
print('')
spiral = create_spiral(dim)
#print sub grid surrounding value
sub_grid(spiral, val)
if __name__ == "__main__":
main() |
65c64695c57b7b45a31a36878176f102e1378d1c | samuel-santos3112/Exercicios-Python | /Tabuada.py | 196 | 3.96875 | 4 | numeroTabuada = int(input("Informe o número de 1 a 10, qual deseja ver a tabuada: "))
for i in range (10):
if i > 0:
multiplicacao= numeroTabuada * i
print(numeroTabuada,"",) |
887f411438f68dc3490ab46992ee52695083d4c9 | K-Rdlbrgr/hackerrank | /Dictionaries and Hashmaps/Sherlock and Anagrams/sherlockandanagrams_solution.py | 2,642 | 4.09375 | 4 | # First we import Counter and combinations
from collections import Counter
from itertools import combinations
def sherlockAndAnagrams(s):
# Assigning an empty list for the count
count = []
# The for-loop and the list comprehension loop through the string and create
for i in range(1, len(s) + 1):
# The list comprehension goes through the string and gets all substrings
# of a speciic length while also sorting it
a = ["".join(sorted(s[j:j + i])) for j in range(len(s) - i + 1)]
# The Counter operator creates a dictionary out of the list of substrings,
# counting the appearance of each of them
b = Counter(a)
# Here we loop through the Counter dictionary and use the combinations
# function to create a list of lists of ('a', 'a') where the ('a', 'a')
# stand for anagrams. The 'a' in the list comprehesion is completely
# arbitrary and could be repalced by anything. K is set to 2 because the
# function is looking for pairs of anagrams. Each ('a', 'a') counts for
# one anagram, so the length stands for the anagram count of each
# dictionary entry and the sum of it represents the anagram count of the
# whole Counter object. Afterwards, the count gets appended to the count
# list and the next loop starts, analysing substrings with one more
# letter.
count.append(sum([len(list(combinations(['a'] * b[j], 2))) for j in b]))
# Return the sum of the count
return sum(count)
# Test
string = 'abba'
print(sherlockAndAnagrams(string))
# Intuitive solution
# This solution, while might being easier to understand is not efficient
# enough to pass the time constraints of the challenge
def sherlockAndAnagramsIntuitive(s):
# Assigning an initial counter and an empty list for all substrings
counter = 0
substrings = []
# Looping through s and extracting all possible substrings while saving them in the corresponding list
for i in range(0, len(s)):
for j in range(i + 1, len(s) + 1):
substrings.append(s[i:j])
# Looping through the extracted substrings, comparing if two substrings
# are anagrams or not by using the Counter operator
for index, sub in enumerate(substrings):
for s in range(index + 1, len(substrings)):
# The counter operator checks if two substrings have the same amount of
# letters and consequently adds one to the counter if they do
if Counter(sub) == Counter(substrings[s]):
counter += 1
# Return the counter
return counter
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.