blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
2b7afbda40cae062fb728648eeb1f7f45c0e9bc5 | AP-MI-2021/lab-2-CarnuStefan | /main.py | 3,609 | 3.8125 | 4 | '''
6. Determină dacă un număr este superprim: dacă toate prefixele sale sunt prime. De exemplu, `233` este superprim,
deoarece `2`, `23` și `233` sunt toate prime, dar `237` nu este superprim, deoarece `237` nu este prim.
- Funcția principală: `is_superprime(n) -> bool`
- Funcția de test: `test_is_superprime()`
'''
def is_prime(n):
if (n<2): return False
for i in range(2,n//2):
if(n%i==0):return False
return True
def is_superprime(n):
while (n):
if is_prime(n)== False: return False
n=n//10
return True
def test_is_superprime():
assert is_superprime(233) == True
assert is_superprime(237) == False
test_is_superprime()
'''
13. Transformă o temperatură dată într-o scară dată (`K`, `F` sau `C`) într-o altă scară dată. De exemplu: `300 K C` -> `26.85`.
- Funcția principală: `get_temp(temp: float, from: str, to: str) -> float`
- Funcția de test: `test_get_temp()`
'''
def get_temp(temp:float,fro:str,to:str):
if (fro == "K")|(fro=="k"):
if (to =="C")| (to=="c"):temp=temp-273.15
if (to =="F")| (to=="f"):temp=(temp-273.15)*9/5+32
if (fro == "C")|(fro=="c"):
if (to =="K")| (to=="k"):temp=temp+273.15
if (to =="F")| (to=="f"):temp=temp*9/5+32
if (fro == "F")|(fro=="f"):
if (to =="K")| (to=="k"):(temp-32)*5/9+273.15
if (to =="C")| (to=="c"):(temp-32)*5/9
return round(temp,2)
def test_get_temp():
assert get_temp(300,"K","C")==26.85
assert get_temp(0,"c","F")==32
assert get_temp(273.15,"K","f")==32
test_get_temp()
'''
Calculează combinări de `n` luate câte `k` (`n` și `k` date).
- Funcția principală: `get_n_choose_k(n: int, k: int) -> int`
- Funcția de test: `test_get_n_choose_k()`
'''
def get_n_choose_k(n:int,k:int):
if(k>n):return None
n_factorial=1
k_factorial=1
diferenta=n-k
diferenta_factorial=1
for i in range (1,n+1,1):
n_factorial=n_factorial*i
for j in range (1,k+1,1):
k_factorial=k_factorial*j
for l in range (1,diferenta+1,1):
diferenta_factorial=diferenta_factorial*l
combinare=n_factorial//(k_factorial*diferenta_factorial)
return combinare
def test_get_n_choose_k():
assert get_n_choose_k(52,5)==2598960
assert get_n_choose_k(10,0)==1
assert get_n_choose_k(234,1)==234
assert get_n_choose_k(24,24)==1
assert get_n_choose_k(2,345)==None
test_get_n_choose_k()
def main():
while True:
print("Meniu\n")
print("Rulati Problema 6-Superprim: 1")
print("Rulati Problema 13-Temperatura: 2")
print("Rulati Problema 10-Combinari de n luate cate k: 3")
print("Inchide:x \n")
varianta=input('Alegeti optiunea:')
if varianta=='1':
nr=int(input("Introduceti numarul care trebuie verificat: "))
if is_superprime(nr): print(f"Numarul {nr} este superprim \n")
else: print(f"Numarul {nr} este superprim \n")
elif varianta=='2':
linie_date=input("Introduceti temperatura, unitatea de temperatura in care este reprezentata si unitatea de temperatura in care trebuie transformata: ")
temp,gr1,gr2=linie_date.split(" ")
temp= float(temp)
print (get_temp(temp,gr1,gr2))
elif varianta=='3':
n=int(input("Introduceti n :"))
k=int(input("Introduceti k :"))
combinare=get_n_choose_k(n,k)
print(f"Rezultatul combinarilor de {n} luate cate {k} este {combinare}")
elif varianta=='x':break
if __name__ == '__main__':
main()
|
4c71d1fa592e3c54844946aa62e8eb4f7c69f95f | Aravindan-C/LearningPython | /LearnSet.py | 535 | 4.3125 | 4 | __author__ = 'aravindan'
"""A set is used to contain an unordered collection of objects,To create a set use the set() function and supply a sequence of items such as follows"""
s= set([3,5,9,10,10,11]) # create a set of unique numbers
t=set("Hello") # create a set of unique characters
u=set("abcde")
"""sets are unordered and cannot be indexed by numbers"""
print t ^ u
print s & u
t.add('x') # To add an item to a set
s.update([9,10,11],[9,14,16]) # To add a multiple item to set
print s
t.remove('H','l')
t.remove('e') |
06623bd65d8ba4d62713be768697929943c83e61 | Aravindan-C/LearningPython | /LearnIterationAndLooping.py | 640 | 4.15625 | 4 | __author__ = 'aravindan'
for n in [1,2,3,4,5,6,7,8,9,0]:
print "2 to the %d power is %d" % (n,2**n)
for n in range(1,10) :
print "2 to the %d power is %d" % (n,2**n)
a= range(5)
b=range(1,8)
c=range(0,14,3)
d=range(8,1,-1)
print a,b,c,d
a= "Hello World"
# print out the individual characters in a
for c in a :
print c
b=["Dave","Mark","Ann","Phill"]
#Print out the members of a list
for name in b:
print name
c={'GOOG' :490.10,'IBM' :91.50,'AAPL' :123.15}
#Print out all of the members of a dictionary
for key in c:
print key,c[key]
#Print all of the lines in a file
f=open("foo.txt")
for line in f:
print line |
0804378fa0c7cbc3f256161e17bef3564748e38e | Icheka/web-scraping-challenges-and-solutions-in-python | /02.py | 1,726 | 4 | 4 | from urllib.request import urlopen
from urllib.error import URLError
from urllib.error import HTTPError
from bs4 import BeautifulSoup
'''
02: Write a Python program to download and display the contens of robots.txt for https://en.wikipedia.org
'''
class Scraper:
'''
Loads any webpage and returns an exit code + a string that can either be an error message or the text of the requested webpage
loadWebPage(url: string): dict
@props url: string representation of the URL to request
'''
def loadWebPage(self, url):
try:
page = urlopen(url)
except URLError:
return {'code': 1, 'error': 'Remote server not found'}
except HTTPError:
return {'code': 2, 'error': 'The request returned an HTTP error'}
else:
bs = BeautifulSoup(page.read(), 'html.parser')
return {'code': 0, 'text': bs.prettify()}
def getRobotsFile(self, url):
if (isinstance(url, str) != True):
return {'code': 2, 'msg': "URL must be a string!"}
page = self.loadWebPage(url)
if (page['code'] != 0):
# I use exit codes (0 for success, any other integer for failure)
# so that the calling function can simply check the exit code
# and determine if the request was successfu or not
# without needing to parse the returned string
return {'code': 1, 'msg': "An error occurred! :>> {}".format(page['error'])}
return {'code': 0, 'msg': "{}".format(page['text'])}
def main():
url = "https://en.wikipedia.org/robots.txt"
scraper = Scraper()
robots_file = scraper.getRobotsFile(url)
print(robots_file['msg'])
main()
|
0fb0931988a35f8b48cc8e4f3d43f7c921b7614e | suribe06/Scientific_Computing | /Laboratorio 3/interpo_lagrange.py | 777 | 3.703125 | 4 | from pypoly import X
import numpy as np
def lagrange(datos):
"""
Entrada: Un conjunto de datos (ti, yi)
Salida: Polinomio interpolante del conjunto de datos con metodo de Lagrange
"""
n, pol = len(datos), 0
for j in range(n):
y = datos[j][1]
prod1, prod2 = 1, 1
for k in range(n):
if k != j:
#Calculo de las productorias
prod1 *= (X - datos[k][0]) #la X sirve para dejar la expresion como una ecuacion que posteriormente se podra evaluar
prod2 *= (datos[j][0] - datos[k][0])
#Funciones base de Lagrange
Lj = prod1 / prod2
ans = (y * Lj)
#Se suman las expresiones para obtener el polinomio interpolante
pol += ans
return pol
|
77bcb095ae5683e04de0a41047e6b1a218890bf7 | Casper-V/Oefening | /user_input.py | 270 | 3.953125 | 4 | # vraag bij restaurant of er plek is
number_of_seats = int(input("How many seats do you want to reserve? "))
if number_of_seats <= 8:
print (f"No problem. We have a table for {number_of_seats} seats ready for you.")
else:
print ("Sorry, you will have to wait.")
|
908ff1d7ed7b294b3bef209c6ca6ffbf43851ba8 | loc-dev/CursoEmVideo-Python-Exercicios | /Exercicio_008/desafio_008.py | 598 | 4.15625 | 4 | # Desafio 008 - Referente aula Fase07
# Escreva um programa que leia um valor em metros
# e o exiba em outras unidades de medidas de comprimento.
# Versão 01
valor_m = float(input('Digite um valor em metros: '))
print(' ')
print('A medida de {}m corresponde a: '.format(valor_m))
print('{}km (Quilômetro)'.format(valor_m / 1000))
print('{}hm (Hectômetro)'.format(valor_m / 100))
print('{:.2f}dam (Decâmetro)'.format(valor_m / 10))
print('{:.0f}dm (Decímetro)'.format(valor_m * 10))
print('{:.0f}cm (Centímetro)'.format(valor_m * 100))
print('{:.0f}mm (Milímetro)'.format(valor_m * 1000))
|
b692aeb005cd6da9ae2b4759d75c482f7fdc56a8 | loc-dev/CursoEmVideo-Python-Exercicios | /Exercicio_017/desafio_017_03.py | 445 | 3.9375 | 4 | # Desafio 017 - Referente aula Fase08
# Faça um programa que leia o comprimento do cateto oposto
# e do cateto adjacente de um triângulo retângulo,
# calcule e mostre o comprimento da hipotenusa.
# Versão 03
from math import hypot
cat_op = float(input('Digite o valor do cateto oposto: '))
cat_adj = float(input('Digite o valor do cateto adjacente: '))
hip = hypot(cat_op, cat_adj)
print('O valor da hipotenusa é {:.2f}.'.format(hip))
|
6743e75e9566149e149f565f5e07b09ac843f17c | loc-dev/CursoEmVideo-Python-Exercicios | /Exercicio_021/desafio_021.py | 413 | 3.734375 | 4 | # Desafio 021 - Referente aula Fase08
# Faça um programa em Python que abra
# e reproduza o áudio de um arquivo MP3.
# Versão 01
from pygame import mixer
# Iniciando o funcionalidade 'mixer'
mixer.init()
# Carregar a música
mixer.music.load("music.mp3")
# Configuração do Volume
mixer.music.set_volume(0.7)
# Iniciar a música
mixer.music.play()
funcao = input('Aperte qualquer tecla para cancelar')
|
b8d2af50ed4f13924ac7edde21e43a48599b56f7 | loc-dev/CursoEmVideo-Python-Exercicios | /Exercicio_034/desafio_034.py | 529 | 3.875 | 4 | # Desafio 034 - Referente aula Fase10
# Escreva um programa que pergunte o salário de um funcionário
# e calcule o valor do seu aumento.
# Para salários superiores a R$ 1250,00, calcule um aumento de 10%
# Para salários inferiores ou iguais, o aumento é de 15%.
salario = float(input('Qual é o salário do funcionário? R$'))
if salario <= 1250:
novo = salario + (salario * 15 / 100)
else:
novo = salario + (salario * 10 / 100)
print('Quem ganhava R${:.2f} passa a ganhar R${:.2f} agora.'.format(salario, novo))
|
37e9ec85ea551c5a0f77ba61a24f955da77d0426 | loc-dev/CursoEmVideo-Python-Exercicios | /Exercicio_022/desafio_022.py | 662 | 4.375 | 4 | # Desafio 022 - Referente aula Fase09
# Crie um programa que leia o nome completo de uma pessoa
# e mostre:
# - O nome com todas as letras maiúsculas e minúsculas.
# - Quantas letras no total (sem considerar espaços).
# - Quantas letras tem o primeiro nome.
nome = input("Digite o seu nome completo: ")
print('')
print("Analisando o seu nome...")
print("Seu nome em letras maiúsculas é: {}".format(nome.upper()))
print("Seu nome em letras minúsculas é: {}".format(nome.lower()))
print("Seu nome tem ao todo {} letras".format(len(nome.replace(" ", ""))))
print("Seu primeiro nome é {} e ele tem {} letras".format(nome.split()[0], len(nome.split()[0])))
|
c21762ec2545a3836c039837ec782c8828044fca | jkusita/Python3-Practice-Projects | /count_vowels.py | 1,833 | 4.25 | 4 | # Count Vowels – Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found.
vowel_list = ["a", "e", "i", "o", "u"]
vowel_count = 0 # Change this so it adds all the values of the keys in the new dictionary.
vowel_count_found = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0} # TODO: maybe you can change the keys from strings to variable (if possible)?
# vowel_count_a = 0
# vowel_count_e = 0
# vowel_count_i = 0
# vowel_count_o = 0
# vowel_count_u = 0
# Counts the number of vowels in the inputted string.
user_input = str.lower(input("Please enter a string: "))
for i in range(len(user_input)):
if user_input[i] in vowel_list:
# Counts the sum of each vowels found in the inputted string.
if user_input[i] == "a":
vowel_count_found[user_input[i]] += 1 # Is there a way to add to a non-string key value in dict?
vowel_count += 1
elif user_input[i] == "e":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
elif user_input[i] == "i":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
elif user_input[i] == "o":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
elif user_input[i] == "u":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
# Prints out how much vowels are in the string based on certain conditions.
if vowel_count == 0:
print("There are no vowels.")
elif vowel_count == 1:
print("There is only one vowel.")
else:
print(f"There are {vowel_count} vowels.")
# Prints out the sum of each vowels found in the inputted string.
for i, j in vowel_count_found.items():
print(i + ":" + str(j))
# For design/spacing.
print("")
|
554fd5879f4e8613e342f6c76be58e0a21065611 | Chicpork/TIL | /CleanCodePython/ch2/iterables.py | 1,241 | 3.9375 | 4 | # %%
from datetime import date, timedelta
class DateRangeIterable:
"""An iterable that contains its own iterator object."""
def __init__(self, start_date, end_date):
self.start_date = start_date
self.end_date = end_date
self._present_day = start_date
def __iter__(self):
return self
def __next__(self):
if self._present_day >= self.end_date:
raise StopIteration
today = self._present_day
self._present_day += timedelta(days=1)
return today
class DateRangeContainerIterable:
"""An range that builds its iteration through a generator."""
def __init__(self, start_date, end_date):
self.start_date = start_date
self.end_date = end_date
def __iter__(self):
current_day = self.start_date
while current_day < self.end_date:
yield current_day
current_day += timedelta(days=1)
# %%
for day in DateRangeIterable(date(2019, 1, 1), date(2019, 1, 5)):
print(day)
# %%
for day in DateRangeContainerIterable(date(2019, 1, 1), date(2019, 1, 5)):
print(day)
# %%
r1 = DateRangeContainerIterable(date(2019, 1, 1), date(2019, 1, 5))
print(", ".join(map(str, r1)))
print(max(r1))
|
d05b098ece960a4d10b4058ccf2b8d7629520ad8 | easykatka04/easy_strr | /ft_count_char_in_str.py | 109 | 3.546875 | 4 | def ft_count_char_in_str(a, b):
c = 0
for i in a:
if i == b:
c += 1
return c
|
15311589d1122ea69e7e73f9a16d2d4bd121eaf8 | RDelg/rl-book | /chapter3/learner.py | 3,053 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.table import Table
from .maze import Enviroment
class ValueLearner(object):
"""Value learner for a 2D grid world.
Parameters
----------
maze : Enviroment
Maze enviroment to work with.
discount : float
Discount factor to calculate the return of the state.
random : bool, default=True
If True, it updates the value of each state simulating taking the action
and then updating the value directly.
If False, it updates the value performing all actions from the state and
then taking the max return between all of them.
"""
def __init__(self, maze: Enviroment, discount: float, random: bool = True):
self.maze = maze
self.random = random
self.value = np.zeros(shape=maze.shape)
self.discount = discount
def update_value(self):
new_value = np.zeros_like(self.value)
values = np.zeros(shape=len(self.maze.actions))
for i in range(self.value.shape[0]):
for j in range(self.value.shape[1]):
for z, action in enumerate(self.maze.actions):
self.maze.set_state(np.array([i, j]))
new_state, reward = self.maze.step(action)
if self.random:
new_value[i, j] += (
1.0
/ len(self.maze.actions)
* (
reward
+ self.discount * self.value[new_state[0], new_state[1]]
)
)
else:
values[z] = (
reward
+ self.discount * self.value[new_state[0], new_state[1]]
)
if not self.random:
new_value[i, j] = np.max(values)
self.value = new_value
def plot_value(self, ax: plt.Axes = None):
if ax is None:
_, ax = plt.subplots()
rounded_value = np.round(self.value, decimals=2)
ax.set_axis_off()
tb = Table(ax, bbox=[0, 0, 1, 1])
nrows, ncols = rounded_value.shape
width, height = 1.0 / ncols, 1.0 / nrows
for (i, j), val in np.ndenumerate(rounded_value):
tb.add_cell(i, j, width, height, text=val, loc="center", facecolor="white")
for i in range(len(rounded_value)):
tb.add_cell(
i,
-1,
width,
height,
text=i + 1,
loc="right",
edgecolor="none",
facecolor="none",
)
tb.add_cell(
-1,
i,
width,
height / 2,
text=i + 1,
loc="center",
edgecolor="none",
facecolor="none",
)
ax.add_table(tb)
|
f0d24ad8911754befad8e7824332714ec16a7fb8 | Melina-Zh/M_L | /nn1.py | 1,036 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 28 16:59:28 2018
@author: Melina
"""
#感知器
import numpy as np
class Perceptron:
def __init__(self,eta=0.01,iter=10):#学习率和迭代次数
self.eta=eta
self.iter=iter
def fit(self,x,y):
self.w=np.zeros(1+x.shape[1])
self.errors=[]
for i in range(self.iter):
errors=0
for xi,target in zip(x,y):
update=self.eta*(target-self.predict(xi))#权重更新
self.w[1:]+=update*xi
self.w[0]+=update*1
errors+=int(update!=0)
self.errors.append(errors)
def net_input(self,x):
return np.dot(x,self.w[1:]+self.w[0]*1) #矩阵乘法
def predict(self,x):
return np.where(self.net_input(x)>=0.0,1,-1)#类似三目运算符
instance=Perceptron(0.01,10)
x=np.array([[1,2],[4,5]])
y=np.array([-1,1])
instance.fit(x,y)
x=np.array([6,6])
print(instance.predict(x))
|
3fd0827e2c0bb92ed205f23420c7c3534951a5fb | jb892/cruw-devkit | /cruw/visualization/draw_rf.py | 1,741 | 3.5625 | 4 | import numpy as np
def magnitude(chirp, radar_data_type):
"""
Calculate magnitude of a chirp
:param chirp: radar data of one chirp (w x h x 2) or (2 x w x h)
:param radar_data_type: current available types include 'RI', 'RISEP', 'AP', 'APSEP'
:return: magnitude map for the input chirp (w x h)
"""
c0, c1, c2 = chirp.shape
if radar_data_type == 'RI' or radar_data_type == 'RISEP':
if c0 == 2:
chirp_abs = np.sqrt(chirp[0, :, :] ** 2 + chirp[1, :, :] ** 2)
elif c2 == 2:
chirp_abs = np.sqrt(chirp[:, :, 0] ** 2 + chirp[:, :, 1] ** 2)
else:
raise ValueError
elif radar_data_type == 'AP' or radar_data_type == 'APSEP':
if c0 == 2:
chirp_abs = chirp[0, :, :]
elif c2 == 2:
chirp_abs = chirp[:, :, 0]
else:
raise ValueError
else:
raise ValueError
return chirp_abs
def draw_centers(ax, chirp, dts, colors, texts=None, chirp_type='RISEP'):
"""
Draw object centers on RF image.
:param ax: plt ax
:param chirp: radar chirp data
:param dts: [n_dts x 2] object detections
:param colors: [n_dts]
:param texts: [n_dts] text to show beside the centers
:param chirp_type: radar chirp type
:return:
"""
chirp_abs = magnitude(chirp, chirp_type)
ax.imshow(chirp_abs, vmin=0, vmax=1, origin='lower')
n_dts = len(dts)
for dt_id in range(n_dts):
color = np.array(colors[dt_id])
color = color.reshape((1, -1))
ax.scatter(dts[dt_id][1], dts[dt_id][0], s=100, c=color, edgecolors='white')
if texts is not None:
ax.text(dts[dt_id][1] + 2, dts[dt_id][0] + 2, '%s' % texts[dt_id], c='white')
|
8c6fc2d2ebb468e9841e5931bb3a157a6ab9ed97 | testroute/HogwartsLG5 | /test_things/test_get_param/testlist.py | 833 | 3.96875 | 4 |
#列表推导式
import datetime
import os
import time
# list3=[i**2 for i in range(1,4) if i !=1]
# print(list3)
# list4=[i*j for i in range(1,4) for j in range(1,5)]
# print(list4.sort())
# tuple1 =1,2,4
# print(type(tuple1))
# list4.pop(2)
# print(list4)
# set1 =set()
# print(set1,type(set1))
# print(os.getcwd())
# # os.path.abspath()
# print(time.strftime("%Y %m %d - %H %M %S", time.localtime(time.time())))
# print(time.localtime(time.time()))
# threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))
# print(threeDayAgo)
# print(datetime.datetime.now())
# :两个无序数组合成一个,并去重,最后从小到大排序
list1=[1,3,6,3,21,56,8]
list2=[3,52,62,2,7,8]
#union intersection difference
set1=set(list1).union(set(list2))
set1.pop()
print(set1)
list1=list(set1)
list1.sort()
print(list1)
|
2487fdd78e971f078f6844a2fa5bb0cd031b0d71 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/week2/src/samples/MathMethods.py | 751 | 4.25 | 4 | # package samples
# math is the python API for numerical calculations
from math import *
def math_program():
f_val = 2.1
print(f"Square root {sqrt(f_val)}")
print(f"Square {pow(f_val, 2)}")
print(f"Floor {floor(f_val)}")
print(f"Ceil {ceil(f_val)}")
print(f"Round {round(f_val)}")
# etc. many more ... type math. (dot) and they will show up ...
print(pi) # Declared in Math library
# Comparing floats
f1 = 1.0 - 0.7 - 0.3 # ~= 0.0
f2 = 1.0 - 0.6 - 0.4 # ~= 0.0
print(f1 == f2) # False!! Rounding error!
print(abs(f1 - f2)) # How large is the rounding error?
# Pythagoras ... (nested calls)
print(sqrt(pow(3, 2) + pow(4, 2)) == 5)
if __name__ == "__main__":
math_program()
|
b4074fc9f325a68ee850c734eb9d7d8814c46a65 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/Week1Exercises/Week1Exercises/week1/src/samples/MethodsBasics.py | 3,542 | 4.40625 | 4 | # package samples
# To structure the program and to help solving specific tasks we use methods.
# Methods, are smaller parts of a program (subprograms)
# - The ideal method returns a calculated value given some input values (similar to a mathematical function)
# - But not all are: Some methods don't take any input and some don't return any result (or both).
#
# Methods here are taking or returning values of primitive types or Strings
#
# Any method *MUST* be declared before use. Method declaration is like:
#
# def name ( parameter list ) -> return_type: (<- method head)
# ...statements ... (<- method body, a block with statements)
#
# - Type after -> is type of value returned (if any), the "return type". This is optional.
# - Name is name of method, to be used when calling the method
# - Parameter list is a number of variable declarations
# (i.e. name, optional type hint, optional default value, separated with ',').
# The parameter variables are used to store incoming data from the method call.
# - The above is collectively named the method head
# - Body is a block of statements that the method should execute. In particular there should
# be a return statement (except if method doesn't return anything).
#
# To call a method (i.e. run the method):
# - Write method name in code, supply arguments in parenthesis.
# - Assign return value to some variable if value should be used later (if not value lost)
# - When assigning result, return type must be compatible with variable type
# - Declared parameter list and arguments values at call must match: number of, type of, order of
#
# NOTE: To inspect the execution of this try the debugger (learn how to use a debugger)
def methods_basics_program():
# Primitive parameters and return values
# Result sent directly to out stream
print(add(1, 3) == 4) # Call to method add, arguments 1 and 3
print(f2c(32) == 0) # Call to method f2c
print(abs(-12) == 12)
print(pow(2, 8) == 256)
print(is_even(6)) # Call method isEven(), argument 6
# Methods with Strings
name = get_name()
welcome(name)
# ----- Method declarations written after (outside) program() ------------
# Method declarations in outermost block
# Method declaration inside other method declaration *NOT* allowed (nested not allowed)
# Order of declarations here doesn't matter (try to change order)
# A method declaration:
# - Return type int, name add, two int parameters named a and b
# - Parameter names may be chosen arbitrary, we need parameters
# for incoming data from call (arguments (values) copied to parameters)
def add(a, b):
return a + b
# Fahrenheit to Celsius
def f2c(fahrenheit):
return (fahrenheit - 32) * 5 / 9
# Sometimes must have more return statement (checked by compiler)
def abs(n):
if n < 0:
return -n
return n
# Mimic built-in ** function
def pow(b, e):
p = 1
for _i in range(e):
p = p * b
return p
# Short boolean method (usage makes code easier to read/understand)
# Expression n % 2 == 0 evaluated, then result sent back, no need for local variables
def is_even(n):
return n % 2 == 0
# String return type
def get_name():
return input("Please enter your name > ")
# String as parameter. void means no return value, so no return statement here.
# This method just performs an action, no value calculated.
def welcome(name):
print("Welcome " + name)
if __name__ == "__main__":
methods_basics_program()
|
a1b609ad8fdc417762f0a8dde352e952751c9672 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/Week1Exercises/Week1Exercises/week1/src/samples/PrimitiveVariables.py | 3,071 | 4 | 4 | # package samples
# Types, literals and primitive variables
#
# The primitive (built in) types (sets of values) in Python are
# Numeric types:
# - int, integers
# - float, real numbers.
# - complex, complex numbers.
# - bool, truth values (are actually considered numeric)
# Sequence types:
# - list, mutable indexed containers.
# - tuple, immutable indexed containers.
# - range, immutable sequence of numbers
# - str, immutable sequence of unicode characters
# Sets and maps:
# - set, unordered container of unique elements
# - dict, mapping of unique keys to values
#
# ... and a bunch of specialized ones that we don't need.
#
# A literal is a fixed value in the code, like 6.7, 'S' or 396 (blue or green in PyCharm)
# A literal never changes. A literal is automatically assigned a type
# - 45 will be an int
# - 3.6 will be a float. Note decimal separator is '.' (dot)
# - True and False will be bool
# - "Hello" or 'Hello' will be str (single or double quotes)
#
# A variable in Python is an alterable container for a specific type of value.
# It is highly recommended to not change the type of value held by a specific variable.
#
# Variables in Python are not (cannot be!) declared before use.
# - Initializing or assigning values to variables is done using the assignment operator '='
#
# To change the value of a primitive variable we may use so called assignment operators,
# such as += or *=.
def primitive_variables_program():
# a # Bad! Must initialize, like below (uncomment to see error message)
a: int = 0 # Declare variable a, name and (optional) type, then initialize to 0
b: int = 5 # 0 and 5 are integer literals (fixed values), automatically assigned type int
# I.e. literals and variables are compatible (types matches)
# a = 1.56 # Bad 1.56 is not an integer (uncomment to see error message)
print(a) # This will print 0 i.e. *value* in variable a on screen
print(b) # 5
# ------ Assignment and in/decrement with ints ----------------
a = 6 # 0 overwritten now a contains 6
b = a # 5 overwritten, replaced with a *copy* of a's value (a is still 6)
print(b) # 6
# b++ # For those familiar with Java/C#/C++: No postfix increment/decrement in Python
b += 1 # Increment value by one (short for b = b + 1)
print(b) # 7
b -= 1 # Decrement
print(b) # 6
a = a + 1 # + is addition. *Right side* of = evaluated first, then copied to left
print(a) # 7
b = b + 2 # Again
print(b) # 9
# -- Other primitive types/variables -----------------------------
bl: bool = True # Note the capital letters for True/False
print(f"{bl} has type {type(bl)}")
f: float = 0.77 # 0.77 is a float literal, assigned type float
print(f"{f} has type {type(f)}")
s: str = "Hello world!" # Single OR double quote for Strings. Anything in quotes is assign type str.
print(f"{s} has type {type(s)}")
s = "" # The empty string, no character at all
print(f"{s} has type {type(s)}")
|
dc51ac0d58866248ae815122aed9640c4bce9d94 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/Week1Exercises/Week1Exercises/week1/src/exercises/Ex7RPS.py | 1,083 | 4.0625 | 4 | # package exercises
from random import random
# /*
# * The Rock, paper, scissor game.
# * See https://en.wikipedia.org/wiki/Rock%E2%80%93paper%E2%80%93scissors
# *
# * This is exercising smallest step programming (no methods needed)
# *
# * Rules:
# *
# * ----------- Beats -------------
# * | |
# * V |
# * Rock (1) --> Scissors (2) --> Paper (3)
# *
# */
def rps_program():
max_rounds = 5
human = 0 # Outcome for player
computer = 0 # Outcome for computer
result = 0 # Result for this round
this_round = 0 # Number of rounds
total: int = 0 # Final result after all rounds
print("Welcome to Rock, Paper and Scissors")
# TODO Write the game here. Use smallest step then surround with loop!!!!
print("Game over!")
if total == 0:
print("Draw")
elif total > 0:
print("Human won.")
else:
print("Computer won.")
if __name__ == "__main__":
rps_program() |
1b54c0d17ea896a12aa2a20779416e0bac85d066 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/week3_tantan/src/exercises/Ex4MedianKthSmallest.py | 901 | 4.15625 | 4 | # package exercises
#
# Even more list methods, possibly even trickier
#
def median_kth_smallest_program():
list1 = [9, 3, 0, 1, 3, -2]
# print(not is_sorted(list1)) # Is sorted in increasing order? No not yet!
# sort(list1) # Sort in increasing order, original order lost!
print(list1 == [-2, 0, 1, 3, 3, 9])
# print(is_sorted(list1)) # Is sorted in increasing order? Yes!
list2 = [5, 4, 2, 1, 7, 0, -1, -4, 12]
list3 = [2, 3, 0, 1]
# print(median(list2) == 2) # Calculate median of elements
# print(median(list3) == 1.5)
list4 = [2, 3, 0, 1, 5, 4]
list5 = [5, 4, 2, 2, 1, 7, 4, 0, -1, -4, 0, 0, 12]
# print(k_smallest(list4, 2) == 1) # Second smallest is 1
# print(k_smallest(list5, 5) == 2) # 5th smallest is 2
# ---------- Write methods here --------------
if __name__ == "__main__":
median_kth_smallest_program()
|
16acd854ef3b668e05578fd5efff2b5c2a6f88f4 | Dunkaburk/gruprog_1 | /grundlaggande_programvareutveckling/Week1Exercises/Week1Exercises/week1/src/exercises/Ex2EasterSunday.py | 1,705 | 4.3125 | 4 | # package exercises
# Program to calculate easter Sunday for some year (1900-2099)
# https://en.wikipedia.org/wiki/Computus (we use a variation of
# Gauss algorithm, scroll down article, don't need to understand in detail)
#
# To check your result: http://www.wheniseastersunday.com/
#
# See:
# - LogicalAndRelationalOps
# - IfStatement
def when_is_easter_sunday_program():
# int a, b, c, d, e, s, t // Avoid variables on same line (but acceptable here)
# int date;
# int year;
# int month = 0;
# ---- Input --------------
year = int(input("Input a year (1900-2099) > "))
# ----- Process -----------
a = year % 19 # Don't need to understand, Gauss did understand
b = year % 4
c = year % 7
s = 19 * a + 24
d = s % 30
t = 2 * b + 4 * c + 6 * d + 5
e = t % 7
date = 22 + d + e
# TODO Now you continue ...
# If date is less than 32, then date is found and month is march.
# Else: Date is set to d + e - 9 and month is april ...
# ... but with two exceptions
# If date is 26 easter is on 19 of april.
# If date is 25 and a = 16 and d = 28 then date is 18 of april.
if date < 32 and date!=26 and date!=25:
month = "march"
elif date == 26:
month = "april"
date = 26
elif date == 25 and a == 16 and d == 28:
month = "april"
date = 18
else:
month = "april"
date = d + e - 9
# --------- Output -----------
print("Easter Sunday for " + str(year) + " is : " + str(date) + "/" + str(month))
# Recommended way to make module executable
if __name__ == "__main__":
when_is_easter_sunday_program()
|
98f95c15adc57a9ecc6153fb8834e239a4b47465 | aneekdas96/MIT_6034_Lab | /lab8/lab8/lab8.py | 9,289 | 3.5625 | 4 | # MIT 6.034 Lab 8: Bayesian Inference
from nets import *
#### Part 1: Warm-up; Ancestors, Descendents, and Non-descendents ##############
def get_ancestors(net, var):
"Return a set containing the ancestors of var"
ancestors = set()
list_of_vars = [var]
while list_of_vars != []:
current_var = list_of_vars[0]
list_of_vars.pop(0)
parents_of_current_var = net.get_parents(current_var)
for parent in parents_of_current_var:
ancestors.add(parent)
list_of_vars.append(parent)
return ancestors
def get_descendants(net, var):
"Returns a set containing the descendants of var"
descendants = set()
list_of_vars = [var]
while list_of_vars != []:
current_var = list_of_vars[0]
list_of_vars.pop(0)
children_of_current_var = net.get_children(current_var)
for child in children_of_current_var:
descendants.add(child)
list_of_vars.append(child)
return descendants
def get_nondescendants(net, var):
"Returns a set containing the non-descendants of var"
children = get_descendants(net, var)
variables = set(net.get_variables())
non_descendants = variables - children
non_descendants.remove(var)
return non_descendants
#### Part 2: Computing Probability #############################################
def simplify_givens(net, var, givens):
"""
If givens include every parent of var and no descendants, returns a
simplified list of givens, keeping only parents. Does not modify original
givens. Otherwise, if not all parents are given, or if a descendant is
given, returns original givens.
"""
#condition1 : all parents included and no descendants
givens_keys = set(givens.keys())
new_givens = {}
flag = False
non_descendants = get_nondescendants(net, var)
parents = net.get_parents(var)
descendants = get_descendants(net, var)
for item in givens_keys:
if item in descendants:
flag = True
if parents - givens_keys == set() and givens_keys - descendants == givens_keys:
to_remove = non_descendants - parents
for item in givens_keys:
if item not in to_remove:
new_givens[item] = givens[item]
return new_givens
elif parents - givens_keys != set() or flag == True:
return givens
def probability_lookup(net, hypothesis, givens=None):
"Looks up a probability in the Bayes net, or raises LookupError"
try:
simplified_givens = None
if givens != None:
var = list(hypothesis.keys())[0]
simplified_givens = simplify_givens(net, var, givens)
prob = net.get_probability(hypothesis, simplified_givens)
return prob
except ValueError:
raise LookupError
def probability_joint(net, hypothesis):
"Uses the chain rule to compute a joint probability"
list_of_variables = net.topological_sort()
total_prob = 1
for index, var in enumerate(list_of_variables):
hyp_temp = {}
given_var = {}
hyp_temp[var] = hypothesis[var]
given_parents = net.get_parents(var)
for parent in given_parents:
given_var[parent] = hypothesis[parent]
total_prob = total_prob * probability_lookup(net, hyp_temp, given_var)
return total_prob
def probability_marginal(net, hypothesis):
"Computes a marginal probability as a sum of joint probabilities"
sum_prob = 0
vars_in_net = net.get_variables()
vars_in_hyp = list(hypothesis.keys())
other_vars = []
for var in vars_in_net:
if var not in vars_in_hyp:
other_vars.append(var)
combine_dicts = net.combinations(other_vars, hypothesis)
for dict_var in combine_dicts:
sum_prob = sum_prob + probability_joint(net, dict_var)
return sum_prob
def probability_conditional(net, hypothesis, givens=None):
"Computes a conditional probability as a ratio of marginal probabilities"
#base case, no conditionals
if givens == None:
return probability_marginal(net, hypothesis)
hyp_vars = list(hypothesis.keys())
given_vars = list(givens.keys())
common_vars = [var for var in hyp_vars if var in given_vars]
#edge case, one variable common in hypothesis and givens
if givens!=None:
if len(hyp_vars) == 1 and len(given_vars) == 1 and hyp_vars[0] == given_vars[0]:
if hypothesis[hyp_vars[0]] == givens[given_vars[0]]:
return 1
else:
return 0
#eliminating common vars
for var in common_vars:
if hypothesis[var] == givens[var]:
hypothesis.pop(var)
elif hypothesis[var] != givens[var]:
return 0
try:
prob = probability_lookup(net, hypothesis, givens)
return prob
except Exception as e:
new_hyp = dict(hypothesis, **givens)
num = probability_marginal(net, new_hyp)
den = probability_marginal(net, givens)
div_val = num/den
return div_val
def probability(net, hypothesis, givens=None):
"Calls previous functions to compute any probability"
hyp_vars = set(list(hypothesis.keys()))
all_vars = set(net.get_variables())
if all_vars - hyp_vars== set():
return probability_joint(net, hypothesis)
elif hyp_vars - all_vars != set() and given == None:
return probability_marginal(net, hypothesis)
else:
return probability_conditional(net, hypothesis, givens)
#### Part 3: Counting Parameters ###############################################
def number_of_parameters(net):
"""
Computes the minimum number of parameters required for the Bayes net.
"""
all_vars = net.topological_sort()
net_params = []
for var in all_vars:
#getting number of columns
no_values = len(net.get_domain(var))
if no_values == 1:
columns = 1
elif no_values >1:
columns = no_values - 1
#getting number of rows
parents = net.get_parents(var)
no_parents = len(parents)
if parents == set():
rows = 1
else:
rows = 1
for parent in parents:
parents_values = len(net.get_domain(parent))
rows = rows * parents_values
params = rows * columns
net_params.append(params)
store = sum(net_params)
return store
#### Part 4: Independence ######################################################
def is_independent(net, var1, var2, givens=None):
"""
Return True if var1, var2 are conditionally independent given givens,
otherwise False. Uses numerical independence.
"""
#marginal case
flag = True
if givens == None:
values_var1 = net.get_domain(var1)
values_var2 = net.get_domain(var2)
for val1 in values_var1:
for val2 in values_var2:
hypothesis = {var1:val1, var2:val2}
actual_marginal = probability_marginal(net, hypothesis)
var1_marginal = probability_marginal(net, {var1: val1})
var2_marginal = probability_marginal(net, {var2: val2})
prod_marginal = var1_marginal * var2_marginal
if approx_equal(actual_marginal, prod_marginal, epsilon=0.0000000001) == False:
flag = False
if flag == False:
return False
else:
return True
else:#conditional case
values_var1 = net.get_domain(var1)
values_var2 = net.get_domain(var2)
count1 = 0
for val1 in values_var1:
for val2 in values_var2:
hypothesis = {var1:val1}
new_givens = givens.copy()
new_givens[var2] = val2
eval_val = probability_conditional(net, hypothesis, givens)
orig_val = probability_conditional(net, hypothesis, new_givens)
if approx_equal(eval_val, orig_val, epsilon=0.0000000001) == False:
flag = False
if flag == False:
return False
else:
return True
def is_structurally_independent(net, var1, var2, givens=None):
"""
Return True if var1, var2 are conditionally independent given givens,
based on the structure of the Bayes net, otherwise False.
Uses structural independence only (not numerical independence).
"""
if givens != None:
list_of_val = [var1, var2]+list(givens.keys())
else:
list_of_val = [var1, var2]
for val in list_of_val:
ancestors = get_ancestors(net, val)
list_of_val += list(ancestors)
list_of_val = set(list_of_val)
sub_net = net.subnet(list_of_val)
parents_to_marry = []
for v1 in sub_net.get_variables():
c1 = sub_net.get_children(v1)
for v2 in sub_net.get_variables():
c2 = sub_net.get_children(v2)
if v1!=v2 and len(c1.intersection(c2)) != 0:
parents_to_marry.append((v1, v2))
for pair in parents_to_marry:
sub_net.link(pair[0],pair[1])
sub_net.make_bidirectional()
if givens != None:
for g in givens:
sub_net.remove_variable(g)
if sub_net.find_path(var1, var2):
return False
else:
return True
#### SURVEY ####################################################################
NAME = 'Aneek Das'
COLLABORATORS = ''
HOW_MANY_HOURS_THIS_LAB_TOOK = 10
WHAT_I_FOUND_INTERESTING = ''
WHAT_I_FOUND_BORING = ''
SUGGESTIONS = ''
|
721f17df884a01ef034deabcb6a71030f44bc438 | wll1014/KKB | /beforeClass/KKB1.py | 1,442 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 06:32:28 2019
@author: llwu
"""
import math
num_str = input("请输入整数:");
num = int(num_str)
num_n = math.sqrt(num)
n = math.floor(num_n)
left_min = n*n
mid_value = n*n + n+1
right_max = (n+1)*(n+1)
def getLeftRightSteps(input_num):
letf_right_steps = math.ceil(input_num/2)-1
up_down_steps = math.floor(input_num/2)
return {
"letf_right_steps":letf_right_steps,
"up_down_steps":up_down_steps
}
def getTotalSteps(num):
if num==left_min:
obj_steps = getLeftRightSteps(n)
left_right_steps = obj_steps["letf_right_steps"]
up_down_steps = obj_steps["up_down_steps"]
return left_right_steps+up_down_steps
else:
if num<mid_value:
obj_steps = getLeftRightSteps(n)
left_right_steps = obj_steps["letf_right_steps"]
up_down_steps = obj_steps["up_down_steps"]
return left_right_steps + 1 +abs(up_down_steps-(num-left_min-1))
else:
obj_steps = getLeftRightSteps(n+1)
left_right_steps = obj_steps["letf_right_steps"]
up_down_steps = obj_steps["up_down_steps"]
return abs(left_right_steps-(right_max-num)) + up_down_steps
total_steps = getTotalSteps(num)
print("total_steps",total_steps) |
9108f6979c6c6626061dc6331eaf870058ba1ff0 | SpyderXu/coding | /template/Prim最小生成树.py | 1,420 | 3.5 | 4 | class edge:
def __init__(self, u, v, w):
self.u = u
self.v = v
self.w = w
def either(self, ):
return self.u
def other(self, p):
if self.u == p:
return self.v
else:
return self.u
def __lt__(self, other):
return self.w < other.w
class PrimMST:
def __init__(self, N):
self.graph = [set() for i in range(N)]
self.N = N
self.marked = [0 for i in range(N)]
self.pq = queue.PriorityQueue()
self.mst = queue.Queue()
def add_egde(self, eg):
u = eg.either()
v = eg.other(u)
self.graph[u].add(eg)
self.graph[v].add(eg)
def add_edges(self, egs):
for eg in egs:
self.add_edge(eg)
def visit(self, v):
self.marked[v] = 1
for eg in self.graph[v]:
u = eg.other(v)
if self.marked[u] == 0:
self.pq.put(eg)
def get_mst(self):
self.visit(0)
while not self.pq.empty():
front = self.pq.get()
u = front.either()
v = front.other()
if self.marked[u] and self.marked[v]:
continue
self.mst.put(front)
if self.marked[u] == 0:
self.visit(u)
if self.marked[v] == 0:
self.visit(v)
return self.mst |
db73fa6e98d9f30aba22d3c4be6be39f7a1529ea | FightingTigers/tic-tac-toe | /student1.py | 2,100 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 23 07:13:26 2019
@author: chaninlaohaphan
"""
from player import MachinePlayer
import random
class RandomBot(MachinePlayer):
def make_move(self, board):
x = random.randrange(3)
y = random.randrange(3)
while board[x][y] != ' ':
x = random.randrange(3)
y = random.randrange(3)
return (x,y)
class ThinkBot(MachinePlayer):
def make_move(self, board):
points = self.get_winning_positions(board, self.check_win)
if len(points) > 0:
return points[random.randrange(len(points))]
points = self.get_winning_positions(board, self.check_lose)
if len(points) > 0:
return points[random.randrange(len(points))]
points = self.get_playable_positions(board)
if len(points) > 0:
return points[random.randrange(len(points))]
return None
def get_winning_positions(self, board, check_win):
result = []
for i in range(3):
if check_win(board[i]):
result.append((i, board[i].index(' ')))
column = [board[0][i], board[1][i], board[2][i]]
if check_win(column):
result.append((column.index(' '), i))
diagonal = [board[0][0], board[1][1], board[2][2]]
if check_win(diagonal):
x = diagonal.index(' ')
result.append((x, x))
diagonal = [board[2][0], board[1][1], board[0][2]]
if check_win(diagonal):
x = diagonal.index(' ')
result.append((2-x,x))
return result
def check_win(self, row):
return row.count(self.piece) == 2 and row.count(' ') == 1
def check_lose(self, row):
return row.count(self.piece) == 0 and row.count(' ') == 1
def get_playable_positions(self, board):
return [(row_index, col_index) for row_index in range(3)
for col_index in range(3) if board[row_index][col_index] == ' ']
|
516bb485b9f00ac390e40581cb3c508b54ffbc48 | justPerson787/Volcanoes-Webmap | /app.py | 1,007 | 3.515625 | 4 | import folium
import pandas #to load csv file with data
data = pandas.read_csv("Volcanoes.txt")
lat = list(data["LAT"])
lon = list(data["LON"])
elevation = list(data["ELEV"])
def marker_color(elevation):
if elevation < 1000:
return 'green'
elif 1000 <= elevation < 3000:
return 'orange'
else:
return 'red'
#create a map object with folium and Leaflet.js
#html for pop-up window on markers
html = """<h4>Volcano information:</h4>
Height: %s m
"""
map = folium.Map(location = [38.58, -99.09],zoom_start=6, tiles = "Mapbox Bright")
feature_group = folium.FeatureGroup(name = 'Map')
for lt, ln, el in zip(lat, lon, elevation):
iframe = folium.IFrame(html=html % str(el), width=200, height=100)
feature_group.add_child(folium.CircleMarker(location = [lt, ln], popup = folium.Popup(iframe),
radius = 8, fill_color = marker_color(el), fill_opacity = 0.8, color = 'grey'))
map.add_child(feature_group)
map.add_child(folium.LayerControl())
map.save("map.html") |
35cdae6706209bde1e562dd18200d9d7c6825e78 | Momemo/PortScanner | /portScanner.py | 1,534 | 3.609375 | 4 | import socket
import threading
from queue import Queue
open_ports = [] # list for open ports
queue = Queue() # empty queue
target = '' # IP address to scan
# This function creates a socket and attempts to connect with given port and IP
# Connection is only sucessful if the port is open
# returns true or false
def portscan(port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target, port))
return True
except:
return False
# This function fills the queue with ports given the port list
def fill_queue(port_list):
for port in port_list:
queue.put(port)
# This function iterates through the queue until its empty
# If the port is open it prints the port
def worker():
while not queue.empty():
port = queue.get()
if portscan(port):
print("port {} is open".format(port))
open_ports.append(port)
port_list = range(1, 500) # Range of the ports to check
fill_queue(port_list) # Call fill queue function passing in the list of ports
thread_list = [] # Create empty list of thread
for t in range(100): # Create 10 threads
thread = threading.Thread(target=worker) # instantiate the thread class with target worker
thread_list.append(thread) # add thread to list
for thread in thread_list: # start thread
thread.start()
for thread in thread_list: # wait for the threads to finish before printing the list of open ports
thread.join()
print("Open ports are ", open_ports)
|
3652541c2e8a1fde2e8924b18df74bdb508c739c | nicky1211/DSALabAssignments | /StackExceptionImplement.py | 1,479 | 3.859375 | 4 | class Error(Exception):
"""Base class for other exceptions"""
pass
class ArrayFullException(Error):
"""Raised when elements are tried to be added when the size if full"""
pass
class ArrayStack:
""" LIFO stack implementation usinng Python list as underlying storage """
def __init__ (self,MAX_LEN = 1):
""" Creat an empty stack """
self._restrictedLenght = MAX_LEN
self._data = []
self._top = -1
self._size = 0
def len (self):
""" Return the number of elements in the stack """
return len (self._data)
def is_empty (self):
""" Return True if the stack is empty """
return len(self._data) == 0
def push (self, e):
try:
if len(self._data) == self._restrictedLenght:
raise ArrayFullException
else:
self._data.append(e)
self._top +=1
except ArrayFullException:
print("The Max Size is reached!")
def top (self):
""" Return (but do not remove) the element at the top of the stack
"""
if self.is_empty():
print('Stack is empty')
else:
return self._data[-1]
def pop (self):
""" Remove and return the element from the top of the stack
"""
if self.is_empty():
print('Stack is empty')
else:
return self._data.pop()
def display(self):
print self._data
def test_stack():
size = 5
st = ArrayStack(size)
st.push(10)
st.push(20)
st.push(30)
st.push(40)
st.push(50)
#Adding the extra element will throw the exception
st.push(60)
if __name__ == '__main__':
test_stack() |
bb15f7b01e6cdd880a79d1febaa15a8d94efe4a8 | davidich/ucla_ml | /Week 04 (hw3)/Homework 03/utils_linear_regression.py | 583 | 3.546875 | 4 | import numpy as np
def h(x: np.ndarray, theta: np.ndarray):
"""
Linear regression hypothesis function.
:param x: Features. N*M matrix. N-instances, M-features
:param theta: Bias + Weights; M*1 column vector
:return: Prediction (y_hat). N*1 column vector
"""
return np.array(x @ theta, dtype=np.float64)
def cost(y_h: np.ndarray, y: np.ndarray):
"""
Cost function for linear regression.
:param y_h: Hypothesis value; M*1 column vector
:param y: Target value; M*1 column vector
:return:
"""
return np.average((y_h - y) ** 2)
|
ea93754a85444bff205ca1803dc04a38f26c0035 | lihalyf/Python | /Restore_IP_Address.py | 1,316 | 3.84375 | 4 | """
426. Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example
Given "25525511135", return
[
"255.255.11.135",
"255.255.111.35"
]
Order does not matter.
"""
class Solution:
"""
@param s: the IP string
@return: All possible valid IP addresses
"""
def restoreIpAddresses(self, s):
# write your code here
if s == None:
return None
result =[]
self.dfs(s, [], result, 0)
dic = {}
for r in result:
if r in dic:
continue
dic[r] = 1
return dic.keys()
def dfs(self, s, subset, result, level):
if len(s) == 0:
if level == 4:
string = "".join(subset)
return result.append(string)
else:
return
for i in range(1, 4):
prefix = s[:i]
if int(prefix) > 255:
continue
if len(prefix) > 1 and prefix[0] == '0':
continue
if level == 3:
subset.append(prefix)
else:
subset.append(prefix + '.')
self.dfs(s[i:], subset, result, level + 1)
subset.pop()
|
f6d7ce480778d230d09d31e6b0c53fdbb96a9cca | anthonysim/Python | /Intro_to_Programming_Python/supremeCourt2.py | 649 | 3.703125 | 4 | """
Supreme Court
A program that requests the name of a president as input and then
displays the names and years of the justices appointed by that president.
"""
import pickle
def main():
dicLst = createDictFromBinaryFile("JusticesDict.dat")
president = input("Enter a president: ")
getJustice(dicLst, president)
def createDictFromBinaryFile(file):
infile = open(file, 'rb')
dicLst = pickle.load(infile)
infile.close()
return dicLst
def getJustice(dicLst, president):
for k in dicLst:
if dicLst[k]['pres'] == president:
print(" {0:17}{1:4}".format(k, dicLst[k]['yrAppt']))
else:
pass
main()
|
45d7b3ced0aafd996aeb5d6cb41fbc96e222a75f | anthonysim/Python | /Intro_to_Programming_Python/min.py | 437 | 4.09375 | 4 | """
Min Function
A function that returns the minimum value in a list of numbers.
"""
def main():
min_number = min()
print("Your minimum number is:", min_number)
def min():
count = int(input("How many numbers in your list?: "))
numbers = []
for number in range(count):
number = int(input("Enter a number: "))
numbers.append(number)
numbers.sort()
min_number = numbers[0]
return min_number
main()
|
fd550e115ac526fe5ac6bc9543278a7d852325b6 | anthonysim/Python | /Intro_to_Programming_Python/pres.py | 444 | 4.5 | 4 | """
US Presidents
Takes the names, sorts the order by first name, then by last name.
From there, the last name is placed in front of the first name, then printed
"""
def main():
names = [("Lyndon, Johnson"), ("John, Kennedy"), ("Andrew, Johnson")]
names.sort(key=lambda name: name.split()[0])
names.sort(key=lambda name: name.split()[1])
for name in names:
space = name.find(" ")
print(name[space + 1:] + ", " + name[ : space-1])
main()
|
25259da4f2ae15d1aa7abbbcb774ea7e55aaee46 | anthonysim/Python | /Intro_to_Programming_Python/oscars.py | 882 | 3.84375 | 4 | """
Academy Awards
A program that displays the different film genres,
requests a genre as input, and then diplays the Oscar-winning films
of that genre.
Use Oscars.txt
"""
def main():
oscars = getData("Oscars.txt")
print()
genre = input("Enter a genre: ")
genre = genre.lower()
winners(oscars, genre)
def getData(f):
infile = open(f, 'r')
genres = [line.rstrip().split(',')[-1] for line in infile]
infile.close()
genres = set(genres)
genres = list(genres)
genres.sort()
print()
print("The different film genres are as follows: ")
for item in genres:
print(" " + item)
infile = open(f, 'r')
oscars = [line.rstrip().split(',') for line in infile]
infile.close()
return oscars
def winners(oscars, genre):
for item in oscars:
if item[1] == genre:
print(" " + item[0])
else:
pass
main() |
339ab46faa86b3adc7d9408ee33f796937b6b5a0 | anthonysim/Python | /Exercises/showStars.py | 204 | 3.703125 | 4 | # A function that forms a "tree" based on
# the amount of rows specified.
def showStars(row):
for i in range(1, row + 1):
stars = '*' * i
print(stars)
showStars(5)
|
500d87f1048fe284c7eb13320e401a0482430cfb | LachezarStoev/Programming-101 | /sum_of_divisors/solution.py | 271 | 3.75 | 4 | def sum_of_divisors(n):
sum=0
for div in range(1,n+1):
if(n%div==0):
sum+=div
return sum
def main():
print(sum_of_divisors(8))
print(sum_of_divisors(7))
print(sum_of_divisors(1))
print(sum_of_divisors(1000))
if __name__ == '__main__':
main() |
3325f75a27d76e34d2c5b22f74ae4a1840f42f2a | LachezarStoev/Programming-101 | /sudoku_solved/solution.py | 660 | 3.6875 | 4 | def column(matrix, i):
return [row[i] for row in matrix]
def row(matrix,i):
return matrix[i]
def take_submatrix_3x3(matrix,p,q):
return [matrix[i][j] for i in range(p,p+3) for j in range(q,q+3)]
def is_array_solved(arr):
unique_numbers=set(arr)
restricted_numbers=[x for x in unique_numbers if x in range(1,10)]
return len(arr) == len(restricted_numbers)
def sudoku_solved(sudoku):
for i in range(0,len(sudoku)):
if not is_array_solved(row(sudoku,i)) or not is_array_solved(column(sudoku,i)):
return False
all_submatrix_3x3=[is_array_solved(take_submatrix_3x3(sudoku,i,j)) for i in [0,3,6] for j in [0,3,6]]
return sum(all_submatrix_3x3) != 0
|
2922ae993bbebccd772d493f79c9a56e7934cccc | LachezarStoev/Programming-101 | /prime_factiorization/solution.py | 594 | 3.8125 | 4 | from itertools import dropwhile, takewhile
def prime_factorization(n):
divs=[]
while(n>1):
for div in range(2,n+1):
if(n%div==0):
divs.append(div)
n//=div
break
result=[]
while(divs != []):
countOfDiv=list(takewhile(lambda x: x==divs[0], divs))
result.append((countOfDiv[0],len(countOfDiv)))
divs=list(dropwhile(lambda x: x==divs[0],divs))
return result
def main():
print(prime_factorization(10))
print(prime_factorization(14))
print(prime_factorization(356))
print(prime_factorization(89))
print(prime_factorization(1000))
if __name__ == '__main__':
main()
|
64d3df0e9550e9f1d1c424ef215675a3251b05b1 | LachezarStoev/Programming-101 | /contains_digits/solution.py | 417 | 3.828125 | 4 | def contains_digits(number, digits):
digitsOfNumber=[]
while number!=0:
digitsOfNumber.append(number%10)
number//=10
for digit in digits:
if(not digit in digitsOfNumber):
return False
return True
def main():
print(contains_digits(402123, [0, 3, 4]))
print(contains_digits(666, [6,4]))
print(contains_digits(123456789, [1,2,3,0]))
print(contains_digits(456, []))
if __name__ == '__main__':
main() |
024b941a6ea2e4efae5ac689a96c2feeaa2b257f | LachezarStoev/Programming-101 | /sum_of_min_and_max/solution.py | 279 | 3.671875 | 4 | def sum_of_min_and_max(arr):
maxElem=max(arr)
minElem=min(arr)
return maxElem+minElem
def main():
print(sum_of_min_and_max([1,2,3,4,5,6,8,9]))
print(sum_of_min_and_max([-10,5,10,100]))
print(sum_of_min_and_max([1]))
if __name__ == '__main__':
main() |
73e7c59448d7646c76286b13dc3d3db3a3dae71d | LachezarStoev/Programming-101 | /sevens_in_a_row/solution.py | 329 | 3.734375 | 4 | def sevens_in_a_row(arr, n):
if( len([x for x in arr if x==7]) >= n):
return True
return False
def main():
print(sevens_in_a_row([10,8,7,6,7,7,7,20,-7], 3))
print(sevens_in_a_row([1,7,1,7,7], 4))
print(sevens_in_a_row([7,7,7,1,1,1,7,7,7,7], 3))
print(sevens_in_a_row([7,2,1,6,2], 1))
if __name__ == '__main__':
main() |
8195e2ea8fcf12229f2ae307020c1fb1b4d21f59 | andrevalasco/ex_python | /ex011.py | 289 | 3.890625 | 4 | l = float(input('Digite a largura da parede: '))
h = float(input('Digite a altura da parede: '))
a = l * h
tinta = a / 2
print('Sua parede tem dimensão {}X{} e sua área é de {} m²'.format(l, h, a))
print('Será necessário {:.2f} l de tinta para pintar esta parede'.format(tinta)) |
b7982e3ed0c4eb5735965df136f16e630ab0fcea | tomasolodun/lab10 | /1.4.1.py | 1,870 | 3.765625 | 4 | """Сформувати функцію для введення з клавіатури послідовності чисел і виведення
її на екран у зворотному порядку (завершаючий символ послідовності – крапка)"""
import timeit
def reverse(n):
if len(n) == 1:
return n[0]
else:
return (n[len(n) - 1] + reverse(n[0:len(n) - 1])) # Поки не закінчаться елементи,
# додаємо елементи з кінця списку в початок,звертаючись до функції знову і знову
def reverse_iter(n):
n1 = []
m = len(n)
for i in range(m):
n1.append(n[m - i - 1])
return n1
n = []
item = 0
k = 0
while item != '.': # Ввід елементів, поки не зустрінеться крапка
k += 1
item = input(f'Введіть {k} елемент: ')
n.append(item)
else:
n.pop() # Видаляємо крапку і отримуємо новий список для подальших дій. Я вважаю, крапка є стопом,
# але не відноситься
# до списку, тому далі я її не враховуватиму і не виводитиму в новому перевернутому списку
print(n)
check = int(input('Виберіть тип виконання операції: 1 - рекурсія, 2 - ітерація. '))
if check == 1:
print(reverse(n)) # Вибір виконання
elif check == 2:
print(reverse_iter(n))
t = timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) # Обрахування часу виконання програми
print(f"Програма виконана за {t} секунд")
|
b2bc221c2df88427fc52958cdd5276a219422dc1 | acbalanza/PythonDoesWhat | /pdw_019_the_confusingly_named_setdefault.py | 978 | 3.8125 | 4 | pdw_id = 19
title = "The confusingly named setdefault"
pub_date = (2010, 12, 28, 11, 42)
author = "Kurt"
tags = ("dict", "setdefault", "collections", "defaultdict")
"""
dict.setdefault(key[, default]) returns the key's value if the key is in the dict.
If it's not, it inserts the default and returns that value. An equivalent function
is described below.
"""
def setdefault_py(my_dict, key, default):
my_dict[key] = my_dict.get(key, default)
return my_dict[key]
"""
Let's take it for a spin:
>>> d = {}
>>> setdefault_py(d, "a", "b")
'b'
>>> d.setdefault(1, 2)
2
>>> setdefault_py(d, "a", "c")
'b'
>>> d.setdefault(1, 3)
2
>>> d
{'a': 'b', 1: 2}
This function is useful in similar cases to a collections.defaultdict. The difference
being, with this function you can choose what you want the default to be each time you
fetch a key from the dictionary. With a defaultdict, the default value for a missing
key must be set at construction time.
"""
|
378cf33e916102adad2d424f85c24484bebfd4f2 | vibin000/twitter-automation-follower-ing-list | /example.py | 1,523 | 3.859375 | 4 | #This is an example which demonstrates how to call the class defined earlier ("twitterBot") and store different calls with different list based on the call to different variables as desired.
#First run the scripts in twitter_automate.py file ,and after defining the class in it ,run the below code.
#For storing the followers into a list named "followers_list" in python
followers_list = twitterBot("username","password").get_followers()
#For storing the users you are following into a list named "following_list" in python
following_list = twitterBot("username","password").get_following()
#For storing the people who have not followed you but followed by you into a list named "following_list" in python.
unfollower_list = twitterBot("username","password").get_unfollowers()
#For storing followers,follwing and unfollowers as a tuple named "all" in python
all_list = twitterBot("username","password").get_all()
#Excel sheet that provide all the above information as 3 seperate excel sheets in an single excel file.
#The example below is for the function call ".get_all()".You can run the code below for any of the embeded functions within the twitterBot call.
import pandas as pd
writer = pd.ExcelWriter(r'Please provide a complete path where you want to store the excel file(example-C:\Users\excel.xlsx)', engine = 'xlsxwriter')
all_list.to_excel(writer,sheet_name= 'Following')
all_list.to_excel(writer,sheet_name= 'Followers')
all_list.to_excel(writer,sheet_name= 'UnFollowing')
writer.save()
writer.close()
|
b47b32ce3cbfeb871e32b807b85662f46fa26b65 | bobradov/Neuromorphic | /mlp2.py | 5,189 | 4.3125 | 4 | """ Multilayer Perceptron.
A Multilayer Perceptron (Neural Network) implementation example using
TensorFlow library. This example is using the MNIST database of handwritten
digits (http://yann.lecun.com/exdb/mnist/).
Links:
[MNIST Dataset](http://yann.lecun.com/exdb/mnist/).
Project: https://github.com/aymericdamien/TensorFlow-Examples/
"""
# ------------------------------------------------------------------
#
# THIS EXAMPLE HAS BEEN RENAMED 'neural_network.py', FOR SIMPLICITY.
#
# ------------------------------------------------------------------
from __future__ import print_function
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
import tensorflow as tf
class mlp_nn(object):
'''
Object for constructing MLPs
'''
def __init__(self, layers, X, Y):
self.n_inputs = layers[0]
self.n_classes = layers[-1]
self.n_layers = len(layers)
# Create weights and biases
self.weights = [ tf.Variable(tf.random_normal( [layers[i], layers[i+1] ]),
name='weight_' + str(i))
for i in range(0, self.n_layers - 1) ]
print('weights: ', self.weights)
self.biases = [ tf.Variable(tf.random_normal( [layers[i+1]]),
name='bias_' + str(i))
for i in range(0, self.n_layers - 1) ]
print('biases: ', self.biases)
# Create NN function
cur_model = X
for layer_index in range(0, self.n_layers - 1):
# Add a z-value
cur_model = tf.add(
tf.matmul(cur_model, self.weights[layer_index]),
self.biases[layer_index],
name='logit_' + str(layer_index)
)
# Add activation
# Sigmoid, except at last layer
if layer_index < self.n_layers - 2:
print('Adding sigmoid ...')
cur_model = tf.sigmoid(cur_model,
name='sigmoid_' + str(layer_index))
#cur_model = tf.nn.relu(cur_model)
# Store completed model
self.logits = cur_model
self.pred = tf.nn.softmax(self.logits, name='Prediction')
self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=self.logits, labels=Y), name='Loss')
# Parameters
learning_rate = 0.01
training_epochs = 300
batch_size = 256
display_step = 20
# Network Parameters
n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 10 # MNIST total classes (0-9 digits)
# tf Graph input
X = tf.placeholder("float", [None, n_input], name='X')
Y = tf.placeholder("float", [None, n_classes], name='Y')
# Construct model
nn_model = mlp_nn([784, 200, 10], X, Y)
#nn_model = mlp_nn([n_input, 50, n_classes], X, Y)
#nn_model = mlp_nn([n_input, 50, 50, 50, 50, n_classes], X, Y)
#logits = nn_model.model
#print(logits)
#exit()
# Define loss and optimizer
loss_op = nn_model.loss
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, name='optim')
#optimizer = tf.train.AdagradOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op, name='optim_min')
# Initializing the variables
init = tf.global_variables_initializer()
# Test model
pred = nn_model.pred # Apply softmax to logits
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1),
name='correct_prediction')
# Calculate accuracy
test_accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"),
name='accuracy')
with tf.Session() as sess:
sess.run(init)
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
# Run optimization op (backprop) and cost op (to get loss value)
_, c = sess.run([train_op, loss_op], feed_dict={X: batch_x,
Y: batch_y})
# Compute average loss
avg_cost += c / total_batch
# Display logs per epoch step
if epoch % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost), end=' ')
# Display test accuracy per epoch
print("Train Accuracy:", test_accuracy.eval( {X: batch_x, Y: batch_y} ), end=' ')
print("Test Accuracy:", test_accuracy.eval(
{X: mnist.test.images, Y: mnist.test.labels} ) )
print("Optimization Finished!")
print("Test Accuracy:", test_accuracy.eval({X: mnist.test.images, Y: mnist.test.labels}))
# Save the graph structure
print('type:')
print(type(nn_model.pred))
writer = tf.summary.FileWriter('./graph_logs', graph=sess.graph)
|
0d1aa02446e1cde49c7a26e347924cf4a24eea36 | antondelchev/For-Loop---Lab | /11. Clever Lily.py | 824 | 3.84375 | 4 | age = int(input())
washing_machine_price = float(input())
single_toy_price = int(input())
toys_number = 0
money_as_a_gift_each_birthday = 0
money_collected_as_gift = 0
money_total = 0
for i in range(1, age + 1):
if i % 2 == 0:
money_as_a_gift_each_birthday += 10
money_collected_as_gift += money_as_a_gift_each_birthday
money_collected_as_gift -= 1
else:
toys_number += 1
sold_toys = toys_number * single_toy_price
money_total = money_collected_as_gift
all_birthdays_funds = sold_toys + money_total
if all_birthdays_funds >= washing_machine_price:
funds_left = all_birthdays_funds - washing_machine_price
print(f"Yes! {funds_left:.2f}")
else:
funds_needed = washing_machine_price - all_birthdays_funds
print(f"No! {funds_needed:.2f}")
|
bb7aae8701b531bbb2f0f460f4eed3b7f87ae312 | josephduarte104/data-science-exercises | /py4e/helper11.py | 509 | 4.0625 | 4 | import re
x = "Why should you learn to write programs? 7746 12 1929 8827 Writing programs (or programming) is a very creative \
7 and rewarding activity. You can write programs for many reasons, ranging from making your living to solving \
8837 a difficult data analysis problem to having fun to helping 128someone else solve a problem. This book assumes that \
everyone needs to know how to program ..."
y = re.findall('[0-9]+',x)
print(y)
a = 0
for j in y:
a += int(j)
print(a)
|
fbd7c968c49807581dd0b51b1bc2e5be7c18e29a | GolanSho/HomeWork | /HM3.py | 1,456 | 3.984375 | 4 | def sumarry():
array = [17, 1, 12, 54, 23, 9, 21]
sumarray = []
for i in array:
if i >= 3 and i <= 20:
sumarray.append(i)
print(sum(sumarray))
sumarry()
def sumval():
val1 = 0
val2 = 0
integ = []
while True:
num = int(input("Enter a Number: "))
integ.append(num)
if val1 <= 10:
val1 += num
val2 += num
elif val2 <= 30:
val2 += num
else:
break
integ = sum(integ)
print(val1, val2, integ)
print(val1 + val2 + integ)
sumval()
def sumval2():
nums = []
while True:
num1 = int(input("Enter a Number: "))
nums.append(num1)
if num1 > 10:
break
elif (sum(nums)) > 30:
break
print(sum(nums))
sumval2()
def arryinpt():
inptarry = []
arrylegh = int(input('Enter the array length: '))
arylgh = arrylegh
while arrylegh > 0:
inptarry.append(None)
arrylegh -= 1
tknpos = []
for i in inptarry:
numpos = int(input('Enter a Position: '))
numin = int(input('Enter a Number: '))
tknpos.append(numpos)
print(f'used positions: {tknpos} ')
inptarry.pop(numpos)
if numin > 3 < 5:
numin = numin**2
inptarry.insert(numpos, numin)
arylgh -= 1
if arylgh == 0:
break
print(inptarry)
arryinpt()
|
aaccb7f0df1646691c4f6621236618b831437e7d | bayukrs/logika-test-BGM | /main.py | 306 | 3.640625 | 4 | def print_hi(N):
for i in range(1, N):
j = i
if i % 3 == 0:
j = "Frontend"
if i % 5 == 0:
j = "Backend"
if i % 5 == 0 and i % 3 == 0:
j = "Frontend Backend"
print(j, ",", end="")
if __name__ == '__main__':
print_hi(50)
|
fc010fd5893b9a047a9c52816b7adaf869ce1498 | sam1037/mini_python_games | /sudoku_backup.py | 3,304 | 3.734375 | 4 | import random
# make a board which you can display number
# player can enter number, undo and get hint
# create list
coords_list = []
y = 0
x = 0
for a in range(81):
coords_list.append((x,y))
x += 1
x %= 9
if len(coords_list) > 8 and x == 0:
y+=1
coords_list = {a:[b for b in range(1,10)] for a in coords_list} # first is coords, second is the possible options of number
# blocks contains 9 coords in a 3x3 square
block0 = [(0,0),(1,0),(2,0),
(0,1),(1,1),(2,1),
(0,2),(1,2),(2,2)]
block1 = [(a[0]+3,a[1]) for a in block0]
block2 = [(a[0]+3,a[1]) for a in block1]
block3 = [(a[0],a[1]+3) for a in block0]
block4 = [(a[0]+3,a[1]) for a in block3]
block5 = [(a[0]+3,a[1]) for a in block4]
block6 = [(a[0],a[1]+3) for a in block3]
block7 = [(a[0]+3,a[1]) for a in block6]
block8 = [(a[0]+3,a[1]) for a in block7]
block_list = [block0,block1,block2,block3,block4,block5,block6,block7,block8]
def a():
ans = []
for list in block_list:
for ele in list:
ans.append(ele)
print(len(ans))
def generate_num(chosen_coord):
# generate coord
possible_options = coords_list[chosen_coord]
# find block of a given coord
def find_block(coord):
for list in block_list:
if coord in list:
return 'block'+str(block_list.index(list))
def eliminate_other_coords():
chosen_coord_block = find_block(chosen_coord)
# eliminate other coords possible options
for other_coords in coords_list:
if other_coords == chosen_coord:
pass
else:
# eliminate other coords possible options
if other_coords[1] == chosen_coord[1] or other_coords[0] == chosen_coord[0] or find_block(
other_coords) == chosen_coord_block:
reduced_list = [a for a in coords_list[other_coords] if a not in coords_list[chosen_coord]].copy()
coords_list[other_coords] = reduced_list
def set_non_option_coord(coord):
"""this is going to re_generate some coord"""
chosen_coord_block = find_block(chosen_coord)
for other_coords in coords_list:
if other_coords[1] == chosen_coord[1] or other_coords[0] == chosen_coord[0] or find_block(
other_coords) == chosen_coord_block:
if len(coords_list[other_coords]) == 1:
generate_num(other_coords)
def main_part():
# if don't need to generate
if len(possible_options) == 1:
pass
# set num for choosen_coord
else:
try:
coords_list[chosen_coord] = [random.choice(coords_list[chosen_coord])].copy()
except Exception as e:
set_non_option_coord(chosen_coord)
# eliminate other coord possible option
eliminate_other_coords()
main_part()
# todo fix possible_option become none problem
def generate_whole():
for block in block_list:
for coord in block:
generate_num(coord)
num_only = [coords_list[a] for a in coords_list]
blank_num = 0
for num in num_only:
if num == []:
blank_num += 1
print(num_only)
print(blank_num)
generate_whole()
|
34a4437906dda2944ba8211b5193b9de0f8780ce | Dantera/Imgen | /jsoner.py | 723 | 3.6875 | 4 | #!usr/bin/py
"""
"""
import json
def load_from_file(file):
"""
Args:
file ():
Returns:
(Dictionary): the data from the file
"""
with open(file) as json_data:
return json.load(json_data)
def save_to_file(data, file, pretty_print=False):
"""
Args:
data (Dictionary): the JSON data to save to file
file (String): name of file to save
pretty_print (boolean): whether to pretty print data to file or single
Returns:
None
"""
with open(file, 'w') as output:
if pretty_print:
json.dump(data, output, sort_keys=True, indent=4, separators=(',', ': '))
else:
json.dump(data, output)
|
41af2c86866f2008093c06a98750c54b43dea176 | icnp2017/submission | /p4_impl/p4t/p4t/utils.py | 1,310 | 3.78125 | 4 | from itertools import count
class Namespace(object):
""" Namespace that provide easy nesting and collision avoidance.
String can be retrieved by means of a standard `str` built-in.
"""
def __init__(self, name='', parent=None):
self._name = name
self._parent = parent
self._children = set()
def create_nested_ns(self, name):
""" Create nested namespace with a given base name.
Args:
name: Base namespace name.
Returns:
New instance of Namespace, which name is close to the given one.
"""
final_name = name
for i in count(1):
if final_name not in self._children:
break
final_name = '{:s}_{:d}'.format(name, i)
self._children.add(final_name)
return Namespace(final_name, self)
def create_nested_name(self, name):
return self.create_nested_ns(name).fullname
@property
def parent(self):
""" Parent namespace. """
return self._parent
@property
def name(self):
return self._name
@property
def fullname(self):
if self._parent is None or not self._parent.fullname:
return self._name
else:
return self._parent.fullname + '_' + self._name
|
be0eaa8ec23bcdc70ee5813849f58ff1687dfa0c | leurekay/Python-Scripts | /plot_arrow/try1.py | 890 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 14 19:56:09 2017
@author: aa
"""
from math import *
import matplotlib.pyplot as plt
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
p1=Point(0,0)
def arrow(f,p,angle):
A=Point(p.x+0.5*cos(pi+angle),p.y+0.5*sin(pi+angle))
B=Point(p.x+0.5*cos(angle),p.y+0.5*sin(angle))
ArrAngle=pi/10
ArrLen=0.1
ArrAngle_absolute1=pi+angle-ArrAngle
ArrAngle_absolute2=pi+angle+ArrAngle
C1=Point(B.x+ArrLen*cos(ArrAngle_absolute1),B.y+ArrLen*sin(ArrAngle_absolute1))
C2=Point(B.x+ArrLen*cos(ArrAngle_absolute2),B.y+ArrLen*sin(ArrAngle_absolute2))
#plt.figure(figsize=(6,6))
plt.plot([A.x,B.x,C1.x,C2.x,B.x],[A.y,B.y,C1.y,C2.y,B.y],"g")
plt.xlim(-1,1)
plt.ylim(-1,1)
f=plt.plot(figsize=(10,10))
ax = plt.gca()
ax.set_aspect(1)
arrow(f,p1,pi/3)
arrow(f,p1,pi/4)
plt.savefig("a")
|
58f26e0f54950f42887d710779fa2bc57dc6fcda | sahasradude/Language-processors | /line no/linecountstop.py | 616 | 3.75 | 4 | file = open(raw_input("Enter filename\n"))
#neededword = raw_input("Enter the word to be searched\n")
i = 1
wordslist = []
text = ""
for line in file:
line = line.strip("\n")+ " "
text += line
i = 1
wordslist = text.split(" ")
print "\n",i,".",
i+=1
for word in wordslist:
print word,
if word.find(".") != -1:
print ("\n",i,".",end='')
i+=1
"""
for word in wordlist:
if word.find(neededword) != -1:
print "line no:",i,"word no:",wordlist.index(word) + 1,"-->",
for word in wordlist:
print word," ",
print "\n"
i+=1
"""
|
bcb8466d7fee03394321cf066b232233769826a2 | DiamondLightSource/auto_tomo_calibration-experimental | /old_code_scripts/harris_edge.py | 6,612 | 3.59375 | 4 | from scipy.ndimage import filters
import numpy as np
import pylab as pl
def compute_harris_response(im, sigma=3):
""" Compute the Harris corner detector response function
for each pixel in a graylevel image.
This indicator function allows to distinguish different
eigenvalue relative sizes without computing them
directly. It is also called the Harris Stephens function
"""
# derivative in x direction of the image
imx = np.zeros(im.shape)
filters.gaussian_filter(im, (sigma, sigma), (0, 1), imx)
# derivative in y direction of the image
imy = np.zeros(im.shape)
filters.gaussian_filter(im, (sigma, sigma), (1, 0), imy)
# compute components of the Harris matrix
# it is usually weighted by a Gaussian
Wxx = filters.gaussian_filter(imx * imx, sigma)
Wxy = filters.gaussian_filter(imx * imy, sigma)
Wyy = filters.gaussian_filter(imy * imy, sigma)
# determinant and trace
Wdet = Wxx * Wyy - Wxy ** 2
Wtr = Wxx + Wyy
return Wdet / Wtr
def hessian_response(im, sigma=3, threshold = 0.05):
# # derivative in x direction of the image
# imx = np.zeros(im.shape)
# imxx = np.zeros(im.shape)
# filters.gaussian_filter(im, (sigma, sigma), (0, 1), imx)
# filters.gaussian_filter(imx, (sigma, sigma), (0, 1), imxx)
#
# # derivative in y direction of the image
# imy = np.zeros(im.shape)
# imyy = np.zeros(im.shape)
# filters.gaussian_filter(im, (sigma, sigma), (1, 0), imy)
# filters.gaussian_filter(imy, (sigma, sigma), (1, 0), imyy)
#
# imxy = np.zeros(im.shape)
# filters.gaussian_filter(imx, (sigma, sigma), (1, 0), imxy)
#
# Wxx = filters.gaussian_filter(imxx, sigma)
# Wxy = filters.gaussian_filter(imxy, sigma)
# Wyy = filters.gaussian_filter(imyy, sigma)
#
# H = np.array([[Wxx, Wxy],
# [Wxy, Wyy]])
#
from numpy import linalg as LA
from skimage.feature import hessian_matrix, hessian_matrix_eigvals
Hxx, Hxy, Hyy = hessian_matrix(im, sigma=0.1)
e_big, e_small = hessian_matrix_eigvals(Hxx, Hxy, Hyy)
#eiglast = 0.5 * (Wxx + Wyy + np.sqrt(Wxx**2 + 4*Wxy**2 - 2*Wxx*Wyy + Wyy**2 ))
# det_hes = Wxx * Wyy - Wxy ** 2
eiglast = e_big
# get maxima of the determinant
# det_thresh = eiglast.max() * threshold
# det_bin = (eiglast >= det_thresh) * 1
#
# coordinates = np.array(det_bin.nonzero()).T
x = [p[0] for p in coordinates]
y = [p[1] for p in coordinates]
edges = np.zeros(im.shape)
edges[x,y] = 1
pl.imshow(edges)
pl.gray()
pl.show()
return
recon = np.load("/dls/tmp/jjl36382/complicated_data/spheres/sphere1.npy")[:,:,100]
hessian_response(recon, 1, 0.5)
def hessian_response_3d(im, sigma=3, threshold = 0.005):
import numpy as np
# derivative in x direction of the image
imx = np.zeros(im.shape)
imxx = np.zeros(im.shape)
filters.gaussian_filter(im, (sigma, sigma, sigma), (0, 0, 1), imx)
filters.gaussian_filter(imx, (sigma, sigma, sigma), (0, 1, 1), imxx)
# derivative in y direction of the image
imy = np.zeros(im.shape)
imyy = np.zeros(im.shape)
filters.gaussian_filter(im, (sigma, sigma, sigma), (1, 0, 1), imy)
filters.gaussian_filter(imy, (sigma, sigma, sigma), (1, 0, 1), imyy)
imz = np.zeros(im.shape)
imzz = np.zeros(im.shape)
filters.gaussian_filter(im, (sigma, sigma, sigma), (1, 1, 0), imz)
filters.gaussian_filter(imz, (sigma, sigma, sigma), (1, 1, 0), imzz)
imxy = np.zeros(im.shape)
filters.gaussian_filter(imx, (sigma, sigma, sigma), (1, 0, 1), imxy)
imxz = np.zeros(im.shape)
filters.gaussian_filter(imx, (sigma, sigma, sigma), (1, 1, 0), imxz)
imyz = np.zeros(im.shape)
filters.gaussian_filter(imy, (sigma, sigma, sigma), (1, 1, 0), imyz)
Wxx = filters.gaussian_filter(imxx, sigma)
Wxy = filters.gaussian_filter(imxy, sigma)
Wxz = filters.gaussian_filter(imxz, sigma)
Wzy = filters.gaussian_filter(imyz, sigma)
Wyy = filters.gaussian_filter(imyy, sigma)
Wzz = filters.gaussian_filter(imzz, sigma)
H = np.array( [[Wxx, Wxy, Wxz],
[Wxy, Wyy, Wzy],
[Wxz, Wzy, Wzz]] )
import numpy.linalg as LA
e_val, e_vec = LA.eig(H)
print H.shape
det_hes = Wxx * (Wyy * Wzz - Wzy ** 2) - Wxy * (Wxy * Wzz - Wzy * Wxz) + Wxz * (Wxy * Wzy - Wyy * Wxz)
# get maxima of the determinant
det_thresh = det_hes.max() * threshold
det_bin = (det_hes >= det_thresh) * 1
coordinates = np.array(det_bin.nonzero()).T
x = [p[0] for p in coordinates]
y = [p[1] for p in coordinates]
z = [p[2] for p in coordinates]
edges = np.zeros(im.shape)
edges[x,y, z] = 1
pl.imshow(edges[:, :, 50])
#pl.scatter(x, y)
pl.gray()
pl.show()
return edges
def get_harris_points(harrisim, min_dist=1, threshold=0.0005):
""" Return corners from a Harris response image
min_dist is the minimum number of pixels separating
corners and image boundary.
min_dist specifies the allowed length"""
# find top corner candidates above a threshold
corner_threshold = harrisim.max() * threshold
harrisim_t = (harrisim > corner_threshold) * 1
# get coordinates of candidates
coords = np.array(harrisim_t.nonzero()).T
# ...and their values
candidate_values = [harrisim[c[0], c[1]] for c in coords]
# sort candidates
index = np.argsort(candidate_values)
# store allowed point locations in array
allowed_locations = np.zeros(harrisim.shape)
allowed_locations[min_dist:-min_dist, min_dist:-min_dist] = 1
# select the best points taking min_distance into account
filtered_coords = []
for i in index:
if allowed_locations[coords[i, 0], coords[i, 1]] == 1:
filtered_coords.append(coords[i])
allowed_locations[(coords[i, 0] - min_dist):(coords[i, 0] + min_dist),
(coords[i, 1] - min_dist):(coords[i, 1] + min_dist)] = 0
return filtered_coords
def plot_harris_points(image, filtered_coords):
""" Plots corners found in image. """
pl.figure()
pl.gray()
pl.imshow(image)
pl.show()
x = [p[1] for p in filtered_coords]
y = [p[0] for p in filtered_coords]
#for i in x:
#pl.plot([p[1] for p in filtered_coords], [p[0] for p in filtered_coords])
#pl.axis("off")
#pl.show()
|
8ad39ace6b0a1df63ec3e11546646180aaa08485 | jaffarabbas/Assignment_python-1 | /Assignment 2/pythonassignment2/task3.py | 127 | 3.59375 | 4 | a = []
a.append("Hello")
a.append("Geeks")
a.append("For")
a.append("Geeks")
print("The length of list is: ", len(a)) |
97ef3b39b97918b53050ebfdfb884c311d281770 | jaffarabbas/Assignment_python-1 | /Assignment 2/pythonassignment2/task4.py | 211 | 4.09375 | 4 | lst = []
num = int(input('Enter how many items in list: '))
for n in range(num):
numbers = int(input('Enter cost of item '))
lst.append(numbers)
print("Sum of elements in given list is :", sum(lst)) |
6badd68a3e7616d18ae577008dde2efc0dbad8fe | biroc/algs | /test.py | 2,593 | 3.65625 | 4 | # import unittest
#
# def max_heapify(array,i,heapsize):
# left = 2 * i + 1
# right = left + 1
# largest = i
#
# if left < heapsize and array[left] > array[largest]:
# largest = left
#
# if right < heapsize and array[right] > array[largest]:
# largest = right
#
# if largest != i:
# array[largest], array[i] = array[i], array[largest]
# max_heapify(array, largest, heapsize)
#
# def build_heap(array,heapsize):
# mid = (heapsize - 1) // 2
# for i in range(mid,-1,-1):
# max_heapify(array,i,heapsize)
#
#
# def heapsort(array):
# heapsize = len(array) - 1
# build_heap(array, heapsize)
# for i in range(len(array) - 1, 0, -1):
# array[0], array[i] = array[i], array[0]
# heapsize -= 1
# max_heapify(array, 0, heapsize)
#
#
# class TestStuff(unittest.TestCase):
#
# def test_heapify(self):
# array = [10,7,8,9,6,5,4,3,2,1]
# max_heapify(array, 1, len(array))
# self.assertEqual(array, [10,9,8,7,6,5,4,3,2,1])
#
# def test_heapsort(self):
# array = [10,7,8,9,6,5,4,3,2,1]
# heapsort(array)
# self.assertEqual(array, [1,2,3,4,5,6,7,8,9,10])
def one_away(first,second):
if abs(len(first) - len(second)) > 1:
return False
m = len(first)
n = len(second)
if m > n:
return one_away(second, first)
diff = n - m
i = 0
while i < m and first[i] == second[i]:
i += 1
if i == m:
return diff == 1
if diff == 0:
i += 1
while i < m and first[i] == second[i + diff]:
i += 1
return i == m
def rotate_90(matrix):
length = len(matrix) - 1
layers = len(matrix) // 2
for curr_layer in range(layers):
for i in range(curr_layer, length - curr_layer):
top = matrix[curr_layer][i]
# left - > top
matrix[curr_layer][i] = matrix[length - i][curr_layer]
# bottom -> left
matrix[length - i][curr_layer] = matrix[length - curr_layer][length - i]
# right -> bottom
matrix[length - curr_layer][length - i] = matrix[i][length - curr_layer]
# top - > right
matrix[i][length - curr_layer] = top
return matrix
def firstRepeatingLetter(s):
dict = {}
lowest_index = len(s)
lowest_letter = ''
for index, c in enumerate(s) :
if c in dict:
if dict[c] < lowest_index:
lowest_letter = c
lowest_index = dict[c]
else:
dict[c] = index
return lowest_letter
|
c1dceb57ede0b3eb1f1fe5fe658fe283116d68f3 | pythonic-shk/Euler-Problems | /euler1.py | 229 | 4.34375 | 4 | n = input("Enter n: ")
multiples = []
for i in range(int(n)):
if i%3 == 0 or i%5 == 0:
multiples.append(i)
print("Multiples of 3 or 5 or both are ",multiples)
print("Sum of Multiples of ",n," Numbers is ",sum(multiples)) |
ff547f2b78a5a972a7526e75402c00796f5d78fc | yashin0993/NeuralNetwork | /study_of_DL/02_NeuralNetwork/two_layer_net1.py | 732 | 3.5625 | 4 | import numpy as np
from activation import activation
act = activation()
def init_network():
network = {}
network['w1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])
network['b1'] = np.array([0.1, 0.2, 0.3])
network['w2'] = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]])
network['b2'] = np.array([0.1, 0.2])
return network
def forward(network, x):
w1, w2 = network['w1'], network['w2']
b1, b2 = network['b1'], network['b2']
a1 = np.dot(x, w1) + b1
z1 = act.sigmoid(a1)
a2 = np.dot(z1, w2) + b2
return a2
# --------- メイン処理 -----------
network = init_network()
x = np.array([1.0, 0.5])
y = forward(network, x)
print("output = " + str(y))
|
a570599cce87b3a8ce25ff8d7d55b528e73325b0 | acorned/Python_lessons_basic | /lesson02/home_work/hw02_easy.py | 1,425 | 3.8125 | 4 | # Задача-1:
# Дан список фруктов. Напишите программу, выводящую фрукты в виде нумерованного списка выровненного по правой сторне
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
arr = ["яблоко", "банан", "киви", "арбуз"]
for num in range(len(arr)):
print('{:<1}{:>7}'.format(num + 1, arr[num]))
# Задача-2:
# Даны два произвольные списка. Удалите из первого списка элементы присутствующие во втором списке
arr = ["яблоко", "банан", "киви", "арбуз"]
arr2 = ["яблоко", "вишня", "апельсин", "арбуз"]
arr = [item for item in arr if item not in arr2]
# Задача-3:
# Дан произвольный список из целых чисел. Получите НОВЫЙ список из элементов исходного выполнив следующие условия:
# если элемент кратный двум, то разделить его на 4, если не кратен, то умножить на два.
arr = [1, 2, 3, 4, 5]
arr2 = [item / 4 if item % 2 == 0 else item * 2 for item in arr]
|
7468f255b87e3b4aa495e372b44aba87ff2928d1 | tengrommel/go_live | /machine_learning_go/01_gathering_and_organizating_data/gopher_style/python_ex/myprogram.py | 449 | 4.3125 | 4 | import pandas as pd
'''
It is true that, very quickly, we can write some Python code to parse this CSV
and output the maximum value from the integer column without even
knowing what types are in the data:
'''
# Define column names
cols = [
'integercolumn',
'stringcolumn'
]
# Read in the CSV with pandas.
data = pd.read_csv('myfile.csv', names=cols)
# Print out the maximum value in the integer column.
print(data['integercolumn'].max()) |
8c2ababb93198e7acae72e46d896a5d2fe257d8d | DanieleSiri/Sudoku | /sudoku_generator.py | 1,513 | 3.765625 | 4 | import random
import sudoku_class
def randomize_position():
random_x = random.randint(0, 8)
random_y = random.randint(0, 8)
return random_x, random_y
def randomize_first_box():
"""used to break most easy patterns in the first box"""
random_x = random.randint(0, 3)
random_y = random.randint(0, 3)
return random_x, random_y
class SudokuGenerator:
def __init__(self, board):
self.board = sudoku_class.SudokuSolver(board)
def randomize(self, pos):
"""
Randomizes the number on board
:param pos: (x, y)
:return: None
"""
random_value = random.randint(1, 9)
if self.board.valid(pos, random_value):
self.board.update_board(pos, random_value)
else:
self.randomize(pos)
def generate(self):
"""generates the random board"""
for i in range(4):
random_first = randomize_first_box()
self.randomize(random_first)
for i in range(9):
random_pos = randomize_position()
self.randomize(random_pos)
self.board.solve()
def remove_numbers(self):
"""removes some numbers from the solution in order to have the solvable board"""
for i in range(len(self.board.board[0])):
while self.board.board[i].count(0) < 6:
random_val = random.randint(0, 8)
self.board.update_board((i, random_val), 0)
def get_board(self):
return self.board.board
|
df200bb09f51b22be14c48d88517d24675893940 | aiguang11211/gitskills | /py/简单tkinter例子.py | 460 | 3.6875 | 4 | from tkinter import *
def resize(ev=None):
label.config(font='Helvetica -%d bold'%scale.get())
top=Tk()
top.geometry('250x150')
label=Label(top,text='Hello World',font='Helvetica -12 bold')
label.pack(fill=Y,expand=1)
scale=Scale(top,from_=10,to=40,
orient=HORIZONTAL,command=resize)
scale.set(12)
scale.pack(fill=X,expand=1)
quit=Button(top,text='QUIT',command=top.quit,activeforeground='white',activebackground='red')
quit.pack()
mainloop() |
e863fd0cfe96478d6550b426d675de6cfc84c08a | kami71539/Python-programs-4 | /Program 19 Printing even and odd number in the given range.py | 515 | 4.28125 | 4 | #To print even numbers from low to high number.
low=int(input("Enter the lower limit: "))
high=int(input("ENter the higher limit: "))
for i in range(low,high):
if(i%2==0):
print(i,end=" ")
print("")
for i in range(low,high):
if(i%2!=0):
print(i,end=" ")
#Printing odd numbers from higher number to lower number
low=int(input("Enter the lower limit: "))
high=int(input("ENter the higher limit: "))
for i in range(high,low,-1):
if(i%2!=0):
print(i,end=" ") |
61bef90211ffd18868427d3059e8ab8dee3fefde | kami71539/Python-programs-4 | /Program 25 Printing text after specific lines.py | 303 | 4.15625 | 4 | #Printing text after specific lines.
text=str(input("Enter Text: "))
text_number=int(input("Enter number of text you'd like to print; "))
line_number=1
for i in range(0,text_number):
print(text)
for j in range(0,line_number):
print("1")
line_number=line_number+1
print(text) |
968098b3815c914233cb9c0632c921b2ef27a589 | kami71539/Python-programs-4 | /Program 12 Dictionary.py | 459 | 3.546875 | 4 | monthconversion={
"Jan":"January",
"Feb":"February",
"Mar":"March",
"Apr":"April",
"May":"May",
6:"June",
"Jul":"July",
"Aug":"August",
"Sep":"September",
"Oct":"October",
"Nov":"November",
"Dec":"December"
}
print(monthconversion.get("Mar"))
print(monthconversion["Jul"])
print(monthconversion[6])
print(monthconversion.get("A value not found in the dict"))
print(monthconversion.get("A value not found in the dict","Not a valid month."))
|
799c2d124d6c7dc11779fa3a6c6e1f3a36980a96 | kami71539/Python-programs-4 | /Program 16 Nested loops.py | 315 | 3.859375 | 4 | #Nested Loops
for i in range(10):
for j in range(10):
print(j,end="")
print("")
print(i)
number_grid=[
[1,2,3],
[4,5,6],
[7,8,9],
[0]
]
print(number_grid[1][2])
for row in number_grid:
print (row)
for coloumn in row:
print(coloumn)
|
38658702ed937a7ba65fd1d478a371e4c6d5e789 | kami71539/Python-programs-4 | /Program 42 Finding LCM and HCF using recursion.py | 259 | 4.25 | 4 | #To find the HCF and LCM of a number using recursion.
def HCF(x,y):
if x%y==0:
return y
else:
return HCF(y,x%y)
x=int(input(""))
y=int(input(""))
hcf=HCF(x,y)
lcm=(x*y)/hcf
print("The HCF is",hcf,". The LCM is",lcm) |
6f2ac1ae18a208e032f7f1db77f64710f3b9bd00 | kami71539/Python-programs-4 | /Program 15 Exponents.py | 221 | 4.375 | 4 | print(2**3)
def exponents(base,power):
i=1
for index in range(power):
i=i*base
return i
a=int(input(""))
b=int(input(""))
print(a, "raised to the power of" ,b,"would give us", exponents(a,b))
|
e80d7d475ddcf65eddd08d77aa4c2c03f965dfb9 | kami71539/Python-programs-4 | /Program 35 To count the uppercase and lowercase characters in the given string. unresolved.py | 458 | 4.125 | 4 | #To count the uppercase and lowercase characters in the given string.
string=input("")
j='a'
lower=0
upper=0
space=0
for i in string:
for j in range(65,92):
if chr(j) in i:
upper=upper+1
elif j==" ":
space=space+1
for j in range(97,123):
if chr(j) in i:
lower=lower+1
#print(chr(j))
print("There are",lower-space,"lower characters and",upper,"upper characters.") |
2afd84914e4120cc7e233dce0b7779a9654318c9 | alexvydrin/gb_course_python_clientserver | /lesson_1/task_1_4.py | 1,283 | 3.921875 | 4 | """
4. Преобразовать слова «разработка», «администрирование», «protocol»,
«standard» из строкового представления в байтовое и выполнить
обратное преобразование (используя методы encode и decode).
Подсказки:
--- используйте списки и циклы, не дублируйте функции
"""
WORDS = ['разработка', 'администрирование', 'protocol', 'standard']
for word in WORDS:
print(f"Выполняем преобразование слова '{word}' в байтовый тип")
WORD_B = word.encode('utf-8')
print("Результат:")
print(f"содержимое переменной: {WORD_B}")
print(f"тип переменной: {type(WORD_B)}")
print(f"длина переменной: {len(WORD_B)}")
print("Выполняем обратное преобразование слова")
WORD_S = WORD_B.decode('utf-8')
print("Результат:")
print(f"содержимое переменной: {WORD_S}")
print(f"тип переменной: {type(WORD_S)}")
print(f"длина переменной: {len(WORD_S)}")
print()
|
9c975a67d5bb4c12d08f6aaf58866b15974b22f3 | xinyuan-Winter2021-Cmput291/291A5 | /A5T5SQLite.py | 986 | 3.5625 | 4 | # 291 A5 Task5 SQLite
import sqlite3
import sys
def task5_sql(cursor):
print("Task 5 SQLite")
if len(sys.argv) > 1:
neighbourhood = str(sys.argv[1])
else:
neighbourhood = input("Please enter a neighbourhood: ")
try:
sql = ''' SELECT avg(price) as average_rental
FROM listings
WHERE neighbourhood = :Neighbourhood
'''
cursor.execute(sql, {'Neighbourhood': neighbourhood})
result = cursor.fetchall()
count = len(result)
# check if there is data
if count > 0:
print("The average price per night of ", neighbourhood, "is: ")
for i in result:
print(int(i[0]))
except Exception as e:
# the error will show if exists
print(e)
print('cannot query')
def main():
conn = sqlite3.connect('./A5.db')
conn.row_factory = sqlite3.Row
c = conn.cursor()
task5_sql(c)
print("\n")
conn.close()
main()
|
9e802716623c03946cee8eddebab2f158da3a15b | stanley-c-yu/mathematics-for-machine-learning | /pca/pca.py | 4,610 | 3.734375 | 4 | import numpy as np
class PCA:
'''
Refactored submission for the PCA Course by the Imperial College of London on Coursera.
Many thanks to the fellow students who completed this course and provided useful tips
and guidance on the forums. None of this would have been possible without you.
Please feel free to use this code as a guide, but please respect the honor code and don't blindly copy-paste.
'''
def normalize(self, X):
"""
Normalize the given dataset X to have zero mean.
Args:
X: ndarray, dataset of shape (N,D)
Returns:
(Xbar, mean): tuple of ndarray, Xbar is the normalized dataset
with mean 0; mean is the sample mean of the dataset.
"""
mu = X.mean(0)
Xbar = X - mu
return Xbar, mu
def eig(self, S):
"""
Normalize the given dataset X to have zero mean.
Args:
X: ndarray, dataset of shape (N,D)
Returns:
(Xbar, mean): tuple of ndarray, Xbar is the normalized dataset
with mean 0; mean is the sample mean of the dataset.
"""
eigvals, eigvecs = np.linalg.eig(S)
# get the indices to sort in descending order with respect to eigenvalues
sorted_indices = np.argsort(eigvals)[::-1]
# Note, only the columns of eigvecs is being sorted, since the columns are the eigenvectors
return eigvals[sorted_indices], eigvecs[:, sorted_indices]
def projection_matrix(self, B):
"""
Compute the projection matrix onto the space spanned by `B`
Args:
B: ndarray of dimension (D, M), the basis for the subspace
Returns:
P: the projection matrix
"""
P = B @ np.linalg.inv(B.T @ B) @ B.T
return P
def pca(self, X, num_components):
"""
Args:
X: ndarray of size (N, D), where D is the dimension of the data,
and N is the number of datapoints
num_components: the number of principal components to use.
Returns:
the reconstructed data, the sample mean of the X, principal values
and principal components
"""
N, D = X.shape
X_normalized, mean = self.normalize(X)
# Compute data covariance matrix
S = np.cov(X_normalized/N, rowvar=False, bias=True)
# Compute the eigenvalues and corresponding eigenvectors for S
eig_vals, eig_vecs = self.eig(S)
# Take the top number of components of the eigenvalues and vectors
# AKA, the principal values and pincipal components
principal_vals = eig_vals[:num_components]
principal_components = eig_vecs[:, :num_components]
# Reconstruct the data using the basis spanned by the PCs.
# Recall that the mean was subtracted from X, so it needs to be added back here
P = self.projection_matrix(principal_components) # projection matrix
reconst = (P @ X_normalized.T).T + mean
return reconst, mean, principal_vals, principal_components
def pca_high_dim(self, X, num_components):
"""
Compute PCA for small sample size but high-dimensional features.
Args:
X: ndarray of size (N, D), where D is the dimension of the sample,
and N is the number of samples
num_components: the number of principal components to use.
Returns:
X_reconstruct: (N, D) ndarray. the reconstruction
of X from the first `num_components` pricipal components.
"""
N, D = X.shape
# Normalize the dataset
X_normalized, mean = self.normalize(X)
# Find the covariance matrix
M = np.dot(X_normalized, X_normalized.T)/N
# Get the eigenvalues and eigenvectors
eig_vals, eig_vecs = self.eig(M)
# Take the top number of the eigenvalues and eigenvectors
principal_values = eig_vals[:num_components]
principal_components = eig_vecs[:, :num_components]
# reconstruct the images from the lower dimensional representation
# Remember to add back the sample mean
P = self.projection_matrix(principal_components)
reconst = (P @ X_normalized) + mean
return reconst, mean, principal_values, principal_components
|
452058865789c23530d5c33c7f063c2f9c0399f3 | lauux/AlgorithmQIUZHAO | /Week_03/127.单词接龙.py | 1,075 | 3.515625 | 4 | #
# @lc app=leetcode.cn id=127 lang=python3
#
# [127] 单词接龙
#
# @lc code=start
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if not endWord or not wordList or endWord not in wordList:
return 0
L = len(endWord)
newWordList = collections.defaultdict(list)
for word in wordList:
for i in range(L):
newWordList[word[:i] + '*' + word[i+1:]].append(word)
queue = [(beginWord, 1)]
visited = {beginWord: True}
while queue:
cur, step = queue.pop(0)
for i in range(L):
interm = cur[:i] + '*' + cur[i+1:]
for tmp in newWordList[interm]:
if tmp == endWord:
return step + 1
if tmp not in visited:
queue.append((tmp, step+1))
visited[tmp] = True
newWordList[interm] = []
return 0
# @lc code=end
|
5ed3de8cc08fe52d61aafac5556b4d7f148cfae3 | lauux/AlgorithmQIUZHAO | /Week_06/205.同构字符串.py | 478 | 3.5 | 4 | #
# @lc app=leetcode.cn id=205 lang=python3
#
# [205] 同构字符串
#
# @lc code=start
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
maps = {}
for i in range(len(s)):
if s[i] in maps and maps[s[i]] != t[i]:
return False
elif s[i] not in maps:
if t[i] in maps.values():
return False
maps[s[i]] = t[i]
return True
# @lc code=end
|
04ae7c06f98e112a0e7fb4f4f1319acb022d8b5f | LEEHOONY/my-project | /week01/company.py | 733 | 3.859375 | 4 | # 회사 조직도 만들기
# 사람 클래스를 만든다(사람의 기본요소는 이름, 나이, 성별로 한다)
# 직장 동료 클래스를 사람 클래스를 이용하여 만든다.(사람 기본 요소 외 직급을 추가한다.)
## Human class
class Human:
company = "Python"
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
human1 = Human("홍길동", "23", "M")
human2 = Human("장희빈", "21", "F")
human3 = Human("임꺽정", "32", "M")
print(human2.name)
print(human3.sex)
## Colleague class
class Colleague(Human):
designation = "부장"
colleague = Colleague("이순신", "40", "M")
print(colleague.name)
print(colleague.designation)
|
06991835059e7a626be65079c8b85c7e0a93a06b | joshunov/SYNCSHACK_2021 | /Main.py | 10,287 | 3.609375 | 4 | import Horse_racing.horse_racing_2 as horse
import fTheBus_fn as ftb
import trivia1 as triv
import kings_cup as king
import random
import time
import os
os.system("pip install pydealer")
os.system("pip install termcolor")
def letter_by_letter(string):
for i in string:
print(i, end= (''), flush= True)
time.sleep(0.025)
return ''
class Game:
def __init__(self):
self.leaderboard = []
self.player_list = []
self.player_num = 0
self.end = False
#include more game info...
def add_person(self,name):
#Creating the object of 10 players to be assigned to each person playing the game, capping the maximum number of players at 10 but can be extended
p1,p2,p3,p4,p5,p6,p7,p8,p9,p10 = Player(),Player(),Player(),Player(),Player(),Player(),Player(),Player(),Player(),Player()
player_positions = [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10]
for positions in player_positions:
if positions.name == " ":
positions.name = name
self.player_list.append(positions)
break
else:
continue
self.player_num += 1
name = Player()
name.name = name
def print_scoreboard(self):
scores = []
for players in self.player_list:
scores.append(players.score)
scores = sorted(scores, reverse=True)
for score in scores:
for player in self.player_list:
if player.score == score and player not in self.leaderboard:
self.leaderboard.append(player)
break
continue
print("Alright, lets see how these scores are looking!")
space = " "
print("\t\t \t\t|\t\t \t\t|\t\t ")
print("\t Position\t\t\t|\t Name \t\t|\t Drinks")
print("\t\t \t\t|\t\t \t\t|\t\t ")
for i in range(len(self.leaderboard)):
print("-----------------------------------------------------------------------------------------------------------")
print("\t\t \t\t|\t\t \t\t|\t\t ")
print(f"\t\t{str(i+1) + space*(8-len(str(i+1)))}\t\t|\t\t{self.leaderboard[i].name + space*(14-len(self.leaderboard[i].name))}\t\t\t|\t\t{self.leaderboard[i].score}")
print("\t\t \t\t|\t\t \t\t|\t\t ")
def run_ftb(self):
ftb.fTheBus(self.player_list)
return
def run_trivia(self):
triv.start_trivia(self.player_list)
return
def run_horse(self):
horse.horse_racing(self.player_list)
return
def run_kings(self):
king.run_kings(self.player_list)
return
def choose_game(self):
try:
letter_by_letter("What game would you like to play?\n\n\n\t(1) Kings Cup\n\n\t(2) Trivia\n\n\t(3) Horse racing\n\n\t(4) Ride the bus\n\n\t(5) Exit the game :(\n\n\t")
game_num = int(input())
if game_num not in [1,2,3,4,5]:
raise TypeError
except:
letter_by_letter("Come on, you saw the list enter one of the numbers!")
letter_by_letter("What game would you like to play?\n\n\n\t(1) Kings Cup\n\n\t(2) Trivia\n\n\t(3) Horse racing\n\n\t(4) Ride the bus\n\n\t(5) Exit the game :(\n\n\t")
game_num = input()
if game_num == 1:
self.run_kings()
elif game_num == 2:
self.run_trivia()
elif game_num == 3:
self.run_horse()
elif game_num == 4:
self.run_ftb()
elif game_num == 5:
self.end == True
exit()
class Player:
def __init__(self):
self.name = " "
self.weight = 0
self.max_bac = 0.05 #<-- determines how drunk ppl will get 0.03-0.05 for safe driving, 0.06-0.1 for impared balance/word slurring, 0.11+ nausea, blurred vision etc
self.max_alcahol = 0.0 #maximum amount of alcahol can be drunk to stay under the max BAC in grams
self.gender = " " # M or F Biological Sex
self.score = 0
self.is_host = False
#attributes for horse_racing
self.bet = 0
self.suit = ""
def calculate_max_alc(self):
"""
using formula BAC = alcahol consumed in grams/body weight in grams*r *100
where r = 0.55 for females and 0.68 for males
"""
if self.gender == "M":
r = 0.68
else:
r = 0.55
self.max_alcahol = self.max_bac*self.weight*r*10
def drink(self,num = 1):
if self.max_alcahol == 0:
self.calculate_max_alc()
self.score += num
# player drinks 10% of their max alcahol every drink, hence never drinking 100% of their max alcahol
# 10g of alcahol = abt 1 standard drink
#p = percentage of total alcahol drank in every sip
p = 0.15**num
self.max_alcahol = self.max_alcahol*(1-p)
#letter_by_letter(f'wow {self.name} has to drink {self.max_alcahol*p} grams!')
drink_statement = [
f"{self.name}, Someone's feeling thirsty\n",
f"{self.name}, you drink has got it's eyes on you\n",
f"{self.name}. Drink. Now\n",
f"{self.name}, RBT means you need a plan B\n",
f"Oh {self.name}, you don't feel it like anymore? I don't care! HAVE A DRINK\n",
f"{self.name}, you know it's better in your belly than on the floor mate. Maybe skip this one\n",
f"{self.name}, keep drinking like that and we will start to call YOU Drinky Bill\n",
f"{self.name}, Drinky Bill would be proud\n",
f"Take it easy {self.name}\n"
]
random.shuffle(drink_statement)
if self.score == 3:
if self.gender == 'M':
gen = "boy"
else:
gen = "girl"
letter_by_letter(f"Whoa there cow{gen} this is your third drink, dont feel bad if you wanna skip this one or replace it with water :)")
elif self.score > 3:
letter_by_letter(f"You're doing well {self.name} but this is your drink No.{self.score}, maybe we should start to slow it down")
elif self.max_alcahol < 3:
letter_by_letter(f"wow {self.name}, we can tell you're reaching your limit, start thinking about slowing down")
elif self.max_alcahol < 1:
letter_by_letter(f"hey there {self.name} we've run the numbers and we think youve hit your limit for tonight, lets stick with water for the rest of the night")
else:
letter_by_letter(drink_statement[0])
letter_by_letter(f" Press Enter once you are finished, but dont feel bad if you need to skip this one out :)")
input()
print()
return self.max_alcahol*p
def introduce(self):
weight_questions = [
f"If you dont mind me asking {self.name}, approximately how much do you weigh in Kg: ",
f"Heyo {self.name}, spill the beans, how much do you weigh in Kg? ",
f"Whats'up {self.name}, Hope your having a good one, let us know your weight in Kg: ",
f"OK {self.name}, you know the deal, How much do you weigh in Kg: ",
f"Hello {self.name}, we need to know your weight in kg, promise its for your own benefit :): ",
f"{self.name} Your looking good tonight, between you and me i recon your gonna win, just tell me your weight in Kg so we can get started: "
]
sex_questions = [
f"Nice {self.name}, now Please enter your bilogical sex: ",
f"Very interesting, Now lets hear your biological sex: ",
f"You weigh whatttt? Just kidding. One more thing, we need to know your biological sex please: ",
f"Hey {self.name} we need your biological sex, we promise we wont tell anyone: "
]
random.shuffle(sex_questions)
random.shuffle(weight_questions)
try:
letter_by_letter(weight_questions[0])
self.weight = int(input())
print("\n")
except:
letter_by_letter(f"\nSeriously {self.name}, That is just not a number, Try again\n")
return False
try:
letter_by_letter(sex_questions[0])
self.gender = input("please enter either M or F: ")
self.gender = self.gender.upper()
assert self.gender in ["M","F"]
return True
except:
print(f"\nCome on either M or F, enter either M or F, dont make me angry")
return False
#Below is a draft of how the game_begin function will be structured:
def game_begin():
game1 = Game()
letter_by_letter("\n\n\n\n\n\n\n\n\n\n\n\t\t\033[92mWelcome to 'Drinky Bill' The safe drinking game for people young and old (but not younger than 18 :)) if you want to have a good time, youve come to the right place. This online drinking game takes information about YOU and works out a safe amount for you to drink, making sure everyone has an enjoyable fun time!\n please follow all of the prompts and values exactly as they are specified, and most importantly enjoy!\033[0m\n\n")
n = int(input("please enter the number of players: "))
#Loop collecting names of every player
for player in range(n):
letter_by_letter(f"\nEnter the name of player {player+1}: ")
curr_name = input()
curr_name = curr_name.lower().capitalize()
curr_name =f'\033[1m{curr_name}\033[0m'
game1.add_person(curr_name)
#loop collecting more info on each player
letter_by_letter(f"\nLets start with some fun Ice-Breakers, {game1.player_list[0].name} you start!")
for i in game1.player_list:
print("\n\n")
while i.introduce() == False:
continue
print(f"\n Thanks {i.name}, lets move on")
print("\n\n\n\n\n")
game1.print_scoreboard()
letter_by_letter("Lets get down to business\n\n")
while game1.end == False:
game1.choose_game()
letter_by_letter("\nhope you enjoyed that, lets get moving onto the next one. ")
game_begin() |
870b35565e3ae8e46a0e2a12179675a20825f5c4 | targupt/projects | /project -1 calculator.py | 325 | 4.3125 | 4 | num1 = int(input("1st number "))
num2 = int(input("2nd number "))
sign = input("which sign(+,-,/,x or *)")
if sign == "+":
print(num1+num2)
elif sign == "-":
print(num1-num2)
elif sign == "/":
print(num1/num2)
elif sign == "x" or sign == "X":
print(num1*num2)
else:
print("wrong input please try again")
|
b37131762f81e96b6122212f27e2265d9ba00ef4 | yana5k/amis | /km-82/Burlachenko_Yana/workshop1/source/The First/Function.py | 286 | 3.78125 | 4 | n = int(input("n = "))#введення даних
def f(n):#рекурсивна функція
if n < 3:#блок перевірки кінця рекурсії
return
if n == 3:#блок перевірки кінця рекурсії
return 4
print(f(n)/f(n - 1)
print(f(n))
|
a1133186f694fb020ebdf74dfb0ee53fa2da721b | waviq/PythonLatihan | /strings.py | 454 | 3.890625 | 4 | nama = 'Waviq Subhi';
print(nama[0])
print(nama[3])
print(nama[-1])
print(nama[0:5:2])
number = "1, 2, 3, 4, 5, 6"
print(number[0::3])
print("Waviq "*2)
print("Waviq "*(3+2))
# #in = digunakan untuk membandingin isi variabel, apakah memiliki nilai
# yang sama atau memiliki isi yang mirip dg variabel yang di bandingin (mirip kya bwt search)
today = "sunday"
print("day" in today)
print("un" in today)
print("waviq" in "waviq")
print("sk" in "waviq") |
8c97900b4ac05dcbfb345d5f6ded07e9cccb823f | ljxgit/DataStructure | /SortAlgorithm/MergeSort.py | 1,058 | 4.03125 | 4 | # -*- coding:utf-8 -*-
# Python实现归并排序(稳定排序),主要思想是合并两个有序数组,如果是一个无序的数组,则首先拆分成单个元素,然后两两合并成有序数组,时间复杂度是O(nlogn)
def merge_sort(lists):
# 递归,先拆分,再合并
if len(lists) <= 1:
return lists
mid = len(lists)>>1
# 切分到left和right都只有一个元素时,开始合并
left = merge_sort(lists[:mid])
right = merge_sort(lists[mid:])
return merge(left, right)
# 合并两个列表,left和right各自已经是有序数组
def merge(left,right):
result = []
idx1 = idx2 =0
while(idx1<len(left) and idx2<len(right)):
if left[idx1]<right[idx2]:
result.append(left[idx1])
idx1+=1
else:
result.append(right[idx2])
idx2+=1
if idx1<len(left): # left有剩余元素,直接加入result列表
result.extend(left[idx1:])
if idx2<len(right):
result.extend(right[idx2:])
return result
|
01c172d4c6c6b4d9714c2aca9b9d4b425a3933d3 | lexjox777/Python-conditional | /main.py | 838 | 4.21875 | 4 | # x=5
# y=6
# if x<y:
# print('Yes')
#==========
# if 'Hello' in 'Hello World!':
# print('Yes')
#==================
# x=7
# y=6
# if x > y:
# print('yes it is greater')
# elif x < y:
# print('no it is less')
# else:
# print('Neither')
#==================
# '''
# Nested if statement
# '''
# num = -3
# if num >= 0:
# if num==0:
# print('Zero')
# else:
# print('Positive number')
# else:
# print('Negative number')
# ===================
# '''
# one-Line 'if' statements
# '''
# if 7>5: print('yes it is')
#==========================
'''
Ternary operator
'''
# print('Yes') if 4>5 else print('No')
#or the above can be written in this form below too
if 4>5:
print('Yes')
else:
print('No')
# num=5
# if num >=0:
# print('Zero')
# else:
# print('Negative')
|
789c16069aa84901e4bbe995d13018a0ed4c11ff | urashimaeffect0083/GovLens | /readSQLite.py | 1,808 | 3.578125 | 4 |
'''
Reference URLs:
https://sqlite.org/cli.html
'''
import sqlite3
import argparse
from os.path import exists, join
from os import makedirs
import pandas as pd
def showSQLite3TblToCSV(inputDFPath, outputDirPath):
# connect database file
conn = sqlite3.connect(inputDFPath)
# set SQL connection and cursor
cursor = conn.cursor()
print(cursor)
# get all tables
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
# fechall table
tables = cursor.fetchall()
# loop through all tables
for table_name in tables:
table_name = table_name[0]
print(table_name)
# set table
table = pd.read_sql_query("SELECT * from %s" % table_name, conn)
# set output file path
outputFilePath = join(outputDirPath, table_name + '.csv')
# output database tables in csv file format
table.to_csv(outputFilePath, index_label='index')
cursor.close()
conn.close()
def main(args):
if not exists(args.input_db_path):
print("Please enter database file path")
exit(0)
if not exists(args.output_dir_path):
makedirs(args.output_dir_path)
showSQLite3TblToCSV( args.input_db_path,
args.output_dir_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='readSQLite.py -- read slite3 data file and show tables.')
parser.add_argument('--input_db_path', type=str,
default='.\db.sqlite3',
help='db.splite3 file path')
parser.add_argument('--output_dir_path', type=str,
default='C:\\Users\\toruh\\Downloads\\outputs',
help='Output directory path.')
args = parser.parse_args()
main(args)
|
84650242ab531d3a0755452b8c6eb4476e0a710c | dncnwtts/project-euler | /1.py | 582 | 4.21875 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
# multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
def multiples(n,k):
multiples = []
i = 1
while i < n:
if k*i < n:
multiples.append(k*i)
i += 1
else:
return multiples
m3 = multiples(10,3)
m5 = multiples(10,5)
mults = m3 + m5
answer = sum(set(mults))
assert answer == 23, "Test case failed, I got {0}".format(answer)
m3 = multiples(1000,3)
m5 = multiples(1000,5)
mults = m3 + m5
answer = sum(set(mults))
print(answer)
|
61c34a415f86f857f22136416b3c7f7a29385617 | dncnwtts/project-euler | /20.py | 561 | 3.859375 | 4 | # 10! = 3628800 and the sum of these digits is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
# Find the sum of the digits in the number 100!.
def fact(n):
if n == 1:
return n
else:
return n*fact(n-1)
def count(n):
numdigs = len(str(n))
val = 0
for i in range(numdigs)[::-1]:
dig = n/10**i
val += dig
n -= dig*10**i
return val
assert fact(10) == 3628800, "Factorial function is incorrect, {0}".format(fact(10))
assert count(fact(10)) == 27, "Sum of digits function is incorrect, {0}".format(count(fact(10)))
n = fact(100)
#print fact(100)
print count(n)
|
a82a468fb42aefca02bb7c6978bbc29e9a77ee05 | dncnwtts/project-euler | /19.py | 1,799 | 3.953125 | 4 | # You are given the following information, but you may prefer to do some research for yourself.
#
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alone,
# Which has twenty-eight, rain or shine.
# And on leap years, twenty-nine.
# A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
#
# How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
class Date():
def __init__(self):
self.day = 1 # monday == 1
self.month = 0 # january == 1
self.date = 1 # first of month
self.year = 1900
self.leap = False
def increment(self):
self.day += 1
if self.day % 7 == 0:
self.day = 0
self.date += 1
if (self.date > 30) & (self.month in [8, 3, 5, 10]):
self.month += 1
self.date = 1
elif (self.date > 31) & (self.month in [0, 2, 4, 6, 7, 9, 11]):
self.month += 1
self.date = 1
elif (self.date > 29) & (self.month == 1) & self.leap:
self.month += 1
self.date = 1
elif (self.date > 28) & (self.month == 1) & (not self.leap):
self.month += 1
self.date = 1
else:
pass
if self.month == 12:
self.month = 0
self.year += 1
if ((self.year % 4 == 0) & (self.year % 100 != 0)) | (self.year % 400 == 0):
self.leap = True
else:
self.leap = False
return
num_firstsuns = 0
current_date = Date()
while current_date.year < 1901:
current_date.increment()
while current_date.year < 2001:
current_date.increment()
if (current_date.day == 0) & (current_date.date == 1):
num_firstsuns += 1
#print '{0}/{1}/{2}'.format(current_date.month+1, current_date.date, current_date.year)
print num_firstsuns
|
d23f970f82d5cf0b3ebccdde733bec17201a980c | dmonyei/Python-Blackjack | /Blackjack(Beta).py | 6,424 | 3.875 | 4 | import random
deck = {"Ace of Diamonds": 11, "Two of Diamonds" : 2, "Three of Diamonds": 3 , "Four of Diamonds": 4 , "Five of Diamonds" : 5,
"Six of Diamonds": 6, "Seven of Diamonds": 7, "Eight of Diamonds": 8, "Nine of Diamonds": 9, "Ten of Diamonds": 10,
"Jack of Diamonds" :10,"Queen of Diamonds": 10, "King of Diamonds" : 10, "Ace of Hearts": 11,
"Two of Hearts": 2, "Three of Hearts": 3 ,"Four of Hearts": 4, "Five of Hearts": 5, "Six of Hearts": 6,
"Seven of Hearts": 7, "Eight of Hearts": 8,"Nine of Hearts": 9, "Ten of Hearts": 10,
"Jack of Hearts": 10, "Queen of Hearts": 10, "King of Hearts": 10,
"Ace of Spades": 11, "Two of Spades": 2, "Three of Spades": 3, "Four of Spades": 4,
"Five of Spades": 5, "Six of Spades": 6, "Seven of Spades": 7, "Eight of Spades": 8, "Nine of Spades": 9,
"Ten of Spades": 10, "Jack of Spades": 10, "Queen of Spades": 10, "King of Spades": 10, "Ace of Clubs": 11,
"Two of Clubs": 2, "Three of Clubs": 3, "Four of Clubs": 4, "Five of Clubs": 5, "Six of Clubs": 6,
"Seven of Clubs": 7, "Eight of Clubs": 8, "Nine of Clubs": 9, "Ten of Clubs": 10,
"Jack of Clubs": 10, "Queen of Clubs": 10, "King of Clubs": 10
}
def score_hand(hand):
score_without_aces = 0
ace_count = 0
possible_scores = []
for card in hand:
if card.startswith('Ace'):
ace_count += 1
pass
else:
score_without_aces += deck[card]
if ace_count == 0:
return score_without_aces
elif ace_count == 1:
possible_scores.append(score_without_aces + 1)
possible_scores.append(score_without_aces + 11)
elif ace_count == 2:
possible_scores.append(score_without_aces + 2)
possible_scores.append(score_without_aces + 12)
elif ace_count == 3:
possible_scores.append(score_without_aces + 3)
possible_scores.append(score_without_aces + 13)
elif ace_count == 4:
possible_scores.append(score_without_aces + 4)
possible_scores.append(score_without_aces + 14)
elif ace_count == 5:
possible_scores.append(score_without_aces + 5)
possible_scores.append(score_without_aces + 15)
for s in sorted(possible_scores, reverse = True):
if s > 21:
continue
else:
return s
class Players:
def __init__(self, name):
self.name = name
self.hand = []
def draw(self):
list_deck = list(deck)
if len(self.hand) == 0:
self.hand.append(random.choice(list_deck))
self.hand.append(random.choice(list_deck))
print(self.name + "Hand: " + ' , '.join(self.hand))
else:
self.hand.append(random.choice(list_deck))
print(self.name + "Hand: " + ' , '.join(self.hand))
dealer = Players("Dealer")
player = Players("Player")
Start_or_Stop = input("Welcome to Casino Blackjack table, Press Enter to continue or 'NO' to Exit")
Start_or_Stop = Start_or_Stop.upper()
if Start_or_Stop == '' \
'':
print("Rules: 1. Dealer must stay on all 17's" '\n' + ' ' + "2. When player has 5 cards in hand and value less than or equal to 21, player wins. ")# " '\n' + ' '
# + "3.
print("***************************************************************************************************************")
if Start_or_Stop == '' \
'':
player.draw()
sum_of_player = score_hand(player.hand)
print("Player Total: ", sum_of_player)
#print("Cards in Hand: ", len(player.hand))
if sum_of_player == 21:
print("Blackjack, YOU WIN")
exit()
choice = input("Do you want to 'HIT' or 'STAY', type your result. ")
decision = choice.upper()
while decision == 'HIT':
#print(player.hand)
player.draw()
#print(player.hand)
sum_of_player = score_hand(player.hand)
if sum_of_player == None:
print("BUST, better luck next time.")
exit()
print("Player Total: ", sum_of_player)
#print("Cards in Hand: ", player.hand)
if sum_of_player == 21:
print("Blackjack, YOU WIN")
break
if len(player.hand) >= 5 and sum_of_player < 21:
print("You beat the odds, YOU WIN")
exit()
elif sum_of_player > 21:
print("BUST, better luck next time.")
exit()
choice = input("Do you want to 'HIT' or 'STAY', type your result. ")
decision = choice.upper()
while decision == "STAY":
dealer.draw()
sum_of_dealer = score_hand(dealer.hand)
print("Dealer Total: ", sum_of_dealer)
#print("Cards in Hand: ", dealer.hand)
#print(sum_of_dealer)
if sum_of_player == sum_of_dealer:
print("push....you Tie, maybe next time.")
exit()
while sum_of_dealer < 17:
dealer.draw()
sum_of_dealer = score_hand(dealer.hand)
print("Dealer Total: ", sum_of_dealer)
#print("number of cards in dealer hand", dealer.hand)
#print("Total of dealer cards", sum_of_dealer)
if sum_of_player == sum_of_dealer:
print("push....you Tie, maybe next time.")
exit()
if sum_of_dealer == None:
print("Dealer BUST, better luck next time.")
print("Player Wins!")
exit()
if sum_of_dealer > 21:
print("Dealer Bust, Player wins")
exit()
if sum_of_dealer >= 17:
if sum_of_player > 21:
print("You Win, Test your luck with another round?")
exit()
if sum_of_dealer < sum_of_player:
print("You Win, Test your luck with another round?")
exit()
elif sum_of_dealer > sum_of_player:
print("You lose, play again???")
exit()
exit()
if Start_or_Stop == "NO":
print("You have exited game")
exit()
|
1d355fa0dce229a7c480bf4043aef3a54c235ba2 | FabijanC/aoc2017 | /day13/13_2.py | 2,113 | 3.609375 | 4 | def move():
global curr, direction, range_
for scanner in curr:
if curr[scanner] == range_[scanner]:
curr[scanner] -= 1
direction[scanner] = "up"
elif curr[scanner] == 1:
curr[scanner] = 2
direction[scanner] = "down"
elif direction[scanner] == "up":
curr[scanner] -= 1
elif direction[scanner] == "down":
curr[scanner] += 1
else:
print("ERR")
'''
if direction[scanner] == "down":
curr[scanner] += 1
if curr[scanner] == range_[scanner]:
direction[scanner] = "up"
if direction[scanner] == "up":
curr[scanner] -= 1
if curr[scanner] == 1:
direction[scanner] = "down"
'''
f = open("13.txt", "r")
lines = f.readlines()
f.close()
range_ = dict()
curr = dict()
direction = dict()
for line in lines:
left, right = [int(i) for i in line.strip().split(": ")]
range_[left] = right
curr[left] = 1
direction[left] = "down"
minseverity = 1
last_config = (dict(curr), dict(direction))
seen = list()
seen.append((tuple(curr.values()), tuple(direction.values())))
while True:
#for i in curr:
# curr[i] = 1
# direction[i] = "down"
#for _ in range(minseverity):
# move()
curr = last_config[0]
direction = last_config[1]
move()
last_config = (dict(curr), dict(direction))
print(curr.values())
#t = (tuple(curr.values()), tuple(direction.values()))
#if t in seen:
# print(minseverity)
# break
#else:
# seen.append(t)
#if minseverity % 1000 == 0:
# print(minseverity)
#max depth is recorded in variable left
severity = 0
for position in range(left + 1):
if position in range_ and curr[position] == 1:
##severity += range_[position] * position
severity = 1
break
move()
if severity == 0:
break
minseverity += 1
print(minseverity)
|
fe2170c700f47a0ddf827508b17d62bebaadd9df | rookie1020/Recommendation-System | /mf_sgd.py | 4,460 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 28 01:48:05 2018
@author: J Rishabh Kumar
@content: matrix factorization using gradient descent
"""
import numpy as np
import matplotlib.pyplot as plt
class MF():
def __init__(self, R, K, alpha, beta, iterations):
"""
Perform matrix factorization to predict empty
entries in a matrix.
Arguments
- R (ndarray) : user-item rating matrix
- K (int) : number of latent dimensions
- alpha (float) : learning rate
- beta (float) : regularization parameter
"""
self.R = R
self.num_users, self.num_items = R.shape
self.K = K
self.alpha = alpha
self.beta = beta
self.iterations = iterations
self.pred_mat = np.zeros(R.shape)
self.RMSE_train_after_each_iter = []
def train(self):
# Initialize user and item latent feature matrice
self.P = np.random.normal(scale=1./self.K, size=(self.num_users, self.K))
self.Q = np.random.normal(scale=1./self.K, size=(self.num_items, self.K))
# Initialize the biases
self.b_u = np.zeros(self.num_users)
self.b_i = np.zeros(self.num_items)
self.b = np.mean(self.R[np.where(self.R != 0)])
# Create a list of training samples
self.samples = [
(i, j, self.R[i, j])
for i in range(self.num_users)
for j in range(self.num_items)
if self.R[i, j] > 0
]
# Perform stochastic gradient descent for number of iterations
training_process = []
for i in range(self.iterations):
np.random.shuffle(self.samples)
self.sgd()
rmse = self.rmse()
self.RMSE_train_after_each_iter.append(rmse)
training_process.append((i, rmse))
print("Iteration: %d ; RMSE = %.4f" % (i+1, rmse))
return training_process, self.pred_mat
def rmse(self):
"""
A function to compute the total mean square error
"""
xs, ys = self.R.nonzero()
self.pred_mat = self.full_matrix()
error = 0
for x, y in zip(xs, ys):
error += pow(self.R[x, y] - self.pred_mat[x, y], 2)
error /= len(xs)
return np.sqrt(error)
def sgd(self):
"""
Perform stochastic graident descent
"""
for i, j, r in self.samples:
# Computer prediction and error
prediction = self.get_rating(i, j)
e = (r - prediction)
# Update biases
self.b_u[i] += self.alpha * (e - self.beta * self.b_u[i])
self.b_i[j] += self.alpha * (e - self.beta * self.b_i[j])
# Update user and item latent feature matrices
self.P[i, :] += self.alpha * (e * self.Q[j, :] - self.beta * self.P[i,:])
self.Q[j, :] += self.alpha * (e * self.P[i, :] - self.beta * self.Q[j,:])
def get_rating(self, i, j):
"""
Get the predicted rating of user i and item j
"""
prediction = self.b + self.b_u[i] + self.b_i[j] + self.P[i, :].dot(self.Q[j, :].T)
if prediction > 5.0:
prediction = 5.0
return prediction
def full_matrix(self):
"""
Computer the full matrix using the resultant biases, P and Q
"""
return self.b + self.b_u[:,np.newaxis] + self.b_i[np.newaxis:,] + self.P.dot(self.Q.T)
def plot_RMSE(self):
plt.plot(range(1,self.iterations + 1),self.RMSE_train_after_each_iter, marker='o', label='Training RMSE')
#plt.plot(range(1,self.iterations + 1),self.RMSE_test_after_each_iter, marker='v', label='Testing RMSE')
plt.title('MF with SGD with alpha = %.3f and $\ beta =%.3f' % (self.alpha, self.beta))
plt.xlabel('Number of iterations')
plt.ylabel('RMSE')
plt.legend()
plt.grid()
plt.show()
def recTopN(self, user, n):
"""
recommend top-N items for user u in form of list
"""
self.n = n
if user >= 0 & user < 50:
user_vec = self.pred_mat[user,:]
recom = dict()
for i in range(len(user_vec)):
temp = []
|
30f24e310183f61b552192a91064c2149d705f07 | clayton-halim/claybotics | /MotorManager.py | 2,273 | 3.75 | 4 | import Motor
from MotorState import MotorState
class MotorManager():
def __init__(self, motorLeft, motorRight):
self.mLeft = motorLeft
self.mRight = motorRight
self.state = MotorState.CENTER
def setDirection(self, horizontal, depth):
if horizontal == "left":
if depth == "forward":
print("forward left")
self.state = MotorState.FORWARD_LEFT
elif depth == "backward":
print("backward left")
self.state = MotorState.BACKWARD_LEFT
else:
print("left")
self.state = MotorState.LEFT
elif horizontal == "right":
if depth == "forward":
print("forward right")
self.state = MotorState.FORWARD_RIGHT
elif depth == "backward":
print("backward right")
self.state = MotorState.BACKWARD_RIGHT
else:
print("right")
self.state = MotorState.RIGHT
elif horizontal == "center":
if depth == "forward":
print("forward")
self.state = MotorState.FORWARD
elif depth == "backward":
print("backward")
self.state = MotorState.BACKWARD
else:
print("stop")
self.state = MotorState.CENTER
def setMovement(self):
if self.state == MotorState.CENTER:
self.stop()
elif self.state == MotorState.FORWARD:
self.forward()
elif self.state == MotorState.BACKWARD:
self.backward()
elif self.state == MotorState.RIGHT:
self.right()
elif self.state == MotorState.LEFT:
self.left()
elif self.state == MotorState.FORWARD_RIGHT:
self.forwardRight()
elif self.state == MotorState.FORWARD_LEFT:
self.forwardLeft()
elif self.state == MotorState.BACKWARD_RIGHT:
self.backwardRight()
elif self.state == MotorState.BACKWARD_LEFT:
self.backwardLeft()
def forward(self):
self.mLeft.forward()
self.mRight.forward()
def backward(self):
self.mLeft.backward()
self.mRight.backward()
def stop(self):
self.mLeft.stop()
self.mRight.stop()
def right(self):
self.mLeft.forward()
self.mRight.backward()
def left(self):
self.mLeft.backward()
self.mRight.forward()
def forwardRight(self):
self.mLeft.forward()
self.mRight.stop()
def forwardLeft(self):
self.mLeft.stop()
self.mRight.forward()
def backwardLeft(self):
self.mLeft.backward()
self.mRight.stop()
def backwardRight(self):
self.mLeft.stop()
self.mRight.backward()
|
e2acccf7ef01ce3f9ee40ffb75f55e502a4c8984 | jhuntley97/Python-Level-2 | /Lab activity 2.py problem 1.py | 90 | 3.609375 | 4 | #Jwaun Huntley
#4/16/19
d={'a':5, 'b':10,'c':15}
for x, y in d.items():
print(x, y)
|
80edc85c156a001668382fe7fe3c1eff3e92617f | Aathish04/Old-Python-Game-Projects | /AdventureTrail/AdventureTrail.py | 14,043 | 3.9375 | 4 | #This game was developed in joint by Rhys Van Der Kruk and Aathish Sivasubrahmanian
#Shoutout to Matthew Riedel, a classmate of mine.
#All My Imports
import time
print("Welcome to Adventure Trail. The Word Game where what you do affects your rate of survival.")
time.sleep(0.5)
playername =(input("Now, What is the name of our brave adventurer? \n > "))#Receives Playername
print("Welcome, " + playername)
time.sleep(0.5)
pathchoose=input("Do you choose the left path, where you can see a forest, or do you go to the right path, where you can see a few buffaloes grazing ? \n >") #The Initial Pathway split, Choosing one or the other pits the player against different obstacles.
if pathchoose=='left':
print("You have chosen the left path")
time.sleep(0.5)
print("You walk down the path towards the dark forest.")
forest=input("A wizard appears before the entrance. He says: Go through the forest or go around, "+playername+", it's your choice. \n > ") #The Second Decision.
if forest=='go through':
print("You enter the forest.")
time.sleep(0.5)
sketchings=input("You see sketchings on a tree. Do you attempt to read them? \n > ")
if sketchings=='yes':
print("They can barely be seen but they say urbytejywkyaoirbke, "+ playername)
time.sleep(0.5)
print("You wonder how your name is here.")
if sketchings=='no':
print("The marks don't seem important. You keep walking on.")
time.sleep(0.5)
dagger=input("As you continue through the forest you almost trip on a dagger. Do you take it? \n >") # The Player chooses whether to take a weapon or not.
if dagger=='yes':
print("You pick up the dagger. You feel its sharp edge")
time.sleep(0.5)
if dagger=='no':
print("Dejectedly, you kick it away, It never was your favourite weapon anyway.")
time.sleep(0.5)
print("You walk into a nearly invisible giant spider web. It's resident, the spider, crawls slowly towards you.")
if dagger=='yes':
print("You take hold of your dagger, glad you picked up.You cut through the web and run away as fast as you can with the spider at your heels.")
time.sleep(0.5)
print("It chases you to the front of a cave, dimly lit with torches.")
time.sleep(0.5)
cave=input("Do you enter the cave? \n >")
if cave=="yes":
time.sleep(0.5)
print("You slowly creep into the cave. You take a torch from the nearby stand, and keep walking.")
time.sleep(0.5)
if cave=="no":
time.sleep(0.5)
print("You decide not to go into the eery cave, which even the spider doesn't want to go near.")
time.sleep(0.5)
print("You notice that there are two paths; each leading different ways")
crossroad1=input("Do you go left, or do you go right?")
if crossroad1=="left" or "go left":
time.sleep(0.5)
print("You have gone left")
if crossroad1=="right" or "go right":
time.sleep(0.5)
print("You have gone right.")
if dagger=='no':
time.sleep(0.5)
print("Now you wish you had the dagger with you. You sense your death coming near")
answer=input(" The Spider says: 'I see you have no weapon to defend yourself. As a gift of mercy, I will ask you a riddle: The riddle is: \n Stronger than steel, yet lighter than cotton \n Found in a corner, forever forgotten, \n I bother so many, but marvel a few \n You can't seem to make me, I'm a mystery to you. \n Now answer or I shall feast. You only get a single chance' \n >")
if answer==('Spider Silk'):
time.sleep(0.5)
print("It seems you have got it correct. Perhaps you are not biological waste after all.(the spider cuts you free)")
cave=input("You then run far away, to a cave, dimly lit with almost stuttering torches. Do you go in? \n>")
if cave=="yes" or "Yes":
print("You slowly step into the cave, taking a lacquer torch from the sides.")
if cave=="no":
print("You take a step back, not wanting to go into the eery cave.")
crossroad2=input("You see that you have arrived at a crossroads. \n Go left or go right? \n >")
if crossroad2=="left":
print("You have gone left.")
if crossroad2=="right":
print("You have gone right.")
else:
time.sleep(0.5)
print("That is incorrect! Now I shall feast. The spider injects you with venom, paralyizing you. Dark spots appear in your eyes. the blood draining out of you and your body liquefyng. Your last thought is...At least I made a pretty good meal for a spider. You are now dead," +playername)
if forest=="go around":
time.sleep(0.5)
print("You decide to go around the forest")
time.sleep(0.5)
print("You walk around with the trees to your left")
sword=input("You see a slightly rusted bronze sword. Do you pick it up? \n >")
if sword=="yes":
time.sleep(0.5)
print("You pick up the sword and strap it to your back. You feel defended now.")
time.sleep(0.5)
print("You continue around the Forest.")
time.sleep(0.5)
ogres=input("You see some ogres. Do you attack or run? \n >")
if ogres=="attack":
print("You manage to successfully stab the nearest one to you without getting eaten, you spin and lop the leg off the second one. The third one, a child, is quivering and shaking in fear.")
time.sleep(0.5)
child=input("Do you kill the child as well? \n > ")
if child=="yes":
time.sleep(0.5)
print("You look the child in the eye, and stab it in the heart, you cruel monster!")
time.sleep(0.5)
bracelet=input("You find that the ogre child has an emerald bracelet. Take Bracelet? \n > ")
if bracelet=="yes":
time.sleep(0.5)
print("Despicable! Stealing from a murdered child!")
if bracelet=="no":
time.sleep(0.5)
print("You feel disgusted at stealing from a dead body.")
sheath=input("Sheath Sword? \n > ")
if sheath=="yes":
time.sleep(0.5)
print("You leave the child's body.")
if sheath=="no":
time.sleep(0.5)
print("You keep your sword in your hand, ready to defend yourself if necessary. \n You slip on a pool of blood, and impale yourself on your own sword, because you didn't sheath it.")
if child=="no":
time.sleep(0.5)
print("You turn your back on the child, sword still in hand.")
time.sleep(0.5)
sheath=input("Sheath Sword? \n > ")
if sheath=="yes":
time.sleep(0.5)
print("You leave the child crying near the bodies of her murdered parents.")
# Add more scenarios here
if sheath=="no":
time.sleep(0.5)
print("You Turn around, sword in hand, you hear a sharp whistling sound an a thwack, as the child fires a dart into your back. \n You see funny colours and black out. You are now dead. ")
if ogres=="run":
print("You quickly run away from the ogre campsite")
time.sleep(0.5)
print("As you keep walking, you find a boat, moored to the river.")
time.sleep(0.5)
river=input("Do you cross the river or sail? \n >")
if river=="cross":
time.sleep(0.5)
print("You use the boat to cross the river, and continue on your journey.")
if river=="sail":
time.sleep(0.5)
print("You use the boat to sail down the river.")
print("You sail for days on end, and all at once, you see a port!")
port==input("Do you dock the boat here? \n >")
if port=="yes"or"yes":
print("You throw a rope onto the port and pull yourself to the banks of the river.")
#add more scenarios here
if port=="no" or "No":
print("You lie back down, thinking that the port isnt worth the trouble, a few days later you have expended all your food. \n You slip into a coma, and your boat falls off a waterfall")
print("Congrajulations, " +playername+ ", You are now dead")
if sword=="no":
time.sleep(0.5)
print("You decide to leave the sword alone. You feel like you have made a bad choice.")
time.sleep(0.5)
print("You continue around the Forest.")
time.sleep(0.5)
ogres=input("You see some ogres. Do you attack or run? \n >")
if ogres=="run":
time.sleep(0.5)
print("You try to run but the ogres spot you and shoot you with a poison dart. You see funny colours and black out. \n You are now dead" +playername+ "because you tried to run from bloody ogres!")
if ogres=="attack":
print("You hit one of the ogres in the face with your fist. The ogre is agitated and flicks you into space.You land on the moon, dazed. You think 'I'm on the moon so that means...Can't....Breath.' \n Great job, you died because you thought you could take down an entire ogre without a weapon, "+playername)
if pathchoose=='right':
print("You have chosen the right path")
print("You walk towards the open plains")
time.sleep(0.5)
buffalo=input("You see a herd of wild buffalo. Do you yell or attack? \n > ")
if buffalo == 'attack' :
print("You decide to attack the buffaloes. The buffaloes charge and trample you. You are now dead, "+playername)
if buffalo=="yell":
time.sleep(0.5)
print("You yell at the buffalo. They start walking away with caution.")
book=input("As you walk along the plains, a book appears from the earth and wills you to take it. \n Do you accept the book? \n > ")
if book=='yes':
time.sleep(0.5)
print("Unable to snap out of the trance you touch the book. It opens and shoots a beam of brown light towards your chest.The longer it beams the heavier you seem and the stronger you feel. The last item you see is a emblem made of earth in the shape of a small mountain. It implants itself into your chest. The book clossess and desinagrates into peices of earth never to be seen again")
time.sleep(0.5)
print("You get up dazed from what just happened. You move you hands and it causes the earth around to move.You get some ideas to help you. You think you can either tunnel undergroud or launch yourself forward.")
idea=input("Tunnel or launch? \n > ")
if idea=="launch":
time.sleep(0.5)
print("You launch yourself into sky and land safely on the far side of the plains next to a desert")
if idea=="tunnel":
time.sleep(0.5)
print("You move the earth around you and make a hole that you fall into. Since you can't control your powers (dumbass),am the hole seals up and crushes you. You are now dead"+playername)
if book=='no':
time.sleep(0.5)
print('You snap out of the trance. The book is too scary to be trusted')
time.sleep(0.5)
print('You keep walking through the plains and you see a friendly squirrel.')
time.sleep(0.5)
squirrel=input('Pet or keep walking? \n > ')
if squirrel=="pet" or "pets":
time.sleep(0.5)
print("The Squirrel savours the moment, looking at you adoringly. It scurries away, returning a moment later with an Acorn and a Small Brass Key.")
takestuff=input("Take Key and acorn? \n >")
if takestuff=="yes":
print("You place your open palm near the squirrel. It quickly places the things into your hand and scurries off. ")
print("You come across an old basin of dirt that seems soft enough to dig")
plant=input("Do you plant the Acorn? \n >")
if plant=="yes"or"Yes"or"Y":
time.sleep(0.5)
print("You kneel down and plant the acorn, feeling good about yourself.")
time.sleep(0.5)
print("As you step back, you feel the ground below you rumbling.")
print("You turn around, and notice that the acorn has already sprouted into a small plant, with two branches; the rumbling seems to be coming from the plant")
time.sleep(0.5)
print("You take a step towards the plant. Suddenly, the plant grows legs, and steps out of the basin.")
time.sleep(0.5)
print("The plant walks up to you, looks up at you and says 'I am Froot!' \n climbing onto your shoulder, all the while repeating the words 'I am Froot!' ")
# More stuff to be added here soon
time.sleep(0.5)
if takestuff=="no":
print("You keep walking.")
time.sleep(0.5)
|
26da6bf89f628c85fe288a0f0e229c8a0772b3b6 | arunravi74/Edyoda_Python_Quiz_App | /database.py | 2,326 | 3.734375 | 4 | import sqlite3
from IPython.display import clear_output
"""connection=sqlite3.connect("Info.db")
sql=\"""CREATE TABLE if not EXISTS questions(
Question VARCHAR(50),
Topic VARCHAR(20),
difficulty_level VARCHAR(20),
Option_A VARCHAR(20),
Option_B VARCHAR(20),
Option_C VARCHAR(20),
Option_D VARCHAR(20),
Corr_Ans VARCHAR(1));\"""
my_cursor=connection.cursor()
my_cursor.execute(sql)
connection.commit()
connection.close()"""
#Adding some questions
"""questions=[('what is capital of India?','General','easy','delhi','bangalore','punjab','hyderabad','A'),
('what is 2/2 = ?','Maths','easy','2','1','3','0','B'),
('What is National bird of India?','General','easy','Eagle','Peigon','peacock','hummingbird','C'),
('where is TajMahal located in india?','General','easy','Agra','Pune','Jaipur','none of the above','A'),
('what is the national sports of India?','Sports','easy','Cricket','Hockey','FootBall','VolleyBall','B'),
('OS computer abbreviation ?','Computer Science','medium','Order of Significance','Open Software','Operating System','Optical Sensor','C')]
sql=\"""INSERT INTO questions (Question,Topic,difficulty_level,Option_A,Option_B,Option_C,Option_D,Corr_Ans)
VALUES(?,?,?,?,?,?,?,?);\"""
conn=sqlite3.connect('Info.db')
my_cursor=conn.cursor()
my_cursor.executemany(sql,questions)
my_cursor.execute("SELECT * FROM questions")
result=my_cursor.fetchall()
for x in result:
print(x)
conn.commit()
conn.close()"""
"""conn=sqlite3.connect('Info.db')
my_cursor=conn.cursor()
my_cursor.execute(\"""CREATE TABLE IF NOT EXISTS Admin(
User_id INTEGER PRIMARY KEY,
Name VARCHAR(30),
Password VARCHAR(20))
\""")
my_cursor.fetchall()
conn.commit()
conn.close()"""
"""conn=sqlite3.connect('Info.db')
my_cursor=conn.cursor()
my_cursor.execute("insert into Admin values(1,'Arun','Arun@123');")
my_cursor.fetchall()
conn.commit()
conn.close()"""
"""conn=sqlite3.connect('Info.db')
my_cursor=conn.cursor()
my_cursor.execute(\"""CREATE TABLE IF NOT EXISTS Members(
Name VARCHAR(30),
Date DATE,
Score INTEGER DEFAULT 0);
\""")
my_cursor.fetchall()
conn.commit()
conn.close()""" |
ff5952abf7de4d60b3123551f4bf05466f67b620 | ankittrehan2000/RockPaperScissors | /RockPaperScissors.py | 270 | 3.71875 | 4 | import random
def RockPaperScissor():
number = random.randint(1,3)
#1 - Rock
#2 - Paper
#3 - Scissors
if (number == 1):
return 'rock'
elif (number == 2):
return 'paper'
elif (number == 3):
return 'scissors'
else:
return 'Facing errors' |
73c582cbae91273375e9d1964873a193a88d19d6 | awanjila/python_play_ground | /roll_dice.py | 298 | 4.0625 | 4 | import random
def roll_the_dice():
max=8
min=1
roll_dice="yes"
while roll_dice =="yes" or roll_dice=="y":
print("rolling the dice...")
print("The values are...")
print random.randint(min,max)
print random.randint(min,max)
roll_dice=raw_input("roll the dices again?")
roll_the_dice() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.