blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
577fdb87b53af5c288fe1fda17035afaea23d082
boyko11/DinosaurIsland_DLAI
/data_service.py
748
3.515625
4
import pprint class DataService: def __init__(self): pass @staticmethod def get_data(): data = open('data/dinos.txt', 'r').read() data = data.lower() chars = list(set(data)) data_size, vocab_size = len(data), len(chars) print('There are %d total characters and %d unique characters in your data.' % (data_size, vocab_size)) chars = sorted(chars) # print(chars) char_to_ix = {ch: i for i, ch in enumerate(chars)} ix_to_char = {i: ch for i, ch in enumerate(chars)} # pp = pprint.PrettyPrinter(indent=4) # pp.pprint(char_to_ix) # print('-------------') # pp.pprint(ix_to_char) return data, char_to_ix, ix_to_char
917e3de1c9b52fb43d4dc9d89a24b47207e5c6a5
ddddfang/my-exercise
/python/algorithm/data_struct/myQueue.py
837
3.796875
4
class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) #则是在第0个元素前插入item def dequeue(self): return self.items.pop() #self.items.pop(0)则是弹出第0个元素 def size(self): return len(self.items) #约瑟夫环:30人围坐一圈,每隔7人杀掉一个,问最后留下的那个人是谁 #创建一个size=30的queue,每次出队并插入到队尾,到第七个人的时候出队直接丢弃 #双端队列:队列和栈的结合,元素可以从两端进,也可以从两端出,看使用者如何用 #利用双端队列可以解决的问题:回文检测,madam,从左到右依次进队,从两端同时弹出 #相同就继续,直到全部弹出或仅剩一个元素
3208a9ee50249d6958b2388f9f104fca0269f38c
gentle-potato/Python
/Practice/0520(1_김형림)(풀이).py
542
3.890625
4
print('#1') print('1)') for j in range(5, 0, -1) : for i in range(j) : print('*', end = '') # j만큼 *을 옆으로 나열! print() print('\n2)') for y in range(5, 0, -1) : for x in range(y) : print(' ', end = '') for x in range(y) : print('*' * (2 * x - 1), end = '') print('\n========================\n') print('#2') num = int(input('숫자 입력 : ')) while True : if num == 7 : print(num, '입력! 종료') break else : num = int(input('다시 입력 : '))
759d99492aa0af836c5e8c851153be04360e6277
gabriellaec/desoft-analise-exercicios
/backup/user_093/ch38_2020_03_29_17_05_26_511640.py
171
3.5
4
def quantos_uns(n): soma=0 a=0 numerostr=str(n) while a<len(numerostr): if numerostr[a]=='1': soma=soma+1 a=a+1 return soma
dc5f40044f303fe41e86b47023b1c3287735f195
mdAshrafuddin/python
/p_code/break_continue.py
339
4
4
for i in range(2, 10): for n in range(2, i): if i % n == 0: print(i, "Equals", n, '*', i // n) break else: print(i, 'is prime number') for i in range(2, 10): if i % 2 == 0: print(i, "prime number") continue else: print(i, 'odd number')
399b145823f478bcf6fc7e74157b3d4f35e2a298
moncada92/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/tests/test_square.py
9,430
3.5
4
#!/usr/bin/python3 """Unittest for class Square """ import io import sys import unittest from models.square import Square from models.base import Base class Testsquare(unittest.TestCase): """test for class square""" def test_init(self): Base._Base__nb_objects = 0 def test_validate_0(self): "Cases 0" rect0 = Square(1, 2) rect1 = Square(3, 2) self.assertEqual(rect0.id, 1) self.assertEqual(rect1.id, 2) def test_validate_1(self): "Cases 1" rect = Square(1, 3) self.assertIsInstance(rect, Square, True) def test_validate_2(self): "Cases 2" rect = Square(1) self.assertEqual(rect.width, 1) self.assertEqual(rect.height, 1) self.assertEqual(rect.x, 0) self.assertEqual(rect.y, 0) rect_1 = Square(1, 2, 4) self.assertEqual(rect_1.width, 1) self.assertEqual(rect_1.height, 1) self.assertEqual(rect_1.x, 2) self.assertEqual(rect_1.y, 4) def test_validate_3(self): "Cases 3" self.assertRaises(TypeError, Square, "2") self.assertRaises(TypeError, Square, "hola") def test_validate_4(self): "Cases 4" self.assertRaises(TypeError, Square, "2.5") self.assertRaises(TypeError, Square, "4.5") def test_validate_5(self): "Cases 5" self.assertRaises(ValueError, Square, -2) self.assertRaises(ValueError, Square, 0) def test_validate_6(self): "Cases 6" self.assertRaises(ValueError, Square, 2, 4, -1) self.assertRaises(ValueError, Square, 2, -1, 2,) def test_validate_7(self): "Cases 7" self.assertRaises(TypeError, Square, 3, 4, "b") self.assertRaises(TypeError, Square, 2, "c", 6) def test_validate_8(self): "Cases 8" self.assertRaises(TypeError, Square, [2]) self.assertRaises(TypeError, Square, ['hello']) def test_validate_9(self): "Cases 9" self.assertRaises(TypeError, Square, (2, 4)) self.assertRaises(TypeError, Square, ('2', '4')) def test_validate_10(self): "Cases 10" self.assertRaises(TypeError, Square, {'size': 5}) self.assertRaises(TypeError, Square, {'size': 'dos'}) def test_validate_11(self): "Cases 11" self.assertRaises(TypeError, Square, 5.6) self.assertRaises(TypeError, Square, 4.5) def test_validate_12(self): "Cases 12" self.assertRaises(TypeError, Square, 6, 5, [2]) self.assertRaises(TypeError, Square, 4, [3], 8) def test_validate_13(self): "Cases 13" self.assertRaises(TypeError, Square, 6, (2, 4), 4) self.assertRaises(TypeError, Square, 6, 5, (2, 4)) def test_validate_14(self): "Cases 14" self.assertRaises(TypeError, Square, 6, {'x': 5}, 4) self.assertRaises(TypeError, Square, 6, 5, {'y': 5}) def test_validate_15(self): "Cases 15" self.assertRaises(TypeError, Square, 6, 5.6, 4) self.assertRaises(TypeError, Square, 6, 2, 4.5) def test_Square16(self): "Cases 16" r = Square(24) self.assertEqual(r.size, 24) self.assertEqual(r.x, 0) self.assertEqual(r.y, 0) def test_validate_17(self): "Case 17" with self.assertRaises(TypeError) as e: s = Square(None) self.assertEqual( "width must be an integer", str(e.exception)) def test_validate_19(self): """Case 19""" rect = Square(2) self.assertEqual(rect.area(), 4) def test_validate_20(self): """Case 20""" r = Square(5) r.update(12) self.assertEqual(r.__str__(), "[Square] (12) 0/0 - 5") r.update(1, 2) self.assertEqual(r.__str__(), "[Square] (1) 0/0 - 2") r.update(1, 2, 3) self.assertEqual(r.__str__(), "[Square] (1) 3/0 - 2") r.update(1, 2, 3, 4) self.assertEqual(r.__str__(), "[Square] (1) 3/4 - 2") r = Square(1, 1) r.update(76, 2, 3, 4) self.assertEqual(r.__str__(), "[Square] (76) 3/4 - 2") def test_validate_21(self): """Case 21""" r = Square(10, 10, 10, 1) r.update(size=12) self.assertEqual(r.__str__(), "[Square] (1) 10/10 - 12") r.update(y=12, x=2) self.assertEqual(r.__str__(), "[Square] (1) 2/12 - 12") r.update(y=1, size=2, x=3, id=2) self.assertEqual(r.__str__(), "[Square] (2) 3/1 - 2") def test_validate_22(self): """Case 22""" r = Square(1, 2, 3, 4) r.update() self.assertEqual(r.__str__(), "[Square] (4) 2/3 - 1") def test_validate_23(self): """Case 23""" r1 = Square(10, 2, 1, 9) r2 = {'id': 9, 'x': 2, 'size': 10, 'y': 1} r3 = r1.to_dictionary() self.assertEqual(r2, r3) def test_validate_24(self): s1 = Square(12, 12, 2) s2 = Square(2, 4) Square.save_to_file([s1, s2]) res = '[{"x": 12, "y": 2, "id": 21, "size": 12},' + \ ' {"x": 4, "y": 0, "id": 22, "size": 2}]' with open("Square.json", "r") as file: self.assertEqual(len(file.read()), len(res)) def test_validate_25(self): s1 = Square(3, 5, 1) s1_dictionary = s1.to_dictionary() s2 = Square.create(**s1_dictionary) self.assertEqual((s1 == s2), False) self.assertEqual((s1 is s2), False) def test_validate_26(self): Square.save_to_file(None) with open("Square.json", "r") as file: self.assertEqual(len(file.read()), 2) def test_validate_27(self): Square.save_to_file([]) with open("Square.json", "r") as file: self.assertEqual(file.read(), '[]') e = [] Square.save_to_file(e) with open("Square.json", "r") as file: self.assertEqual(file.read(), '[]') def test_validate_28(self): with self.assertRaises(TypeError) as e: s = Square() self.assertEqual( "__init__() missing 1 required positional argument: 'size'", str(e.exception)) def test_validate_29(self): s = Square(6, 0) self.assertEqual(s.x, 0) with self.assertRaises(ValueError) as e: s = Square(0, 2) self.assertEqual( "width must be > 0", str(e.exception)) s = Square(1, 0, 0, 0) self.assertEqual(s.x, 0) self.assertEqual(s.y, 0) self.assertEqual(s.id, 0) def test_validate_30(self): s = Square(4, 2) self.assertEqual(s.area(), 16) s = Square(2, 20, 1) self.assertEqual(s.area(), 4) s = Square(10, 5, 6, 2) self.assertEqual(s.area(), 100) s = Square(12, 7, 4, 6) self.assertEqual(s.area(), 144) def test_validate_31(self): s = Square(3, 7, 1, 1) self.assertEqual(s.__str__(), "[Square] (1) 7/1 - 3") s = Square(1, 1, 0) self.assertEqual(s.__str__(), "[Square] (32) 1/0 - 1") s = Square(1, 1) self.assertEqual(s.__str__(), "[Square] (33) 1/0 - 1") def test_validate_32(self): r = Square(5) self.assertEqual(r.size, 5) r.size = 25 self.assertEqual(r.size, 25) with self.assertRaises(TypeError) as e: r.size = "hello" self.assertEqual( "width must be an integer", str(e.exception)) with self.assertRaises(TypeError) as e: r.size = [1, 2] self.assertEqual( "width must be an integer", str(e.exception)) with self.assertRaises(TypeError) as e: r.size = (2,) self.assertEqual( "width must be an integer", str(e.exception)) with self.assertRaises(TypeError) as e: r.size = {"a": 1} self.assertEqual( "width must be an integer", str(e.exception)) with self.assertRaises(TypeError) as e: r.size = True self.assertEqual( "width must be an integer", str(e.exception)) with self.assertRaises(TypeError) as e: r.size = {1, 2} self.assertEqual( "width must be an integer", str(e.exception)) def test_validate_33(self): s = Square(12, 2, 1, 9) s_dict = {'x': 2, 'size': 12, 'y': 1, 'id': 9} self.assertEqual(s.to_dictionary(), s_dict) self.assertEqual(s.to_dictionary() is s_dict, False) s = Square(12, 4, 15) s_dict = {'x': 4, 'id': 35, 'y': 15, 'size': 12} self.assertEqual(s.to_dictionary(), s_dict) self.assertEqual(s.to_dictionary() is s_dict, False) s = Square(96, 313) s_dict = {'x': 313, 'id': 36, 'y': 0, 'size': 96} self.assertEqual(s.to_dictionary(), s_dict) self.assertEqual(s.to_dictionary() is s_dict, False) def test_validate_34(self): r = Square(12, 12, 2) d = r.to_dictionary() json_d = Base.to_json_string([d]) self.assertEqual(type(json_d), str) self.assertEqual(d, {'id': 37, 'x': 12, 'y': 2, 'size': 12}) def test_validate_35(self): Square.save_to_file(None) with open("Square.json", "r") as file: self.assertEqual(len(file.read()), 2)
458fa126307bcc39d01309fcf9f1349c4b17a914
leobalestra/pyhton-aulas-alura
/AulasPython/Conta.py
973
3.734375
4
class Conta: def __init__(self, codigo): self._codigo = codigo self._saldo = 0 def deposita(self, valor): self._saldo += valor def __str__(self): return (f"Código: {self._codigo} saldo: {self._saldo}") #herança class Corrente(Conta): def passa_um_mes(self): self._saldo -= 2 class Poupanca(Conta): def passa_um_mes(self): self._saldo *= 1.01 self._saldo -= 3 conta1 = Corrente(1) conta1.deposita(1000) conta1.passa_um_mes() print(conta1) conta2 = Poupanca(2) conta2.deposita(1000) conta2.passa_um_mes() print(conta2) conta1 = Corrente(1) conta1.deposita(1000) conta1.passa_um_mes() print(conta1) conta2 = Poupanca(2) conta2.deposita(1000) conta2.passa_um_mes() #evitaremos usa o array import array as arr arr.array('d', [1, 3.5]) print(arr.array('d', [1, 3.5])) print(type(arr.array('d', [1, 3.5]))) import numpy as np numeros = np.array([1, 3.5]) print(numeros) print(numeros + 3)
d6238c93d9cf693cdc16fe70da1aa7dfba24f883
Pallavi2000/adobe-training
/day1/p2.py
315
4.28125
4
#Find smallest digit in a number number = int(input("Enter a number ")) temp = number smallest = None while number != 0: remainder = number % 10 number //= 10 if smallest == None or remainder < smallest: smallest = remainder print("The smallest digit of the given number",temp,"is",smallest)
2c2c2a5993d8109540580db4e60ff6d8921e8d5b
stevengonsalvez/python_training
/04_ListsTuplesDictionariesAndSets/Exercises_SourceCode/primes_alt_A.py
1,352
3.796875
4
# -*- coding:utf-8; -*- '''A module providing some functions generating prime numbers.''' __author__ = 'Russel Winder' __date__ = '2014-03-23' __version__ = '1.4' __copyright__ = 'Copyright © 2007, 2012–2014 Russel Winder' __licence__ = 'GNU Public Licence (GPL) v3' def _addIfPrime(primes, value): for p in primes: if value % p == 0: break else: primes.append(value) def primesLessThan(maximum): '''Return a tuple containing the primes less than maximum in ascending order.''' if maximum <= 2: return () primes = [2] for i in range(3, maximum, 2): _addIfPrime(primes, i) return tuple(primes) def firstNPrimes(count): '''Return a tuple containing the first count primes in ascending order''' if count < 1: return () primes = [2] value = 3 while len(primes) < count: _addIfPrime(primes, value) value += 2 return tuple(primes) def sieveOfEratosthenes(maximum): '''Return a tuple containing the primes less than maximum in ascending order.''' if maximum < 2: return () sieve = [False] * 2 + [True] * (maximum - 2) for i in range(2, int(maximum ** 0.5) + 1): if sieve[i]: sieve[i * i: maximum: i] = [False] * (1 + (maximum - 1) // i - i) return tuple(i for i, v in enumerate(sieve) if v)
fd5b9ea35cb573c92c41ad98075f155836495b48
shannonmlance/leetcode
/learning/arrayAndString/conclusion/rotateArray.py
1,579
3.9375
4
# Given an array, rotate the array to the right by k steps, where k is non-negative. # Follow up: # Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. # Could you do it in-place with O(1) extra space? # Example 1: # Input: nums = [1,2,3,4,5,6,7], k = 3 # Output: [5,6,7,1,2,3,4] # Explanation: # rotate 1 steps to the right: [7,1,2,3,4,5,6] # rotate 2 steps to the right: [6,7,1,2,3,4,5] # rotate 3 steps to the right: [5,6,7,1,2,3,4] # Example 2: # Input: nums = [-1,-100,3,99], k = 2 # Output: [3,99,-1,-100] # Explanation: # rotate 1 steps to the right: [99,-1,-100,3] # rotate 2 steps to the right: [3,99,-1,-100] # Constraints: # 1 <= nums.length <= 2 * 10^4 # -2^31 <= nums[i] <= 2^31 - 1 # 0 <= k <= 10^5 class Solution: def rotate(self, nums, k): # quick exit for if the given array contains only one value if len(nums) == 1: return nums # repeat as long as the given rotation number is bigger than the length of the given array while k >= len(nums): # subtract the length of the given array from the given rotation number k -= len(nums) # repeat as many times as the rotation number for i in range(k): # remove the last value from the given array and store it in a variable x = nums.pop() # insert the value stored in the variable at the beginning of the given array nums.insert(0, x) return nums = [1,2,3,4,5,6,7] k = 4 s = Solution() s.rotate(nums, k) print(nums)
d424ecb5191e405b65ce2f28683a1b7e219fa7b4
jerrylance/LeetCode
/771.Jewels and Stones/771.Jewels and Stones.py
866
3.53125
4
# LeetCode Solution # Zeyu Liu # 2019.4.3 # 771.Jewels and Stones from typing import List # method 1 常规法 class Solution: def numJewelsInStones(self, J: str, S: str) -> int: count = 0 for i in S: if i in J: count += 1 return count # transfer method solve = Solution() print(solve.numJewelsInStones("aA", "aAAbbbb")) # method 2 count() class Solution: def numJewelsInStones(self, J: str, S: str) -> int: count = 0 for i in J: count += S.count(i) return count # transfer method solve = Solution() print(solve.numJewelsInStones("aA", "aAAbbbb")) # method 3 Oneline class Solution: def numJewelsInStones(self, J: str, S: str) -> int: return sum(map(J.count,S)) # transfer method solve = Solution() print(solve.numJewelsInStones("aA", "aAAbbbb"))
0df9e10663d0c3b4488df0a1be737b628d073756
gzweigle/deep_learning_feedforward
/backpropagate.py
909
3.71875
4
""" Standard backpropagation algorithm. """ # # by Greg C. Zweigle # import numpy as np import nonlinearities as nl def backpropagate(output_vs_correct, a_matrix, linear_output, dropout, parameters): """ Compute the change in cost vs output for each layer and return as delta. """ delta = [np.empty((k, parameters.minibatch_size)) for k in parameters.layers[1:]] last_layer_index = len(parameters.layers) - 2 # The last-stage nonlinearity, and associated cost metric is either: # sigmoid + cross entropy, or # softmax + log likelihood. # In both cases, mathematically the first delta term is the same. delta[last_layer_index] = output_vs_correct for k in reversed(range(last_layer_index)): delta[k] = (a_matrix[k+1].transpose().dot(delta[k+1]) * nl.rlu_derivative(linear_output[k], dropout[k])) return delta
b952b06627402f623c4633aa20a5a9b34d13c486
Mujju-palaan/Flask01
/section2/31)decorators.py
306
3.546875
4
import functools def my_decorator(func): @functools.wraps(func) def fuction_that_runs_func(): print("In the decorator! ") func() print("After the decorator! ") return fuction_that_runs_func @my_decorator def my_function(): print("I'm the function!") my_function()
67d284f87e237fdc4928998d2c94922c7deb5a84
palandesupriya/python
/basic/control flow/sum_odd.py
427
4.09375
4
''' WAP to find sum of all odd numbers in the given range. ''' def IsOdd(iNum): if (0 != iNum & 1): return True return False def main(): iStart = input("Enter start num:") iEnd = input("Enter end num:") if (iStart < iEnd): iSum = 0 for iTemp in range(iStart, iEnd + 1): if (IsOdd(iTemp)): iSum += iTemp print ("Sum of all odd numbers: {}".format(iSum)) if __name__ == '__main__': main()
f00b9d9ec9eab5debf6813b7598f10b2ea54c6ca
rosepcaldas/Cursoemvideo
/ex027.py
338
3.875
4
# Programa que leia o nome da pessoa e , mostrando em # seguida o primeiro e o último nome separadamente. # Ex. Ana Maria de Souza # primeiro = Ana # Último = Souza nome = str(input('Nome completo: ')).strip() nome1 = nome.split() n = len(nome1) #print(n) print('Primeiro nome: {}'.format(nome1[0])) print('Último nome : {}'.format(nome1[n-1]))
3ffbe91af56fcd941a0bfaa243d64eeb44e5f1d3
YingXie24/Python
/Fundamental-Python/2-DNA-Processing/DnaProcessing.py
3,133
4.28125
4
def get_length(dna): """ (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 """ return len(dna) def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence dna2. >>> is_longer('ATCG', 'AT') True >>> is_longer('ATCG', 'ATCGGA') False """ return len(dna1)>len(dna2) def count_nucleotides(dna, nucleotide): """ (str, str) -> int Return the number of occurrences of nucleotide in the DNA sequence dna. >>> count_nucleotides('ATCGGC', 'G') 2 >>> count_nucleotides('ATCTA', 'G') 0 """ num_nucleotides = 0 for char in dna: if char in nucleotide: num_nucleotides = num_nucleotides + 1 return num_nucleotides def contains_sequence(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna2 occurs in the DNA sequence dna1. >>> contains_sequence('ATCGGC', 'GG') True >>> contains_sequence('ATCGGC', 'GT') False """ return dna2 in dna1 def is_valid_sequence(dna): """ (str)-> bool Return True if and only if the dna sequence is valid. That is, it contains no other characters other than 'A', 'T', 'G', 'C'. >>>is_valid_sequence('ATCGTCA') True >>>is_valid_sequence('ABTGT') False """ ## for char in dna: ## if char in "ATCG": ## a = 1 ## else: ## return False ## ## return True num_invalid_nucleotide = 0 for char in dna: if char not in "ATCG": num_invalid_nucleotide = num_invalid_nucleotide + 1 return num_invalid_nucleotide == 0 def insert_sequence(dna1,dna2,index): """(str,str,int)-> str Return the dna sequence obtained by inserting dna2 into dna1 at the given index. >>>insert_sequence('CCGG','AT',2) 'CCATGG' >>>insert_sequence('CCGG','AT',0) 'ATCCGG' >>>insert_sequence('CCGG','AT',len('CCGG')) 'CCGGAT' """ new_dna = dna1[:index] + dna2 + dna1[index:] return new_dna def get_complement(nucleotide): """ (str)-> str Return the nucleotide's complement. >>>get_complement('A') 'T' >>>get_complement('C') 'G' """ if nucleotide == 'A': return 'T' if nucleotide == 'T': return 'A' if nucleotide == 'C': return 'G' if nucleotide == 'G': return 'C' def get_complementary_sequence(dna): """ (str) -> str >>>get_complementary_sequence('AT') 'TA' >>>get_complementary_sequence('TCAG') 'AGTC' """ complementary_sequence = '' for char in dna: if char in 'ATCG': get_complement(char) complementary_sequence = complementary_sequence + get_complement(char) return complementary_sequence
1fb54145c39dca65da1df34a2d74de12c2e44290
desha19/python_basics
/task_06/lesson_02.py
1,464
3.546875
4
# Реализовать класс Road (дорога), в котором определить атрибуты: # length (длина), width (ширина). Значения данных атрибутов должны передаваться # при создании экземпляра класса. Атрибуты сделать защищенными. # Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. # Использовать формулу: длина*ширина*масса асфальта для покрытия одного кв метра дороги асфальтом, # толщиной в 1 см*число см толщины полотна. Проверить работу метода. # Например: 20м*5000м*25кг*5см = 12500 т class Road: WEIGHT1M2 = 25 # кг/см - вес одного квадратного метра толщиной в 1 см def __init__(self, length, width): self._length = length self._width = width def weight(self, depth): return depth * self.WEIGHT1M2 * self._width * self._length @property def width(self): return self._width if __name__ == '__main__': road_Saratov_Piter = Road(1500, 20) print(road_Saratov_Piter.weight(5)) print(road_Saratov_Piter._length) print(road_Saratov_Piter.width)
e496578b3d9315d1e8384348b696dd6ba06afb12
xiang525/leetcode_2018
/python/53.maximum_subarray.py
4,295
3.53125
4
# 一下解法不是最好的, 估计有些测试是通不过的 # Negative value cannot be border: This method is based on such a fact that the negative # value cannot be the border element in the maximum subarray, since you remove the # negative border out, the sum obviously get larger. So we can scan the array from # left to right and keep a current sum over the scanned elements. If the current sum # become negative, we set it as zero, if the sum is larger than the global maximum sum, # We update the maximum sum. To some extent, this is also could be interpreted as DP # approach. class Solution: # @param {integer[]} nums # @return {integer} def maxSubArray(self, nums): current_sum = 0 max_sum = -10000 for i in range(len(nums)): if current_sum < 0: current_sum = 0 current_sum += nums[i] max_sum = max(max_sum,current_sum) return max_sum """ # ********** The Second Time ********** # O(n)的解法 # http://tech-wonderland.net/blog/leetcode-maximum-subarray.html """ class Solution: # @param {integer[]} nums # @return {integer} def maxSubArray(self, A): if len(A) == 0: return 0 temp = 0 maxSum = A[0] for i in range(len(A)): temp = max(A[i],A[i]+temp) # 精华在此是一种动态规划的思想 if temp > maxSum: maxSum = temp return maxSum """ 题目要求的算法: # O(nlogn): Divide and Conquer: divide the array into left and right part, # recursively find the maximum sub array in the left and right parts. # The third candidate is the subarray cross the mid element (could be calculated in # linear time). Then we compare these three result, return the maximum one. # The time is T(N) = 2*T(N/2) + O(N), by master’s theroy the time complexity is O(NlogN). """ class Solution: # @param {integer[]} nums # @return {integer} def maxSubArray(self, nums): return self.maxSubArrayHelper(nums, 0, len(nums) - 1) def maxSubArrayHelper(self, nums, l, r): if l > r: return -2147483647 #m = l + (r - l) / 2 m = (l+r)/2 leftMax = sumNum = 0 for i in range(m - 1, l - 1, -1): sumNum += nums[i] leftMax = max(leftMax, sumNum) rightMax = sumNum = 0 for i in range(m + 1, r + 1): sumNum += nums[i] rightMax = max(rightMax, sumNum) leftAns = self.maxSubArrayHelper(nums, l, m - 1) rightAns = self.maxSubArrayHelper(nums, m + 1, r) return max(leftMax + nums[m] + rightMax, max(leftAns, rightAns)) """ 以下算法不能通过, 是边界问题, 至今没搞明白边界问题 """ class Solution: # @param {integer[]} nums # @return {integer} def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ self.helper(nums,0,len(nums)) def helper(self,nums,left,right): if left > right:return -(1<<32) m = (left + right)/2 leftMax = sums = 0 for i in range(left,m): sums+= nums[i] leftMax = max(leftMax,sums) rightMax = sums = 0 for i in range(m+1,right): sums += nums[i] rightMax = max(rightMax,sums) lm = self.helper(nums,left,m) rm = self.helper(nums,m+1,right) return max(lm,rm,lm+nums[m]+rm) """ 九章solution:prefix sum """ class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if not nums:return 0 max_value = -999;sums = 0; min_value = 0 for i in range(len(nums)): sums += nums[i] max_value = max(max_value,sums-min_value) min_value = min(min_value,sums) return max_value """ DP solution """ class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) dp = [0] * n dp[0] = nums[0] for i in range(1, n): dp[i] = max(dp[i-1] + nums[i], nums[i]) # key is here return max(dp)
4b5dcde1e408b4fe6df63324fed25a86b9df17d7
Zinko17/FP
/new2.py
673
3.765625
4
# numbers = [1,2,3,4,5,6,7] # # for i in range(1,100): # print(i) # numbers = ['red','yellow', 'green', 'blue'] # for i in range(0,len(numbers),2): # print(numbers[i]) # for i in range(0,1000,2): # print(i) # import random # random_numbers = random.sample(range(1,30),20) # print(random_numbers) # for i in random_numbers: # if i % 2 == 0: # print(i) # random_numbers = [1, 2, [1, 2, 3], 3, 4] # sum = 0 # nested_sum = 0 # for i in random_numbers: # if isinstance(i, int) or isinstance(i, float): # sum += i # elif isinstance(i, list): # for j in i: # nested_sum += j # # print(sum + nested_sum)
fb8270402074fdde424cc11bd0669f6961313822
lukaschoebel/LUMOS
/code/python_scripts/trie.py
1,620
4
4
class Trie(object): """ Trie implementation in python """ def __init__(self, ): """ So we use a dictionary at each level to represent a level in the hashmap the key of the hashmap is the character and the value is another hashmap """ self.node = {} def add(self, str): """ Takes a str and splits it character wise Arguments: - 'str': The string to be stored in the trie """ node = self.node for letter in str: # Hashmap: Lookup is O(1) if letter in node: node = node[letter] else: node[letter] = {} node = node[letter] def search(self, str) -> bool: node = self.node print(f'this is node: {node}') for letter in str: if letter in node: node = node[letter] else: return False return True def find_gcd(self) -> str: node = self.node gcd = '' for key, value in node.items(): print(f"key: {key} - value: {value}") node = node[key] # gcd += node[key] #for letter in return 'gcd' class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: trie = Trie() trie.add(str1) trie.add(str2) return trie.find_gcd() if __name__ == '__main__': sol = Solution() print(sol.gcdOfStrings('AB', 'ABAB')) # print(sol.gcdOfStrings('ABC', 'ABAB')) print(sol.gcdOfStrings('LEET', 'CODE'))
9e7fa1227ec7ad19eac2ca763672ab57efbc98d6
I-will-miss-you/CodePython
/Curso em Video/Exercicios/ex044.py
1,243
3.953125
4
''' Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento: - À vista dinheiro / cheque: 10% de desconto - À vista no cartão: 5% de desconto - em até 2x no cartão: preço normal - 3x ou mais no cartão: 20% de juros ''' print(f"{ ' LOJAS GUANABARA ' :=^40}") preço = float(input('\nPreço das compras: R$')) print(''' FORMAS DE PAGAMENTO [ 1 ] à vista dinheiro/ cheque [ 2 ] à vista cartão [ 3 ] 2x no cartão [ 4 ] 3x ou mais no cartão ''') opção = int(input('Qual é a opção: ')) erro = False if opção == 1: total = preço - (preço * 0.10) elif opção == 2: total = preço - (preço * 0.005) elif opção == 3: total = preço parcela = total / 2 print(f'Sua compra será parcelada em 2x de R${parcela:.2f}') elif opção == 4: total = preço + (preço * 0.20) totparc = int(input('Quantas parcelas? ')) parcela = total / totparc print(f'Sua compra será parcelada em {totparc}x de R${parcela:.2f}') else: total = 0 print('Opção Inválida de pagamento. Tente novamente.') erro = True if not erro: print(f'Sua compra de R${preço:.2f} vai custar R${total:.2f}.')
32623d0878bdfea9696c08b3d4a5332aa305d02f
anzelpwj/git_PDLA2019
/instruments/force_sensors_code.py
2,018
3.640625
4
"""Some basic routines for working with the force sensors.""" import numpy as np import matplotlib.pyplot as plt from scipy.stats import linregress from scipy.interpolate import CubicSpline import sys from calibrations import force_sensors as FORCE_SENSORS def plot_force_sensor(sensor_id): """Generates a plot of the force/voltage response curve for a force sensor. Inputs: sensor_id (str): Serial number of force sensor. """ try: data = FORCE_SENSORS[sensor_id] except: raise ValueError( "Unknown sensor ID %s provided, available sensors in calibrations.py" % sensor_id) forces = np.array(data['forces']) voltages = np.array(data['voltages']) slope, _, _, _, _ = linregress(voltages, forces) spline_y = np.linspace(0, max(voltages)) spline_x = get_force_for_voltage(spline_y, sensor_id) plt.figure(figsize=(5, 5), dpi=150) plt.scatter(forces, 1000*voltages, color='k', marker='o') plt.plot(spline_x, 1000*spline_y, color='k', linewidth=2, linestyle="--") plt.title("Sensor {device}, {factor:.2e} N/V".format(device=sensor_id, factor=slope), fontsize=16) plt.xlabel("Force [N]", fontsize=16) plt.ylabel("Voltage [mV]", fontsize=16) plt.tight_layout() plt.show() def get_force_for_voltage(voltages, sensor_id): """Gets the force for a given voltage with a particular device. Uses cubic interpolation. Inputs: voltage (float or float array): Voltage response. sensor_id (str): Device serial number. Outputs: force (float or float array): Estimated force. """ try: data = FORCE_SENSORS[sensor_id] except: raise ValueError( "Unknown sensor ID %s provided, available sensors in calibrations.py" % sensor_id) spline = CubicSpline(data['voltages'], data['forces'], bc_type='not-a-knot') return spline(voltages) if __name__ == '__main__': sensor = sys.argv[1] plot_force_sensor(sensor)
22efcaee4fd0eda845c98a8d44882cd2d6221add
jefinpaul/codes_useful_forme
/datacamp.py
1,947
4.3125
4
# Dictionary of dictionaries europe = { 'spain': { 'capital':'madrid', 'population':46.77 }, 'france': { 'capital':'paris', 'population':66.03 }, 'germany': { 'capital':'berlin', 'population':80.62 }, 'norway': { 'capital':'oslo', 'population':5.084 } } # Print out the capital of France print(europe['france']) # Create sub-dictionary data data={'population': 59.83,'capital': 'rome'} # Add data to europe under key 'italy' europe['italy']= data # Print europe print(europe) ################################################################################################ Use Boolean conditions to subset for rows in 2010 and 2011, and print the results. Set the index to the date column. Use .loc[] to subset for rows in 2010 and 2011. Use .loc[] to subset for rows from Aug 2010 to Feb 2011. # Use Boolean conditions to subset temperatures for rows in 2010 and 2011 print(temperatures[(temperatures["date"] >= "2010") & (temperatures["date"] < "2012")]) # Set date as an index temperatures_ind = temperatures.set_index("date") # Use .loc[] to subset temperatures_ind for rows in 2010 and 2011 print(temperatures_ind.loc["2010":"2011"]) # Use .loc[] to subset temperatures_ind for rows from Aug 2010 to Feb 2011 print(temperatures_ind.loc["2010-08":"2011-02"]) ######################################################################################## Add a year column to temperatures, from the year component of the date column. Make a pivot table of the avg_temp_c column, with country and city as rows, and year as columns. Assign to temp_by_country_city_vs_year, and look at the result. # Add a year column to temperatures temperatures["year"] = temperatures["date"].dt.year # Pivot avg_temp_c by country and city vs year temp_by_country_city_vs_year = temperatures.pivot_table("avg_temp_c", index = ["country", "city"], columns = "year") # See the result print(temp_by_country_city_vs_year)
5bd572d718dd03673806fd86e929fd094d9f15cb
7708653907/guvi5
/loop6.py
118
4
4
even number 1to n n=int(input("Enter even number")) sum=0 for i in range(1,n): if(i%2==0): sum=sum+i print(sum)
6ad656dbb57f88952e3f348bcda18bb7b7f96f3c
kpbroz/Python-Application-Programming
/Module-4/modifiedRectangle.py
524
4.0625
4
#return a modified rectangle import copy class point: """ created a class point""" class rectangle: """created a class rectangle""" def move_rectangle(rect,dx,dy): new=copy.deepcopy(rect) new.corner.x+=dx new.corner.y+=dy return new box=rectangle() box.width=100 box.height=200 box.corner=point() box.corner.x=0 box.corner.y=0 box2=move_rectangle(box,50,75) print(box.corner.x,box2.corner.x) print(box.corner.y,box2.corner.y) print(box.width,box2.width) print(box.height,box2.height)
a2c7c27fac92e6abfde2ef858295a56349a8af74
swayamsaikar/Drink-Water-Notification-System-Python
/main.py
703
3.796875
4
# This program will notify you every hour to drink water import time from plyer import notification if __name__ == '__main__': while True: notification.notify( title="** Please Drink Water! **", message="Do you know ? The U.S. National Academies of Sciences, Engineering, and Medicine determined that an adequate daily fluid intake is: About 15.5 cups (3.7 liters) of fluids a day for men. About 11.5 cups (2.7 liters) of fluids a day for women.", app_icon="C:\\Users\\LENOVO\\Desktop\\DrinkWaterNotificationProgram\\app.ico", ) time.sleep(60*60) # run pythonw ./main.py command to run for the whole time in your computer
2bae19cbde22da99e48120b9c68e95975c29fdb9
javauniversal/exercism
/python/anagram/anagram.py
840
4.21875
4
def find_anagrams(string, array): letter_dict = {} # dictionary with each character of the given string and it's occurrence compare_dict = {} # dictionary which gets compared to letter_dict for each word in given candidates anagrams = [] # the valid candidates to return for char in string.lower(): if char not in letter_dict: letter_dict[char] = 0 elif char in letter_dict: letter_dict[char] += 1 for word in array: for char in word.lower(): if char not in compare_dict: compare_dict[char] = 0 elif char in letter_dict: compare_dict[char] += 1 if letter_dict == compare_dict and word.lower() != string.lower(): anagrams.append(word) compare_dict = {} return anagrams
af5740ad57c7375394371f4f88e3073348981c82
ResearchInMotion/CloudForce-Python-
/UnboxQuestions/C-1.py
330
3.890625
4
String="Krishna is the only god \n and i confirm that \t which actually no need to prove" space=0 tabs=0 newline=0 for character in String: if (character ==" "): space += 1 elif (character == '\t'): tabs += 1 elif (character == '\n'): newline += 1 print(space) print(tabs) print(newline)
5c734bff85e9160fc4a931bca70cac30645ed92c
EmanuelaMollova/MailList
/mail_list_tests.py
3,064
3.546875
4
import unittest import mail_list class MailListTest(unittest.TestCase): def setUp(self): self.m1 = mail_list.MailList() self.m = mail_list.MailList() self.m.register = { 1: "HackFMI", 2: "FMI"} self.m.mail_list = {"HackFMI" : [["Rado", "radorado@fmi.com"], ], "FMI": [ ["Rado", "radorado@fmi.com"], ["Ico", "icoico@fmi.com"]]} def test_create(self): self.assertEqual("New list <HackBG> was created", self.m1.create("HackBG")) self.assertEqual("HackBG", self.m1.register[1]) self.assertEqual([], self.m1.mail_list["HackBG"]) self.assertEqual("A mail list with this name already exists!", self.m1.create("HackBG")) def test_add_name_email(self): self.assertEqual("Ivaylo <ivo@hackfmi.com> was added to HackFMI", self.m.add_name_email("Ivaylo", "ivo@hackfmi.com", 1)) def test_show_list(self): self.m.add_name_email("Ivaylo", "ivo@hackfmi.com", 1) self.assertEqual("Rado - radorado@fmi.com\nIvaylo - ivo@hackfmi.com\n", self.m.show_list(1)) def test_show_lists(self): self.assertEqual("[1] HackFMI/n[2] FMI", self.m.show_lists_second()) def test_search_unregistered_email(self): self.assertEqual("<anton@antonov.com> was not found in the current mailing lists.", self.m.search_email("anton@antonov.com")) def test_serch_email(self): self.assertEqual("<radorado@fmi.com> was found in:/n[1] HackFMI/n[2] FMI", self.m.search_email("radorado@fmi.com")) def test_is_email_in_mail_list(self): self.assertTrue(self.m.is_email_in_mail_list("radorado@fmi.com", 1)) def test_is_not_email_in_mail_list(self): self.assertTrue(not self.m.is_email_in_mail_list("emoemo@fmi.com", 1)) def test_merge_list(self): mail = mail_list.MailList() mail.create("HB1") index1 = mail.find_list_index("HB1") mail.add_name_email("Emi", "emi@emi.com", index1) mail.create("HB2") index2 = mail.find_list_index("HB2") mail.add_name_email("Rado", "rado@rado.com", index2) mail.create("HB3") index3 = mail.find_list_index("HB3") mail.add_name_email("RadoRado", "rado@rado.com", index3) mail.merge_lists_helper(index2, index3, "Merged2") self.assertEqual("Merged lists <HB1> and <HB2> into <Merged1>", mail.merge_lists_helper(index1, index2, "Merged1")) self.assertEqual(2, len(mail.mail_list["Merged1"])) self.assertEqual(1, len(mail.mail_list["Merged2"])) def test_delete(self): self.assertEqual("<FMI> was deleted.", self.m.delete(2)) def test_delete_not_there(self): self.assertEqual("List with unique identifier <2> was not found.", self.m.delete(2)) def test_update_subscriber(self): self.m1.create("HB") index = self.m1.find_list_index("HB") self.assertTrue(not self.m1.update_subscriber(index, 1)) self.m1.add_name_email("Emi", "emi@emi.com", index) self.m1.update_name_email("", "emanuela@emi.com", index, 1) self.assertEqual("emanuela@emi.com", self.m1["HB"][1][1]) self.assertEqual("Emi", self.m1["HB"][1][0]) if __name__ == '__main__': unittest.main()
6fa857117ab5587887c470fca4b19bc391e67254
ErykUrban/pp1
/02-ControlStructures/During class 2/8 do 14.py
2,290
4
4
#2.8 x =int(input("Wprowadź cyfrę: ")) y =int(input("Wprowadź cyfrę: ")) if x>y: print("x: "+ str(x) + " jest wartością wiekszą") else: print("y: "+ str(y) + " jest wartością wiekszą") print(" ") #2.9 z = int(input("Wprowadź cyfrę: ")) if z%2 == 0: print("even") else: print("odd") print(" ") #2.10 a = int(input("Wprowadź cyfrę: ")) if a>=0 and a%2 != 0: print("Dodatnia nieparzysta") else: print("Podana liczba nie jest, \njednoczesnie nieparzysta i dodatnia") print(" ") #2.11 login = "marek" hasło = "m-123" login_wprowadzony= input("Podaj login: ") hasło_wprowadzone= input("Podaj hasło: ") if login == login_wprowadzony and hasło == hasło_wprowadzone: print("Dane zostały wprowadzone poprawnie") else: print("Login lub hasło jest nieprawidłowe") print(" ") #2.12 x = int(input("Wprowadź liczbę: ")) y = int(input("Wprowadź liczbę: ")) if x < 0 or y <0: print("Jedna lub obie wartości są ujemne.") if x <0 and y <0: print("Obie wartości są ujemne") elif x<0: print("Tylko x: "+str(x)+" jest ujemne") elif y<0: print("Tylko y: "+str(y)+" jest ujemne") print(" ") #2.13 x = (input("Wprowadź 'x': ")) y = (input("Wprowadź 'y': ")) if int(x) == 0 and int(y) ==0: print("Punkt P("+x+","+y+") znajduje się na początku układu wspólrzędnych") elif int(x) > 0 and int(y) >0: print("Punkt P("+x+","+y+") znajduje się w pierwszej ćwiartce układu wspólrzędnych") elif int(x) <0 and int(y) >0: print("Punkt P("+x+","+y+") znajduje się w drugiej ćwiartce układu wspólrzędnych") elif int(x) > 0 and int(y) <0: print("Punkt P("+x+","+y+") znajduje się w czwartej ćwiartce układu wspólrzędnych") elif int(x) == 0 and int(y) >0: print("Punkt P("+x+","+y+") znajduje się na osi y układu współrzędnych") elif int(x)>0 and int(y) ==0: print("Punkt P("+x+","+y+") znajduje się na osi x układu współrzędnych") else: print("Punkt P("+x+","+y+") znajduje się w trzeciej ćwiartce układu współrzędnych") print(" ") #2.14 wiek = int(input("Podaj wiek psa w ludzkich latach: ")) if wiek in range(3): print("Wiek psa w psich latach to "+str(wiek*10.5)) elif wiek>2: print("Wiek psa w psich latach to "+str(21+(wiek-2)*4))
9d3d2c518e51efc1967f7aa5a915212d607f9965
NothinkingGao/python-demos
/dict.py
456
4.1875
4
#coding:utf-8 dict={'name':'kitty','age':2} #默认遍历key for item in dict: print item #如果只遍历值 for value in dict.values(): print value #key和value都遍历 for key,value in dict.items(): print key,value #字典转集合(会把key转成集合) print set(dict) #字典推导式 d = {key:value for (key, value) in dict.items()} print d #例如:快速更换key和value的值 d = {value:key for (key, value) in dict.items()} print d
a4a8ba8b6232c4929be3f71557b9a94dc0058d5d
lamngockhuong/python-guides
/basic/json/json-1.py
244
4
4
# https://www.w3schools.com/python/python_json.asp import json # Convert from JSON to Python # some JSON: x = '{ "name":"John", "age":30, "city":"New York"}' # parse x: y = json.loads(x) # the result is a Python dictionary print(y["age"])
718dde07b1f17f4afe9faaf46b1446c414e6a762
christoskatsivas/ATM-Simulation-project
/app.py
2,548
3.765625
4
from atm import Atm from sys import exit import time time_delay = 1 atm = Atm(150, 250, 10000) #initiates the class( $20 notes, $50 notes, User balances) print('\n\t\t\tWelcome to BANK ATM') def Menu(): time.sleep(time_delay) print('=' * 100) option = int(input( """ OPTIONS: [ 1 ] Withdraw Funds [ 2 ] Deposit Funds [ 3 ] Total Account Balance [ 4 ] Total Amount of ATM [ 5 ] Exit \n""")) if option == 1: user = int(input('Enter the amount of money: ')) while atm.Check(user) is False: print('The amount is not available') option = input('Re-enter the amount, press <N>, return to main menu, press <Q>: ').lower() if option == 'n': user = int(input('Enter the amount of money: ')) if option == 'q': return None while atm.Cash_Analysis(user) is False: print('the amount is not available') option = input('Re-enter the amount, press <N>, return to main menu, press <Q>: ').lower() if option == 'n': user = int(input('Enter the amount of money: ')) if option == 'q': return None total_withdraw = atm.Withdraw_Funds() print('Your total amount to your account is: ${}'.format(total_withdraw)) if option == 2: user = int(input('Enter the amount of money: ')) fifty_user = int(input('Enter the $50 notes number: ')) twenty_user = int(input('Enter the $20 notes number: ')) while atm.Check_Deposit(fifty_user, twenty_user, user) is False: print('Wrong Amount!') option = input('Re-enter the amount, press <N>, return to main menu, press <Q>: ').lower() if option == 'n': user = int(input('Enter the amount of money: ')) fifty_user = int(input('Enter the $50 notes number: ')) twenty_user = int(input('Enter the $20 notes number: ')) if option == 'q': return None total_deposit = atm.Deposit_Funds(fifty_user, twenty_user) print('Your total amount to your account is: ${}'.format(total_deposit)) if option == 3: print('Your total amount to your account is: ${}'.format(atm.Total_Balances())) if option == 4: print(atm.Total_Amount_Atm()) if option == 5: print('\t\tThank you for using BANK ATM!') exit() while True: Menu()
1b412ed8ec09e381eecd0f60c93b35f3560abadf
gessichen/algorithms
/convertListToTree.py
1,343
3.921875
4
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a list node # @return a tree node def buildTree(self, head, length): # print head.val if length == 0: return None if length == 1: return TreeNode(head.val) cursor = head for i in xrange(0, length / 2): cursor = cursor.next # print cursor.val root = TreeNode(cursor.val) root.left = self.buildTree(head, length/2) root.right = self.buildTree(cursor.next, length - length/2 - 1) return root def sortedListToBST(self, head): if head == None: return None length = 0 p = head while p != None: length += 1 p = p.next return self.buildTree (head, length) def printTree (tree): if tree == None: print "#" return print tree.val printTree(tree.left) printTree(tree.right) l1 = ListNode(1) l2 = ListNode(2) l3 = ListNode(3) l4 = ListNode(4) l5 = ListNode(5) l1.next = l2 l2.next = l3 l3.next = l4 l4.next = l5 l5.next = None s = Solution() tree = s.sortedListToBST(l1) printTree(tree)
c2ced7019848a68187e9d4938210abb4d6a2a295
jagadeeshben/bootcamp-project
/project.py
1,415
3.875
4
#!/usr/bin/env python # coding: utf-8 # In[54]: #TO ACCESS THE DATAFRAME USING PANDAS FUNCTION import pandas as pd import numpy as np import seaborn as sb titanic=pd.DataFrame(pd.read_csv(r"C:\Users\user\Desktop\Titanic_ship.csv")) print("Titanic_Ship is type of:",type(titanic))#it gives the type of data frame print("Titanic_Ship have a shape of:",titanic.shape)#it represents a how many rows and colomns present in data frame # In[55]: titanic.head()#TO ACCESS THE first five ROWS of LARGE DATA FRAMES # In[48]: a=titanic.head(10)#TO ACCESS THE SPECIFIC SET OF ROWS IN LARGE DATA FRAMES # In[ ]: # In[56]: titanic['Survived']#To get entire data of specific COLOUMN # In[29]: titanic.count()#to count the number of non NAN values in every coloumn # In[31]: titanic.count(axis=1)#To count the number of non NAN values in every ROW # In[32]: titanic.tail()##TO ACCESS THE last SET OF ROWS IN LARGE DATA FRAMES # In[35]: titanic.isnull().sum()#to count the number of nan values in every column # In[8]: titanic['Pclass'].describe()#IT GIVES THE HOW MANY PASSENGERS ARE PRESENT IN THAT SHIP ACCORDING TO CLASSES # In[66]: sb.countplot(data=a,x='PassengerId') # In[21]: a['Age'].fillna('0') # In[58]: titanic.fillna('0') titanic.isnull().sum() # In[61]: base.color=sb.color_palette([3]) sb.counterplot(data=titanic,x='age>14',color=base_color) # In[ ]:
b72a3400cb2c9820133152d144c9710b60779bec
Chillpudde/studier
/in1000/oblig2/utskrift.py
357
3.828125
4
# Opgave 1. Utskriftsprosedyre # # 1. navn = input("Skriv inn navn: ") sted = input("Hvor kommer du fra? ") print("Hei, " + navn + "! Du er fra " + sted + ".") # 2. count = 0 while count < 3: navn = input("\n" + "Skriv inn navn: ") sted = input("Hvor kommer du fra? ") print("Hei, " + navn + "! Du er fra " + sted + ".") count = count+1
c638de6b613b211aa564889781b1e96b930a35db
herrera-ignacio/coding_problems
/easy/trees/2/solution.py
402
3.8125
4
def nodeDepthAux(node, currentDepth): if not node: return 0 return currentDepth + nodeDepthAux(node.left, currentDepth + 1) + nodeDepthAux(node.right, currentDepth + 1) def nodeDepths(root): return nodeDepthAux(root, 0) # This is the class of the input binary tree. class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None
fc5da59afada5d3bbdbee1f24d45639b0d0a1f62
streefje1996/AD_week3
/opdracht4.py
1,760
3.609375
4
from csv import writer def freq_table(file_name,trie): word_freq = dict() with open(file_name,'r') as file: for line in file: for word in line.split(sep=" "): word = word.strip("\n.\'\"\,;(){}\t\r\f\b\a\0") if word != "": word = word.lower() trie.insert(word) if word in word_freq: word_freq[word] += 1 else: word_freq[word] = 1 with open("table_using_dict.csv", "w", newline='') as file: file.write("SEP=,\n") csv = writer(file,delimiter=',') csv.writerow(["Word","freq"]) for word in word_freq: csv.writerow([word,word_freq[word]]) class TrieNode: def __init__(self): self.n = 0 self.d = dict() def insert(self,word,letter=1): if letter != len(word)+1: if word[:letter] not in self.d: self.d[word[:letter]] = TrieNode() if word[:letter] == word: self.d[word[:letter]].n += 1 self.d[word[:letter]].insert(word,letter+1) def create_csv_file(self,writer,word=None): '''takes a CSV writer as parameter''' if self.n > 0: writer.writerow([word,self.n]) if self.d: for node in self.d: self.d[node].create_csv_file(writer,node) trie = TrieNode() freq_table("test.txt",trie) with open("table_using_trie.csv", "w", newline='') as file: file.write("SEP=,\n") csv = writer(file,delimiter=',') csv.writerow(["Word","freq"]) trie.create_csv_file(csv)
1fd7fbf8715b0d05c708cb3824d455a1143f2c96
MXS-PICHUY/EVIDENCIA_1-S3
/24-08-21#EJ 6.py
238
3.75
4
import collections SEPARADOR = ("*"*20) + "\n" pila_con_lista = list() for i in range(5): pila_con_lista.append(input('dime el nombre a agregar: ')) while pila_con_lista: print(pila_con_lista.pop()) print(SEPARADOR)
092df3dc148eba6c38ede5008472cae1fa95735b
KYUJEONG98/2021-1-OSSP1-CodeNation-5
/loadfile/load file.py
240
3.59375
4
import tkinter from tkinter import filedialog root = tkinter.Tk() root.withdraw() dir_path = filedialog.askopenfilename(parent=root,initialdir="/",title='Please select a directory') print("\ndir_path : ", dir_path) f = open(dir_path, 'r')
fdf1a11986a4abb53e19e3e35dd80ae1031bbe75
sinvaljang/LangStudy
/python/04_dictionary/01_dictionary.py
1,248
3.75
4
################################################### # subject : Dictionary # date : 2017-09-22 11:00 ################################################### #宣言 student = {'name' : 'jang', 'age' : 30} print(student) print(student['name']) print(student['age']) #キーで値取得 student['class'] = 1 print(student['class']) #キー削除 print(student) del student['class'] print(student) #dictionaryからキーをリスト形式で取得 print(student.keys()) for key in student.keys(): print(key) st_key_list = list(student.keys()) print(st_key_list) #dictionaryから値をリスト形式で取得 print(student.values()) for val in student.values(): print(val) st_val_list = list(student.values()) print(st_val_list) #dictionaryからキー、値をリスト形式で取得 print(student.items()) for all in student.items(): print(all) st_all_list = list(student.items()) print(st_all_list) #dictionaryからキーで値を取得する #getはキーがなかったらNoneをリターンする print(student.get('name')) print(student.get('class')) if(student.get('class')): print('clsss ari') else: print('class nasi') #dictionaryの内容を削除 print(student) student.clear() print(student)
e531287b9809f4f67fc1b2fc1e0f9790867556d9
axelaviloff/uri-solutions
/Python3/URI1117.py
220
3.75
4
contador = 0 soma = 0 while contador != 2: nota = float(input()) if not(0 <= nota <= 10): print("nota invalida") else: contador += 1 soma += nota print("media = {:.2f}".format(soma/2))
5215130fccb9edc3aff1fbf2ec0439dead76e165
mangodayup/month01-resource
/day10/demo06.py
1,322
4.15625
4
""" 属性property 原理: 创建类变量,关联属性对象,覆盖实例变量 属性对象需要读取和写入函数 核心思想: 拦截 """ # 疑惑1:属性名等同于实例变量名 # 答:属性需要拦截类外对实例变量的操作 # 疑惑2:属性内部操作私有变量 # 答:私有变量实际存储数据,如果类外可以访问,那么失去保护作用. class Wife: def __init__(self, name="", age=0): self.name = name self.age = age def get_age(self): # 负责读取 return self.__age def set_age(self, value): # 负责写入 self.__age = value # 创建类变量,关联属性,覆盖实例变量 age = property(get_age, set_age) shuang_er = Wife("双儿", 30) print(shuang_er.name) print(shuang_er.age) class Wife: def __init__(self, name="", age=0): self.name = name self.age = age # 创建类变量,关联属性(读),覆盖实例变量 @property # age = property(读取函数) def age(self): # 负责读取的函数 return self.__age @age.setter # age = age.setter(写入函数) def age(self, value): # 负责写入的函数 self.__age = value shuang_er = Wife("双儿", 30) print(shuang_er.name) print(shuang_er.age)
627ba8c79c0d0e4da7150bfda8d9d35b29da2542
eFirewall/Firestuff
/Python_Learning/Python Jumpstart/Random/game.py
705
4.09375
4
u"""Adivina el número.""" import random print('-------------------------------------------') print(' ADIVINA EL NUMERO') print('-------------------------------------------') print() numero = random.randint(0, 100) nombre = input('¿Como te llamas? ') adivina = -1 while adivina != numero: adivina = input('Adivina que numero estoy pensando de 0 a 100? ') adivina = int(adivina) if adivina > numero: print('{}, el número {} es demasiado alto'.format(nombre, adivina)) elif adivina < numero: print('{}, el número {} es demasiado bajo'.format(nombre, adivina)) else: print('¡Enhorabuena {}, {} es el numero!'.format(nombre, adivina)) print('')
5e0f33449648a5ce4505cb62cd8f2673973b9a29
dyrnfmxm/codeit
/0317_palindrome.py
417
4
4
def is_palindrome(word): # 코드를 입력하세요. reverse_word = word[::-1] for i in range(len(word)): if word[i] != reverse_word[i]: return False break return True # 테스트 print(is_palindrome("racecar")) print(is_palindrome("stars")) print(is_palindrome("토마토")) print(is_palindrome("kayak")) print(is_palindrome("hello"))
77955aeefc83870ac8d82673f955f798b56750f2
Akumatic/Playground
/Python/File Checksum/checksum.py
4,274
3.96875
4
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT # Copyright (c) 2020 Akumatic import hashlib, zlib, argparse def _hash ( function, file: str, blocksize: int ) -> str: """ Hashing the given file with the given function Args: function: the function to be used to generate or calculate the hash file (str): the path to the file blocksize (int): the amount of bytes to be read at a time to update the hash Returns: a string containing the calculated hash with uppercase letters. """ try: # MD5, SHA1 and SHA256 if function.__module__ == "_hashlib": hash = function() with open(file, "rb") as f: for chunk in iter(lambda: f.read(blocksize), b""): hash.update(chunk) return hash.hexdigest().upper() # CRC32 elif function.__module__ == "zlib": hash = 0 with open(file, "rb") as f: for chunk in iter(lambda: f.read(blocksize), b""): hash = function(chunk, hash) return ("%08X" % (hash & 0xFFFFFFFF)).upper() except FileNotFoundError: print(f"checksum.py: error: argument file: '{file}' not found") exit(1) def in_bytes ( x ) -> int: """ Verifies the passed input for the amount of bytes to be read at a time. Input has to be an integer and bigger or equals to 1. Args: x: The value to be verified Raises: ArgumentTypeError if the given value is no integer or smaller than 1 """ try: x = int(x) if x < 1: raise argparse.ArgumentTypeError("invalid integer value. " "minimum amount of bytes is 1") return x except ValueError: raise argparse.ArgumentTypeError("invalid integer value.") def parse_args ( algorithms: list ) -> dict: """ Parses cli arguments. Args: algorithms (list): a list with algorithms usable in this program. Returns: a dict containing the parsed arguments. """ p = argparse.ArgumentParser( description="A tool to calculate and compare checksums.") for algo in algorithms: p.add_argument(f"--{algo.lower()}", action="store_true", dest=algo, help=f"calculates checksum with {algo}") p.add_argument("-b", "--blocksize", dest="size", default=64, type=in_bytes, help="specify the amount of bytes to be read at a time") p.add_argument("-c", "--compare", dest="comp", help="compare the given checksum with the calculated ones.") p.add_argument("file", help="the file you want to calculate the checksums for.") return vars(p.parse_args()) def compare ( hashes: dict, hash: str ) -> tuple: """ Compares a hash with a dict of given hashes. Args: hashes (dict): a dict containing the hashing method as key and the hash as value hash: a string with the hash to be compared Returns: a tuple containing a boolean and a string. the boolean stores if a match was found. the string stores the matched hashing algorithm or None. """ for h in hashes: if hashes[h] == hash: return (True, h) return (False, None) if __name__ == __name__: # dict containing hashing algorithms to be used algorithms = { "CRC32": zlib.crc32, "MD5": hashlib.md5, "SHA1": hashlib.sha1, "SHA256": hashlib.sha256 } args = parse_args(algorithms.keys()) # boolean to check if any hashing algorithm was specified passed_algos = any([1 for x in algorithms if args[x]]) print("Checksums:\n==========") hashes = dict() for a in algorithms: if args[a] or not passed_algos: hashes[a] = _hash(algorithms[a], args["file"], args["size"]) print(a, "\t", hashes[a]) if args["comp"]: found, algorithm = compare(hashes, args["comp"].upper()) if found: print("\nMatch found:", algorithm) else: print("\nNo match found.")
6e07d7c0607e6274ac3d701ef990493682f37392
herculesgabriel/trybe-exercises
/MODULO_4_CIENCIA_DA_COMPUTACAO/BLOCO_36/dia_2/conteudo/fibonacci.py
413
4.0625
4
def get_fibonacci_number(n): fibonacci_numbers = [0, 1] while len(fibonacci_numbers) <= n: new_number = fibonacci_numbers[-2] + fibonacci_numbers[-1] fibonacci_numbers.append(new_number) return fibonacci_numbers[-1] print(get_fibonacci_number(7)) def fibonacci(n): if n < 2: return n else: return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(7))
95f8ee4b72a7a64c8600f0088feb2ab5354fe875
sanjana-reddy1652/Python
/lists methods.py
2,097
3.8125
4
#lits methods a_list=[10,56,76,45,13,29] b_list=[18,8.9,"yeonjun",12,90] #len() : length of the list >>> len(a_list) 6 #max() : returns the max element in the list >>> max(a_list) 76 >>> max(b_list) Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> max(b_list) TypeError: '>' not supported between instances of 'str' and 'int' #min() : returns the min element in the list >>>min(a_list) 10 >>> min(b_list) Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> max(b_list) TypeError: '>' not supported between instances of 'str' and 'int' #append() : adds an object into the list at the last index >>>a_list.append(1) print(a_list) [10, 56, 76, 45, 13, 29, 1] >>>b_list.append("15") [18, 8.9, 'yeonjun', 12, 90, 15] #count() : returns the count of how many times an object occurs in the list >>>a_list.count(10) 1 >>> b_list.count("yeonjun") 1 #index() : it returns the lowest index in the list where the object occurs >>>a_list.index(10) 0 >>> b_list.index("yeonjun") 2 #pop() : removes the specfied object and returns the value >>> a_list.pop(5) 29 >>> b_list.pop(5) 'sanjana' #insert() : inserts a specfied object at specfied index >>> a_list.insert(3,45) >>>print( a_list) [10, 56, 76, 45, 45, 13, 1] >>> b_list.insert(3,"sanjana") >>> print(b_list) [18, 8.9, 'yeonjun', 'sanjana', 12, 90] #sort() : sorts the given list >>> a_list.sort() >>> print(a_list) [1, 10, 13, 45, 56, 76] >>> b_list.sort() Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> b_list.sort() TypeError: '<' not supported between instances of 'str' and 'float' #reverse() : reverses the given list >>> a_list.reverse() >>> print(a_list) [76, 56, 45, 13, 10, 1] >>> b_list.reverse() >>> print(b_list) [90, 12, 'sanjana', 'yeonjun', 8.9, 18] #remove() : removes the specfied object >>> b_list.remove(8.9) >>> print(b_list) [90, 12, 'sanjana', 'yeonjun', 18] #extend() : appends the specfied contes to the list >>> a_list.extend(b_list) >>> print(a_list) [76, 56, 45, 13, 10, 1, 90, 12, 'sanjana', 'yeonjun', 18]
bb688723282bdb58065b287e559826743436fc37
chriskok/PythonLearningWorkspace
/customerlist.py
595
3.921875
4
# array of cust dictionaries # Enter cust (y/n) # Enter cust name: Derek # repeat till n received # Derek Banas # Sally Smith choice = input("Enter customer name? (yes/no): ") custList = [] while choice == 'y' or choice == 'yes': fName, lName = input("Please enter customer's name: ").split() custList.append({'fName': fName, 'lName': lName}) choice = input("Enter customer name? (yes/no): ") while choice != 'y' and choice != 'yes' and choice != 'n' and choice != 'no': choice = input("Invalid input, please enter again: ") for i in custList: print(i['fName'], i['lName'])
30b2084eaacc622aec84bad0b4a7d296ce094126
cyberskeleton/sandbox
/tokill/aiaiaiai.py
185
3.640625
4
def f(s): for i in range(0, len(s)): if s[i] == '+': s = s.replace(s[i], '') print(s) return s s = input('input line: ') ans = f(s) print(ans)
1f51d88ca5489fab31367fdf9c9bf440066f20bb
aidardarmesh/leetcode2
/0448. Find All Numbers Disappeared in an Array.py
539
3.53125
4
from typing import * class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: # cyclic-sort i = 0 while i < len(nums): val = nums[i] if val == i+1 or nums[val-1] == val: i += 1 else: nums[i], nums[val-1] = nums[val-1], nums[i] # gathering answer res = [] for i in range(len(nums)): if nums[i] != i+1: res.append(i+1) return res
c00c06c836aa687e9cf1bed0590fb42669d92c4e
Omarabdul3ziz/CodeSteps-3.0
/oj/maxinlist.py
106
3.796875
4
lista = [1, 23, 5, 84, 4] maxi = lista[0] for a in lista: if a > maxi: maxi = a print(maxi)
4c289c514b3478c83d544cff288d61301b9e4a9c
saurabh-c-rai/Data-Science-Projects
/NLP & DeepLearning/DeepLearning/Multi Layered Perceptron/src/trainMultiLayerPerceptron.py
5,508
3.640625
4
#%% import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score #%% path = "../input/bank_customer_churn.csv" data = pd.read_csv(path) # %% data.describe() # %% data.head() # %% # separate into features and target X = data[ [ "CreditScore", "Age", "Tenure", "Balance", "NumOfProducts", "HasCrCard", "IsActiveMember", "EstimatedSalary", ] ] y = data["Exited"] # %% # mean normalization and scaling mean, std = np.mean(X), np.std(X) X = (X - mean) / std X = pd.concat( [X, pd.get_dummies(data["Gender"], prefix="Gender", drop_first=True)], axis=1 ) # %% # transform data according to the model input format X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20, random_state=9 ) # %% # size of layers INPUT_SIZE = X_train.shape[1] HIDDEN_SIZE = 3 OUTPUT_SIZE = 1 np.random.seed(22) # %% # Initializing weights w_1 = np.ones(shape=(INPUT_SIZE, HIDDEN_SIZE)) * 0.05 w_2 = np.ones(shape=(HIDDEN_SIZE, OUTPUT_SIZE)) * 0.05 # %% # Initializing bias values b_1 = np.zeros(shape=(1, HIDDEN_SIZE)) b_2 = np.zeros(shape=(1, OUTPUT_SIZE)) # %% def sigmoid(x): """Function to return sigmoid value Arguments: x {[numpy array]} -- [feature vector] Returns: [float] -- [sigmoid equivalent of input] """ return 1 / (1 + np.exp(-(x))) # %% def forward(w_1, w_2, b_1, b_2, X): """Function to stimulate the forward propogation of Neural Network Arguments: w_1 {[numpy array]} -- [weight vector from input to hidden layer] w_2 {[numpy array]} -- [weight vector from hidden layer to output layer] b_1 {[numpy array]} -- [bias vector for the hidden layer] b_2 {[numpy array]} -- [bias vector for the hidden layer] x {[numpy array]} -- [feature vector row] Returns: a1 {[numpy array]} -- [post activation value of the hidden layer] a2 {[numpy array]} -- [post activation value of the output layer] """ z1 = X @ w_1 + b_1 a1 = sigmoid(z1) z2 = a1 @ w_2 + b_2 a2 = sigmoid(z2) return a1, a2 # %% _, pred = forward(w_1, w_2, b_1, b_2, X_train) # %% pred # %% # function for loss function def cross_entropy(y_actual, y_hat): """Method to calculate Cross Entropy loss function value Arguments: y_actual {[Numpy Array]} -- [Actual Target value] y_hat {[Numpy Array]} -- [Predicted Target value] Returns: [float] -- [Value of loss function] """ return (1 / y_hat.shape[0]) * np.sum( -np.multiply(y_actual.values.reshape(-1, 1), np.log(y_hat)) - np.multiply((1 - y_actual.values.reshape(-1, 1)), np.log(1 - y_hat)) ) # %% # function to score on unseen data def predict(X_test, y_test): """Function to calculate prediction for the given test data. Calculates updated weights using backpropagation and then makes prediction on them using forward propogation Arguments: X_test {[Numpy array/dataframe]} -- [Test set features] y_test {[Numpy Array]} -- [Training set Target] Returns: acc[float] -- [Accuracy score for the prediction] """ # finding best set of weights w1_new, w2_new, b1_new, b2_new = backpropagate( w_1, w_2, b_1, b_2, X_train, X_test, y_train, y_test, 4000, 0.01 ) # make predictions y_pred = forward(w1_new, w2_new, b1_new, b2_new, X_test.values)[1].flatten() # binarize it y_pred = y_pred > 0.5 # calculate accuracy acc = accuracy_score(y_pred, y_test.values) return acc # %% def backpropagate(w_1, w_2, b_1, b_2, X_train, X_test, y_train, y_test, epochs, lr): """ Backpropagation algorithm to find the best set of weights for our problem statement. Arguments: w_1 {[Numpy array]} -- [weights from input to hidden layer] w_2 {[Numpy array]} -- [weights from hidden to output layer] b_1 {[Numpy array]} -- [bias from input to hidden layer] b_2 {[Numpy array]} -- [bias from hidden to output layer] X_train {[Numpy array/dataframe]} -- [Training set features] X_test {[Numpy array/dataframe]} -- [Test set features] y_train {[Numpy Array]} -- [Training set Target] y_test {[Numpy Array]} -- [Training set Target] epochs {[int]} -- [number of iterations over the entire training data] lr {[float]} -- [learning rate] Returns: w_1[Numpy Array] -- [Updated weights from input to hidden layer] w_2[Numpy Array] -- [Updated weights from hidden layer to output layer] b_1[Numpy Array] -- [Updated bias from input to hidden layer] b_2[Numpy Array] -- [Updated bias from hidden layer to output layer] """ m = X_train.shape[0] for _ in range(epochs): a1, a2 = forward(w_1, w_2, b_1, b_2, X_train.values) curr_loss = cross_entropy(y_train, a2) da2 = a2 - y_train.values.reshape(-1, 1) da1 = np.multiply((da2 @ w_2.T), np.multiply(a1, 1 - a1)) dw2 = (1 / m) * a1.T @ (da2) db2 = 1 / m * da2 dw1 = (1 / m) * X_train.values.T @ (da1) db1 = 1 / m * da1 w_1 = w_1 - lr * dw1 w_2 = w_2 - lr * dw2 b_1 -= np.sum(db1) b_2 -= np.sum(db2) return w_1, w_2, b_1, b_2 #%% acc = predict(X_test, y_test) # %% print(acc)
c0cc819c211c5432976bf84639fd05c9441f77c1
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/rob_sanchez/Lesson 2/Series.py
2,957
4
4
import sys #Function returns the nth value of the Fibonacci series def Fibonacci(n): #Defined variables var1=0 var2=1 #if n reaches first Fibonacci value then return its value if n==var1: return var1 #if n reaches second Fibonacci value then return its value elif n==var2: return var2 else: #Surrounding with a try blcok to catch and return #any exceptions raised during execution try: #use recursion to return the sum of the previews two numbers return Fibonacci(n-2) + Fibonacci(n-1) except Exception as e: print(e.message) raise #Function returns the nth value of the Lucas series def Lucas(n): l0=2 l1=1 if n==0: return l0 elif n==1: return l1 else: #Surrounding with a try blcok to catch and return #any exceptions raised during execution try: return Lucas(n-1) + Lucas(n-2) except Exception as e: print(e.message) raise #Function returns sum values based on the initial input #Input: n -- nth value of the sum_series #Optional: var1, var2 with default values 0,1 def sum_series(n, var1=0, var2=1): if n==0: return var1 elif n==1: return var2 else: #Surrounding with a try blcok to catch and return #any exceptions raised during execution try: return sum_series(n-1,var1, var2) + sum_series(n-2, var1, var2) except Exception as e: print(e.message) raise #Fibonacci Test cases: #Default value(0,1) should return numbers from the Fibonacci series #Fibonacci series at index 0 is 0 assert 0 == sum_series(0) #Fibonacci series at index 1 should return 1 assert 1 == sum_series(1) #Fibonacci series at index 2 should return 1 assert 1 == sum_series(2) #Fibonacci series at index 3 should return 2 assert 2 == sum_series(3) #Fibonacci series at index 10 should return 55 assert 55 == sum_series(10) #Lucas Test cases: #Default value(0,1) should return numbers from the Fibonacci series #Lucas at index 0 should return 2 assert 2 == sum_series(0,2,1) #Lucas at index 1 should return 1 assert 1 == sum_series(1,2,1) #Lucas at index 2 should return 3 assert 3 == sum_series(2,2,1) #Lucas at index 3 should return 4 assert 4 == sum_series(3,2,1) #Lucas at index 10 should return 123 assert 123 == sum_series(10,2,1) #Other Series Test cases: #Replacing the default values should return numbers from the other series #This series uses 3 and 2 as default values #Other series at index 0 should return 3 assert 3 == sum_series(0,3,2) #Other series at index 1 should return 2 assert 2 == sum_series(1,3,2) #Other series at index 2 should return 5 assert 5 == sum_series(2,3,2) #Other series at index 3 should return 7 assert 7 == sum_series(3,3,2) #Other series at index 10 should return 212 assert 212 == sum_series(10,3,2)
fe35c0f5ca606fd39188d6fa2a1bef7803aadff4
daniel-reich/ubiquitous-fiesta
/bYDPYX9ajWC6PNGCp_11.py
263
3.671875
4
def track_robot(*steps): x = 0 y = 0 steps = list(steps) for i in range(0,len(steps)): if i % 4 == 0: y += steps[i] elif i % 4 == 1: x += steps[i] elif i % 4 == 2: y -= steps[i] else: x -= steps[i] return [x,y]
1d10e230fffb92b242174b36c803ea3f2441f810
varshakarumanchi/Python-
/scripts/sumofdigits.py
117
3.6875
4
def sumDigits(N): num=N N=N/10 if N==0: return num else: return num%10 + sumDigits(N)
6158c1bcd9b730f8a968051f0162b021b0dd0507
gitnimo/noob
/jump/00/D.py
989
3.515625
4
#import csv #fn='eiv010.csv' #with open(fn) as file: # csvr=csv.reader(file) # csvl=list(csvr) #print(csvl[1][0]) #reader 串列 迴圈方法打開 #import csv #fn='0_01.csv' #with open(fn,'w') as file: #csvWriter=csv.writer(file) #csvWriter.writerow(['name','age','tall']) #csvWriter.writerow(['nimo','22','182']) #csvWriter.writerow(['joker','25','181']) #寫入csv #import csv #fn=' 0_01.csv' #fn2='0_02.csv' #with open(fn,'r') as file: #csvr=csv.reader(file) #csvrl=list(csvr) #with open(fn2,'w',newline='')as file2: # csr=csv.writer(file2) #for row in csvrl: # csr.writerow(row) #複製csv import csv fn3='0_03.csv' with open(fn3,'w') as file: csc=['Name','Age','Home'] f3w=csv.DictWriter(file,fieldnames=csc) f3w.writeheader()#寫入標題 csc f3w.writerow({'Name':'chiami','Age':'23','Home':'yes'}) f3w.writerow({'Name':'dan','Age':'25','Home':'no'})
24583cc88bc8e12c960af0053697386fd6459ad6
santospat-ti/Python_Ex.EstruturadeRepeticao
/nota.py
372
4.1875
4
"""Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido.""" nota = float(input("Digite uma nota entre zero e dez: ")) while (nota>10) or (nota<0): nota = float(input('Valor inválido. Por favor, informe um valor de zero a dez.')) break
b982243027ead8dca4a23ee5e141bfc854a08908
Epineda312/pythonFiles
/UD-Py/day_15/main.py
5,872
4.1875
4
from menu import MENU, resources def starting_supply(supply): machine_water = supply["water"] machine_milk = supply["milk"] machine_coffee = supply["coffee"] return (f" Water remaining: {machine_water}\n" f" Milk remaining: {machine_milk}\n" f" Coffee remaining: {machine_coffee}") machine_is_on = True resources["money"] = 0 water = resources["water"] milk = resources["milk"] coffee = resources["coffee"] espresso_price = MENU["espresso"]["cost"] latte_price = MENU["latte"]["cost"] cappuccino_price = MENU["cappuccino"]["cost"] print(f"Starting resources are as follows:\n{starting_supply(resources)}") while machine_is_on: order_complete = False while not order_complete: choice = input("What would you like? (espresso/latte/cappuccino)\n").lower() if choice == "espresso": print(f"One {choice} coming right up!\n") if water < MENU["espresso"]["ingredients"]["water"]: print("Not enough water") break if coffee < MENU["espresso"]["ingredients"]["coffee"]: print("Not enough coffee") break else: print("insert coins please") quarters = float(input("How many quarters?: ")) dimes = float(input("How many dimes?: ")) nickels = float(input("How many nickles?: ")) pennies = float(input("How many pennies?: ")) total = round((0.25 * quarters) + (0.10 * dimes) + (0.05 * nickels) + (0.01 * pennies), 2) print(f"total coins inserted is ${total}\n") if total >= espresso_price: change = round(total - espresso_price, 2) print(f"Here is ${change} in change.") print(f"Here is your {choice}. enjoy!") resources["money"] = resources["money"] + espresso_price water = water - MENU["espresso"]["ingredients"]["water"] coffee = coffee - MENU["espresso"]["ingredients"]["coffee"] elif total < espresso_price: print("Sorry that's not enough money. Money refunded.") elif choice == "latte": print(f"One {choice} coming right up!\n") if water < MENU["latte"]["ingredients"]["water"]: print("Not enough water") break if milk < MENU["latte"]["ingredients"]["milk"]: print("Not enough milk") break if coffee < MENU["latte"]["ingredients"]["coffee"]: print("Not enough coffee") break else: print("insert coins please") quarters = float(input("How many quarters?: ")) dimes = float(input("How many dimes?: ")) nickels = float(input("How many nickles?: ")) pennies = float(input("How many pennies?: ")) total = round((0.25 * quarters) + (0.10 * dimes) + (0.05 * nickels) + (0.01 * pennies), 2) print(f"total coins inserted is ${total}") if total >= latte_price: change = round(total - latte_price, 2) print(f"Here is ${change} in change.") print(f"Here is your {choice}. enjoy!") resources["money"] = resources["money"] + latte_price water = water - MENU["latte"]["ingredients"]["water"] coffee = coffee - MENU["latte"]["ingredients"]["coffee"] elif total < latte_price: print("Sorry that's not enough money. Money refunded.") elif choice == "cappuccino": print(f"One {choice} coming right up!\n") if water < MENU["cappuccino"]["ingredients"]["water"]: print("Not enough water") break if milk < MENU["cappuccino"]["ingredients"]["milk"]: print("Not enough milk") break if coffee < MENU["cappuccino"]["ingredients"]["coffee"]: print("Not enough coffee") break else: print("insert coins please") quarters = float(input("How many quarters?: ")) dimes = float(input("How many dimes?: ")) nickels = float(input("How many nickles?: ")) pennies = float(input("How many pennies?: ")) total = round((0.25 * quarters) + (0.10 * dimes) + (0.05 * nickels) + (0.01 * pennies), 2) print(f"total coins inserted is ${total}\n") if total >= cappuccino_price: change = round(total - cappuccino_price, 2) print(f"Here is ${change} in change.") print(f"Here is your {choice}. enjoy!") resources["money"] = resources["money"] + cappuccino_price water = water - MENU["cappuccino"]["ingredients"]["water"] milk = milk - MENU["cappuccino"]["ingredients"]["milk"] coffee = coffee - MENU["cappuccino"]["ingredients"]["coffee"] elif total < cappuccino_price: print("Sorry that's not enough money. Money refunded.\n") elif choice == "report": print(f"Water: {water}\n" f"Milk: {milk}\n" f"coffee: {coffee}\n" f"money: ${resources['money']}\n") elif choice == "off": machine_is_on = False order_complete = True print("Goodbye!") else: print("Please enter a valid input\n")
ffc43fe9bb18a7cf84dd6d937ec5ba911fc82e5a
violetyk/study-effective-python
/special-attributes.py
1,487
4.1875
4
#!/usr/bin/env python import math class Point: # __doc__ docstring。トリプルクォーテーションでくくられた改行含む文字列。サブクラスに継承はされない。 """この文字列は 1つの文字列として 扱われます。""" # __init__() コンストラクタ def __init__(self, x, y): self.x = x self.y = y def distance(self): return math.sqrt(self.x * self.x + self.y * self.y) # __getattribute__() クラスのメンバやメソッドを参照できる。 # __getattribute__のフォールバック def __getattr__(self, item): print(item) return 'Member not found' # __getitem__はクラスのインスタンスに対して辞書のindexでアクセスした場合 def __getitem__(self, item): print(f'__getitem__({item}) is called') if item == 'x': return self.x elif item == 'y': return self.y def main(): point = Point(10, 20) print(point.__doc__) print(point.x) # print(point.__getattribute__('x')) とおなじ print(point.distance()) # print(point.__getattribute__('distance')()) とおなじ print(point.x2) # point.__getattribute__('x2')のフォールバックで__getattr__('x2') が呼ばれる # point.__getitem__('x')が呼ばれる print(point['x']) print(point['y']) point.x = 30 if __name__ == '__main__': main()
005e86525a5e0262dec853646308022b65c1e8fb
kolya-t/todo.py
/create_db.py
310
3.53125
4
import sqlite3 def create_db(): connection = sqlite3.connect('toDO.db') cursor = connection.cursor() cursor.execute('''CREATE TABLE if not exists quasks ('id' INTEGER PRIMARY KEY, 'date_created' integer, 'description' text, 'is_done' integer)''') connection.commit() connection.close() return
3e085fb55a5e3ba62bb7f2d5c4c95649549827cb
kaczifant/HackerRank-Problems-In-Python
/Data Structures/Easy/print_the_elements_of_a_linked_list_in_reverse.py
1,164
4.28125
4
# https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list-in-reverse/problem #!/bin/python3 import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = SinglyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node self.tail = node def print_singly_linked_list(node, sep): while node: print(node.data, end='') node = node.next if node: print(sep, end='') # Complete the reversePrint function below. # # For your reference: # # SinglyLinkedListNode: # int data # SinglyLinkedListNode next # # def reversePrint(head): current_node = head if current_node is None: return reversePrint(current_node.next) print(current_node.data) if __name__ == '__main__':
b61def137ee2f4696386a9fa85991ad167276ab6
Leputa/Leetcode
/python/39.Combination Sum.py
735
3.59375
4
class Solution: def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates.sort() res=[] tmpList=[] self.combine(0,candidates,target,tmpList,res) return res def combine(self,start,candidates,target,tmpList,res): if target==0: res.append(tmpList[:]) return if target<0: return for i in range(start,len(candidates)): tmpList.append(candidates[i]) target-=candidates[i] self.combine(i,candidates,target,tmpList,res) target+=candidates[i] tmpList.pop() print(Solution().combinationSum([2, 3, 7, 6],7))
f1d199495325cdde517b5dd9578ca96da8e96773
AbeLudlam/542Poker
/542-Poker/poker.py
6,504
3.671875
4
#Originally project from here https://github.com/fogleman/Poker #New authors: Abraham Ludlam and Hezekiah Pilli #This code evaluates poker hands for 5 and 7 card poker. We added the functionality of 3 player 7 card poker and providing a UI for the user to interact with to run the evaluation functions as much as they want. #Old code written: Global variables, hash function, eval5, eval7, one_round5, one_round7. #New code written: one_round73, use_eval() from poker_data import * import itertools import random #Set up the deck for use for the program. Also set up primes for use in the evaluation process. _SUITS = [1 << (i + 12) for i in range(4)] _RANKS = [(1 << (i + 16)) | (i << 8) for i in range(13)] _PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] _DECK = [_RANKS[rank] | _SUITS[suit] | _PRIMES[rank] for rank, suit in itertools.product(range(13), range(4))] SUITS = 'cdhs' RANKS = '23456789TJQKA' DECK = [''.join(s) for s in itertools.product(RANKS, SUITS)] LOOKUP = dict(zip(DECK, _DECK)) #Original code, I only know it helps with the eval(5) function in returning a score. def hash_function(x): x += 0xe91aaa35 x ^= x >> 16 x += x << 8 x &= 0xffffffff x ^= x >> 4 b = (x >> 8) & 0x1ff a = (x + (x << 2)) >> 19 r = (a ^ HASH_ADJUST[b]) & 0x1fff return HASH_VALUES[r] #This function evaluates a 5 card poker hand. Original code, can't comment more on. def eval5(hand): c1, c2, c3, c4, c5 = (LOOKUP[x] for x in hand) q = (c1 | c2 | c3 | c4 | c5) >> 16 if (0xf000 & c1 & c2 & c3 & c4 & c5): return FLUSHES[q] s = UNIQUE_5[q] if s: return s p = (c1 & 0xff) * (c2 & 0xff) * (c3 & 0xff) * (c4 & 0xff) * (c5 & 0xff) return hash_function(p) #Original code. Uses the eval5 function on all 5 card combinations of the inputted 7 cards. def eval7(hand): return min(eval5(x) for x in itertools.combinations(hand, 5)) #Demonstrates the use of the eval5 function by comparing 2 randomly generated hands. Shows that either hand 1 wins,hand 2 wins, or the hands are tied. def one_round5(): # shuffle a deck deck = list(DECK) random.shuffle(deck) # draw two hands hand1 = deck[:5] hand2 = deck[5:10] # evaluate the hands score1 = eval5(hand1) score2 = eval5(hand2) # display the winning hand hand1 = '[%s]' % ' '.join(hand1) hand2 = '[%s]' % ' '.join(hand2) if score1 < score2: print '%s beats %s' % (hand1, hand2) elif score1 == score2: print '%s ties %s' % (hand1, hand2) else: print '%s beats %s' % (hand2, hand1) #Shows the evaluation of two randomly generated 7 card hands (5 from the community pool and 2 for each player). Will display if hand 1 wins, hand 2 wins, or the two hands are tied. def one_round7(): # shuffle a deck deck = list(DECK) random.shuffle(deck) # draw community and two hands community = deck[:5] hand1 = deck[5:7] hand2 = deck[7:9] # evaluate the hands score1 = eval7(community + hand1) score2 = eval7(community + hand2) # display the winning hand community = '[%s]' % ' '.join(community) hand1 = '[%s]' % ' '.join(hand1) hand2 = '[%s]' % ' '.join(hand2) print community if score1 < score2: print '%s beats %s' % (hand1, hand2) elif score1 == score2: print '%s ties %s' % (hand1, hand2) else: print '%s beats %s' % (hand2, hand1) print #Shows the evaluation of three randomly generated 7 card poker hands (5 from the community pool and 2 for each players' hand). Will display that hand 1 wins, hand 2 wins, hand 3 wins, all hands are tied, hand 1 and hand 2 tied, hand 1 and hand 3 tied, or hand 2 and hand 3 tied. def one_round73(): # shuffle a deck deck = list(DECK) random.shuffle(deck) # draw community and two hands community = deck[:5] hand1 = deck[5:7] hand2 = deck[7:9] hand3 = deck[9:11] # print ina[1] # evaluate the hands score1 = eval7(community + hand1) score2 = eval7(community + hand2) score3 = eval7(community + hand3) # display the winning hand community = '[%s]' % ' '.join(community) hand1 = '[%s]' % ' '.join(hand1) hand2 = '[%s]' % ' '.join(hand2) hand3 = '[%s]' % ' '.join(hand3) print community # more if statements necessary to determine winner if (score1 < score2) & (score1 < score3): print '%s beats %s and %s' % (hand1, hand2, hand3) elif (score2 < score1) & (score2 < score3): print '%s beats %s and %s' % (hand2, hand1, hand3) elif (score3 < score1) & (score3 < score2): print '%s beats %s and %s' % (hand3, hand1, hand2) elif (score1 == score2) & (score1 == score3): print '%s ties %s and %s' % (hand1, hand2, hand3) elif score1 == score2: print '%s ties %s' % (hand1, hand2) elif score1 == score3: print '%s ties %s' % (hand1, hand3) elif score3 == score2: print '%s ties %s' % (hand3, hand2) #This function allows the user to choose which evaluation comparison they want to run, all while looping till the user wants to exit. def use_eval(): #run is to make sure the program loops, loop_7 performs the same function for 7 card evaluations. run = 1 print '\nThis program performs evaluations on poker hands for 5 card or texas holdem poker games' while run: #get the input of the user into inp. print '\nPress 1 for a five card evaluation, 2 for a seven card evaluation, and 3 to quit' inp = raw_input() #5 card eval for 2 players if inp == '1': one_round5() #7 card eval loop begins, user must choose whether to evaluate hands for 2 or 3 players. elif inp == '2': loop_7 = 1 while loop_7: #second input into in7 for 7 card hands print '\nPress 1 for two players or 2 for three players' in7 = raw_input() #7 card eval for 2 players if in7 == '1': one_round7() loop_7 = 0 #7 card eval for 3 players elif in7 == '2': one_round73() loop_7 = 0 #Loop to beginning if input is not valid else: print '\nInvalid input, try again' #Quit the program elif inp == '3': run = 0 #loop to beginning if input not valid else: print '\nInvalid input, try again' if __name__ == '__main__': #run the program use_eval()
b2393ed769bcbdad5fbde2f05d78df9cab4d4521
Maria16pca111/ProblemSolving
/UnsortedArray/indices_which_adds_x.py
549
3.796875
4
#Return the Indices of Values which adds upto x def Subset_Pair_X(A,a,X): for x in A: for y in a: if(x+y==X): print x,y return 0 def subset_adds_return_indices(array1,array2,x): Count=0 for x in array1: for y in array2: if(Subset_Pair_X(array1,array2,x)==True): Count+=1 print(array1[x],array2[y]) return False array1=[1,2,3,4,5] array2=[1,3,5,6] x=4 subset_adds_return_indices(array1,array2,x)
d4695a65abde936e6d93920096cba3f57fbeeb18
gabriellaec/desoft-analise-exercicios
/backup/user_086/ch75_2019_09_25_18_28_00_210703.py
569
3.546875
4
def eh_primo(numero): impar=3 if numero==0 or numero==1: return False if numero==2: return True if numero%2==0: return False while impar<numero: if numero%impar==0: return False impar+=2 return True def verifica_primos(listanum): dicionario=dict() i=0 while i<len(listanum): numero=eh_primo(listanum[i]) if numero==True: dicionario[listanum[i]]=True else: dicionario[listanum[i]]=False return dicionario
079950570c5dada0298c509d350d7c9e13c88b4d
Hadiyaqoobi/NYUx
/callcoster.py
1,635
4.21875
4
""" Description Write a program that computes the cost of a long-distance call. The cost of the call is determined according to the following rate schedule: • Any call started between 8:00 A.M. and 6:00 P.M., Monday through Friday, is billed at a rate of $0.40 per minute. • Any call starting before 8:00 A.M. or after 6:00 P.M., Monday through Friday, is charged at a rate of $0.25 per minute. • Any call started on a Saturday or Sunday is charged at a rate of $0.15 per minute. The input will consist of the day of the week, the time the call started, and the length of the call in minutes. The output will be the cost of the call. Notes: 1. The time is to be input as 4 digit number, representing the time in 24-hour notation, so the time 1:30 P.M. is input as 1330 2. The day of the week will be read as one of the following three character string: ‘Mon’, ‘Tue’, ‘Wed’, ‘Thr’, ‘Fri’, ‘Sat’ or ‘Sun’ 3. The number of minutes will be input as a positive integer. For example, an execution could look like this: Enter the day the call started at: Fri Enter the time the call started at (hhmm): 2350 Enter the duration of the call (in minutes): 22 This call will cost $5.50 """ import math rate = .40 print("Enter the day the call started at: ") day = input() print("Enter the time the call started at (hhmm): ") start = int(input()) if day == "Sat" or day == "Sun": rate = .15 elif start <= 600 or start >= 1800: rate = .25 print("Enter the duration of the call (in minutes): ") minutes = int(input()) cost = rate * minutes print("This call will cost $%2.2f" % cost)
b86366954df9868841916c54bba6f90e804ed910
Shanshan-IC/lintcode_python
/dfs/423_valid_parentheses.py
608
3.921875
4
class Solution: """ @param s: A string @return: whether the string is a valid parentheses """ def isValidParentheses(self, s): if s is None or len(s) == 0: return True st = [] for ss in s: if ss == '(' or ss == '[' or ss == '{': st.append(ss) else: if len(st) == 0: return False if ss == ']' and st[-1] != '[' or ss == '}' and st[-1] != '{' or ss == ')' and st[-1] != '(': return False st.pop() return len(st) == 0
d0027c35701927b550aba50143708a1c9a6996ce
ivSaav/Programming-Fundamentals
/RE07/translate.py
287
4.03125
4
def translate(astring, table): # translates a given string 'astring' using a translation table for char in astring: for atuple in table: if atuple[0] == char: result = astring.replace((atuple[0]), str(atuple[1])) return result
082e8efa71c1d28df3a71f857124ecdfa8a65ca7
yang4978/Hackerrank_for_Python
/Practice for Python/Strings/09_designer_door_mat.py
409
3.515625
4
#https://www.hackerrank.com/challenges/designer-door-mat/problem if __name__ == '__main__': parameter = list(map(int,input().split())); N = parameter[0]; M = parameter[1]; for i in range(N//2): c = '.|.' print((c*(2*i+1)).center(M,'-')); print('WELCOME'.center(M,'-')); for i in range(N//2,0,-1): c = '.|.' print((c*(2*i-1)).center(M,'-'));
a0b426454b0c58358ce4f6b4d68f0ef99f4f879e
EGhamgui/Segmentation-of-Skin-Lesions
/Morphological.py
642
3.828125
4
#--------------------------Morphological------------------------# ## Import Libraries import numpy as np import scipy ## The function def Morphological(im): """ This function is the morphological filling operation on the binary image. It takes an image as input and returns a filled image""" # Make a copy of the image to inverse its values im1 = np.copy(im) im1[im==0]=1 im1[im==1]=0 # Perform the morphological filling res = scipy.ndimage.morphology.binary_fill_holes(im1) # Re-inverse the image res1 = np.copy(res) res1[res==0]=1 res1[res==1]=0 return(res1)
8f85af19209361a843a626fda9619c52ec5a6cd6
viverbungag/Codewars
/Multiples of 3 or 5.py
106
3.859375
4
def solution(number): return sum([x for x in range(number-1, 2, -1) if x%3 == 0 or x%5 == 0])
8726ce60c6dcccca6455adaa94d2fea0b9b86698
jwu424/Leetcode
/UniquePaths.py
1,140
4.125
4
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). # How many possible unique paths are there? # 1. Use math formula to get. Total steps: m+n-2, choose n-1 steps to go down. # Note: m = max(m, n); n = min(m, n) # 2. DP. except first row and first column, others equals to the sum of above and previous elem. # Time: O(mn) class Solution: def uniquePaths1(self, m: int, n: int) -> int: m, n = max(m, n), min(m, n) upper = 1 lower = 1 for elem in range(m, m+n-1): upper *= elem for elem in range(1, n): lower *= elem return upper // lower def uniquePaths2(self, m: int, n: int) -> int: if n == 1 or m == 1: return 1 res = [[1 for x in range(n)] for x in range(m)] for i in range(1, m): for j in range(1, n): res[i][j] = res[i-1][j] + res[i][j-1] return res[-1][-1]
7e19babd92ca5f7c2f00e65e4e6239095e0310eb
cudjoeab/python_fundamentals2
/exercise7.py
1,327
4.15625
4
# # make some code DRY # #function to input the distance and time # print("How far did they run (in metres)?") # distance = float(input()) # print("How long (in minutes) did they run take to run {} metres?".format(distance)) # time = float(input()) # def distance_time(runner): # return distance , time # print(distance_time(runner)) # def speed(runner): # speed = distance / (time * 60) # return speed # print (speed(runner)) #create method, cleans up the first question def get_speed(person_number): print(f"How far did person {person_number} run (in metres)?") #using float string distance = float(input()) print(f"How long (in minutes) did person 1 run take to run {distance} metres?") mins = float(input()) secs = mins * 60 speed = distance / secs return speed speed1 = get_speed(1) speed2 = get_speed(2) speed3 = get_speed(3) if speed3 > speed2 and speed3 > speed1: print("Person 3 was the fastest at {} m/s".format(speed3)) elif speed2 > speed3 and speed2 > speed1: print("Person 2 was the fastest at {} m/s".format(speed2)) elif speed1 > speed3 and speed1 > speed2: print("Person 1 was the fastest at {} m/s".format(speed1)) elif speed1 == speed2 and speed2 == speed3: print("Everyone tied at {} m/s".format(speed1)) else: print("Well done everyone!")
c7b6b0e75d0bfd852d352f35783cd9584e5f45d9
reader2330/Pruebas
/PythonPrueba/addFuncionsinRecusividad.py
305
3.671875
4
def calculatePlus(i): value = 0 while i > 0: value += i i = i-1 return value def init(): try: value = 0 n = input("Dame una n: ") print("La funcion F(x) da :", calculatePlus(int(n))) except TypeError: print("Caracter incorrecto") init()
db94b653674d0492cf403bd954054d01247af511
yifanzhou106/leetcode
/DesignHashMap.py
2,614
3.859375
4
class Node(object): def __init__(self, key, val): self.key = key self.val = val self.next = None class MyHashMap(object): def __init__(self): """ Initialize your data structure here. """ self.size = 1000 self.hashlist = [None] * self.size def put(self, key, value): """ value will always be non-negative. :type key: int :type value: int :rtype: None """ index = key % self.size if not self.hashlist[index]: singlenode = Node(key, value) self.hashlist[index] = singlenode else: singlenode = self.hashlist[index] while singlenode.next: if key == singlenode.key: singlenode.val = value return singlenode = singlenode.next if key == singlenode.key: singlenode.val = value return singlenode.next = Node(key, value) def get(self, key): """ Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key :type key: int :rtype: int """ index = key % self.size if not self.hashlist[index]: return -1 else: singlenode = self.hashlist[index] while singlenode.next: if key == singlenode.key: return singlenode.val singlenode = singlenode.next if key == singlenode.key: return singlenode.val return -1 def remove(self, key): """ Removes the mapping of the specified value key if this map contains a mapping for the key :type key: int :rtype: None """ index = key % self.size if self.hashlist[index]: singlenode = self.hashlist[index] prenode = singlenode if key == singlenode.key: self.hashlist[index] = singlenode.next return singlenode = singlenode.next while singlenode: if key == singlenode.key: prenode.next = singlenode.next return prenode = singlenode singlenode = singlenode.next # Your MyHashMap object will be instantiated and called as such: # obj = MyHashMap() # obj.put(key,value) # param_2 = obj.get(key) # obj.remove(key)
95bd1312adecd7fd1466b037bec422f640b62dd7
AlexCSoh/dev-challenge
/chapter3_exercises.py
484
3.515625
4
# Exercises for chapter 3: #Ex 3.5 def print_box(): part1 = "+ - -" part2 = "- -" part3 = "+" part4 = "| " part5 = "|" print part1,part2,part1,part2,part3 print part4,part4,part5 print part4,part4,part5 print part4,part4,part5 print part4,part4,part5 print part1,part2,part1,part2,part3 print part4,part4,part5 print part4,part4,part5 print part4,part4,part5 print part4,part4,part5 print part1,part2,part1,part2,part3 print print_box print_box() # Name:
9fc1f161947c44069d99c08e909117c9f1617385
sgygayoung/ImPython
/Lec1005/Lec1005/Lec1005.py
2,078
4.03125
4
#coding:cp949 #Class class A(): def __init__(self, a): self.a = a def show(self): print("show a:",self.a) class B(A): def __init__(self, b, **arg): super().__init__(**arg) self.b=b def show(self): print("show b:",self.b) super().show() class C(A): def __init__(self, c,**arg): super().__init__(**arg) self.c = c def show(self): print("show c:",self.c) super().show() class D(B,C): def __init__(self,d,**arg): super().__init__(**arg) self.d=d def show(self): print("show d:",self.d) super().show() data = D(a=1,b=2,c=3,d=4) data.show() print() #Private Variables class Mapping: def __init__(self, iterable): self.items_list = [] self.__update(iterable) def update(self, iterable): for item in iterable: self.items_list.append(item) #private copy of original update() method __update = update class MappingSubclass(Mapping): def update(self,keys,values): #provides new signature for update() #but does not break __init__() for item in zip(keys,values): self.items_list.append(item) print(item) list = ['a','b','c'] Test_Class = MappingSubclass(list) print(Test_Class.items_list) # Test_Class.__update(['1']) : Ұ Private̱ !!!!!!!! Test_Class.update(['name','phone','address'],['','01028881898',' ']) print(Test_Class.items_list) print() #ó import sys number1 = float(input('enter a number:')) number2 = float(input('enter a number:')) try: result = number1/number2 print(result) except ZeroDivisionError as e: print(e) print('The answer is infinity') except: error = sys.exc_info()[0] # ߻ Ʃ÷ ȯ classtype, value, traceback = sys.exc_info() print(classtype) print(value) print(error) sys.exit() print('i am sorry something went wrong') finally: print('Done') print()
a6787f4f19cbe43380ad16dcf75db318271a0386
skarthikeyan85/learn
/python/format.py
195
3.921875
4
#!/usr/bin/env python def main(): print("%s\t%s\t%s" % ( 'a', 'a^2', 'a^3')) for x in range(1,6): print("%d\t%d\t%d" % ( x, x*x, x*x*x)) if __name__ == '__main__': main()
20c6359b7c6d460bb387d0e4692d716a53386387
AbhishekC04/mycode
/netfacd/interface_reader.py
1,136
3.5
4
#!/usr/bin/env python3 import netifaces print(netifaces.interfaces()) ## function to return IP Address def ip_addr(netifaces.interfaces()): ips = set() interfaces = netifaces.interfaces() for interface in interfaces: addresses = netifaces.ifaddresses(interface) ip_return_addr = netifaces.ifaddresses(ip_addr)[netifaces.AF_INET][0]['addr'] print(ip_return_addr) return (ips) def main(): for i in netifaces.interfaces(): print('\n**************Details of Interface - ' + i + ' *********************') try: print('MAC Address: ', end='') # This print statement will always print MAC without an end of line print(netifaces.ifaddresses(i)[netifaces.AF_LINK][0]['addr']) #Prints the MAC Addr print('IP Address: ', end='') # This print statement will always print MAC without an end of line print(netifaces.ifaddresses(i)[netifaces.AF_INET][0]['addr']) #Prints the IP Addr except: print('Could not collect adapter information') ip_addr(netifaces.interfaces()) main()
4fa96cebf17f0c0359669057ef920f0d79ffef56
Sk0uF/Algorithms
/py_algo/number_theory/basic_part_1/the_final_fight.py
3,319
3.5625
4
""" Codemonk link: https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-1/practice-problems/algorithm/the-final-fight-6/ Fatal Eagle has had it enough with Arjit aka Mr. XYZ who's been trying to destroy the city from the first go. He cannot tolerate all this nuisance anymore. He's... tired of it. He decides to get rid of Arjit and his allies in a war. He knows that Arjit has N people fighting for him, so he brings his own N people in the war to face him. (So, there will be 2 * N people fighting in this war!). He knows for him to win the war against his enemy, members of his army should be present before the members of Arjit come up in the battlefield - that is to say, whenever a member of Arijt's army comes in the battlefield, there should already be a member of his own army there to handle him. (In short, the number of his army members should never be less than the number of Arjit's army members in the field!). If he figures out the number of ways such such sequences can be formed, the good will be able to conquer evil yet again. Help Fatal Eagle in figuring it out to defeat Arjit - once and for all. Input - Output: There is only one integer in the only line of the input, denoting the value of N. Print the number of valid sequences. Since the output might be very big, print it modulo 10^9+9. Sample input: 3 Sample Output: 5 """ """ That's a pure math's problem. The total amount of combinations if we could place the first army wherever we wanted, would be the combinations of picking N out of 2*N positions. 2*N are the total soldiers of both armies. That can be easily calculated by our logic, or, if we already understand the logic behind it, we can directly use the binomial coefficient. From the total amount of combinations we must subtract those that are invalid. How many are those? The answer is bionomial(2n, n+1). If we make the total calculation, we derive the catalan number. 1) bionimial(2n, n+1) = n/(n+1)*bionimial(2n, n). The proof is very easy. 2) bionimial(2n, n) - (bionimial(2n, n+1) = bionimial(2n, n) - n/(n+1)*bionimial(2n, n) = bionimial(2n, n) * [1-n/(n+1)] = 1/(n+1) * bionimial(2n, n) = 1/(n+1) * (2n)!/(n!n!) The above explanation is not THAT straight forward. Another, better way to understand the derivation of the catalan number and the one suggested has been proven in the paper of Rukavicka Josef (2011). Just to give a brief spoil, the catalan number is: 1/(n+1) * bionomial(2n, n). It's like we split the bionomial term in n+1 equal parts and the answer is one of them!! Since our mod is a prime number, we can calculate using the Fermat's little theorem the modulo inverse for n! and n+1 and make the calculation easier. O(logN) for the exponentiations and O(N) for the factorizations. Final complexity: O(N) """ def exponentiate(number, exponent): result = 1 while exponent > 0: if exponent % 2 == 1: result = (number * result) % mod number = (number ** 2) % mod exponent //= 2 return result def factorial(number): temp = 1 for i in range(1, number+1): temp = (temp*i) % mod return temp n = int(input()) mod = 1000000009 a = factorial(2*n) b = exponentiate(factorial(n), mod-2) c = exponentiate(n+1, mod-2) answer = (a*b*b*c) % mod print(answer)
2e912a6d3cef24a0209bcf21e0a5e4919acd8ef7
Hug0Albert0/Introduccion_Python
/ejercicio1.py
601
3.65625
4
import math #Cuadrado lado = 20 area_cuadrado = lado * lado #area_cuadrado = pow(lado, 2) mensaje_cuadrado = """ El area del cuadrado de lado {lado}cm es igual a {area_cuadrado}cm2 """.format( lado = lado, area_cuadrado = area_cuadrado ) print(mensaje_cuadrado) base = 5.90 altura = 15.75 area_triangulo = round((base * altura) / 2, 2) print(area_triangulo) import math print("Si fuera una esfera") pi = math.pi radio = 100 volumen_esfera = round(4 * (pi * pow(radio, 3)) / 3, 2) print(volumen_esfera) print("Si fuera un circulo") area_circulo = pi * (radio * radio) print(area_circulo)
5e1c3c3e4f15e0a840cab9543997fc470ab2979c
aidonker/buscar_numeroprimo
/buscar_primo.py
1,335
3.984375
4
""" Buscar un numero primo, con un numero determinado ingresado por pantalla """ n = int(input("Ingrese hasta que numero quiere hallar los numeros primos: ")) #Ingreso del dato contador = 0 if n > 0: #Comprueba si el numero ingresado sea ENTERO POSITIVO for i in range(2, n + 1): #Empieza i desde 2 hasta el numero ingresado creciente = 2 #Variable para dividir, y comprobar si es una division exacta esPrimo = True #Consideremos todos los numeros PRIMOS while esPrimo and creciente < i: #Mientras esPrimo es TRUE y creciente menor a i(El numero de del arreglo) if i % creciente == 0: #Si el modulo de i es igual a 0(Division exacta) esPrimo = False #esPrimo cambia a ser Falso #print(f"{i} no es un numero primo") Si desea mostrar el numero que NO es primo else: creciente += 1 #Creciente aumenta en 1, si el residuo es 0 if esPrimo: #Si esPrimo es verdadero (True) print(f"{i} es numero primo") #Imprime todos los numeros primos contador += 1 #Cuenta cuantos numeros primos son else: print("El numero ingresado no es correcto, porfavor ingrese nuevamente") #Imprime error, si el numero no es entero y no es positivo print(f"{contador}, numeros son primos menores a {n}.")
1650f09a15ac7751dd2a01683dd458a477dd76d8
WalesMei/StudyProgramming
/Python/Prime.py
306
3.90625
4
# -*- coding: UTF-8 -*- import math def ifprime(num): ip = True for i in range(math.sqrt(num)): if num % i == 0: ip = False break else: continue return ip def allprime(start, end): primes = [] for num in range(start, end): if ifprime(num) == True: primes.append(num) print(primes)
050d7b15e27d41bf65189fff9bd814d8e876c276
moritzkrusche/Udacity-projects
/movies website/media.py
756
3.84375
4
import webbrowser # class to create instances of movies displayed on the web page class Movie(): """ This class provides a way to store movie-related information; (1) movies title, (2) short storyline, (3) poster image url and (4) youtube trailer url. Poster is displayed via deeplink; trailer shown on click. """ def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): self.title = movie_title self.storyline = movie_storyline self.poster_image_url = poster_image self.trailer_youtube_url = trailer_youtube # opens a trailer of the movie when it's label is clicked through a popup on the same page. def show_trailer(self): webbrowser.open(self.trailer_youtube_url)
f4acbea4aa7b152fd292d4f5b36e11ef1cba97d3
sajad-lp16/factory_designpattern
/abstract_factory_method.py
2,142
4.625
5
# Author Sajad """ This design pattern is used to create a family of objects which they are connected together """ from abc import ABCMeta, abstractmethod # main abstract class class CoffeeFactory(metaclass=ABCMeta): @abstractmethod def coffee_without_milk(self): pass @abstractmethod def coffee_with_milk(self): pass # This concrete class uses the main abstract class class FrenchCoffeeFactory(CoffeeFactory): def coffee_without_milk(self): return FrenchEspresso() def coffee_with_milk(self): return FrenchCappuccino() # The same as previous class ItalianCoffeeFactory(CoffeeFactory): def coffee_without_milk(self): return ItalianEspresso() def coffee_with_milk(self): return ItalianCappuccino() # Another abstract class which they are # used inside previous classes objects class CoffeeWithoutMilk(metaclass=ABCMeta): @abstractmethod def prepare(self): pass # The same as previous class CoffeeWithMilk(metaclass=ABCMeta): @abstractmethod def serve(self): pass class FrenchEspresso(CoffeeWithoutMilk): def prepare(self): print('preparing ', self.__class__.__name__) class ItalianEspresso(CoffeeWithoutMilk): def prepare(self): print('preparing ', self.__class__.__name__) class FrenchCappuccino(CoffeeWithMilk): def serve(self): print(self.__class__.__name__, ' is served with sheep\'s milk on ', CoffeeWithoutMilk.__name__) class ItalianCappuccino(CoffeeWithMilk): def serve(self): print(type(self).__name__, ' is served with cow\'s milk on', CoffeeWithoutMilk.__name__) # Client section class CoffeeStore: def make_coffee(self): for factory in [ItalianCoffeeFactory(), FrenchCoffeeFactory()]: self.factory = factory self.coffee_without_milk = self.factory.coffee_without_milk() self.coffee_with_milk = self.factory.coffee_with_milk() self.coffee_without_milk.prepare() self.coffee_with_milk.serve() coffee = CoffeeStore() coffee.make_coffee()
b5aa307e882ccb2d4812d17e0650d409df5cf4ad
oormaman/JoBot
/server/jobsDBLogic.py
5,189
3.578125
4
import sqlite3 from datetime import datetime from server import initializationDb database_path = initializationDb.database_path def insert_job(new_job): conn = sqlite3.connect(database_path) c = conn.cursor() with conn: c.execute("INSERT INTO Student_Jobs(name,link,description,site_name,upload_date,affiliation1,affiliation2) " "VALUES ( :name, :link, :description, :site_name,:upload_date,:affiliation1,:affiliation2)", { 'name': new_job.job_name,'link': new_job.link,'description': new_job.description , 'site_name': new_job.site_name, 'upload_date':datetime.now().strftime("%x"+" %X"),'affiliation1':new_job.affiliation1,'affiliation2':new_job.affiliation2}) def get_exist_job(user_id_in_telegram): conn = sqlite3.connect(database_path) c = conn.cursor() last_job_id_in_db=int(get_last_job_id()) with conn: # Get the last job id that the user viewed: stmt = "SELECT * FROM Users WHERE userId='" + str(user_id_in_telegram) + "'" print(stmt) job_list=[] c.execute(stmt) user_tupple = c.fetchall() last_job_that_the_user_viewed = user_tupple[0][2] total_job_that_the_user_viewed= user_tupple[0][3] user_affiliation = user_tupple[0][5] # Check if we have another job in db that the user has not seen: while int(last_job_that_the_user_viewed) < int(last_job_id_in_db): job_that_the_user_didnt_viewed = str(int(last_job_that_the_user_viewed) + 1) last_job_that_the_user_viewed=job_that_the_user_didnt_viewed stmt = "UPDATE Users SET lastJobThatTheUserViewed='" + str( last_job_that_the_user_viewed) + "' WHERE userId='" + str(user_id_in_telegram) + "'" c.execute(stmt) # update_last_job_that_the_user_viewed(last_job_that_the_user_viewed, user_id_in_telegram) stmt = "SELECT affiliation FROM Users WHERE userId='" + str(user_id_in_telegram) + "'" c.execute(stmt) job_details = get_job_tupple(job_that_the_user_didnt_viewed,user_affiliation) if job_details is not None: total_job_that_the_user_viewed= str(int(total_job_that_the_user_viewed) + 1) stmt = "UPDATE Users SET totalJobThatTheUserViewed='" + total_job_that_the_user_viewed + "' WHERE userId='" + str(user_id_in_telegram) + "'" c.execute(stmt) job_list.append(job_details) return job_list def update_last_job_that_the_user_viewed(last_job_that_the_user_viewed,user_id_in_telegram): conn = sqlite3.connect(database_path) c = conn.cursor() with conn: stmt = "UPDATE Users SET lastJobThatTheUserViewed='" + str( last_job_that_the_user_viewed) + "' WHERE userId='" + str(user_id_in_telegram) + "'" c.execute(stmt) def update_total_jobs_that_the_user_viewed(total_job_that_the_user_viewed,user_id_in_telegram): conn = sqlite3.connect(database_path) c = conn.cursor() with conn: stmt = "UPDATE Users SET totalJobThatTheUserViewed='" + str(int(total_job_that_the_user_viewed)+1) + "' WHERE userId='" + str(user_id_in_telegram) + "'" c.execute(stmt) def get_job_tupple(job_id,user_affiliation): conn = sqlite3.connect(database_path) c = conn.cursor() with conn: stmt = "SELECT * FROM Student_Jobs WHERE (id='" + job_id + "'"+" AND affiliation1='"+user_affiliation+"')" print(stmt) c.execute(stmt) job_tupple = c.fetchone() print(job_tupple) return job_tupple def get_first_job_id(): conn = sqlite3.connect(database_path) c = conn.cursor() with conn: stmt = "SELECT MIN(id) FROM Student_Jobs" c.execute(stmt) last_job_id=c.fetchone()[0] return last_job_id # return 1 def get_last_job_id(): conn = sqlite3.connect(database_path) c = conn.cursor() with conn: # Get the last job id in Jobs table stmt = "SELECT MAX(id) FROM Student_Jobs" c.execute(stmt) last_job_id=c.fetchone()[0] return last_job_id def check_if_job_already_exist_in_db(job_link): conn = sqlite3.connect(database_path) c = conn.cursor() with conn: stmt = "SELECT * FROM Student_Jobs WHERE link='" + job_link + "'" print(stmt) c.execute(stmt) job_tupple = c.fetchone() if job_tupple is None: return False return True def get_all_job_links_in_db(): conn = sqlite3.connect(database_path) c = conn.cursor() with conn: stmt = "SELECT link FROM Student_Jobs" print(stmt) c.execute(stmt) job_link_tupple = c.fetchall() print(type(job_link_tupple)) return job_link_tupple def delete_job_from_db(job_link): conn = sqlite3.connect(database_path) c = conn.cursor() with conn: stmt = "DELETE FROM Student_Jobs WHERE link='" + job_link + "'" print(stmt) c.execute(stmt)
cd47484361864d9f27f6133c54484d9739ea071f
Anthony-Harrison/QA_Python
/Practice/is_it_a_prime.py
276
4.0625
4
test = int(input("Enter a number ")) if test > 1: for i in range(2, test//2): if (test % i) == 0: print(test, "is not a prime number") break else: print(test, "is a prime number") else: print(test, "is not a prime number")
5b68cf46876436e3d984e0ddb57af5dda54a348c
G-g-s9/alien_invasion
/alien.py
2,598
3.6875
4
import pygame from pygame.sprite import Sprite #不止一个时需要 class Alien(Sprite): '''初始化外星人相应属性并确定其起始位置''' def __init__(self,ai_settings,screen): #ai_settings过渡传参,本类中无调用,但要写进属性中(后来加了个外星人高设置,这里就用上了) super().__init__() #继承Sprite的属性方法 self.screen = screen #传参屏幕属性 self.ai_settings = ai_settings #传参设置属性 #外星人图片载入及其初始位置确立 # ~ self.image = pygame.image.load("images/alien.png") #加载外星人图 self.image = pygame.image.load("images/monster.png") #加载团子图(置换上一条使用) #图片锁定比例变换尺寸 self.rect = self.image.get_rect() #获得外星人图片rect属性 self.scale = float(self.rect.width)/float(self.rect.height) #记录原图比例 self.size = int(ai_settings.alien_h*self.scale),ai_settings.alien_h #调整为高49px,宽随比例给出 self.image = pygame.transform.scale(self.image,self.size) # ~ self.image.set_alpha(2) #失败了这个,后面再优化了。。。本来想让外星人透明点 self.rect = self.image.get_rect() #获得实际显示外星人图片rect属性 self.rect.x = self.rect.width #这里x坐标,在外星人群建立后失效】初始x坐标,屏幕左上角隔着一个外星人的宽 self.rect.y = self.rect.height #初始y坐标,屏幕左上角隔着一个外星人的高 self.x = float(self.rect.x) #x坐标浮点化,可相对微调 def check_edges(self): '''检查边缘-碰壁响应,如外星人位于边缘就返回True''' screen_rect = self.screen.get_rect() #获取屏幕rect属性 #如触及甚至超出屏幕范围 if self.rect.right >= screen_rect.right: return True elif self.rect.left <=0: return True def update(self,ai_settings): '''屏幕内左右移动外星人,碰壁反向运动''' self.x += self.ai_settings.alien_speed_factor * \ self.ai_settings.fleet_direction #浮点型位置,运动速度和方向,左负右正 self.rect.x = self.x #传给rect属性位置(截取了整数部分 def blitme(self): '''指定位置绘制外星人''' self.screen.blit(self.image,self.rect) #将图片绘制到屏幕指定的坐标(上面那个rect的左上角坐标位置)
e9023f76f82b8f067f6ac4f5426fc0a2344819df
kshah17/Python
/python_expamples.py
894
4.25
4
''' age = 25 year = 1995 print (f"john is {age} years old and born in {year}") print (f"john is\ {{age}} years old and born in {year}") price = 3.99 print(type(price)) price = 3.99 price_of_type = type(price) print(price_of_type) age = 21 type_of_age = str(age) print(type_of_age) word1 = "Good" word2 = "Day" word3 = "Dave" sentence = word1 + " " + word2 + " " + word3 print(sentence) number1 = input("enter whole number: ") number2 = input("decimal number: ") integer_number = int(number1) float_number = float(number2) rounded_number = int(round(float_number)) print(number1) print(number2) print(rounded_number) name = "Pep Guardogiola" age = 3 bark = True tweet = False print("My pet is called", name, ", He is", age, "years old.") print(f"My pet is called {name}, He is {age} years old.") print(f"Statement: {name}, barks {bark}") print(f"Statement: {name}, tweets {tweet} ") '''
04d5e9634a10599dd56355e95aa364f1aeb338f8
Imafikus/ppj
/3cas/2.py
660
4.09375
4
#!/usr/bin/python3 import sys import re def main(): poruka = 'Danas je divan dan' #ignorisi velika/mala slova, nadji sve alfanumerike vise puta match = re.match(r'(?i)(\w+\s+)+', poruka) if match: print(match.group()) else: print('nema poklapanja') # trazim prvu rec koje pocinju na d m = re.search(r'\bd([a-z]+)', poruka) if m: print(m.group()) # trazim sve reci koje pocinju na d, sad mora u zagradu m = re.findall(r'\b(d([a-z]+))', poruka) if m: print(m) # prosto menjanje stringa print(poruka.replace('Danas', 'Sutra')) if __name__ == "__main__": main()
1777d63653fb33f5e7d116e7c77a1d72bd34344e
webscraping-python/BeautifulSoup-Course
/main.py
1,624
3.859375
4
from bs4 import BeautifulSoup as bs import requests import re url = "https://keithgalli.github.io/web-scraping/example.html" r = requests.get(url) # Convertir a un objeto de beautiful soup #soup = bs(r.content) soup = bs(r.content, 'lxml') #print(soup.prettify()) # find and find_all first_header = soup.find("h2") #print(f' first_header {first_header}' ) headers = soup.find_all("h2") #print(f' headers {headers}') # Pasar una lista de elementos first_header = soup.find(["h1", "h2"]) headers = soup.find_all(["h1", "h2"]) #print(f' first_header {first_header}' ) #print(f' headers {headers}') # Podemos pasarale atributos a find/find_all paragraph = soup.find_all("p", attrs={"id": "paragraph-id"}) #print(paragraph) # Podemos anidar llamadas body = soup.find('body') div = body.find('div') header = div.find('h1') #print(header) # Podemos buscar una cadena específica en find/find_all paragraphs = soup.find_all("p", string=re.compile("Some")) #print(paragraph) headers = soup.find_all("h2", string=re.compile("(H|h)eader")) #print(header) #select (CSS selector) #print(soup.body.prettify()) content = soup.select("div p") #print(content) paragraphs = soup.select("h2 ~ p") bold_text = soup.select("p#paragraph-id b") paragraphs = soup.select("body > p") for paragraph in paragraphs: paragraph.select("i") #Obtener diferentes propiedades del HTML header = soup.find("h2") print(header.string) div = soup.find("div") print(div.prettify()) print(div.get_text()) link = soup.find("a") print(link['href']) paragraphs = soup.select("p#paragraph-id") print(paragraphs[0]['id'])
ea98d6a75ecff0147b8f46105e8fb99c5a538418
bvo773/PythonFun
/tutorialspy/basic/tuple.py
311
3.703125
4
# Tuple - Like a List, but it's 'Immutable'. Can't be modified. # tupleName = (object1, object2, object3) # Tuple to store historic World War Dates historicWarDates = (1914, 1939) historicWarDates[0] # Accessing an element in the tuple del(historicWarDates) # Deleting a tuple by using python provided del()
df5d684a4f7ec604af065d9ca29f7479525892d5
h4hany/yeet-the-leet
/algorithms/Medium/1344.angle-between-hands-of-a-clock.py
1,010
3.640625
4
# # @lc app=leetcode id=1344 lang=python3 # # [1344] Angle Between Hands of a Clock # # https://leetcode.com/problems/angle-between-hands-of-a-clock/description/ # # algorithms # Medium (61.26%) # Total Accepted: 41.7K # Total Submissions: 68K # Testcase Example: '12\n30' # # Given two numbers, hour and minutes. Return the smaller angle (in degrees) # formed between the hour and the minute hand. # # # Example 1: # # # # # Input: hour = 12, minutes = 30 # Output: 165 # # # Example 2: # # # # # Input: hour = 3, minutes = 30 # Output: 75 # # # Example 3: # # # # # Input: hour = 3, minutes = 15 # Output: 7.5 # # # Example 4: # # # Input: hour = 4, minutes = 50 # Output: 155 # # # Example 5: # # # Input: hour = 12, minutes = 0 # Output: 0 # # # # Constraints: # # # 1 <= hour <= 12 # 0 <= minutes <= 59 # Answers within 10^-5 of the actual value will be accepted as correct. # # # class Solution: def angleClock(self, hour: int, minutes: int) -> float:
42944114b3ce81fff02313285233e6424a172cbb
Maxondria/pythonic-concepts
/file_objects/file-demo-context-manager.py
1,193
3.796875
4
with open('test.txt', 'r') as f: # print(f.name, f.mode) # READ ALL CONTENT AT ONCE # f_contents = f.read() # print (f_contents, end='') # READ LINES INSTEAD - (Somehow efficient for big files) # f_lines = f.readlines() # print(f_lines, end='') # READ ONLY THE FIRST LINE # f_line = f.readline() # print(f_line, end='') # LOOP THROUGH EACH LINE # for line in f: # Iterating thru these lines one by one - Efficient # print(line, end='') # READ FILES IN CHUNKS - (Most Efficient) # first_hundred_chars = f.read(100) # 100 is the number of chars to read # print(first_hundred_chars, end='') # next_hundred_chars = f.read(100) # 100 is the number of chars to read # print(next_hundred_chars, end='') # MORE EFFICIENT CHUNKS - READ SLOWLY UNTIL NOTHING IN FILE size_to_read = 100 f_contents = f.read(size_to_read) # print(f.tell()) # Tells the position where the cursor is at the time in the file # print(f.seek(0)) # Reads well, pushes the cursor back to position 0 on next read() while len(f_contents) > 0: print(f_contents, end='') f_contents = f.read(size_to_read)
10bca4d1ca316634c8a10728ea5675f4f96bd3d8
devang191/algorithms_competitions
/codeforces/problem_set/26A.py
407
3.796875
4
import math def is_prime(n): for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True primes = [] for i in range(2, 3000): if is_prime(i): primes.append(i) n = int(raw_input()) count = 0 for i in range(1, n + 1): divisors = 0 for prime in primes: if i % prime == 0: divisors = divisors + 1 if divisors == 2: count = count + 1 print count
46bb311f095818ae38a85f8b0d1148e55ee71849
keyurbsq/Consultadd
/Task5/ex6.py
339
3.96875
4
""" Read doc.txt file using Python File handling concept and return only the even length string from the file """ with open('doc.txt', 'r') as file: # reading each line for line in file: # reading each word for word in line.split(): if len(word) % 2 == 0: print(word)
7dd8664bdf5a91c5cd43b6b9f950b1c7c9d240ae
sasha-n17/python_homeworks
/homework_4/task_6.py
643
3.609375
4
from itertools import count, cycle # итератор, генерирующий целые числа, начиная с указанного try: n = int(input('Введите число: ')) for el in count(n): if el <= 2 * n: print(el) else: break except ValueError: print('Введено не число!') print() # итератор, повторяющий элементы некоторого списка, определённого заранее test_list = list('PYTHON') c = 0 for el in cycle(test_list): if c >= 2 * len(test_list): break print(el) c += 1
07869ea5487c0f1a3fb87e9d32c6abd6e0589302
minhtruong262/STA-141C-Final-Project
/KNN/knn.py
7,725
3.640625
4
#--------------------------------------------- # Import necessary packages #--------------------------------------------- import numpy as np import pandas as pd import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import time from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import LabelEncoder #---------------------------------------------------- # Make a function that computes success rate with KNN #---------------------------------------------------- def knn_rate(xtrain,ytrain,xtest,ytest,k): """This function takes in a training dataset of features, a training dataset of labels, a testing dataset of features, a testing dataset of labels, and a specified number of neighbors. It will run KNN algorithms on the training set, predict the testing set, compare the results with the true labels, and return success rate.""" prediction = [] count = 0 knn = KNeighborsClassifier(n_neighbors=k) knn.fit(xtrain,ytrain) accu_rate = knn.score(xtest,ytest) return accu_rate #--------------------------------------------- # Spambase Data #--------------------------------------------- # Import spambase.data df = pd.read_csv("spambase.data", header = None) # Split the features and the labels X = df.iloc[:,0:57] y = df.iloc[:,57] # Split dataset into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=5) # Reset the indices X_train = X_train.reset_index(drop=True) X_test = X_test.reset_index(drop=True) y_train = y_train.reset_index(drop=True) y_test = y_test.reset_index(drop=True) # Run the knn_rate function on data using 1 to 25 neighbors accu_list = [knn_rate(X_train,y_train,X_test,y_test,i) for i in range(1,26)] # Make a plot plt.close() plt.rcParams["figure.figsize"] = [10, 8] plt.plot(list(range(1,26)),accu_list,'-o') plt.xticks(np.arange(0, 26, 1.0)) plt.title('Number of Neighbors vs. Success Rate for Spambase Dataset') plt.xlabel('Number of Neighbors') plt.ylabel('Success Rate') plt.grid() plt.savefig('knn_spam.png') # Time the KNN algorithm start = time.time() knn_rate(X_train,y_train,X_test,y_test,1) end = time.time() print("It takes " + str(end - start) + " seconds to run KNN algorithm on spambase dataset with 1 neighbor.") #--------------------------------------------- # Breast Cancer Data #--------------------------------------------- # Import wdbc.data df2 = pd.read_csv("wdbc.data", header = None) # Split the features and the labels X2 = df2.iloc[:,2:32] y2 = df2.iloc[:,1] # Split dataset into training and testing sets X_train2, X_test2, y_train2, y_test2 = train_test_split(X2, y2, test_size=0.2, random_state=5) # Reset the indices X_train2 = X_train2.reset_index(drop=True) X_test2 = X_test2.reset_index(drop=True) y_train2 = y_train2.reset_index(drop=True) y_test2 = y_test2.reset_index(drop=True) # Run the knn_rate function on data using 1 to 25 neighbors accu_list2 = [knn_rate(X_train2,y_train2,X_test2,y_test2,i) for i in range(1,26)] # Make a plot plt.close() plt.rcParams["figure.figsize"] = [10, 8] plt.plot(list(range(1,26)),accu_list2,'-o') plt.xticks(np.arange(0, 26, 1.0)) plt.title('Number of Neighbors vs. Success Rate for Breast Cancer Dataset') plt.xlabel('Number of Neighbors') plt.ylabel('Success Rate') plt.grid() plt.savefig('knn_breast.png') # Time the KNN algorithm start = time.time() knn_rate(X_train2,y_train2,X_test2,y_test2,11) end = time.time() print("It takes " + str(end - start) + " seconds to run KNN algorithm on breast cancer dataset with 11 neighbors.") #----------------------------------------------------- # Adult Dataset #----------------------------------------------------- # Import adult.data df3 = pd.read_csv("adult.data", header = None) # Convert the categorical variables to numerical categorical_features = [1,3,5,6,7,8,9,13] le = LabelEncoder() for i in range(0,len(categorical_features )): new = le.fit_transform(df3[categorical_features[i]]) df3[categorical_features[i]] = new # Split the features and the labels X3 = df3.iloc[:,0:14] y3 = df3.iloc[:,14] # Split dataset into training and testing sets X_train3, X_test3, y_train3, y_test3 = train_test_split(X3, y3, test_size=0.2, random_state=5) # Reset indices X_train3 = X_train3.reset_index(drop=True) X_test3 = X_test3.reset_index(drop=True) y_train3 = y_train3.reset_index(drop=True) y_test3 = y_test3.reset_index(drop=True) # Run the knn_rate function on data using 1 to 25 neighbors accu_list3 = [knn_rate(X_train3,y_train3,X_test3,y_test3,i) for i in range(1,26)] # Make a plot plt.close() plt.rcParams["figure.figsize"] = [10, 8] plt.plot(list(range(1,26)),accu_list3,'-o') plt.xticks(np.arange(0, 26, 1.0)) plt.title('Number of Neighbors vs. Success Rate for Adult Dataset') plt.xlabel('Number of Neighbors') plt.ylabel('Success Rate') plt.grid() plt.savefig('knn_adult.png') # Time the KNN algorithm start = time.time() knn_rate(X_train3,y_train3,X_test3,y_test3,22) end = time.time() print("It takes " + str(end - start) + " seconds to run KNN algorithm on adult dataset with 22 neighbors.") #------------------------------------------------------------ # Madelon Dataset #------------------------------------------------------------ # Read in features/labels training sets and features/labels testing set x_train_m = pd.read_csv("madelon_train.data",header = None,sep = '\s+') y_train_m = pd.read_csv("madelon_train.labels",header = None) x_test_m = pd.read_csv("madelon_valid.data",header = None,sep = '\s+') y_test_m = pd.read_csv("madelon_valid.labels",header = None) # Run the knn_rate function on data using 1 to 25 neighbors accu_list4 = [knn_rate(x_train_m,y_train_m,x_test_m,y_test_m,i) for i in range(1,26)] # Make a plot plt.close() plt.rcParams["figure.figsize"] = [10, 8] plt.plot(list(range(1,26)),accu_list4,'-o') plt.xticks(np.arange(0, 26, 1.0)) plt.title('Number of Neighbors vs. Success Rate for Madelon Dataset') plt.xlabel('Number of Neighbors') plt.ylabel('Success Rate') plt.grid() plt.savefig('knn_madelon.png') # Time the KNN algorithm start = time.time() knn_rate(X_train,y_train,X_test,y_test,21) end = time.time() print("It takes " + str(end - start) + " seconds to run KNN algorithm on madelon dataset with 21 neighbors.") #--------------------------------------------- # Parkinson Data #--------------------------------------------- # Import spambase.data df_parkinson = pd.read_csv("pd_speech_features.csv") # Split the features and the labels X_p = df_parkinson.iloc[:,1:754] y_p = df_parkinson.iloc[:,754] # Split dataset into training and testing sets X_train_p, X_test_p, y_train_p, y_test_p = train_test_split(X_p, y_p, test_size=0.2, random_state=5) # Reset the indices X_train_p = X_train_p.reset_index(drop=True) X_test_p = X_test_p.reset_index(drop=True) y_train_p = y_train_p.reset_index(drop=True) y_test_p = y_test_p.reset_index(drop=True) # Run the knn_rate function on data using 1 to 25 neighbors accu_list5 = [knn_rate(X_train_p,y_train_p,X_test_p,y_test_p,i) for i in range(1,26)] # Make a plot plt.close() plt.rcParams["figure.figsize"] = [10, 8] plt.plot(list(range(1,26)),accu_list5,'-o') plt.xticks(np.arange(0, 26, 1.0)) plt.title('Number of Neighbors vs. Success Rate for Parkinson Dataset') plt.xlabel('Number of Neighbors') plt.ylabel('Success Rate') plt.grid() plt.savefig('knn_parkinson.png') # Time the KNN algorithm start = time.time() knn_rate(X_train_p,y_train_p,X_test_p,y_test_p,23) end = time.time() print("It takes " + str(end - start) + " seconds to run KNN algorithm on parkinson dataset with 23 neighbors.")
ff500bc386f6a37f814b9344fef04ccfbf3d7e70
jaime-araujo-ntt/CursoemVideo-YouTube
/ex013.py
151
3.796875
4
salario = int(input('Digite o salário ATUAL:')) aumento = salario * 1.15 print('Com a promoção o salário aumenta para R$ {:.2f}!'.format(aumento))