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 |
|---|---|---|---|---|---|---|
c2d821b83ecc693ba04247ba12a8d7ffcf0919cc | MatthewH1988/Python-Techdegree-Project-1 | /guessing_game.py | 1,238 | 4.0625 | 4 |
import random
def start_game():
print("Welcome to the Number Guessing Game!")
import random
guess_count = 1
while True:
try:
random_number = random.randrange(0, 11)
player_guess = int(input("Please guess a number between 0 and 10: "))
if player_guess < 0 or player_guess > 10:
raise ValueError
except ValueError:
print("That is not a valid response! Please try again!")
continue
else:
while player_guess != random_number:
if (player_guess > random_number):
print("It's lower")
guess_count += 1
player_guess = int(input("Please guess again!: "))
elif (player_guess < random_number):
print("It's higher")
guess_count += 1
player_guess = int(input("Please guess again!: "))
else:
attempt_count += 1
break
print("That's correct!")
break
print("That's the end of the game! It took you {} attempts to guess correctly!".format(guess_count))
start_game() |
aaa0660306c6486820cde0f6e75f315cfec3ca3b | NickSKim/csci321 | /PygameDemos/0700rpg/tiles.py | 4,897 | 3.625 | 4 | import os, pygame
from pygame.locals import *
from utilities import loadImage
class InvisibleBlock(pygame.sprite.Sprite):
def __init__(self, rect):
pygame.sprite.Sprite.__init__(self)
self.rect = rect
def draw(surface):
pass
class Tile(pygame.sprite.Sprite):
def __init__(self, image, position, wall):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = image.get_rect()
self.rect.topleft = position
self.wall = wall
class EmptyTile(pygame.sprite.Sprite):
"""Used to fill empty space, so that each cell of the board
can hold some data. For example, "Are you a wall?"""
def __init__(self, wall = False):
pygame.sprite.Sprite.__init__(self)
self.wall = wall
class _TileManager():
def __init__(self,tilefile='basictiles.png',
room='roomtiling.data',
tilemap='tilemap.data',
datafolder=os.path.join('data','text'),
imagefolder=os.path.join('data','images')
):
self.tilefile = tilefile
self.room = room
self.tilemap = tilemap
self.datafolder = datafolder
self.imagefolder = imagefolder
self.invisibleBlocks = []
self.initialized = False
def initialize(self, scale = 3):
if self.initialized:
return self
self.initialized = True
# load all the tiles
self.tilefile = loadImage( self.tilefile, self.imagefolder, colorkey=None)
mapfile = open(os.path.join(self.datafolder, self.tilemap), 'r')
maplines = mapfile.read().splitlines()
self.dict = {}
for x in maplines:
mapping = [s.strip() for s in x.split(',')]
key = mapping[6]
self.dict[key] = {}
w,h = int(mapping[2]), int(mapping[3])
row, col = int(mapping[4]), int(mapping[5])
self.dict[key]['name'] = mapping[0]
self.dict[key]['file'] = mapping[1]
self.dict[key]['width'] = w
self.dict[key]['height'] = h
self.dict[key]['row'] = row
self.dict[key]['col'] = col
self.dict[key]['roomkey'] = mapping[6]
self.dict[key]['wall'] = mapping[7] == 'wall'
# find image for this tile
#w, h = self.dict[key]['width'], self.dict[key]['height']
#row, col = self.dict[key]['row'], self.dict[key]['col']
image = pygame.Surface((w,h))
image.blit(self.tilefile, (0,0),
((col*w, row*h), (w,h)))
image = pygame.transform.scale(image, (scale*w, scale*h))
letter = self.dict[key]['roomkey']
if letter in '12346':
w,h = image.get_size()
image.set_colorkey(image.get_at((w/2,h/2)))
elif letter in '578':
image.set_colorkey(image.get_at((0,0)))
self.dict[key]['image'] = image
# tile the room
roomfile = open(os.path.join(self.datafolder, self.room),'r')
roomrows = roomfile.read().splitlines()
self.tiles = pygame.sprite.RenderPlain()
self.tileArray = [[None for x in range(len(roomrows[0]))]
for y in range(len(roomrows))]
for roomrow, keys in enumerate(roomrows):
for roomcol, letter in enumerate(keys):
if letter == '.':
newTile = EmptyTile()
else:
data = self.dict[letter]
newTile = Tile(data['image'],
(roomcol*scale*w, roomrow*scale*h),
data['wall'])
if data['wall']:
newBlock = InvisibleBlock(
pygame.Rect(roomcol*scale*w, roomrow*scale*h,
scale*w, scale*h))
self.invisibleBlocks.append(newBlock)
self.tiles.add(newTile)
self.tileArray[roomrow][roomcol] = newTile
return self
_tilemanager = _TileManager()
def TileManager():
return _tilemanager
#### Some tests:
if __name__ == "__main__":
scale = 3
try:
pygame.init()
screen = pygame.display.set_mode((scale*400, scale*240))
# now we can initialize the tile manager:
tm = TileManager().initialize()
done = False
while not(done):
screen.fill((128,0,0))
tm.tiles.draw(screen)
pygame.display.flip()
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == KEYDOWN and event.key == K_ESCAPE:
done = True
finally:
pygame.quit()
|
c6248c29ef8daad133c18babcffa42664d602a72 | RiverTate/Chern | /hofstadter.py | 2,417 | 3.609375 | 4 | # This program calculate the eigen energies of a qantum Hall
# system (square lattice), and plot the energy as a function
# of flux (applied magnetic filed). The plot of nergy vs. flux
# would generate hofstadter butterfly
# Author: Amin Ahmadi
# Date: Jan 16, 2018
############################################################
# importing numpy and linear algebra modules
import numpy as np
import numpy.linalg as lg
# Function that calculate Hamiltonian H(k)
def H_k(k_vec, p, q):
""" This function calulate the Hamiltonian of a
2D electron gas in presence of an applied magnetic
field. The magnetic field is introduced using
Landau's guage.
in: kx, ky,
p and q are the ratio of p/q = phi/phi0
out: H_k, k-representation of H
"""
Hk = np.zeros((q,q), dtype=complex)
t = 1. # hopping amplitude
phi_ratio = (1.*p)/q # flux per plaquette
kx = k_vec[0]
ky = k_vec[1]
# diagonal elements
for i in range(q):
Hk[i,i] = -t*np.cos( ky - 2.*(i+1)*np.pi*phi_ratio )
# off-diagonal elements
for i in range(q-1):
Hk[i,i+1] = -t
# Magnetic Bloch element
Hk[0,q-1] = -t*np.exp(-q*1.j*kx)
# Make it hermitian
Hk = Hk + Hk.conj().T
return Hk
############################################################
################### Main Program #########################
############################################################
q = 501 # phi/phi0 = p/q
k_vec = np.array([3.0,0], float)
E_arr = np.zeros((q,q), float)
for p in range(q):
E_k= lg.eigvalsh(H_k(k_vec, p, q))
# save data for plotting
E_arr[:, p] = E_k[:]
# save date in file
np.save('./Result/hofs_501_00', E_arr)
############################################################
#################### plotting #########################
############################################################
import matplotlib.pyplot as pl
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
pl.rc("font", family='serif')
pl.rc('text', usetex=True)
fig = pl.figure(figsize=(8,6))
ax = fig.add_subplot(1,1,1)
pq = np.linspace(0,1,q)
for p in range(q):
ax.plot(pq, E_arr[p,:],',k')
ax.set_xlabel(r'$\frac{\phi}{\phi_0}$', fontsize=16)
ax.set_ylabel(r'$E$', fontsize=16)
pl.show()
fig.savefig('./Result/butterfly_501.pdf', bbox_inches='tight')
|
ea9d13753a22f346cd86b677fa49ad6ad54846f6 | AlexFabra/Sudoku | /Sudoku.py | 8,138 | 4 | 4 | import math
class Sudoku:
# guardem els números necessaris per que una fila, columna o quadrant estiguin complets:
nombresNecessaris = [1, 2, 3, 4, 5, 6, 7, 8, 9]
#creem el constructor de Sudoku. Li passarem com a paràmetre un array d'arrays:
def __init__(self,arrays):
self.arrays=arrays
#el métode actualitza actualitza arrays, posant el número introduït a les coordenades:
def actualitza(self,nouNumero,cX,cY):
self.arrays[cX][cY]=nouNumero
#Donats els paràmetres cX i nouNumero, el mètode comprovar fila serveix
# per analitzar si l'últim número introduït és repeteix.
#cX és la coordenadaX, és a dir, la fila que volem obtenir.
#nouNumero és el número introduït per l'usuari.
def comprovarFila(self,fila,nouNumero):
numerosFila = []
for nColumna in range(len(self.arrays)):
numerosFila.append(arrays[fila][nColumna])
#si al vector hi ha més d'un valor igual al nouNumero, retorna false
#false representa un error en el Sudoku:
if numerosFila.count(nouNumero)>1:
print("Aquest número ja hi és a la fila.")
return False
else:
return True
#funció que donat el número a comprovar i la fila on comprovar la seva repetició, retorna true si no s'ha repetit.
#columna és la columna que volem obtenir.
#nouNumero és el número que volem veure si es repeteix.
def comprovarColumna(self,columna,nouNumero):
numerosColumna = []
for nFila in range(len(self.arrays)):
numerosColumna.append(arrays[nFila][columna])
#si al vector hi ha més d'un valor igual al nouNumero, retorna false
#false representa un error en el Sudoku:
if numerosColumna.count(nouNumero)>1:
print("Aquest número ja hi és a la columna.")
return False
else:
return True
#funció que donat un número a comprovar i la posició horitzontal i vertical on s'ubica, identifica el cuadrant
#i retorna false si ja hi ha un número igual en aquest:
def comprovarQuadrant(self,columna,fila,nouNumero):
#vector on guardarem els nombres del quadrant:
numQuadrant = []
# Com que volem trobar el primer número del quadrant per iterar fins a l'últim, treiem el floor de la divisió
# de les coordenades entre 3 (això ens donarà un numero del 0 al 2) i ho multipliquem per 3, que en donarà el
# numero inicial d'un quadrant:
fila = (math.floor(fila / 3)*3)
columna = (math.floor(columna / 3)*3)
# Amb el iterador posem els numeros del quadrant a la llista:
for num in range(fila, fila + 3):
#extend afegeix al final de la llista 'numQuadrant' el valor de la coordenada de 'arrays':
#guardem els valors de tres en tres:
numQuadrant.extend(arrays[num][columna:columna + 3])
#si al vector hi ha més d'un valor igual al nouNumero, retorna false
#false representa un error en el Sudoku:
if numQuadrant.count(nouNumero)>1:
print("Aquest número ja hi és al quadrant.")
return False
else:
return True
#finalFila comprova que la fila estigui complerta i retorna true només en aquest cas:
def finalFila(self,fila):
numerosFila = []
for nColumna in range(len(self.arrays)):
numerosFila.append(arrays[fila][nColumna])
#mirem si els valors de la llista nombresNecessaris hi son a numerosFila:
comprovacio = all(item in numerosFila for item in self.nombresNecessaris)
return comprovacio
#finalColumna comprova que la columna estigui complerta i retorna true només en aquest cas:
def finalColumna(self,columna):
numerosColumna = []
for nFila in range(len(self.arrays)):
numerosColumna.append(arrays[nFila][columna])
#mirem si els valors de la llista nombresNecessaris hi son a numerosColumna:
comprovacio = all(item in numerosColumna for item in self.nombresNecessaris)
return comprovacio
#finalQuadrant comprova que el quadrant estigui complert i retorna true només en aquest cas:
def finalQuadrant(self,fila,columna):
#aquest codi és reutilitzat de la funció comprovarQuadrant i està comentat allà:
numerosQuadrant = []
fila = (math.floor(fila / 3)*3)
columna = (math.floor(columna / 3)*3)
for num in range(fila, fila + 3):
numerosQuadrant.extend(arrays[num][columna:columna + 3])
#mirem si els valors de la llista nombresNecessaris hi son a numerosQuadrant:
comprovacio = all(item in numerosQuadrant for item in self.nombresNecessaris)
return comprovacio
def sudokuComplert(self):
completat = True
comptador=0
comptador1=0
while completat and comptador<9:
completat=self.finalFila(comptador)
if completat:
completat=self.finalColumna(comptador)
comptador+=1
while completat and comptador1<9:
completat=self.finalQuadrant(comptador,comptador1)
comptador1+=1
return completat
# creem el métode toString que retorna l'estat de l'objecte:
def __str__(self):
mostraString=""
contador=0
contador1=0
mostraString += "\n-------------------------------\n"
#fem un for anidat per recòrrer el vector de vectors:
for y in arrays:
for x in y:
if(contador%3==0):
mostraString+="|"
#guardem a mostraString el valor:
mostraString+=" "+ str(x)+ " "
contador += 1
mostraString += "|"
contador1+=1
#si el modul del contador1 entre 3 equival a 0:
if (contador1 % 3 == 0):
#fem un salt de línea quan sortim del for intern:
mostraString+="\n-------------------------------\n"
else:
mostraString += "\n"
#tornem a posar el contador a 1:
contador=0
#retornem el string que és el sudoku:
return(mostraString)
#declarem l'array que tractarem com a sudoku:
arrays = \
[[3, 1, 5, 6, 2, 9, 8, 4, 7],
[7, 0, 6, 1, 0, 8, 0, 0, 0],
[8, 3, 1, 4, 7, 9, 2, 6, 5],
[5, 0, 3, 0, 0, 5, 0, 7, 0],
[6, 8, 7, 0, 0, 0, 0, 0, 0],
[2, 0, 0, 7, 0, 0, 6, 0, 0],
[4, 7, 9, 5, 8, 0, 0, 2, 0],
[1, 0, 0, 4, 3, 0, 5, 0, 9],
[9, 0, 8, 9, 0, 0, 0, 0, 6]]
#fem un objecte passant-li 'arrays' com a paràmetre:
s1 = Sudoku(arrays)
#declarem el boolean sudokuComplert en valor false:
sudokuComplert=False
while sudokuComplert==False:
#mostrem el sudoku (#imprimim el vector de vectors amb format gràcies al __str__):
print(s1)
#declarem l'String coordenada:
coordenada = "0,0"
#demanem les coordenades a modificar:
coordenada=input("introdueïx coordenada ([fila],[columna]): ")
#demanem un valor per posar en les coordenades:
nouValor=int(input("introdueïx nou valor: "))
#dividim l'String 'coordenada' per la coma per treballar amb els valors
coo=coordenada.split(',')
#fem un cast a integer i guardem els valors:
x=int(coo[0])
y=int(coo[1])
#restem els valors perque 1 sigui la primera fila o columna, i no la segona:
x=x-1
y=y-1
#executem la funció 'actualitza()'
s1.actualitza(nouValor,x,y)
#si cap d'aquest mètodes retorna false, és que es repeteix el valor en fila, columna o quadrant:
filaValorRepetit=s1.comprovarFila(x,nouValor)
columnaValorRepetit=s1.comprovarColumna(y,nouValor)
quadrantValorRepetit=s1.comprovarQuadrant(x,y,nouValor)
#si cap d'aquests mètodes retorna false, és que no estan complerts la fila, la columna o el quadrant:
filaComplerta=s1.finalFila(x)
columnaComplerta=s1.finalColumna(y)
quadrantComplert=s1.finalQuadrant(x,y)
#si la funció sudokuComplert() ens retorna false, és que el sudoku no està complert:
sudokuComplert=s1.sudokuComplert()
|
1825ecd0df5fdfa00eb0e0c5322caef87081e4c5 | yijirong/movie-dataset-analysis | /model.py | 427 | 3.609375 | 4 | class StudentModel:
def __init__(self, name="", sex="", score=0.0, age=0, sid=0):
self.name = name
self.sex = sex
self.score = score
self.age = age
self.sid = sid
def __str__(self):
return f"{self.name} your account is {self.sid},age is {self.age},movie name is {self.sex},movie score is {self.score}"
def __eq__(self, other):
return self.sid == other.sid |
86afe70c6c5a94161b4a211ca835ffb0e402765a | willbrom/py_prog | /guess_a_number.py | 514 | 4.09375 | 4 | #!/bin/python3
#This is a guess the number game
from random import randint
rand_num = randint(1,20)
print('I am thinking of a number between 1 and 20')
for guess_taken in range(0, 7):
print('Take a guess')
guess = int(input())
if guess < rand_num:
print('Your guess is too low')
elif guess > rand_num:
print('Your guess is too high')
else:
break
if guess == rand_num:
print('Good job! you guessed my number in ' + str(guess_taken + 1) + ' guesses!')
else:
print('Better luck next time, scrub!')
|
df8537c34ccabcdf0404e8b0416d6711c59410ca | felipebregalda/gogitcl | /notas.py | 278 | 3.53125 | 4 | #-*- coding utf-8 -*-
from funcoes import notaFinal
print 'Calculo de notas do Aluno\n'
nome = raw_input ('Nome: ')
nota1 = float( raw_input('Nota 1: '))
nota2 = float( raw_input('Nota 2: '))
notaFinal = notaFinal(nota1, nota2)
print 'Nota final do aluno',nome,'eh',notaFinal |
5a9c5719e053d265dd173e766008bc33118b6dae | peterzhou84/datastructure | /samples/python/array.py | 1,542 | 4.4375 | 4 | #coding=utf-8
#!/usr/bin/python3
'''
展示在Python中,如何操作数组
'''
#################################################
### 一维数组 http://www.runoob.com/python3/python3-list.html
squares = [1, 4, 9, 16, 25, 36]
print("打印原数组:")
print(squares)
'''
Python的编号可以为正负
+---+---+---+---+---+---+
| 1 | 4 | 9 | 16| 25| 36|
+---+---+---+---+---+---+
0 1 2 3 4 5 从第一个开始编号为0
-6 -5 -4 -3 -2 -1 从最后一个开始,编号为-1
'''
## 找到特定下标的元素
print("打印下标为4的元素:")
print(squares[4]) # 从第一个开始数,指向25
print("打印下标为-2的元素:")
print(squares[-2]) # 从最后一个开始数,指向25
## 找到特定下标范围的元素
print("打印下标为2(包含)到4(不包含)之间的所有元素:")
print(squares[2:4])
print("打印下标从4开始(包含)到数组最后的所有元素:")
print(squares[4:])
print("打印第一个元素到第-2(不含)的元素:")
print(squares[:-2])
## 设置数组元素的值
print("下标为2的元素乘以10:")
squares[2] *= 10
print(squares)
## 删除数组里面的元素
print("删除下标为4的元素")
del squares[4]
print(squares)
#################################################
### 元组 Python 的元组与列表类似,不同之处在于元组的元素不能修改。
# 元组使用小括号,列表使用方括号。
tup1 = ('Google', 'Runoob', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d"; |
2630ddaf65b81180029e68506dce3a45e8c82c08 | jamesmold/learning | /aoc2.py | 528 | 3.53125 | 4 | from collections import Counter
fhand = open("aoc2.txt")
lines = [x.strip() for x in fhand] #removes the new lines from the input file aoc2.txt
def part1():
has2 = 0
has3 = 0
for line in lines:
c = Counter(line).values() #Counter counts like elements in a string (returns as dict key value pair, adding the .values just returns the value not the key)
if 2 in c:
has2 = has2 + 1
if 3 in c:
has3 = has3 + 1
else: continue
return has2 * has3
print(part1()) |
5e0f8b72f7946109f1bb70e8cca938c7a5d0da0e | DarioBernardo/hackerrank_exercises | /dinner_party.py | 1,521 | 3.78125 | 4 | # Find all possible combination of friends using recursion
# the total number of combination is given by binomial coefficient formula
# n choose k where n is the number of guest and k is the table size
# binomial coefficient = n!/(k!*(n-k)!)
from itertools import combinations
friends = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'L', 'M', 'N']
# friends = ['A', 'B', 'C', 'D']
table_size = 5
# print([tuple(elem) for elem in friends])
solution = [x for x in combinations(friends, table_size)]
print(solution)
def get_table_guest(friends_list, table_size, group=[], groups=[]):
if len(group) is table_size:
groups.append(tuple(group))
return
if len(group) + len(friends_list) == table_size:
group.extend(friends_list)
groups.append(tuple(group))
return
curr_friend = friends_list.pop(0)
group_without = group.copy()
group.append(curr_friend)
# take branch
get_table_guest(friends_list.copy(), table_size, group, groups)
# leave branch
get_table_guest(friends_list.copy(), table_size, group_without, groups)
return groups
prop_solution = get_table_guest(friends, table_size)
print(prop_solution)
for elem in solution:
if elem in prop_solution:
prop_solution.remove(elem)
else:
raise Exception(f"Element {elem} not present")
if len(prop_solution) > 0:
raise Exception(f"There are some extra elements in the proposed solution: {prop_solution}")
if len(prop_solution) == 0:
print("ALL GOOD!")
|
7a39583a260a600b2228795bcaa18dd97cb9acde | DarioBernardo/hackerrank_exercises | /recursion/word_break.py | 1,959 | 4.0625 | 4 | """
EASY
https://leetcode.com/explore/interview/card/facebook/55/dynamic-programming-3/3036/
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
"""
from functools import lru_cache
from typing import List, FrozenSet
def wordBreak(s: str, wordDict: List[str]) -> bool:
@lru_cache()
def wordBreakMemo(s: str, wordDict: FrozenSet[str]) -> bool:
if len(wordDict) == 0:
return False
if len(s) == 0:
return True
pointer = 1
is_valid = False
while pointer < len(s) + 1:
sub = s[0:pointer]
if sub in wordDict:
is_valid = wordBreakMemo(s[pointer:], wordDict)
if is_valid:
return True
pointer += 1
return is_valid
return wordBreakMemo(s, frozenset(wordDict))
din = [
("leetcode", ["leet", "code"]),
("applepenapple", ["apple", "pen"]),
("catsandog", ["cats", "dog", "sand", "and", "cat"]),
("ccbb", ["bc", "cb"]),
("a", ["b"])
]
dout = [
True,
True,
False,
False
]
for data_in, expected_result in zip(din, dout):
actual_result = wordBreak(data_in[0], data_in[1])
print(f"Expected: {expected_result} Actual: {actual_result}")
assert expected_result == actual_result
|
0a992d783e6c4208da21a3efbdccfd612437d30b | DarioBernardo/hackerrank_exercises | /stacks_and_queues/minimum_lenght_substring.py | 4,025 | 4.125 | 4 | """
Minimum Length Substrings
You are given two strings s and t. You can select any substring of string s and rearrange the characters of the selected substring. Determine the minimum length of the substring of s such that string t is a substring of the selected substring.
Signature
int minLengthSubstring(String s, String t)
Input
s and t are non-empty strings that contain less than 1,000,000 characters each
Output
Return the minimum length of the substring of s. If it is not possible, return -1
Example
s = "dcbefebce"
t = "fd"'
output = 5
Explanation:
Substring "dcbef" can be rearranged to "cfdeb", "cefdb", and so on. String t is a substring of "cfdeb". Thus, the minimum length required is 5.
"""
def compare_dicts(a, b) -> bool:
for k in b.keys():
if k not in a:
return False
else:
if b[k] > a[k]:
return False
return True
def min_length_substring(s, t):
# Write your code here
if len(s) == 0 or len(t) == 0:
return 0
control = s
test = t
if len(s) < len(t):
test = s
control = t
if len(test) == 1:
return 1 if test in control else 0
results = []
stack_index = []
stack = []
string_hash = {}
test_hash = {}
for c in test:
char_counter = test_hash.get(c, 0)
char_counter += 1
test_hash[c] = char_counter
for pos, c in enumerate(control):
if c in test_hash.keys():
stack.append(c)
stack_index.append(pos)
char_counter = string_hash.get(c, 0)
char_counter += 1
string_hash[c] = char_counter
if compare_dicts(string_hash, test_hash):
results.append(stack_index[-1] - stack_index[0] + 1)
removed_elem = stack.pop(0)
_ = stack_index.pop(0)
string_hash[removed_elem] -= 1
while string_hash[stack[0]] > 1:
removed_elem = stack.pop(0)
_ = stack_index.pop(0)
string_hash[removed_elem] -= 1
if string_hash[removed_elem] <= 0:
del string_hash[removed_elem]
if compare_dicts(string_hash, test_hash):
results.append(stack_index[-1] - stack_index[0] + 1)
return -1 if len(results) == 0 else min(results)
# These are the tests we use to determine if the solution is correct.
# You can add your own at the bottom, but they are otherwise not editable!
def printInteger(n):
print('[', n, ']', sep='', end='')
test_case_number = 1
def check(expected, output):
global test_case_number
result = False
if expected == output:
result = True
rightTick = '\u2713'
wrongTick = '\u2717'
if result:
print(rightTick, 'Test #', test_case_number, sep='')
else:
print(wrongTick, 'Test #', test_case_number, ': Expected ', sep='', end='')
printInteger(expected)
print(' Your output: ', end='')
printInteger(output)
print()
test_case_number += 1
if __name__ == "__main__":
s1 = "dcbefebce"
t1 = "fd"
expected_1 = 5
output_1 = min_length_substring(s1, t1)
check(expected_1, output_1)
s2 = "bfbeadbcbcbfeaaeefcddcccbbbfaaafdbebedddf"
t2 = "cbccfafebccdccebdd"
expected_2 = -1
output_2 = min_length_substring(s2, t2)
check(expected_2, output_2)
# Add your own test cases here
s3 = "abcdefghilmno"
t3 = "gme"
expected_3 = 7
output_3 = min_length_substring(s3, t3)
check(expected_3, output_3)
s2 = "ambhicdefgmnbo"
t2 = "gme"
expected_2 = 4
output_2 = min_length_substring(s2, t2)
check(expected_2, output_2)
s2 = "ambhicdefgmnboglkslkbtemg"
t2 = "gme"
expected_2 = 3
output_2 = min_length_substring(s2, t2)
check(expected_2, output_2)
s6 = "ambhicdefgmnboglkslkbtmegdff"
t6 = "gme"
expected_6 = 3
output_6 = min_length_substring(s6, t6)
check(expected_6, output_6)
|
2a4554a80c37176663dba8d9e8159fc3676c0e74 | DarioBernardo/hackerrank_exercises | /graphs/alien_dictionary.py | 2,872 | 4.03125 | 4 | """
ALIEN DICTIONARY (HARD)
https://leetcode.com/explore/interview/card/facebook/52/trees-and-graphs/3025/
Example of topological sort exercise.
There is a new alien language that uses the English alphabet. However, the order among letters are unknown to you.
You are given a list of strings words from the dictionary, where words are sorted lexicographically by the rules of this new language.
Derive the order of letters in this language, and return it. If the given input is invalid, return "". If there are multiple valid solutions, return any of them.
Example 1:
Input: words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
Example 2:
Input: words = ["z","x"]
Output: "zx"
Example 3:
Input: words = ["z","x","z"]
Output: ""
Explanation: The order is invalid, so return "".
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] consists of only lowercase English letters.
"""
from typing import List, Tuple
def get_association(a: str, b: str):
for ca, cb in zip(a, b):
if ca != cb:
return ca, cb
if len(a) > len(b):
return -1
return ""
def alien_order(words: List[str]) -> str:
if len(words) == 0:
return ""
if len(words) == 1:
return words[0]
if len(words[0][0]) == 0:
return ""
associations_map = dict()
indegree_count = dict()
for i in range(0, len(words)):
if i < len(words) - 1:
association = get_association(words[i], words[i + 1])
if association == -1:
return ""
if association != "":
children = associations_map.get(association[0], [])
children.append(association[1])
associations_map[association[0]] = children
counter = indegree_count.get(association[1], 0)
indegree_count[association[1]] = counter + 1
for c in set(words[i]):
counter = indegree_count.get(c, 0)
indegree_count[c] = counter
queue = []
seen = set()
for letter, counter in indegree_count.items():
if counter == 0:
queue.append(letter)
sol = ""
while len(queue) != 0:
node = queue.pop(0)
seen.add(node)
sol += node
children = associations_map.get(node, [])
for child in children:
indegree_count[child] -= 1
if indegree_count[child] == 0 and child not in seen:
queue.append(child)
if len(indegree_count) - len(seen) > 0:
return ""
return sol
words_in = [
["wrt", "wrf", "er", "ett", "rftt"],
["z", "x"],
["z", "x", "z"],
["z", "z"],
["zy", "zx"]
]
sols = [
"wertf",
"zx",
"",
"z",
"yzx"
]
for i, expected in zip(words_in, sols):
actual = alien_order(i)
print(actual)
assert actual == expected
|
486b6adf4f4fc17b23f16aafca1a3fdafe92465d | DarioBernardo/hackerrank_exercises | /new_year_chaos.py | 1,301 | 3.65625 | 4 | """
NEW YEAR CHAOS
https://www.hackerrank.com/challenges/new-year-chaos
"""
def shift(arr, src_index, dest_index):
if src_index == dest_index or abs(src_index - dest_index) > 2:
return
if src_index - dest_index == 1:
swap(arr, dest_index, src_index)
else:
swap(arr, dest_index, src_index)
swap(arr, dest_index, src_index+1)
def swap(arr, dest_index, src_index):
temp = arr[src_index]
arr[src_index] = arr[dest_index]
arr[dest_index] = temp
def minimumBribes(q):
tot_bribes = 0
state = list(range(1, len(q)+1))
for index, elem in enumerate(q):
bribe = 0
while elem != state[index+bribe] and bribe < 3:
bribe += 1
if bribe >= 3:
print("Too chaotic")
return
if bribe > 0:
shift(state, index, index+bribe)
tot_bribes += bribe
print(f"Bribes: {tot_bribes}")
return tot_bribes
q = [2, 1, 5, 3, 4]
bribes = minimumBribes(q)
assert bribes == 3
q = [1, 2, 5, 3, 7, 8, 6, 4]
"""
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 5, 4, 6, 7, 8]
[1, 2, 5, 3, 4, 6, 7, 8]
[1, 2, 5, 3, 4, 7, 6, 8]
[1, 2, 5, 3, 7, 4, 6, 8]
[1, 2, 5, 3, 7, 4, 8, 6]
[1, 2, 5, 3, 7, 8, 4, 6]
[1, 2, 5, 3, 7, 8, 6, 4]
"""
bribes = minimumBribes(q)
assert bribes == 7
|
3720bb40db37bf3006c90c72bce9419a953aded6 | DarioBernardo/hackerrank_exercises | /arrays/merge_intervals.py | 1,271 | 4.0625 | 4 | """
MEDIUM
https://leetcode.com/problems/merge-intervals/
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals,
and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
"""
from typing import List
def merge(intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) <= 1:
return intervals
intervals = sorted(intervals, key=lambda tup: tup[0])
start_interval = intervals[0][0]
end_interval = intervals[0][1]
sol = []
for i in range(1, len(intervals)):
if end_interval >= intervals[i][0]:
start_interval = min(intervals[i][0], start_interval)
end_interval = max(intervals[i][1], end_interval)
else:
sol.append([start_interval, end_interval])
start_interval = intervals[i][0]
end_interval = intervals[i][1]
sol.append([start_interval, end_interval])
return sol
|
b347b04bc5734a10812e42e9060e8d6323038692 | DarioBernardo/hackerrank_exercises | /search/insert_in_sorted_list.py | 1,090 | 3.84375 | 4 | """
Insert a new elem in a sorted list in O(log N)
"""
import random
from typing import List
def insert_elem(in_list: List, val: int):
if len(in_list) == 0:
in_list.append(elem)
return
start = 0
end = len(in_list)
while start < end:
middle = start + int((end - start) / 2)
if in_list[middle] > val:
end = middle
else:
start = middle + 1
in_list.insert(start, val)
INPUT_LIST_SIZE = 20
NUMBER_OF_TESTS = 10
for _ in range(0, NUMBER_OF_TESTS):
input_list = sorted(list([random.randint(-int(INPUT_LIST_SIZE/2), int(INPUT_LIST_SIZE/2)) for _ in range(0, INPUT_LIST_SIZE)]))
elem = random.randint(-int(INPUT_LIST_SIZE/2), int(INPUT_LIST_SIZE/2))
solution = input_list.copy()
solution.append(elem)
solution = sorted(solution)
insert_elem(input_list, elem)
print(input_list)
print(solution)
assert solution == input_list
input_list = [0, 0, 0, 0, 0]
insert_elem(input_list, 1)
print(input_list)
print([0, 0, 0, 0, 0, 1])
assert [0, 0, 0, 0, 0, 1] == input_list
|
bfecec5ea05dd2fd58ee9e5d88cf083126a5bd06 | DarioBernardo/hackerrank_exercises | /linked_lists/reorder_list.py | 2,478 | 4.0625 | 4 | """
https://leetcode.com/explore/interview/card/facebook/6/linked-list/3021/ (HARD)
You are given the head of a singly linked-list. The list can be represented as:
L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4]
Output: [1,4,2,3]
Example 2:
Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reorderList(head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return
if not head.next:
return
# STEP 1: find middle point
# STEP 2: reverse second part
# STEP 3: stitch them togheter
# STEP 1:
slow_pointer = head
fast_pointer = head
while fast_pointer.next and fast_pointer.next.next:
fast_pointer = fast_pointer.next.next
slow_pointer = slow_pointer.next
# STEP 2:
prev = None
current = slow_pointer.next # in current I will find the beginning of the reversed list
slow_pointer.next = None
next_elem = current.next
while next_elem:
current.next = prev
temp = next_elem.next
prev = current
current = next_elem
next_elem = temp
current.next = prev
# STEP 3:
pointer = head
while current:
temp_reverse = current.next
temp_forwad = pointer.next
pointer.next = current
current.next = temp_forwad
current = temp_reverse
pointer = temp_forwad
din = [
[1, 2, 3, 4],
[1, 2, 3, 4, 5]
]
dout = [
[1, 4, 2, 3],
[1, 5, 2, 4, 3]
]
for data_in, expected in zip(din, dout):
head = None
pointer = None
for val in data_in:
node = ListNode(val)
if pointer:
pointer.next = node
pointer = node
if not head:
head = node
reorderList(head)
pointer = head
counter = 0
while pointer:
print(pointer.val)
assert pointer.val == expected[counter], "value {} do not match expected {}".format(pointer.val, expected[counter])
counter += 1
pointer = pointer.next
assert counter == len(expected), "Different number of element returned!"
|
0ef227f6d8f07559a75faa3767d0da5d8fbcbb88 | DarioBernardo/hackerrank_exercises | /tree_and_graphs/tree_level_avg_bfs_and_dfsv2.py | 2,446 | 4 | 4 | """
Given a binary tree, get the average value at each level of the tree.
Explained here:
https://vimeo.com/357608978
pass fbprep
"""
from typing import List
class Node:
def __init__(self, val):
self.value = val
self.right = None
self.left = None
def get_bfs(nodes: List[Node], result: list):
if len(nodes) == 0:
return
current_level_values = []
next_level_children = []
for n in nodes:
current_level_values.append(n.value)
if n.left:
next_level_children.append(n.left)
if n.right:
next_level_children.append(n.right)
result.append(sum(current_level_values)/len(current_level_values))
get_bfs(next_level_children, result)
def get_dfs(n: Node, level_map: dict, current_level: int = 0):
this_level_map = level_map.get(current_level, [])
this_level_map.append(n.value)
level_map[current_level] = this_level_map
if n.left:
get_dfs(n.left, level_map, current_level+1)
if n.right:
get_dfs(n.right, level_map, current_level+1)
def get_level_average(head: Node) -> list:
if head is None:
return []
level_map = {}
get_dfs(head, level_map)
result = []
levels = sorted(level_map.keys())
for level in levels:
level_values = level_map[level]
result.append(sum(level_values)/len(level_values))
return result
def get_level_average_2(head: Node) -> list:
if head is None:
return []
result = []
get_bfs([head], result)
return result
th = Node(4)
th.left = Node(7)
th.right = Node(9)
th.right.right = Node(6)
th.left.left = Node(10)
th.left.right = Node(2)
th.left.right.right = Node(6)
th.left.right.right.left = Node(2)
expected = [4, 8, 6, 6, 2]
actual = get_level_average(th)
actual_bfs = get_level_average_2(th)
print("ACTUAL: \t{}".format(actual))
print("EXPECTED:\t{}".format(expected))
assert actual == expected
assert actual_bfs == expected
root_2 = Node(10)
root_2.left = Node(8)
root_2.right = Node(15)
root_2.left.left = Node(3)
root_2.left.left.right = Node(5)
root_2.left.left.right.right = Node(6)
root_2.right.left = Node(14)
root_2.right.right = Node(16)
expected = [10.0, 11.5, 11, 5, 6]
actual = get_level_average(root_2)
actual_bfs = get_level_average_2(root_2)
print("ACTUAL: \t{}".format(actual))
print("EXPECTED:\t{}".format(expected))
assert actual == expected
assert actual_bfs == expected
|
d4f7b9d7c21da7b017e930daf5fbf1fb729dfe7f | DarioBernardo/hackerrank_exercises | /graphs/journey_to_the_moon.py | 2,213 | 3.703125 | 4 | """
medium
https://www.hackerrank.com/challenges/journey-to-the-moon/problem
"""
class GraphMap:
def __init__(self):
self.graph_map = dict()
def add_link(self, a, b):
links = self.children_of(a)
links.append(b)
self.graph_map[a] = links
def add_bidirectional_link(self, a, b):
self.add_link(a, b)
self.add_link(b, a)
def children_of(self, a):
return self.graph_map.get(a, [])
def size_of_parent_graph(astronaut, gm, visited_astronauts):
queue = [astronaut]
graph_size = 0
while len(queue) != 0:
a = queue.pop(0)
if a not in visited_astronauts:
visited_astronauts.add(a)
graph_size += 1
children = gm.children_of(a)
queue.extend(children)
return graph_size
# Complete the journeyToMoon function below.
def journeyToMoon(n, astronaut):
if n <= 1:
return 0
graph_map = GraphMap()
for pair in astronaut:
graph_map.add_bidirectional_link(pair[0], pair[1])
# find unique separate graphs
country_sizes = []
visited_astronauts = set()
for a in range(0, n):
if a not in visited_astronauts:
country_size = size_of_parent_graph(a, graph_map, visited_astronauts)
country_sizes.append(country_size)
total = 0
my_result = 0
for size in country_sizes:
my_result += total * size
total += size
return my_result
data_in = [
(5, [(0, 1), (2, 3), (0, 4)]),
(4, [(0, 2)]),
(10, [(0, 2), (1, 8), (1, 4), (2, 8), (2, 6), (3, 5), (6, 9)])
]
expected_outputs = [6, 5, 23]
test_case_number = 1
for (tot_number_of_astronauts, astronauts_pairs), expected in zip(data_in, expected_outputs):
actual = journeyToMoon(tot_number_of_astronauts, astronauts_pairs)
result = actual == expected
rightTick = '\u2713'
wrongTick = '\u2717'
if result:
print(rightTick, 'Test #', test_case_number, sep='')
else:
print(wrongTick, 'Test #', test_case_number, ': Expected ', sep='', end='')
print(expected, end='')
print(' Your output: ', end='')
print(actual)
print()
test_case_number += 1
|
79fe834ad9528d7d1d6bdfcb8c8e37dfe8e90fc9 | DarioBernardo/hackerrank_exercises | /graphs/number_of_islands.py | 2,474 | 3.953125 | 4 | """
Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
"""
from typing import List
def hash(i, j) -> str:
return "{}-{}".format(i, j)
def get_children(x: int, y: int, x_max: int, y_max: int) -> list:
children = []
if x > 0:
children.append((x - 1, y))
if x < x_max:
children.append((x + 1, y))
if y > 0:
children.append((x, y - 1))
if y < y_max:
children.append((x, y + 1))
return children
def bfs(queue, visited_nodes, grid):
x = len(grid)-1
y = len(grid[0])-1
while len(queue) > 0:
elem = queue.pop(0)
if hash(elem[0], elem[1]) not in visited_nodes:
visited_nodes.add(hash(elem[0], elem[1]))
children = get_children(elem[0], elem[1], x, y)
for child in children:
if grid[child[0]][child[1]] == "1":
queue.append(child)
def num_islands(grid: List[List[str]]) -> int:
if len(grid) == 0:
return 0
if len(grid[0]) == 0:
return 0
if len(grid) == 1 and len(grid[0]) == 1:
return 1 if grid[0][0] == "1" else "0"
x = len(grid)
y = len(grid[0])
visited_nodes = set()
island_counter = 0
for xi in range(0, x):
for yi in range(0, y):
starting_point = grid[xi][yi]
if hash(xi, yi) not in visited_nodes and starting_point == "1":
island_counter += 1
queue = [(xi, yi)]
bfs(queue, visited_nodes, grid)
return island_counter
din = [
[["1", "1", "1", "1", "0"],
["1", "1", "0", "1", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "0", "0", "0"]],
[["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"]]
]
expected_results = [
1,
3
]
for i, expected in zip(din, expected_results):
actual = num_islands(i)
print(actual)
print(expected)
assert actual == expected
|
d1d844be30625c6e2038e0596b19c05cf9a489fa | DarioBernardo/hackerrank_exercises | /recursion/num_decodings.py | 2,241 | 4.28125 | 4 | """
HARD
https://leetcode.com/problems/decode-ways/submissions/
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:
Input: s = "12"
Output: 2
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: s = "226"
Output: 3
Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Example 3:
Input: s = "0"
Output: 0
Explanation: There is no character that is mapped to a number starting with 0.
The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of which start with 0.
Hence, there are no valid ways to decode this since all digits need to be mapped.
Example 4:
Input: s = "06"
Output: 0
Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
"""
from functools import lru_cache
def num_decodings(s: str):
@lru_cache(maxsize=None) # This automatically implement memoisation
def recursive(s: str, index=0):
if index == len(s):
return 1
# If the string starts with a zero, it can't be decoded
if s[index] == '0':
return 0
if index == len(s) - 1:
return 1
answer = recursive(s, index + 1)
if int(s[index: index + 2]) <= 26:
answer += recursive(s, index + 2)
return answer
return recursive(s, 0)
din = [
"234",
"2101",
"1201234"
]
dout = [
2,
1,
3
]
for data_in, expected_result in zip(din, dout):
actual_result = num_decodings(data_in)
print(f"Expected: {expected_result} Actual: {actual_result}")
assert expected_result == actual_result
|
668c5cda04ba409fcad5811fbbe85594be6b3c57 | elenaborisova/Softuniada-Hackathon | /softuniada_2021/06_the_game.py | 573 | 4.0625 | 4 | def get_minimum_operations(first, second):
count = 0
i = len(first) - 1
j = i
while i >= 0:
while i >= 0 and not first[i] == second[j]:
i -= 1
count += 1
i -= 1
j -= 1
return count
shuffled_name = input()
name = input()
if not len(shuffled_name) == len(name):
print('The name cannot be transformed!')
else:
min_operations = get_minimum_operations(shuffled_name, name)
print(f'The minimum operations required to convert "{shuffled_name}" '
f'to "{name}" are {min_operations}')
|
a58d108cc4b7729d8345250fb6b3fbc7e067b38b | srushti-maladkar/python_methods | /lists.py | 342 | 3.71875 | 4 | # import __hello__
li = [1, 2, 3, 4, 5, 6,"S"]
li.append(7) #takes 1 value to append
print(li)
li.append((8, 9, 10))
print(li)
li.clear()
print(li)
li = [1, 2, 3, 4, 5, 6]
li2 = li.copy()
li.append(6)
print(li, li2)
print(li.count(6))
print(li.index(4))
li.insert(2, 22)
print(li)
li.pop(1)
print(li)
li.remove(22)
print(li)
|
5d792080e230b43aa25835367606510d0bb63af7 | feynmanliang/Monte-Carlo-Pi | /MonteCarloPi.py | 1,197 | 4.21875 | 4 | # MonteCarloPi.py
# November 15, 2011
# By: Feynman Liang <feynman.liang@gmail.com>
from random import random
def main():
printIntro()
n = getInput()
pi = simulate(n)
printResults(pi, n)
def printIntro():
print "This program will use Monte Carlo techniques to generate an"
print "experimental value for Pi. A circle of radius 1 will be"
print "inscribed in a square with side length 2. Random points"
print "will be selected. Since Pi is the constant of proportionality"
print "between a square and its inscribed circle, Pi should be"
print "equal to 2*2*(points inside circle/points total)"
def getInput():
n = input("Enter number of trials: ")
return n
def simulate(n):
hit = 0
for i in range(n):
result = simulateOne()
if result == 1:
hit = hit + 1
pi = 4 * float(hit) / n
return pi
def simulateOne():
x = genCoord()
y = genCoord()
distance = x*x + y*y
if distance <= 1:
return 1
else:
return 0
def genCoord():
coord = 2*random()-1
return coord
def printResults(pi, n):
print "After", n, "simulations, pi was calculated to be: ", pi
if __name__ == "__main__": main()
|
5251c5a37c2fbd8d4298810bf4b1ecb818fcda07 | jambompeople/jambompeople.github.io | /pythonclass.py | 238 | 3.859375 | 4 | class people:
def __init__(self, name, age):
self.name = name
self.age = age
def print(self):
print(self.name,self.age)
Jackson = people("Jackson", 13)
Jackson.name = "JD"
Jackson.age = 12
Jackson.print()
|
119122c529770f37325bd9e50a3c7e5a9bfa4004 | saridha11/python | /count sapce beg.py | 112 | 3.71875 | 4 | string =input()
count = 0
for a in string:
if (a.isspace()) == True:
count+=1
print(count)
|
a7a45dbf67baf4b430ff38fbb50854ab8f01fa75 | saridha11/python | /interval.positive.py | 123 | 3.671875 | 4 | def main():
a=7
b=9
for num in range(a,b+1):
if num%2==0:
print(num,end=" ")
main()
|
c38ad0e4f85157fae49fbc5e86efde52e8542dbe | saridha11/python | /anagrampro.py | 160 | 3.90625 | 4 | def check(str1,str2):
if(sorted(str1)==sorted(str2)):
print("yes")
else:
print("no")
str1=input()
str2=input()
check(str1,str2)
|
fb2117ab2600331a2f94a09c5b3c3412bcdb0cb3 | saridha11/python | /swap ch.py | 130 | 3.671875 | 4 | def swap():
s = 'abcd'
t = list(s)
t[::2], t[1::2] = t[1::2], t[::2]
x=''.join(t)
print("badc")
swap()
|
b52bb5f53ee3842e205131242bb3ef13df5fc8d6 | shuklaham/spojpractice | /ALICESIE.py | 155 | 3.671875 | 4 |
def main():
tc = int(raw_input())
for i in range(tc):
num = int(raw_input())
if num%2 ==0:
print num//2
else:
print (num+1)//2
main()
|
5db532b280a6b04d302432c29e7d83f76c75e485 | shuklaham/spojpractice | /samer08f.py | 271 | 3.5625 | 4 | #spoj solutions
known = {1:1}
def nsquares(n):
if n in known:
return known[n]
else:
c = n**2 + nsquares(n-1)
known[n] = c
return known[n]
num = int(raw_input())
while num != 0:
print nsquares(num)
num = int(raw_input())
|
dcb748b79f6f897f88430352c0a53b873592435b | ztwu/python-demo | /classdemo.py | 261 | 3.578125 | 4 | class ztwu:
p = 0
def __init__(self,p1):
ztwu.p = p1
return
def m1(self):
print("m1",ztwu.p)
return
def m2(self, p1, p2):
print(p1+p2)
return
def m3(self):
print("m3")
return |
876d3e79b2c05a6e0495a27b24268d966784018d | Drishti-Jain/ai_exp | /exp1 toy problem.py | 318 | 3.5 | 4 | x=int(input("No. of bananas at the beginning: "))
y=int(input("Distance to be covered: "))
z=int(input("Max capacity of camel: "))
lost=0
start=x
for i in range(y):
while start>0:
start=start-z
if start==1:
lost=lost-1
lost=lost+2
lost=lost-1
start=x-lost
if start==0:
break
print(start)
|
83c601b56a12f48a2ad1c73646eab2f9a9c71a03 | c2lyh/leetcode | /longest_common_prefix.py | 843 | 4.0625 | 4 | '''
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
'''
class Solution:
def longestCommonPrefix(self, strs) -> str:
if strs == []:
return ''
min_str = min([len(i) for i in strs])
prefix = ''
for index in range(min_str):
if len(set([j[index] for j in strs])) == 1:
prefix += strs[0][index]
else:
break
print(prefix)
return prefix
if __name__ == '__main__':
b = ["flower", "flow", "flight"]
a = Solution()
a.longestCommonPrefix(b)
|
cbfd4dde0f5203f05c73fc790b93d7c4a10edcd6 | jsbarbosa/MonitoriaMetodosComputacionales | /Ejercicios/derivadas.py | 2,668 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 17 19:43:58 2016
@author: Juan
"""
# imports required modules
import matplotlib.pyplot as plt
import numpy as np
# sets the functions and their derivatives
functions = [np.cos, np.exp] # example functions
derivatives = [np.sin, np.exp] # exact derivatives, minus sign in sine will later be introduced
functions_labels = ["$\cos x$", "$e^x$"] # LaTex representation of the functions
# sets the positions to be evaluated, differents widths and method used
positions = [0.1, 10, 100]
widths = [10**(-i) for i in range(1, 12)]
methods = ["Forward", "Central"]
def differentiation(method, function, position, width):
"""
Method that calculates a derivative using central or forward differences formula.
"""
def central(f, t, h):
return (f(t+h/2.) - f(t-h/2.))/h
def forward(f, t, h):
return (f(t+h)-f(t))/h
if method == "Forward":
return forward(function, position, width)
elif method == "Central":
return central(function, position, width)
fig = plt.figure(figsize=(10, 5)) # creates figure
ax = fig.add_axes([0.1, 0.1, 0.55, 0.8]) # makes up enough space for legend
for method in methods:
for (function, derivative, f_label) in zip(functions, derivatives, functions_labels): # usefull to interate over various elements of different lists, arrays, tuples, etc
for position in positions:
log_error = [] # sets up a buffer to store values
for width in widths:
result = differentiation(method, function, position, width) # calculates derivative
exact = derivative(position)
if f_label == "$\cos x$": # includes minus sign of sine derivative
exact *= -1
error = abs((result-exact)/exact)
error = np.log10(error)
log_error.append(error) # stores the value
text = method + " " + f_label + r", $x=" + str(position) + r"$" # sets the text to be shown at the legend
# plots different lines depending on the method used
if method == "Forward":
style = "-"
else:
style = "--"
ax.plot(np.log10(widths), log_error, style, label = text) # makes the plot
# additional plot data
ax.legend(loc='upper left', bbox_to_anchor=(1.02, 1))
ax.set_xlabel("$\log_{10}h$")
ax.set_ylabel("$\log_{10}\epsilon$")
plt.grid() # includes a grid
plt.show() # shows the plot
|
adf1a8f9da44ef3590068589a9e68d5413e354c9 | karthikBalasubramanian/MapReduceDesignPatterns | /code/mapper_inverted_index.py | 1,359 | 4.03125 | 4 | #!/usr/bin/python
# in Lesson 3. The dataset is more complicated and closer to what you might
# see in the real world. It was generated by exporting data from a SQL database.
#
# The data in at least one of the fields (the body field) can include newline
# characters, and all the fields are enclosed in double quotes. Therefore, we
# will need to process the data file in a way other than using split(","). To do this,
# we have provided sample code for using the csv module of Python. Each 'line'
# will be a list that contains each field in sequential order.
#
# In this exercise, we are interested in the field 'body' (which is the 5th field,
# line[4]). The objective is to count the number of forum nodes where 'body' either
# contains none of the three punctuation marks: period ('.'), exclamation point ('!'),
# question mark ('?'), or else 'body' contains exactly one such punctuation mark as the
# last character. There is no need to parse the HTML inside 'body'. Also, do not pay
# special attention to newline characters.
import string
import re
import csv
reader = csv.reader(sys.stdin, delimiter='\t')
for line in reader:
words = re.findall(r"[\w']+", line[4])
words = map(lambda x: x.lower(), words)
# if "fantastically" in words:
# writer.writerow(line)
for word in words:
print word, '\t', line[0]
|
9e7d64fbc8fd69a5d56e3f65a057a2a3ce08da27 | revanth465/Algorithms | /Searching Algorithms.py | 1,403 | 4.21875 | 4 | # Linear Search | Time Complexity : O(n)
import random
def linearSearch(numbers, find):
for i in numbers:
if(i==find):
return "Found"
return "Not Found"
numbers = [1,3,5,23,5,23,34,5,63]
find = 23
print(linearSearch(numbers,find))
# Insertion Sort | Time Complexity : O(N^2)
def insertionSort(numbers):
i = 2
while(i <= len(numbers)):
j = i-1
while( j > 0 ):
if(numbers[j] < numbers[j-1]):
temp = numbers[j-1]
numbers[j-1] = numbers[j]
numbers[j] = temp
j -= 1
else:
break
i += 1
return numbers
# Binary Search | Time Complexity : O(logN) | With Insertion Sort : O(N^2)
def binarySearch():
# Let's build a list of random numbers and a random value to find in the list.
numbers = [random.randint(1,21) for i in range(10)]
find = random.randint(1,21)
numbers = insertionSort(numbers)
low = 0
high = len(numbers) -1
while(low <= high):
middle = (low + high) /2
if(numbers[middle] == find):
return "Number Found"
elif(find < numbers[middle]):
high = middle - 1
else:
low = middle + 1
return "Number Not Found"
print(binarySearch())
|
18d8ac2957545f1c72ddb30ce917fa52be6f3b81 | OlegZhdanoff/python_basic_07_04_20 | /lesson_1-1.py | 553 | 3.9375 | 4 | var_str = 'hello'
var_int = 5
var_float = 3.2
print('String = ', var_str, '\nInteger = ', var_int, '\nFloat = ', var_float)
random_str = input('Введите произвольную строку\n')
random_int = input('Введите произвольное целое число\n')
random_float = input('Введите произвольное дробное число\n')
print('Ваша строка = ', random_str, '\nВаше целое число = ', int(random_int), '\nВаше дробное число = ',
float(random_float))
|
b6125617c91172dc3fb3b4c784e30d03d472eaeb | OlegZhdanoff/python_basic_07_04_20 | /lesson_7/lesson_7_3.py | 1,963 | 3.515625 | 4 | """3. Реализовать программу работы с органическими клетками. Необходимо создать класс Клетка. В его конструкторе
инициализировать параметр, соответствующий количеству клеток (целое число). В классе должны быть реализованы методы
перегрузки арифметических операторов: сложение (add()), вычитание (sub()), умножение (mul()), деление (truediv(
)).Данные методы должны применяться только к клеткам и выполнять увеличение, уменьшение, умножение и обычное (не
целочисленное) деление клеток, соответственно. В методе деления должно осуществляться округление значения до целого
числа. """
class Cell:
def __init__(self, num: int):
self.qty = num
def __add__(self, other):
return Cell(self.qty + other.qty)
def __sub__(self, other):
tmp = self.qty - other.qty
if tmp > 0:
return Cell(tmp)
else:
print('Клеток не может стать меньше нуля')
return Cell(0)
def __mul__(self, other):
return Cell(self.qty * other.qty)
def __truediv__(self, other):
return Cell(round(self.qty / other.qty))
def make_order(self, num):
tmp_str = ''
for i in range(self.qty // num):
tmp_str += '*' * num
if i < (self.qty // num - 1):
tmp_str += '\n'
if self.qty % num:
tmp_str += '\n' + ('*' * (self.qty % num))
return tmp_str
c1 = Cell(8)
c2 = Cell(3)
c3 = c1 / c2
print(c1.make_order(3))
print(c3.qty)
|
e9c965347e640a3dc9c568f854d7840faa5ff31a | OlegZhdanoff/python_basic_07_04_20 | /lesson_2_2.py | 809 | 4.21875 | 4 | """
2. Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами
0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка
элементов необходимо использовать функцию input().
"""
my_list = []
el = 1
i = 0
while el:
el = input('Введите элемент списка\n')
if el:
my_list.append(el)
print('Ваш список: ', my_list)
while i < len(my_list)-1:
my_list[i], my_list[i+1] = my_list[i+1], my_list[i]
i += 2
print('Результат: ', my_list)
|
a1e6886e32335718cb3de5274dc0380f28c01c0b | OlegZhdanoff/python_basic_07_04_20 | /lesson_1_3.py | 198 | 3.671875 | 4 | n = int(input('Введите число n\n'))
nn = int(str(n) + str(n))
nnn = int(str(n) + str(n) + str(n))
result = n + nn + nnn
print('Сумма чисел', n, nn, nnn, 'равна', result)
|
d4488bb782387cd7a639961df403754416a1022f | MigrantJ/sea-c34-python | /students/MaryDickson/session04/exceptions.py | 709 | 3.984375 | 4 | # questions about the exceptions section in slides 4
list = [0, 1, 4, 8, 100, 1001]
def printitem(list, num):
"""
Can I throw a warning message if number not in range?
"""
try:
return list[num]
except:
return(u"oops not long enough")
finally:
list.append(34)
print list
print printitem(list, 2)
print printitem(list, 10)
print list
def make_name_error(name):
'''
say hello given a name (string)
'''
try:
print "Hello %s" % name
except NameError:
print "Oops, try that again with a string this time"
finally:
return "program finished"
print make_name_error(Mary) # name error
print make_name_error("Mary")
|
1fe9ccebdbd43d3542d2b84d40aff034a96eb035 | danevd-TCD/leetcode | /Medium/2-Add Two Numbers.py | 2,276 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
list1 = [] #array for linked list 1
list2 = [] #array for linled list 2
current1 = l1
current2 = l2
print(current1)
#print(current.next)
#current = current.next
#print(current.val)
#list 1
while current1.next != None:
#print("Current val: " + str(current1.val))
list1.append(current1.val)
current1 = current1.next
list1.append(current1.val)
#list 2
while current2.next != None:
#print("Current val: " + str(current2.val))
list2.append(current2.val)
current2 = current2.next
list2.append(current2.val)
#reverse list 1:
end1 = len(list1) -1
str1 = ""
for i in range(end1,-1,-1):
str1 += str(list1[i])
#reverse list 2:
end2 = len(list2) -1
str2 = ""
for j in range(end2,-1,-1):
str2 += str(list2[j])
#sum and convert sum to string
outputSum = int(str1) + int(str2)
outputString = str(outputSum)
#reverse the outputString
endStringLen = len(outputString) - 1
reversedOutput = ""
for k in range(endStringLen, -1, -1):
reversedOutput += str(outputString[k])
print(reversedOutput)
#ListNode{val: 2, next: ListNode{val: 4, next: ListNode{val: 3, next: None}}}
current = ListNode()
for i in range(len(reversedOutput)):
current = current.next
current.val = reversedOutput[i] #this works
#print(current.val) #as evidenced by this: 7, 0, 8
#issue is somewhere here
current.next = ListNode()
print(current)
#create list
|
c31b9941a741feb5f72068044ec410b1ff11532e | KevinFrankhouser/PythonProjects | /Encapsulation.py | 509 | 3.734375 | 4 | class Car:
def __init__(self, speed, color):
self.__speed = speed
self._color = color
def set_speed(self, value):
self.__speed = value
def get_speed(self):
return self.__speed
def set_color(self, value):
self._color = value
def get_color(self):
return self._color
ford = Car(200, 'red')
honda = Car(250, 'blue')
audi = Car(300, 'black')
ford.set_speed(300)
print(ford.get_speed())
print(ford.get_color())
|
ed2837d7ad12ce569757025fbb8e849d5d9914bd | YoonKiBum/programmers | /Level1/68644.py | 302 | 3.6875 | 4 | from itertools import combinations
def solution(numbers):
answer = []
for combination in combinations(numbers, 2):
x = int(combination[0])
y = int(combination[1])
answer.append(x+y)
answer = set(answer)
answer = list(answer)
answer.sort()
return answer
|
6265b2b09f6ce1fa39701aa34d95723dd69c310f | abhnvkmr/hackerRank | /algorithms/anagram.py | 682 | 3.640625 | 4 | # HackerRank - Algorithms - Strings
# Anagrams
def shifts_required(input_str):
shifts = 0
if len(input_str) % 2:
return -1
a, b = input_str[: len(input_str) // 2], input_str[len(input_str) // 2 :]
dict = {}
dicta = {}
for i in b:
if i in dict.keys():
dict[i] += 1
else:
dict[i] = 1
dicta[i] = 0
for i in a:
if i in dicta.keys():
dicta[i] += 1
else:
dicta[i] = 1
for i in dict.keys():
if dict[i] > dicta[i]:
shifts += dict[i] - dicta[i]
return shifts
t = int(input())
for _ in range(t):
print(shifts_required(input()))
|
c7bb7446021d6d43b02e561dd4e663248e76f79a | abhinavchinna/complex--number-calculator | /code.py | 1,802 | 3.5 | 4 | # --------------
import pandas as pd
import numpy as np
import math
#Code starts here
class complex_numbers:
def __init__(self,a,b):
self.real=a
self.imag=b
def __repr__(self):
if self.real == 0.0 and self.imag == 0.0:
return "0.00"
if self.real == 0:
return "%.2fi" % self.imag
if self.imag == 0:
return "%.2f" % self.real
return "%.2f %s %.2fi" % (self.real, "+" if self.imag >= 0 else "-", abs(self.imag))
def __add__(self,other):
ans=complex_numbers((self.real+other.real),(self.imag+other.imag))
return ans
def __sub__(self,other):
ans=complex_numbers((self.real-other.real),(self.imag-other.imag))
return ans
def __mul__(self,other):
ans=complex_numbers((self.real*other.real-self.imag*other.imag),(self.imag*other.real+self.real*other.imag))
return ans
def __truediv__(self,other):
a1=self.real
b1=self.imag
a2=other.real
b2=other.imag
a=(a1*a2+b1*b2)/(a2**2 + b2**2)
b=(b1*a2-a1*b2)/(a2**2 + b2**2)
return complex_numbers(a,b)
def absolute(self):
ans=math.sqrt(self.real**2 + self.imag**2)
return ans
def argument(self):
ans=math.degrees(math.atan2(self.imag,self.real))
return ans
def conjugate(self):
if self.imag<0:
return complex_numbers(self.real,abs(self.imag))
return complex_numbers(self.real,-(self.imag))
comp_1=complex_numbers(3,5)
comp_2=complex_numbers(4,4)
comp_sum=comp_1+comp_2
comp_diff=comp_1-comp_2
comp_prod=comp_1*comp_2
comp_quot=comp_1/comp_2
comp_abs=comp_1.absolute()
comp_conj=comp_1.conjugate()
comp_arg=comp_1.argument()
|
6c82627929fa81cdd0998309ec049b8ef4d7bc86 | Helen-Sk-2020/JtBr_Arithmetic_Exam_Application | /Arithmetic Exam Application/task/arithmetic.py | 2,032 | 4.125 | 4 | import random
import math
def check_input():
while True:
print('''Which level do you want? Enter a number:
1 - simple operations with numbers 2-9
2 - integral squares of 11-29''')
x = int(input())
if x == 1 or x == 2:
return x
break
else:
print('Incorrect format.')
def check_answer(answer):
while True:
x = input()
if x.strip('-').isdigit():
if int(x) == answer:
print('Right!')
return 'Right!'
else:
print('Wrong!')
break
else:
print('Incorrect format.')
def simple_operations():
total = 0
a = random.randint(2, 9)
b = random.randint(2, 9)
operator = random.choice('+-*')
print(f"{a} {operator} {b}")
if operator == "+":
total = int(a) + int(b)
elif operator == "-":
total = int(a) - int(b)
elif operator == "*":
total = int(a) * int(b)
return total
def integral_squares():
num = random.randint(11, 29)
print(num)
square = math.pow(num, 2)
return square
def save_result(level, n):
print("What is your name?")
name = input()
if level == 1:
level_description = 'simple operations with numbers 2-9'
elif level == 2:
level_description = 'integral squares of 11-29'
results = open('results.txt', 'a', encoding='utf-8')
results.write(f'{name}: {n}/5 in level {level} ({level_description})')
results.close()
print('The results are saved in "results.txt".')
level = check_input()
counter = n = 0
while counter < 5:
if level == 1:
result = simple_operations()
elif level == 2:
result = integral_squares()
if check_answer(result) == 'Right!':
n += 1
counter += 1
print(f"Your mark is {n}/5. Would you like to save the result?")
user_answer = str(input())
if user_answer.lower() == 'yes' or user_answer == 'y':
save_result(level, n)
|
c123ff4f0b25cab5630f2b7fb6cb3243cd9abbe0 | Helen-Sk-2020/JtBr_Arithmetic_Exam_Application | /Topics/Writing files/Theory/main.py | 225 | 3.765625 | 4 | names = ['Kate', 'Alexander', 'Oscar', 'Mary']
name_file = open('names.txt', 'w', encoding='utf-8')
# write the names on separate lines
for name in names:
name_file.write(name + '\n')
name_file.close()
print(name_file) |
f35a379b82ba3181da4dbfeda3df222ae24d1370 | zenefits-brody/liaoxuefeng-python | /lambda-function.py | 220 | 3.921875 | 4 | """
https://www.liaoxuefeng.com/wiki/1016959663602400/1017451447842528
请用匿名函数改造下面的代码
"""
def is_odd(n):
return n % 2 == 1
L = list(filter(lambda x: x % 2 == 1, range(1, 20)))
print(L)
|
fc09097d3be62c80b2072cba63db8e4fbb5650d3 | Qasim-Habib/Rush-Hour | /rush_hour.py | 27,924 | 3.828125 | 4 | import sys
from queue import PriorityQueue
import copy
import time
def list_to_string(arr): #convert list to string
str_node=''
for i in range(0, Puzzle.size_table):
for j in range(0, Puzzle.size_table):
str_node += arr[i][j]
return str_node
def print_array(ar): #print the array in the form of matrix
print('\n'.join([''.join(['{:5}'.format(item) for item in row])
for row in ar]))
class Node:
# constructor construct the node
def __init__(self,state_of_puzzle,parent,depth,array_puzle,herstic_val,move):
self.state_of_puzzle=state_of_puzzle #dictionary that save to every car thw location of the car in the array(puzle)and the type of the car and the type of the move
self.parent=parent #save pionter to the parent
self.depth=depth # save the depth
self.array_puzle=array_puzle #save the array
self.herstic_val=herstic_val
self.move=move #save the last move that by this move we arrive to this node
def __lt__(self, other): #the priorty quiue use this function to compare between the nodes that found in the quiue
"""
:param other: compare
:return: 0
"""
return 0
def goal_state(self): #if the red car found in the end of the third row so the red car can exit and we arrive to the solution
return self.array_puzle[2][5]=='X'
def score(self,herstic_id): #compute the f value of the node in according to the algortim we use it to find the solution
if herstic_id=='iterative_deepning' or herstic_id=='DFS':
return -self.depth
elif herstic_id=='BFS':
return self.depth
elif herstic_id==9:
return self.herstic_val
elif herstic_id==3:
return self.herstic_val-self.depth
return self.depth+self.herstic_val
#function that take the car that we want to move it and take the direction and the amount of move
def create_new_node(self, cur_car, sum, direction,herstic_id):
new_array_board = copy.deepcopy(self.array_puzle) #create a new array to the new node
move=[]
move.append(self.array_puzle[cur_car.index[0]][cur_car.index[1]])
move.append(direction)
move.append(str(sum)) #save the last move
new_dict_car = dict(self.state_of_puzzle) #create new dictionary
index = cur_car.index
new_location_car = self.array_puzle[index[0]][index[1]]
if cur_car.type_of_move==0: #according to the direction we change the array and change the location of the car
if direction=='L':
for i in range(0,cur_car.type_of_car+2):
new_array_board[index[0]][index[1]-sum+i]= new_array_board[index[0]][index[1]+i]
new_array_board[index[0]][index[1] + i]='.'
index=(index[0],index[1]-sum)
elif direction=='R':
for i in range(cur_car.type_of_car+1,-1,-1):
new_array_board[index[0]][index[1]+sum+i]= new_array_board[index[0]][index[1]+i]
new_array_board[index[0]][index[1] + i]='.'
index = (index[0], index[1] + sum)
else:
if direction=='U':
for i in range(0,cur_car.type_of_car+2):
new_array_board[index[0]-sum+i][index[1]]= new_array_board[index[0]+i][index[1]]
new_array_board[index[0]+i][index[1]]='.'
index=(index[0]-sum,index[1])
else:
for i in range(cur_car.type_of_car+1,-1,-1):
new_array_board[index[0]+sum+i][index[1]]= new_array_board[index[0]+i][index[1]]
new_array_board[index[0]+i][index[1]]='.'
index=(index[0]+sum,index[1])
str_newarray=list_to_string(new_array_board)
if herstic_id=='iterative_deepning':
if str_newarray not in Iterative_deepning.visited:
depth = self.depth + 1
car = Car(index, cur_car.type_of_car, cur_car.type_of_move)
new_dict_car[new_location_car] = car
new_parent = self
new_node = Node(new_dict_car, new_parent, depth, new_array_board, None, move)
new_node.herstic_val=0
Iterative_deepning.waiting_nodes.put((new_node.score('iterative_deepning'), new_node))
else:
#if we visit the new node in the past so No need to go through it again
if str_newarray not in Puzzle.visited:
depth = self.depth + 1
#Puzzle.number_of_nodes += 1
car = Car(index, cur_car.type_of_car, cur_car.type_of_move)
new_dict_car[new_location_car] = car
new_parent = self
new_node = Node(new_dict_car, new_parent, depth, new_array_board, None, move)
if herstic_id==4:
val_herstic = new_node.calc_herustic_valtemp()
else:
val_herstic = new_node.calc_herustic_val(herstic_id)
new_node.herstic_val = val_herstic
Puzzle.add_to_waitlist(new_node,herstic_id)
def how_to_move(self,cars_can_move): #function that take the cars the can move and compute to every car can move the direction of the move
mov_car = {}
for key in cars_can_move:
curent_car = self.state_of_puzzle[key]
location = curent_car.index
count = curent_car.type_of_car + 2
moves=(0,0)
if curent_car.type_of_move == 0: #if the type of the move is horizontal
if location[1] - 1 >= 0 and self.array_puzle[location[0]][location[1] - 1] == '.':
moves=(1,moves[1]) #the car can move left L1
if location[1] + count< Puzzle.size_table and self.array_puzle[location[0]][location[1]+count]=='.':
moves=(moves[0],1) #the car can move right R1
mov_car[key]=moves #save the move to this car in the dictionary (the key is the car )
elif curent_car.type_of_move==1:#if the type of the move is vertical
if location[0] - 1 >= 0 and self.array_puzle[location[0]-1][location[1]] == '.':
moves=(1,moves[1]) #the car can move up U1
if location[0] + count < Puzzle.size_table and self.array_puzle[location[0]+count][location[1]]=='.':
moves=(moves[0],1)#the car can move down D1
mov_car[key]=moves
return mov_car #return the dictionary the key is the cars and the values is the moves
def calc_successors(self,herstic_id):#compute the children of the node
succesors = []
for succ in self.state_of_puzzle:
location = self.state_of_puzzle[succ].index
suc_car = self.state_of_puzzle[succ]
if suc_car.type_of_move == 0: # if no find space near the car so the car can't move so we don't save it in the list
if location[1] % 6 == 0:
if self.array_puzle[location[0]][location[1] + suc_car.type_of_car + 2] != '.':
continue
elif (location[1] + suc_car.type_of_car + 1) % 6 == 5:
if self.array_puzle[location[0]][location[1] - 1] != '.':
continue
elif self.array_puzle[location[0]][location[1] + suc_car.type_of_car + 2] != '.' and \
self.array_puzle[location[0]][location[1] - 1] != '.':
continue
succesors.append(succ)
else:
if location[0] % 6==0:
if self.array_puzle[location[0]+suc_car.type_of_car+2][location[1]] != '.':
continue
elif (location[0]+suc_car.type_of_car+1)%6==5:
if self.array_puzle[location[0]-1][location[1]]!='.':
continue
elif self.array_puzle[location[0]+suc_car.type_of_car+2][location[1]] != '.' and self.array_puzle[location[0]-1][location[1]]!='.':
continue
succesors.append(succ)
mov_car = self.how_to_move(succesors)
for key in succesors:
curent_car = self.state_of_puzzle[key]
if curent_car.type_of_move==0:
if mov_car[key][0]>0:
self.create_new_node(curent_car, mov_car[key][0], 'L',herstic_id)
if mov_car[key][1]>0:
self.create_new_node(curent_car, mov_car[key][1], 'R',herstic_id)
elif curent_car.type_of_move==1:
if mov_car[key][0]>0:
self.create_new_node(curent_car, mov_car[key][0], 'U',herstic_id)
if mov_car[key][1]>0:
self.create_new_node(curent_car, mov_car[key][1], 'D',herstic_id)
def find_blocking_cars(self,blocking_cars,diff_locationcar):#function that take the cars that block the red car the cars that found in the third row after the red car
#and the function finds if there are cars that block the path of the other cars that block the path of the red car if yes we save them and return them
for key in diff_locationcar:
if key=='X':
continue
move=diff_locationcar[key]
cur_car=self.state_of_puzzle[key]
for i in range(cur_car.index[0],cur_car.index[0]-move[0]-1):
if i<0:
break
elif self.array_puzle[i][cur_car.index[1]] in blocking_cars or self.array_puzle[i][cur_car.index[1]]=='.':
continue
else:
blocking_cars.append(self.array_puzle[i][cur_car.index[1]])
for i in range(cur_car.index[0],cur_car.index[0]+cur_car.type_of_car+2+move[1]):
if i>Puzzle.size_table:
break
elif self.array_puzle[i][cur_car.index[1]] in blocking_cars or self.array_puzle[i][ cur_car.index[1]]=='.':
continue
else:
blocking_cars.append(self.array_puzle[i][cur_car.index[1]])
return blocking_cars
def calc_herustic_val(self,herstic_id): #the function compute the herstic value of the node
index = self.state_of_puzzle['X'].index #save the location of the red car
if index[0] == 2 and index[1] == Puzzle.size_table - 2: #if the red car found in the end of the third row so the red car can exit and return 0
return 0
new_location = []
diff_locationcar={}
new_location.append('X') #we save the cars that block the path of the red car also the red car
sum = Puzzle.size_table - 1 - index[1] - 1
for i in range(index[1],Puzzle.size_table):
move=(0,0)
if self.array_puzle[index[0]][i] not in new_location and self.array_puzle[index[0]][i]!='.':
if self.array_puzle[index[0]][i]!='X'and self.state_of_puzzle[self.array_puzle[index[0]][i]].type_of_move==0:
return sys.maxsize #faluire if there is car that move horizontal that found after the red car so the red car can't exit
car=self.state_of_puzzle[self.array_puzle[index[0]][i]]
diff = index[0] - car.index[0]
num_down = car.type_of_car + 2 - abs(diff) - 1
if num_down + 1 <= car.index[0] % 6: #check if the car the block the path of the red car can move up and open the path to the red car
move=(num_down+1,move[1])
diff_locationcar[self.array_puzle[index[0]][i]] = move
num_up = car.type_of_car + 2 - num_down - 1
if num_up + 1 + car.index[0] + car.type_of_car + 1 <= Puzzle.size_table - 1:#check if the car the block the path of the red car can move down and open the path to the red
move=(move[0],num_up+1)
diff_locationcar[self.array_puzle[index[0]][i]] = move
if move[0]<=move[1] and move[0]!=0:
sum+=move[0]
elif move[1]<move[0] and move[1]!=0:
sum+=move[1]
new_location.append(self.array_puzle[index[0]][i])
if herstic_id==1 or herstic_id==9:
new_location=self.find_blocking_cars(new_location,diff_locationcar)
if herstic_id==3:
return sum
return len(new_location)
class Iterative_deepning:#class that run the algorthim iterative deepning
visited = {}
waiting_nodes = PriorityQueue()
def iterative_deepning(root):
size_table = 6
number_of_nodes=0
sum_herustic=0
start = time.time()
for i in range(0,sys.maxsize):
Iterative_deepning.waiting_nodes = PriorityQueue()
Iterative_deepning.visited={}
Iterative_deepning.waiting_nodes.put((root.score('iterative_deepning'), root))
while not Iterative_deepning.waiting_nodes.empty():
cur_node = Iterative_deepning.waiting_nodes.get()[1]
str_node = list_to_string(cur_node.array_puzle)
while str_node in Iterative_deepning.visited and not Iterative_deepning.waiting_nodes.empty():
cur_node = Iterative_deepning.waiting_nodes.get()[1]
str_node = list_to_string(cur_node.array_puzle)
if cur_node.depth>i:
continue
Iterative_deepning.visited[str_node] = 1
number_of_nodes += 1
sum_herustic += cur_node.score('iterative_deepning')
if time.time() - start>80:
print('failed')
return number_of_nodes,herstic_id,0,sum_herustic/number_of_nodes,number_of_nodes**(1/cur_node.depth),cur_node.depth,cur_node.depth,cur_node.depth,80
elif cur_node.goal_state():
timeExe = time.time() - start
print("Time of execution:", timeExe)
if timeExe <= 80:
temp_node = cur_node
last_move = []
last_move.append('X')
last_move.append('R')
a = 2
last_move.append(str(a))
list_moves = []
count = 1
while temp_node.parent != None:
str_move = temp_node.move
if str_move[0] == last_move[0] and str_move[1] == last_move[1]:
count += 1
else:
str1 = last_move[0] + last_move[1] + str(count)
list_moves.append(str1)
count = 1
last_move = str_move
temp_node = temp_node.parent
if last_move != None:
str1 = last_move[0] + last_move[1] + str(count)
list_moves.append(str1)
temp_node = cur_node
max_depth = None
min_depth = None
size = 0
sum_depth = 0
while not Iterative_deepning.waiting_nodes.empty():
temp_node = Iterative_deepning.waiting_nodes.get()[1]
size += 1
sum_depth += temp_node.depth
if max_depth == None or max_depth < temp_node.depth:
max_depth = temp_node.depth
if min_depth == None or min_depth > temp_node.depth:
min_depth = temp_node.depth
avg_depth = 0
if size == 0:
avg_depth = 0
min_depth=cur_node.depth
max_depth=cur_node.depth
else:
avg_depth = sum_depth / size
count = len(list_moves)
for i in range(count - 1, -1, -1):
print(list_moves[i], end=" ")
print('\n number of visited nodes:', number_of_nodes)
print(' Penetrance: ', cur_node.depth / number_of_nodes)
print('avg H value: ', sum_herustic / number_of_nodes)
print('EBF: ', number_of_nodes ** (1 / cur_node.depth))
print('Max depth: ', max_depth)
print('Min depth: ', min_depth)
print('Average depth: ', avg_depth)
return number_of_nodes,'iterative_deepning',cur_node.depth/number_of_nodes,sum_herustic/number_of_nodes,number_of_nodes ** (1 / cur_node.depth),max_depth,min_depth,avg_depth,timeExe
else:
print('failed')
else:
cur_node.calc_successors('iterative_deepning')
class Car:
def __init__(self,index,type_of_car,type_of_move):#constructor that build the car
self.index=index #the location of the car
self.type_of_car=type_of_car # 1 if the car Occupying three slots and 0 if the car Occupying two slots
self.type_of_move=type_of_move # 0 if the car move horizontal and 1 if the car move vertical
class Puzzle:
size_table = 6
number_of_nodes = 0
visited = {}
sum_herustic=0
waiting_nodes = PriorityQueue()
def search(self,herstic_id):
start = time.time()
while not self.waiting_nodes.empty():
cur_node = self.waiting_nodes.get()[1]
str_node = list_to_string(cur_node.array_puzle)
while str_node in self.visited and not self.waiting_nodes.empty():
cur_node = self.waiting_nodes.get()[1]
str_node = list_to_string(cur_node.array_puzle)
self.visited[str_node] = 1
self.number_of_nodes+=1
self.sum_herustic+=cur_node.herstic_val
if cur_node.goal_state():
timeExe = time.time() - start
print("Time of execution:", timeExe)
if timeExe<=time_limit:
temp_node=cur_node
last_move=[]
last_move.append('X')
last_move.append('R')
a=2
last_move.append(str(a))
list_moves=[]
count=1
while temp_node.parent!= None:
str_move=temp_node.move
if str_move[0]==last_move[0] and str_move[1]==last_move[1]:
count+=1
else:
str1=last_move[0]+last_move[1]+str(count)
list_moves.append(str1)
count=1
last_move=str_move
temp_node = temp_node.parent
if last_move!=None:
str1 = last_move[0] + last_move[1] + str(count)
list_moves.append(str1)
temp_node=cur_node
max_depth=None
min_depth=None
size=0
sum_depth=0
while not self.waiting_nodes.empty():
temp_node = self.waiting_nodes.get()[1]
size+=1
sum_depth+=temp_node.depth
if max_depth==None or max_depth<temp_node.depth:
max_depth=temp_node.depth
if min_depth==None or min_depth>temp_node.depth:
min_depth=temp_node.depth
avg_depth=0
if size==0:
avg_depth=0
max_depth=cur_node.depth
min_depth=cur_node.depth
else:
avg_depth=sum_depth/size
count=len(list_moves)
temp_list=[]
for i in range(count-1,-1,-1):
print(list_moves[i], end=" ")
temp_list.append(list_moves[i])
with open("solution.txt", "a") as my_file:
my_file.write(" ".join(temp_list)+' ' )
my_file.write("\n")
penetrance=cur_node.depth/self.number_of_nodes
avg_h_value=self.sum_herustic/self.number_of_nodes
ebf=self.number_of_nodes**(1/cur_node.depth)
print('\n number of visited nodes:',self.number_of_nodes)
print('herstic_id: ', herstic_id)
print(' Penetrance: ',penetrance)
print('avg H value: ',avg_h_value)
print('EBF: ',ebf)
print('Max depth: ',max_depth)
print('Min depth: ', min_depth)
print('Average depth: ',avg_depth)
return self.number_of_nodes,herstic_id,penetrance,avg_h_value,ebf,max_depth,min_depth,avg_depth,timeExe
else:
with open("solution.txt", "a") as my_file:
my_file.write("failed\n")
print('failed')
return self.number_of_nodes,herstic_id,0,self.sum_herustic/self.number_of_nodes,self.number_of_nodes**(1/cur_node.depth),cur_node.depth,cur_node.depth,cur_node.depth,10
else:
cur_node.calc_successors(herstic_id)
@staticmethod
def add_to_waitlist(current_node,herstic_id):
Puzzle.waiting_nodes.put((current_node.score(herstic_id), current_node))
def init_the_game(self, node_text,herstic_id): #create the init board the root
cur_cars = {}
array_board = list()
for i in range(0, self.size_table):
array_board.append(list(node_text[i * self.size_table:i * self.size_table + self.size_table]))
for i in range(0, self.size_table):
for j in range(0, self.size_table):
if array_board[i][j] == '.':
continue
if ('A' <= array_board[i][j] <= 'K' or array_board[i][j] == 'X') and array_board[i][j] not in cur_cars:
type_car = 0
if j == self.size_table - 1:
type_move = 1
elif j < self.size_table - 1:
if array_board[i][j] == array_board[i][j + 1]:
type_move = 0
else:
type_move = 1
elif 'O' <= array_board[i][j] <= 'R' and array_board[i][j] not in cur_cars:
type_car = 1
if j >= self.size_table - 2:
type_move = 1
elif j < self.size_table - 2:
if array_board[i][j + 1] == array_board[i][j] and array_board[i][j] == array_board[i][j + 2]:
type_move = 0
else:
type_move = 1
if array_board[i][j] not in cur_cars:
index = (i, j)
car = Car(index, type_car, type_move)
cur_cars[array_board[i][j]] = car
# self.number_of_nodes += 1
current_node = Node(cur_cars, None, 0, array_board, None, None)
print_array(array_board)
if herstic_id==4:
val_herstic = current_node.calc_herustic_valtemp()
else:
val_herstic = current_node.calc_herustic_val(herstic_id)
current_node.herstic_val = val_herstic
if herstic_id=='iterative_deepning':
return Iterative_deepning.iterative_deepning(current_node)
else:
self.add_to_waitlist(current_node,herstic_id)
return self.search(herstic_id)
time_limit=4
if __name__ == "__main__":
with open("rh.txt" ,"r") as f:
fileData = f.read()
data = fileData.split("--- RH-input ---")
data = data[1]
data = data.split("--- end RH-input ---")
data = data[0]
games = data.split("\n")
games = games[1:]
sum_N=0
sum_penetrance=0
sum_avg_h_value=0
sum_ebf=0
sum_max_depth=0
sum_min_depth=0
sum_avg_depth=0
sum_time_exe=0
levels_nodesnumber=[0,0,0,0]
levels_time_exe=[0,0,0,0]
levels_penetrance=[0,0,0,0]
levels_avg_h=[0,0,0,0]
levels_ebf=[0,0,0,0]
levels_mindepth=[0,0,0,0]
levels_avg_avgdepth=[0,0,0,0]
levels_maxdepth=[0,0,0,0]
size=len(games)-1
for i in range(0, size):
print("-------------------------------------------------------------------------------------------------------")
print("Problem:" ,str(i+1))
currentData =games[i]
puzzle = Puzzle()
if i+1==14:
N, herstic_id, penetrance, avg_h_value, ebf, max_depth, min_depth, avg_depth, time_exe = puzzle.init_the_game(currentData, 3)
else:
N,herstic_id,penetrance,avg_h_value,ebf,max_depth,min_depth,avg_depth,time_exe=puzzle.init_the_game(currentData,9)
j=int(i/10)
levels_nodesnumber[j]+=N
levels_time_exe[j]+=time_exe
levels_penetrance[j]+=penetrance
levels_ebf[j]+=ebf
levels_avg_h[j]+=avg_h_value
levels_mindepth[j]+=min_depth
levels_avg_avgdepth[j]+=avg_depth
levels_maxdepth[j]+=max_depth
sum_N+=N
sum_penetrance+=penetrance
sum_avg_h_value+=avg_h_value
sum_ebf+=ebf
sum_max_depth+=max_depth
sum_min_depth+=min_depth
sum_avg_depth+=avg_depth
sum_time_exe+=time_exe
print("-------------------------------------------------------------------------------------------------------")
print(herstic_id)
print('average number of vistid nodes: ',sum_N/size)
print('average time of execution: ',sum_time_exe/size)
print('average penetrance: ',sum_penetrance/size)
print('average ebf: ',sum_ebf/size)
print('average H value: ', sum_avg_h_value/size)
print('average max depth: ',sum_max_depth/size)
print('average min depth: ',sum_min_depth/size)
print('average of average depth: ',sum_avg_depth/size)
print("-------------------------------------------------------------------------------------------------------")
levels=['beginer','intermdate','advanced','expert']
for i in range(0,len(levels)):
print('average number of vistid nodes for ',levels[i], 'is: ', levels_nodesnumber[i]/10)
print('average time of execution for ', levels[i], 'is: ', levels_time_exe[i] / 10)
print('average penetrance for ', levels[i], 'is: ', levels_penetrance[i] / 10)
print('average ebf for ', levels[i], 'is: ', levels_ebf[i] / 10)
print('average H value for ', levels[i], 'is: ', levels_avg_h[i] / 10)
print('average min depth for ', levels[i], 'is: ', levels_mindepth[i] / 10)
print('average of average depth for ', levels[i], 'is: ', levels_avg_avgdepth[i] / 10)
print('average max depth for ', levels[i], 'is: ', levels_maxdepth[i] / 10)
|
b513eaa39db2de8aab8d3e3b99d2d4f342d26b14 | Gi-lab/Mathematica-Python | /07-Mate.py | 351 | 4.3125 | 4 | lista_numeros = []
quantidade = int(input('Quantos numeros voce deseja inserir? '))
while len(lista_numeros) + 1 <= quantidade:
numero = int(input('Digite um numero '))
lista_numeros.append(numero)
maior_numero = max(lista_numeros)
print(f'O maior número da lista é {maior_numero}')
input('Digite uma tecla para fechar o programa') |
0a52989a5efd0d95afbd0b5d2d213834ecbb3505 | AnkitaPisal1510/dictionary | /dic_Q10.py | 309 | 3.671875 | 4 | #
#q10
d={
"alex":["sub1","sub2","sub3"],
"david":["sub1","sub2"]
}
# l=[]
# for i in d:
# # print(y[i])
# # print(len(y[i]))
# j=len(d[i])
# l.append(j)
# print(sum(l))
#second method
list1=[]
for i in d.values():
for j in i:
list1.append(j)
print(len(list1))
print(list1) |
30437b421a5e77cea639d04f38b77d6e94c62c2f | AnkitaPisal1510/dictionary | /dic_Q7.py | 273 | 3.5625 | 4 | #q7 ["2","7",'9','5','1']
d=[
{"first":"1"},
{"second":"2"},
{"third":"1"},
{"four":"5"},
{"five":"5"},
{"six":"9"},
{"seven":"7"}
]
# a=[]
# for i in d:
# for j in i:
# if i[j] not in a:
# a.append(i[j])
# print(a)
|
ad503eddaa5c4a00adab20760850c56e7710ee13 | etallman/backend-numseq | /numseq/fib.py | 307 | 4.03125 | 4 | # Fibonacci
'''Within the numseq package, creates a module named fib. Within the fib module, defines a function fib(n) that returns the nth Fibonacci number.'''
def fib(n):
fib_list = [0,1]
for i in range(2, n+1):
fib_list.append(fib_list[i-2] + fib_list[i-1])
return fib_list[n] |
c3d6fa2e65ece7d2cc4c04e2aa815e142bf25306 | Artengar/Drawbot | /Letters_overlay/Letters_overlay.py | 396 | 3.984375 | 4 | #This script put letters on top of each other, comparing which parts of the letters are similar in all typefaces installed on your computer
presentFonts = installedFonts()
fill(0, 0, 0, 0.2)
for item in presentFonts:
if item != item.endswith("egular"):
print(type(item))
print(item)
font(item, 450)
text("f", (350, 400))
saveImage("~/Desktop/f.jpg") |
760cff566ac1cf331b44d84a449fb5da9eb2b3e9 | Artengar/Drawbot | /Rolling_eyes_3/Rolling_eyes_3.py | 1,717 | 3.921875 | 4 | #Rolling eyes on the number 3.
#Free for use and modify, as long as a reference is provided.
#created by Maarten Renckens (maarten.renckens@artengar.com)
amountOfPages = 16
pageWidth = 1000
pageHeight = 1000
#information for drawing the circle:
midpointX = 0
midpointY = 0
ratio = 1
singleAngle = 360/amountOfPages
#Some default functions
import random
#Create the animation
def drawCircle(page, singleAngle, amountOfCircling, midpointX, midpointY, ratio, color):
fill(color)
#Get the amount of movement
currentAngle = singleAngle*page-90
correctX=random.randint(0,30)
correctY=random.randint(0,30)
oval(midpointX+(correctX)-ratio,midpointY+(correctY)-ratio,ratio*2,ratio*2)
for page in range(amountOfPages):
print("==================== Starting page %s ====================" %page)
if page != 0:
newPage(pageWidth, pageHeight)
elif page ==0:
size(pageWidth, pageHeight)
#set the origin in the middle of the page
translate(pageWidth/2, pageHeight/2)
#create a background
fill(1)
rect(-pageWidth/2,-pageHeight/2,pageWidth, pageHeight)
#first circle #black
midpointX=0
midpointY=200
ratio=160
drawCircle(page, singleAngle, 0, midpointX, midpointY, ratio, 0)
#second circle #black
midpointX=0
midpointY=-100
ratio=230
drawCircle(page, singleAngle, 0, midpointX, midpointY, ratio, 0)
#third circle #white
midpointY=200
midpointX=-50
ratio=150
drawCircle(page, singleAngle, 40, midpointX, midpointY, ratio, 1)
#fourth circle #white
midpointY=-100
midpointX=-60
ratio=230
drawCircle(page, singleAngle, 50, midpointX, midpointY, ratio, 1)
saveImage("~/Desktop/Rolling_eyes_3.gif")
|
bcc0887e2fc2dadab69e061cf0ebb7771acb7145 | techmexdev/Networking | /tcp_client.py | 663 | 3.53125 | 4 | from socket import *
server_name = 'localhost'
server_port = 3000
# SOCK_STREAM = TCP
while True:
client_socket = socket(AF_INET, SOCK_STREAM)
# connection must be established before sending data
client_socket.connect((server_name, server_port))
message = input(f'\nSend letter to {server_name}:{server_port}\n')
encoded_message = message.encode()
client_socket.send(encoded_message)
# 4096 is reccomended buffer size: https://docs.python.org/3/library/socket.html#socket.socket.recv
reply = client_socket.recv(4096)
print(f'received letter from {server_name}:{server_port}:\n{reply.decode()}')
client_socket.close()
|
91c93f60046efb049315fb5bb439f0629e079325 | dwightr/ud036_StarterCode | /media.py | 1,186 | 3.609375 | 4 | import webbrowser
class Video():
"""
Video Class provides a way to store
video related information
"""
def __init__(self, trailer_youtube_url):
# Initialize Video Class Instance Variables
self.trailer_youtube_url = trailer_youtube_url
class Movie(Video):
"""
Movie Class provides a way to store
movie related information and will inherit
Instance Variable from the Video class
"""
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
def __init__(self, title, movie_storyline, poster_image,
trailer_youtube_url):
"""
Constructor method will initialize instance variables
and variables inhertied from video class
"""
# Initialize Variables Inhertied From Video Class
Video.__init__(self, trailer_youtube_url)
# Initialize Movie Class Instance Variables
self.title = title
self.movie_storyline = movie_storyline
self.poster_image_url = poster_image
def show_trailer(self):
# This Method Shows The Trailer Of The Instance It Is Called From
webbrowser.open(self.trailer_youtube_url)
|
cedb0a8cbf50d11ab70ab10be53e0892ca290bd3 | drsantos20/python-concurrency | /algorithms/test_binary_search.py | 349 | 3.59375 | 4 | import unittest
from algorithms.binary_search import binary_search
class TestBinarySearch(unittest.TestCase):
def test_binary_search(self):
array = [3, 4, 5, 6, 7, 8, 9]
find = 8
result = binary_search(array, find, 0, len(array)-1)
self.assertEqual(result, 1)
if __name__ == '__main__':
unittest.main()
|
8c81bbc51967ddf5ab6e0d6d40cdea1e0a2dfbd3 | renanpaduac/LP_ATIVIDADE_4 | /create_db.py | 338 | 3.59375 | 4 | # -*- coding: latin1 -*-
import sqlite3
con = sqlite3.connect("imc_calc.db")
cur = con.cursor()
sql = "create table calc_imc (id integer primary key, " \
"nome varchar(100), " \
"peso float(10), " \
"altura float(10), " \
"resultado float(100))"
cur.execute(sql)
con.close()
print ("DB Criada com Sucesso!")
|
129123b7825f07aa303dad36c1b93fd5c27329c6 | forwardslash333/PythonPractice | /10. Add Pattern.py | 398 | 3.9375 | 4 | '''
Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn
Sample value of n is 5
Expected Result : 615
'''
n = input ('Enter an integer\n')
n1 = int('%s' % n) # single digit integer
n2 = int('%s%s' % (n,n)) # second digit number
n3 = int('%s%s%s' % (n,n,n)) # Three digit number
print(n1+n2+n3) |
b7d148d07dedf887d3b750bd29238f7852060f02 | Yaraslau-Ilnitski/homework | /Class/Class7/7.08.py | 323 | 3.65625 | 4 | from math import sqrt
def func(mean_type, *args):
acc = 0
count = 0
if mean_type:
for item in args:
acc += item
count += 1
return acc / count
acc = 1
for item in args:
acc += item
count += 1
return acc ** (1 / count)
func(False, 1, 2, 3)
|
54469d6f0b99a60f520db6c0b159891a8bddc45c | Yaraslau-Ilnitski/homework | /Homeworks/Homework1/task_1_3.py | 198 | 3.59375 | 4 | a = float(input("Ребро куба = "))
V_cube = a ** 3
V_cube_side = 4 * V_cube
print('Площадь куба =', V_cube, 'Площадь боковой поверхности =', V_cube_side)
|
90e3af08fb0b5b7cc753583416b5a3927da92f5b | Yaraslau-Ilnitski/homework | /Class/Class3/3.07.py | 189 | 3.9375 | 4 | stroka = input("Введите предложение\n")
if len(stroka) > 5 :
print(stroka)
elif len(stroka) < 5:
print("Need more!")
elif len(stroka) == 5:
print("It is five") |
e04141931c38d8747c39a4a00ff527725b6e6fa9 | Yaraslau-Ilnitski/homework | /Homeworks/Homework3/task_3_1.py | 250 | 3.578125 | 4 | a = int(input("Введите число делящееся на 1000:\n"))
while True:
if a % 1000 == 0:
print('millenium')
break
else:
a = int(input("...\nВведите число делящееся на 1000:\n"))
|
af1751ce022c930e5b09ba0332f4eb16d39d9b02 | Yaraslau-Ilnitski/homework | /Class/Class7/7.02.py | 1,098 | 3.78125 | 4 | from random import randint
def create_matrix(length, height):
rows = []
for i in range(length):
tnp = []
for i in range(height):
tnp.append(randint(0, 10))
rows.append(tnp)
return rows
matrix = create_matrix(2, 2)
def view(matrix):
for vert in matrix:
for item in vert:
print(item)
# print(matrix)
# view(matrix)
def sum(matrix):
s = 0
for valueList in matrix:
for i in valueList:
s += i
return s
# print(matrix)
# print(sum(matrix))
def greatest(matrix):
greatest = 0
for valueRows in matrix:
for valueTNP in valueRows:
if valueTNP > greatest:
greatest = valueTNP
return greatest
# print(greatest(matrix))
def minimum(matrix):
minimum = matrix[0][0] # берем значение как первый элемент матрицы
for valueRows in matrix:
for valueTNP in valueRows:
if minimum > valueTNP:
minimum = valueTNP
return minimum
print(matrix)
print(minimum(matrix))
|
24a0de5ae6d529277c7770ba74537acf5ae23f3b | Yaraslau-Ilnitski/homework | /Class/Class11/Test.py | 445 | 3.78125 | 4 | class main:
self.x = x
self.y = y
class Line:
point_a = None
point_b = None
def __init__(self, a: Point, b: Point):
self.point_a = a
self.point_b = b
def length(self):
diff = self.point_a.y - self.point_b.y
if diff < 0:
diff = -diff
return diff
def points():
line = Line(Point(1,2),Point(1,6)
print(line.length())
if __name__ == '__main__':
points()
|
848b8f6dc9767fe4be22982f73a76e8e376bdbb9 | wan-si/pythonLearning | /nowcoder/countUpper.py | 252 | 3.78125 | 4 | # 找出给定字符串中大写字符(即'A'-'Z')的个数
while True:
try:
string = input()
count =0
for i in string:
if i.isupper():
count+=1
print(count)
except:
break |
7e2470a00ba8544adad824e27f443cf6aeea842a | wan-si/pythonLearning | /nowcoder/stepSquar 2.py | 729 | 3.53125 | 4 | # 描述
# 请计算n*m的棋盘格子(n为横向的格子数,m为竖向的格子数)沿着各自边缘线从左上角走到右下角,总共有多少种走法,要求不能走回头路,即:只能往右和往下走,不能往左和往上走。
# 本题含有多组样例输入。
# 输入描述:
# 每组样例输入两个正整数n和m,用空格隔开。(1≤n,m≤8)
# 输出描述:
# 每组样例输出一行结果
# 示例1
# 输入:
# 2 2
# 1 2
# 复制
# 输出:
# 6
# 3
# 复制
def steps(n,m):
if n==0 or m==0:
return 1
else:
return steps(m,n-1)+steps(n,m-1)
while True:
try:
n,m = map(int,input().split())
print(steps(n,m))
except:
break |
875f5cfd880c495fd2daa4a4285492bbd9176681 | chyko67/- | /200528p56.py | 599 | 3.515625 | 4 | import re
def maketext(script):
written_pattern = r':'
match = re.findall(written_pattern, script)
for writtenString in match:
script = script.replace(writtenString, 'said,')
return script
s = """mother : My kids are waiting for me. What time is it? What time is it? What time is it, trees!
trees : Eight O'clock, Eight O'clock, It's eight O'clock, Tic Tock
mother : What time is it? What time is it? What time is it, birds!
birds : Twelve O'clock, Twelve O'clock, It's Twelve O'clock, Tic Tock
mother : It's so late!"""
print(maketext(s))
|
832f2065b6df66978a435e81418a8458472ea4b8 | ajwake97/Weather-App | /Weather Program.py | 1,352 | 3.765625 | 4 |
import requests
import json
import time
#This is the API Key
API_KEY = "10b3ff178d347bb5e10cfee10deb2b63"
#This is the base URL
baseUrl = "https://api.openweathermap.org/data/2.5/weather?"
#This prompts the user for the desired zipcdoe
def zipInput():
zipCode = input("Enter the zipcode: ")
#Sends a request to the openweathermaps.org and uses my API key and zipcode to return data
response = requests.get((f'http://api.openweathermap.org/data/2.5/weather?zip={zipCode}&appid={API_KEY}'))
#Prints the response and displays the returned data
if response.status_code == 200:
print('Connection Sucessful')
time.sleep(2)
print(json.dumps(response.json(), indent=1))
reRun()
if response.status_code != 200: #Displays connection issue if true
print('Connection Unsuccessful')
print('Zipcode Not Valid')
try:
zipCode() #retries zipcode function
except:
print('Error handling Zipcode')
time.sleep(1)
print('Please Rerun Program')
time.sleep(1)
print('Program Ending')
exit() #closes program
def reRun(): #function allows user to rerun the program
Y = input('\n\nWould you like to rerun this program? \nType "Yes" to input another zipcode. \ntype "Quit" to end program\n')
while Y == "Yes":
zipInput()
while Y == "Quit":
exit()
zipInput()
reRun() |
b3fac7fac215201441c828afbecfd522e043a42c | shruti0/guvi-1 | /leap.py | 109 | 3.765625 | 4 | year = int(input())
if ((year%4==0 and year%100 !=0) or (year%400 == 0)):
print('yes')
else:
print('no')
|
f0b85958acc09ea92cbf9a995aa24311241efb09 | Jrjh27CS/Python-Samples | /practice-python-web/listLessThanTen.py | 735 | 4.0625 | 4 | #Challenge given by https://www.practicepython.org
#Jordan Jones Apr 16, 2019
#Challenge: Write a program that prints out all of the elements in given list a less than 5
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for x in a:
if x < 10:
print(x)
#Extra 1: Instead of 1 by 1 print, make a new list that has all elements less than 5 and print new list
b = []
for x in a:
if x < 5:
b.append(x)
print(b)
#Extra 2: Write this in one line of python
print([x for x in a if x < 5])
#Extra 3: Ask user for num and return a list that contains only nums from a that are smaller than given number
limiter = int(input("What number would you like all elements to be smaller than? Num:"))
print([num for num in a if num < limiter])
|
0a6b38b73eea3f054edadbf5dc5f08ee4c524cb1 | Jrjh27CS/Python-Samples | /practice-python-web/fibonacci.py | 690 | 4.21875 | 4 | #Challenge given by https://www.practicepython.org
#Jordan Jones Apr 16, 2019
#Challenge: Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
# Take this opportunity to think about how you can use functions.
# Make sure to ask the user to enter the number of numbers in the sequence to generate.
def fib(x):
z = []
if x == 0:
return z
z.append(0)
if x == 1:
return z
z.append(1)
if x == 2:
return z
while len(z) != x:
z.append(z[len(z)-1] + z[len(z)-2])
return z
num = int(input("How many fibonacci numbers would you like starting from 0? Num:"))
print(fib(num))
|
b87ed85c70fab6268ef65915778bbed612ba6f0a | C4st3ll4n/Cods_Py | /aleatorio/PouI.py | 874 | 3.625 | 4 | from random import randint as rr
v = 0
d = 0
while True:
jogador = int(input("Digite um valor: "))
pc = rr(0,11)
t = jogador + pc
tipo = ' '
while tipo not in 'PI':
tipo = input("Par ou Impar? [P/I]\n ").strip().upper()[0]
print(f'Deu {t}')
if tipo == "P":
if t % 2 == 0:
print("YOU WIN !")
v += 1
else:
print("YOU LOOOOSE !")
d += 1
if tipo == "I":
if t % 2 == 1:
v += 1
print("YOU WIN !")
else:
print("YOU LOOOOSE !")
d += 1
print("Eae, vamos de novo ?!")
resposta = input("[S/N]")
if resposta.strip().upper()[0] == "S":
continue
else:
print(f"Vitórias = {v}\nDerrotas = {d}")
print("Tchau Tchau !")
break
print("\nFIM !") |
d2e4e3492046a7fb161d10ee63db46deab2862d5 | C4st3ll4n/Cods_Py | /aleatorio/ex62.py | 532 | 3.8125 | 4 | pri = int(input("Primeiro termo: "))
razao = int(input("Razão: "))
termo = pri
cont = 1
total = 0
mais = 10
while mais != 0:
total = total + mais
while cont <= total:
print(termo, " ", end="")
termo = termo + razao
cont += 1
print("\nWait for it....")
decisao = input("Deseja mostrar algum número a mais ?\n[S/N] ")
if decisao == "S":
mais = int(input("Quantos ? "))
else:
print("Total de termos: {}".format(total))
break
print("Fim!")
|
38a1b18e152c1156560e74d62f3b826e04c1adbc | CarsonP25/sic_xe-assembler | /symtab.py | 442 | 3.515625 | 4 | class Symtab:
"""Symbol tables containing labels and addresses"""
def __init__(self):
"""Init table"""
self.table = {}
def addSym(self, label, value):
"""Add an entry to the SYMTAB"""
self.table[label] = value
def searchSym(self, label):
for name in self.table.keys():
if name == label:
return True
return False
|
3ec773ad3e28f8538c0d76a12d6062df0d30014e | mohan2005mona/python | /regularexpression 1.py | 5,799 | 4.0625 | 4 | import re
email=input('enter valid email address')
result=re.search(r'[\w\.-]+@google.com',email)
if result:
print("its a valid google id")
else:
print('Your email id is invalid')
result=re.sub(r'[\w\.-]+@google.com','\2\1@gmail.com',email)
print(result)
import re
str= '808-1234 #athis is my phone number dafdfafdafaf'
result=re.sub(r'-',' ',re.sub(r'#.*','',str))
print(result)
#program to replace the comments in the string and also the other charcters in the Phone number i.e,. hyphen(-) and Dollar($)
import re
str= '808-12-$34 #athis is my phone number dafdfafdafaf'
result=re.sub(r'-',' ',re.sub(r'#.*','',str))
print(result)
result=re.sub(r'\D',' ',re.sub(r'#.*','',str))
print(result)
# Program to replace the string pattern with other pattern - here we are using multiple combination of pattern to search and replace with the string
import re
str= '''U.S. stock-index futures pointed
to a solidly higher open on Monday,
indicating that major
benchmarks were poised to USA reboundfrom last week's sharp decline,
\nwhich represented their biggest weekly drops in months.'''
i=re.sub(r'USA|U.S.|US','United States',str)
print(i)
str= 'Dan has 3 snails. Mike has 4 cats. Alisa has 9 monkeys.'
re.search('\d+',str).group()
------>
str= 'Dan has 3 snails. Mike has 4 cats. Alisa has 9 monkeys.'
i=re.search('\d+',str) # --> prints only 3 because search functions check all the strings and prints only the first occurance of the string
i=re.findall('\d+',str) # --> this prints 3,4,9 as findall finds all the occurances
print(i)
#---------------------------------------------------------------------------------------------------------------------------
#this program is to square the numbers which are available in the strings and also used a function.
import re
def square(x):
return (x ** 2)
string= 'Dan has 3 snails. Mike has 4 cats. Alisa has 9 monkeys.'
#x=re.sub('(\d+)',lambda x: str(x),string) --> this line finds the matching digit objects and again prints back the same thing. this is to illustrate about lamba
x=re.sub('(\d+)',lambda x: str(square(int(x.group(0)))),string)
print(x)
import re
input="eat 9laugh sleep study"
final=re.sub('\w+',lambda m: str(m.group()) +'ing',input)
print(final)
#printing duplicate entries - \1 prints the duplicate strings which are in consecutive in nature
txt='''
hello hello
how are are how you
bye bye
'''
x=re.compile(r'(\w+) \1')
print(x.findall(txt))
#backreferencing
import re
string="Merry Merry Christmas"
x=re.sub(r'(\w+) \1',r'Happy \1',string)
print(x)
#Output : Happy Merry Christmas
import re
string="Merry Merry Christmas"
x=re.sub(r'(\w+) \1',r'Happy',string)
print(x)
#Output : Happy Christmas
#_---------------------------------------------------------------------------
import re
txt='''
C:\Windows
C:\Python
C:\Windows\System32
'''
pattern=re.compile(input('enter the pattern you want to search'))
#pattern=re.compile(r'C:\\Windows\\System32')
print(pattern.search(txt))
#find all the matches for dog and dogs in the given text
import re
txt='''
I have 2 dogs. one dog is 1 year old and other one is 2 years old. Both
dogs are very cute!
'''
print(re.findall('dogs?',txt))
## the regular expression can also be like this re.findall(dog|dogs)... but the output will not find dogs as complete string instead it will only find "dog" matching string
##first hence dogs will not be in the result.. the result set is [dog,dog,dog] instead of [dog,dogs,dog]
#find all filenames starting with file and ending with .txt
import re
txt='''
file1.txt
file_one.txt
file.txt
fil.txt
file.xml
'''
print(re.findall('file\w*\.txt',txt))
##find all filenames starting with file and ending with .txt - plus(+) quantifiers
import re
txt='''
file1.txt
file_one.txt
fil89e.txt
fil.txt
file23.xml
file.txt
'''
print(re.findall('file\d+\.txt',txt))
#find years in the given text.
import re
txt='''
The first season of Indian Premiere League (IPL) was played in 2008.
The second season was played in 2009 in South Africe.
Last season was played in 2018 and won by Chennai Super Kings(CSK).
CSL won the title in 2010 and 2011 as well.
Mumbai Indians (MI) has also won the title 3 times in 2013, 2015 and 2017.
'''
print(re.findall('[1-9]\d{3}',txt))
#In thegiven text,filter out all 4 or more digit numbers.
import re
txt='''
123143
432
5657
4435
54
65111
'''
print(re.findall('\d{4,}',txt))
# in case if i have to filter the numbers which has maximum number 4. re.findall('\d{,4})
#In thegiven text,filter out all 4 or more digit numbers.
import re
txt='''
123143
432
5657
4435
54
65111
'''
#print(re.findall('\d{4,}',txt))
print(re.findall('\d{1,4}',txt)) --> this is used list out 4 charcters excluding space otherwise it starts from 0 and treat space as separtae character
#write a pattern to validate telephone numbers.
#Telephone numbers can be of the form : 555-555-5555,555 555 5555
#5555555555
import re
txt='''
555-555-5555
555 555 5555
5555555555
'''
#print(re.findall('\d{4,}',txt))
print(re.findall('\d{3}[\s\-]?\d{3}[\s\-]?\d{4}',txt))
##End of quantifiers.
##BELOW PROGRAM IS NOT WORKING
##Greedy Behaviour
import re
txt='''<html><head><title>Title</title>'''
print(re.findall("<.*>"),txt)
print(re.findall("<.*?>"),txt) # treat each match found as separate entity
##Bounday \b operations
import re
txt=''' you are trying to find all the and or the symbols
in the text but the and or for band is theft by a former
'''
print(re.findall('\\b(and|or|the)\\b',txt)) ## boundary matches
##consider a scenario where we want to find all the lines
##in the given text which start with the pattern.
import re
txt='''
Name:
age: 0
Roll No :15
Grade : S
Name: Ravi
Age : -1
Roll No : 123 Name :ABC
Grade : k
Name: Ram
Age : N/A
Roll No : 1
Grade: G
'''
print(re.findall('^Name:.*',txt,flags=re.M))
|
63b47daca4a17690bf29270996835298782b1659 | Rodo2005/bucles_python | /ejemplos_clase.py | 6,647 | 4.125 | 4 | #!/usr/bin/env python
'''
Bucles [Python]
Ejemplos de clase
---------------------------
Autor: Inove Coding School
Version: 1.1
Descripcion:
Programa creado para mostrar ejemplos prácticos de los visto durante la clase
'''
__author__ = "Inove Coding School"
__email__ = "alumnos@inove.com.ar"
__version__ = "1.1"
valor_maximo = 5
def bucle_while():
# Ejemplos con bucle while "mientras"
x = 0
# En este caso realizaremos un bucle mientras
# x sea menor a 5
while x < valor_maximo:
if x == 4:
print('Bucle interrumpido en x=', x)
break
x_aux = x # Guardamos en una variable auxiliar (aux) el valor de x
x += 1 # Incrementamos el valor de x para que el bucle avance
# Si x es par, continuo el bucle sin terminarlo
if (x_aux % 2) == 0:
continue
# Imprimimos en pantalla el valorde x_aux,
# que era el valor de x antes de incrementarlo
print(x_aux, 'es menor a', valor_maximo)
while True:
print('Ingrese un número distinto de cero!')
numero = int(input())
if numero == 0:
print('Se acabó el juego! numero={}'.format(numero))
break
print('Número ingresado={}'.format(numero))
def bucle_for():
# Ejemplos con bucle for "para"
# Realizaremos el mismo caso que el primer ejemplo de "while"
# pero ahora con el bucle "for"
# Este bucle "for" caso es el indicado para este tipo de acciones
for x in range(5):
if x == 4:
print('Bucle interrumpido en x=', x)
break
# Si x es par, continuo el bucle sin terminarlo
if (x % 2) == 0:
continue
print(x, 'es menor a', valor_maximo)
# Ahora recorreremos (iterar) una lista de datos en donde
# en los índices pares (0, 2, 4) se encuentran los nombres de los contactos
# y en los índices impares (1, 3, 5) los números de los contacto
# Es una lista mezclada de strings y números
agenda = ['Claudia', 123, 'Roberto', 456, 'Inove', 789]
agenda_len = len(agenda)
for i in range(agenda_len):
if (i % 2) == 0:
# Índice par, imprimo nombre
nombre = agenda[i]
print("Nombre contacto:", nombre)
else:
# Índice impar, imprimo número
numero = agenda[i]
print("Número contacto:", numero)
def contador():
# Ejemplo de como contar la cantidad de veces
# que un elemento se repite o evento ocurre
# En este ejemplo se contará cuantas veces se ingresa
# un número par
# El bucle finaliza al ingresar vacio
# primero debo inicializar mi contador
# Como vamos a "contar", el contador debe arrancar en "0"
contador = 0
# Bandera que usamos para indicar que el bucle siga corriendo
numero_valido = True
print("Ingrese cualquier número entero mayor a cero")
print("Ingrese número negativo para teriminar el programa")
while numero_valido:
numero = int(input())
if numero >= 0:
if(numero % 2) == 0: # El número es par?
contador += 1 # Incremento el contador
print("Contador =", contador)
else:
numero_valido = False # Número negativo, numero_valido falso
def sumatoria():
# Ejemplos de ecuaciones con bucles
# Cuando queremos realizar la suma de una serie de números
# la ecuación la escribiriamos de la siguiente forma:
# sumatoria = numero_1 + numero_2 + numero_3 + .... + numero_10
# Que es equivalente a hacer un incremento de la variable sumatoria
# por cada valor deseado a sumar
# sumatoria += numero_1
# sumatoria += numero_2
# sumatoria += numero_3
# sumatoria += .....
# sumatoria += numero_10
# Esta operación se puede realizar con un bucle "for"
# dado la lista de números
numeros = [1, 2, 3, 4, 5]
# Debo primero inicializar la variable donde almacenaré la sumatoria
# Ya que es necesario que empiece con un valor conocido
sumatoria = 0
for numero in numeros:
sumatoria += numero # sumatoria = sumatoria + numero
print("número = ", numero, "sumatoria =", sumatoria)
def bucle_while_for():
# Ejemplos de bucles while + for
# Como bien vimos, los bucles while "mientras"
# se deben utilizar cuando no se conoce la secuencia que se recorrerá
# Cuando se posee la secuencia se debe usar el bucle for "para"
# El bucle while se utiliza mucho para hacer que un programa corra/funcione
# indefinidamente hasta que una condición de salida ocurra
# Ejemplificaremos esto junto al uso de un ejercicio con bucle for
# El objetivo es pedir por consola un número y almacenarlo en un listado
# para imprimirlo al final.
# Además, se debe almacenar cual fue el máximo número ingresado
# Se debe repetir este proceso hasta que se ingrese un número negativo
# Solo se aceptan números positivos o cero
maximo_numero = None
lista_numeros = []
print("Ingrese un número mayor o igual a cero")
while True:
# Tomamos el valor de la consola
numero = int(input())
# Verificamos si el número es negativo
if numero < 0:
print('Hasta acá llegamos!')
break # Salgo del bucle!
# Verifico si el número ingresado es mayor al
# máximo número ingresado hasta el momento
if (maximo_numero == None) or (numero > maximo_numero):
maximo_numero = numero
lista_numeros.append(numero)
# Termino el bucle imprimo la lista de números:
print("Lista: ", lista_numeros)
# Imprimo el máximo número encontrado
print("Máximo número = ", maximo_numero)
# Imprimo el máximo número utilizando la función max de Python
print("Máximo número con Python = ", max(lista_numeros))
# Imprimo el índice del máximo número en la lista
print("Índice del máximo número en la lista = ",
lista_numeros.index(maximo_numero))
# Imprimo cuantas veces se repite el máximo número en la lista
print("Cantidad del máximo número en la lista = ",
lista_numeros.count(maximo_numero))
if __name__ == '__main__':
print("Bienvenidos a otra clase de Inove con Python")
# bucle_while()
# bucle_for()
# contador()
# sumatoria()
# bucle_while_for()
|
99fb47e8d7b77982b52335e4d53ef5f5a05b6dc8 | nicolascordoba1/PythonIntermedio | /hangman.py | 943 | 3.5 | 4 | from random import randint
import os
def run():
with open("./archivos/data.txt", "r", encoding= "utf-8") as f:
contador = 0
palabras = []
for line in f:
palabras.append(line.rstrip())
contador +=1
numero = randint(0, contador-1)
palabra = palabras[numero]
palabra = list(palabra)
os.system("cls")
print("Empieza el juego")
#print(palabra)
palabra_actual = list("_" * len(palabra))
cant_barraspiso = len(palabra_actual)
print(palabra_actual)
while cant_barraspiso > 0: #Mientras la cantidad de "_" sea mayor a 0 ejecutese
letra = input("Adivina la palabra: ")
for i in range(len(palabra)):
if palabra[i] == letra:
palabra_actual[i] = letra
cant_barraspiso -= 1
print(palabra_actual)
if __name__ == "__main__":
run() |
6bf2e38a0c09451811be3e0f0d17b5d172b839e5 | Arselena/higher-school | /Level_0_8.py | 662 | 3.71875 | 4 | def SumOfThe(N, data):
try:
assert type(N) is int and N >= 2 and N == len(data)
for i in range(len(data)):
assert type(data[i]) is int # Проверяем Элемент массива
DATA = list(data)
SUM = None
for i in range(1, N):
if DATA[0] == sum(DATA[1:N]):
SUM = DATA[0]
break
elif DATA[N-1] == sum(DATA[0:(N-1)]):
SUM = DATA[N-1]
else:
DATA[0], DATA[i] = DATA[i], DATA[0]
return SUM
except AssertionError:
pass
print(SumOfThe(7, [100, -50, 10, -25, 90, -35, 90])) |
66a860394ed31f2c6c821d93b5ccebefe40742be | Arselena/higher-school | /Level_0_11.py | 474 | 3.875 | 4 | def BigMinus(s1, s2):
try:
assert type(s1) is str and type(s2) is str
assert s1 != '' and s2 != ''
def modul(x): # Возвращает модуль x
if x < 0:
x = x * (-1)
return x
a = int(s1)
b = int(s2)
assert 0 <= a <= (10**16) and 0 <= b <= (10**16)
s = modul(a - b) # или s = abs(a - b)
return(str(s))
except AssertionError:
pass |
57d1ca01b8dde421ca7f9e9fc001725a516febb3 | rdiazrincon/PytorchZeroToAll | /5_Linear_Regression.py | 3,039 | 4.0625 | 4 | import torch
from torch import nn
from torch import tensor
# x_data is the number of hours studied
x_data = tensor([[1.0], [2.0], [3.0], [4.0]])
# y_data is the number of points obtained
y_data = tensor([[3.0], [5.0], [7.0], [9.0]])
# e.g: 1 hour of study -> 2 points. 2 hours of study -> 4 points usw
# hours_of_study is the parameter we pass on. What we want to predict is our score
hours_of_study = 5.0
# Steps to create a Neural Network
# Step 1: Design the Model using classes
# Step 2: Define a loss function and optimizer
# Step 3: Train your model
class Model(nn.Module):
def __init__(self):
"""
In the constructor we instantiate two nn.Linear module
"""
# Initializing the Model with the class
super(Model, self).__init__()
# torch.nn.Linear applies a Linear transformation. The first parameter is the size of each input sample. The second is the size of the output sample
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
"""
In the forward function we accept a Variable of input data and we must return
a Variable of output data. We can use Modules defined in the constructor as
well as arbitrary operators on Variables.
"""
y_pred = self.linear(x)
return y_pred
# Our model
model = Model()
# Construct our loss function and an Optimizer.
# The call to model.parameters() in the SGD constructor will contain the learnable parameters of the two
# nn.Linear modules which are members of the model.
loss_function = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# for name in model.named_parameters():
# print (name)
# Other optimizers: torch.optim.Adagrad, torch.optim.Adam, torch.optim.Adamax, torch.optim.ASGD, torch.optim.LBFGS, torch.optim.RMSprop, torch.optim.Rprop, torch.optim.SGD
# Training loop
for epoch in range(500):
# 1) Forward pass: Compute predicted y by passing x to the model
y_pred = model(x_data)
# 2) Compute and print loss
# Both y_pred and y_data are tensors
loss = loss_function(y_pred, y_data)
# print(f'Epoch: {epoch} | Loss: {loss.item()} ')
# Inside the training loop, optimization happens in three steps:
# Call optimizer.zero_grad() to reset the gradients of model parameters. Gradients by default add up; to prevent double-counting, we explicitly zero them at each iteration.
optimizer.zero_grad()
# Backpropagate the prediction loss with a call to loss.backwards(). PyTorch deposits the gradients of the loss w.r.t. each parameter.
loss.backward()
# Once we have our gradients, we call optimizer.step() to adjust the parameters by the gradients collected in the backward pass.
optimizer.step()
# What we are trying to do is predict the score or points we will get if we study hours_of_study
hour_var = tensor([[hours_of_study]])
y_pred = model(hour_var)
print(f'If we study {hours_of_study} hours we will get a score of {model(hour_var).data[0][0].item()}') |
f7011fc9cd0a66c35e67f3440e67aff78ca813f6 | LeoKnox/kanji_app_a | /tree.py | 1,514 | 3.75 | 4 | class Tree:
def __init__(self, info):
self.left = None
self.right = None
self.info = info
def delNode(self, info):
if self.info == info:
print('equal')
if not self.left and not self.right:
print('a')
self.left = None
self.right = None
self.info = None
elif self.right:
print('aa')
self.left = None
self.right = None
self.info = None
else:
print('d')
elif info <= self.info:
print('e')
self.left.delNode(self.info)
elif info > self.info:
print('f')
self.delNode(self.info)
def addNode(self, info):
if self.info:
if info < self.info:
if self.left == None:
self.left = Tree(info)
else:
self.left.addNode(info)
elif info >= self.info:
if self.right == None:
self.right = Tree(info)
else:
self.right.addNode(info)
def traceTree(self):
if self.left:
self.left.traceTree()
print( self.info),
if self.right:
self.right.traceTree()
t = Tree(7)
t.addNode(8)
t.addNode(3)
t.traceTree()
t.delNode(3)
print('99999')
t.traceTree() |
5c9720ba0f06dc339f3d3054cc59a9ae573e8093 | brammetjedv/PYTAchievements | /ifstatements.py | 275 | 3.71875 | 4 | varA = 6
if ( varA == 5 ):
print("cool")
elif ( varA > 5 ):
print("kinda cool")
elif ( varA == 69 )
pass
else :
print("not cool")
varW = True
varX = True
varY = True
varZ = True
if ( (varW and varX) or (varY and varZ) ):
print("flopje")
print("end")
|
7620b60fd16105ff63f2738573db92dc2d8f3fd5 | tegupta/fulltopractice | /OOPs/using_init_method.py | 281 | 3.84375 | 4 |
class Emp(object):
def __init__(self,name,salary):
self.name=name
self.salary=salary
return None
def display(self):
print(f"The name is: {self.name}\nThe salary is:{self.salary}")
return None
emp1=Emp('Ramu', 54000)
emp1.display() |
61e3abf84388aa418bbbd5e32adbda69f0da9fb0 | Pod5GS/CS5785-Applied-Machine-Learning | /HW0/iris_plot.py | 2,920 | 3.59375 | 4 | #!/usr/bin/env python
"""
This script read Iris dataset, and output the scatter plot of the dataset.
Be sure the Iris dataset file is in the 'dataset' directory.
"""
from matplotlib import pyplot as plt
import numpy
# This function draw the labels
def draw_label(fig, label, index):
"""
:param fig: The figure instance
:param label: The text shown in the subplot
:param index: The index of subplot
"""
ax = fig.add_subplot(4, 4, index)
ax.set_xticks(()) # get rid of x axis
ax.set_yticks(()) # get rid of y axis
ax.text(0.5, # x coordinate, 0 leftmost positioned, 1 rightmost
0.5, # y coordinate, 0 topmost positioned, 1 bottommost
label, # the text which will be printed
horizontalalignment='center', # set horizontal alignment to center
verticalalignment='center', # set vertical alignment to center
fontsize=20, # set font size
)
# This function read Iris dataset into arrays and draw the scatter plot
def iris_plot():
attributes = [] # N * p array
labels = [] # label of each line of data
for line in open("F:\Cornell Tech\HW\CS5785-AML\HW0\dataset\iris.data.txt"):
if not line.split():
continue
attributes.append(line.split(',')[:4]) # first 4 elements are attributes
labels.append(line.split(',')[-1].strip('\n')) # last element is label, strip the '\n'
attributes = numpy.array(attributes) # convert N * p array to Numpy array
for i in range(len(labels)): # assign colors for each label
if labels[i] == 'Iris-setosa':
labels[i] = 'r'
elif labels[i] == 'Iris-versicolor':
labels[i] = 'g'
else:
labels[i] = 'b'
fig = plt.figure(figsize=(15., 15.)) # set figure size
fig.suptitle('Iris Data(red=setosa, green=versicolor, blue=virginica)', fontsize=30) # set figure title
count = 1 # variable used to track current sub figure to draw
for x in range(4):
for y in range(4):
if x == y: # when x equal to y, draw label
if x == 0:
draw_label(fig, 'Sepal.Length', count)
elif x == 1:
draw_label(fig, 'Sepal.Width', count)
elif x == 2:
draw_label(fig, 'Petal.Length', count)
elif x == 3:
draw_label(fig, 'Petal.Width', count)
else: # else draw the scatter plot of every 2 combinations of those 4 attributes
xs = numpy.array(attributes.T[y])
ys = numpy.array(attributes.T[x])
ax = fig.add_subplot(4, 4, count)
ax.scatter(xs, ys, c=labels)
count += 1
fig.savefig('plot.png') # save the figure
if __name__ == '__main__':
iris_plot()
|
165c2222f7e8767fc1201b609da4a4c8aabfbc6b | knotriders/programarcadegame | /pt6.2.2.py | 244 | 3.640625 | 4 | n = int(input("How many eggs?:"))
print("E.g. n: ",n)
# n = 8
for i in range(n):
for j in range(n*2):
if i in (0 , n-1) or j in (0, 2*n-1):
print("o", end = "")
else:
print(" ", end = "")
print()
|
fbbe40dbd80fa0eb0af9a22c7c1f78775dca2dca | knotriders/programarcadegame | /test2.py | 274 | 3.90625 | 4 | done = False
while not done:
quit = input("Do you want to quit? ")
if quit == "y":
done = True
else:
attack = input("Does your elf attack the dragon? ")
if attack == "y":
print("Bad choice, you died.")
done = True |
8eae2a9c399ad80545c8ac7f3d4878fcfef4285e | hmcurt01/Ivy-Plus | /printdata.py | 3,541 | 3.8125 | 4 | from data import student_dict
import pyperclip
#convert student dict into text
def printdict(value, grade):
studentamt = 0
sortednames = {}
for o in student_dict:
if student_dict[o].grade == grade:
sortednames[o] = student_dict[o].name
if value == "stats":
label = "NAME " + "|ACT |" + "C/RANK |" + "COGAT |" + "F/GEN |" + "GPA |" + "HOUSE |" +\
"L/I |" + "MINOR |" + "RACE |"
datastring = "Class of " + grade + ": \n\n" + label + "\n\n"
for i in sorted(sortednames.items(), key=lambda kv: (kv[1], kv[0])):
i = i[0]
if student_dict[i].grade == grade:
studentamt += 1
if studentamt > 20:
studentamt = 0
datastring = datastring + label + "\n\n"
datastring = datastring + short_string(student_dict[i].name[:24], 25)
for key, char in sorted(student_dict[i].__dict__.items()):
if key == "act" or key == "classrank" or key == "cogat" or key == "firstgen" or key == "gpa"\
or key == "house" or key == "lowincome" or key == "minority" or key == "race":
datastring = datastring + "|" + short_string(str(char), 8)
datastring = datastring + "|" + "\n" + "\n"
else:
datastring = "Class of " + grade + ": \n\n"
for i in sorted(sortednames.items(), key=lambda kv: (kv[1], kv[0])):
i = i[0]
if student_dict[i].grade == grade:
datastring = datastring + student_dict[i].name + ": \n"
for key, char in student_dict[i].__dict__.items():
if key != "act" and key != "classrank" and key != "cogat" and key != "firstgen" and key != "gpa" \
and key != "house" and key != "lowincome" and key != "minority" and key != "race" and key\
!= "colleges" and key != "mentees" and key != "recs" and key != "name" and key != "grade"\
and key != "Class":
if str(char).strip() == "Designate Class":
char == "Undesignated"
datastring = datastring + key.upper() + ": " + str(char) +"\n"
if key == "colleges":
datastring = datastring + "COLLEGES: "
for p in student_dict[i].colleges:
datastring = datastring + student_dict[i].colleges[p].name + ", "
datastring = datastring + "\n"
if key == "mentees":
datastring = datastring + "MENTEES: "
for p in student_dict[i].mentees:
datastring = datastring + student_dict[i].mentees[p].name + ", "
datastring = datastring + "\n"
if key == "recs":
datastring = datastring + "RECS: "
for p in student_dict[i].recs:
datastring = datastring + student_dict[i].recs[p].name + ", "
datastring = datastring + "\n"
datastring = datastring + "\n"
pyperclip.copy(datastring)
#add blank space to short string
def short_string(str, length):
if len(str) < length:
while len(str) < length-1:
str = str + " "
return str
return str
|
dcbe36488dc453401fb81abd4a01dd2fe29bcbbf | moribello/engine5_honor_roll | /tools/split_names.py | 1,231 | 4.375 | 4 | # Python script to split full names into "Last Name", "First Name" format
#Note: this script will take a .csv file from the argument and create a new one with "_split" appended to the filename. The original file should have a single column labled "Full Name"
import pandas as pd
import sys
def import_list():
while True:
try:
listname1 = sys.argv[1]
list1 = pd.read_csv(listname1)
break
except:
print(listname1)
print("That doesn't appear to be a valid file. Please try again.")
break
return list1, listname1
def split_fullnames(df, listname):
# new data frame with split value columns
new = df["Full Name"].str.split(" ", n = 1, expand = True)
# making separate first and last name columns from new data frame
df["First Name"]= new[1]
df["Last Name"]= new[0]
df = df.drop(columns=['Full Name'])
new_filename = listname[:-4]
df.to_csv(new_filename+"_split.csv", index=False)
print("Spaces removed. Changes written to file {}_split.csv.".format(new_filename))
def main():
list1, listname1 = import_list()
split_fullnames(list1, listname1)
if __name__ == "__main__":
main()
|
6ac521f4fa27b32de1192e7f2b8367ac6b86f9ea | Meet00732/DataStructure_And_Algorithms | /Breath_First_Search/BFS.py | 929 | 3.90625 | 4 | import time
graph = dict()
visited = []
queue = []
n = int(input("enter number of nodes = "))
for i in range(n):
node = input("enter node = ")
edge = list(input("enter edges = ").split(","))
graph[node] = edge
# print(graph)
def bfs(visited, graph, n):
queue.append(n)
for node in queue:
if node not in visited:
visited.append(node)
for value in graph[node]:
if value not in queue:
queue.append(value)
for node in graph.keys():
if node not in visited:
queue.append(node)
visited.append(node)
for value in graph[node]:
if value not in queue:
queue.append(value)
print(visited)
def give_time(start_time):
print("Time taken = ", time.time() - start_time)
start_time = time.time()
bfs(visited, graph, 'u')
give_time(start_time) |
50d6496496531c365527290d9d12bcf4fb1f1c5f | DanilkaZanin/vsu_programming | /Time/Time.py | 559 | 4.125 | 4 | #Реализация класса Time (из 1 лекции этого года)
class Time:
def __init__(self, hours, minutes, seconds):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def time_input(self):
self.hours = int(input('Hours: '))
self.minutes = int(input('Minutes: '))
self.seconds = int(input('Seconds: '))
def print_time(self):
print(f'{self.hours}:{self.minutes}:{self.seconds}')
time = Time(1 , 2 , 3)
time.time_input()
time.print_time() |
77c1a636b346eb0a29ce7010a249a0d13c375fb6 | shaikhul/scoring_engine | /parsers.py | 716 | 3.75 | 4 | import csv
from custom_exceptions import ParseError
class Parser(object):
def __init__(self, file_path):
self.file_path = file_path
def parse(self):
raise NotImplementedError('Parse method does not implemented')
class CSVParser(Parser):
def parse(self):
with open(self.file_path, 'rb') as f:
reader = csv.reader(f)
rows = []
try:
for row in reader:
if len(row) != 3:
raise ParseError('No of column mismatch, expected 3 got %d' % len(row))
rows.append(row)
return rows
except csv.Error as e:
raise ParseError(str(e))
|
89de0d0d8b5680f76b8150da9a93320b89e6a41b | summerpenguin/learning-CS | /ex16-4.py | 2,123 | 3.859375 | 4 | #将参数调入模块
from sys import argv
#在运行代码时需要输入的代码文件名称和需要调用的文件名称
script, filename = argv
#打印”我们将要擦除文件,文件名为格式化字符%r带标点映射文件名“
print "We're goint to erase %r." % filename
#打印”如果你不想这么做,可以按CERL-C键终止进程“
print "If you don't want that, hit CRTL-C (^C)."
#打印”如果你想这么做,请点击RETURN键“
print "If you do want that, hit RETURN."
#以”?“为提示符读取控制台的输入
raw_input("?")
#打印#开启文件。。。#
print "Opening the file..."
#为变量target赋值为开启命令,开启对象是写入状态下的文件名
target = open(filename, 'w')
#打印”正在清空文件。再见!“
print "Truncating the file. Goodbye!"
#使变量target执行truncate命令
target.truncate()
#打印”现在我将针对文本文件中的三行对你提问“
print "Now I'm going to ask you for three lines."
#以”第一行:“为提示符读取控制台的输入,并将其赋值给变量line1
line1 = raw_input("line 1: ")
#以”第二行:“为提示符读取控制台的输入,并将其赋值给变量line2
line2 = raw_input("line 2: ")
#以”第三行:“为提示符读取控制台的输入,并将其赋值给变量line3
line3 = raw_input("line 3: ")
#打印”我即将要将这些信息输入到文件中。“
print "I'm going to write these to the file."
,c
#使变量target执行write命令,材料是变量line1的赋值
target.write(line1)
#使变量target执行write命令,材料是分行符
target.write("\n")
#使变量target执行write命令,材料是变量line2的赋值
target.write(line2)
#使变量target执行write命令,材料是分行符
target.write("\n")
#使变量target执行write命令,材料是变量line3的赋值
target.write(line3)
#使变量target执行write命令,材料是分行符
target.write("\n")
#打印“于是结束了,让我们关闭文件。”
print "And finally, we close it."
#使变量target执行close命令,关闭文档并保存
target.close()
|
fb43b06f60b0b73c57a7c99814e2ad1e2d6acf15 | james-prior/python-asyncio-experiments | /mylog.py | 899 | 3.8125 | 4 | import datetime
def format_time(t):
return f'{t.seconds:2}.{t.microseconds:06}'
def log(message):
'''
prints a line with:
elapsed time since this function was first called
elapsed time since this function was previously called
message
Elapsed times are shown in seconds with microsecond resolution
although one does not know what the accuracy is.
'''
global time_of_first_call
global time_of_previous_call
now = datetime.datetime.now()
try:
time_of_first_call
except NameError:
time_of_first_call = now
time_of_previous_call = now
time_since_first_call = now - time_of_first_call
time_since_previous_call = now - time_of_previous_call
print(
format_time(time_since_first_call),
format_time(time_since_previous_call),
message,
)
time_of_previous_call = now
|
0ddd1c97e6e4b0b15dcfd7f5f09fdf19c822120a | james-prior/python-asyncio-experiments | /2-sequential-waits.py | 474 | 3.78125 | 4 | #!/usr/bin/env python3
'''
Awaiting on a coroutine.
Print “hello” after waiting for 1 second,
and then print “world” after waiting for another 2 seconds.
Note that waits are sequential.
'''
import asyncio
from mylog import log
async def say_after(delay, what):
await asyncio.sleep(delay)
log(what)
async def main():
log('main starts')
await say_after(1, 'hello')
await say_after(2, 'world')
log('main finishes')
asyncio.run(main())
|
a31c0549965ec668c0009148d5a94db2bc70225f | taysemaia/basic_python | /conjuntos.py | 437 | 3.734375 | 4 | # coding: utf-8
# Programação 1, 2018.2
# Tayse de Oliveira Maia
# Conjunto com mais elementos
numero = []
soma = 0.0
while True:
numeros = raw_input()
if numeros == 'fim':
break
soma += 1
if int(numeros) < 0:
numero.append(soma)
soma = 0.0
for i in range(len(numero)):
numero[i] = numero[i] - 1
maior = max(numero)
indice = numero.index(maior)
print "Conjunto %d - %d elemento(s)" % (indice + 1, numero[indice])
|
a9653885227248fd5605eb6b0fcc7ec6b2bb5cfc | taysemaia/basic_python | /avre.py | 270 | 3.75 | 4 | # coding: utf-8
# Programação 1, 2018.2
# Tayse de Oliveira Maia
# Arvore Natal
altura = int(raw_input())
larguramax = 2 * altura - 1
for alturas in range(altura + 1):
print ' ' * (larguramax - ( 2 * alturas - 1) / 2),
print 'o' * (2 * alturas - 1)
print (larguramax + 1) * " " + "o"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.