blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
109107bcb725f8d9f683055f03d141db5b0c8a7a
zangfans/pythonstack
/modle/module.py
957
3.515625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:zangfans time:2019/10/12 import math import random import statistics import keyword import hello # import sys # for i in sys.modules: # print(i) # print(i) #将大型程序分割成多个包含Python代码的文件,也被成为模块.模块中支持使用另一个模块的代码。Python解释器自带内置模块 # import sys # def sqlparse(): # print('from mysql sqlparse') # # def sqlpare(): # print('from oracle sqlparse') # # db_type = input('>>: ') # if db_type == 'mysql': # import mysql as db # elif db_type == 'oracle': # import oracle as db # db.sqlparse() print(math.pow(2,3)) print(random.randint(0,100)) nums = [1, 5, 33, 12, 46, 33, 2] #均值 print(statistics.mean(nums)) #中值 print(statistics.median(nums)) #众数 print(statistics.mode(nums)) print(keyword.iskeyword("for")) print(keyword.iskeyword("zangfans")) print(hello.print_hello())
7b615cbad7321223bb13b2468c8de1e6e073c9dc
WebSofter/lessnor
/python/1. objects and data types/list.py
562
4.1875
4
""" Basic list """ players = [45, 25, 12, '445'] print(players) for player in players: print(player) """ + - Summ two and more lists """ players = players + [99, 88, 44] print(players) """ .append() - Append new item to list end """ players.append(25) print(players) """ :n, n:, m:n - Cut from and to element with number n(For example :2 - this is all from 1 to 2, and cuted all) """ print(players[:2]) """ Empty or replace specify items in list """ players[:2] = [1,2,3] print(players) """ Empty all items in list """ players[:] = [] print(players)
65b40303fd2dff4c4190b94544a53ef2b7aac8f9
bnkent/my_100days-of-code-with-python
/day37-39/weather_csv_demo/research.py
1,288
3.578125
4
import os import csv import collections import pprint from typing import List data = [] Record = collections.namedtuple('Record', 'date, actual_min_temp, actual_max_temp, actual_precipitation') def init(): filename = os.path.join(os.path.dirname(__file__), 'data', 'seattle.csv') if not data: with open(filename) as fin: reader = csv.DictReader(fin) data.clear() for row in reader: data.append(parse(row)) def get_hot_days() -> List[Record]: return sorted(data, key=lambda x: x.actual_max_temp, reverse=True) def get_cold_days() -> List[Record]: return sorted(data, key=lambda x: x.actual_min_temp) def get_wettest_days() -> List[Record]: return sorted(data, key=lambda x: x.actual_precipitation, reverse=True) def parse(row): row['actual_min_temp'] = int(row['actual_min_temp']) row['actual_max_temp'] = int(row['actual_max_temp']) row['actual_precipitation'] = float(row['actual_precipitation']) record = Record( date=row.get('date'), actual_min_temp=row.get('actual_min_temp'), actual_max_temp=row.get('actual_max_temp'), actual_precipitation=row.get('actual_precipitation') ) return record
f086870f62715b05dcb1e5a2507362947336ca50
Leeyp/DHS-work
/practical 1/q1_farenheit_to_celsius.py
110
3.859375
4
Farenheit = input("Input the Farenheit in double!") celsius = (5/9) * (float(Farenheit) - 32) print(celsius)
a0ada53e426ebcbd9353b65f152baa12ff02a6b2
rafaelperazzo/programacao-web
/moodledata/vpl_data/79/usersdata/231/43198/submittedfiles/serie1.py
190
3.765625
4
# -*- coding: utf-8 -*- import math n=int(input('digite n: ')) soma=0 for i in range(1,n+1,1): if i%2==1: soma=soma+i/i**2 else: soma=soma-i/i**2 print('%.5f'%soma)
d31259205cc3b59d55e1ae0230818dbcb650975d
yatish1606/gitExampleSE
/example.py
106
3.5
4
characters = ['Jonas', 'Martha', 'Ulrich', 'Charlotte'] for character in characters: print(character)
7bf480859260ad319277073245abdf136da8f53b
shaziakaleem/Datastructure_Algo
/binary_heap.py
1,870
3.890625
4
''' BINARY HEAP A binary heap is a binary tree with below properties: 1. elements are arranged in level order, first level element from left to right followed by second level 2. value of parent is always smaller than children 3. an additional element 0 is added in binary heap for formula : left_child = 2*parent right_child = 2*parent+1 4. It’s a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array. 5. Binary Heap is either Min Heap or Max Heap. 6. A binary heap(complete binary tree) is typically represented as an array. ''' class BinHeap: def __init__(self): self.heap_list =[] self.size =0 def percUp(self,i): while i//2>0: if self.heap_list[i]>self.heap_list[i//2]: temp = self.heap_list[i] self.heap_list[i//2] = self.heap_list[i] self.heap_list[i] = temp i = i//2 def add(self,item): self.heap_list.append(item) self.size += 1 self.percUp(1) def percDown(self,i): while i*2> self.size: min_child = self.find_min(i) if self.heap_list[i]>self.heap_list[min_child]: temp = self.heap_list[i] self.heap_list[min_child] = self.heap_list[i] self.heap_list[i] = temp def delMin(self): retval = self.heap_list[1] self.heap_list[1] = self.heap_list[self.size] self.heap_list.pop() self.size -=1 self.percDown(1) return retval def buildHeap(self,alist): i = len(alist)//2 self.heap_list = [0]+alist self.size = len(alist) while(i>0): self.percDown(i) i -+ 1
3177eaee95fb5e2684f4763ef39565e517b20553
ibahbah/NLP-Sentiment-analysis-using-logistic-regression
/build_freqs.py
1,246
3.65625
4
# ```python def build_freqs(tweets, ys): # """Build frequencies. # Input: # tweets: a list of tweets # ys: an m x 1 array with the sentiment label of each tweet # (either 0 or 1) # Output: # freqs: a dictionary mapping each (word, sentiment) pair to its # frequency # """ # # Convert np array to list since zip needs an iterable. # # The squeeze is necessary or the list ends up with one element. # # Also note that this is just a NOP if ys is already a list. yslist = np.squeeze(ys).tolist() # # # Start with an empty dictionary and populate it by looping over all tweets # # and over all processed words in each tweet. freqs = {} for y, tweet in zip(yslist, tweets): for word in process_tweet(tweet): pair = (word, y) if pair in freqs: freqs[pair] += 1 else: freqs[pair] = 1 return freqs # ``` # You can also do the for loop like this to make it a bit more compact: # # ```python # for y, tweet in zip(yslist, tweets): # for word in process_tweet(tweet): # pair = (word, y) # freqs[pair] = freqs.get(pair, 0) + 1 # ```
7fa86dd7a2ca7e75dcaccc72605c058e729a7d80
basseld21-meet/meet2019y1lab3
/Echo.py
134
3.640625
4
user=input ("Say something! ") print("UPPER: " + user.upper()) print ("lower: " + user.lower()) print ("swapcase:" + user.swapcase())
2f88ae1165787d1fd4e690cb42a9b687e0ecbb01
ZhengLiangliang1996/Leetcode_ML_Daily
/DP/62_UniquePath.py
575
3.609375
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2023 liangliang <liangliang@Liangliangs-MacBook-Air.local> # # Distributed under terms of the MIT license. class Solution: def uniquePaths(self, m: int, n: int) -> int: # dp[i][j] means number of possible unique paths reach to bottom right if m == 1 or n == 1: return 1 dp = [[1 for _ in range(n)] for _ in range(m)] for i in range(1, m): for j in range(1, n): print(i, j) dp[i][j] = dp[i][j-1] + dp[i-1][j] return dp[-1][-1]
d987c3e748e548342ddf5f40cb362b60454c19a6
AkaashLessons/Homeworks
/hw2.py
1,706
4.3125
4
##here are the 2 functions we wrote in class## ##we didn't go over this, but instead of writing print at the end of the function ##write return which accomplishes the same thing but will be more useful later def three(number): return number + 3 def a_to_b(a_word): b_word = a_word.replace('a','b') return b_word #Problem 1: write a function that takes in an float and returns a int #example: takes in 2.9, returns 2 def float_to_int(flo): integer = int(flo) return integer #Problem 2: write a function that takes in a temp in Fahrenheit and returns it in celsius #hint 1: the input and outputs will be numbers #hint 2: the conversion formula is C = (F - 32) x 5/9 #example (use this to check that you got it right): takes in 44, returns 6.6666667 def f_to_c(fahrenheit): celsius = (fahrenheit - 32) * 5/9 return celsius #Problem 3: write a function that takes in a string and returns the first two letters followed by "poop" #example: takes in "hello", returns "hepoop" def poop(word): poop = word[0:2] + "poop" return poop #Problem 4: write a function that takes in a list and returns a list of the third element repeated 4 times #example 1: takes in ["akaash", "can", "do", "this"], returns ["do, "do", "do", "do"] #example 2: takes in [1, 2, 3, 4], returns [3, 3, 3, 3] def repeat(lst): repeat = lst[2:3] * 4 return repeat #Problem 5: write a function that takes in a string and checks whether the letter "a" is in it #example: takes in "alphabet", returns True #hint: use the "in" method def a_in_it(string): a_in_it = "a" in string return a_in_it def a_in_it(string, letter): a_in_it = letter in string return a_in_it
2d9ee59fe1172f12f0d959f98e9514d6c20b79c6
Vedant-S/AIMechanics
/DeepLearningLibrary/trainMeDeep.py
1,340
3.984375
4
import DeepLearningLibrary.isthara_versatile as ist import matplotlib.pyplot as plt def model(X, Y, layers_dims,activation_tuple, learning_rate = 0.01, num_iterations = 15000, print_cost = True): grads = {} costs = [] # to keep track of the loss m = X.shape[1] # number of examples # Initialize parameters dictionary. parameters = ist.intialize_parameters(layers_dims) # Loop (gradient descent) for i in range(0, num_iterations): # Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID. AL, caches,activation_tuple = ist.linear_deep_forward(X, parameters,activation_tuple) # Loss cost = ist.compute_cost(AL, Y) # Backward propagation. grads = ist.linear_deep_backward(AL, Y, caches,activation_tuple) # Update parameters. parameters = ist.update_parameters(parameters, grads, learning_rate) # Print the loss every 1000 iterations if print_cost and i % 1000 == 0: print("Cost after iteration {}: {}".format(i, cost)) costs.append(cost) # plot the loss plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (per thousand)') plt.title("Learning rate =" + str(learning_rate)) plt.show() return parameters
3a9fdd9a8f5e2ec71be53abe42c605c94b87a7f5
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_5_set/set_opertation_symetric_difference.py
305
3.71875
4
# set operation # symmetric difference A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # A ^ B C = A ^ B print(C) # C = A.difference(B) # print(C) # use symmetric_difference function on A d = A.symmetric_difference(B) print(d) # use symmetric_difference function on B d = B.symmetric_difference(A) print(d)
0f61d31ef31c6660cf1894518095df9a3db027ac
Amit902/python_assignment02.py
/assignment23.py
166
3.546875
4
x=""" python class is going on...""" y="""there is no doubt in first class.""" z=x+y print(z) print(type(z)) x=10 y=1.2 z='a'
00d3ecbfd140ea657c41b074ceaeaecebcb11817
lishuchen/Algorithms
/lintcode/136_Palindrome_Partitioning.py
858
3.65625
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- class Solution: # @param s, a string # @return a list of lists of string def partition(self, s): # write your code here if not s: return [] rsl = list() self.find(s, 0, [], rsl) return rsl def find(self, s, start, cur, rsl): if start == len(s): rsl.append(cur) for j in range(start, len(s)): part = s[start: j + 1] if self.is_pldr(part): self.find(s, j + 1, cur + [part], rsl) def is_pldr(self, s): if len(s) == 1: return True start, end = 0, len(s) - 1 while start <= end: if s[start] == s[end]: start += 1 end -= 1 else: return False return True
6a1edc4f0ed198e33e28f57db1207f91d443e882
Omar-Velez/MinTIC2022
/Perfeccionamiento/reto4.py
185
3.796875
4
cantidadMonedas, memoria = 5,3 #[int(valor) for valor in input().split()] monedas=[int(valor) for valor in input().split()] monedas.reverse() print(monedas) # 11 4 # 1 2 3 4 5 6 7 8 9
f362581209fee4fffd595936f4cd336b276a32fa
emilyusa/coda-kids
/project-solutions/level-4/restarter2.py
1,015
3.546875
4
"""General information on your module and what it does.""" import coda_kids as coda # load sprites IMAGE_BUTTON = coda.Image("assets/button.png") # modifiable data class Data: """place changable state variables here.""" restart_button = coda.Object(IMAGE_BUTTON) display_text = coda.TextObject(coda.color.WHITE, 24, "Player 2 wins! Play again?") MY = Data() def initialize(window): """Initializes the restart menu state.""" MY.restart_button.location = window / 2 def update(delta_time): """Updates the restart menu state.""" for event in coda.event.listing(): if coda.event.quit_game(event): coda.stop() if coda.event.mouse_l_button_down(event): if MY.restart_button.collides_with_point(coda.event.mouse_position()): coda.state.change(0) def draw(screen): """Draws the restart menu state.""" MY.restart_button.draw(screen) MY.display_text.draw(screen) def cleanup(): """Cleans up the restart menu state."""
1fac29da9de3f4988e401d1e868afe4ee0645f2a
bitpit/CS112-Spring2012
/classcode/day06--code_formating/broken2.py
741
4
4
#!/usr/bin/env python from random import randint user_input=int(raw_input()) list=[] #initiliazing variables for _ in range(user_input): #appends input quantity list.append(randint(0,20))#of random vars between #1 and 20 to list based on #the number the user entered print list #prints list as it is after above control_var = 1 while control_var: #while s is not zero control_var=0 for number in range(1,user_input): if list[number-1]>list[number]: t1=list[number-1] t2=list[number] list[number-1]=t2 list[number]=t1 control_var=1 print list #prints altered list
05f85d5e2a79d9b905c1ab8b6068858b3b190797
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_96/1859.py
1,158
3.609375
4
from sys import stdin def get_judge_points(total): if not isinstance(total, int): total = int(total) i = int(total/3) remainder = total % 3 points = [i, i, i] while remainder > 0: points[remainder] += 1 remainder -= 1 return points def do_surprise(points): diff = max(points) - min(points) if min(points) > 0: if diff == 0: points[0] -= 1 points[1] += 1 elif diff == 1: number_of_max = len(filter(lambda x: x == max(points), points)) if number_of_max == 2: points[points.index(max(points))] -= 1 points[points.index(max(points))] += 1 return points t = 0 for line in stdin.readlines(): t_in = 0 y = 0 if t == 0: t_in == int(line.rstrip()) else: numbers = line.rstrip().split(' ') n, s, p = map(lambda x: int(x), numbers[0:3]) scores = map(get_judge_points, numbers[3:]) for score in scores: diff = max(score) - min(score) if max(score) < p and (diff >= 0) and (p - max(score) <= 1) and s > 0: do_surprise(score) s -= 1 if max(score) >= p: y += 1 print 'Case #%i: %i' % (t, y) t += 1
c627de0808839f41a6c6b9b5c6138ea4c227c2aa
pedroheck/uri-online-judge-training
/Iniciante/1060.py
181
3.6875
4
lista = [] contador = 0 for i in range(0, 6): lista.append(float(input())) for i in lista: if i > 0: contador += 1 print("{} valores positivos".format(contador))
b49d8c10ae83f4f18d0ebed68964bc27f261230a
JoaoXavierDEV/ParadgimasPython
/20201116/trabalhoExtraAv2-num3-6.py
1,069
3.953125
4
x = lambda: 2+2 y = lambda valor1: valor1 # print(x()) # ------------------------------------- class TV(): def __init__(self, ligada , canal, volume): self.ligada = ligada self.canal = canal self.volume = volume def mudarVolume(self): volume = input("VOLUME 0 - 10\n") if (int(volume) >= 0 and int(volume) <= 10): self.volume = volume print("O volume foi alterado para {}".format(self.volume)) elif (int(volume) > 10): print("Insira um valor entre 0 e 10") def mudarCanal(self, canal): canal = input("INSIRA UM CANAL 1 -- 99 \n") if (int(canal) >= 1 and int(canal) <= 99): self.canal = canal elif (int(canal) > 99): print("Digite um canal válido") def infoTV(self): if(self.ligada): print("A tv está ligada \nCanal: {} \nVolume: {}".format(self.canal, self.volume)) else: print("A tv está desligada") tv = TV(True, 0, 0) tv.mudarVolume() tv.infoTV()
a78a73c0df6a1230466ae22b314dc6c95fad838e
berkercaner/pythonTraining
/Chap03/types.py
1,049
3.8125
4
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ x = 7 y = """berker caner {}""".upper().format(9) print('x is {} {}'.format(x,y)) print(type(x),type(y)) z = 'berker "{1:<09}" "{0:>010}"'.format(8,1232) print(z) a = 8 w = f"it's {a} not {3}" print(w) b = 7 * 3.1415 #numeric type c = 7 / 3 d = 7 // 3 print(type(b), type(c), type(d)) e = 0.1 + 0.1 + 0.1 - 0.3 # makes a problem with dealing money print(e,type(e)) from decimal import * a = Decimal('0.1') b = Decimal('0.3') e = a + a + a - b print(e,type(e)) x = (1,'two',3.0,[4, 'four'], 5) y = (1,'two',3.0,[4, 'four'], 5) print('x is {}'.format(x)) print(f"type of x {type(x)} id of x {id(x)} id of x[0] {id(x[0])}") print(f"type of y {type(y)} id of y {id(y)} id of y[0] {id(y[0])}") #IDs of tuples will be different but id of same elements will be same if x[0] is y[0]: print('yeap') else: print('nope') if type(x) is 'tuple': #CANT USE LIKE THIS print('yeap') else: print('nope') if isinstance(x,tuple): print('yeap') else: print('nope')
2696f7d0d95a089df6134d6a80f24bec74bfad90
atul-maverick/weather_analysis_hadoop
/mapper1.py
1,096
3.859375
4
#!/usr/bin/env python """A more advanced Mapper, using Python iterators and generators.""" import sys import operator #http://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/#reduce-step-reducerpy def read_input(file): for line in file: line=line.split('\t') month=int(line[0][4:]) if month>=3 and month<=5: yield line[0][0:4],"Spring",line[1],line[2],line[3] elif month>=6 and month<=8: yield line[0][0:4],"Summer",line[1],line[2],line[3] elif month>=9 and month<=11: yield line[0][0:4],"Fall",line[1],line[2],line[3] else: yield line[0][0:4],"Winter",line[1],line[2],line[3] def main(separator='\n'): # input comes from STDIN (standard input) data = read_input(sys.stdin) #date = read_date(sys.stdin) for words in data: # write the results to STDOUT (standard output); # what we output here will be the input for the # Reduce step, i.e. the input for reducer.py print "{0}\t{1}\t{2}\t{3}\t{4}".format(words[0],words[1],words[2],words[3],words[4]) if __name__ == "__main__": main()
5b91156821c6891006549b56a1eaa19892d2cc60
AbelRapha/Python-Exercicios-CeV
/Mundo 3/ex097 Um print especial.py
223
3.578125
4
def Escreva(palavra): tamanho = len(palavra)+4 print("-"*(tamanho)) print(f' {palavra.center(tamanho)}') print("-"*(tamanho)) palavra = input("Digite qualquer palavra: ") print(Escreva(palavra=palavra))
89d8504815c5f725802d8ef9136b3454b611d4b2
Merovizian/Aula19
/Desafio091 - Dados aleatórios em um dicionario.py
1,013
3.734375
4
from random import randint import time print(f"\033[;1m{'Desafio 091 - Jogando com numeros aleatorios eu um dicionario':*^70}\033[m") # cria um dicionario e uma lista dicionario = dict() lista = list() # cria as keys e coloca os valores delas no dicionario e o dicionario dentro da lista. for a in range (0,4): dicionario['nome'] = input(f"Informe o nome o {a+1}o jogador: ") # a key 'dado' é preenchida com um valor random que vai de 1 a 6 - usando o ranint dicionario['dado'] = randint(1,6) lista.append(dicionario.copy()) # printa na tela os nomes e os valores tirados nos dados print("Valores Sorteados:") for a in lista: time.sleep(1) print(f"O jogador {a['nome']} tirou {a['dado']}") time.sleep(1) # ordena a lista usando a função sorted com argumentos. lista = sorted(lista , key= lambda k:k['dado'], reverse=True) # printa na tela os valores já ordenados. print("Ranking dos Jogadores:") for a, v in enumerate(lista): print(f"{a+1}o lugar {v['nome']} com {v['dado']} ")
340b1481b39b4ed272b3bd09ad648f933570e7de
scarletgrant/python-programming1
/p8p3_multiplication_table_simple.py
415
4.3125
4
''' PROGRAM p8p3 Write a program that uses a while loop to generate a simple multiplication table from 0 to 20. PSEUDO-CODE initialize i to zero prompt user for number j that set the table size while i <= 20: print(i, " ", i*j) increment i+=1 print a new line with print() ''' i = 0 j = int(input("Please enter a number: ")) while i <= 20: print(i, " ", i*j) i+=1 print()
bba283662a32f7e065a92be45060bdf4662bacdf
Vasilic-Maxim/LeetCode-Problems
/problems/1038. Binary Search Tree to Greater Sum Tree/1 - DFS In-order Traverse.py
550
3.640625
4
class TreeNode: def __init__(self, x, left=None, right=None): self.val = x self.left = left self.right = right class Solution: """ Time: O(n) Space: O(n) """ def bstToGst(self, root: TreeNode) -> TreeNode: self.recalculate(root) return root def recalculate(self, node: TreeNode, value: int = 0): if node is None: return value value = self.recalculate(node.right, value) node.val += value return self.recalculate(node.left, node.val)
4d39d20e155d7871100f9d6a8bc3e8629050cea9
britel-chaimaa20/mundiapolis-math
/math/0x01-plotting/1-scatter.py
331
3.546875
4
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt mean = [69, 0] cov = [[15, 8], [8, 15]] np.random.seed(5) x, y = np.random.multivariate_normal(mean, cov, 2000).T y += 180 plt.title("Men's Height vs Weight") plt.ylabel("Weight (lbs)") plt.xlabel("Height (in)") plt.scatter(x,y) plt.show()
4e58ea9fdead7751620e06a6e2c2ae71def5c0d0
eloydrummerboy/Udemy
/Deep_Learning_PreReq_Numpy/Exercise4.py
1,111
3.53125
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 30 18:29:35 2017 @author: eloy """ # Write a function that flips an image 90 degrees clockwise import os os.chdir("/home/eloy/Data_Science/Kaggle/MNIST/") import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("train.csv") test = df.loc[df['label'] == 9] test_mu = test.mean() test_mu = np.array(test_mu) test_mu = test_mu[1:] test_mu = test_mu.reshape(28,28) plt.imshow(test_mu) plt.show() # Rotate with For Loops # rotated[0,0] will == test_mu[0,27] # rotated[0,1] will == test_mu[1,27] # rotated[1,0] will == test_mu[0,26] # so rotated row = 27 -test_mu col # and rotated col = 27 - test_mu row # a.k.a. rows become columns, columns are reversed rotated_for = np.ones((28,28)) for row in range(0,len(test_mu)): for col in range(0,len(test_mu)): rotated_for[row,col] = test_mu[27-col,row] plt.imshow(rotated_for) plt.show() # Rotate with numpy # Rows become Columns rotated_np = test_mu.transpose() # Columns are reversed rotated_np = rotated_np[:,::-1] plt.imshow(rotated_np) plt.show()
3c77c40fa12aa27666c7f112fb1b2c9a65886638
mn113/adventofcode2019
/python/04.py
958
3.859375
4
def is_increasing(n): s = str(n) return s[1] >= s[0] and s[2] >= s[1] and s[3] >= s[2] and s[4] >= s[3] and s[5] >= s[4] def has_double(n): s = str(n) return s[1] == s[0] or s[2] == s[1] or s[3] == s[2] or s[4] == s[3] or s[5] == s[4] def has_isolated_double(n): s = str(n) return (s[0] == s[1] and s[1] != s[2]) \ or (s[1] == s[2] and s[0] != s[1] and s[2] != s[3]) \ or (s[2] == s[3] and s[1] != s[2] and s[3] != s[4]) \ or (s[3] == s[4] and s[2] != s[3] and s[4] != s[5]) \ or (s[4] == s[5] and s[3] != s[4]) def is_valid(n): return is_increasing(n) and has_double(n) def is_strictly_valid(n): return is_increasing(n) and has_isolated_double(n) def part1(): valid = [c for c in range(start, end) if is_valid(c)] print(len(valid)) def part2(): valid = [c for c in range(start, end) if is_strictly_valid(c)] print(len(valid)) start = 134792 end = 675810 part1() part2()
3c955f5304190eab182b21ba76973de5367a187d
alisen39/algorithm
/algorithms/spiralMatrix2.py
1,254
3.96875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/19 15:22 # @Author : Alisen # @File : spiralMatrix2.py class Solution: def generateMatrix(self, n: int): matrix = [[0 for _ in range(n)] for _ in range(n)] # print(matrix) left = 0 right = len(matrix[0]) - 1 top = 0 buttom = len(matrix) - 1 i = 0 j = 0 k = 0 while left <= right and top <= buttom: while j <= right: k += 1 matrix[i][j] = k j += 1 j -= 1 i += 1 while i <= buttom: k += 1 matrix[i][j] = k i += 1 i -= 1 top += 1 if left < right and top <= buttom: while j > left: j -= 1 k += 1 matrix[i][j] = k while i > top: i -= 1 k += 1 matrix[i][j] = k j += 1 right -= 1 buttom -= 1 left += 1 return matrix if __name__ == '__main__': n = 3 res = Solution().generateMatrix(n) print(res)
f96c1fb70cbdecbd8e694e8312b8c57d3688871a
netzak75/test_3-11
/Shelve test.py
413
3.640625
4
import shelve with shelve.open('ShelveTest') as fruit: fruit['orange'] = "a sweet, orange, citrus fruit" fruit['apple'] = "a sweet fruit for making cider" fruit['grape'] = "a small, sweet fruit that grows in bunches" fruit['banana'] = "a long yellow fruit covered in a peel" fruit['cherry'] = "a small, red fruit with a pit in the middle" print(fruit["cherry"]) print(fruit["apple"])
9210e707e0a54cfd284538508ac5c834bb036e9b
plutmercury/OpenEduProject
/w03/task_w03e09.py
610
4.125
4
# Дана строка, состоящая из слов, разделенных пробелами. Определите, сколько в # ней слов. # Гарантируется, что в строке не встречается несколько пробелов подряд. # # Подсказка: у строк есть полезный метод count, а количество слов напрямую # связано с количеством пробелов, их разделяющих # # Sample Input: # # Hello world # # Sample Output: # # 2 s = input() print(s.count(' ') + 1)
f25487365f8e4052f95d28203a5844eac7c60206
adityamangal1/DSA-questions
/gfg/PeakElement.py
208
3.765625
4
N = 3 arr = [1, 2, 3] a = [] for i in range(len(arr)): try: print(arr[i]) if(arr[i] > arr[i+1]): print('ji') a.append(arr[i]) except: pass print(a)
a2fae60cf2162d171db406831cad6d1c35af14b4
KirillK-16/Z63-TMS
/students/shloma/001_homework_01/task_1_5.py
336
4.25
4
# Катеты прямоугольного треугольника a, b = 6, 8 # Гипотенуза треугольника c = (a ** 2 + b ** 2) ** 0.5 # Площадь треугольника s = a * b / 2 print("Гипотенуза прямоугольника:", c) print("Площадь прямоугольника:", s)
f200cabf6c91de536459558f9820668157c32549
Toetoise/python_test
/设计模式(单例).py
992
3.984375
4
''' 工厂模式:创建出的产品都有相同的特点 首先写一些基类(父类),具有相同的特点,创造出很多具有这些特点的产品,然后独有的特点 继承相同的特点的基础上再拓展就可以用工厂模式 单例模式:有些对象需要具有唯一性,可以用单例模式来实现 ''' class Zhuxi: """ 1.不管创建多少对象,内存地址是唯一 __new__魔法方法 给待创建的对象分配内存空间 返回内存地址的引用 """ instance = None init_flag = False def __new__(cls): if not cls.instance: print("创建第一个实例") cls.instance = super().__new__(cls) # 给待创建的对象分配内存空间 return cls.instance def __init__(self): if not self.init_flag: print("第一次初始化") self.init_flag = True if __name__ == '__main__': a = Zhuxi() print(id(a)) b = Zhuxi() print(id(b))
b03282cb9349e6bbad73609dcfe369287d6fa6e6
surajbarailee/PythonExercise
/python_topics/strings.py
973
4.375
4
""" Strings in python """ string = "Hello*World!" """ H e l l o * W o r l d ! 0 1 2 3 4 5 6 7 8 9 10 11 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 """ print(string[2:]) # get every element from second index print(string[-2:]) # get every element from -2 print(string[2:6]) #get every element from second element to sixth (sixth exclusive) print(string[2:-6]) print(string[::2]) print(string[::-1]) print(string[::-2]) print(string[::-3]) print(string[6:1:-2]) # get every second element from 6 to 1 in reversed print("=====") print(string[3::-3]) # get evey third element starting from 3 in reversed print(string[11:11]) print(len(string)) print(string.upper()) print(string.lower()) print(string.upper()) print(string.lower()) print(string.capitalize()) print(string.title()) print(string.swapcase()) print(string.strip()) print(string.lstrip()) print(string.rstrip()) print(string.replace("World", "Universe"))
d6e5a9b34c22b434c194fccdc7820ba69a3cb2d4
chengchaoyang/my-leetcode-record
/array/0075-sort-colors.py
2,868
4.1875
4
""" 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 注意: 不能使用代码库中的排序函数来解决这道题。 示例: 输入: [2,0,2,1,1,0] 输出: [0,0,1,1,2,2] 进阶: 一个直观的解决方案是使用计数排序的两趟扫描算法。 首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。 你能想出一个仅使用常数空间的一趟扫描算法吗? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sort-colors """ from collections import defaultdict from typing import List class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ counter = [0] * 3 for num in nums: counter[num] += 1 i = 0 for _ in range(counter[0]): nums[i] = 0 i += 1 for _ in range(counter[1]): nums[i] = 1 i += 1 for _ in range(counter[2]): nums[i] = 2 i += 1 class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ counter = [0] * 3 for num in nums: counter[num] += 1 i = 0 for idx, count in enumerate(counter): for _ in range(count): nums[i] = idx i += 1 class Solution: "三路快排,[0,k) , [k,j], (j,-1]" def sortColors(self, nums): k = 0 j = len(nums) - 1 for i in range(len(nums)): print(nums) if nums[i] == 0: nums[i],nums[k] = nums[k],nums[i] k += 1 elif nums[i] == 2: nums[i],nums[j] = nums[j],nums[i] j -= 1 return nums class Solution: def sortColors(self, nums): l = len(nums) # 循环不变量的定义: # [0, zero] 中的元素全部等于 0 # (zero, i) 中的元素全部等于 1 # [two, l - 1] 中的元素全部等于 2 zero = -1 two = l i = 0 # 马上要看的位置 while i < two: print(i,nums) if nums[i] == 0: zero += 1 nums[zero], nums[i] = nums[i], nums[zero] i += 1 elif nums[i] == 1: i += 1 else: two -= 1 nums[two], nums[i] = nums[i], nums[two] nums = [2,0,2,1,1,2] print(Solution().sortColors(nums))
5a479e7ea6faba9464fbfd5d901f8dec12637f2e
Anteste/Pentesting-Notes
/Courses/TCM Security/Practical Ethical Hacking/Ressources/Python/math.py
263
3.671875
4
#!/bin/python3 # Math print(50 + 50) # add print(50 - 50) # subtract print(50 + 50) # multiply print(50 / 50) # divide print(50 + 50 - 50 * 50 / 50) # PEMDAS print(50** 2) # exponents print(50 % 6) # modulo print(50 / 6) # leftovers print(50 // 6) # no leftovers
f4b6d2bb900a1e4038a0eb838bf056af4a1a4d8f
CodingDojoDallas/python_july_2017
/david_conley/Python/checkerbox.py
122
3.75
4
row = '-'.join('+' * 8) row2 = '|'.join('#' * 8); for i in range (8,0,-1): print (row) print (row2) print(row)
6a9d022a1ed11ae3670b87ec300ab71549a9bb26
ticotheps/practice_problems
/code_signal/arcade/journey_begins/add/add.py
103
3.578125
4
def add(param1, param2): sum = param1 + param2 return(sum) print(add(1, 4)) # should print "5"
d069eac410bc45e07b9c09960f78e292ca074fac
fabianobasso/Python_Projects
/person registration - V2.0/appCadastro.py
8,125
3.5625
4
""" Programa para fazer cadastro de pessoas usando MySQL em python modulo usado para conectar no banco mysql.connector """ # Modulos importados import mysql.connector from mysql.connector import errorcode import sys ########################### # Variáveis Globais # ########################### cleanColor = '\033[0;0m' statusColorError = '\033[1;31m' statusColorSuccess = '\033[1;32m' ########################### # Funções do programa ########################### # conDataBase -> Função que faz a conexão com o banco (OBS: o dicionário config contém as informações de um Laboratório de Dev pessoal) def conDataBase(): global cleanColor, statusColorError config = { 'user': 'pyDev', 'password': 'pydev2019', 'host': '10.10.10.7', 'database': 'pydev' } try: con = mysql.connector.connect(**config) except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print(f"{statusColorError}Algo está errado com seu nome de usuário ou senha{cleanColor}") if err.errno == errorcode.ER_BAD_DB_ERROR: print(f"{statusColorError}O banco de dados não exite{cleanColor}") return con def personRegistration(con): global statusColorError, cleanColor, statusColorSuccess print(f"\n{statusColorSuccess} Novo Cadastro {cleanColor}") print(f"{statusColorSuccess}\n Digite as informações para cadastrar usuário: {cleanColor}") name = input(" Nome: ") email = input(" Email: ") phone = input(" Telefone: ") cursor = con.cursor() sql = "insert into cadastroUser(nome, email, phone) values('"+name+"','"+email+"','"+phone+"')" try: cursor.execute(sql) con.commit() print(f"{statusColorSuccess}\n usuário cadastrado com sucesso.{cleanColor}") except mysql.connector.Error as err: print(f"{statusColorError} Algo deu errado: {err} {cleanColor}") con.close() Main() def viewAllRegistration(con): global statusColorError, cleanColor, statusColorSuccess cursor = con.cursor() sql = "select * from cadastroUser" try: cursor.execute(sql) dataViews = cursor.fetchall() print(108 * "-") print(f"{45 * ' '} Listar Todos") print(108 * "-") for data in dataViews: name = data[0] email = data[1] phone = data[2] idUser = data[3] print(f"{statusColorSuccess}ID:{cleanColor} {idUser} {statusColorSuccess}Nome:{cleanColor}{name}{(30 - len(name)) * ' '}{statusColorSuccess}Email:{cleanColor}{email}{(30 - len(email)) * ' '}{statusColorSuccess}Telefone:{cleanColor} {phone} ") except mysql.connector.Error as err: print(f"{statusColorError} Algo deu errado: {err} {cleanColor}") con.close() Main() def searchRegistration(con): global statusColorError, cleanColor, statusColorSuccess cursor = con.cursor() print(f"\n {statusColorSuccess} Pesquisar Cadastro \n ") print(statusColorSuccess,end=' ') search = input(" Digite o Nome a ser pesquisado: ") print(cleanColor) sql = "select * from cadastroUser where nome like '%"+search+"%'" try: cursor.execute(sql) dataViews = cursor.fetchall() print(108 * "-") print(f"{45 * ' '} Pesquisado por {search}") print(108 * "-") for data in dataViews: name = data[0] email = data[1] phone = data[2] idUser = data[3] print(f"{statusColorSuccess}ID:{cleanColor} {idUser} {statusColorSuccess}Nome:{cleanColor}{name}{(30 - len(name)) * ' '}{statusColorSuccess}Email:{cleanColor}{email}{(30 - len(email)) * ' '}{statusColorSuccess}Telefone:{cleanColor} {phone} ") except mysql.connector.Error as err: print(f"{statusColorError} Algo deu errado: {err} {cleanColor}") con.close() Main() def deleteRegistration(con): global statusColorError, cleanColor, statusColorSuccess cursor = con.cursor() print(f"\n{statusColorSuccess} Excluir Cadastro \n {cleanColor}") code = input(" Informe o ID para excluir usuário: ") sql = "delete from cadastroUser where idUser ="+code try: cursor.execute(sql) con.commit() print(f"{statusColorSuccess} \n Usuário deletado com sucesso {cleanColor}") except mysql.connector.Error as err: print(f"{statusColorError} Algo deu errado: {err} {cleanColor}") Main() con.close() Main() def changeRegistration(con): global statusColorError, cleanColor, statusColorSuccess cursor = con.cursor() update = True print(f"\n{statusColorSuccess} Alterar Cadastro \n{cleanColor}") code = input(" Informe o ID do registro que deseja alterar: ") while update: print("""\n [1] - Nome [2] - Telefone [3] - E-Mail""") try: choseChange = int(input(" Escolha o que vai ser alterado nesse cadastro: ")) if choseChange == 1: newname = input(" Informe o nome para alterar: ") sql = "update cadastroUser set nome='"+newname+"' where idUser = "+code try: cursor.execute(sql) con.commit() print(f"{statusColorSuccess} \n Nome Alterado com sucesso {cleanColor}") update = False except mysql.connector.Error as err: print(f"{statusColorError} Algo deu errado: {err} {cleanColor}") update = False elif choseChange == 2: newPhone = input(" Informe o telefone para alterar: ") sql = "update cadastroUser set phone='"+newPhone+"' where idUser = "+code try: cursor.execute(sql) con.commit() print(f"{statusColorSuccess} \n Telefone Alterado com sucesso {cleanColor}") update = False except mysql.connector.Error as err: print(f"{statusColorError} Algo deu errado: {err} {cleanColor}") update = False elif choseChange == 3: newEmail = input(" Informe o e-mail para alterar: ") sql = "update cadastroUser set email='"+newEmail+"' where idUser = "+code try: cursor.execute(sql) con.commit() print(f"{statusColorSuccess} \n E-Mail Alterado com sucesso {cleanColor}") update = False except mysql.connector.Error as err: print(f"{statusColorError} Algo deu errado: {err} {cleanColor}") update = False else: print('\033[1;31m'+" Opção Invalida, escolha entre 1 e 3"+'\033[0;0m') except ValueError: print('\033[1;31m'+" Não é numero, escolha entre 1 e 3"+'\033[0;0m') con.close() Main() # Main -> Função do menu principal do programa def Main(): print("""\n [1] - Cadastrar [2] - ALterar [3] - Excluir [4] - Pesquisar [5] - Listar Todos [6] - Sair""") try: choseOp = int(input("\n Escolha uma opção: ")) if choseOp < 1 or choseOp > 6: print('\033[1;31m'+" Opção Invalida, escolha entre 1 e 6"+'\033[0;0m') Main() except ValueError: print('\033[1;31m'+" Não é numero, escolha entre 1 e 6"+'\033[0;0m') Main() con = conDataBase() if choseOp == 1: personRegistration(con) if choseOp == 2: changeRegistration(con) if choseOp == 3: deleteRegistration(con) if choseOp == 4: searchRegistration(con) if choseOp == 5: viewAllRegistration(con) if choseOp == 5: sys.exit() if __name__ == '__main__': Main()
d8e3541a38b285ff4f12e793ca2f2f77e9d92717
DevByAthi/cuttingSequence
/eigenvectors.py
2,722
4.0625
4
''' eigenvectors.py Takes a given matrix, checks that it is hyperbolic, and returns the expanding eigenvector and its slope ''' import numpy as np import math from random import * #=== Function Definitions ===# ''' tests if a given matrix has a determinant of 1 ''' def detTest(matrix): print round(np.linalg.det(matrix)) == 1 ''' tests if a given matrix is hyperbolic (i.e. has determinant of 1 and a trace whose absolute value is greater than 2) ''' def isHyperbolic(matrix): if np.trace(matrix) > 2 and round(np.linalg.det(matrix)) == 1: return True; return False; ''' @param: - matrix: 2-by-2 matrix with real entries @return: returns the eigenvector of the given hyperbolic matrix whose slope is positive ''' def eigenHyp(matrix): list = [] if isHyperbolic(matrix): w, v = np.linalg.eig(matrix) largestEigenvalue = 0 termOfLargest = -1 for i in range(len(v)): # print i # print "Eigenvalue for (0): {1}".format(i, w[i]) # print "Eigenvector for (0): {1}, with slope {2}".format(i, v[i], slope(v[i])) # if slope(v[i]) > 0: # return v[i] if abs(w[i]) > abs(largestEigenvalue): largestEigenvalue = w[i] termOfLargest = i return v[termOfLargest] ''' Determines slope of a 2-by-1 vector (which can encode the slope of a line crossing through it) @return: returns slope of given vector ''' def slope(vector): return (1.0*vector.item(1))/vector.item(0); ''' Randomly generates a hyperbolic matrix, checking that the matrix formed is hyperbolic @return: returns a random hyperbolic matrix with elements of value "> 0" and "< max" ''' def genMatrix(max): # initialize a = randint(0,max) b = 0 c = 0 d = randint(0,max) while abs(a+d) <= 2: d = randint(0,max) bc = (a*d) - 1 if a == 0 or d == 0: b = 1 c = -1 else: if isPrime(bc): b = bc c = 1 else: b = randFactor(bc) c = bc/b retMatrix = np.matrix([[a, b], [c, d]]) if isHyperbolic(retMatrix): return retMatrix ''' Checks if an integer is prime. Speeds up calculations in determining 'b' and 'c' in the genMatrix() function @param: - num (integer): an integer input @return: a boolean stating whether "num" is prime ''' def isPrime(num): if num < 2: return False; for i in range(2,num): if num % i == 0: return False; return True; ''' Returns a random factor of a given integer. Speeds up calculations in determining 'b' and 'c' in the genMatrix() function, should b*c not be prime @param: - num (integer): an integer input @return: a random factor of "num" ''' def randFactor(num): if isPrime(num): return 1 list = [] for i in range(2,num): if num % i == 0: list.append(i) return list[randint(0,len(list) - 1)]
b0c7f317561aca9d01a9905da4aafe3f2de7bfdd
alfielytorres/algorithms-data-structures
/capstones/assignment/plotting.py
1,432
3.671875
4
from matplotlib import pyplot as plt from matplotlib.pyplot import plot from regression import line, slope def label(a, b): if a!=0 and b!=0: return r'$y={a}x + {b}$' elif a!=0: return r'$y={a}x$' else: return r'$y={b}$' def linear(a, b, x_min=-1, x_max=1, points=1000, **kwargs): xx = [x_min + i/points*(x_max-x_min) for i in range(points+1)] yy = [a*x + b for x in xx] plot(xx, yy, label=label(a,b), **kwargs) def plot2DData(expVariable, target): plt.plot(expVariable, target, marker='x', linestyle=' ', color='black') def plot_1d_predictors(lines, x=[], y=[], outfile=None): rng = max(x) - min(x) x_min = min(x) - 0.1*rng x_max = max(x) + 0.1*rng plt.xlim(x_min, x_max) for a, b in lines: linear(a, b, x_min, x_max) plt.xlabel('$x$') plt.ylabel('$y$') plt.legend() plt.plot(x, y, marker='x', linestyle=' ', color='black') def example1(): linear(1/3, 0.5, 0, 4, color='black') linear(0.0, 0.5, 0, 4, color='black', linestyle='--') plt.plot([1, 2, 3], [1, 1, 2], marker='o', linestyle=' ', color='black') plt.plot([-1, 0, 1], [-1/3, -1/3, 2/3], marker='x', linestyle=' ', color='black') plt.xlim(-4, 4) plt.ylim(-3, 3) plt.tight_layout() plt.show() def example2(): x = [0, 1, 2] y = [1, 1, 2] plot_1d_predictors([line(x, y), (slope(x, y), 0.0)], x, y) plt.show() example2()
5abea467a1e4ace5ade20daa498ed7efa59ad1ef
xiaohuanlin/Algorithms
/Leetcode/2807. Insert Greatest Common Divisors in Linked List.py
1,887
4.3125
4
''' Given the head of a linked list head, in which each node contains an integer value. Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them. Return the linked list after insertion. The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. Example 1: Input: head = [18,6,10,3] Output: [18,6,6,2,10,1,3] Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes). - We insert the greatest common divisor of 18 and 6 = 6 between the 1st and the 2nd nodes. - We insert the greatest common divisor of 6 and 10 = 2 between the 2nd and the 3rd nodes. - We insert the greatest common divisor of 10 and 3 = 1 between the 3rd and the 4th nodes. There are no more adjacent nodes, so we return the linked list. Example 2: Input: head = [7] Output: [7] Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes. There are no pairs of adjacent nodes, so we return the initial linked list. Constraints: The number of nodes in the list is in the range [1, 5000]. 1 <= Node.val <= 1000 ''' from typing import * import unittest from math import gcd # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]: current = head while current: next = current.next if not next: break current.next = ListNode(gcd(current.val, next.val)) current.next.next = next current = next return head
e1e4fabf7eea714778a29496d0d5848533611ea0
saregos/ssw567
/hw1/triangle.py
1,794
3.859375
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 10 19:54:28 2021 @author: weige """ import unittest def classifyTriangle(a,b,c): try: a = float(a) except: print("Input A is not a number") return "Error" try: b = float(b) except: print("Input B is not a number") return "Error" try: c = float(c) except: print("Input C is not a number") return "Error" if a > 0 and b > 0 and c > 0: if a + b > c and a + c > b and b + c > a: if a == b == c: return "Equilateral" elif a == b or a == c or b == c: return "Isoceles" elif a**2 + b**2 == c**2 or a**2 + c**2 == b**2 or b**2 + c**2 == a**2: return "Right" else: return "Scalene" return "Not a Triangle" def runClassifyTriangle(a,b,c): print('classifyTriangle(',a, ',', b, ',', c, ') = ',classifyTriangle(a,b,c),sep="") class TestTriangles(unittest.TestCase): def testSet1(self): self.assertEqual(classifyTriangle(3,4,-1),"Not a Triangle","Testing negative input") self.assertEqual(classifyTriangle(3,4,'five'),"Error","Testing string input") self.assertEqual(classifyTriangle(1,4,2),"Not a Triangle","Testing invalid triplet") def testSet2(self): self.assertEqual(classifyTriangle(0.3,0.5,0.4),"Right","Testing Right triangle and float input") self.assertEqual(classifyTriangle(3,3,3),"Equilateral","Testing Equilateral") self.assertEqual(classifyTriangle(3,3.0001,3.0002),"Scalene","Testing Scalene") self.assertEqual(classifyTriangle(1,2,2),"Isoceles","Testing Isoceles") if __name__ == '__main__': unittest.main(exit=False)
7865ee46fcf3671cea7bda25497adf4c8f9c53f4
A01252512/EjerciciosPrepWhile
/assignments/SumaNConsecutivos/src/exercise.py
473
4.125
4
#Escribe un método que reciba un número entero positivo n, después debe calcular la suma 1+2+3+...+n. Finalmente regrese el resultado de la suma y sea impreso en pantalla. #Entrada: Un número entero positivo n #Salida: El resultado de la suma 1+2+3...+n def main(): #escribe tu código abajo de esta línea n = int(input('Número: ')) i = 1 suma = 0 while i <= n: suma += i i+=1 print(suma) if __name__=='__main__': main()
d26dcb3c967a74ee869bcd764e723008be7374c8
A-khateeb/Full-Stack-Development-Path
/Python/PCC/Chapter6/Glossary.py
684
4.03125
4
glossary = {"Dictionary":"Is a key-value pair structure", "del":"is a method used to delete the list or Dictionary without having any way to retrive data", "Lists":"Is an array based structure", "Tuple":"Is a list, however, the values cannot change", "pop":"is a method used to delete the list or Dictionary without having any way to retrive data"} print("Dictionary in python:") print(glossary["Dictionary"]+"\n") print("del in python:") print(glossary["del"]+"\n") print("Lists in python:") print(glossary["Lists"]+"\n") print("Tuple in python:") print(glossary["Tuple"]+"\n") print("pop in python:") print(glossary["pop"]+"\n")
0c8f7bccb0f59791cf7133b833d0012c69dea615
lom360/python-programming
/2) DataStructures/Week1-Strings/find.py
290
3.578125
4
text = "X-DSPAM-Confidence: 0.8475" # When accessing index. We can also use methods of the same string/array to access the index. # Line 5 is an example. 1 was added to avoid including the colon. string_num = text[(text.find(':') + 1) : ] float_num = float(string_num) print(float_num)
4b57d7961e74d8e8455cbc4c833bb106273ef51d
upputuriyamini/yamini
/76.py
141
3.640625
4
n=int(raw_input()) f=0 for i in range (1,n): if n%i==0: f=i if f>1: print 'yes' else: print 'no'
d36e92b74dbad8e42d63515b41e2a79c56937c1b
ryanvade/CS456
/Proj3/src/PriorityQueue/PriorityQueue.py
838
3.5
4
#!/usr/bin/env python3 from heapq import heappush, heappop import queue class PriorityQueue(queue.PriorityQueue): def _init(self, maxsize): self.queue = [] def _qsize(self): return len(self.queue) def _put(self, item): heappush(self.queue, item) def _get(self): return heappop(self.queue) def __contains__(self, item): with self.mutex: for iq in self.queue: if item[1]['name'] == iq[1]['name']: return True return False def remove(self, item): with self.mutex: for iq in self.queue: if item[1]['name'] == iq[1]['name']: self.queue.remove(iq) break def __len__(self): with self.mutex: return len(self.queue)
f95906ad0f5fd2615e5018a04dfd8418f99ae34b
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/125_2.py
2,482
4.34375
4
Python | Mean of tuple list Sometimes, while working with Python tuple list, we can have a problem in which we need to find the average of tuple values in the list. This problem has the possible application in many domains including mathematics. Let’s discuss certain ways in which this task can be performed. **Method #1 : Using loops** The first approach that can be thought of to solve this problem can be a brute force approach in which we just loop each tuple to add element and then just divide it by number of tuples in the list. __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Mean of tuple list # Using loops # Initializing list test_list = [(1, 4, 5), (7, 8), (2, 4, 10)] # printing original list print("The original list is : " + str(test_list)) # Average of tuple list # Using loops sum = 0 for sub in test_list: for i in sub: sum = sum + i res = sum / len(test_list) # printing result print("The mean of tuple list is : " + str(res)) --- __ __ **Output :** The original list is : [(1, 4, 5), (7, 8), (2, 4, 10)] The mean of tuple list is : 13.666666666666666 **Method #2 : Usingchain() + sum()** In order to reduce the line of codes, the chain() functionality can be used so that all the elements can be extracted and then can be added using sum(). __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Mean of tuple list # Using chain() + sum() from itertools import chain # Initializing list test_list = [(1, 4, 5), (7, 8), (2, 4, 10)] # printing original list print("The original list is : " + str(test_list)) # Average of tuple list # Using chain() + sum() temp = list(chain(*test_list)) res = sum(temp)/ len(test_list) # printing result print("The mean of tuple list is : " + str(res)) --- __ __ **Output :** The original list is : [(1, 4, 5), (7, 8), (2, 4, 10)] The mean of tuple list is : 13.666666666666666 Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
fa97637bcf945171195fc7960e9cf1d5403055fd
torjusti/tdt4110
/assignments/2/klassifisering.py
829
4.03125
4
def wholeNumber(num): if num == int(num): return 1 return 0 def evenNumber(num): return not (num % 2) def isPositive(num): return num > 0 def compareNr(a, b): return not bool(a - b) def main(): num = float(input("Number: ")) if wholeNumber(num): print("Dette er et heltall.") else: print("Dette er ikke et heltall") if evenNumber(num): print("Dette er et partall.") else: print("Dette er ikke et partall.") if isPositive(num): print("Dette er et positivt tall.") else: print("Dette er et negativt tall.") a = float(input("a: ")) b = float(input("b: ")) if compareNr(a, b): print("The numbers are equal") else: print("The numbers are not equal") if __name__ == "__main__": main()
778ffeb74ddaae6e0d01d15ddb73219948b30722
Team-Tomato/Learn
/Juniors - 1st Year/Suvetha Devi/day4/string_rev.py
164
4.3125
4
def reverse(word): i= -1 while i>=-(len(word)): print (word[i] ,end =" ") i-=1 str = input("Enter a string to reverse") reverse(str)
b7ac006a135cd006f47d30b1120d59f1a390cad5
RadkaValkova/SoftUni-Web-Developer
/Programming Basics Python/02 Simple_Conditions_Exam Problems/Scholarship.py
1,305
3.59375
4
import math income = float(input()) success_aver = float(input()) minimal_selary = float(input()) scholarship = 0 social_scholarship = math.floor(minimal_selary * 0.35) susccess_scholarship = math.floor(success_aver * 25) sotial_scholarship_aprooved = income < minimal_selary and success_aver > 4.50 and success_aver < 5.50 success_scholarship_aprooved = success_aver >= 5.50 if not success_scholarship_aprooved and not sotial_scholarship_aprooved: print('You cannot get a scholarship!') elif income < minimal_selary and success_scholarship_aprooved: if social_scholarship > susccess_scholarship: scholarship = social_scholarship print(f'You get a Social scholarship {scholarship} BGN') elif susccess_scholarship > social_scholarship: scholarship = susccess_scholarship print(f'You get a scholarship for excellent results {scholarship} BGN') else: scholarship = susccess_scholarship print(f'You get a scholarship for excellent results {scholarship} BGN') elif sotial_scholarship_aprooved: scholarship = social_scholarship print(f'You get a Social scholarship {scholarship} BGN') elif success_scholarship_aprooved: scholarship = susccess_scholarship print(f'You get a scholarship for excellent results {scholarship} BGN')
b9d150f16ff77823ad3e651ddbb0819d94c49645
mbryant1997/mbryant1997
/atmProject4.py
5,270
3.984375
4
from datetime import datetime import random import validation import database from getpass import getpass #register # username, password, and email address #generate user account # login #username or email and password #bank operations #initialize the System def init(): now = datetime.now() print (now) print("Welcome to Bank Py") try: haveAccount = int(input("Do you have an account with us? 1 for yes and 2 for no: ")) if (haveAccount == 1): login() elif (haveAccount == 2): register() except ValueError: print("Please enter a number") init() else: print("You have selected an invalid option") init() def login(): print("Login to your account") global accountNumFromUser accountNumFromUser = (input ("What is your account number? To go back, press 0 \n")) if (accountNumFromUser == 0): init() isValidAccountNum = validation.accountNumValidate(accountNumFromUser) if isValidAccountNum: #passwordUser = input ("What is your password?\n") passwordUser = getpass("What is your password?\n") user= database.authenticateUser(accountNumFromUser, passwordUser) if (user): database.createCurrentSesh(accountNumFromUser, user) bankOp(user) else: print ("Invalid password") login() else: print ("Account number invalid: check that you have 10 digits and only integers") init() def register(): print ("***Please Register***") email = input ("What is your email address?\n") fName = input ("What is your first name?\n") lName = input ("What is your last name?\n") #password = input ("Create a password for yourself \n" ) password = getpass ("Create a password for yourself:\n" ) accountNumber = genAccount() isUserCreated = database.create(accountNumber,fName,lName,email,password) if isUserCreated: print("Your account has been created") print("=== ==== ==== ==== ==== ==== ===") print("Your account number is %d " %accountNumber) print("=== ==== ==== ==== ==== ==== ===") print("Keep this information safe") print("=== ==== ==== ==== ==== ==== ===") login() else: print("Something went wrong. Please try again") register() def bankOp(user): print ("Welcome %s %s!" %(user[0], user[1])) print("These are the available options: ") print("1. Withdrawal ") print("2. Cash Deposit ") print("3. Complaint ") print("4. Logout") choice = int(input("What option number would you like to do today? ")) if (choice ==1): withdrawal(user) elif (choice ==2): deposit(user) elif (choice ==3): complaint() elif (choice ==4): logout() init() else: print("Invalid option)") bankOp(user) def withdrawal(user): currentAmount = float(user[4]) print ("Your current balance is $%.2f" %currentAmount) withdraw = float (input("How much would you like to withdraw? $")) try: if (withdraw <= currentAmount): balance = currentAmount - withdraw #updateBalance = database.update(balance) #newAmount = user[0] + "," + user[1] + "," + user[2] + "," + user[3] + "," + str(balance) isNewAmount = database.newAmountTotal(accountNumFromUser, user) if (isNewAmount): print("Your new balance is $%.2f" %balance) print ("Please take your cash") else: print("Not enough funds in your account") except AttributeError: print("Please try again") withdrawal(database) check = True while check == True: anyMore = int(input ("Is that all for today? 1 for yes and 2 for no \n")) if (anyMore ==1): check = False logout() init() elif (anyMore == 2): check=False login() else: print("Invalid option") check = True def deposit(user): currentAmount = float(user[4]) print ("Your current balance is $%.2f" %currentAmount) depo = float (input("How much would you like to deposit? $")) try: balance = currentAmount + depo #newAmount = user[0] + "," + user[1] + "," + user[2] + "," + user[3] + "," + str(balance) isNewAmount = database.newAmountTotal(accountNumFromUser, user) if (isNewAmount): print ("Please insert your cash") print("Your new balance is $%.2f" %balance) except AttributeError: print("Please try again") deposit(user) check = True while check == True: anyMore = int(input ("Is that all for today? 1 for yes and 2 for no \n")) if (anyMore ==1): check = False logout() init() elif (anyMore == 2): check=False login() else: print("Invalid option") check = True def complaint(): issue = input ("What issue would you like to report? ") print ("Thank you for contacting us") check = True while check == True: anyMore = int(input ("Is that all for today? 1 for yes and 2 for no \n")) if (anyMore ==1): check = False logout() init() elif (anyMore == 2): check=False login() else: print("Invalid option") check = True def logout(): database.deleteCurrentSesh(accountNumFromUser) print("Goodbye") def genAccount(): return random.randrange(1111111111,9999999999) #print (genAccount()) init()
50f92fd24e6caa16e7a16187a3d06c65193f4980
enextus/python_learnstuff
/fibonacci_yield_rev.2.py
517
3.59375
4
# Eduard # die yield funktion def my_fibonacci_range(): # anfangsparameter for fib liste fibbonacci_folge = [] sequence_number = [] i = 1 # recursive fibonacci function def recur_fibo(n): if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) # endlose Schleife while True: fibbonacci_folge.append(recur_fibo(i)) sequence_number.append(i) yield fibbonacci_folge[-1] i = i + 1 # create a yield object p = my_fibonacci_range() # ausgabe for i in range(35): print(next(p))
34796cb1db063fcc8268f21cfa0788fbd7751b6f
inon19-meet/YL1-201718
/agario_proj.py
4,771
3.578125
4
import turtle import math import time import random from ball import Ball turtle.tracer(delay=0) turtle.hideturtle() RUNNING = True SLEEP = 0.0077 SCREEN_WIDTH = turtle.getcanvas().winfo_width()/2 SCREEN_HEIGHT = turtle.getcanvas().winfo_height()/2 MY_BALL=Ball(10,10,10,10,5,"red") NUMBER_OF_BALLS = 5 MINIMUM_BALL_RADIUS = 10 MAXIMUM_BALL_RADIUS = 100 MINIMUM_BALL_DX = -5 MAXIMUM_BALL_DX = 5 MINIMUM_BALL_DY = -5 MAXIMUM_BALL_DY = 5 BALLS = [] for i in range(NUMBER_OF_BALLS): x = random.randint(int(-SCREEN_WIDTH) + MAXIMUM_BALL_RADIUS,int(SCREEN_WIDTH) - MAXIMUM_BALL_RADIUS) y = random.randint(int(-SCREEN_HEIGHT) + MAXIMUM_BALL_RADIUS,int(SCREEN_HEIGHT) - MAXIMUM_BALL_RADIUS) dx = random.randint(MINIMUM_BALL_DX,MAXIMUM_BALL_DX) dy = random.randint(MINIMUM_BALL_DY,MAXIMUM_BALL_DY) redius = random.randint(MINIMUM_BALL_RADIUS,MAXIMUM_BALL_RADIUS) color =(random.random(),random.random(),random.random()) d1 = Ball(x,y,dx,dy,redius,color) BALLS.append(d1) def move_all_balls(): for ball in BALLS: ball.Move(SCREEN_WIDTH,SCREEN_HEIGHT) def collide(ball1,ball2): if ball1.pos()==ball2.pos(): return False D = math.sqrt(math.pow(ball2.xcor()-ball1.xcor(),2)+math.pow(ball2.ycor()-ball1.ycor(),2)) summ = ball1.r+ball2.r if(D>summ): return False if(D<summ): return True def check_collision(): for ball1 in BALLS: for ball2 in BALLS: if collide(ball1,ball2): br1 = ball1.r br2 = ball2.r x_cor = random.randint(int(-SCREEN_WIDTH) + MAXIMUM_BALL_RADIUS,int(SCREEN_WIDTH) - MAXIMUM_BALL_RADIUS) y_cor = random.randint(int(-SCREEN_HEIGHT) + MAXIMUM_BALL_RADIUS,int(SCREEN_HEIGHT) - MAXIMUM_BALL_RADIUS) dx_speed = random.randint(MINIMUM_BALL_DX,MAXIMUM_BALL_DX) dy_speed = random.randint(MINIMUM_BALL_DY,MAXIMUM_BALL_DY) redius = random.randint(MINIMUM_BALL_RADIUS,MAXIMUM_BALL_RADIUS) color =(random.random(),random.random(),random.random()) if br1<br2: ball1.x = x_cor ball1.y = y_cor ball1.goto(x_cor,y_cor) ball1.dx = dx_speed ball1.dy = dy_speed ball1.r = redius ball1.shapesize(redius/10) ball1.color(color) ball2.r=br2+1 ball2.shapesize(ball2.r/10) if br1>br2: ball2.x = x_cor ball2.y = y_cor ball2.goto(x_cor,y_cor) ball2.dx = dx_speed ball2.dy = dy_speed ball2.r = redius ball2.shapesize(redius/10) ball2.color(color) ball1.r=br2+1 ball1.shapesize(ball2.r/10) def check_myball_collision(): for MY_Ball in BALLS: for ball in BALLS: if collide(MY_BALL,ball): br11 = ball.r brMB = MY_BALL.r x_cor = random.randint(int(-SCREEN_WIDTH) + MAXIMUM_BALL_RADIUS,int(SCREEN_WIDTH) - MAXIMUM_BALL_RADIUS) y_cor = random.randint(int(-SCREEN_HEIGHT) + MAXIMUM_BALL_RADIUS,int(SCREEN_HEIGHT) - MAXIMUM_BALL_RADIUS) dx_speed = random.randint(MINIMUM_BALL_DX,MAXIMUM_BALL_DX) dy_speed = random.randint(MINIMUM_BALL_DY,MAXIMUM_BALL_DY) redius = random.randint(MINIMUM_BALL_RADIUS,MAXIMUM_BALL_RADIUS) color =(random.random(),random.random(),random.random()) if brMB<br11: ball.x = x_cor ball.y = y_cor ball.dx = dx_speed ball.dy = dy_speed ball.r = redius ball.color = color if brMB>br11: brMB=brMB+1 if(MY_BALL.r<ball.r): return False return True def movearound(event): MY_BALL.goto(event.x-SCREEN_WIDTH,SCREEN_HEIGHT-event.y) turtle.getcanvas().bind("<Motion>", movearound) turtle.listen() while RUNNING == True: if SCREEN_WIDTH!=turtle.getcanvas().winfo_width()/2 or SCREEN_HEIGHT != turtle.getcanvas().winfo_height()/2: SCREEN_WIDTH=turtle.getcanvas().winfo_width()/2 SCREEN_HEIGHT = turtle.getcanvas().winfo_height()/2 move_all_balls() check_collision() #MY_BALL.Move(SCREEN_WIDTH, SCREEN_HEIGHT) check_myball_collision() turtle.update() time.sleep(SLEEP)
6e6bbe49dc05d4acc53c00f7f371962666ea92ff
coco-in-bluemoon/baekjoon-online-judge
/CLASS 1/1157: 단어 공부/solution.py
727
3.71875
4
from collections import defaultdict def solution(word): frequency_dictionary = defaultdict(int) word = word.upper() for character in word: frequency_dictionary[character] += 1 frequency_dictionary = sorted( frequency_dictionary.items(), key=lambda x: x[1], reverse=True ) if len(frequency_dictionary) == 1: return frequency_dictionary[0][0] if frequency_dictionary[0][1] == frequency_dictionary[1][1]: return '?' return frequency_dictionary[0][0] if __name__ == "__main__": word = 'Mississipi' assert solution(word) == '?' word = 'zZa' assert solution(word) == 'Z' word = input().strip() answer = solution(word) print(answer)
fd8bed7c139716eb8d1f6543167f8001afec4814
hjs90911/1804_Learning_MachineLearning
/Day_2/regression_basic.py
875
3.8125
4
# -*- coding: ms949 -*- from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import mglearn import matplotlib.pyplot as plt X, y = mglearn.datasets.make_wave(n_samples=60) print(X.shape, y.shape) plt.plot(X, y,'o') # 'o' make scatter plot plt.ylim(-3, 3) plt.xlabel("feature") plt.ylabel("target") plt.show() X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) lr = LinearRegression().fit(X_train, y_train) # Transfer train data plt.plot(X, y, 'o', X, lr.predict(X)) plt.show() print("lr.coef_L: {}".format(lr.coef_)) # (slope) print("lr.intercept_: {}".format(lr.intercept_)) # y """Accuracy will Increase if dataset increase""" print("train score:{:.2f}".format(lr.score(X_train, y_train))) print("test score:{:.2f}".format(lr.score(X_test, y_test)))
37750f264e542bcc75eadc01ffa81049b07b5c9b
Lancasterwu/gatorgrouper
/gatorgrouper/tests/test_absent.py
2,212
3.90625
4
"""Testing if absent.py correctly handles being absent""" from utils import remove_absent_students def test_remove_absent_students(): """Testing the remove_absent_students() function with an input that includes one absent student""" list_of_students = [ ["student1", 0, 1, 0], ["student2", 1, 0, 1], ["student3", 1, 1, 0], ] list_of_absent_students = ["student2"] desired_output = [["student1", 0, 1, 0], ["student3", 1, 1, 0]] actual_output = remove_absent_students.remove_absent_students( list_of_absent_students, list_of_students ) assert len(list_of_students) == 3 assert (desired_output == actual_output) is True def test_remove_absent_students_one(): """Checking to see if absent one student is removed""" absent_list = ["Nick"] list_of_student_of_lists = [ ["Nick", False, True, False], ["Marvin", False, True, True], ["Evin", True, True, False], ] removed_list = remove_absent_students.remove_absent_students( absent_list, list_of_student_of_lists ) assert (absent_list in removed_list) is False assert len(removed_list) == 2 def test_remove_absent_students_two(): """Checking to see if absent two students is removed""" absent_list = ["Nick", "Marvin"] list_of_student_of_lists = [ ["Nick", False, True, False], ["Marvin", False, True, True], ["Evin", True, True, False], ] removed_list = remove_absent_students.remove_absent_students( absent_list, list_of_student_of_lists ) assert (absent_list in removed_list) is False assert len(removed_list) == 1 def test_remove_absent_students_all(): """Checking to see if absent all students are removed""" absent_list = ["Nick", "Marvin", "Evin"] list_of_student_of_lists = [ ["Nick", 0, 1, 0], ["Marvin", 0, 1, 1], ["Evin", 1, 1, 0], ] correct = [] removed_list = remove_absent_students.remove_absent_students( absent_list, list_of_student_of_lists ) assert (absent_list in removed_list) is False # is the list empty assert not removed_list assert correct == removed_list
08a7fffde54b101b159043394358ec0a222fd2ce
vinitjfaria/Python
/HackerEarth/Factorial.py
456
4.0625
4
'''Using the Python language, have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it (e.g. if num = 4, return (4 * 3 * 2 * 1)). For the test cases, the range will be between 1 and 18 and the input will always be an integer.''' def FirstFactorial(num): fact=1 for number in range(1,num+1): fact = fact*number return fact # keep this function call here print(FirstFactorial(8))
12cc871475127be492e9c10aa49cc7087b4e2c51
standardgalactic/graph
/graph/graph_visualizer.py
1,165
3.765625
4
from .graph import Graph from PIL import Image import pydot import tempfile def display_graph(graph, graph_name=None): """ Generate graph image by using pydot and Graphviz Display graph image by using PIL (Python Image Library) """ graph_type = "digraph" if graph.is_directed() else "graph" pydot_graph = pydot.Dot(graph_type=graph_type) if graph_name: pydot_graph.set_label(graph_name) # draw vertices for vertex in graph.get_vertices().values(): node = pydot.Node(vertex.get_label()) node.set_style("filled") node.set_fillcolor("#a1eacd") pydot_graph.add_node(node) # draw edges for edge in graph.get_edges(): start_vertex_label = edge.get_start_vertex().get_label() end_vertex_label = edge.get_end_vertex().get_label() weight = str(edge.get_weight()) pydot_edge = pydot.Edge(start_vertex_label, end_vertex_label) pydot_edge.set_label(weight) pydot_graph.add_edge(pydot_edge) temp = tempfile.NamedTemporaryFile() pydot_graph.write_png(temp.name) image = Image.open(temp.name) temp.close() image.show()
91526c2632a1b08553c35eda93279327addf79fc
KyrillosL/AlgorithmeGenetique
/classes.py
5,573
3.71875
4
''' 5 Flips puis 3 Flips puis 1 flip -> Utiliser la roulette -> Mettre à jour à chaque fois la moyenne. Au départ la même probabilité. Calculer la meilleure amélioration à chaque tout. Pour l'instant on enlève le croisement Sous forme de tableau ecart type voir photo Faire des courbes lisses en faisant la moyenne des représentations Garder les mêmes graines aléatoires. bit flip chaque gene a 1/N chance de changer 1 flip yen a qu'un qui change sur tout le chromosome ''' #Various import import random from copy import copy import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) class Agent: """ An agent has data (a string containing a number of "0") and the length of the string. For this problem, the score is the number of 1 in the string. We can perform various mutations on the string """ def __init__(self, data, id): self.data = np.array(data) self.size = len(data) self.id = id self.score =0 self.age = 0 def __str__(self): #return "Agent " + str(self.id) + ", " + ''.join(self.data) + " | Score : " + str(self.get_score()) return "Agent " + str(self.id) + ", " + str(self.data.tolist()) + " | Score : " + str(self.get_score()) def __repr__(self): return self.__str__() def __gt__(self, other): return (self.score > other.score) def __copy__(self): return Agent(self.data, self.id) def get_score(self): self.score= 1 - ((self.size - np.sum(self.data)) / self.size) return self.score class Population: def __init__(self, nb_agent=0, taille_agent=0): self.taille_agent=taille_agent self.nb_agent = nb_agent self.agents = [] for x in range(nb_agent): l = [0 for y in range(taille_agent)] #l = [random.randrange(0, 2) for y in range(taille_agent)] #self.agents.append(Agent("".join(str(x) for x in l), x)) self.agents.append(Agent( l, x)) self.sort() def sort(self): self.agents.sort(reverse=True) def __str__(self): string_to_return = "" for agent in self.agents: string_to_return =string_to_return+ (agent.__str__()+"\n") return string_to_return def __repr__(self): return self.__str__() def get(self, index): return self.agents[index] def set(self, index, agent): self.agents[index]=agent def get_agents(self): return self.agents def select_best_agents(self,number_of_agent_to_return): new_population_to_return = Population() new_population_to_return.add_agents(self.agents[:number_of_agent_to_return]) return new_population_to_return def select_random_agents(self,number_of_agent_to_return): new_population_to_return = Population() agents_in_population = self.agents.copy() for x in range(number_of_agent_to_return): random_number = random.randrange(0, len(agents_in_population)) new_population_to_return.add_an_agent(agents_in_population[random_number]) agents_in_population.remove(agents_in_population[random_number]) return new_population_to_return def select_tournament_agents(self,number_of_agent_to_return, number_of_turn ): copy_of_agents=self.agents.copy() new_population_to_return = Population() for x in range(number_of_agent_to_return): population_with_best_agent = copy_of_agents[random.randrange(0, len(copy_of_agents))] for y in range(number_of_turn): population_with_new_agent=copy_of_agents[random.randrange(0, len(copy_of_agents))] if (population_with_best_agent.score() <population_with_new_agent.score() ): population_with_best_agent=population_with_new_agent new_population_to_return.add_an_agent(population_with_best_agent) copy_of_agents.remove(population_with_best_agent) return new_population_to_return def croisement(self, agent1, agent2): #@TODO : ADD ONE POINT TO SLICE agent1Temporaire = copy(agent1) agent2Temporaire = copy(agent2) agent1.data = agent1.data[:int((agent1.size)/2)] #Cut the string at the half agent1.data += (agent2.data[int((agent2.size)/2):]) #Append the end of the second one agent2.data = agent2Temporaire.data[:int((agent2Temporaire.size)/2)] agent2.data += (agent1Temporaire.data[int((agent1Temporaire.size)/2):]) def remove_worst_agents(self): list_to_return = [] list_to_return.append( min(self.agents).id) self.agents.remove(min(self.agents)) list_to_return.append( min(self.agents).id) self.agents.remove(min(self.agents)) return list_to_return def remove_old_agents(self): list_to_return = [] for x in range(2): max_age = self.agents[0].age oldest_agent =self.agents[0] for a in self.agents: if max_age< a.age: max_age=a.age oldest_agent=a list_to_return.append(oldest_agent.id) self.agents.remove(oldest_agent) return list_to_return def add_agents(self,agents): for agent in agents: self.agents.insert(0,agent) self.sort() def add_an_agent(self, agent, pos): self.agents.insert(pos, agent) self.sort() #print("ADDED AN") #print(self.agents)
406c780d5063ef5cc85b6dda7ffb3a63ee1c8305
Immortalits/Python-fuggvenyek
/4-feladat.py
336
3.6875
4
import math sugar = input('Add meg a kör sugarát: ') def convert_to_number(sugar): r = int(sugar) return r def kerulet(r): kerulet = 2 * math.pi * convert_to_number(r) return kerulet def terulet(r): terulet = math.pi * convert_to_number(r)**2 return terulet print(kerulet(sugar)) print(terulet(sugar))
74b29454497d520cccec4b5b1682615a0e120be7
darrencheng0817/AlgorithmLearning
/Python/leetcode/BasicCalculatorIi.py
576
3.765625
4
''' Created on 1.12.2016 @author: Darren '''''' Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. You may assume that the given expression is always valid. Some examples: "3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5 Note: Do not use the eval built-in library function. Credits:Special thanks to @ts for adding this problem and creating all test cases." '''
13589da6c473552ff79b04c44dff0f9bce710caa
jnkg9five/Python_Crash_Course_Work
/Loop_Lists.py
7,853
4.5
4
#Python_List_Exercise #PYTHON CRASH COURSE Chapter#4 LISTS #What is a List? #List is a collection of elementss in a particular order. #You can put any data you want in a list. #elementss in a list don't have to be categorically related. ex. Integers, Strings, Floatpoints #In Python, a list is contains in square brackets. ######################################### # Looping through a List ######################################### #You want to run through all entries in a list. #You want to do the same operation with each element. #We have a list and we want to get every element of the list printed. HOW TO? cars = ['Zonda','Agera','Carrera_GT','Veyron'] for car in cars: print(cars) #We just used a for loop to print all the elements in the list cars #the for loop has a temporary variable that holds each value in the list for each rescursion. #Recursion is the method or concept of repeating the same call or function over and over again. #Iteration is the method or concept of having a call or function repeated until a certain condition is met. #Recursion uses more memory and is slower on a computer machine. Less complex than iterative solutions. #You can show the concept of recursion by printing multiple times with a for loop in Python cars2 = ['ID_3','Model_3','Bolt','Leaf','Rimac_C2'] for car in cars2: print(car.title() + ", is my favorite car.") #You can keep having recursion on every line within the for loop print(car.lower() + ", is my favorite car.") #Use tab or space not both to indicate when the scope of your loop ends print(car + "is my favorite car.") #notice how the last value of the temp variable is still maintained in memory. ######################################### # Numerical Lists / Indentation Errors ######################################### # Python uses indention (tab/spaces not mixed) to determine is lines of code are connected. # The indentations in Python show the overall program's organization. # DO NOT MIX SPACES OR TABS. #You can use the range() function to generate a series of numbers. for value in range(1,10): print(value) #Now you can use the range() function is the list() function to create a list within the range parameters. numbers = list(range(1,15)) print(numbers) #The range function can take a third parameter to iterate by a value until list is complete numbers = list(range(0,100,10)) print(numbers) #Lets now combine several concepts of for loops, numerical lists, and operand for exponents **. squares = [] for value in range(1,10): square = value**2 squares.append(square) print(squares) #The above function declared a list variable squares. Then uses a for loop to create a list with temp value var. #The range function specifies the size of the list to be made. #The squared value is stored in temp var square and then append() to the squares list and finally printed. #BUT you can make the code more concise. square2 = [] for value in range(1,15): square2.append(value**2) print(squares) #There are some statistical functions you can apply to lists. digits = range(2,10,2) mini = min(digits) maxi = max(digits) total = sum(digits) print("The min value of digits is " + str(mini) + ". The max value is " + str(maxi) + ". The total value is " + str(total) + ".") #List Comprehensions can generate more complex logic for lists. #It combines the for loop and adds to new elements and appends them to the list in the same line. squares = [value**2 for value in range(1,10)] print(squares) ######################################### # Numerical Lists Pratice Exercises ######################################### #Use a for loop to print the numbers from 1 to 20 inclusive. for numbers in range(1,21): print(numbers) #Print the numbers one to one million, then use min() and max() to make sure your list starts at 1. Ends at 1 million. one2onemil = range(1,1000**2+1) mini = min(one2onemil) maxi = max(one2onemil) total = sum(one2onemil) print(total) #Make a list of the ODD NUMBERS, use the range() functions from 1 to 20, print each number. oddnum = range(1,21,2) for numbers in oddnum: #oddnum defines the list size in the for loop print(numbers) #Make a list of the multiples of 3 from 3 to 30. Use a for loop to print the list. threethirty = range(3,31,3) for numbers in threethirty: print(numbers) #MAke a list of the first 10 cubes and use a for loop to print out the value of each cube. thecubes = list(range(1,11)) #cannot perform operand on entire list all at once cubes = [] for cube3 in range(0,10): cubes.append(thecubes[cube3]**3) #You have to index from 0. print(cubes) #Use a list comprehension to egenerate a list of the first 10 cubes. cubes22 = [value**3 for value in range(1,11)] print(cubes22) ######################################### # Partitioning/Slicing a List ######################################### #You can slice a list to segment part of it to manipulate or change. character = ['charles','martina','michael','florence','eli'] print(character[0:3]) #this will print [charles, martine, michael] index 0 #You can slice from the beginning of a list automatically print(character[:3]) #will print the same as above. #And you can slice from a specific index to the end of the list print(character[3:]) #And don't forget that negative index number will rollback from the end of the list. print(character[-3:]) #Slices are useful in for instance games. You can add a player's final score to a list every time a player finishes playing. #You can get the top 3 scores by slicing the first three scores. So when working with data, you can use slices #So here is a list slice to show the top three characters. print("Here are the top three characters in my book series: ") for player in character[:3]: print(player.title()) #NOW you can go and copy a list. #Lets say you want to make a new list of an existing list you instantiated. #Lets make a list of favorite foods. Then copy that list to a list for my friends favorite food. my_foods = ['pizza','falafel','carrot_cake'] friend_foods = my_foods[:] #using [:] copies the entire list print("My favorite foods are: ") print(my_foods) print("\nMy friend's favorite foods are also: ") print(friend_foods) #There are TWO seperate lists. They are not linked lists. To demonstrate, we will append another element to one. friend_foods.append('jackfruit') print(friend_foods) my_foods.append('mango') print(my_foods) #To set two different lists, you have to use slicing [:] ######################################### # Partitioning/Slicing a List Exercises ######################################### #Using the programs add several lines to the end of the programs you written. #Print the first three items in the lists. print("The first three items in the list are: ") print(my_foods[:3]) #Print the three items from the middle of the list. print("The items from the middle of the list are: ") print(my_foods[2:4]) #Print the three items for the last three of the list. print("The last three items in the list are: ") print(my_foods[-3:]) ######################################### # Tuples ######################################### #List work well for storing sets of elements. Sometimes you want a list that cannot change. #You can use Tuples. Python has values that cannot change/immutable. #An immutable list is called a tuple. #Tuples look like a list except you use paretheses (). dimension = (200, 50) print(dimension[0]) #200 print(dimension[1]) #50 #dimension[0] = 250 This will not work, reassigning tuple value not allowed. #To change tuple, you have to redefine the entire tuple list. dimension = (400, 100) #block defines the tuple. print(dimension[0]) print(dimension[1]) #tuples are simple data structures. for dim in dimension: #You can use the for loop. print(dim) #END/FINALE
8f6f65e1d48ee45e1d3e7e1389a304ad2e135a95
macavas/PythonRainCode
/PyGameRain.py
1,042
3.71875
4
import pygame import random width = 1080 height = 720 class Drop: x = 0 y = 0 dropWidth = 3 dropHeight = 15 vel = 3 def fall(self): self.y += self.vel if self.y > (height): self.y = random.randint(0,height)-height pygame.draw.rect(win, (55,55,255), (self.x, self.y, self.dropWidth, self.dropHeight)) pygame.init() win = pygame.display.set_mode((width,height)) pygame.display.set_caption("First Game") sizes = [1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,5] drops = [] for x in range(500): drops.append(Drop()) drops[x].x = random.randint(0,width) drops[x].y = random.randint(0,height) - height size = sizes[random.randint(0,len(sizes)-1)] drops[x].dropWidth = size drops[x].dropHeight = size*5 drops[x].vel = size * 3 + 2 run = True while run: pygame.time.delay(10) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False win.fill((0,0,0)) for drop in drops: drop.fall() pygame.display.update() pygame.quit()
978cfd8fbcbb72c68846e58fc077abd904ddd72d
itsvinayak/algorithms
/algorithms/arrays/random_array.py
661
4.34375
4
""" Given a array/list , return a randomly shuffle array/list this is implementation of "Fisher–Yates shuffle Algorithm",time complexity of this algorithm is O(n) assumption here is, function rand() that generates random number in O(1) time. Examples: Given [1,2,3,4,5,6,7], [5, 2, 3, 4, 1] Given [1,2,3,4,5,6,7], [1,2,3,4,5,6,7] Given [1,2,3,4,5,6,7], [1, 2, 3, 5, 4] """ import random def randomize_array(arr): for i in range(len(arr)-1,0,-1): # To generate a random nummber within it's index j = random.randint(0,i) # Swap arr[i] with the element at random index arr[i],arr[j] = arr[j],arr[i] return arr
789f5173020de042a83dba98db2768ed37e13baf
FlamesSpirit/FlamesSpirit
/SYRACUSE PROBLEM.py
485
4.09375
4
def even(num): reamainder = num % 2 if reamainder == 0: even = True elif reamainder == 1: even = False return even # 3 * x + 1 y = int(input("num: ")) x = y print(even(x)) while x > 2: if x < 2: break while even(x) == True: if x < 2: break x = x // 2 print(x) while even(x) == False: if x < 2: break x = 3 * x + 1 print(x) print(x)
6843d17548fff08011f0aff5733325cd0b0233f3
Kunal2700/Tic-Tac-Toe
/tictactoe.py
3,803
4.0625
4
""" Tic Tac Toe Player """ import math, copy X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Returns player who has the next turn on a board. """ x_count = 0 o_count = 0 for row in board: x_count += row.count(X) o_count += row.count(O) if x_count == o_count: return X else: return O def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ possible_actions = set() for i in range(len(board)): for j in range(len(board)): if board[i][j] == EMPTY: possible_actions.add((i, j)) return possible_actions def result(board, action): """ Returns the board that results from making move (i, j) on the board. """ i, j = action if board[i][j] != EMPTY: raise Exception new_board = copy.deepcopy(board) p = player(board) new_board[i][j] = p return new_board def winner(board): """ Returns the winner of the game, if there is one. """ # Check Horizontal for row in board: if row.count(X) == 3: return X elif row.count(O) == 3: return O # Check Vertical column = [] for i in range(len(board)): for j in range(len(board)): column.append(board[j][i]) if column.count(X) == 3: return X elif column.count(O) == 3: return O column.clear() # Check Diagonal diag = [] for i in range(len(board)): diag.append(board[i][i]) if diag.count(X) == 3: return X elif diag.count(O) == 3: return O diag.clear() for i in range(len(board)): diag.append(board[i][3-i-1]) if diag.count(X) == 3: return X elif diag.count(O) == 3: return O return None def terminal(board): """ Returns True if game is over, False otherwise. """ if winner(board): return True for row in board: for value in row: if value == EMPTY: return False return True def utility(board): """ Returns 1 if X has won the game, -1 if O has won, 0 otherwise. """ if winner(board) == X: return 1 elif winner(board) == O: return -1 else: return 0 def minimax(board): """ Returns the optimal action for the current player on the board. """ if terminal(board): return None AI = player(board) pairs = [] options = set() if AI == O: for action in actions(board): pairs.append((action, max_value(result(board, action)))) values = [pair[1] for pair in pairs] min_action = min(values) for pair in pairs: if pair[1] == min_action: options.add(pair[0]) else: for action in actions(board): pairs.append((action, min_value(result(board, action)))) values = [pair[1] for pair in pairs] max_action = max(values) for pair in pairs: if pair[1] == max_action: options.add(pair[0]) return options.pop() def max_value(board): if terminal(board): return utility(board) v = -math.inf for action in actions(board): v = max(v, min_value(result(board, action))) return v def min_value(board): if terminal(board): return utility(board) v = math.inf for action in actions(board): v = min(v, max_value(result(board, action))) return v
2d6f6f6d0c01b057c6dad67a94ce9bad6817971a
Narendrasinghks2020/python
/multiplication.py
101
3.984375
4
a=input("enter number a:") b=input("enter number b:") c=a*b print "multiplication of two numbers:",c
076caa5b6f0b933c21e83202488d01201b0c2e8b
khushboomehla33/Facebook-Text-Based-Captcha
/what.py
1,069
4.0625
4
from tkinter import * def what1(): root=Tk() head=Frame(root,width=1366,height=45,bg='#3b5998') head.place(x=0,y=0) heading=Label(head,text="What is Captcha?",bg='#3b5998',fg='white',font=('Segoe UI',20,'bold'),justify="center") heading.place(x=5,y=5) text = Label(root, text='\nCAPTCHA is Completely Automated Public Turing Test To Tell Computers and Humans Apart .\nIt was coined in 2000 by Luis von Ahn, Manuel Blum, Nicholas Hopper and John Langford of Carnegie Mellon University.\nA CAPTCHA is a program that protects websites against bots by generating and grading tests that humans can pass but current computer programs cannot.\n For example, humans can read distorted text as the one shown below, but current computer programs can not.\nIf your website needs protection from abuse, it is recommended that you use a CAPTCHA. \nThere are many CAPTCHA implementations, some better than others.',bg='white',font=('verdana' ,12, 'bold')) text.place(x=0,y=50) root.configure(background='white') root.geometry("1366x700+0+0") root.mainloop()
823d8f79d90a4b3224c279c9e3c458abc8fbd1c2
Audarya07/Daily-Flash-Codes
/Week5/Day2/Solutions/Python/prog2.py
153
4.125
4
num = int(input("Enter octal number:")) base = 1 rem = 0 while num: rem += (num%10)*base num//=10 base *= 8 print("Decimal number:",rem)
b290ea5c8aa63592924f54a999eaa451267256f3
yu-11-22/python_training
/set-dictionary.py
835
4.03125
4
# 集合的運算 s1 = {3, 4, 5} print(3 in s1) print(10 not in s1) s2 = {4, 5, 6, 7} s3 = s1 & s2 # 交集,兩個集合中,相同的資料 print(s3) s4 = s1 | s2 # 聯集,取兩個集合中的所有資料,但不重複取 print(s4) s5 = s1-s2 # 差集,從s1中減去s2重疊的部分 print(s5) s6 = s1 ^ s2 # 反交集,取兩個集合中,不重疊的部分 print(s6) s = set("Hello") # set(字串),把字串中的字母拆解成集合 print(s) print("H" in s) # 字典的運算:key-value 配對 dic = {"apple": "蘋果", "bug": "蟲"} print(dic["apple"]) print("bug" in dic) print(dic) del dic["apple"] # 刪除字典中的鍵值對(key-value pair) print(dic) dictionary = {x: x*2 for x in [3, 4, 5]} # [3,4,5]為列表,從列表的資料產生字典 print(dictionary) dictionary = {x: x*2 for x in ["Hello"]} print(dictionary)
0552e6d3292512ce43b913ca0ad45f8554c16a74
guilhermebaos/Curso-em-Video-Python
/1_Python/Desafios/093_Informação_jogador_futbol.py
860
3.703125
4
info = dict() total = 0 info['nome'] = str(input('Nome do jogador: ')).strip() while True: jogos = str(input('Número de jogos jogados: ')).strip() if jogos.isnumeric(): jogos = int(jogos) break else: print('Escreve só o número!\n') info['golos'] = [] for c1 in range(0, jogos): while True: g = str(input(f'Núemro de golos marcados pelo jogador no {c1 + 1}º jogo: ')).strip() if g.isnumeric(): g = int(g) break else: print('Escreve só o número!\n') info['golos'].append(g) total += g info['total'] = total print(f'\nO jogador {info["nome"]} marcou no total {info["total"]} golos:') for c2 in range(0, jogos): print(f' >>> {info["golos"][c2]} golos no {c2 + 1}º jogo') print(f'\nO que dá uma média de {total / jogos:3} golos por jogo!')
dbcdf1a6f3c7fd1f48817cce89a059cc329a6357
gabrielaraujo3/exercicios-python
/exercicios/ex16.py
137
3.734375
4
import math n1 = float(input('Digite um valor: ')) ni = math.trunc(n1) print('A porção inteira do número digitado é {}.'.format(ni))
43dc2a11a1dc6558bd95ab0a942fb9d33707e7e5
schappidi0526/IntroToPython
/4_1_loops.py
1,156
4.09375
4
#forloop numbers = range(0,11) for number in numbers: print (number) #while loop Numbers=[1,2,3,4,5,6,7] print (len(Numbers)) indexid=0 while indexid<len(Numbers): print (Numbers[indexid]) indexid=indexid+1 # Find all the odd numbers between 1 and 20. Append them to a string with spaces in between. # Like so Numbers= range(0,20) odd_numbers='' for number in Numbers: cat=number%2 if int(cat)>0: odd_numbers=odd_numbers+str(number) + ' ' print (odd_numbers.strip()) #this is working here but not in the udemy class note # Numbers= range(0,20) # odd_numbers=[] # cat=0.0 # #print (cat) # for number in Numbers: # cat=number%2 # print ("for " + str(number) + " reminder is "+str(cat)) # print (cat) # if int(cat)>0: # odd_numbers.append(number) # #print (odd_numbers) # odd_numbers_str=str(odd_numbers[0])+' '+str(odd_numbers[1])+' '+str(odd_numbers[2])+' '+str(odd_numbers[3])+' '+str(odd_numbers[4])+' '+str(odd_numbers[5])+' '+str(odd_numbers[6])+' '+str(odd_numbers[7])+' '+str(odd_numbers[8])+' '+str(odd_numbers[9]) # print (odd_numbers_str)
04cba82e9f81dc9e5b7ec8b544cba43fa059e93e
joenco/simredop
/funtion.py
1,870
3.515625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # funciones para el simulador experimental de redes completamente opticas # Autor: Marielb Marquez - Jorge Ortega # Cotutor: Andrés Arcia-Moret # # -*- coding: utf-8 -*- def crearmalla(n): n = n a = [] l = 0 t=k = 0 nodos = 2*n-1 for j in range(nodos): l += 1 for i in range(n): a.append([]) if l%2 != 0: t += 1 a[k].append(t) if i < n-1: a[k].append('-') else: a[k].append('|') a[k].append(' '), k += 1 return a def cambiarmalla(malla, n, a, b): malla = malla n = n a = a b = b nodos = 2*n-1 for i in range(nodos): for j in range(nodos): if malla[i][j] == a: x=i y=j for i in range(nodos): if malla[x][i] == b: if a < b: malla[x][i-1] = ' => ' else: malla[x][i+1] = ' <= ' break; if malla[i][y] == b: if a < b: malla[i-1][y] = '||' else: malla[i+1][y] = ' || ' break; return malla def mayordispo(malla, pos, salida): malla = malla pos = pos salida = salida mayor = 0 for k in range(1, 5): if malla[pos][k] != 0: if salida == malla[pos][k]: mayor = salida else: if salida - malla[pos][k] < salida - malla[pos][k+1]: if salida - malla[pos][k] > 0: mayor = malla[pos][k] else: mayor = malla[pos][k+1] else: if salida - malla[pos][k] < 0: mayor = malla[pos][k+1] else: mayor = malla[pos][k] return mayor def graficarmalla(malla, e, s): malla = malla e = e s = s h=0 for i in malla: for j in i: h=0 for k in e: if k == j: h=k if h == 0 and s[0] != j: print j, elif h==j: print str(j)+'E', else: print str(j)+'S', print ""
0a92c53b9165af7dc226c42fc40b7f901907d464
vardhan-duvvuri/Challange
/ch22.py
231
3.84375
4
def countLetters(word): letters = [] for i in word: letters.append(i) letters = set(letters) output = {} for i in letters: output[i] = word.count(i) return output if __name__ == "__main__": print countLetters('google')
722732060e57294fc203928595b526a8da3c338a
ansh-arora/assignments
/assignment-18.py
1,178
3.953125
4
#Q1 from tkinter import * # main= Tk() # Label(main, text='Hello World!').pack() # Button(main, text='Exit',command= sys.exit, activeforeground='red' ).pack() # mainloop() #Q2 # def press(): # print('hiii') # Label(main, text='Hello Again !!').pack() # main= Tk() # Label(main, text='Hello World!').pack() # Button(main, text='Exit',command= sys.exit, activeforeground='red' ).pack() # Button(main, text='Press me !',command= press, activeforeground='Blue' ).pack() # mainloop() #Q3 # main=Tk() # def change(): # l.configure(text='Hi hello!!') # f=Frame(main).pack() # l=Label(f, text='hello') # l.pack() # Button(f, text='Press me to change the text', activeforeground='blue',command=change).pack() # Button(main, text='Exit',command= sys.exit, activeforeground='red' ).pack() # mainloop() #Q4 # def p(e): # print('your name is:',e) # Label(main, text='You entered your name as :').grid(row=1) # Label(main, text=e).grid(row=1,column=1) # main=Tk() # Label(main,text='Your name').grid(row=0) # e=Entry(main) # e.grid(row=0,column=1) # Button(main, text='Submit', activeforeground='blue',command=lambda :p(e.get())).grid(row=0,column=2) # mainloop()
fd7e7ecc4634ada5cd7cd539d9845a532e9cb368
mobai-du/DPJ-1
/Demo/Demo/while循环.py
157
3.515625
4
count = 0 while count <= 100: if count == 50: pass else: print(count) if 60 < count < 80: print(count*count) count+=1
1fb76083eeef473b8afaa9f791f06f40c49a4782
SONGjiaxiu/CS-111
/binary search.py
1,428
4.0625
4
# Binary Search ["bob","joe","alice"] def linearSearch(list,target): for index in range(len(list)): return index return -1 """ say you have to guess a number between 1-100 and the number is 60: 1st guess: 50 2nd guess: 75 3rd guess: 63 4th guess: 56 5th guess: 60 take the middle of either the upper or lower half each time. n(length of list) steps n = 2^(steps-1) 1 1 2 2 steps = log(base 2) (n) +1 number of times to halve it to get to 1 4 3 8 4 16 5 1000 10 1000000 20 1000000000 30 """ def binarySearch(list, target): ''' binary search for position of taget in list pre: list is a sorted list, target is a possible element of list post: return the inder of target in the list, -1 if target is not in the list ''' leftIndex = 0 # left most extreme rightIndex = len(list)-1 # right most extreme while leftIndex <= rightIndex: midIndex = (leftIndex+rightIndex)//2 if list[midIndex] == target: return midIndex elif list[midIndex] < target: leftIndex = midIndex + 1 else: # list[midIndex] > target: rightIndex = midIndex - 1 return -1
c12333009fa3f30e9cd75c6c257a38562b7d3ad1
GenryEden/kpolyakovName
/3689.py
424
3.921875
4
from math import isqrt def isPrime(x): if x == 1: return False if x == 2: return True if x % 2 == 0: return False for i in range(3, isqrt(x)+1, 2): if x % i == 0: return False return True def toCountSystem(x, y): ans = '' while x: ans += hex(x % y)[2:] x //= y return ans[::-1] s = 0 for x in range(2, 10+1): res = toCountSystem(437, x) if isPrime(sum([int(i) for i in res])): s += x print(s)
1333386f0e9952be02aa6bf30ac4560c290a6955
rayga/Python-Script
/linkto.py
357
3.53125
4
# Script for grabbing link in a website __author__ = 'n4rut0' import urllib from bs4 import BeautifulSoup url = raw_input("Enter hostname target : ") u = "http://" uri = u + url read_page = uri.read() parser = BeautifulSoup(read_page, "html.parser") print parser.title print parser.title.text for link in parser.find_all('a'): print(link.get('href'))
44026365aa9b148f102a065915ae7dd48c0442bd
ravisjoshi/python_snippets
/DataStructure/StackAndQueue/stack_balancedParentheses.py
1,087
3.84375
4
""" Given an expression string exp , write a program to examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp. {[]{()}} - Balanced [{}{})(] - Unbalanced ((() - Unbalanced """ class checkParentheseseBalance(): def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def is_empty(self): return self.items == [] def peek(self): if not self.is_empty(): return self.items[-1] p = checkParentheseseBalance() pString = '[{}{}()]' for symbol in pString: if symbol in "[, {, (": p.push(symbol) elif p.is_empty() and symbol in "], }, )": print("Not Balanced!!") exit(0) elif symbol in "]" and p.peek() == '[': p.pop() elif symbol in "}" and p.peek() == '{': p.pop() elif symbol in ")" and p.peek() == '(': p.pop() else: p.push(symbol) if p.is_empty(): print("Evenly Balanced!!") else: print("Not Balanced!!")
4f606534d8e41729e6ea3572240319cd4df374c2
wbreen/PythonWork
/quiz2/Quiz2.py
838
3.875
4
# -*- coding: utf-8 -*- """ William Breen Programming languages quiz 2 """ testOne = {'x':1, 'y':2, 'z':3} testTwo = {'x':1, 'y':2, 'z':2} def invertDictionary(oldDict): invertedDic = {} for key in oldDict: newKey = oldDict[key] newVals = key if newKey in invertedDic: inDicVals = invertedDic[newKey] inDicVals.append(newVals) invertedDic[newKey] = inDicVals else:invertedDic[newKey] = [newVals] return invertedDic print(invertDictionary(testOne)) print(invertDictionary(testTwo)) def fileAndWords(): givenFile = input("Enter a file name:") print(givenFile) #import file to list wordAfter = input("Enter a word:") for word in givenFile: output.append(givenFileList[word+1]) return output fileAndWords()
e2adf9f0e9e1ac235b73515f28228de82dc9948e
sequix/8digits
/astar.py
854
3.875
4
#!/usr/bin/env python3 # -*- coding: utf8 -*- from board import Board from reader import Reader from utils import first_board from priority_queue import PriorityQueue reader = Reader() used = set() board_goal = Board(first_board) que = PriorityQueue(key=lambda board: board.priority) initial_board = reader.read_board() used.add(initial_board) que.push(initial_board) while not que.empty(): board_current = que.pop() if board_current == board_goal: board_goal = board_current break new_boards = [ board_current.move_up(), board_current.move_down(), board_current.move_left(), board_current.move_right() ] for new_board in new_boards: if new_board and new_board not in used: que.push(new_board) used.add(new_board) print(''.join(board_goal.path))
aabef8e3365bbb3f70ffb08103b118f1ffd69d1e
rahul-krupani/foobar
/Level 3/fuel-injection-perfection.py
247
3.53125
4
def solution(n): i = 0; n = int(n) while n != 1: if n%2==0: n = n//2 elif n==3 or n%4==1: n -= 1 else: n += 1 i += 1 return i print(solution('15'))
6f80e95b19b781b1c6438745882a164833d05320
asiftandel96/Object-Oriented-Programming
/Annotations/Basic Annotation.py
5,120
4.40625
4
"""Annotations Annotations were introduced in Python 3.0, originally without any specific purpose. They were simply a way to associate arbitrary expressions to function arguments and return values. Years later, PEP 484 defined how to add type hints to your Python code, based off work that Jukka Lehtosalo had done on his Ph.D. project—Mypy. The main way to add type hints is using annotations. As type checking is becoming more and more common, this also means that annotations should mainly be reserved for type hints. The next sections explain how annotations work in the context of type hints.""" """Function Annotations For functions, you can annotate arguments and the return value. This is done as follows def func(arg: arg_type,optarg: arg_type=default) -> return_type: For arguments the syntax is argument: annotation, while the return type is annotated using -> annotation. Note that the annotation must be a valid Python expression. The following simple example adds annotations to a function that calculates the circumference of a circle: """ import math def circumference(radius: float) -> float: return 2 * math.pi * radius print(circumference(3)) print(circumference.__annotations__) """Sometimes you might be confused by how Mypy is interpreting your type hints. For those cases there are special Mypy expressions: reveal_type() and reveal_locals(). You can add these to your code before running Mypy, and Mypy will dutifully report which types it has inferred """ """Even without any annotations Mypy has correctly inferred the types of the built-in math.pi, as well as our local variables radius and circumference. Note: The reveal expressions are only meant as a tool helping you add types and debug your type hints. If you try to run the reveal.py file as a Python script it will crash with a NameError since reveal_type() is not a function known to the Python interpreter. If Mypy says that “Name ‘reveal_locals‘ is not defined” you might need to update your Mypy installation. The reveal_locals() expression is available in Mypy version 0.610 and later. """ """Variable Annotations Variable Annotations In the definition of circumference() in the previous section, you only annotated the arguments and the return value. You did not add any annotations inside the function body. More often than not, this is enough. However, sometimes the type checker needs help in figuring out the types of variables as well. Variable annotations were defined in PEP 526 and introduced in Python 3.6. The syntax is the same as for function argument annotations: """ pi: float = 3.1432 def circumference_1(radius: float) -> float: return 2 * pi * radius print(circumference_1(4)) # print(pi.__annotations__) nothing: str # print(nothing) # print(dir(nothing)) """Since no value was assigned to nothing, the name nothing is not yet defined.""" # Type Comment """Type Comments As mentioned, annotations were introduced in Python 3, and they’ve not been backported to Python 2. This means that if you’re writing code that needs to support legacy Python, you can’t use annotations. Instead, you can use type comments. These are specially formatted comments that can be used to add type hints compatible with older code. To add type comments to a function you do something like this: """ def circumference_type(radius): type: float > - float return 2 * math.pi * radius print(circumference_type(2)) """The type comments are just comments, so they can be used in any version of Python. Type comments are handled directly by the type checker, so these types are not available in the __annotations__ dictionary:""" print(circumference_type.__annotations__) """A type comment must start with the type: literal, and be on the same or the following line as the function definition. If you want to annotate a function with several arguments, you write each type separated by comma: """ def headline_type(text, width=80, fill_char='-'): type: (str, str, str) > - int return f"({text.title()})".center(width, fill_char) print(headline_type("Use this type comments", width=40)) """So, Type Annotations or Type Comments? Should you use annotations or type comments when adding type hints to your own code? In short: Use annotations if you can, use type comments if you must. Annotations provide a cleaner syntax keeping type information closer to your code. They are also the officially recommended way of writing type hints, and will be further developed and properly maintained in the future. Type comments are more verbose and might conflict with other kinds of comments in your code like linter directives. However, they can be used in code bases that don’t support annotations. There is also hidden option number three: stub files. You will learn about these later, when we discuss adding types to third party libraries. Stub files will work in any version of Python, at the expense of having to maintain a second set of files. In general, you only want to use stub files if you can’t change the original source code."""
0dc02b1ec77d41420414a605050252cfaab720d2
0212Infinity/PythonExercises
/day08/property.py
322
3.59375
4
class Student: # 类属性 name = 'liming' def __init__(self, age): # 实例对象 self.age = age pass obj = Student(17) print(obj.name) print(obj.age) print(Student.name) # 类属性可以 被类对象和实例对象共同访问使用 # 实例属性只能 由实例对象所访问
f12e3d106ac87cc9996e5e948280aee77d2a3ed7
ARWA-ALraddadi/python-tutorial-for-beginners
/12-How to do more than one thing Demos/I_savings_account.py
2,013
4.59375
5
###################################################################### ## ## Demonstration - Using superclass methods ## ## This demonstration shows how a subclass can use methods from ## the superclass to define its own methods ## ###################################################################### # # As an extension of the "bank account" class we defined earlier we # now want to create a savings account class which introduces a # new method for awarding annual interest # # Import the bank account class from G_bank_account import * # A class for savings accounts class Savings_Account(Bank_Account): # When first created a savings account has the same # characteristics as a general bank account, plus an # interest rate and a fixed interest threshold def __init__(self, depositor, opening_deposit, interest_rate): Bank_Account.__init__(self, depositor, opening_deposit) self.__int_rate = interest_rate # percent self.__threshold = 100.00 # dollars # Award the account annual interest, provided it is above # a fixed threshold, by making use of methods inherited from # the superclass def pay_interest(self): # Get the current balance balance = self.query() # Pay interest, if eligible if balance > self.__threshold: self.deposit((self.__int_rate * balance) / 100.0) ###################################################################### # # Some tests that show how "savings account" objects can do everything # a "bank account" object can, and more # if __name__ == '__main__': agent86 = Savings_Account('Maxwell Smart', 1500.15, 5.0) agent86.withdraw(250.00) # take some money out print(agent86) # check the balance agent86.deposit(50.00) # add a little in agent86.withdraw(300.15) # take some more out print(agent86) # check the balance agent86.pay_interest() # award annual interest print(agent86) # confirm that we got $50 in interest
b4418e366e43cae36a12b15128abbfd6335ebefa
skinder/Algos
/PythonAlgos/Done/dict_test.py
121
3.546875
4
a = {'A':[], 'B':0, 'C':''} lst = ['o','b'] for i in lst: a['A'].append(i) a['B'] += 1 a['C'] += i print(a)
cf0e0e53dc6e318c8bf3597bd126d447d63d3d0a
wafasa/soal-kerja
/kmklabs/kmk2.py
380
3.734375
4
# menghitung Leveinsthein Distance def measure(str1, str2): if len(str1) != len(str2): return -1 else: dif = 0 for i in range(len(str1)): if str1[i] == str2[i]: dif = dif + 0 else: dif = dif + 1 return dif print measure('aku', 'aku') print measure('michael', 'mikhail')
95e7809cf0fc88977e1891bdf040df2b0aae258f
green-fox-academy/nandormatyas
/week-04/day-01/fleet_of_things.py
431
3.59375
4
from fleet import Fleet from thing import Thing fleet = Fleet() todo = ["Get milk", "Remove the obstacles"] completed=["Stand up", "Eat lunch"] for i in todo: x = Thing(i) fleet.add(x) for j in completed: y = Thing(j) y.complete() fleet.add(y) #Thing(fleet) # Create a fleet of things to have this output: # 1. [ ] Get milk # 2. [ ] Remove the obstacles # 3. [x] Stand up # 4. [x] Eat lunch print(fleet)
d7ac335d94f57dd3f92889784bed1c06ce052bf3
Ganesh2611/guvi_python
/natural.py
76
3.578125
4
v=int(input()) sum2 = 0 while(v > 0): sum2=sum2+v v=v-1 print(sum2)
d16699215ccbb2fea8f45821b9f5b7632efaa4ad
franklingu/leetcode-solutions
/questions/word-break-ii/Solution.py
1,711
3.96875
4
""" Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. Note: The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not contain duplicate words. Example 1: Input: s = "catsanddog" wordDict = ["cat", "cats", "and", "sand", "dog"] Output: [   "cats and dog",   "cat sand dog" ] Example 2: Input: s = "pineapplepenapple" wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] Output: [   "pine apple pen apple",   "pineapple pen apple",   "pine applepen apple" ] Explanation: Note that you are allowed to reuse a dictionary word. Example 3: Input: s = "catsandog" wordDict = ["cats", "dog", "sand", "and", "cat"] Output: [] """ class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: def try_break(s, dd, mem): if len(s) == 0: return [''] elif s in mem: return mem[s] ret = [] for i in range(1, len(s) + 1): prev, after = s[:i], s[i:] if not dd.get(prev, False): continue if len(after) == 0: ret.append(prev) continue ls = try_break(after, dd, mem) for bp in ls: ret.append('{} {}'.format(prev, bp)) mem[s] = ret return ret track = dict((word, True) for word in wordDict) mem = {} return try_break(s, track, mem)
8e3ea927b7ef763d7bb96c7e9dcee22bf6299dd3
abhishek-coding-pandey/pycode
/full calculator.py
393
4.0625
4
print("this is my cal") print("enter your first number") n1=int(input()) print("enter you oprehend ") op=input() print("enter your second number") n2=int(input()) if op=="+": print("your answer is ,",int(n1)+int(n2)) if op== '-': print("your answer is",int(n1)-int(n2)) if op=="*": print ("your answer is ",int(n1)*int(n2)) if op== "/": print("your answer is ",int(n1)/int(n2))
f76aeafd3053d1ca776a6cb1600f5aa7383f1702
jungmkitLez/algorithm_study
/프로그래머스/이분탐색/징검다리/stones.py
699
3.5
4
from collections import defaultdict def solution(distance, rocks, n): answer = 0 sorted_rocks = [0] sorted_rocks.extend(sorted(rocks)) sorted_rocks.append(distance) diffs = [] for i in range(len(sorted_rocks)-1): diffs.append(sorted_rocks[i+1] - sorted_rocks[i]) value_indexes = defaultdict(list) for i,v in enumerate(diffs): value_indexes[v].append(i) diff_unique = list(sorted(set(diffs))) left = 0 right = len(diff_unique) print(value_indexes) while left <= right: mid = diff_unique[len(diff_unique)//2] return answer distance = 25 rocks = [2, 14, 11, 21, 17] n = 2 print(solution(distance, rocks, n))
8238662ee69f4abc9a0973bcebf673153df9f3fb
zeddinarief/progjar2018
/kelasc/coba.py
143
3.78125
4
jumlah = input("Masukkan jumlahnya : ") for i in range(1,int(jumlah)+1): for j in range(1,i+1): print("* ", end='') print(" ")