blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
44b20fe69d34e06ac2f6b4028e07ea3fbf079a3b
1bertovalente/PythonGustavoGuanabara
/ex010.py
146
3.859375
4
real = float(input('Valor em R$:')) #Considere dolar a 3,27 dolar = real / 3.27 print('Com R${:.2f} você comprar ${:.2f}'.format(real,dolar))
9c6162818dd837aea4117625da80438475c28ec9
worzwhere/lab_helloworld
/py_lab/input_yes.py
194
4.125
4
x = "NO" while x == "YES": x = str(input("Please type "+"YES" +": " )) while x == "YES": print("That is all right : " + (x)) break else: print("Wrong")
456eaeb9b444b5250797350f79c79c7a9dd6b78a
Max-Kaye/IT-project
/Examples/Max/Example_001.py
277
3.640625
4
import datetime start = datetime.datetime.now() print "x|y" print "===" xs = range(1, 1000001) for x in xs: y = x * x + 3 table = "{}|{}".format(x, y) print table time_taken = datetime.datetime.now() - start print("calculated results in:{}".format( time_taken))
9f7f3e1f18ba427ee83d49add67cd594eb6ea2f8
koen095/DataStruc_Alg
/playing_card.py
1,282
4.25
4
import random class PlayingCard: """A class that represents a simple playing card""" def __init__(self): """Initizalize the attributes of the playing card""" self.ranks = ['two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'jack', 'queen', 'king', 'ace'] self.suits = ['hearts', 'diamonds', 'spades', 'clubs'] self.color = ['black', 'red'] def possible_ranks(self): """Function that prints what different ranks a card can have""" print("\nA playing card can have one the following 13 ranks:") for rank in self.ranks: print(f"\t- {rank}") def possible_suits(self): """Function that prints the possible suits a card can have""" print("\nA playing card can have one the following 4 suits:") for suit in self.suits: print(f"\t- {suit}") #def possible_colors(self, suit): def generate_playing_card(self): """A function that generates a playing card with the initialized attributes""" generated_rank = random.choice(self.ranks) generated_suit = random.choice(self.suits) generated_card = f"{generated_rank} of {generated_suit}" return generated_card p1 = PlayingCard()
c4e891bf2cce7f7641668b6a18f5f3e8378dce16
pranshu798/Python-programs
/Data Types/Lists/Negative Indexing.py
244
4.5
4
List = [1,2,'Python',4,'with',6,'Pranshu'] #accessing an element using negative indexing print("Accessing element using negative indexing") #print the last element of list print(List[-1]) #print the third last element of list print(List[-3])
1be3444a22fb89c5e6a6b67f40637653a5d1636f
sigga-vala/algs4
/Notes/week_02_2/python/shell_sort.py
834
3.828125
4
#!/usr/local/bin/python # encoding: utf-8 class ShellSort(object): def sort(self, items): length = len(items) h = 1 while h < length/3: h = 3 * h + 1 while h >= 1: for i in xrange(h, length): for j in xrange(i, 0, -h): if int(items[j]) < int(items[j-h]): items[j], items[j-h] = items[j-h], items[j] else: break h /= 3 return items def solution(data_as_text, alg_class): # data = [int(x) for x in data_as_text.split(' ')] data = data_as_text sort = alg_class() return sort.sort(data) if __name__ == '__main__': res = solution([3, 9, 5, 8, 1, '5', 4, 5, 11, 6], ShellSort) print res == range(10), res # T(N) ~ N^(3/2)
ea57c4dbadbc97e2efe595ac2d9690d7b5379721
bhattanugrah/HackerRank-Solutions
/Tree_IsThisBinarySearchTree.py
416
3.90625
4
#Problem Link: https://www.hackerrank.com/challenges/is-binary-search-tree/problem def inOrder(root, tree): if root is None: return else: inOrder(root.left, tree) tree.append(root.data, tree) inOrder(tree.right, tree) def check_binary_search_tree(root): tree = [] inOrder(root, tree) if tree==sorted(set(tree)): return True else: return False
77f9784840090ce1a34dda0b57299390545ef30d
Epsilon456/WordSimilarities
/UCLAScraper.py
2,533
3.65625
4
from lxml import html import requests import random as rand import time import Setup """ This script contains the scraper which pulls the relevant data from USC's course catalog. """ def GetPage(url): """Pulls the html from the webpage. Adds a random delay between web page calls. Input: url - A string representing the desired url to visit Output An html tree """ #Adds random delay (to avoid overworking the server) time.sleep(rand.uniform(.7,4.0)) page = requests.get(url) tree = html.fromstring(page.content) print(url) return tree def UCLAScrape(): """Scrapes course data from the UCLA course catalog and returns a dictionary containing {'name':[],'description':[]} A copy of this dictionary is saved as a json file. """ #Scrape the page containing all schools. url = r'https://www.registrar.ucla.edu/Academics/Course-Descriptions' baseUrl = r'https://www.registrar.ucla.edu/' page = GetPage(url) things = page.xpath('//td[contains(@style,"width:50%;")]') Schools = {'school':[],'href':[]} #Iterate through all schools and save their paths to a list. for thing in things: name = thing.xpath('.//li/a/text()')[0].title() _href = name = thing.xpath('.//li/a')[0].values()[0] href = baseUrl+_href Schools['school'].append(name) Schools['href'].append(href) print(name) i = 0 myDictionary = {'name':[],'description':[]} #Go through each path from the first page for url in Schools['href']: print(url) print(i,"/",len(Schools['href'])) i +=1 #Get the page from the given path. page = GetPage(url) #Go through each course, save the name and description to a dictionary. courses = page.xpath('//li[contains(@class,"media category-list-item")]') for course in courses: try: name = course.xpath('.//div/h3/text()')[0].title() descripton = course.xpath('.//p[2]/text()')[0].title() myDictionary['name'].append(name) myDictionary['description'].append(descripton) except IndexError: pass #Save dictionary to json file. import json jsonFile = Setup.UCLA with open(jsonFile, 'w') as outfile: json.dump(myDictionary, outfile) print("Save dictionary as Json")
5aaec345b10e8ac6591a1b7cb0ef8cd3e6eea286
Jobinjosey/HIPC
/Assignment/chapter2/question _no_8.py
748
4.25
4
########################################Finding eigen values and EigenVectors###################################################################### import numpy as np # create numpy 2d-array m = np.array([[1, 2,-1], [2, 1,2], [-1,2,1]]) print("Printing the Original square array:\n", m) # finding eigenvalues and eigenvectors w, v = np.linalg.eig(m) # printing eigen values print("Printing the Eigen values of the given square array:\n", w) # printing eigen vectors print("Printing Right eigenvectors of the given square array:\n",v) #############################################################################################################################################################
21179e1a70410170ae4f45368a69aa2f9c7c2de9
Jorgepastorr/m03
/python/ejercicios/ips/clac-ip-chapuza.py
1,776
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ################ def my_rango(inicio,fin,incremento): while inicio <= fin : yield inicio inicio=inicio+incremento ###################################################33 print "Separa los octetos por comas." li=input("ip: ") var=0 masbred=0 cont=1 salir =False while salir == False: mascara=raw_input("mascara: b/c ") if mascara == "c": salir =True elif mascara == "b": redes=input("Cuantas redes quieres max 255: ") salir =True else: print "opción incorrecta" if mascara == "c": for fila in my_rango(1,2,1): for col in my_rango(1,4,1): if fila == 1: if col == 1: print " red ", elif col ==2: print " Primer host ", elif col ==3: print " Ultimo host ", elif col ==4: print " Brodcast ", elif fila == 2: if col == 1: print li[:3], print var," ", elif col ==2: print li[:3], print var+1," ", elif col ==3: print li[:3], print var+254," ", elif col ==4: print li[:3], print var+255," ", print "" elif mascara == "b": for fila in my_rango(1,redes,1): for col in my_rango(1,4,1): if fila == 1: if col == 1: print " red ", elif col ==2: print " Primer host ", elif col ==3: print " Ultimo host ", elif col ==4: print " Brodcast ", else : if col == 1: print cont, print li[:2], print masbred,var," ", elif col ==2: print li[:2], print masbred,var+1," ", elif col ==3: print li[:2], print masbred,var+254," ", elif col ==4: print li[:2], print masbred,var+255," ", masbred=masbred+1 print "" cont=cont+1
78f949157ccc6fbc3d7055070e2da73a32fdb811
villares/py.processing-play
/PONG/pong_procedural_com_teclado.pyde
3,778
3.53125
4
""" Pong Procedural Esta estrutura deve facilitar uma futura refacção orientada a objetos Teclas 'a' e 'z' controlam um jogador, as setas para cima e para baixo o outro. *** Tecla 'espaço' para iniciar o ponto. """ DIA_BOLA = 10 VEL_INICIAL = 4 MEIO_JOGADOR = 50 ESP_JOGADOR = 10 VEL_JOGADOR = 5 def setup(): global velX, velY size(600, 400) noStroke() prepara_jogo() # prepara o jogo, esta função normalmente recomeça o jogo velX, velY = 0, 0 # mas aqui eu logo em seguida paro a bola zerando as velocidades def draw(): background(0) if not game_over: jogadores_move() jogadores_desenha() bola_move() bola_desenha() else: escreve_game_over() def keyPressed(): global sobe_1, desce_1, sobe_2, desce_2 if key == 'a': sobe_1 = True elif key == 'z': desce_1 = True if keyCode == UP: sobe_2 = True elif keyCode == DOWN: desce_2 = True if key == ' ': prepara_jogo() def keyReleased(): global sobe_1, desce_1, sobe_2, desce_2 if key == 'a': sobe_1 = False elif key == 'z': desce_1 = False if keyCode == UP: sobe_2 = False elif keyCode == DOWN: desce_2 = False def bola_move(): global bolaX, bolaY, velX, velY, game_over bolaX, bolaY = bolaX + velX, bolaY + velY # altera posição x e y da bola usando as velocidades x e y if not(0 < bolaX < width): # se a bola sair da tela à direita ou à esquerda if jogador_rebate(1) or jogador_rebate(2): # se for rebatida pelo jogador 1 ou 2 velX = -velX # inverta a velocidade horizontal else: # senão: game_over = True # game over! if not(0 < bolaY < height): # se sair da tela por cima ou por baixo velY = -velY # inverta a velocidade vertical def bola_desenha(): fill (255, 0, 0) # vermelho ellipse(bolaX, bolaY, DIA_BOLA, DIA_BOLA) def jogadores_move(): global j1Y, j2Y if sobe_1: j1Y = j1Y - VEL_JOGADOR if desce_1: j1Y = j1Y + VEL_JOGADOR if sobe_2: j2Y = j2Y - VEL_JOGADOR if desce_2: j2Y = j2Y + VEL_JOGADOR def jogadores_desenha(): fill(0,0,255) # azul rect (0, j1Y - MEIO_JOGADOR, ESP_JOGADOR, MEIO_JOGADOR*2) rect (width - ESP_JOGADOR, j2Y - MEIO_JOGADOR, ESP_JOGADOR, MEIO_JOGADOR*2) def prepara_jogo(): # começa ou recomeça um jogo global game_over global bolaX, bolaY, velX, velY global sobe_1, desce_1, sobe_2, desce_2 global j1Y, j2Y #, j1_points, j2_points bolaX, bolaY = width/2, height/2 velX = (-VEL_INICIAL, VEL_INICIAL)[int(random(2))] velY = (-VEL_INICIAL, VEL_INICIAL)[int(random(2))] sobe_1 = desce_1 = sobe_2 = desce_2 = False j1Y = j2Y = height/2 #j1_pontos = j2_pontos = 0 game_over = False def escreve_game_over(): textSize(60) textAlign(CENTER) text("GAME OVER", width/2, height/2) def jogador_rebate(jogador): # checa se jogador 1 ou 2 rebateu com sucesso a bola if jogador == 1: return (bolaX <= 0 and j1Y - MEIO_JOGADOR < bolaY < j1Y + MEIO_JOGADOR) else: return (bolaX >= width and j2Y - MEIO_JOGADOR < bolaY < j2Y + MEIO_JOGADOR)
1717aa87fefccecf9563e3220f5ff5cdb37b34e4
isabela-dominguez/practice
/checkPermutation.py
313
3.921875
4
def checkPermutation(word1, word2): if((len(word1) != len(word2))): return False word1 = ''.join(sorted(word1)) word2 = ''.join(sorted(word2)) #if(word1 == word2): # return True #else: # return False return word1 == word2 print(checkPermutation("aabb", "bbab"))
c3f6cd3194c0c6cfc7e965b99244b82240d49779
wa57/info108
/Chapter7/ex1.py
430
4.375
4
""" 1._____ Write a while loop that lets the user enter a number. The number should be multiplied by 2, and the result assigned to a variable named “product”. The program should continue to multiply by 2 and print &quot;product&quot; out as long as “product” is less than 1000. """ number = int(input('Enter a number: ')) while number < 1000: number = number * 2 print(number) input('Press Enter to continue...')
a6f701ff420e821a70dd9f56350aa28d53657877
HarryTanNguyen/Deep-Learning-Tensoflow-file
/MeanSquErr_Tensorflow 1.py
4,594
3.78125
4
import tensorflow as tf import numpy as np import math import matplotlib.pyplot as plt import matplotlib.animation as animation ##NOTE: This template using tensorflow 1 keep in mind #generation some house sizes between 1000 and 3500 num_house = 160 np.random.seed(42) house_size=np.random.randint(low=1000,high=3500,size=num_house) #generation house price from house size with a random noise added np.random.seed(42) house_price = house_size * 100 + np.random.randint(low=20000, high=70000, size = num_house) ## ##plt.plot(house_size,house_price,"bx") ##plt.ylabel("Price") ##plt.xlabel("Size") ##plt.show() #normalize values to prevent under/overflow def normalize(array): return(array - array.mean())/array.std() #define number of training example,0.7 = 70%. We can take the first 70% #since the values are random num_train_sample = math.floor(num_house*0.7) #define training data train_house_size = np.asarray(house_size[:num_train_sample]) train_price = np.asarray(house_price[:num_train_sample]) train_house_size_norm=normalize(train_house_size) train_price_norm=normalize(train_price) #define test data test_house_size= np.array(house_size[num_train_sample:]) test_house_price = np.array(house_price[num_train_sample:]) test_house_size_norm=normalize(test_house_size) test_house_price_norm=normalize(test_house_price) #tensor types: #Constant - constant value #Variable - values adjusted in graph #PlaceHolder - used to pass data into graph #set up the TensorFlow placeholders that get updated as we descend down the gradient tf_house_size= tf.placeholder("float", name="house_size") tf_price=tf.placeholder("float",name="price") #define the variables holding the size_factor and price we set during training #we initialize them to some random values based on the normal distribution tf_size_factor=tf.Variable(np.random.randn(),name="size_factor") tf_price_offset =tf.Variable(np.random.randn(),name="price_offset") #2.Define the operation for the prediction valuse_ predicted price =(size_factor*house_size)+ price_offset #Notice, the use of the tensorflow add and multiply function tf_price_pred = tf.add(tf.multiply(tf_size_factor,tf_house_size),tf_price_offset) #3. Define the Loss Function (how much error) - Mean squared error tf_cost=tf.reduce_sum(tf.pow(tf_price_pred-tf_price,2))/(2*mum_train_samples) #Optimizer learning rate. The size of the step down the gradient learning_rate = 0.1 #4. Define a Gradient descent optimizer that will minimize the loss #defined in the operation "cost" optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(tf_cost) #initializing the varables init= tf.global_variables_initializer() #Launch the graph in the session with tf.compat.v1.Session() as sess: sess.run(init) #set how of ten to display training progress and number of training iterations display_every=2 num_training_iter=50 #keep iterating the training data for iteration in range(num_training_iter): #Fit all training data for (x,y) in zip(train_house_size_norm,train_price_norm): sess.run(optimizer,feed_dict={tf_house_size: x,tf_price: y}) #Display current status if(iteration+1)% display_every ==0: c=sess.run(tf_cost,feed_dict={tf_house_size:train_house_size_norm, tf_price:train_price_norm}) print("iteration #:",'%04d' % (iteraion+1),"cost=","{:.9f}".format(c),\ "size_factor=",sess.run(tf_size_factor),"price_offset=",sees.run(tf_price_offset)) print("Optimization Finished!") training_cost=sess.run(tf_cost, feed_dict={tf_house_size:train_house_size_norm, tf_price:train_price_norm}) print("Trained cost=",training_cost,"size_factor=",sess.run(tf_size_factor),"price_offset=",sess.run(tf_price_offset),'\n') #plot training and test data and learned regression train_house_size_mean = train_house_size.mean() train_house_size_std=train_house_size.std() train_price_mean= train_price_mean() train_price_std= train_price.std() #plot graph plt.rcParams["figure.figsize"]=(10,8) plt.figure() plt.ylabel("price") plt.xlabel("size") plt.plot(train_house_size,train_price,'go',label='training data') plt.plot(test_house_size,test_house_price,'mo',label='Testing data') plt.plot(train_house_size_norm*train_house_size_std+train_house_size_mean, (sess.run(tf_size_factor)*train_house_size_norm+sess.run(tf_price_offset))*train_price_std+train_price_mean, label='Learned regression') plt.legent(loc='upper left') plt.show()
3708b05fcff21adfffe6e12f0ba4c03547802621
slee625/python_tips
/ordereddict.py
945
4.0625
4
''' Ordered dictionary is pretty useful when we implement Queue in dictionary form ''' import collections Q = collections.OrderedDict() A = [('Foreast Gump','1988'),('Titanic','1992'),('Matrix','2003'),('Avengers I','2013'),('Benet','2020')] for x in A: Q[x[0]] = x[1] print(Q) # Pop the first element (FIFO) that was inserted to the dictionary print(Q) # OrderedDict([('Foreast Gump', '1988'), ('Titanic', '1992'), ('Matrix', '2003'), ('Avengers I', '2013'), ('Benet', '2020')]) Q.popitem(last = False) print(Q) # OrderedDict([ ('Titanic', '1992'), ('Matrix', '2003'), ('Avengers I', '2013'), ('Benet', '2020')]) # Pop (delete) the specified key print(Q) # OrderedDict([('Titanic', '1992'), ('Matrix', '2003'), ('Avengers I', '2013'), ('Benet', '2020')]) Q.pop('Matrix') print(Q) # OrderedDict([('Titanic', '1992'), , ('Avengers I', '2013'), ('Benet', '2020')])
74cc0e301f13c65f868f158ea20fdcfc70234ec3
bmk316/daniel_liang_python_solutions
/4.21.py
1,619
4.15625
4
#4.21 Zeller's formula to calculate day of the week # h is the day of the week (0: Saturday, 1: Sunday, 2: Monday, 3: Tuesday 4: Wednesday, 5: Thursday, 6: Friday). # q is the day of the month. # m is the month (3: March, 4: April, ..., 12: December). January and February are counted as months 13 and 14 of the previous year. # j is the century (i.e. year/100). # k is the year of the century (i.e., year % 100). import math saturday = "Saturday" sunday = "Sunday" monday = "Monday" tuesday = "Tuesday" wednesday = "Wednesday" thursday = "Thursday" friday = "Friday" year = eval(input("Enter the year (e.g., 2007): ")) j = math.floor(year/100) k = year % 100 m = eval(input("Enter the month: 1-12: ")) #Which month? q = eval(input("Enter the day of the month: 1-31: ")) #Day of the month h = (q + math.floor(26 * (m - 2) / 10) + k + math.floor(k / 4) + math.floor(j / 4) + 5 * j) % 7 if m == 1: m += 12 year -= 1 h = (q + math.floor(26 * (m - 2) / 10) + k + math.floor(k / 4) + math.floor(j / 4) + 5 * j) % 7 if m == 2: m += 12 year -= 1 h = (q + math.floor(26 * (m - 2) / 10) + k + math.floor(k / 4) + math.floor(j / 4) + 5 * j) % 7 print(h) if h == 0: print("Day of the week is:", saturday) elif h == 1: print("Day of the week is:", sunday) elif h == 2: print("Day of the week is:", monday) elif h == 3: print("Day of the week is:", tuesday) elif h == 4: print("Day of the week is:", wednesday) elif h == 5: print("Day of the week is:", thursday) elif h == 6: print("Day of the week is:", friday)
651b0fa1a0601fba6968fa666e42e37b683e926d
neveSZ/fatecsp-ads
/IAL-002/Listas/3-Laços de Repetição/Outros/02.py
387
4.03125
4
''' Crie um programa que leia um numero inteiro n e, em seguida leia diversos outros inteiros ate que se insira um maior que n. O programa exibira a quantidade de valores inseridos depois de n. Obs: Usar while True(repita) ''' n = int(input('n: ')) contador = 0 while True: numero = int(input('numero: ')) contador = contador + 1 if numero > n: break print(contador)
e746e686f87b097248ea157d7c11dd391461e28a
edecambra/mapreduce_python_framework
/friend_count.py
718
3.609375
4
import MapReduce import sys """ Friend Count using simple simulated social network data represented as person,friend tuples """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # key: person identifier # value: friend identifier key = record[0] value = record[1] mr.emit_intermediate(key, 1) def reducer(key, friend_counts): # key: word # value: list of occurrence counts total = 0 for f in friend_counts: total += f mr.emit((key, total)) # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
918457c210d25bd2f46a830178f8062e3652adc3
AlyssaDonchu/Harvard-CS50
/week6/readability.py
1,384
4
4
import cs50 class Solution: def readability(): string = cs50.get_string("Please, enter your text: ") letters = 0 words = 0 sentences = 0 #in this for loop we count the number of words, letters and sentences for i in string: if i.isalpha(): letters += 1 if i == " ": words += 1 if i == "." or i == "!" or i == "?": sentences += 1 #at the end I increased the word by one, because in C language we had the option to recognize the end if #string by "\0", here we count the words by " " (space) separator and that way it doesn't count the last word, #so we add it manually by increasing the word by one words += 1 #the Coleman-Liau index is computed as 0.0588 * L - 0.296 * S - 15.8, where L is the average number of #letters per 100 words in the text, and S is the average number of sentences per 100 words in the text. l = letters / words * 100 s = sentences / words * 100 grade = round(0.0588 * l - 0.296 * s - 15.8) if grade < 1: print("Before Grade 1") return(0) if grade >= 16: print("Grade 16+") return(0) else: print("Grade", grade) return(0) Solution.readability()
b7af366ceeeff3f7e7f687efa0f63a2373fe492f
CagdasAyyildiz/Python
/Scope/Global1.py
395
4.0625
4
def outer(): value = 3 print("outer value: {}".format(value)) # Output : 3 def inner(): value = 5 print("inner value: {}".format(value)) # Output : 5 inner() print("after inner value: {}".format(value)) # Output : 3 value = 0 print("called outer") outer() # Output : 3 5 3 print("Global: {}".format(value)) # Output : 0 # Global value didn't change
1ce80321be2bf728f15b3bed481cb05dadf361e1
EhsanKia/ProjectEuler
/93_ArithmeticExpressions.py
1,194
3.515625
4
import itertools import operator OPS = [operator.add, operator.sub, operator.mul, operator.truediv] def arithmetic_outputs_run_length(digits): """Computes the consecutive run length in the arithmetic outputs of 4 digits. This method computes all possible positive integer outputs that can be obtained after applying the arithmetic operations (+. -, *, /) to the 4 given digits, and then computes the longest consecutive run from 1 to n in those outputs. Args: digits: List of 4 positive digits. Returns: Longest consecutive run length """ outputs = set() for a, b, c, d in itertools.permutations(digits): for op1, op2, op3 in itertools.product(OPS, repeat=3): outputs.update([ op1(op2(op3(a, b), c), d), # (((a . b) . c) . d) op1(op2(a, b), op3(c, d)), # ((a . b) . (c . d)) ]) # Computes the length of the consecutive run from 1 to n in the outputs. return next(i for i in itertools.count(1) if i not in outputs) - 1 # Find the 4 digits that produce the longest run length print max(itertools.combinations(range(1, 10), 4), key=arithmetic_outputs_run_length)
c17fd709bdb3d8820680b0403c710f75696e7330
tawlas/python-template
/app/main.py
1,578
3.921875
4
""" The main.py file is currently used for demonstration only within this project, in order to offer a standard entry point to the whole template. The structure of the app itself is not predefined, and different apps will present different structures, hence the freedom. In this example, the main file is supposed to be called directly from an interpreter which will call the main() function. .. code-block:: python if __name__ == '__main__': main() """ def fibonacci( index: int ) -> int: """ Computes the Fibonacci number for a given index through recursion. """ result = None if index == 0: result = 0 elif index == 1: result = 1 elif index > 1: result = fibonacci( index - 1 ) + fibonacci( index - 2 ) return result def main() -> None: """ The main function within this example simply computes the first ten digits of the Fibonacci sequence. .. warning:: Using a recursive function in this instance is a waste of resources, but this is just an example. The Fibonacci number have an interesting mathematical significance, and have many applications. .. note:: See https://en.wikipedia.org/wiki/Fibonacci_number for more on the Fibonacci numbers. """ print( 'Computing the first 10 digits of the Fibonacci sequence:' ) for index in range( 0, 10 ): template = 'fibonacci({index}) = {result}' print( template.format( index = index, result = fibonacci( index ) ) ) if __name__ == '__main__': main()
b40f1182f0336f4a25b52d4a93e8b81ee17f31a8
Katarzyna-Bak/Coding-exercises
/Return Negative.py
592
4.46875
4
""" In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative? Example: make_negative(1); # return -1 make_negative(-5); # return -5 make_negative(0); # return 0 Notes: The number can be negative already, in which case no change is required. Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense. """ def make_negative(number): return abs(number)*(-1) if number != 0 else 0 print("Tests:") print(make_negative(42)) print(make_negative(-9)) print(make_negative(0))
e292d7608ff7f41fcf301cb2c79f95a259b47114
lili-n-f/Nobrega-Liliana-2021-2
/player_functions.py
6,666
3.921875
4
import pickle import os from Player import Player def register_player(players): """Función de registro de jugador: pide nombre de usuario, contraseña, edad, llama a la función para obtener el avatar que usará en la partida y guarda los datos del nuevo jugador al archivo registered_players.txt llamando a la función indicada. Args: players (dict): diccionario de jugadores ya registrados. Tiene como llaves los nombres de usuario de cada uno y como valores las instancias de la clase Player asociados a cada jugador. Raises: Exception: si la edad ingresada fue menor o igual a cero (edades inválidas). Returns: player (Player): intancia de la clase Player asociado al jugador que se acaba de registrar. """ print("\n", "REGISTRO".center(120, "-")) print("\n", "NOMBRE DE USUARIO".center(120, "-"), "\nPodrá tener caracteres alfanuméricos y una longitud máxima de 30 caracteres. \nTu nombre de usuario debe ser ÚNICO: si ya fue registrado, deberás ingresar otro.") while True: #loop infinito para realizar la validación del nombre de usuario (una vez se ingrese un nombre válido, se sale del loop) username = input("Ingresa el nombre de usuario que quieras usar (no podrás cambiarlo después):\n>") if not (username.isalnum()) or len(username) > 30: print("ERROR: Nombre de usuario inválido.\n") elif username in players: print(f"El nombre de usuario '{username}' ya fue tomado.\n") else: print("Nombre de usuario válido. ✔️") break print("\n", "CONTRASEÑA".center(120, "-"), "\nDeberá tener entre 8 y 30 caracteres. No está permitido el uso de espacios.") while True: #loop para validación de la contraseña password = input("Ingresa la contraseña a utilizar (no podrás cambiarla después):\n>") if password.count(" ") != 0 or not (8 <= len(password) <= 30): print("ERROR: contraseña inválida.\n") else: print("Contraseña válida. ✔️") break print("\n", "EDAD".center(120, "-"), "\nDebes ingresar tu edad como un número natural.") while True: try: age = int(input("Ingresa tu edad:\n>")) if age <= 0: raise Exception print("Edad válida. ✔️") break except: print("ERROR: edad inválida.\n") avatar = ask_for_avatar() print("\n✔️¡Jugador registrado exitosamente!✔️") player = Player(username, password, age, avatar) players[username] = player load_data_to_txt('registered_players.txt', players) return player def ask_for_avatar(): """Función que pregunta al usuario qué avatar quiere usar. Se le pregunta esto al usuario antes de empezar cada partida. Raises: Exception: si el usuario colocó un número fuera de range(1,6) (opción inválida para los avatares). Returns: str: nombre del avatar escogido """ print("\n", "AVATAR".center(120, "-"), "\nPara esta partida podrás escoger entre...\n\t1. Benjamín Scharifker 🏫🎓\n\t2. Eugenio Mendoza 🕴️\n\t3. Pelusa 😻\n\t4. Gandhi 👤☮️\n\t5. ✨Estudiante Estresad@✨") while True: try: avatar = int(input("\nIngresa el número del avatar que deseas usar:\n>")) if avatar in range(1,6): print("Avatar escogido exitosamente. ✔️") if avatar == 1: return 'Benjamín Scharifker' elif avatar == 2: return 'Eugenio Mendoza' elif avatar == 3: return 'Pelusa' elif avatar == 4: return 'Gandhi' elif avatar == 5: return 'Estudiante Estresad@' else: raise Exception except: print("ERROR: opción inválida.") def get_data_from_txt(file_name, data): """Función para obtener los datos serializados de un archivo txt. Args: file_name (str): nombre del archivo txt donde conseguir los datos. data (dict): datos a actualizar con los datos que se encuentran en el archivo. Returns: dict: datos obtenidos del archivo. """ while True: try: read_binary = open(file_name, 'rb') if os.stat(file_name).st_size != 0: #chequea si hay algún dato registrado que leer (es decir, si su 'size' es distinto a 0) data = pickle.load(read_binary) read_binary.close() del read_binary return data except FileNotFoundError: #si el file no existe, se crea. y como se está en un loop, se vuelve nuevamente a intentar la operación de lectura. file = open(file_name, 'w') file.close() del file def load_data_to_txt(file_name, data): """Función para cargar datos a un archivo txt mediante serialización. Args: file_name (str): nombre del archivo txt donde cargar los datos. data (dict): datos a cargar. """ write_binary = open(file_name, 'wb') data = pickle.dump(data, write_binary) write_binary.close() del write_binary del data def sign_in(players): """Función que permite que un usuario, si tiene una cuenta, ingrese a ella a partir de su nombre de usuario y contraseña. Args: players (dict): diccionario de jugadores ya registrados. Tiene como llaves los nombres de usuario de cada uno y como valores las instancias de la clase Player asociados a cada jugador. Returns: Player: si se ingresa correctamente a una cuenta (nombre de usuario y contraseña correcta) o si es necesario registrarse (ya que la función register_player también retorna una instancia de Player) """ while True: username = input("Nombre de usuario:\n>") password = input("Contraseña:\n>") if username in players and password == players[username].get_password(): print("\n✔️¡Ingreso exitoso!✔️") avatar = ask_for_avatar() players[username].set_avatar(avatar) players[username].reset_inventory() return players[username] else: print("ERROR: nombre de usuario o contraseña errada.") if input("\n¿Quieres intentar otra vez? [S] = sí, cualquier otro caracter = no, quiero registrarme\n>").lower() != 's': return register_player(players)
e7d48e8897397846f1825e4e1af3877799a8ea5c
BbillahrariBBr/python
/Book1/saarc.py
283
4.28125
4
saarc = ["Bangladesh","Afganistan","Bhutan","Nepal","India","Pakistan","Srilanka"] country = input("Enter the name of Country: ") if country in saarc: print(country, "is a member of SAARC") else: print(country, "is not a member of SAARC") print("Program terminated")
3058df82da66d3c6b7289cc895588c186d438634
reachabhi/python
/practice_exercises/partition_eve_odd.py
223
3.578125
4
def isEven(num): return num % 2 == 0 def partition(collection, fn): return [[i for i in collection if isEven(i)], [i for i in collection if not isEven(i)]] print(partition([1,2,3,4], isEven)) # [[2,4],[1,3]]
4e61e8d3e6ca00a1258a79d60cd109fc4e06afbb
Douchebag/-FOR1T05BU
/aefingaverkefni/Tuple aefingaverkefni.py
1,921
3.609375
4
#26.9.2017 #Ingvar Vigfússon #Tuples æfingaverkefni #valmynd valm="" while valm !="6": print("\n--------------") print("1. Dæmi") print("2. Dæmi") print("3. Dæmi") print("4. Dæmi") print("5. Dæmi") print("6. Hætta") print("--------------") valm=input("") if valm == "1": tupla_1 = (1, 'hallo', 'bless', 6, 'test', 'hae', 'bae') print("Stak nr.3 er:", tupla_1[2]) for x in tupla_1: print(x, end=":") elif valm == "2": tupla_2 = (['a', 'c'], [7, 4], [24, 5], ['z', 's', 'd']) # 0 1 2 3 # 0 1 0 1 0 1 0 1 2 print(tupla_2) print(tupla_2[1][1]) elif valm == "3": tupla_3 = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n') # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 print(tupla_3[4])#stak 4 er fimmti stafurinn print(tupla_3[-4])#fjórða aftasta stakið print(tupla_3[2:9])#frá 2 og upp að 9, tekur ekki 9 með elif valm == "4": tupla_4 = (1, 2, 3, 4, 5) tupla_44 = [] margfTal = int(input("Hver er margföldunar talan? ")) for x in tupla_4: margf = x * margfTal tupla_44.append(margf) print(tuple(tupla_44)) elif valm == "5": tuple_a = ('a', 'v', 'c', 'x', 'o', 'y', 'd') stafur = input("Hver er stafurinn? ") if stafur in tuple_a: print("Stafurinn", stafur, "er í tuple_a") else: print("Stafurinn", stafur, "er ekki í tuple_a") #auka er_til = False for stak in tuple_a: if stak == stafur: er_til = True break if er_til: #stytting á er_til == True print("Já") else: print("nei")
326f7a93a48056474f339a64600515e45a6963c2
klknet/geeks4geeks
/algorithm/dp/parenthesization.py
1,593
3.984375
4
""" Parenthesization Problem Given a boolean expression and operators between them. Count the number of ways we can parenthesize the expression so that the value of the expression evaluates to true. """ def count_number(express, operator): n = len(express) # t[i][j] represents the number of ways to parenthesize the symbols between i and j(both inclusive) so that the # subexpression between i and j evaluates to true. t = [[0 for i in range(n)] for j in range(n)] # t[i][j] represents the number of ways to parenthesize the symboles between i and j (both inclusive) so that the # subexpression evaluates to false. f = [[0 for i in range(n)] for j in range(n)] for i in range(n): t[i][i] = 1 if express[i] == 'T' else 0 f[i][i] = 0 if express[i] == 'T' else 1 for L in range(1, n + 1): for i in range(n - L + 1): j = i + L - 1 for k in range(i, j): tik = t[i][k] + f[i][k] tkj = t[k + 1][j] + f[k + 1][j] if operator[k] == '&': t[i][j] += t[i][k] * t[k + 1][j] f[i][j] += (tik*tkj - t[i][k] * t[k + 1][j]) elif operator[k] == '|': t[i][j] += (tik*tkj - f[i][k] * f[k + 1][j]) f[i][j] += f[i][k] * f[k + 1][j] else: t[i][j] += (t[i][k] * f[k + 1][j] + f[i][k] * t[k + 1][j]) f[i][j] += (t[i][k] * t[k + 1][j] + f[i][k] * f[k + 1][j]) return t[0][n - 1] e = "TTFT" o = "|&^" print(count_number(e, o))
bb6d6c8ea63b8c664c914d5a8fef683210fa73ed
poojamadan96/code
/string/palandrome.py
270
3.515625
4
#palandrome.py same name from front and bavck like madam name=input("Enter name") name=name.lower() name1=name[::-1] if name==name1: print("Palandrome") else: print("Not palandrome")
d3513a0acfa17419f19ccb6b80997f2b1a43cdb6
Sreyorn/Hacktoberfest2019
/beginner/python/DrawPie.py
587
3.640625
4
import math import turtle def draw_pie(t,n,r): polypie(t,n,r) t.pu() t.fd(r*2+10) t.pd() def polypie(t,n,r): angle=360/n for i in range(n): isosceles(t,r,angle/2) t.lt(angle) def isosceles(t,r,angle): y=r*math.sin(angle*math.pi/180) t.rt(angle) t.fd(r) t.lt(90+angle) t.fd(2*y) t.lt(90+angle) t.fd(r) t.lt(180-angle) bob=turtle.Turtle() bob.pu() bob.bk(130) bob.pd() size=40 draw_pie(bob,5,size) draw_pie(bob,6,size) draw_pie(bob,7,size) draw_pie(bob,8,size) draw_pie(bob,10,60) bob.hideturtle() turtle.mainloop()
b4455f2c6ea231e1d4195ecac652470a00f2dac1
ErlingLie/FysikkLab
/FysikkProject/Gjennomsnitt.py
653
3.53125
4
import math vals = [1.561, 1.533, 1.692, 1.543, 1.391, 1.526, 1.746, 1.580, 1.606, 1.654] oving3 = [0.166, 0.154, 0.184, 0.187, 0.186, 0.179, 0.162, 0.161] def mean(vals): total = 0; for i in vals: total += i total /= len(vals) return total def standardDeviation(vals): meanValue = mean(vals) total = 0 for i in vals: total += (i-meanValue)**2 total /= (len(vals) - 1) return math.sqrt(total) def standardError(vals): deviation = standardDeviation(vals) return deviation/math.sqrt(len(vals)) print(mean(oving3)) print(standardDeviation(oving3)) print(standardError(oving3))
0d9f5ab21c32ba57892eb4e97a5bfe739972baba
vebbox321/hi
/main.py
3,510
3.703125
4
''' from tkinter import * box=Tk() box.geometry("500x500") https://www.youtube.com/watch?v=bt4-FwVe1Fk&list=RDHhWum37Mg8o&index=22 username_label = Label(box,text="username").place(x=60,y=60) password_label = Label(box,text="password").place(x=60,y=100) username_text= Entry(box,width=20).place(x=140,y=60) password_text= Entry(box,width=20).place(x=140,y=100) submit_button=Button(box,text="submit").place(x=110,y=150) box.mainloop() ''' # # # pip install pafy # #pip install youtube_dl # import pafy # # from tkinter import * # # def getMetaData(video): # print("Video Details are ---") # print("video title : ",video.title) #print title # # print view count # # print(f"Total views : {video.viewcount}| video lenght : {video.lengh} secounds") # print("channel name : ",video.author) #print author # # def download_As_video(video): # getMetaData(video) #get video details # best= video.getbest() # print(f"Video Resolution:{best.resolution}\n video extension:{best.extension}") # best.download()#download the video # print("Video is downloaded...") # # # # # if __name__ == "__main__": # # url = input("Enter video url : ") # # #create instance # # video = pafy.new(url) # # download_As_video(video) # def fn(): # url=textbox.get() # video = pafy.new(url) # download_As_video(video) # # print(textbox.get()) # # frame=Tk() # # frame.geometry("300x300") # textbox = Entry(frame,width="20",textvariable="textbox") # textbox.place(x=30,y=30) # # btn = Button(frame,text="submit",command=fn).place(x=50,y=70) # frame.mainloop()\ # pip install pandas # pip install sklearn import numpy as np from sklearn.ensemble import RandomForestRegressor from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import pandas as pd def random_foerst(): candidates = {'pc': [780,750,690,710,680,730,690,720,740,690,610,690,710,680,770,610,580,650,540,590,620,600,550,550,570,670,660,580,650,660,640,620,660,660,680,650,670,580,590,690], 'load': [4,3.9,3.3,3.7,3.9,3.7,2.3,3.3,3.3,1.7,2.7,3.7,3.7,3.3,3.3,3,2.7,3.7,2.7,2.3,3.3,2,2.3,2.7,3,3.3,3.7,2.3,3.7,3.3,3,2.7,4,3.3,3.3,2.3,2.7,3.3,1.7,3.7], 'ipc': [3,4,3,5,4,6,1,4,5,1,3,5,6,4,3,1,4,6,2,3,2,1,4,1,2,6,4,2,6,5,1,2,4,6,5,1,2,1,4,5], 'vehicle':[6,4,3,1,4,6,3,4,3,5,4,6,1,4,5,1,3,5,6,4,3,1,4,6,2,3,2,1,4,1,2,6,4,2,6,5,1,2,4,6], 'speed':[70,55,40,91,30,71,40,80,30,20,20,81,91,40,70,35,23,70,40,30,30,20,30,20,45,100,80,40,71,61,40,30,51,81,71,20,30,20,40,60], 'accident': [1,1,0,1,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,0,1,0,0,0,0,1,1,0,1,1,0,0,1,1,1,0,0,0,0,1] } df = pd.DataFrame(candidates,columns= ['pc', 'load','ipc','vehicle','speed','accident']) print(df) x = df.iloc[:, 0:5].values y = df.iloc[:, 5].values print(x) print(y) xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size=.40) sc = StandardScaler() X_train = sc.fit_transform(xtrain) X_test = sc.transform(xtest) regressor = RandomForestRegressor(n_estimators=200, random_state=0) regressor.fit(X_train, ytrain) y_pred = regressor.predict(X_test) print('Mean Absolute Error:', metrics.mean_absolute_error(ytest, y_pred)) print('Mean Squared Error:', metrics.mean_squared_error(ytest, y_pred)) print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(ytest, y_pred))) random_foerst()
0d78454c8944a3cb09a458439b27455e4a82f01d
paultrigcode/lang_translation
/translator/translation/service/provider.py
872
3.5625
4
import abc class Provider ( metaclass=abc.ABCMeta ): """ Define the interface of objects the _get_service_provider method creates. """ @abc.abstractmethod def translate ( self, text, src_lang, target_lang ): """ Abstract class that will be concertedly implemented by its children classes. :param text: str :param src_lang: str :param target_lang: str :return: """ pass @abc.abstractmethod def get_supported_language_code ( self ): """ Abstract class that will be concertedly implemented by its children classes. :return: """ pass @abc.abstractmethod def get_supported_languages ( self ): """ Abstract class that will be concertedly implemented by its children classes. :return: """ pass
45f3f9f3889fe6465caec9146d11a5c3ef1a6936
cicihou/LearningProject
/leetcode-py/leetcode125.py
193
3.53125
4
class Solution: def isPalindrome(self, s: str) -> bool: res = '' for ch in s: if ch.isalnum(): res += ch.lower() return res == res[::-1]
64dd17c87ea46d8e7330723cebca555123f9f1c2
YuanZheCSYZ/algorithm
/graph/59 Spiral Matrix II.py
1,314
3.515625
4
# https://leetcode.com/problems/spiral-matrix-ii/ class Solution: """ Runtime: 32 ms, faster than 71.21% of Python3 online submissions for Spiral Matrix II. Memory Usage: 14.2 MB, less than 77.60% of Python3 online submissions for Spiral Matrix II. """ def generateMatrix(self, n: int, start=1) -> List[List[int]]: if n == 1: return [[start]] elif n == 2: return [ [start, start + 1], [start + 3, start + 2], ] last = self.generateMatrix(n - 2, n * 4 - 4 + start) for y in range(n - 2): last[y] = [start + n * 4 - 4 - y - 1] + last[y] + [start + n + y] return [[start + x for x in range(n)]] + \ last + \ [[start + n * 3 - 2 - x - 1 for x in range(n)]] """ Runtime: 37 ms, faster than 24.63% of Python3 online submissions for Spiral Matrix II. Memory Usage: 14.2 MB, less than 92.00% of Python3 online submissions for Spiral Matrix II. https://leetcode.com/problems/spiral-matrix-ii/discuss/22282/4-9-lines-Python-solutions """ def generateMatrix(self, n): A, lo = [], n * n + 1 while lo > 1: lo, hi = lo - len(A), lo A = [range(lo, hi)] + list(zip(*A[::-1])) return A
66f4e75980d8f1c3a316f3955f34a2ef1b88f679
owensheehan/ModularProgramming
/Lab5Exercise1_1.py
456
3.953125
4
# Script: Lab5Exercise1_1 # Author: Owen Sheehan # Description: Creating and accessing lists in python def main (): list1=[15,14,77,23] print("The first number in the list is",list1[0]) listLenght=len(list1) print("The Last number in the list is",list1[listLenght-1]) print("The list is",listLenght,"numbers in Lenght") list2=[]+list1 i=0 for i in range(0,listLenght): list1[i]+=1 print(list1) print(list2) main()
f398f45933ea585c6dc088ad3322594f2a202bba
corey33p/2048
/_2048_Game.py
7,779
3.578125
4
import numpy as np import random class Game: def __init__(self,board=None): self.console_print = True self.new_game(board) def print_board(self): print("----------") print("move #" + str(self.number_of_moves)) print("score: " + str(self.score)) print(str(self.board)) def undo(self): self.board,self.previous_board = self.previous_board,self.board if self.console_print: self.print_board() def new_game(self,board=None): if board is not None: assert np.all(board.shape == (4,4)) self.board = board else: self.board = np.zeros((4,4),np.int32) self.random_spawn() self.random_spawn() self.number_of_moves = 0 self.score = 0 self.previous_board = np.copy(self.board) if self.console_print: self.print_board() def random_spawn(self): empty_spots = np.argwhere(self.board == 0) random_spot = random.choice(empty_spots) if random.uniform(0,1) < .1: self.board[random_spot[0],random_spot[1]] = 4 else: self.board[random_spot[0],random_spot[1]] = 2 def move(self,direction): valid_direction = direction in ("up","right","down","left") if valid_direction: if direction == "up": move_direction = np.array([-1,0]) elif direction == "right": move_direction = np.array([0,1]) elif direction == "down": move_direction = np.array([1,0]) elif direction == "left": move_direction = np.array([0,-1]) something_moved = True board_copy = np.array(self.board) while something_moved: # input("loop") something_moved = False nonzero_locations = np.argwhere(self.board!=0) for nonzero_location in nonzero_locations: # iterate all the nonempty tiles # print("----nonzero_location: " + str(nonzero_location)) # print("----loop") current_location = nonzero_location quit_loop = False while 1: # print("--------loop") current_location = current_location + move_direction for coordinate in current_location: # check if new location valid, if not, move back and break loop if coordinate < 0 or coordinate > 3: current_location = current_location - move_direction quit_loop = True break if quit_loop: break if self.board[current_location[0],current_location[1]] != 0: current_location = current_location - move_direction break # print("--------current_location: " + str(current_location)) if np.any(current_location != nonzero_location): # print("----self.board:\n" + str(self.board)) # print("----swapping") self.board[current_location[0],current_location[1]],self.board[nonzero_location[0],nonzero_location[1]]=self.board[nonzero_location[0],nonzero_location[1]],self.board[current_location[0],current_location[1]] something_moved = True self.board = np.copy(self.board) # print("----self.board:\n" + str(self.board)) # print("board_copy55:\n" + str(board_copy)) # print("self.board55:\n" + str(self.board)) self.consolidate(direction) # print("board_copy66:\n" + str(board_copy)) # print("self.board66:\n" + str(self.board)) something_changed = not np.all(board_copy == self.board) if something_changed: # print("here77") self.previous_board = board_copy self.random_spawn() self.number_of_moves += 1 if self.console_print: self.print_board() def consolidate(self,direction): print("consolidating") valid_direction = direction in ("up","right","down","left") if valid_direction: if direction in ("left","right"): if direction == "left": for row in range(4): for col in range(1,4): if self.board[row,col-1]==self.board[row,col]: if self.board[row,col] != 0: self.board[row,col-1] = np.sum(self.board[row,col]+self.board[row,col-1]) self.score += self.board[row,col-1] self.board[row,col]=0 self.board[row,col:]=np.roll(self.board[row,col:],-1,axis=0) else: for row in range(4): for col in range(2,-1,-1): # print("what up") if self.board[row,col]==self.board[row,col+1]: if self.board[row,col] != 0: self.board[row,col+1] = np.sum(self.board[row,col]+self.board[row,col+1]) self.score += self.board[row,col+1] self.board[row,col]=0 self.board[row,:col]=np.roll(self.board[row,:col],1,axis=0) else: if direction == "up": for col in range(4): for row in range(1,4): if self.board[row-1,col]==self.board[row,col]: if self.board[row,col] != 0: self.board[row-1,col] = np.sum(self.board[row,col]+self.board[row-1,col]) self.score += self.board[row-1,col] self.board[row,col]=0 self.board[row:,col]=np.roll(self.board[row:,col],-1,axis=0) else: for col in range(4): for row in range(2,-1,-1): if self.board[row,col]==self.board[row+1,col]: if self.board[row,col] != 0: self.board[row+1,col] = np.sum(self.board[row,col]+self.board[row+1,col]) self.score += self.board[row+1,col] self.board[row,col]=0 self.board[:row,col]=np.roll(self.board[:row,col],1,axis=0) # print("here") # game = Game() # # game.board = np.array([[2,0,2,0], # # [0,2,0,2], # # [2,0,2,0], # # [0,2,0,2]]) # # game.board = np.array([[0,0,2,0], # # [0,0,0,0], # # [0,0,0,0], # # [0,0,0,0]]) # # game.board = np.array([[2,2,2,2], # # [0,0,0,0], # # [0,0,0,0], # # [0,0,0,0]]) # game.board = np.array([[0,8,0,0], # [0,8,0,0], # [0,8,0,0], # [0,8,0,0]]) # print("game.board:\n" + str(game.board)) # game.move("up") # print("game.board:\n" + str(game.board))
95773e10dfbba27b116a9741330257a2bfea8f9d
rustycoopes/a-maze-ing-game
/grid_images.py
2,339
3.640625
4
import pygame class SpriteSheet(object): """ Class used to grab images out of a sprite sheet. """ def __init__(self, file_name): """ Constructor. Pass in the file name of the sprite sheet. """ self.sprite_sheet = pygame.image.load(file_name).convert_alpha() def get_image(self, x, y, width, height): """ Grab a single image out of a larger spritesheet Pass in the x, y location of the sprite and the width and height of the sprite. """ # Create a new blank image image = pygame.Surface([width, height]).convert() # Copy the sprite from the large sheet onto the smaller image image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) # Assuming black works as the transparent color image.set_colorkey((0,0,0)) # Return the image return image def create_sprites(cell_size): """ Loads required images for games, to make an appropriately sized set of images available to the painter """ ss = SpriteSheet('images/players.png') sprite_size_H = 80 sprite_size_W = 80 player_sprites= {pygame.K_RIGHT: ss.get_image( 1 * sprite_size_W, 0 * sprite_size_H, sprite_size_W, sprite_size_H), pygame.K_LEFT: ss.get_image( 10 * sprite_size_W, 2 * sprite_size_H, sprite_size_W, sprite_size_H), pygame.K_UP: ss.get_image( 1 * sprite_size_W, 5 * sprite_size_H, sprite_size_W, sprite_size_H), pygame.K_DOWN: ss.get_image( 6 * sprite_size_W, 5 * sprite_size_H, sprite_size_W, sprite_size_H)} player_sprites[pygame.K_RIGHT] = pygame.transform.scale(player_sprites[pygame.K_RIGHT], (int(cell_size * 0.5), int(cell_size * 0.5))) player_sprites[pygame.K_LEFT] = pygame.transform.scale(player_sprites[pygame.K_LEFT], (int(cell_size * 0.5), int(cell_size * 0.5))) player_sprites[pygame.K_UP] = pygame.transform.scale(player_sprites[pygame.K_UP], (int(cell_size * 0.5), int(cell_size * 0.5))) player_sprites[pygame.K_DOWN] = pygame.transform.scale(player_sprites[pygame.K_DOWN], (int(cell_size * 0.5), int(cell_size * 0.5))) return player_sprites def create_finish(cell_size): finish = pygame.image.load('images/finish.png') finish = pygame.transform.scale(finish, (cell_size -2, cell_size -2)) return finish
046ee43c0adfb081f8e207951e03c304fb484753
katoluo/Python_Crash_Course
/chapter_10/10-2.py
879
3.6875
4
#!/usr/bin/env python3 # encoding: utf-8 # coding style: pep8 # ==================================================== # Copyright (C) 2021 All rights reserved # # Author : kato # Email : 1123629751@qq.com # File Name : 10-2.py # Last Modified : 2021-01-07 22:50 # Describe : # # ==================================================== file_name = 'learning_python.txt' with open(file_name) as file_object: contents = file_object.read() contents = contents.rstrip() print(contents.replace('Python', 'C')) print('\n') with open(file_name) as file_object: for content in file_object: content = content.rstrip() print(content.replace('Python', 'C')) print('\n') with open(file_name) as file_object: lines = file_object.readlines() for line in lines: line = line.rstrip() print(line.replace('Python', 'C'))
e426814b1845d07b53b9c76bbfc3e18e59e99452
SolanoJason/CS50W
/Lecture 2 - Python/class.py
187
3.625
4
class Point: x = "as" def __init__(self): print("Point created") self.x = "po" def square(self): print("square") x = Point() x.square() print(x.x)
6e4c8fe47c2b09e940b939280331f084e795694e
jstrnbrg/Learning-Python
/PCCourse/8.2.py
557
4.09375
4
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] while unprinted_designs: #While list is not empty, when empty it will evaluate to False current_design = unprinted_designs.pop() #Take the last item of the list, remove it and save it in current_desgn var print("Printing model: " + current_design) completed_models.append(current_design) #add current design to completed models list print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model)
1be7eff0ebcdb7228976a5d1d43a4f4066455e64
BigBricks/PythonChallenges
/HumanReadableTime.py
396
3.6875
4
def make_readable(seconds): # Do something hours = math.floor(seconds/3600) seconds = seconds - (hours*3600) minutes = math.floor(seconds/60) seconds = seconds - (minutes*60) return '{}:{}:{}'.format(add_zero(hours), add_zero(minutes), add_zero(seconds)) def add_zero(number): if number >= 10: return str(number) else: return "0" + str(number)
3c1c692bbc22cfbd864ebb59b2267038d478abf9
littlespeechless/leetcode
/23/main.py
2,266
3.84375
4
from typing import List import queue # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: if len(lists) == 0: return None lo = 0 cur = lo hi = len(lists) while lo <= hi: print(f'lo = {lo}, cur = {cur}, hi = {hi}') if lo + 1 == hi: if hi == 1: break else: lists[cur] = lists[lo] lo = 0 hi = cur + 1 cur = lo continue elif lo == hi: if cur == 1: break else: lo = 0 hi = cur cur = lo continue l1 = lists[lo] l2 = lists[lo + 1] c1 = l1 c2 = l2 c3 = ListNode() head = c3 while True: if c1 is None: if c2 is None: break else: c3.next = c2 break elif c2 is None: c3.next = c1 break if c1.val < c2.val: c3.next = c1 c1 = c1.next else: c3.next = c2 c2 = c2.next c3 = c3.next lists[cur] = head.next cur += 1 lo += 2 return lists[0] def convert(Input: List[List[int]]) -> List[ListNode]: res: List[ListNode] = [] for lst in Input: if len(lst) == 0: res.append(None) continue head = ListNode(lst[0]) head_bak = head for i in range(1, len(lst)): head.next = ListNode(lst[i]) head = head.next res.append(head_bak) return res if __name__ == '__main__': Input = [[1,4,5],[1,3,4],[2,6]] sol = Solution() lists = convert(Input) res = sol.mergeKLists(lists) print(res)
ce03577dbdfe2e4a7ed67c80d0481e06e2f3f089
csancini/Course-Overview
/week_1/HW/averages.py
315
3.9375
4
a = input("Please input the number a:") b = input("Please input the number b:") numA = float(a) numB = float(b) print("The arithmetic mean is: ", round((numA + numB)/2, 2)) print("The geometric mean is: ", round((numA*numB)**0.5, 2)) print("The root-mean-square is: ", round((((numA**2) + (numB**2))/2)**0.5, 2))
acc2e3b89c94fd96a4f9ef2e5f2a971bfcf0ddce
eoinlees/Labsheets2020
/Lab 04 - Flow/Lab04.03-average.py
539
4.1875
4
#Eoin Lees #This program reads in numbers until the user enters a 0 #The numbers are printed along with the average numbers = [] # first number tehn we check if it is 0 in the while loop number = int(input("Enter number (0 to quit): ")) while number != 0: numbers.append(number) # Read teh next number and check if 0 number = int(input("Enter number (0 to quit): ")) for value in numbers: print (value) # Average to be float average = float(sum(numbers)) / len(numbers) print ("The average is {}".format(average))
9afa73e19860e5fdc5369c1024725568d38e7d94
jessicasuse/EjerciciosPython
/EjerciciosPythonCarlos/raizCuadradaPOO.py
1,159
3.703125
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import math class EcuacionSegundoGrado: def __init__(self, a ,b ,c): self.a = a self.b = b self.c = c def solucionarEcuacion(self): if (self.errorRaizNegativaOIgualACero() == "continua"): solucion1 = (-self.b + self.calculoRaiz())/(2*self.a) solucion2 = (-self.b - self.calculoRaiz())/(2*self.a) solucionEcuacion = print("solucion1: ",solucion1 ,"solucion2: ",solucion2) else: solucionEcuacion = self.errorRaizNegativaOIgualACero() print(solucionEcuacion) def errorRaizNegativaOIgualACero(self): if(self.b**2 < 4*self.a*self.c or self.b**2 - 4*self.a*self.c == 0): mensaje = "La Ecuación no tiene solución real" else: mensaje = "continua" return mensaje def calculoRaiz (self): resultado = math.sqrt(self.b**2 -4*self.a*self.c) return resultado ecuacionSegundoGrado1 = EcuacionSegundoGrado(2, 7, 10).solucionarEcuacion()
891fd6afc2a6b5da7fe7934b0d0a75753133c4d7
MOULIES/DataStructures
/Array.py
296
3.921875
4
import array #declaration of array a = array.array('i',[]) # a = array.array('i',[1,23,56,4,9]) #initialisation of array for i in range(int(input('enter size of array'))): a.append(int(input('enter element {}'.format(i+1)))) ## 1 Traversal for i in range(len(a)): print(a[i])
041675f767ffcd88b389cb1f5004416fbb30ae52
taeyeonssupdate/leetcode
/python/AC/412. Fizz Buzz.py
605
3.734375
4
class Solution: def fizzBuzz(self, n): return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)] class mySolution: def fizzBuzz(self, n): data = [str(i) for i in range(1,n+1)] for i in range(n): if not int(data[i]) % 3 and not int(data[i]) % 5: data[i] = 'FizzBuzz' elif not int(data[i]) % 3: data[i] = 'Fizz' elif not int(data[i]) % 5: data[i] = 'Buzz' return data import json print(json.dumps(Solution().fizzBuzz(15),indent= 4, ensure_ascii=False))
6966ec8c8e614855ef493e1be6395345c57b0395
choct155/en685_621
/algorithms/covid/CaseStats.py
2,356
3.515625
4
from dataclasses import dataclass from numbers import Rational from typing import NamedTuple @dataclass class CaseStats: """ Struct holding relevant information that can be cumulatively extracted from a series of cumulative COVID-19 cases within an abritrary cell (e.g city, state, or country). Keyword arguments: stock -- Cumalitive count of cases flow -- Daily new cases max_flow -- Maximum count of new cases in a day for the days since onset avg_flow -- Average count of new cases in a day for the days since onset onset_days -- Days since the first case (inclusive of the first day) """ stock: Rational flow: Rational max_flow: Rational avg_flow: Rational onset_days: int @dataclass class CaseStatsByGeo: """ Struct holding relevant information that can be cumulatively extracted from a series of cumulative COVID-19 cases within an abritrary cell (e.g city, state, or country). Distinguished from CaseStats because of the desire to hold geographic labels in some cases. Keyword arguments: geo -- Name of the geographic area in which the cases occurred stock -- Cumalitive count of cases flow -- Daily new cases max_flow -- Maximum count of new cases in a day for the days since onset avg_flow -- Average count of new cases in a day for the days since onset onset_days -- Days since the first case (inclusive of the first day) """ geo: str stock: Rational flow: Rational max_flow: Rational avg_flow: Rational onset_days: int class CaseStatsTup(NamedTuple): """Just to play nice with pandas""" stock: Rational flow: Rational max_flow: Rational avg_flow: Rational onset_days: int class CaseStatsByGeoTup(NamedTuple): """Just to play nice with pandas""" geo: str stock: Rational flow: Rational max_flow: Rational avg_flow: Rational onset_days: int class CaseStatOps: @staticmethod def toCaseStatsTup(cs: CaseStats) -> CaseStatsTup: return CaseStatsTup(cs.stock, cs.flow, cs.max_flow, cs.avg_flow, cs.onset_days) @staticmethod def toCaseStatsByGeoTup(cs: CaseStatsByGeo) -> CaseStatsByGeoTup: return CaseStatsByGeoTup(cs.geo, cs.stock, cs.flow, cs.max_flow, cs.avg_flow, cs.onset_days)
d98278a91768510659a84a95b369141d23fc2668
DMamrenko/Project-Euler
/p50.py
1,193
3.734375
4
#Project Euler Problem #50 most_consecutives = 0 longest_chain = 0 file = open('primes.txt', 'r') primes = file.read().splitlines() def primes_below(start, n): current = start bank = [] while n > int(primes[current]): bank.append(int(primes[current])) current += 1 return bank def consecutive_primes(start, target): s = 0 #holds the sum, want it to reach the target chain = 0 #holds the length of the chain bank = primes_below(start, target) n = 0 if bank == []: return 0 while s < target: s += bank[n] n+=1 if n == len(bank): return 0 chain += 1 if s == target: return chain elif s > target: if start == len(bank)-1: return 0 else: start += 1 return consecutive_primes(start, target) for i in primes: chain = consecutive_primes(0, int(i)) if chain > longest_chain: longest_chain = chain most_consecutives = i print("{} has a new longest chain of {} primes summed.".format(most_consecutives, longest_chain))
7a85911f9904089d98f3632a05c616b1ad268757
Iverance/leetcode
/138.copy-list-with-random-pointer.py
1,429
3.65625
4
# # [138] Copy List with Random Pointer # # https://leetcode.com/problems/copy-list-with-random-pointer # # Medium (26.24%) # Total Accepted: # Total Submissions: # Testcase Example: '{}' # # # A linked list is given such that each node contains an additional random # pointer which could point to any node in the list or null. # # # # Return a deep copy of the list. # # # Definition for singly-linked list with a random pointer. # class RandomListNode(object): # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution(object): def copyRandomList(self, head): """ :type head: RandomListNode :rtype: RandomListNode """ table = {} # {oriNode: cloneNode} def getNode(node, existNodes): if node in existNodes: return existNodes[node] else: newNode = RandomListNode(node.label) table[node] = newNode return newNode dummy = RandomListNode(0) ptr_clone = dummy ptr = head while ptr: newNode = getNode(ptr, table) if ptr.random: newNode.random = getNode(ptr.random, table) ptr_clone.next = newNode ptr, ptr_clone = ptr.next, ptr_clone.next return dummy.next
2913aeaa4bc02326b87a3f32eb9404b3fc4503b4
Seancheey/CMPSC122-Homework
/evalpostfix.py
1,597
3.984375
4
# author: Qiyi Shan # Date: 3.4.2017 from Homework.linkedlist import LinkedList from Homework.vartree import VarTree def is_number(s): try: float(s) return True except ValueError: return False def eval_postfix(tree: VarTree, expr): number_stack = LinkedList() for item in expr: if is_number(item) or item.isalpha(): # item is a variable or number number_stack.push(int(item) if is_number(item) else item) else: # item is an operator b_num = number_stack.pop() a_num = number_stack.pop() if type(b_num) is str: b_num = tree.lookup(b_num) if item == '=': if a_num.isnumeric(): raise ValueError("Assign a value to a number") else: tree.assign(a_num, b_num) number_stack.push(tree.lookup(a_num)) if type(a_num) is str: if tree.lookup(a_num) is not None: a_num = tree.lookup(a_num) else: a_num = 0 if item == '+': number_stack.push(a_num + b_num) elif item == '-': number_stack.push(a_num - b_num) elif item == '*': number_stack.push(a_num * b_num) elif item == '/': number_stack.push(a_num / b_num) elif item == '%': number_stack.push(a_num % b_num) elif item == '**': number_stack.push(a_num ** b_num) if len(number_stack) == 1: if type(number_stack._head._value) is str: value = V.lookup(number_stack._head._value) return value if value is not None else 0 return number_stack._head._value else: raise SyntaxError("Too less operators: " + str(number_stack)) if __name__ == '__main__': V = VarTree() print(eval_postfix(V, ['4', '1', '4', '-', '1', '**', '-']))
15a10adee204998bc783b282b2f6824db021f217
jbobo/leetcode
/k_closest_coordinates.py
3,013
3.984375
4
#!/usr/bin/env python3 def distance(coord): """Return the distance of the given coordinate from the origin. We use manhattan distance from (0, 0), but it could be extended to use a given origin, or euclidian distance. If time is valued over space, we could compute all of the distance values ahead of time and store them in the coordinate tuples or in a hashmap. """ coord_x, coord_y = coord return (abs(coord_x) + abs(coord_y)) def partition(coords, low_pointer, high_pointer): """Lomuto's partition algo from QuickSort. This is more easily understood and more commonly used than Hoare's partition algo. We're iterating over the partition, moving all values less than the pivot value to the left side of the partition, then returning the swap_index. everything to the left of the swap index is lower than the value at the swap index. """ # swap_index, should initialize as the lowest index in the partition. swap_index = low_pointer pivot_value = distance(coords[high_pointer]) for current_index in range(low_pointer, high_pointer): if distance(coords[current_index]) <= pivot_value: # if the current value is less than the pivot value, swap them, to move # the current value to the left side of the partition. coords[swap_index], coords[current_index] = coords[current_index], coords[swap_index] # increment swap_index. swap_index += 1 # Put our pivot_value back at the swap_index. coords[swap_index], coords[high_pointer] = coords[high_pointer], coords[swap_index] return swap_index def k_closest(coords, k): """Partially sorts A[i:j+1] so the first k elements are the smallest k elements. We don't care about sorting of the elements after k. so we can get away with less than N(Log(N)) runtime complexity in most cases where k < len(coords) and k is not in non-increasing order. """ # Validation steps: Handle empty coords or k=0. if not coords or not k: return [] if k >= len(coords): return coords left = 0 right = len(coords) - 1 # Initialize the pivot point at the returned swap_index of the first run of # our quicksort partition algo. pivot = partition(coords, left, right) # We can guarantee that all indexes left of the pivot index will be less than # the pivot index. so we'll basically keep running quicksort (repeatedly # partition, shifting left or right of the current pivot point) until the # returned swap_index is at K. while pivot != k: print(pivot, left, right) if pivot > k: right = pivot - 1 elif pivot < k: left = pivot + 1 pivot = partition(coords, left, right) # return a slice of coords from 0->k () return coords[:k] if __name__ == "__main__": coords = [(1, 3), (4, -2), (-2, 2), (-3, 3), (2, -2), (5, 5)] k = 2 print(k_closest(coords, k))
0e6a57f499114cb099ab2320dfae0972cfae1c4e
bymestefe/Python_Task
/for_example/highest_score.py
538
4.28125
4
# Let's find the highest exam grade, without using the max method # En yüksek sınav notunu bulalım, max metodunu kullanmadan bulmaya çalışalım number_of_student = int(input("enter the number of students = ")) exam_grades = [] for result in range(number_of_student): exam_grade = int(input("enter exam grade = ")) exam_grades.append(exam_grade) # print(exam_results) highest_grade = exam_grades[0] for i in exam_grades: if i > exam_grades[0]: highest_grade = i print(f"Highest Grade : {highest_grade}")
1b92aa24fc14545479a424b0447d3af71d358e70
scan3ls/holbertonschool-higher_level_programming
/0x0B-python-input_output/12-student.py
571
3.671875
4
#!/usr/bin/python3 """Students """ class Student: """Muh student""" def __init__(self, first_name, last_name, age): """Constructor""" self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """Return JSONy values""" if attrs is None: return dict(self.__dict__) attrs = list(attrs) new = {} d = dict(self.__dict__) for item in attrs: if item in d: new[item] = d[item] return new
9628068eb672c49b4ab9a1e6ea1cc7e13760f05c
crystallistic/wallbreakers-hw
/week1/344.py
245
3.5
4
class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ return [s[i] for i in range(len(s)-1,-1,-1)]
334eccd17aaea798884886af8ab9151d94ee42ae
janosgyerik/advent-of-code
/2018/day9/part1.py
1,376
3.75
4
#!/usr/bin/env python import sys def compute_high_score(p, m): ''' >>> compute_high_score(9, 25) 32 >>> compute_high_score(10, 1618) 8317 >>> compute_high_score(13, 7999) 146373 >>> compute_high_score(17, 1104) 2764 >>> compute_high_score(21, 6111) 54718 >>> compute_high_score(30, 5807) 37305 >>> compute_high_score(416, 71975) 439341 ''' current_index = 0 scores = {i: 0 for i in range(p)} highest = 0 marbles = [0] for marble in range(1, m+1): if marble % 23 == 0: current_player = marble % p scores[current_player] += marble current_index = (len(marbles) + current_index - 7) % len(marbles) scores[current_player] += marbles[current_index] highest = max(highest, scores[current_player]) del marbles[current_index] continue current_index += 2 if current_index < len(marbles): marbles.insert(current_index, marble) continue if current_index == len(marbles): marbles.append(marble) continue current_index = 1 marbles.insert(current_index, marble) return highest if __name__ == '__main__': players = int(sys.argv[1]) marbles = int(sys.argv[2]) print(compute_high_score(players, marbles))
9b39e754bf0f266f1b3407700514a66ae98ec6f9
vidarmagnusson/FrodiWithAddon
/secondary_schools/courses/ruleparser.py
1,822
3.625
4
#!/usr/bin/python # -*- coding: utf-8 -*- ''' FROM THE GITHUB WIKI: A collection of semi-formal, language based rules to describe the course prerequisites. In order to automatically check the the curriculum for validity these rules should be followed (the user input box will use a guided input to help the user form the rules). All rules which do not conform to the rules are then saved as free text, and always marked specially for certifiers to look carefully at. The rules can be something like 6 credits of Mathematics courses or The course MAT2ST02H**** (The latter rule is based on the course ID, described below) ############################################################################### The parsing of text has 2 functions. 1. Support the guided entry of prerequisites. 2. Verify that a finished list of prerequisites Ekki allar reglur í belg og biðu heldur listi af stuttum strengjum sem geta: a) mappast á reglur b) vistast sem freeform texti ''' def rule_course_list(s): ''' "Eftirfarandi áfangar ISL2BL03H,ISL2BL03H,ISL2BL03H" ''' if not s.startswith('Eftirfarandi áfangar'): return False, None l = s.split(',') l[0] = l[0].split(' ')[-1] for item in l: if not is_course(item): return False, None return True, l class RuleParser(object): def __init__(self): self.rulelist = [rule_course_list] def parse_text(self, text): sentences = text.split('.') l = [process_sentence(s) for s in sentences] # build html def process_sentence(self, s): for rule in self.rulelist: is_match, result = rule(s) if is_match: return result, s def validate_curricula(self, curricula): ''' ''' pass
6117c9147983010e19c4127c11cb93ce6a65aa39
9hanyuchen/learning
/python/newYear/flower/Test/newYearTest.py
7,520
3.640625
4
import turtle as t import random import time x = -200 y = 100 # 画樱花的躯干(60,t) def Tree(branch, t): time.sleep(0.0005) if branch > 3: if 8 <= branch <= 12: if random.randint(0, 2) == 0: t.color('snow') # 白 else: t.color('lightcoral') # 淡珊瑚色 t.pensize(branch / 3) elif branch < 8: if random.randint(0, 1) == 0: t.color('snow') else: t.color('lightcoral') # 淡珊瑚色 t.pensize(branch / 2) else: t.color('sienna') # 赭(zhě)色 t.pensize(branch / 10) # 6 t.forward(branch) a = 1.5 * random.random() t.right(20 * a) b = 1.5 * random.random() Tree(branch - 10 * b, t) t.left(40 * a) Tree(branch - 10 * b, t) t.right(20 * a) t.up() t.backward(branch) t.down() # 掉落的花瓣 def Petal(m, t): for i in range(m): a = 200 - 400 * random.random() b = 10 - 20 * random.random() t.up() t.forward(b) t.left(90) t.forward(a) t.down() t.color('lightcoral') # 淡珊瑚色 t.circle(1) t.up() t.backward(a) t.right(90) t.backward(b) def txt(): t1 = (x, y) t2 = (x + 12, y - 12) # 点、 t.up() t.goto(t1) t.down() # 移动,画线 t.goto(t2) # 横 - x1 = x - 18 y1 = y - 22 t3 = (x1, y1) t4 = (x1 + 60, y1) t.up() t.goto(t3) t.down() t.goto(t4) # 点、、 x2 = x1 + 16 y2 = y1 - 10 t5 = (x2, y2) t6 = (x2 + 8, y2 - 16) t7 = (x2 + 26, y2) t8 = (x2 + 18, y2 - 18) t.up() t.goto(t5) t.down() t.goto(t6) t.up() t.goto(t7) t.down() t.goto(t8) # 长横- x3 = x1 - 15 y3 = y2 - 24 t9 = (x3, y3) t10 = (x3 + 90, y3) t.up() t.goto(t9) t.down() t.goto(t10) # 横 - x4 = x3 + 10 y4 = y3 - 22 t11 = (x4, y4) t12 = (x4 + 70, y4) t.up() t.goto(t11) t.down() t.goto(t12) # 竖 | x5 = x + 12 y5 = y3 t13 = (x5, y5) t14 = (x5, y5 - 90) t.up() t.goto(t13) t.down() t.goto(t14) # 勾 x6 = x5 y6 = y5 - 90 t15 = (x6 - 12, y6 + 10) t.goto(t15) # 点、、 x7 = x6 - 12 y7 = y5 - 40 t16 = (x7, y7) t17 = (x7 - 8, y7 - 20) t.up() t.goto(t16) t.down() t.goto(t17) t18 = (x7 + 24, y7 - 5) t19 = (x7 + 30, y7 - 16) t.up() t.goto(t18) t.down() t.goto(t19) # 撇 x8 = x + 100 y8 = y - 10 t20 = (x8, y8) t21 = (x8 - 32, y8 - 20) t.up() t.goto(t20) t.down() t.goto(t21) # 撇 t22 = (x8 - 40, y8 - 135) t.goto(t22) # 横 x9 = x3 + 100 y9 = y3 - 8 t23 = (x9, y9) t24 = (x9 + 50, y9) t.up() t.goto(t23) t.down() t.goto(t24) # 竖 x10 = x9 + 24 y10 = y9 t25 = (x10, y10) t26 = (x10, y10 - 80) t.up() t.goto(t25) t.down() t.goto(t26) nian() kuai() le() # t.done() # 年 def nian(): # 撇 x1 = x + 180 y1 = y - 10 t1 = (x1, y1) t2 = (x1 - 18, y1 - 28) t.up() t.goto(t1) t.down() t.goto(t2) # 横 x2 = x1 - 8 y2 = y - 25 t3 = (x2, y2) t4 = (x2 + 60, y2) t.up() t.goto(t3) t.down() t.goto(t4) # 横 x3 = x2 - 8 y3 = y - 65 t5 = (x3, y3) t6 = (x3 + 65, y3) t.up() t.goto(t5) t.down() t.goto(t6) # 小竖 x4 = x3 y4 = y3 - 25 t7 = (x4, y4) t.up() t.goto(t5) t.down() t.goto(t7) # 长横 x5 = x4 - 10 y5 = y4 t8 = (x5, y5) t9 = (x5 + 85, y5) t.up() t.goto(t8) t.down() t.goto(t9) # 长竖 x6 = x2 + 25 y6 = y2 t10 = (x6, y6) t11 = (x6, y6 - 120) t.up() t.goto(t10) t.down() t.goto(t11) # 快 def kuai(): # 点 x1 = x + 280 y1 = y - 65 t1 = (x1, y1) t2 = (x1 - 6, y1 - 25) t.up() t.goto(t1) t.down() t.goto(t2) # 竖 x2 = x1 + 10 y2 = y - 15 t3 = (x2, y2) t4 = (x2, y2 - 130) t.up() t.goto(t3) t.down() t.goto(t4) # 点 x3 = x2 + 10 y3 = y1 - 8 t5 = (x3, y3) t6 = (x3 + 6, y3 - 10) t.up() t.goto(t5) t.down() t.goto(t6) # 横 x4 = x3 + 25 y4 = y - 60 t7 = (x4, y4) t8 = (x4 + 60, y4) t9 = (x4 + 60, y4 - 28) t.up() t.goto(t7) t.down() t.goto(t8) t.goto(t9) # 长横 x5 = x4 - 10 y5 = y4 - 28 t10 = (x5, y5) t11 = (x5 + 90, y5) t.up() t.goto(t10) t.down() t.goto(t11) # 撇 x6 = x4 + 30 y6 = y2 - 5 t12 = (x6, y6) t13 = (x6 - 18, y6 - 125) t.up() t.goto(t12) t.down() t.goto(t13) # 捺 x7 = x6 + 8 y7 = y5 - 20 t14 = (x7, y7) t15 = (x7 + 12, y7 - 38) t.up() t.goto(t14) t.down() t.goto(t15) # 乐 def le(): # 撇 x1 = x + 510 y1 = y - 20 t1 = (x1, y1) t2 = (x1 - 65, y1 - 20) t3 = (x1 - 68, y1 - 60) t4 = (x1 + 10, y1 - 60) t.up() t.goto(t1) t.down() t.goto(t2) t.goto(t3) t.goto(t4) # 竖 x2 = x1 - 30 y2 = y1 - 35 t5 = (x2, y2) t6 = (x2, y2 - 92) t7 = (x2 - 12, y2 - 85) t.up() t.goto(t5) t.down() t.goto(t6) t.goto(t7) # 点、、 x3 = x2 - 20 y3 = y2 - 50 t8 = (x3, y3) t9 = (x3 - 8, y3 - 20) t.up() t.goto(t8) t.down() t.goto(t9) t10 = (x3 + 40, y3 - 5) t11 = (x3 + 46, y3 - 16) t.up() t.goto(t10) t.down() t.goto(t11) # 新年快乐 def xin(): # t.title('dalao 带带我') # 设置标题栏文字 # # t.hideturtle() # 隐藏箭头 # t.getscreen().bgcolor('#f0f0f0') # 背景色 # t.color('#c1e6c6', 'red') # 设置画线颜色、填充颜色,可以直接写 green,也可以用 #c1e6c6 # t.pensize(2) # 笔的大小 # t.speed(3) # 图形绘制的速度,1~10 t.up() # 移动,不画线 t.goto(0, -150) t.down() # 移动,画线 # t.begin_fill() # 开始填充 # t.goto(0, -150) t.goto(-175.12, -8.59) t.left(140) pos = [] for i in range(19): t.right(10) t.forward(20) pos.append((-t.pos()[0], t.pos()[1])) for item in pos[::-1]: t.goto(item) t.goto(175.12, -8.59) t.goto(0, -150) t.left(50) t.end_fill() # 结束填充,显示填充效果 t.done() def writePoetry(): t.penup() t.goto(400, -150) t.pencolor((255, 255, 0)) # 诗句 potery = ["但\n愿\n人\n长\n久\n", "千\n里\n共\n婵\n娟\n"] # 诗句位置(可自行设计添加), 最好2/4句五言诗 coordinates = [(300, -150), (200, -150), (100, -150)] for i, p in enumerate(potery): t.write(p, align="center", font=("STXingkai", 50, "bold")) if (i + 1) != len(potery): time.sleep(2) t.goto(coordinates[i]) import turtle as T #main() time.sleep(0.5) t.setup(1000, 700) t.screensize(1200, 1000, "wheat") t.pensize(5) t.pencolor("#ff0000") # t.speed(10) t.hideturtle() t.tracer(5, 0) t.left(90) t.up() t.backward(150) t.down() t.color('sienna') Tree(60, t) # 掉落的花瓣 Petal(30, t) t.pensize(5) t.pencolor("#ff0000") t.tracer(1, 0) txt() # t.setup(1000, 600) t.colormode(255) writePoetry() t.exitonclick()
00f64e89d3b6111427d0b3f284b63248d4479607
rahmatmaftuh/basic-python
/7_stringoperation.py
350
3.828125
4
# #untuk indexing # string_operation = "Halo Dunia" # print (string_operation) # print (string_operation[0]) # print (string_operation[1:6]) # print (len(string_operation)) #ngasih tau kalo ada berapa karakter # ''' # H a l o D u n i a # 0 1 2 3 4 5 6 7 8 9 # ''' #Merch atau menggabungkan a = "Hello" b = str(123) print(a + " " + b)
e6cb41e983fb4c40222a00a41603a18fe5389e5d
clarissadesimoni/aoc15
/day5/day5.py
1,659
3.546875
4
data = open('day5/day5.txt').read().split('\n') def listOccurrences(string, substring): count = [] if substring in string: for i in range(len(string)): if string[i:].startswith(substring): count.append(i) return count def contains3vowels(string): return sum(map(lambda x: string.count(x), ['a', 'e', 'i', 'o', 'u'])) >= 3 def containsDoubles(string): alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] for a in alphabet: if string.count(a + a) >= 1: return True return False def containsNoNaughty(string): return all(c not in string for c in ['ab', 'cd', 'pq', 'xy']) def isNice1(string): return contains3vowels(string) and containsDoubles(string) and containsNoNaughty(string) def containsRepeatingCouple(string): found = False for i in range(len(string) - 1): occ = listOccurrences(string, string[i:i + 2]) occ = list(filter(lambda o: (o - 1) not in occ, occ)) found = len(occ) - 1 > 0 if (found): break return found def containsAlternatingLetter(string): found = False for i in range(len(string) - 2): found = string[i] == string[i + 2] if (found): break return found def isNice2(string): return containsRepeatingCouple(string) and containsAlternatingLetter(string) def part1(): return len(list(filter(lambda l: isNice1(l), data))) def part2(): return len(list(filter(lambda l: isNice2(l), data))) print(f"Part 1: {part1()}") print(f"Part 2: {part2()}")
590c6535d0271e48b25e4357a15f0f4fe114ff91
Sudani-Coder/python
/Encryption Using Dictionary/index.py
752
4.09375
4
## Project: 3 # Encryption using Dictionary # i will develop my script by adding decrypthion key mother fuckers حطور الكود بتاعي من التشفير الى فك التشفير keys = { "A":"E", "B":"F", "C":"G", "D":"H", "E":"I", "F":"J", "G":"K", "H":"L", "I":"M", "J":"N", "K":"O", "L":"P", "M":"Q", "N":"R", "O":"S", "P":"T", "Q":"U", "R":"V", "S":"W", "T":"X", "U":"Y", "V":"Z", "W":"A", "X":"B", "Y":"C", "Z":"D", " ":" " } message = input("Enter the message: ").upper() def cipher(key , msg): encrypted = "" for letters in message: if letters in keys: encrypted += keys[letters] else: encrypted += letters return encrypted print(cipher(keys, message))
d1303e90dcf470fa2e4f5974fe7d248199d3259b
smartinsert/CodingProblem
/algorithmic_patterns/subsets/subsets_with_duplicates.py
875
4.0625
4
""" Given a set of numbers that might contain duplicates, find all of its distinct subsets. Example 1: Input: [1, 3, 3] Output: [], [1], [3], [1,3], [3,3], [1,3,3] Example 2: Input: [1, 5, 3, 3] Output: [], [1], [5], [3], [1,5], [1,3], [5,3], [1,5,3], [3,3], [1,3,3], [3,3,5], [1,5,3,3] """ def unique_subsets(nums: []) -> [[]]: if not nums: return [[]] subsets = [] subsets.append([]) start_idx, end_idx = 0, 0 for idx, number in enumerate(sorted(nums)): if idx > 0 and nums[idx] == nums[idx-1]: start_idx = end_idx + 1 end_idx = len(subsets) - 1 for j in range(start_idx, end_idx+1): current_subset = list(subsets[j]) current_subset.append(number) subsets.append(current_subset) return subsets print(unique_subsets([1, 3, 3])) print(unique_subsets([1, 5, 3, 3]))
11dc0cd396a311c33c1ff7a885028eb95346b01f
danbailo/Python
/Snippets/regex/foo.py
195
3.609375
4
import re text = "Dummy python text" print(re.sub("m", "-", text)) print(re.sub("m|t", "-", text)) print(re.sub("m|t|o", "-", text)) #Du--y python text #Du--y py-hon -ex- #Du--y py-h-n -ex-
4b97ba01dccd048a8111dcf1ccca897fc4555330
RED2916/Learning_Python
/A1.py
4,676
3.703125
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 28 14:56:02 2021 @author: 57553 """ import re import timeit # from testrandomcase import randomcase human_number = 0 man_number = 0 woman_number = 0 n = 0 man_finished = [0 for i in range(0,n)] woman_choice = [0 for i in range(0,n)] # transfer char list into number list def deal_char(char_list): number_list = [] for i in range(0,len(char_list)): number_list.append( int(char_list[i]) ) return number_list #deal input into acceptable data type def deal_input(input_all_split): length = len(input_all_split) global human_number global woman_number global man_number human_number = length - 4 woman_number = human_number // 2 man_number = human_number - woman_number man_list_temp = [[]for i in range(man_number)] woman_list_temp = [[]for i in range(woman_number)] #print(man_number,woman_number,human_number) temp1 = 0 temp2 = 0 for i in range(4,length): temp = deal_char(re.findall("\d+", input_all_split[i])) del temp[0] if( i%2 == 0 ): man_list_temp[temp1] = []+temp temp1 = temp1 + 1 else: woman_list_temp[temp2] = []+temp temp2 = temp2 + 1 return man_list_temp,woman_list_temp def man_index_trans( man_index ): man_real_index = (man_index + 1)//2 - 1 return man_real_index def woman_index_trans(woman_index): woman_real_index = woman_index // 2 - 1 return woman_real_index # create the inverse list of woman, the largest number represent the strongest willing def inverse_list(woman_list_input): woman_inverse_output = [[0 for i in range(0,n)] for j in range(0,n)] for i in range(0,n): for j in range(0,n): temp = man_index_trans(woman_list_input[i][j]) woman_inverse_output[i][temp] = n - j return woman_inverse_output def choice_empty_man( man_finished_input ): for i in range(0,n): if( man_finished_input[i] == -1 ): break return i # man propose to woman def man_propose(man_index_input,woman_index_input,woman_inverse): global woman_choice global man_finished if( woman_choice[woman_index_input] == -1 ): # success and kick out none man_finished[man_index_input] = woman_index_input woman_choice[woman_index_input] = man_index_input # print(man_finished,woman_choice) return 1 elif( woman_inverse[woman_index_input][man_index_input] > woman_inverse[woman_index_input][woman_choice[woman_index_input]] ): # success and kick out someone man_finished[woman_choice[woman_index_input]] = -1 man_finished[man_index_input] = woman_index_input woman_choice[woman_index_input] = man_index_input # print(man_finished,woman_choice) return 0 else: # fail return -1 def inverse_real_index(man_real_index,woman_real_index): man_index = man_real_index*2 + 1 woman_index = (woman_real_index+1) * 2 return man_index,woman_index def show_output(man_finished): for i in range(0,n): man,woman=inverse_real_index(i, man_finished[i]) print(man,woman) def main(): #get input # input_all = input(); # input_all_split = input_all.split("\n") input_all = input(); input_all_split = input_all.split("\n") global n global man_finished global woman_choice # n = int(re.findall("\d+",input_all_split[2])[0]) n = filter(str.isdigit,input_all_split[2]) n = int("".join(n)) man_finished = [-1 for i in range(0,n)] woman_choice = [-1 for i in range(0,n)] man_list,woman_list=deal_input(input_all_split) execute_number = 0 woman_inverse = inverse_list(woman_list) # matching while( execute_number < n ): man_empty = choice_empty_man( man_finished ) # print(man_empty,man_finished) for i in range(0,n): man_target = woman_index_trans(man_list[man_empty][i]) # print(man_list[man_empty],man_target) test_output = man_propose(man_empty, man_target, woman_inverse) if( test_output == 1 ): execute_number = execute_number + 1 break elif( test_output == 0 ): break # print(man_finished) show_output(man_finished) if __name__ == '__main__': # start = timeit.default_timer() main() # print(timeit.default_timer()-start)
879ef3504974c4ea18e5fe110417d23035040bc0
FilipLe/DailyInterviewPro-Unsolved
/First and Last Indices of an Element in a Sorted Array (SOLVED)/indices.py
1,189
3.609375
4
class Solution: def getRange(self, arr, target): # Fill this in. #Array to store the indices of target number indexArr = [] count = 0 #Loop to store the indices of target number while count < len(arr): #If num at this position is the same as the target number, store it in indexArr if arr[count] == target: indexArr.append(count) count += 1 #If array is empty --> target not found --> return -1 if not indexArr: return [-1,-1] #If array is not empty --> target number exists if indexArr: #Array to store the range rangeArr = [] #Store the first element from the index array (start of range) rangeArr.append(indexArr[0]) #Store the last element from the index array (end of range) rangeArr.append(indexArr[len(indexArr)-1]) return rangeArr # Test program 1 arr = [1, 2, 2, 2, 2, 3, 4, 7, 8, 8] x = 2 print(Solution().getRange(arr, x)) # [1, 4] # Test program 2 arr = [1,2,3,4,5,6,10] x = 9 print(Solution().getRange(arr, x)) # [-1, -1]
21a40dcae0679dc08cbc80c810d485aef413c451
TomMago/EulerProject
/Problem4.py
266
3.65625
4
def dec1(num1, num2): if checkpal(num1*num2): print(num1,num2,num1*num2) else: dec1(num1-1,num2) def checkpal(num): st = str(num) if st==st[::-1]: #print(num) return True for x in range(999,100,-1): dec1(999,x)
e5aa0934da7f1226440e11c08bfd4b3fd9f2ce5e
Vaishnavi-Gajinkar/Bridgelabz
/Week1/square root.py
147
3.890625
4
print("Enter a value to find its squareroot") c=int(input()) t=c ct=c/t e=pow(10,-15) while abs(t-ct)>(e*t): t=((c/t)+t)/2 ct=c/t print(t)
c5fe88c0a0889d32ea59b38fe45832f83ef396cf
steppedaxis/Python
/milestone project 1-tic tac toe game/TIC TAC TOE milestone project.py
5,873
4.125
4
def print_board(board): # THIS FUNCTION SIMPLY PRINTS THE BOARD index=0 for x in board: print('|',end=" ") print(x,end=" ") print('|',end=" ") index+=1 if index%3==0: # GO DOWN A ROW IF THE NUMBER DIVIDES WITH NO REMINDER WITH THE BOARD SIZE(IN THIS CASE 3) print(' ') def player_input(input,index,board): # THIS FUNCTION RECIEVES THE BOARD,THE PLAYER INPUT(BOARD INDEX) AND MARK(X OR O) AND THEN REPLACES THE MATCHING NUMBER ON THE BOARD WITH X OR O for x in board: if input=='X': if x==index: board[x-1]='X' elif input=='O': if x==index: board[x-1]='O' print_board(board) # PRINT THE BOARD AFTER THE PLAYER CHOOSES THE INDEX HE WANTS TO CHANGE def check_winner(playermarker,board,status): # THIS FUNCTION CHECKS THE WINNING CONDITIONS, IT TAKES THE PLAYER MARKER(X OR O),THE BOARD AND THE STATUS, AND RETURN THE STATUS AS TRUE IF ONE OF THE CODITIONS IS MET # THIS BLOCK CHECKS THE ROWS if board[0]==board[1]==board[2]==playermarker: status=True if board[3]==board[4]==board[5]==playermarker: status=True if board[6]==board[7]==board[8]==playermarker: status=True # THIS BLOCK CHECKS THE COLUMNS if board[0]==board[3]==board[6]==playermarker: status=True if board[1]==board[4]==board[7]==playermarker: status=True if board[2]==board[5]==board[8]==playermarker: status=True # THIS BLOCK CHECKS THE DIAGONALS if board[0]==board[4]==board[8]==playermarker: status=True if board[6]==board[4]==board[2]==playermarker: status=True return status # IF ONE OF THE CONDITIONS IS MET, RETURN THE STATUS AS TRUE(MEANING SOMEONE WON) board=[1,2,3,4,5,6,7,8,9] draw_index=0 #THIS COUNTER COUNTS THE AVILABLE INDEXES ON THE BOARD, IF BY ANY CHANCE IT GETS TO 9 AND NO ONE HAS WON, THEN WE KNOW THAT THERE IS A TIE print_board(board) player1='X' player2='O' gamestatus=False # THE GAME STATUS IS FALSE AT FIRST, MEANING NO ONE HAS WON YET, THE FUNCTION check_winner WILL CHANGE IT TO TRUE IF SOMEONE HAVE WON THE GAME new_game='' #THIS IS A STRING THAT RECIEVES THE PLAYER INPUT ABOUT PLAYING A NEW GAME while(gamestatus==False): #---------------PLAYER 1 INPUT AND TURN--------------------# #take inputs from player 1 player1input=int(input('player 1! please enter an index number of board\n')) while player1input>9 or player1input<0: # CHECK FOR VALID INPUT OF P1 print('wrong input, try again!') player1input=int(input()) player_input(player1,player1input,board) draw_index+=1 # INCREMENT DRAW INDEX BY 1 TILL IT GETS TO 9, THEN WE KNOW WE HAVE A DRAW SINCE THE BOARD IS FULL gamestatus_player1=check_winner(player1,board,gamestatus) # CHECK IF PLAYER 1 WINS if gamestatus_player1==True: print('player 1 wins!') print('would you like to play again? enter YES for a new game or NO to exit') # ASK THE PLAYERS IF THE WANT ANOTHER GO new_game=input() if new_game=='YES' or new_game=='yes': # IF THEY WRITE YES OR yes THEN I PRESENT THE INITIAL BOARD AGAIN,ZERO THE DRAW INDEX AND CONTINUE THE WHILE LOOP board=[1,2,3,4,5,6,7,8,9] print_board(board) draw_index=0 continue elif new_game=='NO' or new_game=='no': # IF THEY WRITE NO OR no THEN THE LOOP IS BROKEN AND THE GAME IS OVER break if draw_index==9: # CHECK THE DRAW INDEX, IF IT GETS TO 9 THEN WE HAVE A TIE print('its a draw!') print('would you like to play again? enter YES for a new game or NO to exit') new_game=input() if new_game=='YES' or new_game=='yes': board=[1,2,3,4,5,6,7,8,9] print_board(board) draw_index=0 continue elif new_game=='NO' or new_game=='no': break #----------------PLAYER 2 INPUT AND TURN ------------------------# #take input from player 2 player2input=int(input('player 2! please enter an index number of board\n')) while player2input>9 or player2input<0: # CHECK FOR VALID INPUT OF P1 print('wrong input, try again!') player2input=int(input()) player_input(player2,player2input,board) draw_index+=1 # INCREMENT DRAW INDEX BY 1 TILL IT GETS TO 9, THEN WE KNOW WE HAVE A DRAW SINCE THE BOARD IS FULL gamestatus_player2=check_winner(player2,board,gamestatus) # CHECK IF PLAYER 1 WINS if gamestatus_player2==True: print('player 2 wins!') print('would you like to play again? enter YES for a new game or NO to exit') # ASK THE PLAYERS IF THE WANT ANOTHER GO new_game=input() if new_game=='YES' or new_game=='yes': # IF THEY WRITE YES OR yes THEN I PRESENT THE INITIAL BOARD AGAIN,ZERO THE DRAW INDEX AND CONTINUE THE WHILE LOOP print('\n'*100) board=[1,2,3,4,5,6,7,8,9] print_board(board) draw_index=0 continue elif new_game=='NO' or new_game=='no': # IF THEY WRITE NO OR no THEN THE LOOP IS BROKEN AND THE GAME IS OVER break if draw_index==9: # CHECK THE DRAW INDEX, IF IT GETS TO 9 THEN WE HAVE A TIE print('its a draw!') print('would you like to play again? enter YES for a new game or NO to exit') new_game=input() if new_game=='YES' or new_game=='yes': print('\n'*100) board=[1,2,3,4,5,6,7,8,9] print_board(board) draw_index=0 continue elif new_game=='NO' or new_game=='no': break
99472b5e5673a4225054b8b3bc9b5c3420312a64
surathjhakal/data_structures-algorithim
/recursion_&_backtracking/palindrome.py
281
4.15625
4
def palindrome(p): if len(p)<1: return '' elif p[0]!=p[len(p)-1]: return False else: return palindrome(p[1:len(p)-1]) p='madam' a=palindrome(p) if a==False: print("the number is not palindrome") else: print("the number is palindrome")
e229bcd40d5515aa8b6c9b11506275a82f359ea6
ystop/algorithms
/leetcode/230. Kth Smallest Element in a BST.py
844
3.75
4
# -*- coding:utf-8 -*- # 思路:二叉搜索树, 中序遍历,有序 # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ stack = [] ret = [] node = root while stack or node: while node: stack.append(node) node = node.left temp = stack.pop() ret.append(temp.val) node = temp.right return ret[k - 1] t3 = TreeNode(3) t1 = TreeNode(1) t4 = TreeNode(4) t2 = TreeNode(2) # t3.left = t1 # t3.right = t4 # t1.right = t2 s = Solution() print s.kthSmallest(t3,1)
f680857ffabdb6beede4e6829d758c44a0133432
hellstrikes13/sudipython
/star_diamond.py
387
3.515625
4
n = input('no of lines in triange: ') if n % 2 == 0: print 'sorry i dont like even number gimme an odd number' else: count = n/2 for i in range(1,n+1,2)[:-1]: print count * ' ' + i * '*' + count * ' ' count = count - 1 count = 1 print n * '*' for k in range(n,0,-2)[1:]: print count * ' ' + k * '*' + count * ' ' count = count + 1 ''' * *** ***** ***** *** * '''
055de77fe286c3e14c5869e9e04fbcd2a9922103
elizabethmuirhead-toast/python-eliz
/fractal_tree.py
4,802
4.21875
4
""" CSC 111, Lab 9 Author: Sara Mathieson (modified from Lab 8 solution) Author: Elizabeth Muirhead and Maddy Kulke A program to draw a fractal tree using recursion. """ from graphics import * import math import random # GLOBALS theta = 0.7 # angle of each branch away from its trunk petal_color = "magenta4" # color of the petals center_color = "yellow" # color of the center of the flower sky_color = "light pink" # color of the sky/background ground_color = "dark green" # color of the ground branch_color = "navy" # color of the branches flower_lst = [] #global # CLASSES # Creases flower object class Flower: #initializes instance variable def __init__(self, x, y): # make a yellow center for the flower center = Circle(Point(x,y),2) center.setFill(center_color) center.setOutline(center_color) # set petal length and pick a random orientation for the flower petal_len = 18 angle = random.uniform(0,2*math.pi) # make four petals using helper function petal1 = self.make_petal(x, y, petal_len,angle) petal2 = self.make_petal(x, y, petal_len,angle+math.pi/2) petal3 = self.make_petal(x, y, petal_len,angle+math.pi) petal4 = self.make_petal(x, y, petal_len,angle+3*math.pi/2) # list with all the components iof the flower self.part_lst = [center, petal1, petal2, petal3, petal4] # builds and returns a petal def make_petal(self, x, y, length, angle): # first point closest to the center p1 = Point(x,y) # left-most point dx2 = length/2*math.cos(angle-0.3) dy2 = length/2*math.sin(angle-0.3) p2 = Point(x+dx2,y+dy2) # furthest point from the center dx3 = length*math.cos(angle) dy3 = length*math.sin(angle) p3 = Point(x+dx3,y+dy3) # right-most point dx4 = length/2*math.cos(angle+0.3) dy4 = length/2*math.sin(angle+0.3) p4 = Point(x+dx4,y+dy4) # create the diamond-shaped petal petal = Polygon(p1,p2,p3,p4) petal.setFill(petal_color) petal.setOutline(petal_color) return petal # draws all parts in part list of flower def draw(self, window): for part in self.part_lst: part.draw(window) # moves all parts in part list def move(self, dx, dy): for part in self.part_lst: part.move(dx, dy) # gets center of circle in part list, returns true if flower center is less than height def is_above_ground(self, y): flower_center = self.part_lst[0].getCenter() y_height = flower_center.getY() if y_height < y: return True else: return False # HELPER FUNCTIONS # recursively draws a fractal tree def draw_tree(window, order, x, y, length, angle): # compute the coordinates of end of the current branch dx = length * math.cos(angle) dy = length * math.sin(angle) x2 = x + dx y2 = y + dy # draw current branch branch = Line(Point(x,y), Point(x2,y2)) branch.setFill(branch_color) branch.setWidth(order) # make the higher order branches thicker branch.draw(window) # base case: at the leaves, draw a flower if order == 0: flower = Flower(x2,y2) flower.draw(window) flower_lst.append(flower) # recursion case: if order > 0, draw two subtrees else: new_len = length*0.7 draw_tree(window, order-1, x2, y2, new_len, angle-theta) # "left" branch draw_tree(window, order-1, x2, y2, new_len, angle+theta) # "right" branch # MAIN def main(): # set up the graphics window width = 800 height = 600 win = GraphWin("Fractal Tree", width, height) win.setBackground(sky_color) # draws the ground ground = Rectangle(Point(0,height-80), Point(width,height)) ground.setFill(ground_color) ground.setOutline(ground_color) ground.draw(win) # set up parameters for our call to the recursive function order = 6 x_start = width/2 # middle of the window y_start = height-10 # close to the bottom of the window angle = -math.pi/2 # initial branch (trunk) pointing *upwards* length = 200 # length of initial branch (trunk) # calls recursive function to draw tree draw_tree(win, order, x_start, y_start, length, angle) # loops through the flowers for f in flower_lst: # while loop checks to see if flower_Center y is less than height-20 while f.is_above_ground(height-(random.randint(20,70))): # while true, flower continues to move down by 10 f.move(0, 10) # close on click win.getMouse() win.close() main()
dbc58ac7cb3a44253c199859d4ef1aef7625f25a
atfb10/Scripts
/text_to_speech/text_to_speech.py
887
3.8125
4
# Import libraries import os from gtts import gTTS as google_text_to_speech def text_to_speech(): ''' define language as English Ask user for text to be converted Ask user for what to save file to build object of google text to speech class save object to mp3 file save object to wav file informational message standard function return ''' language = 'en' print('\nwrite text you want converted', end=': ') your_text = input() print('name wav file', end=': ') filename = input() mp3 = filename + '.mp3' wav = filename + '.wav' noise_obj = google_text_to_speech(text=your_text, lang=language, slow=False) noise_obj.save(mp3) noise_obj.save(wav) print('\n' + mp3 + ' successfully built') print(wav + ' successfully built') return # Call text to speech function text_to_speech()
e60733f586165b6f0c6df0871b6bb2faa8586a54
mycodesrb/Machine_Learning_Algorithms_Python_My_Codes
/SVR_in_SVM_Implementation_And_Visualization.py
3,428
3.953125
4
#!/usr/bin/env python # coding: utf-8 # SVM stands for Support Vector Machine. Under SVM we have Support vector Regression and Support Vector Classification both # Here we will see SVM for regression data. It's implementation is just the same for classification. The difference being # using Support Vector Classification object instead of regression. # Here, no external dataset is reffered. I have generated random numbers to simplify the understandability. # mport required libraries/packages import pandas as pd import numpy as np # Generate Data: Here, 40 random numbers are generated X= np.sort(np.random.rand(40,1),axis=0) #column wise sort X = np.sort(5 * np.random.rand(40, 1), axis=0) # 5 is just a number to increase the magnitude, any number can be taken y=np.sin(X).ravel() # Sin() to get sine of X values and Ravel() falttens it to 1D X[:5] y[:5] # Let us plot X vs y to see the sine curve import matplotlib.pyplot as plt plt.scatter(X,y) plt.legend() plt.show() # Make data frame df = pd.DataFrame(X.tolist()) #to convert array to list and then to DF df['Y']=y df.columns=['X','Y'] df.head() # Let's mplement SVR algorithm from sklearn.svm import SVR # We have 3 different kernels in SVR. We need to select the best one according to the vaues # Linear would plot like a straight line irrespective of the spread of data # Poly would plot a curve with regularization with dispersed data # RBF: Radial Based Function would plot with most of the dispersed data with maximum regularization hence it is more used. # Also, we get the lease SSE in case of RBF as compared to other two kernel types # Lets create objects for the above 3 kernels svr_lin = SVR(kernel='linear') svr_poly=SVR(kernel='poly') svr_rbf=SVR(kernel='rbf') # For linear kernel svr_lin.fit(df[['X']],df['Y']) svr_lin.score(df[['X']],df['Y']) # for Poly kernel svr_poly.fit(df[['X']],df['Y']) svr_poly.score(df[['X']],df['Y']) # for RBF kernel svr_rbf.fit(df[['X']],df['Y']) svr_rbf.score(df[['X']],df['Y']) # we see it gives the maximum score # Let us predict for all 3 kernels df['y_lin']=svr_lin.predict(df[['X']]) df['y_poly']=svr_poly.predict(df[['X']]) df['y_rbf']=svr_rbf.predict(df[['X']]) df.head(2) #Let's plot the the regression line for all three kernels plt.scatter(df['X'],df['Y'], label="Observed") plt.plot(df['X'],df['y_lin'],label="Linear") plt.plot(df['X'],df['y_poly'],label="Poly") plt.plot(df['X'],df['y_rbf'],label="rbf") plt.legend() plt.show() # Here we see that rbf has the curve with maximum values covered in its plot. #Lets check with SSE for kernels df['SE_lin']=(df['y_lin']-df['Y'])**2 df['SE_poly']=(df['y_poly']-df['Y'])**2 df['SE_rabf']=(df['y_rbf']-df['Y'])**2 df.head(2) df.sum() # we see that the minimum squared error is with RBF # Some imp points # along with kernel type, we can specify the C parameter, often termed as the regularization parameter, which specifies to SVM # optimizer how much to avois missclassifying the values # Along with kernel, C we and specify gamma parameter which defines how far the influence of a singke training example reaches # For high gamma value, only nearby values are considered but for a low gamma value. farther values are also considered. # We can get different scores by changing the values of C and gamma and can plot the curves. Depending upon the need and best # scores, the best suitable parameters can be set as final calculating arrangement.
8a7f593a47db0ae92d6553eb83d07ce4c0a79afa
menard-noe/LeetCode
/Check If It Is a Straight Line.py
498
3.703125
4
from typing import List class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: (x1, y1), (x2, y2) = coordinates[:2] for i in range(2, len(coordinates)): (x, y) = coordinates[i] if ((y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1)): return False return True if __name__ == "__main__": coordinates = [[0,0],[0,1],[0,-1]] solution = Solution() print(solution.checkStraightLine(coordinates))
5805ed538f27a7261c6a25242e836a6ba119a572
JoankaStefaniak/Kurs_Python
/03_kolekcje/zad_5_set.py
516
4.0625
4
''' 5▹ Porównaj zachowanie discard() vs remove() dla typu set. remove(elem) Remove element elem from the set. Raises KeyError if elem is not contained in the set. discard(elem) Remove element elem from the set if it is present. ''' example_set = {1, 2, 3, 4, 5, 'e', 'r', 'xyz'} print(example_set.discard(1)) print(example_set.discard(0)) print(example_set) example_set2 = {1, 2, 3, 4, 5, 'e', 'r', 'xyz'} print(example_set2.remove(1)) #print(example_set2.remove(10)) #return KeyError: 10 print(example_set2)
ac35d6dd7140398474f094aa9f308a249faba139
GDawg4/proyecto1LogicaMatematica
/proyecto1.py
500
3.53125
4
def solve(graph): size = len(graph) reach =[i[:] for i in graph] for k in range(size): for i in range(size): for j in range(size): reach[i][j] = reach[i][j] or (reach[i][k] and reach[k][j]) return reach graph = [ [0, 0, 1, 1], [1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]] solution = solve(graph) for i in range(len(solution)): print(solution[i])
064447f07565ec1000610dda22843209cff78565
zgaleday/CalTechML
/HW1/data_gen.py
7,433
3.71875
4
import numpy as np import matplotlib.pyplot as plt class DataSet: """Class to generate and manipulate a uniform distribution in 2D with a defined target function (randomly generated)""" def __init__(self, size, linear=True, threshold=0, noise=0, generate=True): self.size = size self.bools = np.ones(self.size, dtype=bool) self.points = np.random.uniform(-1, 1, (self.size, 3)) self.transform = np.empty((self.size, 6)) self.target = [0, 0, 0] self.m = 0 self.b = 0 self.linear = linear self.threshold = threshold self.noise = noise self.both_sides = False self.support_vector = np.zeros(self.size, dtype=bool) if linear: self.target_function() else: self.do_transform(self.transform, self.points) if generate: self.generate_set() """Generates a new set of points and target function for the DataSet class""" def new_set(self): if self.linear: self.target_function() self.support_vector = np.zeros(self.size, dtype=bool) for count, point in enumerate(self.points): point[0] = np.random.uniform(-1, 1) point[1] = np.random.uniform(-1, 1) if self.linear: self.classify(point, count) else: self.do_transform(self.transform, self.points) self.bools[count] = self.nonlinear_classify(point) """ Function generates a random line by choosing two points uniformly ([-1,1], [-1,1]) at random in 2D plane. The function returns the value of the slope and the value of the intercept to caller. """ def target_function(self): point_a = (np.random.uniform(-1, 1), np.random.uniform(-1, 1)) point_b = (np.random.uniform(-1, 1), np.random.uniform(-1, 1)) self.m = (point_a[1] - point_b[1]) / (point_a[0] - point_b[0]) self.b = point_a[1] - self.m * point_a[0] self.target = np.array([self.m, -1, self.b]) """ Function that generated the transform x, y, xy, x^2, y^2, 1 of the generate set of points. Params: none Return: none """ def do_transform(self, transform, array): for index,point in enumerate(array): transform[index][0] = point[0] transform[index][1] = point[1] transform[index][2] = point[1] * point[2] transform[index][3] = point[0] ** 2 transform[index][4] = point[1] ** 2 transform[index][5] = 1 """Picks what set to generate based on linear boolean in class init. Generates linear if LINEAR is True non-linear otherwise. """ def generate_set(self): if self.linear: self.linear_generate_set() else: self.quad_generate_set() """ Generates the data set. See classify method for details. If all points on one side of target generates a new set Return: none """ def linear_generate_set(self): both = None for count, point in enumerate(self.points): if count == 0: both = self.classify(point, count) point[2] = 1.0 else: point[2] = 1.0 if both != self.classify(point, count): self.both_sides = True if not self.both_sides: self.new_set() """ Generates a non-linearly classified data set. See non-linear classify for details. Params: """ def quad_generate_set(self): for count, point in enumerate(self.points): point[2] = 1.0 self.bools[count] = self.nonlinear_classify(point) """Classified the points compared to the target function. If dot is positive then classified as True or +1. If dot negative classify as -1. """ def classify(self, point, index): dot = np.dot(point, self.target) if dot > 0: self.bools[index] = True return True else: self.bools[index] = False return False """Check if classification matches for target and given input vector Param: vector and index of point Return: True if classification matches false otherwise """ def check(self, index, h): if self.linear: dot = np.dot(self.points[index], h) else: dot = np.dot(self.transform[index], h) if (dot > 0 and self.bools[index]) or (dot <= 0 and self.bools[index] == False): return True else: return False """ Compared the classification of given point with against the target function and a given vector Params: Point, vector Return: True if target and vector class ==, false otherwise """ def compare(self, point, g): dot = np.dot(point, self.target) dot_g = np.dot(point, g) if np.sign(dot) == np.sign(dot_g): return True else: return False """ Takes the points generated in the generate set function and draws a scatter containing those plots. The scatter also shows the target function. This is used as a visible conformation of the boolean assignation in generate_set() Takes vectors from generate set and m, b for the target function as params. Return 1. """ def plot_points(self, plot=False): plt.plot([((-1 - self.b) / self.m), ((1 - self.b) / self.m)], [-1, 1], 'r') for count, point in enumerate(self.points): if self.support_vector[count]: if self.bools[count]: plt.plot(point[0], point[1], 'bx') else: plt.plot(point[0], point[1], 'rx') else: if self.bools[count]: plt.plot(point[0], point[1], 'bo') else: plt.plot(point[0], point[1], 'ro') plt.ylim([-1, 1]) plt.xlim([-1, 1]) if plot: plt.show() """ Takes the points in the data set the target function and a given vector and plots them all Param: vector Return: None """ def visualize_hypoth(self, g): self.plot_points() slope, inter = self.vector_to_standard(g) plt.plot([((-1 - inter) / slope), ((1 - inter) / slope)], [-1, 1], 'b') plt.show() """ Function to take hypothesis vector and return slope and intercept Params: Hypothesis vector Return: m, b of hypothesis vector """ def vector_to_standard(self, w): m = (- 1 / w[1]) * w[0] b = (- 1 / w[1]) * w[2] return m, b """ A function classify points according to a non-linear target. Has a toggle function that either adds or removes noise to the target function. Target will be of the form x^2 + y^2 - threshold Params: Threshold of quad target (float), point to be classified, and noise in the classification (prob of miscalc 0-1). Return: True if sign x_1^2 + x_2^2 - threshold positive, False otherwise. """ def nonlinear_classify(self, point): temp = np.sign(point[0] ** 2 + point[1] ** 2 - self.threshold) det = np.random.random() if (temp == 1 and det < self.noise) or (temp != 1 and det > self.noise): return True else: return False
fa771e4a2cfdc487069a456fa47cdef385c61fe5
llgeek/leetcode
/3_LongestSubstringWithoutRepeatingCharacters/solution.py
754
3.5625
4
""" O(n) use set """ class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ start, end = 0, 0 maxlen = 0 charset = set() nowlen = 0 for end in range(len(s)): if s[end] not in charset: nowlen += 1 charset.add(s[end]) else: maxlen = max(maxlen, nowlen) while s[start] != s[end]: charset.discard(s[start]) start += 1 nowlen -= 1 start += 1 return max(maxlen, nowlen) if __name__ == "__main__": s = " " sol = Solution() print(sol.lengthOfLongestSubstring(s))
56c7411cc95df6b0399ca8992e69d659babad8b9
lemoonbox/algorithm_std
/search/02.linked_list.py
1,241
4.15625
4
#1. linked list 생성기 #2. link 삽입기 원하는 데이터와 index 순서를 입력하면 삽입 class Node: def __init__(self, data, next=None): self.data = data self.next = next class LinkedList: def __init__(self, head = None): self.head = head def create_list(self, datalist): now_node = Node(datalist[0]) self.head= now_node for i in range(1, len(datalist)): new_node = Node(datalist[i]) now_node.next = new_node now_node = new_node def prt_allnode(self): now_node = self.head while 1: print("",now_node.data, end="") if now_node.next == None: break now_node = now_node.next def insertnode(self, data, index =0): new_node = Node(data) now_node = self.head if index == 0: self.head = new_node self.head.next = now_node return for i in range(0, index-2): now_node = now_node.next new_node.next = now_node.next now_node.next = new_node linklist = LinkedList() linklist.create_list([1,2,3,4,5]) linklist.prt_allnode() linklist.insertnode(10, 6) linklist.prt_allnode()
45aa55c72959087c7e7fde398108b46987628f47
Velrok/python-game-of-life
/main.py
2,321
3.609375
4
#!/usr/bin/env python import time import random from itertools import chain import os from collections import deque def create_world(width, height, population_prob): return [ [1 if (random.random() <= population_prob) else 0 for _ in range(width)] for _ in range(height)] def render_world(world, cycle): def output_mapper(x): if x == 1: return "#" else: return " " print "cycle: {}".format(cycle) for row in world: print "|{}|".format( "".join( map(output_mapper, row))) def new_cell_state(state, neighbors): alive_neighbors_count = sum(chain(*neighbors)) # print "neighbors: " + str(neighbors) # print "alive_neighbors_count:" + str(alive_neighbors_count) # print "state:" + str(state) if (state == 1): # alive # print "alive" alive_neighbors_count -= 1 # sub this alive cell from sum if(alive_neighbors_count == 2 or alive_neighbors_count == 3): return 1 else: return 0 else: # dead cell # print "dead" if(alive_neighbors_count == 3): return 1 else: return 0 def element_at(x, y, world): w_height = len(world) w_width = len(world[0]) if x < 0 or y < 0 or x >= w_width or y >= w_height: return 0 else: return world[y][x] def neighbors(x, y, world): return [[ element_at(x + dx, y + dy, world) for dx in range(-1, 2)] for dy in range(-1, 2)] def next_state(world): return [[new_cell_state(cell, neighbors(x, y, world)) for x, cell in enumerate(row)] for y, row in enumerate(world)] def spawn_beacon(x, y, world): new_world = world coords = [(0,0), (1,0), (1,1), (0,1), (2,2), (2,3), (3,3), (3,2)] for dx, dy in coords: new_world[y + dy][x + dx] = 1 return new_world def all_equal(l): def eq(tup): return tup[0] == tup[1] return all(map(eq, zip(list(l)[1:], list(l)))) if __name__ == "__main__": world = create_world(50, 20, 0.4) world = spawn_beacon(1,1, world) cycle = 0 laste_states = deque([world], maxlen=5) while not all_equal(laste_states) or len(laste_states) < 5: os.system('clear') render_world(world, cycle) world = next_state(world) laste_states.append(world) cycle += 1 time.sleep(0.2) print "world stabe -> quit"
7ebb219103cd7bdcde11b896cd9e0fbe32f750e9
JennyShalai/Python-basics
/python-string-and-list.py
3,068
4.3125
4
# INTRO TO PYTHON (numeric data and basic math operations ) int, float, complex snake_case_naming_convention if elif else while continue, break, pass # STRINGS AND LISTS str str(value) # casting to string + # concatenate strings *n #repeat string n times strip() #removes the trailing space  strip() #returns a new string after removing any leading and trailing whitespaces including tabs (\t). rstrip() #returns a new string with trailing whitespace removed. It’s easier to remember as removing white spaces from “right” side of the string. lstrip() #returns a new string with leading whitespace removed, or removing whitespaces from the “left” side of the string. capitalize() upper() lower() replace(value, new_value) split() # list (array) of words isupper() # bool endswith() len(string) # length string[i] # chat at I position count(value) # count words in string isnumeric() # returns true if all characters in the string are numeric isalpha() # returns true if all characters in the string are alphabetic "-".join("a", "b", "c") # return "a-b-c", join() string[i,j] # chars from i to j-1 positions string[N:] # remover first N chars string[:N] # leaves first N chars string[:-N] # removes last N chars string[-N:] # leaves last N chars '012345'[:2] # 01 '012345'[2:] # 2345 '012345'[:-2] # 0123 '012345'[-2:] # 45 '012345'[::2] # 024 - every second char '012345'[1:5:2] #135 in range from 1 to (5-1) position take every second char string.index("x") #method index() returning the position of the first "x" in the string # !!! So ‘:’ is a separator to set a range for string slicing, # if no number is given it mean “from the beginning of the sting # till N position” like so [:N], or “from N position till the end # of the sting” like so [N:] while index < len(string): print(string[index]) index += 1 for index in range(len(string)): print(string[index]) for char in string: print(char) format(parameter) # string formatting # print(‘Hello, {}!’.format(‘John’)) # print(‘Hello, {0}! I am {1}’.format(‘John’, ‘Jen’)) # print('%d %s %.4f.' % (2, 'formatting', 3.1415)) -> 2 formatting 3.1415. # list is an array in swift list = [1, ‘hi’, 4.5] list('hello') # ['h', 'e', 'l', 'l', 'o'] len(list) # number of elements in list append(value) # add new value at the end of the list append(index, value) #add new value to the index position pop() # delete last element in list and return it’s value pop(index) # pop() by index remove() # delete last element of the list reverse() sort() # sort from small to big list[index] list[start_index:end_index] # sublist of elements from start_index till (end_index-1) list[-1] # last element list[:] # all elements list[::3] # every 3rd element for element in list: print(element) for index, element in enumerate(list): print(index, element) # list comprehension in_list = ['SPAM', 'Spam', 'spam'] answer = [value.lower() for value in in_list] # what to do # with what #from where
6bdfdf708589ab0a62a1f5503bbad86849cfb4cc
shenhongcai/algorithm
/insertSort.py
1,059
3.921875
4
""" @Project Name: pycharmproj @Author: Shen Hongcai @Time: 2019-03-19, 10:52 @Python Version: python3.6 @Coding Scheme: utf-8 @Interpreter Name: PyCharm """ import timeit def insertSort(arr): for i in range(1, len(arr)): current = arr[i] index = i # 每次遍历开始,都将游标指向当前元素(待比较) # 将要插入的元素与已经排好的子序列中的元素从后往前逐一比较,直到找到一个比待插入元素小的 while arr[index-1] > current and index > 0: arr[index] = arr[index-1] index = index-1 arr[index] = current return arr if __name__ == "__main__": test = [9, 8, -3, 5, 13, 1, 2, -10, -12, 15] insertSort(test) time1 = timeit.Timer(stmt="insertSort(test),test", setup="from __main__ import insertSort, test") print("插入排序的时间:%s s" % time1.timeit(1)) print(insertSort(test)) # 使用lambda 推导 print("插入排序的时间:%s s" % timeit.Timer(lambda: insertSort(test)).timeit(1))
0e38ddaaa9c2a1d702a9218265670d61ff20459f
supvenka/pythonSamples
/functionsLocalGlobal.py
808
3.75
4
total = 0 # Global Scope myTotal =0; def sum(a,b): total = a + b print "Inside function , total = ", total sum(10,20) print "OutSide function , total = ", total # now from inside the function I want to update the global variable total def updateGlobal(a,b): global myTotal myTotal = a + b print "Inside function , total = ", myTotal updateGlobal(10,30) print "myTotal outside", myTotal def sumAll(a,b): global total, counter total = a + b counter +=1 print "Inside sumAll function , total = ", total #print "counter outside", counter #functiona taking function as argument def doOperations(operation, a, b): operation(a,b) doOperations(sum,1,2) def subtract (a,b): print a-b doOperations(subtract,10,5)
ca7f67bc7f0d33ddcc40dcb16a9422bda54ac7ae
Anil314/HackerEarth-Solutions
/Bit Manipulation/Flash vs Katmos.py
1,717
3.765625
4
''' Katmos is the sole survivor and former ruler of an iron-based race that ruled the Earth 8 million years ago until nearly all of them were wiped out by a comet. When an archaeologist frees Katmos after he takes control of their mind, he uses his mind control gun on the archaeologist to further his power. Deciding to take over the world, Katmos begins activities, for attracting the attention of the Flash. The fastest man alive battles the prehistoric humanoid but before that, Katmos plants bomb to several places in Central City. these bombs are programmed to be a blast in order of the binary equivalent of place numbers. which place number has least ON bits blast will occur first and so on. Help Flash by sorting the place numbers where he needs to reach first to save that place. NOTE: In case of same no. of ON bits, the smallest index will take place first. Input: The first line of input contains an integer T, where T is the number of test cases. The first line of each test case contains N, where N is the number of Places. The second line of each test case contains an array of places, where ith element of an array represents a single place number. Output: For each test case print in a separate line and sorted place numbers separated by space. SAMPLE INPUT 1 4 2 5 6 1 SAMPLE OUTPUT 2 1 5 6 Explanation: in first test case, 4 places are given as 2 5 6 1 and no. of ON bits in 2 is one, in 5 is two, in 6 is two and in 1 is one. based on the given input output will be 2 1 5 6 ''' t=int(input()) for i in range(t): n=int(input()) a= [int(x) for x in input().split()] d=sorted(a, key= lambda x: str(bin(x)).count("1")) d=[str(x) for x in d] print(" ".join(d))
0360e696438fb61adc83a61ae53e36c1f5e0bc21
VettiEbinyjar/py-learning
/3-sequence-types/1-lists.py
527
3.875
4
# ipAddress = input('IP: ') ipAddress = '192.02.244.225' print(ipAddress.count('.')) print('=======================================================') even = [2, 4, 6, 8] odd = [1, 3, 5, 7] odd.append(9) # append numbers = odd + even numbers2 = numbers numbers.sort() # sort existing list, NOT return new list sortedNumbers = sorted(numbers2) # sorting that returns a list print(numbers) print(numbers2) if numbers == sortedNumbers: # TRUE print('Lists are equal')
959ef0f7c32ddd203e18a727cd7aaf0ad0ea5e57
pumbaacave/atcoder
/Leetcode/GetIntersectionNode.py
1,036
3.609375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None import copy class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ def cal_len(head): print(id(head)) cnt = 0 while head: cnt += 1 print(id(head)) head = head.next return cnt # ca, cb = copy.copy(headA), copy.copy(headB) lenA, lenB = cal_len(headA), cal_len(headB) if lenA < lenB: # headA is longer headA, headB = headB, headA delta = abs(lenA - lenB) while delta: delta -= 1 headA = headA.next while headA and headB and headA.val != headB.val: headA = headA.next headB = headB.next if headA: return headA else: return None
1c1fabba61fa1f9706222ece5352ea47dba68292
sobko/SpaceGame2
/pygame_space.py
1,908
3.546875
4
import pygame from random import randint pygame.init() screen = pygame.display.set_mode((800,600)) pygame.display.set_caption("Space Game") #set up sprites and other variables enemies = [] bullets = [] ship_rect = [300,500,45,27] ship_image = pygame.image.load('ship.png') enemy_image = pygame.image.load('enemy.png') gameover = False clock = pygame.time.Clock() #game loop starts here while not gameover: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: gameover = True #other key events here that happen ONCE when you press if event.key == pygame.K_SPACE: bullet = pygame.Rect(ship_rect[0] + 22, ship_rect[1], 5, 5) bullets.append(bullet) #keys that you can hold down: keys = pygame.key.get_pressed() if keys[pygame.K_RIGHT]: ship_rect[0] += 5 if keys[pygame.K_LEFT]: ship_rect[0] -= 5 #actions that happen automatically. if randint(1, 10) == 1: new_enemy = pygame.Rect(randint(0, 760), -50, 40, 33) enemies.append(new_enemy) #move stuff for enemy in enemies: enemy[1] += 10 for bullet in bullets: bullet[1] -= 8 #handle collisions for enemy in enemies.copy(): for bullet in bullets.copy(): if enemy.colliderect(bullet): enemies.remove(enemy) bullets.remove(bullet) #clear the screen screen.fill((0,0,0)) #draw stuff screen.blit(ship_image, ship_rect) for enemy in enemies: screen.blit(enemy_image, enemy) for bullet in bullets: pygame.draw.ellipse(screen, (200,200,0), bullet) #show the new screen (60x per second). pygame.display.flip() pygame.quit()
e366c36625e74324e2e40962e6932398d3c114b4
giorgi01/fibonacci-checker
/fibonacci.py
520
3.78125
4
def fibonacci_num(lst): index1 = 0 index2 = 1 for i in lst: index1 += 1 index2 += 1 if index1 >= len(lst) or index2 >= len(lst): break if lst[index2] == lst[index1] + i: if index1 == len(lst) - 2: print("ფიბონაჩის მიმდევრობაა") break else: print("ფიბონაჩის მიმდევრობა არაა") break
6a32ad44f18f142ebd0997575efccd7ea3dd61c2
edu-athensoft/stem1401python_student
/py200622_python2/day02_py200625/ex/func_1_yixuan.py
220
3.875
4
""" yixuan """ def adding2(x, y, z): sum = x + y + z return sum # adding n1, n2, n3 n1 = 10 n2 = 20 n3 = 30 result = adding2(n1,n2,n3) print("{n1} + {n2} + {n3} = {res}".format(n1=n1, n2=n2, n3=n3, res=result))
57f592401527e20e86633c809cd3bee2ea4da2ad
r2d209git/pythonpractice
/Contact/contact.py
2,388
3.9375
4
class Contact: def __init__(self, name, phone_number, e_mail, addr): self.name = name self.phone_number = phone_number self.e_mail = e_mail self.addr = addr def print_info(self): print("Name: ", self.name) print("Phone Number: ", self.phone_number) print("E-mail: ", self.e_mail) print("Address: ", self.addr) def set_contact(): name = input("Name: ") phone_number = input("Phone Number: ") e_mail = input("E-mail: ") addr = input("Address: ") contact = Contact(name, phone_number, e_mail, addr) return contact def print_contact(contact_list): for contact in contact_list: contact.print_info() def delete_contact(contact_list, name): # for i, contact in enumerate(contact_list): for contact in contact_list: if contact.name == name: contact_list.remove(contact) # del contact_list[i] def store_contact(contact_list): file = open("D:\\Python\\prj\\learnpython\\file\\contact_db.txt", 'wt') for contact in contact_list: file.write(contact.name + ':' + contact.phone_number + ':' + contact.e_mail + ':' + contact.addr + '\n') file.close() def load_contact(contact_list): try: file = open("D:\\Python\\prj\\learnpython\\file\\contact_db.txt", 'rt') except FileNotFoundError: pass else: lines = file.readlines() for line in lines: name, phone_number, e_mail, addr = line.split(":") contact = Contact(name, phone_number, e_mail, addr) contact_list.append(contact) #finally: file.close() def print_menu(): print("1. 연락처 입력") print("2. 연락처 출력") print("3. 연락처 삭제") print("4. 종료") menu = input("메뉴 선택: ") return int(menu) def run(): contact_list = list() load_contact(contact_list) while True: menu = print_menu() if menu == 1: contact = set_contact() contact_list.append(contact) elif menu == 2: print_contact(contact_list) elif menu == 3: name = input("Name: ") delete_contact(contact_list, name) elif menu == 4: store_contact(contact_list) break else: pass if __name__ == "__main__": run()
81c3e8cd14bac8a8b61afd2921b0c0312c860e42
rajatkashyap/Python
/StringReverse.py
529
3.546875
4
str=raw_input('Input a string') ln=len(str) str1='' str2='' str3='' x=1 y=0 for l in range(ln-1,-1,-1): str2=str2+str[l] print str2 str2='' for i in range(ln-1,-1,-1): str2=str2+str[i] print str2 for letter in str[::-1]: str3=str3+letter while ln>0 : ln=ln-1 str1=str1+str[ln] print str1 #print str2 #print str3 while x: x=raw_input('Input a no, -1 to exit') x=int(x) if x==-1: break y=y+x print 'The sum is', y #print reversed(str) #print ''.join(reversed(str))
a60757055471195c9ddfb76915874be53e94ba9a
OleksandrLozinskyy/Hillel_Python_Lessons
/Lesson9/2d_array_columns_sort_pandas.py
1,475
3.921875
4
# Start off by importing the pandas module import pandas import sys from random import randrange while True: column_count = input("Введите размер массива для генерации (column_count должен быть больше 5): ") if str(column_count) == 'q': sys.exit() elif not str(column_count).isdigit() or int(column_count) <= 5: print('Введенное значение не удовлетворяет требованию. Значение должно быть целым числом больше 5.\n \ Попробуйте еще раз или нажмите q для выхода.') continue else: break print(f'Исходный массив будет иметь размер М*М - {column_count}*{column_count}') column_count = int(column_count) # Создаем исходный массив М*М gen_arr = [[randrange(1, 50) for i in range(column_count)] for _ in range(column_count)] for i in range(len(gen_arr)): if i % 2 == 0: gen_arr[i] = sorted(gen_arr[i], reverse=True) else: gen_arr[i] = sorted(gen_arr[i], reverse=False) #print(gen_arr) #print('\n\n') # Clean data, create dataframe and calculate columns sum arr_df = pandas.DataFrame(gen_arr) totals_list = arr_df.sum(axis=1).tolist() #print(totals_list) #print('\n\n') arr_df['Total'] = totals_list arr_df = arr_df.transpose() print(arr_df.to_string(index=False, header=False))
0fb6516a17e969b1ccdc89329fd7ae690c35b292
ICPM-submission/Online-Predictive-Process-Monitoring
/OPPM/components/labeling.py
1,742
3.828125
4
class labeler(): """ Base labeling function: current implementation is value-occurence Initiate by setting various values, call to check or get label """ def __init__(self, outcomes:set, positive_outcomes:set, feature:str, positive_label=1, negative_label=0): """ Initiate labeling function Parameters: outcomes (set): The set of outcomes to represent a label positive_outcomes (set): The outcomes to return a 'positive' label feature (str): The feature to look for the set of outcomes positive_label (str): The label to return as positive label negative_label (str): The label to return as negative label """ self.outcomes = outcomes self.positive_outcomes = positive_outcomes self.feature = feature self.positive_label = positive_label self.negative_label = negative_label def check(self, x): """ Quick set comprehension check if feature is in outcomes """ if x[self.feature] in self.outcomes: return True else: return False def get(self, x): """ Retrieve the actual label """ return self.positive_label if x[self.feature] in self.positive_outcomes else self.negative_label def check_get(self, x): """ Set comprehension to see if feature in outcomes: - If feature is in outcomes, return outcome - Otherwise, return None """ if x[self.feature] in self.outcomes: return self.positive_label if x[self.feature] in self.positive_outcomes else self.negative_label else: return None
c726fcbd1d3287cb9d739572c9cff7d040ef788f
annapooranikuthalingam/python_crash_course
/chapter9/exercise_9_2_three_restaurants.py
487
4.09375
4
""" 9-2. Three Restaurants: Start with your class from Exercise 9-1. Create three different instances from the class, and call describe_restaurant() for each instance. """ from exercise_9_1_restaurant import Restaurant restaurant_1=Restaurant('McDonalds','American') restaurant_2=Restaurant('TacoBell','Mexican') restaurant_3=Restaurant('Chaat House','Indian') restaurant_1.describe_restaurant() restaurant_2.describe_restaurant() restaurant_3.describe_restaurant()
5d688e664bd3e05d5a23f12a320fd7761a59f40c
kameranis/Project_Euler
/Problem 12 - Highly Divisible Triangular Number/highdiv.py
457
3.609375
4
""" Highly Divisible Triangular Number Finds the first triangular number which has over 500 divisors Konstantinos Ameranis 13.9.2013 """ import math def highdiv(y, x): count = 0 for i in range(1, int(math.sqrt(x))): if x % i ==0: count += 2 if x % int(math.sqrt(x)) == 0: count += 1 if count > 500: return False else: return True summ = 1 i = 1 while highdiv(i, summ): i += 1 summ += i print summ
3c95f17c6989c4fcb9d1e79990903beae74a1ad2
franktea/acm
/uva.onlinejudge.org/uva 156 - Ananagrams/156.py
585
3.515625
4
words = [] line = input() while line != "#": words.extend(line.split()) line = input() class WordItem: def __init__(self, word): self.original = word changed = [c for c in word.lower()] changed.sort() self.key = ''.join(changed) self.times = 1 all_dict = {} for word in words: wi = WordItem(word) if not wi.key in all_dict: all_dict[wi.key] = wi else: all_dict[wi.key].times += 1 result = [x.original for x in all_dict.values() if x.times == 1] result.sort() for r in result: print(r)
5c7e7cfc4a3945d61272ab47cf81730695a5c480
netdevmike/python-programming
/Module2/Ch02_ex20.py
813
4.65625
5
# Write a program that prompts for an integer and prints the integer, but if something other than an integer is input, the program keeps asking for an integer. Here is a sample session: # Input an integer: abc # Error: try again. Input an integer: 4a Error: try again. Input an integer: 2.5 Error: try again. # Input an integer: 123 The integer is: 123 # Hint: The string isdigit method will be useful. # Get integer input num = input("Enter an integer number: ") # Look executes until input is other than integer while num.isdigit() == False: # display the error message and get another input num = input("Error: trye again, Enter an integer number: ") else: # convert the input to integer number_int = int(num) # Display the integer number print("The integer number is: ", number_int)
4b7cdccb3cb25ea3bdefdf29dc7cd3d47f77b2b5
AK-1121/code_extraction
/python/python_28496.py
255
3.578125
4
# What is the Pythonic way of doing this? &gt;&gt;&gt; dataList = ['Jim 5656 qwgh', 'Tim 5833 qwgh'] &gt;&gt;&gt; [dict(zip(['name', 'sknum'], s.split())) for s in dataList] [{'name': 'Jim', 'sknum': '5656'}, {'name': 'Tim', 'sknum': '5833'}]