blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
b00639462737fce6440a481c232abbd3ce6abf91
ccirelli2/mutual_fund_analytics_lab_sentiment_analysis
/scripts/functions_decorators.py
1,413
3.65625
4
""" Decorator functions for this program """ ############################################################################### # Import Python Libraries ############################################################################### import logging; logging.basicConfig(level=logging.INFO) from functools import wraps from datetime import datetime ############################################################################### # Decorators ############################################################################### def my_timeit(f): """ Decorator function to log function name and duration. Args: f: function Returns: """ @wraps(f) # see docs. retains info about f def wrapped(*args, **kwargs): logging.info(f'Starting function {f.__name__}') start = datetime.now() response = f(*args, **kwargs) duration = (datetime.now() - start).total_seconds() logging.info(f'{f.__name__} finished. Duration => {duration}') logging.info('\n\n') return response return wrapped
1a076304c384df34684971effecc69c702342683
jarroba/Curso-Python
/Casos Prácticos/6.2-math_stirling.py
565
3.6875
4
import math # 1 num = 100 primera_parte = math.sqrt(2 * math.pi * num) segunda_parte = math.pow(num/math.e, num) # == (num / math.e) ** num resultado = primera_parte * segunda_parte print("Por fórmula de Stirling: {numero}!= {resultado}".format(numero=num, resultado=resultado)) # 2 res_factorial = math.factorial(num) print("Por fórumula normal: {numero}! = {resultado}".format(numero=num, resultado=res_factorial))
a4644a5aa54ed966e76a12b18651173ba15682f9
jarroba/Curso-Python
/Casos Prácticos/5.5-funcion_return_none_espacio.py
234
3.59375
4
# 1 def espacio(velocidad, tiempo): resultado = velocidad * tiempo # 2 if resultado < 0: return None else: return resultado # 3 tiempo_retornado = espacio(120, -10) print(tiempo_retornado)
34b47f5f402c625167dd07b74dde3a50af7abb3e
jarroba/Curso-Python
/Casos Prácticos/4.15-tuplas.py
497
3.875
4
# 1 tupla1 = ("manzana", "rojo", "dulce") tupla2 = ("melocotón", "naranja", "ácido") tupla3 = ("plátano", "amarillo", "amargo") print(tupla1) # 2 lista_de_tuplas = [] lista_de_tuplas.append(tupla1) lista_de_tuplas.append(tupla2) lista_de_tuplas.append(tupla3) # 3 for fruta, color, sabor in lista_de_tuplas: print("La {fruta} es {color} " "y sabe a {sabor}".format(fruta=fruta, color=color, sabor=sabor))
042b6738c14747adbe173d1b09239927f92d2aa9
binit-singh/python-datastructures
/3_fibonacci_number/fibonacci_last_digit.py
581
4.0625
4
# Uses python3 def get_fibonacci_last_digit_naive(n): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current % 10 def get_fibonacci_last_digit_fast(n): if n < 1: return 1 previous_last = 0 current_last = 1 for _ in range(n-1): previous_last, current_last = current_last % 10, (previous_last + current_last) % 10 return current_last if __name__ == '__main__': n = int(input()) print(get_fibonacci_last_digit_fast(n))
688f45329b2e7371b61189f3cd3b2d5a77d3a0f5
codacy-acme/pythest
/main.py
1,029
3.640625
4
import httpoxy def square(a): """item_exporters.py contains Scrapy item exporters. Once you have scraped your items, you often want to persist or export those items, to use the data in some other application. That is, after all, the whole purpose of the scraping process. For this purpose Scrapy provides a collection of Item Exporters for different output formats, such as XML, CSV or JSON. More Info: https://doc.scrapy.org/en/latest/topics/exporters.html """ return a**a def square2(a): """item_exporters.py contains Scrapy item exporters. Once you have scraped your items, you often want to persist or export those items, to use the data in some other application. That is, after all, the whole purpose of the scraping process. For this purpose Scrapy provides a collection of Item Exporters for different output formats, such as XML, CSV or JSON. More Info: https://doc.scrapy.org/en/latest/topics/exporters.html """ return a**a x = 1 if x == 1: # indented four spaces print("x is 1.")
843061e943b25fa172636d9f77017ea2294aa96d
ramza007/Password-Locker
/credentials-test.py
2,276
3.765625
4
import unittest from credentials import Credentials class TestCredentials(unittest.TestCase): ''' test class that defines test cases for the credentials class ''' def setUp(self): ''' set up method that runs before each test case ''' self.new_credentials = Credentials("Google", "3344") def tearDown(self): ''' tear down method that does clean up after each test case has run. ''' Credentials.credentials_list = [] def test_credentials_instance(self): ''' method to test if new credentials have been instanciated properly ''' self.assertEqual(self.new_credentials.account_name, "Google") self.assertEqual(self.new_credentials.account_password, "3344") def test_save_credentials(self): ''' test case to test if credentials objects have been saved ''' self.new_credentials.save_credentials() # save new user self.assertEqual(len(Credentials.credentials_list), 1) def test_delete_credentials(self): ''' test delete credentials to test if we can remove a account from our list ''' self.new_credentials.save_credentials() test_credentials = Credentials("Google", "3344") test_credentials.save_credentials() self.new_credentials.delete_credentials() # to delete a credentials object self.assertEqual(len(Credentials.credentials_list), 1) def test_find_credentials_by_name(self): ''' test to check if credentials by the account name and can display information ''' self.new_credentials.save_credentials() test_credentials = Credentials("Google", "3344") test_credentials.save_credentials() # found_credentials = Credentials.find_by_number("0711491808") # self.assertEqual(found_credentials.credentials_name, # test_credentials.password) def test_display_all_credentials(self): ''' Test to check if all contacts can be viewed ''' self.assertEqual(Credentials.display_credentials(), Credentials.credentials_list) if __name__ == '__main__': unittest.main()
4885fd3b53635d85138d7987793f5159eab172bd
charboltron/artificial_intelligence
/genetic_8_queens/genetic_alg_8_queens.py
8,873
3.546875
4
#%% import sys import random import math import numpy as np import matplotlib.pyplot as plt test_boards = [[2,4,7,4,8,5,5,2],[3,2,7,5,2,4,1,1],[2,4,4,1,5,1,2,4],[3,2,5,4,3,2,1,3]] #constants/twiddle factors num_iterations = 10000 def print_board(board): for i in range(8, 0, -1): print('\n') for j in range(8): if board[j] == i: print(u' \u2655 ',end='') else: print(' ___ ', end='') def test(): fscores=[] for board in test_boards: fscore = get_fscore(board) print('fitness: ', fscore) fscores.append(fscore) fprobs = fitprobs(4, fscores) print(fprobs) def goal_state(board): if get_fscore(board) == 28: return True return False def randomize (board, n): for i in range(n): queens = random.randint(1,8) board[i] = queens return board population = [] def generate_population(population_size): population = [] for _ in range(population_size): board = [0,0,0,0,0,0,0,0] n = len(board) randomize(board, n) population.append(board) return population def get_fscore(board): fitness = 28 for i in range(len(board)-1): queen = i+1 # print(f'\nThis queen: ({queen}, {board[i]})') # print('Other queens: ', end='') for j in range(i+1, len(board)): # is_attack = '' other_queen = j+1 if(board[i] == board[j]): fitness -= 1 # is_attack = '<-A!' elif abs((board[i] - board[j])/((queen)-(other_queen))) == 1: fitness -= 1 # is_attack = '<-A!' # print(f'({other_queen}, {board[j]}){is_attack}, ', end='') return fitness def get_probs(population): fscores = [] for i in range(len(population)): fscore = get_fscore(population[i]) fscores.append(fscore) fprobs = fitprobs(len(population), fscores) return fscores, fprobs def fitprobs(pop_size, fs): denom = 0 probs = [] for i in range(pop_size): denom+=fs[i] if(denom > 0): for i in range(pop_size): s_i = fs[i]/denom probs.append(s_i) else: print("Error: Denom !>0 !") exit() return probs def get_avg_fitness(fs, pop_size): avg = 0 for i in range(pop_size): avg+=fs[i] avg = avg/pop_size return avg def cull_population(d, initial_popsize, pop_size, population): # print("population size before culling: ", len(d)) cull_size = pop_size-initial_popsize d = sorted(d, key=lambda x: x[0]) for i in range(cull_size): temp = d[i][1] for j in range(len(population)): if population[j] == temp: # print(f'deleting j = {population[j]}') del population[j] break del d[i] # print("population size after culling: ", len(d)) return d, pop_size-cull_size, population def fitness_proportionate_selection(d): sum_of_fitness = 0.0 bins = [] for i in d: sum_of_fitness+=i[0] # print(sum_of_fitness) # print(d) prev_prob = 0.0 d = sorted(d, key=lambda x: x[0]) for i in range(len(d)): # print(d[i][0]) if (i+1) == len(d): right_range = 1.0 else: right_range = prev_prob + d[i][0] bins.append([prev_prob, right_range]) prev_prob += d[i][0] # for bin in bins: # print(bin) return bins def select_from_population(bins, d): mom, dad = [],[] cnt = 0 while(mom == [] or dad == []): cnt+=1 x = random.randint(0, 100)/100 y = random.randint(0, 100)/100 x = .9999999 if x > .99 else x x = .0000001 if x < 0.01 else x y = .9999999 if y > .99 else y y = .0000001 if y < 0.01 else y # while(y == x): # y = random.randint(0, 100)/100 for i, bin in enumerate(bins): # print(bin) if x >= bin[0] and x <= bin[1]: mom = d[i] if y >= bin[0] and y <= bin[1]: dad = d[i] if cnt == 1000: print("wtf") print(mom, dad) exit() if mom == [] or dad == []: print("Empty list after selection! Exiting.") print(x, y, mom, dad) exit() return mom, dad def breed(d): bins = fitness_proportionate_selection(d) mom, dad = select_from_population(bins, d) # print(f'mom: {mom}, dad: {dad}') split = random.randint(1,7) # print(f'split = {split}') mom_genes_first = mom[1][0:split] dad_genes_first = dad[1][split:] dad_genes_secnd = dad[1][0:split] mom_genes_secnd = mom[1][split:] # print(f'{mom_genes_first} , {dad_genes_first}') # print(f'{dad_genes_secnd} , {mom_genes_secnd}') first_born = [0,0,0,0,0,0,0,0] secnd_born = [0,0,0,0,0,0,0,0] for i in range(8): if i < split: first_born[i] = mom_genes_first[i] secnd_born[i] = dad_genes_secnd[i] else: first_born[i] = dad_genes_first[split-i] secnd_born[i] = mom_genes_secnd[split-i] # print(f'M: {mom}, D: {dad}, C1: {first_born}, C2: {secnd_born}') return first_born, secnd_born def mutate(c1, c2, mutation_thresh): m1 = random.randint(0, 100)/100 m2 = random.randint(0, 100)/100 if m1 >= mutation_thresh: queen_to_mutate = random.randint(0, 7) c1[queen_to_mutate] = random.randint(1, 8) if m2 >= mutation_thresh: queen_to_mutate = random.randint(0, 7) c2[queen_to_mutate] = random.randint(1, 8) return c1, c2 def genetic_eight_queens(pop_size, m): f = open('out.txt', 'w') print(f'\nBegin up to {num_iterations} iterations: Breeding...') avg_fitness_to_pop = [] population = generate_population(pop_size) initial_pop_size = pop_size # print(fs) fittest = 0.0 board = [] fs, probs = get_probs(population) d = list(zip(probs, population)) for i in range(num_iterations): if initial_pop_size < pop_size: d, pop_size, population = cull_population(d, initial_pop_size, pop_size, population) if i%100==0: # print(pop_size) print(f'i:..{i} ') f.write(f'\nfittest member of population at iteration {i}: {d[len(d)-1]}. Score: {fittest}') # print(f'fittest = {fittest} board: {board}') # print(len(population)) fs, probs = get_probs(population) d = list(zip(probs, population)) # print(fs) avg_fitness_to_pop.append((i, get_avg_fitness(fs, pop_size))) for k in range(len(d)): if fs[k] > fittest: fittest = fs[k] board = d[k][1] d = sorted(d, key=lambda x: x[0]) child1, child2 = breed(d) child1, child2 = mutate(child1, child2, m) if goal_state(child1): print(f'\nGoal State has been found! After: {i} iterations.\n') print(f'This is the configuration of queens found {child1}\n') print_board(child1) return avg_fitness_to_pop, i elif goal_state(child2): print(f'\nGoal State has been found! After: {i} iterations.\n') print(f'This is the configuration of queens found {child2}\n') print_board(child2) return avg_fitness_to_pop, i population.append(child1) population.append(child2) pop_size+=2 print(f'No Goal State was found after {i} iterations.\n') return avg_fitness_to_pop, num_iterations def main(): # test() p = input("Please enter initial population size in the range (10, 1000): ") if int(p) < 10 or int(p) > 1000: print('You entered a bad population number. Exiting') exit() pop_size = int(p) m = input("Please enter mutation rate as a percentage in the range (0, 100): ") if int(m) < 0 or int(m) > 100: print('You entered a bad mutation percentage. Exiting') exit() mutation_thresh = (100 - int(m))/100 mutation_rate = int(m) #breeding frequencies avg1, is_til_goal = genetic_eight_queens(pop_size, mutation_thresh) print('\n') # pp = PdfPages('plot.pdf') # print(avg1) x1 = [avg[0] for avg in avg1] y1 = [avg[1] for avg in avg1] # print(x1) # print(y1) print("plot ready") plt.title(f'total iterations: {is_til_goal}| population size: {pop_size}| mutation rate: {mutation_rate} ') plt.xlabel('Generation') plt.ylabel('Average Fitness') plt.scatter(x1, y1) plt.show() if __name__ == "__main__": main() # %%
470d83e0c57151a4ac54e15c22a5a36befc592c5
JansherKhantajik/Python
/first program.py
613
4.03125
4
#print a program which input number from user and you will give 5 guess to equvalate with your answer print("Word of Guess Number, Input Your Guess that You have five chance") guess = int(input()) i=0 while (True): if (guess <15): print("Please Enter more then",guess) break elif guess <20 and guess >15: print("little More then",guess) elif guess <35 and guess >25: print("Enter less then",guess) elif guess <25 and guess >20: print("Congurate You Have Got it Number is Between 20 to 25 .. your guess ",guess) else: print("Invelid number") i=i+1 break
409ef68a67f735a647f22040ad7c1086cd991de2
sleevewind/practice
/0217/列表的复制.py
133
3.71875
4
# 可变类型和不可变类型 a = 12 b = a print('a={},b={}'.format(hex(id(a)), hex(id(b)))) # a=0x7ff95c6a2880,b=0x7ff95c6a2880
0b8fd9d19b5e21325b8499480ed594c2a33a9740
sleevewind/practice
/0217/列表的排序和反转.py
396
4.0625
4
# sort()直接对列表排序 nums = [6, 5, 3, 1, 8, 7, 2, 4] nums.sort() print(nums) # [1, 2, 3, 4, 5, 6, 7, 8] nums.sort(reverse=True) print(nums) # [8, 7, 6, 5, 4, 3, 2, 1] # sorted()内置函数, 返回新的列表, 不改变原来的列表 print(sorted(nums)) # [1, 2, 3, 4, 5, 6, 7, 8] # reverse() nums = [6, 5, 3, 1, 8, 7, 2, 4] nums.reverse() print(nums) # [4, 2, 7, 8, 1, 3, 5, 6]
f889d7e66bf7bd2b2dd2647cf64cdfe91189052e
sleevewind/practice
/0217/列表的增删改查.py
1,466
3.5625
4
# 操作列表, 一般包括 增删改查 heroes = ['镜', '嬴政', '露娜', '娜可露露'] # 添加元素的方法 # append heroes.append('黄忠') print(heroes) # 在列表最后面追加 # insert(index, object) 在指定位置插入 heroes.insert(1, '小乔') print(heroes) newHeroes = ['狄仁杰', '王昭君'] # extend(iterable) 添加可迭代对象 heroes.extend(newHeroes) print(heroes) # 删除元素 pop print(heroes) # ['镜', '小乔', '嬴政', '露娜', '娜可露露', '黄忠', '狄仁杰', '王昭君'] x = heroes.pop() # 删除并返回 print(x) # 王昭君 x = heroes.pop(2) # 删除指定下标的元素 print(x) # 嬴政 print(heroes) # ['镜', '小乔', '露娜', '娜可露露', '黄忠', '狄仁杰'] # remove heroes.remove('小乔') # 删除不存在的会报错 print(heroes) # ['镜', '露娜', '娜可露露', '黄忠', '狄仁杰'] # del关键字 这个功能强大, 列表删除少用 del heroes[2] print(heroes) # ['镜', '露娜', '黄忠', '狄仁杰'] # clear heroes.clear() print(heroes) # [] # 查询 heroes = ['镜', '小乔', '镜', '露娜', '娜可露露', '黄忠', '狄仁杰'] print(heroes.index('镜')) # 返回下标, 不存在元素报错 print(heroes.count('镜')) # 2, 返回个数 # in 运算符 flag = '小乔' in heroes print(flag) # True # 修改元素, 使用下标直接修改 heroes[1] = '镜' print(heroes) # ['镜', '镜', '镜', '露娜', '娜可露露', '黄忠', '狄仁杰']
bb22aef9984883cee87a02c39b509e7d496a4107
innovatorved/python-recall
/py51-python-cahching-by-funtools.py
386
3.578125
4
# python3 py51-python-cahching-by-funtools.py import time from functools import lru_cache @lru_cache(maxsize = 3) # save last 3 value def sleep_n_time(n): time.sleep(n) return n if __name__ == "__main__": print(sleep_n_time(3)) # it create an cahe for this same def for for reducing time and space print(sleep_n_time(3)) print(sleep_n_time(2))
2c55330c7204f8bceaa6eed1e9533f05a6e18b1e
innovatorved/python-recall
/py40-access-specifier-public-private.py
918
3.796875
4
# Access Specifier # public # protected # private class Student: public_var = "this variable is public" _protected_var = "this is private var" __private_var = "this is private var" def __init__(self ,public , protected , private): self.public = public self._protected = protected self.__private = private if __name__ == "__main__": ved = Student("Name : Ved Prakash Gupta" , "Age : 19" , "Mobile:7007868719") print(ved.public) # Output :'Name : Ved Prakash Gupta' print(ved._protected) # Output : 'Age : 19' print(ved.__private) # Output : """Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> ved.__private AttributeError: 'Student' object has no attribute '__private'""" print(ved._Student__private) # Output : 'Mobile:7007868719' # private variable acces by classs define
a32d740aaec9947b0f5b7d64a72a47f10a28718a
innovatorved/python-recall
/py49-genrators-ex1.py
288
3.609375
4
# python3 py49-genrators-ex1.py n = 10 def fib(a=0 , b = 1): for x in range(n): yield (a+b) a , b = b , b+a a = fib(0,1) print(a.__next__()) print(a.__next__()) print(a.__next__()) print(a.__next__()) print(a.__next__()) print(a.__next__())
8207d31429cc76165b8136f1c186f7d0f39bd62b
innovatorved/python-recall
/py20 - enumeratefin.py
522
3.90625
4
#enumerate function a = ["ved" , "Prakash" , "Gupta" , "hello"] i = 1 for item in a: #print(item) if i%2 != 0: print(f"item {item}") i+= 1 #with enumerate function print(enumerate(a)) # Output : <enumerate object at 0x000002452601E700> print(list(enumerate(a))) # Output : [(0, 'ved'), (1, 'Prakash'), (2, 'Gupta'), (3, 'hello')] for index , item in enumerate(a): print(f"index is {index} and value is {item}") if index%2 != 0: print(f"item {item}")
7d828ae6dabb5d3283927d7ec88800acd45164d2
innovatorved/python-recall
/py6 - list.py
643
3.671875
4
# List Name = [ "Ved Gupta" ," Ramesh Prasad" , "Anand Kumar" "Shrish Guptas" , "Rishi sharma" ] Age = [20,56,89,12,45] print(type(Name),type(Age)) # Age.sort() print(Age) print(sum(Age)) print(min(Age)) print(max(Age)) print(len(Age)) Age.reverse() print(Age) Age.sort() print(Age) new = sorted(Age) print(new) """ <class 'list'> <class 'list'> [20, 56, 89, 12, 45] 222 12 89 5 [45, 12, 89, 56, 20] [12, 20, 45, 56, 89] [12, 20, 45, 56, 89] """ print(Age) new = Name.copy() print(new) print(new.count("Ved Gupta")) new.clear() print(new) """ [12, 20, 45, 56, 89] ['Ved Gupta', ' Ramesh Prasad', 'Anand KumarShrish Guptas', 'Rishi sharma'] 1 [] """
7f71835bcdea55a10aef9e2602161ea23d979484
innovatorved/python-recall
/start-dynamic/fibonachi-sequence.py
138
3.65625
4
# python3 fibonachi-sequence.py def fib_seq(n ,a=0,b=1): if n != 0: print(a+b) fib_seq(n-1 ,b,a+b) fib_seq(5)
382a67dd059c8a7b93b9e01bfeacc25424f32307
innovatorved/python-recall
/py17 - Fabonachi Sequence.py
306
3.71875
4
# Fabonachi Sequence # find fabonachi sequene def fab(n,a = 0 , b = 1): if n > 0: c = a+b print(c) fab(n-1,b,c) a = int(input("How much No . of sequence you want to find :")) fab(a) """ How much No . of sequence you want to find :10 1 2 3 5 8 13 21 34 55 89 """
d393755ca2b2661c053f02573f582213d0bd1f32
innovatorved/python-recall
/py48-genrators-yield.py
574
4.0625
4
# python3 py48-genrators-yield.py """ Iterable : __iter__() or __getitem__() Iterator : __next__() Iteration : """ # genrators are iteraators but you can only iterate ones def range_1_to_n(n) : for x in range(1 , n): yield x print(range_1_to_n(10)) num = range_1_to_n(10) print(num.__next__()) # 1 print(num.__next__()) # 2 # __iter__() a = "Ved Prakash Gupta" li = [1,2,3,4,5,6,7,8,9] a = iter(a) b = iter(li) print(a.__next__()) print(b.__next__()) print(a.__next__()) print(b.__next__()) print(a.__next__()) print(b.__next__())
7b73a9dde0dccdaf19434419c4ce16387f099588
hyrdbyrd/ctf-route
/public/tasks-content/code.python.py
124
3.53125
4
def encrypt(text): key = len(text) res = [] for i in text: res.append(ord(i) + (ord(i) % key)) key += 1 return res
a3dd8e793dba43fdc1f0c05044e9751e46daf6ed
joanamcsp/leetcode-python
/perfect_number.py
392
3.5625
4
import math class Solution: def checkPerfectNumber(self, num): """ :type num: int :rtype: bool """ if num <= 0: return False divisors = [div for div in range(1,int(math.ceil(math.sqrt(num)))) if num % div == 0] divisors.extend([num // div for div in divisors if num // div < num]) return sum(divisors) == num
d1a1cdab267d500a7ff27780a56f13f548a29a6b
VeraMendes/lambdata_DS8
/lambdata_veramendes/functions.py
462
3.875
4
""" utility functions """ import pandas as pd import numpy as np TEST_DF = pd.DataFrame([1,2,3,4,5,6]) def five_mult(x): """multiplying a number by 5 function""" return 5 * x def tri_recursion(k): """recursion of a value""" if(k>0): result = k + tri_recursion(k-1) # print(result) else: result = 0 return result def sum_two_numbers(a,b): """sum two numbers""" return a + b
427707409b4897dea8ae9fd913944ac23a2feb03
russjohnson09/sentential-logic
/sentential.py
3,123
4.15625
4
#!/usr/bin/env python """ Main Methods ----------------------------------- The following are all of the methods needed to apply logic rules and confirm that a Hilbert style proof is correct. Arguments given to each method are the line number of the statement and any line numbers needed to check for validity. ---- """ import sys import re from syntax import Grammar def file_to_list_of_parsed(nameoffile): """ Takes a file and returns a list of parsed lines. This can then be used to verify the proof. """ a = Grammar() b = a.syntax() file1 = open(nameoffile,'r') parsed = [] for line in file1: parsed.append(b.parseString(line)) return parsed def pr(line_number): return True def ei(line_number1, line_number2): dict1 = {} compare1 = parsed[int(line_number1) - 1].expr[2] compare2 = parsed[int(line_number2) - 1].expr for i in range(len(compare1)): try: if not compare1[i].islower(): if not compare1[i] == compare2[i]: return False else: if compare1[i] in dict1: if not dict1[compare1[i]] == compare2[i]: return False else: dict1[compare1[i]] = compare2[i] except: return False return True def simp(line1, line2): str1 = ''.join(list(parsed[int(line2) - 1].expr)) str2 = ''.join(list(parsed[int(line1) - 1].expr)) lst1 = str2.split('*') return str1 in lst1 def mp(line1, line2, line3): lst1 = list(parsed[int(line3)-1].expr) lst2 = list(parsed[int(line2)-1].expr) str1 = ''.join(lst2) + '->' + ''.join(lst1) str2 = ''.join(list(parsed[int(line1)-1].expr)) return str1 == str2 def eg(line1, line2): "The inverse of ei." return ei(line2, line1) def conj(line1, line2, line3): str1 = ''.join(list(parsed[int(line1)-1].expr)) str1 += '*' + ''.join(list(parsed[int(line2)-1].expr)) str2 = ''.join(list(parsed[int(line3)-1].expr)) return str1 == str2 def ui(line_number1, line_number2): dict1 = {} compare1 = parsed[int(line_number1) - 1].expr[1] compare2 = parsed[int(line_number2) - 1].expr for i in range(len(compare1)): try: if not compare1[i].islower(): if not compare1[i] == compare2[i]: return False else: if compare1[i] in dict1: if not dict1[compare1[i]] == compare2[i]: return False else: dict1[compare1[i]] = compare2[i] except: return False return True def verify(nameoffile): global parsed parsed = file_to_list_of_parsed(nameoffile) for line in parsed: if not line.reason[0] == 'Pr': str1 = str(line.reason[0].lower()) str1 += '(*' args = line.reason[1:] + list(line.linenumber) str1 += str(args) str1 += ')' print eval(str1) verify('quacker2.txt')
b733f8bd4a9d664973423240f106c8d252cdf13b
Adi7290/Python_Projects
/chschs.py
6,228
3.6875
4
Python 3.8.7 (tags/v3.8.7:6503f05, Dec 21 2020, 17:59:51) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> for i in range(0,100): if i%2==1: print(i) elif i%2 ==0: pass i=i+1 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> for i in range(0,100): if i%(2,3,5,7,9)==0: pass elif i%(2,3,5,7,9)==1: print(i) i+=1 Traceback (most recent call last): File "<pyshell#35>", line 2, in <module> if i%(2,3,5,7,9)==0: TypeError: unsupported operand type(s) for %: 'int' and 'tuple' >>> for i in range(0,100): if i%2,3,5,7==0: SyntaxError: invalid syntax >>> for i in range(0,100): if i%2==0 and i%3==0 and i%5==0 and i %7==0: pass elif i%2==1 and i%3==1 and i%5==1 and i%7==1: print(i) i+=1 1 >>> for i in range(0,1000): if i%2==0 and i%3==0 and i%5==0 and i%7==0: print(i) i+=1 0 210 420 630 840 >>> for i in range(0,1000): if i % i ==0: print(i) elif i%i==1: pass i+=1 Traceback (most recent call last): File "<pyshell#57>", line 2, in <module> if i % i ==0: ZeroDivisionError: integer division or modulo by zero >>> for i in range(2,150): if i%i ==0 SyntaxError: invalid syntax >>> for i in range(2,150): if i%i ==0: print(i) elif i%i ==1: pass i+=1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 >>> for i in range(2,150): if i%i ==0: pass elif i%i ==1: print(i) i+=1 >>> >>> >>> >>> >>> for i in range(0,100): if i%1==0 and i%i==0: print(i) elif i%2==0: pass Traceback (most recent call last): File "<pyshell#77>", line 2, in <module> if i%1==0 and i%i==0: ZeroDivisionError: integer division or modulo by zero >>> KeyboardInterrupt >>> for i in range(0,100): if i%3==0 and i%2 ==0: if i%5==0 and i%7==0: pass elif: SyntaxError: invalid syntax >>> for i in range(0,100): if i%3==0 and i%2 ==0: if i%5==0 and i%7==0: pass elif: SyntaxError: invalid syntax >>> for i in range(0,100): if i%3==0 and i%2 ==0: elif i%5==0 and i%7==0: pass elif: SyntaxError: invalid syntax >>> for i in range(0,100): if i%3==0 and i%2 ==0: if i%5==0 and i%7==0: pass else: print(i) i+=1 1 2 3 4 5 7 8 9 10 11 13 14 15 16 17 19 20 21 22 23 25 26 27 28 29 31 32 33 34 35 37 38 39 40 41 43 44 45 46 47 49 50 51 52 53 55 56 57 58 59 61 62 63 64 65 67 68 69 70 71 73 74 75 76 77 79 80 81 82 83 85 86 87 88 89 91 92 93 94 95 97 98 99 >>> for i in range(0,100): if i%3==0 and i%2 ==0: if i%5==0 and i%7==0: pass else i%3==1 and i%2 ==1: if i%5==1 and i%7==1: print(i) i+=1 SyntaxError: invalid syntax >>> for i in range(0,100): if i%3==0 and i%2 ==0: if i%5==0 and i%7==0: pass elif i%3==1 and i%2 ==1: if i%5==1 and i%7==1: print(i) i+=1 SyntaxError: expected an indented block >>> >>> for i in range(0,100): if i%3==0 and i%2 ==0: if i%5==0 and i%7==0: pass elif i%3==1 and i%2 ==1: if i%5==1 and i%7==1: print(i) i+=1 1 >>> for i in range(0,100): if i//2 ==0: pass elif i//2==1: print(i) i+=1 2 3 >>> >>> >>> for i in range(2,101): if i%2==0: elif i%3==0: SyntaxError: invalid syntax >>> for i in range(2,101): if i%1==True and i%i == True: print(i) elif i%2==True: elif i%3==True: SyntaxError: invalid syntax >>> KeyboardInterrupt >>> KeyboardInterrupt >>> KeyboardInterrupt >>> KeyboardInterrupt >>> KeyboardInterrupt >>> KeyboardInterrupt >>> KeyboardInterrupt >>> >>> >>> >>> >>> >>> >>> >>> >>> for i in range(0,100): if i%2 and 3 and 5 and 7 ==0: print(i) >>> if i%2 and 3 and 5 and 7==0: print('h') >>> >>> a = 1 >>> b=2 >>> c=3 >>> d=4 >>> a,b,c,d (1, 2, 3, 4) >>> a,b,c,d==0 (1, 2, 3, False) >>> a and b and c and d ==0 False >>> a and b==0 False >>> c and d ==0 False >>> a and c ==0 False >>> a = i%2==0 >>> b = i%3==0 >>> c = i%5==0 >>> d = i%7==0 >>> for i in range(2,101): if a and b and c and d ==True: pass elif a and b and c and d ==False: print(i) i+=1 >>> a and b and c and d False >>> for i in range(2,101): a = i%2==0 >>> b = i%3==0 >>> c = i%5==0 >>> d = i%7==0 SyntaxError: invalid syntax >>> >>> >>> >>> >>> >>> >>> >>> for i in range(2,101): if i %2 and i%3 and i%5 and i%7==0: pass elif i %2 and i%3 and i%5 and i%7==1: print(i) i+=1 29 43 71 >>> for i in range(0,100): if i%2 or i%3 or i %5 or i%7==0: print(i) elif i%2 or i%3 or i%5 or i%7 ==1: pass i+=1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 91 92 93 94 95 96 97 98 99 >>> KeyboardInterrupt >>> KeyboardInterrupt >>> KeyboardInterrupt >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>>
5c5199249efa2ba277218ed47e4ae2554a0bbf7e
Adi7290/Python_Projects
/improvise_2numeric_arithmetic.py
660
4.21875
4
#Write a program to enter two integers and then perform all arithmetic operators on them num1 = int(input('Enter the first number please : \t ')) num2 = int(input('Enter the second number please :\t')) print(f'''the addittion of {num1} and {num2} will be :\t {num1+num2}\n the subtraction of {num1} and {num2} will be :\t {num1-num2}\n the multiplication of {num1} and {num2} will be :\t {num1*num2}\n the division of {num1} and {num2} will be :\t {num1/num2}\n the power of {num1} and {num2} will be :\t {num1**num2}\n the modulus of {num1} and {num2} will be :\t {num1%num2}\n the floor division of {num1} and {num2} will be :\t {num1//num2}\n''')
4cc7aabb1e5e2b48cc90c607acce1b67f9fac93d
Adi7290/Python_Projects
/Herons formula.py
350
4.28125
4
#Write a program to calculate the area of triangle using herons formula a= float(input("Enter the first side :\t")) b= float(input("Enter the second side :\t")) c= float(input("Enter the third side :\t")) print(f"Side1 ={a}\t,Side2 = {b}\t,Side3={c}") s = (a+b+c)/2 area=(s*(s-a)*(s-b)*(s-c))**0.5 print(f"Semi = {s}, and the area = {area}")
ea0b627a1ee97b93acd9087b18e36c3fa5d10b4d
Adi7290/Python_Projects
/singlequantity_grocery.py
942
4.1875
4
'''Write a program to prepare a grocery bill , for that enter the name of items , quantity in which it is purchased and its price per unit the display the bill in the following format *************BILL*************** item name item quantity item price ******************************** total amount to be paid : *********************************''' name = input('Enter the name of item purchased :\t') quantity = int(input('Enter the quantity of the item :\t')) amount = int(input('Enter the amount of the item :\t')) item_price = quantity * amount print('*****************BILL****************') print(f'Item Name\t Item Quantity\t Item Price') print(f'{name}\t\t {quantity}\t\t {item_price}') print('************************************') print(f'Price per unit is \t \t {amount}') print('************************************') print(f'Total amount :\t\t{item_price}') print('************************************')
4303d8cef8cb2db91a035f228e311f265873c29c
Adi7290/Python_Projects
/sum_arithmetic.py
210
3.875
4
"""Write a program to sum the series 1+1/2+....1/n""" number = int(input('Enter the number :\t')) sum1=0 for i in range(1,number+1): a = 1.0/i sum1=sum1+a print(f'The sum of 1+1/2...1n is {sum1}')
2b786c15f95d48b9e59555d2557cc497d922d948
Adi7290/Python_Projects
/Armstrong_number.py
534
4.40625
4
"""Write a program to find whether the given number is an Armstrong Number or not Hint:An armstrong number of three digit is an integer such that the sum of the cubes of its digits is equal to the number itself.For example 371 is the armstrong number since 3**3+7**3+1**3""" num = int(input('Enter the number to check if its an Armstrong number or not :\t')) orig = num sm =0 while num>0: sm = sm+(num%10)*(num%10)* (num%10) num =num//10 if orig == sm: print('Armstrong') else: print('Not Armstrong')
57aef9d462a85029bc3e2bd58909ee7267d5f7d1
turamant/ToolKit
/PyQt_ToolKit/PushButton/pushbutton_1.py
1,582
3.578125
4
""" PushButton часто используется, чтобы заставить программу делать что-то, когда пользователю просто нужно нажать кнопку. Этот может начинать загрузку или удалять файл. """ import sys from PyQt5.QtWidgets import QWidget, QGridLayout, QPushButton, QApplication """ -= SIGNALS -= Одна из общих функций кнопки - это нажатие пользователем и выполнение связанного действия. Это делается путем подключения сигнала нажатия кнопки к соответствующей функции: """ class Window(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): layout = QGridLayout() self.setLayout(layout) button = QPushButton("Нажми сюда") button.setToolTip("This ToolTip simply displays text.") button.clicked.connect(self.on_button_clicked) layout.addWidget(button, 0, 0) button = QPushButton("выход") button.clicked.connect(self.exit_window) layout.addWidget(button, 0, 1) self.show() def on_button_clicked(self): print("Кнопка была нажата. Я функция - СЛОТ") def exit_window(self): sys.exit(app.exec_()) if __name__=='__main__': app = QApplication(sys.argv) screen = Window() sys.exit(app.exec_())
0c111ad94df47ec95d63a25d1f2f208994da4894
Mariano92m/commonTecInfo2016
/EjerciciosdeFunciones/EjerR-Func.py
381
3.6875
4
def prime (x): prim=True res=1 for y in range (2, x-1): if x%y==0: prim=False if (prim==True): for y in range (1, x+1): res= res * y print res else: for y in range (1, x): if y < 1000: if x%y==0: print y Seg=(raw_input("Desea ingresar otro numero? S/N ")).upper() if Seg == "S": x=int(input("Ingrese el numero que desea evaluar ")) prime (x)
bbde6653d2ecfc5f88b88fdd486cb9b7f3c2f7b7
Mariano92m/commonTecInfo2016
/EjerciciosdeFunciones/EjerM-Func.py
178
3.921875
4
def rango(L1,L2,x): if(L1<=x and x<=L2): print("Se encuentra dentro del rango") elif(L1>x): print("Se encuentra a la izquierda") else: print("Se encuentra a la derecha")
ce600e5d9e467ece05d83bc117e4c0b71f001c53
Mariano92m/commonTecInfo2016
/Ejercicios de Estructuras Secuenciales/S1.py
166
3.703125
4
print ("Situacion 1") Nac = int (input("Fecha de Nacimiento:")) Fut = int (input("Fecha a Futuro:")) resultado = Fut - Nac print ("Tu edad en esa Fecha:", resultado)
bc1882e40e3063c0c24e2fcc8ad1f6e7862c6301
Mariano92m/commonTecInfo2016
/Examen Juegos/ElCaminoDelGigante.py
1,857
3.90625
4
print ("*********************************************************************") print (" El camino del gigante designed by /commonTec: real game engineering/") print ("*********************************************************************") print(" ") print(" ") print ("Bienvenido a El camino del gigante!") print ("El juego que todos estaban esperando") print("") #Espacio print(" ") #Introduccion print(""" Tu objetivo es que el gigante llegue a su Caverna. Supongamos que se llama Bob. Tienes 3 intentos lanzando el dado para sumar pasos al gigante. \nEmpecemos...""") print(" ") print ("\nBob necesita dar 20 pasos para llegar a su caverna, si Bob da mas de 20 pasos cae a un precipicio") print(" ") #Variables import random pasos = random.randint(1,20) tiradas = random.randint(1,3) llegada = 20 print(" ") #Pasos realizados y faltantes print (("-El Gigante ha caminado %s pasos-")%(pasos)) restante = (20 - (pasos)) print (("\nAun le quedan %s pasos para llegar a la caverna")%(restante)) intentos = 1 #Mientras los intentos sean menores o iguales a 3 while intentos <= 3: dado = input("Lanzar dado? s/n:\n>:") #Si el dado se lanza... if dado == "s": tDado = random.randint(1,6) print(("\nEl dado ha caido en %s")%(tDado)) pasos+=tDado print (("\nAhora Bob ha hecho %s pasos")%(pasos)) restante-=tDado print (("Y restan %s pasos para llegar")%(restante)) intentos += 1 #Precipicio elif pasos > llegada: dado == "x" print ("\n Lo sentimos: has superado la cantidad de pasos. \nCaiste al precipicio!") intentos = 4 #En el caso de que se gane... if pasos == llegada: intentos = 4 print("\nHas llevado a Bob a la caverna!\n Ganaste!") #Si el Dado no se Lanza... else: break print ("\nBob no lo ha conseguido!\n - GAME OVER - ")
d72c45554eb24913e774a7ce1bf716428bc089d2
Mariano92m/commonTecInfo2016
/Ejercicios de Estructuras Repetitivas/R1.py
812
3.953125
4
sIni=0; transaccion=True while transaccion==True: print("----------------------0---------------------") print("Bienvenido señor!") print("Si desea realizar un deposito presione 1") print("Si desea realizar un retiro presione 2") pedido=int(input("Presione uno de los numeros y luego enter: ")) if(pedido==1): aDep=int(input("Cuanto desea depositar? ")) sIni=sIni+aDep elif(pedido==2): aRet=int(input("Cuanto desea retirar? ")) if(aRet>sIni): print("No puede retirar ese monto por que no tiene los fondos necesarios") else: sIni=sIni-aRet else: print("El numero ingresado es incorrecto"); print("Si desea continuar con la transaccion pulse 1, sino puse 2, y luego enter: ") aux=int(input("aux= ")) if(aux==1): transaccion=True elif(aux==2): transaccion=False print(sIni)
438bbaf5e4ab15eaeb4dc8cfa320bc2efff2c699
Mariano92m/commonTecInfo2016
/Ejercicios de Estructuras Condicionales/C2.py
315
3.984375
4
v1=int(input("Agrega un valor: ")); v2=int(input("Agrega un valor: ")); v3=int(input("Agrega un valor: ")); promedio=(v1+v2+v3)/3 if(v1>promedio): print("%s es mayor que el promedio"%(v1)); if(v2>promedio): print("%s es mayor que el promedio"%(v2)); if(v3>promedio): print("%s es mayor que el promedio"%(v3));
9d73cbb02966e689c21fa90b5afa888b190c2456
Mariano92m/commonTecInfo2016
/EjerciciosdeFunciones/EjerI-Func.py
176
3.65625
4
def tipo(k): sum=0 for x in range (1,k-1): if (k%x==0): sum=sum+x if sum==k: return ("perfecto") elif sum < k: return ("deficiente") else: return ("abundante")
5d3eaa8f3c83e461a73884e67a4eafacf24044d8
kamyu104/GoogleCodeJam-2016
/Round 1A/rank-and-file.py
774
3.578125
4
# Copyright (c) 2016 kamyu. All rights reserved. # # Google Code Jam 2016 Round 1A - Problem B. Rank and File # https://code.google.com/codejam/contest/4304486/dashboard#s=p1 # # Time: O(N^2) # Space: O(N^2), at most N^2 numbers in the Counter # from collections import Counter def rank_and_file(): N = input() cnt = Counter() for _ in xrange(2 * N - 1): cnt += Counter(list(raw_input().strip().split())) file = [] for k, v in cnt.iteritems(): # The count of the missing number must be odd. if v % 2 == 1: file.append(k) # The order of the missing numbers must be sorted. file.sort(key=int) return " ".join(file) for case in xrange(input()): print 'Case #%d: %s' % (case+1, rank_and_file())
bfd09acba86e48a9aca78e9c2fb7ad9b5f63dd32
Dami-Lapite/guess-the-song
/guessTheSong.py
2,297
3.5
4
import random import os import pygame import tkinter as tk from tkinter.filedialog import askdirectory def prompt(count, playTime, answer): if count == 3 : prompt_text = input("No more music \n\nType a for answer \n\nType q for quit\n\n") if prompt_text == "a": print("\n..............................\n") print("The correct answer was",answer) print("\n..............................\n") return True else: prompt_text = input("Type m for more \n\nType a for answer \n\nType q for quit\n\n") if prompt_text == "m": pygame.mixer.music.unpause() while pygame.mixer.music.get_pos() < playTime: continue pygame.mixer.music.pause() return False elif prompt_text == "a": print("\n..............................\n") print("The correct answer was",answer) print("\n..............................\n") return True else : return True def main(): pygame.mixer.init() root = tk.Tk() root.withdraw() directory = askdirectory() os.chdir(directory) list_dir = os.listdir(directory) list_dir.sort() list_of_songs = [] for files in list_dir: if files.endswith(".mp3"): list_of_songs.append(files) another_track = True score = 0 while another_track: try: random_song_index = random.randint(0, len(list_of_songs)-1) pygame.mixer.music.stop() pygame.mixer.init() pygame.mixer.music.load(list_of_songs[random_song_index]) pygame.mixer.music.play() while pygame.mixer.music.get_pos() < 3000: continue pygame.mixer.music.pause() done = False count = 1 playTime = 8000 while not done: done = prompt(count, playTime, list_of_songs[int(random_song_index)]) count += 1 playTime = 15000 another_round = input("would you like another round ? (y/n) ") if another_round == "n": break except pygame.error: continue if __name__ == "__main__": main()
023270d8f656b3949d6d95c8e3c423a2f94f66de
phuang7008/machine_learning
/Calculate_LR.py
1,643
3.5
4
#!/usr/bin/python from statistics import mean import numpy as np import random #xs = np.array([1,2,3,4,5,6], dtype=np.float64) #ys = np.array([5,4,6,5,6,7], dtype=np.float64) # here we are going to generate a random dataset for future usage def create_dataset(num, variance, step=2, correlation=False): val = 1 y = [] for i in range(num): yy = val + random.randrange(-variance, variance) y.append(yy) if correlation and correlation=='pos': val+=step elif correlation and correlation == 'neg': val-=step x = [i for i in range(len(y))] return np.array(x, dtype=np.float64), np.array(y, dtype=np.float64) # calculate the line parameters def slope_and_intercept(x, y): m = ( (mean(x) * mean(y) - mean(x*y) ) / (mean(x) * mean(x) - mean(x*x)) ) b = mean(y) - m * mean(x) return m, b # get some random data xs, ys = create_dataset(40, 20, 2, 'pos') print("x values are"); print(xs) print("y values are"); print(ys) m, b = slope_and_intercept(xs, ys) print(m, b) regression_line = [ m*x + b for x in xs] # now need to calculate the R-square (coefficient of determination) def square_error(y_orig, y_line): return sum((y_orig - y_line)**2) def coefficient_of_determination(y_orig, y_line): y_mean_line = [mean(y_orig) for y in y_orig] square_error_regression = square_error(y_orig, y_line) square_error_y_mean = square_error(y_orig, y_mean_line) return 1 - (square_error_regression / square_error_y_mean) cod = coefficient_of_determination(ys, regression_line) print("COD is %f" % cod)
816ca748495fb1b1f8dac3444233b19329738dcf
neuronalX/esn-lm
/esnlm/readouts/logistic.py
5,460
3.515625
4
""" This module defines the different nodes used to construct hierarchical language models""" import numpy as np from esnlm.utils import softmax from esnlm.optimization import newton_raphson, gradient, hessian class LogisticRegression: """ Class for the multivariate logistiv regression. Parameters ---------- input_dim : an integer corresponding to the number of features in input. output_dim : an integer corresponding to the number of classes. Notes ----- The model is trained by minimizing a cross-entropy function. The target can be binary (one-hot) vectors or have continuous value. This allows to use the LOgisticRegression node as a component of a Mixture of Experts (MoE) model. """ def __init__(self, input_dim, output_dim, verbose=True): self.input_dim = input_dim self.output_dim = output_dim self.verbose = verbose self.params = 3*(-1 + 2*np.random.rand(input_dim, output_dim))/np.sqrt(input_dim) def py_given_x(self, x): """ Returns the conditional probability of y given x Parameters ---------- x : array of shape nb_samples*input_dim Returns ------- y : array of shape nb_samples*output_dim with class probability components """ return softmax(np.dot(x, self.params)) def log_likelihood(self, x, y): """ Compute the log-likelihood of the data {x,y} according to the current parameters of the model. Parameters ---------- x : array of shape nb_samples*input_dim y : array of shape nb_samples*output_dim with one-hot row components Returns ------- ll : the log-likelihood """ post = self.py_given_x(x) lik = np.prod(post**y, axis=1) return np.sum(np.log(lik+1e-7)) def sample_y_given_x(self, x): """ Generate of sample for each row of x according to P(Y|X=x). Parameters ---------- x : array of shape nb_samples*input_dim Returns ------- y : array of shape nb_samples*output_dim with one-hot row vectors """ post = self.py_given_x(x) y = np.array([np.random.multinomial(1, post[i, :]) for i in range(x.shape[0])]) return y def fit(self, x, y, method='Newton-Raphson', max_iter=20): """ Learn the parameters of the model, i.e. self.params. Parameters ---------- x : array of shape nb_samples*nb_features y : array of shape nb_samples*output_dim method : string indicating the type of optimization - 'Newton-Raphson' nb_iter : the maximum number of iterations Returns ------- params : the matrix of parameters Examples -------- >>> from esnlm.nodes import LogisticRegression >>> x = np.array([[1., 0.],[0., 1]] >>> y = np.array([[0., 1.],[1., 0]] >>> params = LogisticRegression(2,2).fit(x, y) """ if type(y) == type([]): y = np.eye(self.output_dim)[y] def _objective_function(params): py_given_x = softmax(np.dot(x, params.reshape(self.params.shape))) lik = np.prod(py_given_x**y, axis=1) return np.sum(np.log(lik+1e-7)) params = np.array(self.params) old_value = _objective_function(params) if method == 'Newton-Raphson': print "... Newton-Raphson:", for i in range(max_iter): if self.verbose == True: print i, post = softmax(np.dot(x, params)) grad = gradient(x, y, post, np.ones((y.shape[0], ))) hess = hessian(x, y, post, np.ones((y.shape[0], ))) params = newton_raphson(grad, hess, params, _objective_function) new_value = _objective_function(params) if new_value < old_value + 1: break old_value = new_value self.params = params.reshape(self.params.shape) if self.verbose == True: print "The End." else: from scipy.optimize import minimize def obj(params): return -_objective_function(params) def grd(params): post = softmax(np.dot(x, params.reshape(self.params.shape))) return -gradient(x, y, post, np.ones((y.shape[0], ))).squeeze() def hsn(params): post = softmax(np.dot(x, params.reshape(self.params.shape))) return -hessian(x, y, post, np.ones((y.shape[0], ))) params = params.reshape(params.size) res = minimize(obj, params,jac=grd, hess=hsn, method=method, options={'maxiter':100, 'xtol': 1e-4, 'disp': True}) params = res.x self.params = params.reshape(self.params.shape) return params
b45c2f73e4c932c428e95e963b5b50a93cc5f80a
Realdo-Justino/infosatc-lp-avaliativo-01
/exercicio-18.py
114
3.640625
4
volume=float(input("Insira um valor em metros cubicos ")) litros=volume*1000 print("O valor em litros é",litros)
d26f22245aa20f0fdfaf0bb1900fa1f5a9e759d2
dcxufpb/unidade-1-exercicio-09-python-antonia-exe
/cupom.py
2,611
3.5
4
# coding: utf-8 def isEmpty(value: str) -> bool: return (value == None) or (len(value) == value.count(" ")) class Loja: def __init__(self, nome_loja, logradouro, numero, complemento, bairro, municipio, estado, cep, telefone, observacao, cnpj, inscricao_estadual): self.nome_loja = nome_loja self.logradouro = logradouro self.numero = numero self.complemento = complemento self.bairro = bairro self.municipio = municipio self.estado = estado self.cep = cep self.telefone = telefone self.observacao = observacao self.cnpj = cnpj self.inscricao_estadual = inscricao_estadual def dados_loja(self): if (isEmpty(self.nome_loja)): raise Exception("O campo nome da loja é obrigatório") if (isEmpty(self.logradouro)): raise Exception("O campo logradouro do endereço é obrigatório") numero = int() try: numero = int(self.numero) except Exception: numero = 0 if numero <= 0: numero = "s/n" if (isEmpty(self.municipio)): raise Exception("O campo município do endereço é obrigatório") if (isEmpty(self.estado)): raise Exception("O campo estado do endereço é obrigatório") if (isEmpty(self.cnpj)): raise Exception("O campo CNPJ da loja é obrigatório") if (isEmpty(self.inscricao_estadual)): raise Exception( "O campo inscrição estadual da loja é obrigatório") linha2 = f"{self.logradouro}, {numero}" if not isEmpty(self.complemento): linha2 += f" {self.complemento}" linha3 = str() if not isEmpty(self.bairro): linha3 += f"{self.bairro} - " linha3 += f"{self.municipio} - {self.estado}" linha4 = str() if not isEmpty(self.cep): linha4 = f"CEP:{self.cep}" if not isEmpty(self.telefone): if not isEmpty(linha4): linha4 += " " linha4 += f"Tel {self.telefone}" if not isEmpty(linha4): linha4 += "\n" linha5 = str() if not isEmpty(self.observacao): linha5 += f"{self.observacao}" output = f"{self.nome_loja}\n" output += f"{linha2}\n" output += f"{linha3}\n" output += f"{linha4}" output += f"{linha5}\n" output += f"CNPJ: {self.cnpj}\n" output += f"IE: {self.inscricao_estadual}" return output
5b972c19cb57573030b07f0d87949d4647b6c3bc
jeremysen/Python_Trip_Project
/Software/filter_suitable_service.py
2,115
3.5625
4
# -*- coding: utf-8 -*- ''' @Description: This file is used to generate suitable service for customer @Author: Shanyue @Time: 2019-10-02 ''' import pandas as pd def add_range_air(price,air_down,air_up): ''' Add range for air line :param price: price in df :param air_down: air_down :param air_up: air_up :return: whether in range ''' price = int(price) if(price<=(int)(air_up) and price>=(int)(air_down)): return 1 else: return 0 def get_suitable_hotel(city, mode): ''' Get suitable hotel based on mode :param city: city :param mode: mode of customer :return: hotel series ''' hotel = pd.read_csv("dataset/hotel_data.csv") hotel_city = hotel[(hotel["city"]==city) & (hotel["rate"] == "Excellent ")] if(len(hotel_city) == 0): hotel_city = hotel[(hotel["city"]==city) & (hotel["rate"] == "Very good ")] hotel_city = hotel_city.sort_values(by="price", ascending=True).reset_index(drop=True) if(mode=="Economy"): return list(hotel_city.iloc[0])[2], list(hotel_city.iloc[0])[6] else: return list(hotel_city.iloc[60])[2], list(hotel_city.iloc[60])[6] def get_suitable_airline(city, air_down, air_up): ''' Get suitable airline :param city: city :param air_down: air_down :param air_up: air_up :return: airline series ''' airline = pd.read_excel("dataset/airline_data.xlsx") airline_city = airline[(airline["ArrivalAirport"].str.contains(city))] airline_city = airline_city[~airline_city["Price"].isna()] airline_city["Price"] = airline_city["Price"].astype(int) airline_city["price_within"] = airline_city["Price"].apply(lambda x:add_range_air(x,air_down,air_up)) airline_city = airline_city[airline_city["price_within"] == 1] airline_city = airline_city.sort_values(by="Price", ascending=True).reset_index(drop=True) return list(airline_city.iloc[0])[5], list(airline_city.iloc[0])[10], list(airline_city.iloc[0]) if(__name__=="__main__"): suitable_hotel, hotel_price = get_suitable_hotel("Adelaide")
52999cf0bd784008f72c1b7469a5833acdb40749
gladguang/python-study
/study/笔记_python函数基础.py
2,667
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #**************************** 函数 ************************* ''' 我们知道圆的面积计算公式为: S = πr2 当代码出现有规律的重复的时候,你就需要当心了,每次写3.14 * x * x不仅很麻烦, 而且,如果要把3.14改成3.14159265359的时候,得全部替换。 有了函数,我们就不再每次写s = 3.14 * x * x,而是写成更有意义的函数调用s = area_of_circle(x), 而函数area_of_circle本身只需要写一次,就可以多次调用。 基本上所有的高级语言都支持函数,Python也不例外。Python不但能非常灵活地定义函数, 而且本身内置了很多有用的函数,可以直接调用。''' # abs() 求绝对值函数 max()返回最大值函数 ''' 练习 请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程 ax^2+bx+c=0ax 2 +bx+c=0 的两个解。 提示: 一元二次方程的求根公式为: 计算平方根可以调用math.sqrt()函数: >>> import math >>> math.sqrt(2) 1.4142135623730951 ''' """ import math def quadratic(a, b, c): if not isinstance(a,(int,float)) or not isinstance(b,(int,float)) or not isinstance(c,(int,float)): raise TypeError('bad operand type') d = b**2 - 4*a*c # 数字和字母相乘需要‘ * ’,和数学还是有差别的 if a == 0: # ‘ == ’在Python中是等于而‘ = ’是赋值,已踩坑 print('该方程没有意义') elif d < 0: # 小于零后是负数式子就不成立,所以无解 print('该方程无解') elif d == 0: x = -b/(2*a) # print(f'该方程的两个解为:x1=x2={x:.1f}') else: x1 = (-b+math.sqrt(d))/(2*a) x2 = (-b-math.sqrt(d))/(2*a) print(f'该方程的两个解为:x1={x1:.1f} x2={x2:.1f}') """ # 廖雪峰py进度 https://www.liaoxuefeng.com/wiki/1016959663602400/1017261630425888 2021.08.25 #************************************ 递归函数 *************************************** """card = '''---------------------- 信息卡 ---------------------- 姓名:文逸轩 --- 年龄:12 --- 籍贯:江西 --- 出生日期:2008 --- ------------------------------------------------------''' print(card)"""
836a7d1ef29a0c1bf1e530af5ffaffa8921a659b
gladguang/python-study
/study/7for_in循环.py
1,579
3.640625
4
# 计算1加到100之和 sum = 0 # 先初始化变量sum for a in range(1,101): # range(1,101)取大于等于1小于101的整数 ,即循环取1到10整数 sum += a # sum += a 等价于 sum = sum + a print(sum) # 打印和 ''' range(stop): 0~stop-1 range(start,stop): start~stop-1 range(start,stop,step): start~stop step(步长) ''' # 求1到100之间偶数之和 sum = 0 # 先初始化变量sum for a in range(2,101,2): # range(2,101,2)取从2开始加2一直到100的和 sum += a # sum += a 等价于 sum = sum + a print(sum) # 打印和 # 求1到100之间奇数之和 sum = 0 # 先初始化变量sum for a in range(1,101,2): # range(1,101,2)取从1开始加2一直到99的和 sum += a # sum += a 等价于 sum = sum + a print(sum) # 打印和 # 有1,2,3,4四个数字,求这四个数字能生成多少个互不相同且无重复数字的三位数 i = 0 for x in range(1,5): for y in range(1,5): for z in range(1,5): if (x!=y) and (y!=z) and (z!=x): i += 1 if i%4: print("%d%d%d" % (x, y, z), end=" | ") else: print("%d%d%d" % (x, y, z)) # 打印9*9乘法表 for i in range(1,10): for j in range(1,i+1): print('%d * %d = %d\t' %(i,j,i*j),end='') print()
56518fed8c3d23112f342a9e64337de4188da23e
razerboot/DataStrcutures-and-Algorithms
/python/sort_stack.py
252
3.6875
4
stack = [] def is_empty(stack): return len(stack)==0 def last(stack): if is_empty(stack): return False return stack[-1] def pop(stack): if is_empty(stack): return False return stack.pop(-1) def sort(stack):
eae0408ff5aa53a85d3e80e67443aaa30823a625
razerboot/DataStrcutures-and-Algorithms
/python/k_small_sorted_matrix.py
1,415
3.640625
4
# finding kth smallest element in row wise and column wise sorted matrix # complexity of k*(m+n) where m is row length and n is column length def adjust(matrix,x,y): n=len(matrix) m=len(matrix[x]) while(x<n and y<m): minx,miny = x,y leftx,lefty=x+1,y rightx,righty=x,y+1 if leftx<n and lefty<len(matrix[leftx]) and matrix[leftx][lefty]<matrix[minx][miny]: minx,miny=leftx,lefty if righty<len(matrix[x]) and rightx<n and matrix[rightx][righty]<matrix[minx][miny]: minx,miny = rightx,righty if (minx,miny) == (x,y): break else: matrix[x][y],matrix[minx][miny]=matrix[minx][miny],matrix[x][y] x,y = minx,miny def matrix_pop(matrix): n=len(matrix) m=len(matrix[n-1]) if n==1 and m==1: return matrix[0].pop() while matrix[n-1]==[]: matrix.pop() n=len(matrix) last = matrix[n-1].pop() first=matrix[0][0] matrix[0][0]=last adjust(matrix,0,0) return first def k_matrix_pop(matrix,k): for i in xrange(k-1): matrix_pop(matrix) return matrix_pop(matrix) matrix=[] n,m = map(int,raw_input().split()) for a0 in xrange(n): row=list(map(int,raw_input().split())) matrix.append(row) print k_matrix_pop(matrix,25) print matrix ''' # input 5 5 1 3 5 7 9 6 8 11 13 15 10 21 25 27 29 12 22 26 29 30 13 23 31 34 37 '''
2b8d249fbfa4d7edc6b4b1c466a31768418146a5
razerboot/DataStrcutures-and-Algorithms
/python/practice_llist_1.py
1,097
3.953125
4
class Node: def __init__(self,data): self.data = data self.next = None class llist: def __init__(self): self.head = None def is_empty(self): return self.head==None def add_node(self,data): temp = Node(data) temp.next = self.head self.head = temp def detect_loop(self): slow = self.head fast = self.head.next # detect loop while(fast and fast.next): if self==fast: break slow = slow.next fast =fast.next.next # move slow pointer from start and fast at meeting point with same speed till they meet which is the loop point #here we are checking slow!=fast.next bcoz both fast and slow will meet one step earlier instead of m since we intialized fast at one step ahead #of slow for not breaking the first loop at first step itself if slow==fast: slow = self.head while(slow!=fast.next): slow = slow.next fast = fast.next fast.next = None
fe0de4706937c31a0bb80b395dd15aa7d19241f3
razerboot/DataStrcutures-and-Algorithms
/python/count_sort.py
515
3.65625
4
def count_sort(arr): a = arr[min(arr)] b = arr[max(arr)] arr1 = {} # creating a count array for i in range(a,b): if arr[i]<=b and arr[i]>=a: if arr[i] in arr1: arr1[str(i)] += 1 else: arr1[str(i)] = 1 return arr1 #modifying count array def adding(arr,i): if i==0: return arr[0] arr[i] = arr[i]+adding(arr,i-1) return arr for i in range(arr): index = arr1[str(arr[i])] if i!=index: arr1
192ed0c3f624ef44e4be6a588c8fe8b4b7c8967e
razerboot/DataStrcutures-and-Algorithms
/python/max_heap_sort.py
1,406
3.8125
4
import math def max_heapify(arr,i,N): largest = i left = 2*i right = 2*i+1 if left<=N and arr[left]>arr[largest]: largest = left if right<=N and arr[right]>arr[largest]: largest=right if i!=largest: arr[i],arr[largest]=arr[largest],arr[i] max_heapify(arr,largest,N) def get_height(arr): N = len(arr)-1 return math.ceil(math.log(N+1,2)) def build_maxheap(arr,N): i = N/2 while(i>0): max_heapify(arr,i,N) i -=1 def insert_to_heap(arr,key,N): arr.append(key) N += 1 i = N p = N/2 while(p>=1 and arr[i]>arr[p]): arr[i],arr[p]=arr[p],arr[i] i /= 2 p /= 2 def extract_max(arr): N = len(arr)-1 #use heapify arr[1],arr[N] = arr[N],arr[1] value = arr.pop() max_heapify(arr,1,N-1) return value def find_max(): return arr[1] def heap_sort(arr,N): build_maxheap(arr,N) i=N while(i>1): arr[1],arr[i]=arr[i],arr[1] max_heapify(arr,1,i-1) i -= 1 #use build_maxheap once #use heapify arr =[0] n = int(raw_input()) arr1= map(int,raw_input().strip().split()) arr.extend(arr1) print get_height(arr) build_maxheap(arr,n) print arr print get_height(arr) print extract_max(arr) print arr print get_height(arr) print extract_max(arr) print arr print get_height(arr) insert_to_heap(arr,200,len(arr)-1) print arr
c3ef17c89a84060229e21c19f3c923f783e1d17f
razerboot/DataStrcutures-and-Algorithms
/python/bs_tree.py
5,099
3.703125
4
class Node(): def __init__(self,key): self.left = None self.right = None self.val = key class BST(): def __init__(self): self.head=None def insert(self,head,key): if key>head.val: if head.right==None: head.right=Node(key) else: self.insert(head.right,key) elif key<head.val: if head.left==None: head.left=Node(key) else: self.insert(head.left, key) return def inorder_succ(self,node): succ = None if node.right==None: succ = self.inorder_succ_null(self.head,node,succ) else: succ = self.find_min(node.right) return succ def inorder_succ_null(self,head,node,succ): if head==None: return None while(head!=None): if node.val>head.val: head = head.right elif node.val<head.val: succ = head head=head.left else: break return succ def find_min(self,head): if head is None: return while(head.left!=None): head = head.left return head def lca(self,key1,key2,head): if head==None: return None if key1<head.val and key2<head.val: return self.lca(key1,key2,head.left) elif key1>head.val and key2>head.val: return self.lca(key1,key2,head.right) else: return head def traverse_inorder(self,head,arr): if head==None: return self.traverse_inorder(head.left,arr) arr.append(head.val) self.traverse_inorder(head.right,arr) return # checking whether a bt is a bst or not #application of dfs inorder def check_bst(self,head,prev): if head==None: return True if not self.check_bst(head.left,prev): return False if head.val<prev[0]: return False prev[0] = head.val if not self.check_bst(head.right,prev): return False return True #returning kth element using in order traversal def return_k(self,head,k,c): if head==None: return None left = self.return_k(head.left,k,c) if left: return left c[0]+=1 if k==c[0]: return head.val right=self.return_k(head.right,k,c) if right: return right #swap wrongly inserted elements def swap(self,head,arr,prev): if head==None: return if len(arr)>2: return self.swap(head.left,arr,prev) if prev[0].val>head.val: if arr==[]: arr.append(prev[0]) arr.append(head) else: arr.append(head) prev[0] = head self.swap(head.right,arr,prev) return def delete(self,head,key): if key>head.val: head.right=self.delete(head.right, key) elif key<head.val: head.left = self.delete(head.left, key) else: if head.left==None: temp = head.right head=None return temp elif head.right==None: temp=head.left head=None return temp temp = self.inorder_succ(head) head.val = temp.val head.right = self.delete(head.right,temp.val) return head b_tree = BST() b_tree.head=Node(14) b_tree.insert(b_tree.head,8) b_tree.insert(b_tree.head,21) b_tree.insert(b_tree.head,4) b_tree.insert(b_tree.head,11) b_tree.insert(b_tree.head,17) b_tree.insert(b_tree.head,25) b_tree.insert(b_tree.head,2) b_tree.insert(b_tree.head,6) b_tree.insert(b_tree.head,9) b_tree.insert(b_tree.head,13) b_tree.insert(b_tree.head,15) b_tree.insert(b_tree.head,19) b_tree.insert(b_tree.head,23) b_tree.insert(b_tree.head,1) b_tree.insert(b_tree.head,3) b_tree.insert(b_tree.head,5) b_tree.insert(b_tree.head,7) b_tree.insert(b_tree.head,10) b_tree.insert(b_tree.head,12) b_tree.insert(b_tree.head,16) b_tree.insert(b_tree.head,18) b_tree.insert(b_tree.head,20) b_tree.insert(b_tree.head,22) b_tree.insert(b_tree.head,24) b_tree.insert(b_tree.head,26) b_tree.head.left.val,b_tree.head.left.left.right.right.val = b_tree.head.left.left.right.right.val,b_tree.head.left.val arr=[] b_tree.traverse_inorder(b_tree.head,arr) print arr #print b_tree.find_min(b_tree.head).val #b_tree.delete(b_tree.head,1) print b_tree.check_bst(b_tree.head,[-422234245]) #print b_tree.lca(10,8,b_tree.head).val #print b_tree.return_k(b_tree.head,21,[0]) #temp = Node(-24346321) #arr = [] #b_tree.swap(b_tree.head,arr,[temp]) #if len(arr)==2: # arr[0].val,arr[1].val = arr[1].val,arr[0].val #elif len(arr)==3: # arr[0].val, arr[2].val = arr[2].val, arr[0].val #arr=[] #b_tree.traverse_inorder(b_tree.head,arr) #print arr #print arr[0].val #print arr[1].val #print arr[2].val
9290cc0f2726d048b125d78b6b8bc83a11f97d74
R-aryan/Basics-Data-Structures-And-Algorithms
/Arrays/Anagram_Check.py
731
4.0625
4
''' Problem - Given two strings s1 and s2, check if both the strings are anagrams of each other. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. ''' from collections import Counter def check_anagram(first_string,second_string): d1=Counter(first_string) d2= Counter(second_string) # print(d1) # print(d2) if d1==d2: #print('Are anagrams') return True else: return False s1= (input("Enter first string \n")).lower() s2= (input("Enter second string \n")).lower() if check_anagram(s1,s2): print('True') else: print('False')
08a84913a2e0a9de0789aeb099a6ffc7a2b94f7a
R-aryan/Basics-Data-Structures-And-Algorithms
/stacks and Queues/dqueue.py
862
3.71875
4
class Dqueue(object): def __init__(self): self.items=[] def isEmpty(self): return self.items==[] def addFront(self,num): self.items.append(num) print("{} Added at front successfully..!".format(num)) def addRear(self,num): self.items.insert(0,num) print("{} Added at rear successfully..!".format(num)) def removeFront(self): r= self.items.pop() print('Successfully popped from front...!!'+str(r)) def removeRear(self): r= self.items.pop(0) print("Successfuly removed from rear..!!"+str(r)) def size(self): l= len(self.items) print("Length of Deque is "+ str(l)) d=Dqueue() d.addFront(12) d.addRear(45) d.addFront(89) d.addFront(78) d.addFront(42) d.addRear(890) d.size() d.removeFront() d.removeRear() d.size()
0e9880512bebfff94a020bf37ea1adedbad5d70d
Hollow667/Python-Crash-Course
/Lastname_greet.py
195
3.84375
4
pretty = "*" name = input("Enter your name: ") school = input("What school do you go to?") print(pretty *70) print("\tHi, " + name + ", " + school + " is a great school") print(pretty *70)
85a6612754425c4b01800d97166616c6fcb296e4
byronlara5/python_analyzing_data
/module_1/three.py
1,490
4.09375
4
import pandas as pd file = '/home/byron_lara/PycharmProjects/analyzing_data/venv/module_1/cars.csv' # Creating DataFrame with the Cars file df = pd.read_csv(file) # List of headers for the CSV File headers = [ "Symboling","Normalized-losses","Make","Fuel-type","Aspiration","Num-of-doors","Body-style", "Drive-wheels","Engine-location","Wheel-base","Length","Width","Height","Curb-weight","Engine-type", "Num-of-cylinders","Engine-size","Fuel-system","Bore","Stroke","Compression-ratio","HP","Peak-rpm", "City-mpg","Highway-mpg","Price" ] # Assigning the headers df.columns = headers # Dropping missing values in the column Price # axis=0 drops the entire row, axis=1 drops the entire column df.dropna(subset=["Price"], axis=0) # Saving the dataset (We do this in order to add the new header to the file df.to_csv("cars_new.csv", index=False) """ We can also read and save to other file formats, like this: (pd meaning: pandas, df meaning: dataframe) Data Formate | Read | Save | ========================================================= CSV pd.read_csv() df.to_csv() JSON pd.read_json() df.to_json() EXCEL pd.read_excel() df.to_excel() HDF pd.read_hdf() df.to_hdf() SQL pd.read_sql() df.to_sql() ========================================================= """
94d50aa6f1e74abbd70d07494e2b3df47fb1bc20
amyq7526110/python
/python1/while.py
1,899
3.515625
4
#!/usr/bin/env python3 import os import readline a=os.popen('echo 1').readline() print(a) os.system('ls') # 循环概述 # • 一组被重复执行的语句称之为循环体,能否继续重复, # 决定循环的终止条件 # • Python中的循环有while循环和for循环 # • 循环次数未知的情况下,建议采用while循环 # • 循环次数可以预知的情况下,建议采用for循环 # while循环语法结构 # • 当需要语句不断的重复执行时,可以使用while循环 # while expression: # while_suite # 语句while_suite会被连续不断的循环执行,直到表达 # 式的值变成0或False a=1 while a <= 20 : print(a,end=' ') a += 1 # print() a=1 while a <= 20: print(a,end=' ') a += 2 # 循环语句进阶 # # break语句 # break语句可以结束当前循环然后跳转到下条语句 # 写程序的时候,应尽量避免重复的代码,在这种情况 # 下可以使用while-break结构 name = input('username=') while name !='tom': name = input('username=') while True: name = input('username=') if name == 'tom': break # continue语句 # • 当遇到continue语句时,程序会终止当前循环,并忽 # 略剩余的语句,然后回到循环的顶端 # • 如果仍然满足循环条件,循环体内语句继续执行,否 # 则退出循环 num=0 while num < 20: num += 1 if num % 2 == 0: continue print(num,end=' ') print() # else语句 # • python中的while语句也支持else子句 # • else子句只在循环完成后执行 # • break语句也会跳过else块 sum10 = 0 i = 1 while i <= 10: sum10 += i i += 1 else: print(sum10) # 死循环 # 条件永远满足的循环叫做死循环 # 使用break可以退出死循环 # else永远不执行
74bd3483814ac5ccf695c5df2fe7fee7a826ee7e
amyq7526110/python
/python1/xvlist.py
1,414
4
4
#!/usr/bin/env python3 # 序列 # 序列类型操作符 # 序列操作符 作用 # seq[ind] 获得下标为ind的元素 # seq[ind1:ind2] 获得下标从ind1到ind2间的元素集合 # seq * expr 序列重复expr次 # seq1 + seq2 连接序列seq1和seq2 # obj in seq 判断obj元素是否包含在seq中 # obj not in seq 判断obj元素是否不包含在seq中 # 内建函数 # 函 数 含 义 # list(iter) 把可迭代对象转换为列表 # str(obj) 把obj对象转换成字符串 # tuple(iter) 把一个可迭代对象转换成一个元组对象 print(list('abc')) print(list(range(10))) print(list([1,2,3])) # print(list(132)) # 报错 print(str(100)) print(str(True)) print(tuple(range(10))) print(tuple('abc')) # 内建函数(续1) # len(seq):返回seq的长度 # max(iter,key=None):返回iter中的最大值 # enumerate:接受一个可迭代对象作为参数,返回一 # 个enumerate对象 print(enumerate('abc')) # 内建函数(续2) # reversed(seq):接受一个序列作为参数,返回一个以 # 逆序访问的迭代器 # sorted(iter):接受一个可迭代对象作为参数,返回 # 一个有序的列表 print(reversed([1,2,3])) for i in reversed([1,2,3]): print(i,end='') print() print(sorted('abecd')) print(sorted([1,4,3,7,6,8])) print(sorted((1,10,8,5,9)))
163314ac51a6e2c90fddc5a9da703cd00391aa27
amyq7526110/python
/python6/zb4.py
1,094
3.53125
4
#!/usr/bin/env python3 import os import time start = time.time() print('Start...') pid = os.fork() if pid: print('in parent..') print(os.waitpid(-1,1)) # 挂起 time.sleep(20) else: print('in child') time.sleep(10) end = time.time() print(end - start) # 使用轮询解决zombie问题 # • 父进程通过os.wait()来得到子进程是否终止的信息 # • 在子进程终止和父进程调用wait()之间的这段时间, # 子进程被称为zombie(僵尸)进程 # • 如果子进程还没有终止,父进程先退出了,那么子进 # 程会持续工作。系统自动将子进程的父进程设置为 # init进程,init将来负责清理僵尸进程使用轮询解决zombie问题(续1) # • python可以使用waitpid()来处理子进程 # • waitpid()接受两个参数,第一个参数设置为-1,表示 # 与wait()函数相同;第二参数如果设置为0表示挂起父 # 进程,直到子程序退出,设置为1表示不挂起父进程 # • waitpid()的返回值:如果子进程尚未结束则返回0, # 否则返回子进程的PID
0e206114f148e603d7e0a233aa46fa3e6bfca7d0
amyq7526110/python
/python1/else.py
266
3.765625
4
#!/usr/bin/env python3 # else语句 # • python中的while语句也支持else子句 # • else子句只在循环完成后执行 # • break语句也会跳过else块 sum10 = 0 i = 1 while i <= 10: sum10 += i i += 1 else: print(sum10)
6c135e2c9a64ba6083c31ea591caaf1974ba6a0b
amyq7526110/python
/python4/toy.factory4.py
2,322
3.5625
4
#!/usr/bin/env python3 # 构造器方法 # • 当实例化类的对象是,构造器方法默认自动调用 # • 实例本身作为第一个参数,传递给self class BearToy: def __init__(self,name,size,color): "实例化自动调用" self.name = name # 绑定属性到self 上整个类可以引用 self.size = size self.color = color # 创建子类(续1) #• 创建子类只需要在圆括号中写明从哪个父类继承即可 # 继承 # • 继承描述了基类的属性如何“遗传”给派生类 # • 子类可以继承它的基类的任何属性,不管是数据属性 # 还是方法 class NewBear(BearToy): # "父子类有同名方法,子类对象继承子类方法" def __init__(self,name,size,color,date): super(NewBear, self).__init__(name,size,color) self.date = date def run(self): print('我能爬!') # 创建子类 # • 当类之间有显著的不同,并且较小的类是较大的类所 # 需要的组件时组合表现得很好;但当设计“相同的类 # 但有一些不同的功能”时,派生就是一个更加合理的 # 选择了 # • OOP 的更强大方面之一是能够使用一个已经定义好 # 的类,扩展它或者对其进行修改,而不会影响系统中 # 使用现存类的其它代码片段 # • OOD(面向对象设计)允许类特征在子孙类或子类中进行继承 # 其他绑定方法 # • 类中定义的方法需要绑定在具体的实例,由实例调用 # • 实例方法需要明确调用 def sing(self): print('I am %s, lalala' % self.name) if __name__ == '__main__': big = NewBear('雄大','Large','Brown','2018-10') # 将会调用__init__ 方法,big传递给self big.run() print(big.date) print(big.name) # 组合应用 # • 两个类明显不同 # • 一个类是另一个类的组件 # 知 # 识 # 讲 # 解 # classManufacture: # def__init__(self, phone, email): # self.phone= phone2numeric( # self.email= email # # classBearToy: # def__init__(self, size, color, phone, email): # self.size= sizeCentralDir # self.color= color_content( # self.vendor= Manufacture(phone, email)
b4590355111ceb038ccf9732c54cf66e4e83fee8
amyq7526110/python
/python4/jingtff.py
451
4.03125
4
#!/usr/bin/env python3 class Date: def __init__(self,year,month,date): self.year = year self.month = month self.date = date @staticmethod def is_date_valid(string_date): year,month,date = map(int,string_date.split('-')) return 1 <= date <=21 and 1 <= month <= 12 and year <= 3999 if __name__ == '__main__': print(Date.is_date_valid('2018-05-04')) print(Date.is_date_valid('2018-22-04'))
1ddc769f2b667a16f412974597748cf09b7c1832
amyq7526110/python
/python1/fibs.py
302
3.75
4
#!/usr/bin/env python3 def fib(x): fibo = [0,1 ] for i in range(x-2): fibo.append(fibo[-1]+fibo[-2]) print(fibo) #fibs(10) #febo(6) #febo(10) print(__name__) # 保存模块名 # 当模块直接执行是__name__的值为__name__ # if __name__ == '__mian__': fib(10)
34a8045d00851db70682202a13250056e1c691f6
MoonRaccoon/CS101
/while_loops.py
95
3.625
4
def print_numbers(a): while(x != a): x = 0 x = x + 1 print x
5ae1dd1fb039661776c36210caee4d8a191ef53d
MoonRaccoon/CS101
/range.py
586
3.71875
4
def bigger(a, b): if a > b: return a else: return b def smaller(a, b): if a < b: return a else: return b def biggest(a, b, c): return bigger(a, bigger(b, c)) def smallest(a, b, c): if biggest(a, b, c) == a: med = smaller(b, c) return med if biggest(a, b, c) == b: med = smaller(a,c) return med if biggest(a, b, c) == c: med = smaller(a,b) return med def set_range(a, b, c): maximum = biggest(a, b, c) minimum = smallest(a, b ,c) return maximum - minimum
4e406529eac6ea82a9ea111bd67afcbe5ca2bd69
Viniuau/meus-scripts
/math.py
900
4.09375
4
print("Digita um número ae meu consagrado") x = int(input("Número 1 é esse: ")) y = int(input("Número 2 é esse: ")) print("Prontinho, agora escolhe o que tu quer fazer com eles") print("1 - Somar") print("2 - Subtração") print("3 - Multiplicação") print("4 - Divisão") escolha = int(input("Seu comando: ")) while(escolha > 0): if (escolha == 1): print("A soma dá", x+y, "meu amiguinho") escolha = 0 elif (escolha == 2): print("A subtração dá", x-y, "meu amiguinho") escolha = 0 elif(escolha == 3): print("A multiplicação dá", x*y, "meu amiguinho") escolha = 0 elif(escolha == 4): print("A divisão dá", x/y, "meu amiguinho") escolha = 0 else: print("opora tu digitou o número errado") break else: print("Valeu por usar meu script para suas fórmulas matemágicas kek flw flw")
503700558831bf7513fc8987bb669f0e17d144c0
deepika7007/bootcamp_day2
/Day 2 .py
1,301
4.1875
4
#Day 2 string practice # print a value print("30 days 30 hour challenge") print('30 days Bootcamp') #Assigning string to Variable Hours="Thirty" print(Hours) #Indexing using String Days="Thirty days" print(Days[0]) print(Days[3]) #Print particular character from certin text Challenge="I will win" print(challenge[7:10]) #print the length of the character Challenge="I will win" print(len(Challenge)) #convert String into lower character Challenge="I Will win" print(Challenge.lower()) #String concatenation - joining two strings A="30 days" B="30 hours" C = A+B print(C) #Adding space during Concatenation A="30days" B="30hours" C=A+" "+B print(C) #Casefold() - Usage text="Thirty Days and Thirty Hours" x=text.casefold() print(x) #capitalize() usage text="Thirty Days and Thirty Hours" x=text.capitalize() print(x) #find() text="Thirty Days and Thirty Hours" x=text.find() print(x) #isalpha() text="Thirty Days and Thirty Hours" x=text.isalpha() print(x) #isalnum() text="Thirty Days and Thirty Hours" x=text.isalnum() print(x) Result: 30 days 30 hour challenge 30 days Bootcamp Thirty T r win 10 i will win 30 days30 hours 30days 30hours thirty days and thirty hours Thirty days and thirty hours -1 False False ** Process exited - Return Code: 0 ** Press Enter to exit terminal
5571025882b22c9211572e657dd38b1a9ecdfa74
martinkozon/Martin_Kozon-Year-12-Computer-Science
/Python/extra_sum_of_two.py
342
4.1875
4
#Program which will add two numbers together #User has to input two numbers - number1 and number2 number1 = int(input("Number a: ")) number2 = int(input("Number b: ")) #add numbers number1 and number2 together and print it out print(number1 + number2) #TEST DATA #Input 1, 17 -> output 18 #Input 2, 5 -> output 7 #Input 66, 33 -> output 99
fa98a79e66cd7e8575c857dabad5877c3b78cd87
martinkozon/Martin_Kozon-Year-12-Computer-Science
/Python/06_input-validation.py
816
4.25
4
#User has to input a number between 1 and 10 #eg. if user inputs 3, the result will be as follows: 3 -> 3*1=3, 3*2=6, 3*3=9 #ask a user to input a number number = int(input("Input number between 1 and 10: ")) #if the input number is 99 than exit the program if number == 99: exit() # end if #if the number isn't the one we want, the user will have to submit it again while number < 1 or number > 10: print("Number needs to be BETWEEN 1 and 10") number = int(input("Input number between 1 and 10: ")) # end while #times table running in a for loop with a range of 12 for count in range(12): table = (count+1) * number #multiply count by the inputted number print(str(count + 1) + " * " + str(number) + " = " + str(table)) #print out a result # end for # 27.9.19 EDIT - updated variable naming
1165adb6c5f681f38ee8fc21eda598f9ace811fe
martinkozon/Martin_Kozon-Year-12-Computer-Science
/Python/Python Prep and Worksheet practice/CarPark.py
812
3.96875
4
carPark = [ [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], ] #always ask the user for input while True: row = int(input("Row location (1 to 10): ")) - 1 # -1 because arrays start from 0 position = int(input("Position (1 to 6): ")) - 1 #user input validation, if it's incorrect that user has to submit again if (row > -1) and (row < 11) and (position > -1) and (position < 7): #if there's a car parked already, user will have to submit again if carPark[row][position] == 1: print("You can't park there...") else: carPark[row][position] = 1 print("You've parked in a row " + str(row + 1)) print(carPark[row]) else: print("Submit again...")
726a2e884e1ea29daf0c322c6c9d7051e0735a1a
martinkozon/Martin_Kozon-Year-12-Computer-Science
/Python/pass_by_reference_or_value.py
204
3.578125
4
def proc1(x, y): x = x - 2 y = 0 print(x, y) #result is 6,0 #end procedure #main program m = 8 n = 10 proc1(m ,n) print(m, n) #result is 8,10 #by val: x - immutable #by ref: y - mutable
5453ba2f4a55d71966633f1e2236982b4177e7ae
MyHealthyHair/Week7
/guests.py
114
3.71875
4
name = input("enter your name: ") filename = 'guest.txt' with open(filename, 'w') as f: f.write(name)
a0a908c5a23b2a5f2c73753fb526d3c006076b7a
RF0606/CISC327_PROJECT
/qa327/app.py
13,484
3.640625
4
import csv import time import re status = False user_name = '' user_email = '' user_password = '' balance = -1 accFile = open('accounts.csv', 'r+') ticketFile = open('tickets.csv', 'r+') accReader = csv.reader(accFile) ticketReader = csv.reader(ticketFile) location_arg = open('frontend_locations.txt', 'r').readline() tranFile = open(location_arg+'_transactions.csv', 'a+', newline='') tranWriter = csv.writer(tranFile) def main(): print('Welcome the Queens ticket trade machine') R1() def R1(): if status: print('your balance:', balance) # print out the user's balance input1 = input('type your choice:\nsell buy update logout\n') if input1 == 'sell': # user wants to go to sell session R4() elif input1 == 'buy': # user wants to go to buy session R5() elif input1 == 'update': # user wants to go to update session R6() elif input1 == 'logout': # user wants to go to logout session R7() else: # user enters other invalid commands print('invalid command') R1() if not status: input1 = input('type your choice:\nregister login exit\n') if input1 == 'register': # user wants to go to register session R2() elif input1 == 'login': # user wants to go to login session R3() elif input1 == 'exit': # user wants to go to exit session R8() else: # user enters other invalid commands print('invalid command') R1() def R2(): # R2 will be the register session, which will allow user to register their account print('register session started successfully') try: # if inputs are missing, call R2 again register_email, register_name, register_password, register_password2 = input('please enter your email, user ' 'name, password and confirm your ' 'password:\n').split(',') except: #optin to exit print('please retype\nthe number of inputs should be 4 or exit') exitOrNot = input('do you want to exit register session(type exit to leave):') if exitOrNot == 'exit': R1() R2() # do the testing for user inputs, and outputs warning if there is any error. finally, go back to R1 if not (check_register_email(register_email) and check_exits_email(register_email) and check_register_name( register_name) and check_register_password(register_password) and check_register_password2( register_password, register_password2)): R1() tranWriter.writerow(['registration', register_name, register_email, register_password, 3000]) # write registration information into file tranFile.flush() print('account registered') R1() def R3(): print('login session started successfully') try: # if inputs are missing, call R3 again login_email, login_password = input('please type your email and password:\n').split(',') except: print('please retype\nthe number of inputs should be 2') R1() if not (check_register_email(login_email) and check_register_password(login_password)): R1() # check the format of inputs. return R1 if there is anything invalid for i in accReader: # go over every user info to check login if not i: continue if login_email == i[0] and login_password == i[2]: global status, user_name, user_email, user_password, balance # set global value to be the user info if login succeeded user_name = i[1] user_email = i[0] user_password = i[2] balance = i[3] status = True print('account logged in') R1() # return R1 if failed print('login failed') R1() def R4(): print('selling session started successfully') try: # if inputs are missing, call R4 again ticket_name, price, quantity, date = input('please type ticket name, price, quantity, date:\n').split(',') except: print('please retype\nthe number of inputs should be 4') R1() if not (check_ticket_name(ticket_name) and check_price(price) and check_quantity_sell(quantity) and check_date( date)): R1() # check the format of inputs. return R1 if there is anything invalid price = eval(price) price = round(price, 2) # write the transaction tranWriter.writerow(['selling', user_email, ticket_name, price, quantity]) tranFile.flush() print('selling transaction was created successfully') R1() def R5(): print('buying session started successfully') try: # if inputs are missing, call R5 again ticket_name, quantity = input('please type ticket name, quantity:\n').split(',') except: print('please retype\nthe number of inputs should be 2') R1() if not (check_ticket_name(ticket_name)): R1() # check the format of inputs. return R1 if there is anything invalid count = 0 for i in ticketReader: # go over every ticket to check if exists if not i: continue if ticket_name == i[0]: price = i[1] aval_quantity = i[2] count += 1 if count == 0: print('the ticket does not exist') R1() if not (check_quantity_buy(price, quantity, aval_quantity)): R1() # check the format of inputs. return R1 if there is anything invalid price = eval(price) price = round(price, 2) # write the transaction tranWriter.writerow(['buying', user_email, ticket_name, price, quantity]) tranFile.flush() print('buying transaction was created successfully') R1() def R6(): print('updating session started successfully') try: # if inputs are missing, call R6 again ticket_name, price, quantity, date = input('please type ticket name, price, quantity, date:\n').split(',') except: print('please retype\nthe number of inputs should be 4') R1() if not (check_ticket_name(ticket_name) and check_price(price) and check_quantity_sell(quantity) and check_date( date)): R1() # check the format of inputs. return R1 if there is anything invalid count = 0 for i in ticketReader: # go over every ticket to check if exists if not i: continue if ticket_name == i[0] and user_email == i[3]: count += 1 if count == 0: print('the ticket does not exist') R1() price = eval(price) price = round(price, 2) # write the transaction tranWriter.writerow(['updating', user_email, ticket_name, price, quantity]) tranFile.flush() print('updating transaction was created successfully') R1() def R7(): global status, user_name, user_email, user_password, balance if status: # user already logged in print("logout successfully") user_name = '' user_email = '' user_password = '' balance = -1 status = False else: # user has not logged in print("you are not login\nplease enter login") def R8(): print('exit') # close three resource files accFile.close() ticketFile.close() tranFile.close() exit(0) ''' this function will check the ticket name format ''' def check_ticket_name(ticket_name): if not (ticket_name.replace(' ','').isalnum()): print('transaction was created unsuccessfully\nplease retype\nticket name should be ' 'alphanumeric-only') return False if ticket_name[0].isspace() or ticket_name[len(ticket_name) - 1].isspace(): print('transaction was created unsuccessfully\nplease retype\nspace allowed only if it is not the ' 'first or the last character') return False elif len(ticket_name) > 60: print('transaction was created unsuccessfully\nplease retype\nthe ticket name should be no longer ' 'than 60 characters') return False return True ''' this function will check the price valid ''' def check_price(price): if not (price.isdigit()): print('transaction was created unsuccessfully\nplease retype\nthe ticket price should be numeric') return False price = eval(price) if not (10 <= price <= 100): print('transaction was created unsuccessfully\nplease retype\nthe ticket price should be of range [' '10, 100]') return False return True ''' this function will check the quantity valid when selling ''' def check_quantity_sell(quantity): quantity = eval(quantity) if not (isinstance(quantity, int)): print('transaction was created unsuccessfully\nplease retype\nthe ticket quantity should be an ' 'integer') return False if not (0 < quantity <= 100): print('transaction was created unsuccessfully\nplease retype\nthe quantity of the tickets has to be ' 'more than 0, and less than or equal to 100') return False return True ''' this function will check date format ''' def check_date(date): try: time.strptime(date, "%Y%m%d") return True except: print('transaction was created unsuccessfully\nplease retype\ndate must be given in the format ' 'YYYYMMDD') return False ''' this function will check the quantity valid when buying ''' def check_quantity_buy(price, quantity, aval_quantity): price = eval(price) quantity = eval(quantity) aval_quantity = eval(aval_quantity) if not (isinstance(quantity, int)): print('transaction was created unsuccessfully\nplease retype\nthe ticket quantity should be an ' 'integer') return False if not (0 < quantity <= aval_quantity): print('transaction was created unsuccessfully\nplease retype\nthe quantity of the tickets has to be ' 'more than 0, and less than or equal to the available quantity') return False elif not (float(balance) >= price * quantity * 1.35 * 1.05): print('transaction was created unsuccessfully\nplease retype\nyour balance is insufficient') return False return True ''' this function will take an string of user email as input, and True or False as output it will check if the format of email is correct ''' def check_register_email(register_email): # if the format of input email is not as follows, return false if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", register_email) is None: print("email format is incorrect\n") return False return True ''' this function will take an string of user email as input, and True or False as output it will check if the email is already exits ''' def check_exits_email(register_email): accReader = csv.reader(open('accounts.csv', 'r')) # read the file # if input email already exits, return False for i in accReader: if not i: continue elif register_email == i[0]: print("account exits\n") return False return True ''' this function will take an string of user name as input, and True or False as output it will check if the format of user name is correct ''' def check_register_name(register_name): # name can only be alphanumerical if not (register_name.isalnum() or ' ' in register_name): print('user name format is incorrect (User name should be alphanumeric-only)\n') return False # space allowed only if it's not the first and last character if (register_name[0] == ' ' or register_name[len(register_name) - 1] == ' '): print('user name format is incorrect (Space allowed only if it is not the first or the last character)\n') return False # length of name should be longer than 2 and shorter than 20 elif len(register_name) >= 20 or len(register_name) <= 2 : print('user name format is incorrect (User name should be longer than 2 and shorter that 20 characters)\n') return False return True ''' this function will take an string of user password as input, and True or False as output it will check if the format of user password is correct ''' def check_register_password(register_password): # if the format of input password is not as follows, return false # at least one upper and one lower case with special characters, minimum 6 in length #pattern = r'^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)^.{6,}$' pattern = '^(?=.*[a-z])(?=.*[A-Z])(?=.*[-+_!@#$%^&*., ?])^.{6,}$' # Compile the ReGex res = re.compile(pattern) if re.search(res, register_password): return True print('password format is incorrect\n') return False ''' this function will take two string of user password as input, and True or False as output it will check if two input are the same ''' def check_register_password2(register_password, register_password2): if register_password == register_password2: return True print("two password doesn't match, please confirm your password\n") return False if __name__ == "__main__": main()
f51967bcf553fce95358287bbbec086d9551f58f
KUMAWAT55/Monk-Code
/Hackerrank/Python/Integer-comes-in-all-sizes.py
270
3.78125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT a=int(raw_input()) b=int(raw_input()) c=int(raw_input()) d=int(raw_input()) if 1<=a<=1000: if 1<=b<=1000: if 1<=c<=1000: if 1<=d<=1000: print pow(a,b)+pow(c,d)
d6e2926f246dc78f660d0f156d763e4a4202aa3d
KUMAWAT55/Monk-Code
/Hackerrank/Python/Loops.py
200
3.78125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT #input converting to integer n=int(raw_input()) if 1<=n<=20: i=0 while i<n: print i*i i=i+1
4f2cac94170db764aa3dacd2ca2dc11671fc0c7d
KUMAWAT55/Monk-Code
/Hackerrank/Algorithms/A_Very_Big_Sum.py
167
3.515625
4
#----------> PYTHON 3 <---------- import sys sum=0 n = int(input().strip()) arr = input().strip().split(' ') for i in range(0,n): sum=sum+int(arr[i]) print (sum)
e0c5f15e87b35d74bd3256cc70124ecb3cca737d
KUMAWAT55/Monk-Code
/HackerEarth/Basic-Programming/Palindromic String.py
148
3.609375
4
n=raw_input() if 1<=len(n)<=100: c=''.join(reversed(n)) if n==c: print "YES" else: print "NO"
ec26668740975b3d929b8114eaa5bd9845582967
JohntyR/Day18_Turtle
/newmain.py
557
3.71875
4
import turtle as t from shape import Shape from random import randint screen = t.Screen() timmy = t.Turtle() screen.colormode(255) timmy.shape("turtle") timmy.color("dark magenta") timmy.pensize(10) timmy.speed("fastest") timmy.penup() def gen_random_colour(): r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) return (r, g, b) for i in range(10): timmy.setposition(-300, 300 - (i * 45)) for j in range(10): timmy.color(gen_random_colour()) timmy.dot() timmy.forward(45) screen.exitonclick()
15e022eb2fbc2d17ee9dd7787a5c301d43dbb89a
GitLeeRepo/PythonNotes
/basics/sort_ex1.py
777
4.59375
5
#!/usr/bin/python3 # Examples of using the sorted() function # example function to be used as key by sorted function def sortbylen(x): return len(x) # List to sort, first alphabetically, then by length a = [ 'ccc', 'aaaa', 'd', 'bb'] # Orig list print(a) # Sorted ascending alphabetic print(sorted(a)) # sorted decending alphabetc print(sorted(a, reverse=True)) # use the len() function to sort by length print(sorted(a, key=len)) # use my own custom sort key function print(sorted(a, key=sortbylen)) # use my custom sort key function reversed print(sorted(a, key=sortbylen, reverse=True)) # Orig list still unchanged print(a) # but the sort() method will change the underlying list # unlike the sorted function call which creates a new one a.sort() print(a)
8da7f3ba63ae287850cb95fdaf6991da36855947
GitLeeRepo/PythonNotes
/basics/python_sandbox01.py
1,833
4.1875
4
#!/usr/bin/python3 # Just a sandbox app to explore different Python features and techniques for learning purposes import sys def hello(showPrompt=True): s = "Hello World!" print (s) #using slice syntax below print (s[:5]) #Hello print (s[6:-1]) #World print (s[1:8]) #ello wo print (s[1:-4]) #ello wo - same result indexing from right if len(sys.argv) > 1: print ("Command line args: " + str(sys.argv[1:])) #print the command line args if they exists if showPrompt: name = input ("Name?") print ("Hello " + name) print ("Hello", name) #both valid, 2nd adds its own space else: print ("Input not selected (pass True on hello() method call to display input prompt)") def listDemos(): list1 = [1, 2, 3] print(list1) list2 = [4, 5, 6] list3 = list1 + list2 #adds list2 to the end of list1 print(list3) list4 = list2 + list1 #adds list1 to the end of list2 print(list4) print("List pointer:") list1Pointer = list1 #they point to same location list1[0] = "1b" print(list1) print(list1Pointer) print("List copy") list1Copy = list1[:] #makes a copy, two different lists list1[0] = 1 print(list1) print(list1Copy) def menuChoices(): print ("Choose:") print ("1 - call hello (demo strings and argv command lines)") print ("2 - list demo") print ("d - display menu choices") print ("x - exit program") def main(): menuChoices() select = input("Selection: ") while select != "x": if select == "1": hello(False) #hello() without arg will use the default specified in parameter def elif select == "2": listDemos() elif select == "d": menuChoices() select = input("Selection: ") main()
867fcd25f4325f61306ee3c2540981fa3d8653d2
GitLeeRepo/PythonNotes
/basics/tuples_ex1.py
280
3.796875
4
#!/usr/bin/python3 person = ( 'Bill', 'Jones', '(999)999-9999' ) single = ( 'justone', ) # note the trailing comma # assign to individual variables first_name, last_name, phone = person print(person) print(first_name, last_name, phone) print(single) # tuple with one element
1ab70f1a5c8b75a9a72c42b72a9e5121fe6d8f0b
gatinueta/FranksRepo
/python/chess.py
358
3.703125
4
class Board: def __init__(self): self.b = [ [None] * 8 for i in range(8) ] def set(self, c, piece): self.b[c.col][c.row] = piece def __str__(self): s = '' for col in self.b: for row in col: s += str(self.b[col][row]) s += "\n" return s b = Board() print(str(b))
6e6841ad28295804712aa997f1486ecdf2f0db4e
gatinueta/FranksRepo
/python/bodyguards.py
342
3.53125
4
import fileinput import re for line in fileinput.input(): line = '.' + line + '.' ms = re.finditer('[A-Z]{3}[a-z][A-Z]{3}', line) for m in ms: # print(m.group()) print(line[m.start()-1:m.end()+1]) if not line[m.start()-1].isupper() and not line[m.end()].isupper(): print(' : ', m.group())
ae0ea94137c2b1c80943742de3edcee0685099b9
PoroTomato99/Python_Crash_Course
/palindrome.py
249
3.78125
4
message = "abc123" a = "" reversed_a = "" for c in message: print(f"this is => {c}") a = a + c print(f"this is a => {a}") reversed_a = c + reversed_a print(f"this is reversed_a => {reversed_a}") print(a) print(reversed_a)
fcda0d855c24a95ba0b1c667a5d40b536742eafd
xueyinjun/Learn-Python-The-Hard-Way
/ex31.py
1,030
3.859375
4
#encoding =utf-8 print ("You enter a dark room with two doors. Do you go through door #1 or door #2") door = input(">") if door == "1": print("There's a agin bear here eating a cheese cake.What do you do") print("1. Take the cake") print("2.Scream at the beat") bear = input(">") if bear=="1": print("The bear eats your face off. Good job!") elif bear =="2": print("The bear eats your legs off. Good job!") else: print("Well doing %s id probably better. Bear runs away" %(bear)) elif door =="2": print("You stare into the endless abyss at Cthuhu's retina.") print("1. Blueberries.") print("2. Yellow jacker clothespins") print("3.Understanding revolvers yelling melodies") insanity =input(">") if insanity =="1 " or insanity =="2": print("Your body survives powered by a mind of jello.Good job!") else: print("The insanity rots your eyes into a pool of muck Good job!") else: print("You stumble around and fall on a knife and die. Good job!")
40d301b151cbc2b146c2e880539c8aa38e70a3ab
ecastillob/project-euler
/001 - 050/46.py
1,251
3.890625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: """ It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×12 15 = 7 + 2×22 21 = 3 + 2×32 25 = 7 + 2×32 27 = 19 + 2×22 33 = 31 + 2×12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? """ # In[2]: def es_primo_simple(N): es = True extremo = (N // 2)+1 for i in range(3, extremo, 2): if N % i == 0: es = False break return es # In[3]: N = 10000 primos = (2,) + tuple(i for i in range(3, N+1, 2) if es_primo_simple(i)) s = set(primos) len(primos), primos[:10] # In[4]: contador = 0 resultado = -1 for i in range(3, N, 2): if i in s: continue es = False print(i, end="\t") valor = 0 for p in primos: for b in range(1, p): valor = p + 2*(b**2) if valor >= i: break if valor == i: es = True contador += 1 #print(i, "\t", f"{p} + 2x({b}**2)") break if not es: print("\n----") resultado = i break resultado # 5777
0ffe4f4ec06484dd0cfeecee9158c693c5ce24ce
ecastillob/project-euler
/101 - 150/104.py
1,159
3.9375
4
#!/usr/bin/env python # coding: utf-8 # # Problem [104](https://projecteuler.net/problem=104): Pandigital Fibonacci ends # The Fibonacci sequence is defined by the recurrence relation: # # $$ F_n = F_{n−1} + F_{n−2}, \mathrm{where} \ F_1 = 1 \ \mathrm{and} \ F_2 = 1. $$ # # It turns out that $F_{541}$, which contains 113 digits, is the first Fibonacci number for which the last nine digits are 1-9 pandigital (contain all the digits 1 to 9, but not necessarily in order). And $F_{2749}$, which contains 575 digits, is the first Fibonacci number for which the first nine digits are 1-9 pandigital. # # Given that $F_k$ is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find $k$. # In[1]: s = {'1', '2', '3', '4', '5', '6', '7', '8', '9'} s # In[ ]: %%time a = 0 b = 1 k = 1 inicio, final = "", "" while not (s.issubset(inicio) and s.issubset(final)): print(k, end="\t") b = b + a a = b - a valor = str(a) inicio, final = valor[:9], valor[-9:] k += 1 print("") """ 329468 CPU times: user 2h 25min 32s, sys: 44.6 s, total: 2h 26min 17s Wall time: 2h 29min 54s ""
26a820a4654a0ae290874fb48bff92f22ebbfbf6
ecastillob/project-euler
/001 - 050/12.py
4,012
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[5]: def get_divisores(N): divisores = [] for i in range(1,N+1): if N%i==0: divisores.append(i) return divisores # In[6]: get_divisores(28) # In[12]: N = 7 suma = int(N*(N+1)/2) suma # In[18]: def get_cantidad_divisores(N): divisores = 0 for i in range(1,N+1): if N%i==0: divisores += 1 return divisores # In[19]: get_cantidad_divisores(28) # In[16]: N = 0 while True: N += 1 suma = int(N*(N+1)/2) divisores = get_divisores(suma) print (suma, divisores) if len(divisores) > 5: break suma # In[21]: N = 0 while True: N += 1 suma = int(N*(N+1)/2) if get_cantidad_divisores(suma) > 500: break suma """ #include <stdio.h> #include <time.h> int get_cantidad_divisores(int N){ int divisores = 0; int i; for (i=1; i<N+1; i++){ if (N%i==0) divisores++; } return divisores; } int main(){ time_t start,end; double dif; time (&start); int N = 0; // 5 : 28, 0 seg. // 300 : 2162160, 7 seg. // 350 : 17907120, 175 seg. int suma = 0; while (1){ N++; suma = (N*(N+1))/2; if (get_cantidad_divisores(suma) > 5) break; } printf("\n %d", suma); time (&end); dif = difftime (end,start); printf ("\nYour calculations took %.2lf seconds to run.\n", dif ); } """ """ #include <stdio.h> #include <time.h> int get_cantidad_divisores(int N){ int divisores = 0; int i; int extremo = (N/2) + 1; if (N%2 == 0){ for (i=1; i<=extremo; i++){ if (N%i==0){ divisores++; } } } else{ for (i=1; i<=extremo; i+=2){ if (N%i==0){ divisores++; } } } return divisores; } int main(){ time_t start,end; double dif; /* time_t t = time(NULL); struct tm tm = *localtime(&t); printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); */ time_t t; //struct tm; time (&start); // divisores : tiempo // 5 : 28, 0 seg. /* N = 7 suma = 28 */ // 200 : /* LIMITE = 200 N = 2015 suma = 2031120 Your calculations took 4.00 seconds to run. */ /* LIMITE = 250 N = 2079 suma = 2162160 Your calculations took 5.00 seconds to run. */ /* N = 5984 suma = 17907120 Your calculations took 175.00 seconds to run. LIMITE = 350 N = 5984 suma = 17907120 Your calculations took 100.00 seconds to run. */ /* LIMITE = 400 N = 5984 suma = 17907120 Your calculations took 99.00 seconds to run. */ /* LIMITE = 500 N = 12375 divisores = 576 suma = 76576500 // este numero es la respuesta Your calculations took 553.00 seconds to run. */ int N = 0; int suma = 0; int divisores = 0; const int LIMITE = 500; while (divisores <= LIMITE){ N++; suma = (N*(N+1))/2; divisores = get_cantidad_divisores(suma); if (N % 1000 == 0){ t = time(NULL); struct tm tm = *localtime(&t); printf("\n %d-%d-%d %d:%d:%d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); printf("\n N = %d", N); printf("\n divisores = %d", divisores); printf("\n suma = %d", suma); printf("\n"); } } printf("\n LIMITE = %d", LIMITE); printf("\n N = %d", N); printf("\n divisores = %d", divisores); printf("\n suma = %d", suma); printf("\n"); time (&end); dif = difftime (end,start); printf ("\nYour calculations took %.2lf seconds to run.\n", dif ); } """
66d407d714258a6aceea8e800a10ba5994af040a
ecastillob/project-euler
/101 - 150/112.py
1,846
4.40625
4
#!/usr/bin/env python # coding: utf-8 """ Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ # In[1]: def arriba(N): valor = -1 actual = -1 for n_str in str(N): actual = int(n_str) if actual < valor: return False valor = actual return True # In[2]: def abajo(N): valor = 10 actual = 10 for n_str in str(N): actual = int(n_str) if actual > valor: return False valor = actual return True # In[3]: def es_bouncy(N): return not (arriba(N) or abajo(N)) # In[4]: arriba(134468), abajo(66420), es_bouncy(155349) # In[5]: def contar_bouncies(RATIO_LIMITE): contador = 0 ratio = 0 i = 100 while (ratio != RATIO_LIMITE): if es_bouncy(i): contador += 1 ratio = contador / i i += 1 return [contador, i - 1, ratio] # In[6]: contar_bouncies(0.5) # [269, 538, 0.5] # In[7]: contar_bouncies(0.9) # [19602, 21780, 0.9] # In[8]: contar_bouncies(0.99) # [1571130, 1587000, 0.99]
3e99069ad82eed7cd473865c13af5584f2ce9467
ecastillob/project-euler
/051 - 100/56.py
552
3.5
4
""" A googol ($10^{100}$) is a massive number: one followed by one-hundred zeros; $100^{100}$ is almost unimaginably large: one followed by two-hundred zeros. <br> Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the form, $a^b$, where a, b < 100, what is the maximum digital sum? """ maximo = 0 for a in range(1, 100): for b in range(1, 100): n = pow(a, b) suma = sum([int(c) for c in str(n)]) if maximo < suma: maximo = suma maximo # 972
86b37e269f4b6d38ba7c04312c37446a5d690a4f
Qausain/PIAIC-Q-1
/PIAIC 8 If else statements.py
229
3.9375
4
#If statements a= 100 b= 200 if a<b: print("a is less than b") print("Hello A") print("Hello B") print("Help python") if b<a: print("b is less than a") # this block will not be executed print("Pakistan")
3e08723fb5d96d9bb3570cf0157fdf7da1d38428
liujieliewang/Python
/fibs.py
164
3.796875
4
#Python 3.5.2 fibs = [0,1] n = input("请输入求第几位数:") n = int(n) for i in range(n-1): fibs.append(fibs[-1]+fibs[-2]) print(fibs) print(fibs[-1])
28083881cf61c01eecd51f82f8162052ca533e07
shivanand217/some-useful-scripts
/email_crawler.py
400
3.609375
4
import requests import re #url = str(input('Enter a URL: ')) url = 'https://blog.anudeep2011.com/20-by-25/' website = requests.get(url) html = website.text links = re.findall('"((html|ftp)s?://.*?)"', html) emails = re.findall('([\w\.,]+@[\w\.,]+\.\w+)', html) # list print(len(emails)) print("\n Found {} links".format(len(links))) for email in emails: print(email)
0daa2d8b4bcf20bc8ebc25b059e62ef920065d5f
al0fayz/python-playgrounds
/fundamental/14-class.py
467
3.875
4
#example class in python class siswa: #this like constructor in other programming def __init__(self, name, city): #this like this in other language self.name = name self.city = city #create object siswa_object = siswa("bento", "Jakarta") print(siswa_object.name) print(siswa_object.city) #modify object siswa_object.name = "alfa code" print(siswa_object.name) #delete properties del siswa_object.city #delete object del siswa_object
9bb69fee060d1b2704b37388080cc2488b447c0c
al0fayz/python-playgrounds
/mysql/4-select.py
584
3.5
4
import mysql.connector db = mysql.connector.connect( host="localhost", user="root", password="", database="python_example" ) con = db.cursor() con.execute("SELECT * FROM customers") myresult = con.fetchall() for x in myresult: print(x) print("==========================================") # select column con.execute("SELECT name, address FROM customers") myresult = con.fetchall() for x in myresult: print(x) print("==========================================") #get 1 row con.execute("SELECT * FROM customers") myresult = con.fetchone() print(myresult)
6a442bcbc6464c0e325b859b78633111ae48a649
al0fayz/python-playgrounds
/fundamental/1-variabel.py
1,045
4.3125
4
#example variabel in python x = 5 y = 2 kalimat = "hello world" kalimat1 = 'hai all!' print(x) print(y) print(kalimat) print(kalimat1) a , b , c = 1, 2, 3 text1, text2, text3 = "apa", "kabar", "indonesia?" print(a, b, c) print(text1, text2, text3) result1 = result2 = result3 = 80 print(result1, result2, result3) print("your weight is" , result1) #integer print("i like " + text3) #string #example global variabel # this is a global variabel name = "alfa" def test(): # i can call variabel global inside function print("my name is " + name) #call function test() # global variabel can call inside or outside function # example local varibel def coba(): address = "jakarta" #this is local variabel you can call on outside func print(address) # if you want set global varibel inside function you can add global #ex : global bahasa #you must defined first , you can't insert value directly bahasa = "indonesia" print(bahasa) coba() # i try call variabel global print("my language is "+ bahasa)
cfcbe016443d6a8fa6bd958d56d8e49705269b81
al0fayz/python-playgrounds
/fundamental/6-tuples.py
726
4.3125
4
#contoh tuples """ tuples bersifat ordered, tidak bisa berubah, dan dapat duplicate """ contoh = ("satu", "dua", "tiga", "tiga") print(contoh) #acces tuples print(contoh[0]) print(contoh[-1]) print(contoh[1:4]) #loop tuples for x in contoh: print(x) #check if exist if "satu" in contoh: print("yes exist") #length of tuples print(len(contoh)) #kita tidak bisa menghapus element atau menambahkan element pada tuples # tapi kita bisa delete tuples del contoh #delete tuples #join tuples tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3) #tuples constructor untuk membuat tuples thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets print(thistuple)
2eca24e3b6f7fa52f1e1ab9bd8fd20f6d2e46e3d
aaryanredkar/prog4everybody
/project10.py
158
4.25
4
number = int(input("print number:")) for i in range(2,number+1,2): print(i,"is even") for i in range( 1,number+1,2): print (i, "is odd number")
7643854c54690814e2744e3cd80bc02ec02770e1
aaryanredkar/prog4everybody
/L1C2_Fibonacci.py
229
4.28125
4
Value = int(input("Please enter MaxValue for Fibonacci sequence : ")) print ("The fibonacci sequence <=",Value, "is: ") a, b = 0, 1 temp = 0 print ("0 ") while (b <= Value): print (b) temp = a+b a = b b = temp