blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
f754b7af16c0a9ad8dd345fc9f80ec58be889d66
s0fiateixeira/FEUP_FPRO
/Testes/PE4/maximum_depth.py
430
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 8 15:05:22 2019 @author: exame """ def maximum_depth(l): maximo = 1 for i in range(len(l)): depth = len(l[i])+2 if depth >= maximo: maximo = depth return(maximo) #print(maximum_depth([[], [[]], [], [[]]])) #print(maximum_depth([[[], [], [[]]], [[]], [], [[]]])) #print(maximum_depth([[[], [], [[]]], [[[[]]]]]))
f4e2435415ad33e0fc7c77aa414351ff595d5940
lama-imp/python_basics_coursera
/Week5_tasks/32_replacemaxmin.py
391
4.03125
4
# В списке все элементы попарно различны. Поменяйте местами минимальный \ # и максимальный элемент этого списка. list = list(map(int, input().split())) max = int(max(list)) min = int(min(list)) max_idx = list.index(max) min_idx = list.index(min) list[max_idx] = min list[min_idx] = max print(*list)
09d6056918a914a9e3223ddab042b9c320cc1cc7
CodeInDna/CodePython
/Basics/43_unit_testing_part2.py
995
4.125
4
#---------------Testing with Python-----------------# # setUp and tearDown # For larger applications, you might want similar application state before # running tests # setUp runs before each test method # tearDown runs after each test method # Common Use cases: adding/removing data from a test database, creating instances of # a class import unittest from robots import Robot class RobotTests(unittest.TestCase): def setUp(self): self.mega_man = Robot("Mega Man", battery=50) def test_charge(self): # make new robot each time # mega_man = Robot("Mega Man", battery=50) # Use setUp to make robot once self.mega_man.charge() self.assertEqual(self.mega_man.battery, 100) def test_say_name(self): # make new robot each time # mega_man = Robot("Mega Man", battery=50) # Use setUp to make robot once self.assertEqual(self.mega_man.say_name(), "BEEP BOOP BEEP BOOP. I AM MEGA MAN") self.assertEqual(self.mega_man.battery, 49) if __name__=='__main__': unittest.main()
8453a6620b0887e277c039421f3077cbac85d867
acaciomartins/trilhapython
/lampadas.py
300
3.5
4
n = int(input()) acoes = input().split() lampadaA = 0 lampadaB = 0 for interruptor in acoes : if interruptor == '1': lampadaA = 1 if lampadaA == 0 else 0 if interruptor == '2': lampadaA = 1 if lampadaA == 0 else 0 lampadaB = 1 if lampadaB == 0 else 0 print(lampadaA) print(lampadaB)
64aacdf86d5c8bc413102cb711332faa8d41abdb
mickew/PITemperature
/nginx/PiSupply/softshut.py
698
3.765625
4
# Import the modules to send commands to the system and access GPIO pins from subprocess import call import RPi.GPIO as gpio # Define variables to store the pin numbers soft_shutdown_pin = 13 # Default pin for Pi Supply is 7 # Define a function to run when an interrupt is called def shutdown(): # Cleanup GPIO gpio.cleanup() # Shutdown with halt and power off in 1 minute call(['shutdown', '-h','now'], shell=False) # Set pin numbering to board numbering gpio.setmode(gpio.BOARD) # Setup the input Pin to wait on gpio.setup(soft_shutdown_pin, gpio.IN) gpio.wait_for_edge(soft_shutdown_pin, gpio.RISING) # Wait for input from button # Run the shutdown function shutdown()
c0d286d03acb279378977907d221945693fe0d55
zee7han/algorithms
/array/missing_element.py
2,528
4.21875
4
import collections # Here finder find the missing element of arr1 in arr2 def finder(arr1, arr2): # sort the both lists arr1.sort() arr2.sort() # Here we loop throigh the arr1 from 0 to length-1 for i in range(0,len(arr1)-1): # Check this condition till the lenght of arr2 or if arr2 is not out of bounds if i < len(arr1)-2: if arr1[i] != arr2[i]: print(f"{arr1[i]} is the missing element") return # Here we are handling the missing element is the last element of the arr1 # This will simply print the last element of arr1. else: print(f"{arr1[i+1]} is the missing element") return finder([1,4,2,53,54,2,4],[2,4,53,1,54,4]) finder([1,2,3,4,5,6],[2,4,3,1,5]) # This approach will find the element in O(NlogN) def finder2(arr1, arr2): # Here we sort the both lists arr1.sort() arr2.sort() # Here we loop through the zip of both element # zip return the tuple of element of same index from both lists for num1, num2 in zip(arr1,arr2): if num1 != num2: print(f"{num1} is the missing element") return num1 # Here we return the last element of the arr1 print(f"{arr1[-1]} is the missing element") return arr1[-1] finder2([1,4,2,53,54,2,4],[2,4,53,1,54,4]) finder2([1,2,3,4,5,6],[2,4,3,1,5]) # This approach will take around the O(N) time complexity def finder3(arr1, arr2): # this create the dictionary which not throw error while a key is not found dic = collections.defaultdict(int) # Update the dic if key available update it by 1 or not available then create new key and update it it for num in arr2: dic[num] += 1 # check if arr1 key present in dic then return number otherwise decrease the count of that number for num in arr1: # Return the number that is missing if dic[num] == 0: print(f"{num} is the missing element") return num # decrease the count of that number else: dic[num] -= 1 finder3([1,4,2,53,54,2,4],[2,4,53,1,54,4]) finder3([1,2,3,4,5,6],[2,4,3,1,5]) # Here i am using the clever trick that using the XOR operator def finder4(arr1, arr2): result =0 # Loop through the list after concatenation for num in arr1+arr2: # XOR the every result with the number result^=num return result print(finder4([1,4,2,53,54,2,4],[2,4,53,1,54,4])) print(finder4([1,2,3,4,5,6],[2,4,3,1,5]))
02ba62933700d633776963c8df7a91fdcc2f21eb
omullaboyev/python-lessons
/FOR-cycle.py
1,696
3.6875
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 20 01:58:07 2021 @author: omon """ # ============================================================================= #CYCLE FOR # mehmonlar = ["Ali", "Vali", "Hasan", "Husan", "Olim"] # print(mehmonlar) # for mehmon in mehmonlar: # print("Salom ", mehmon) # print("Hayr, ", mehmon) # print("Yana keling ", mehmon) # ============================================================================= # ============================================================================= #CYCLE FOR + fstring # mehmonlar = ["Ali", "Vali", "Hasan", "Husan", "Olim"] # for mehmon in mehmonlar: # print(f"Hurmatli {mehmon} sizni oshga chaqiramiz") # print("Hurmat bilan Corvax\n") # ============================================================================= # ============================================================================= #CYCLE FOR + list, range # sonlar = list(range(1, 11)) # for son in sonlar: # print(f"{son} sonining kvadrati {son**2} ga teng") # ============================================================================= # ============================================================================= #CYCLE FOR + list + range + list.append # sonlar = list(range(11)) # sonlar_kvadrati = [] # for son in sonlar: # sonlar_kvadrati.append(son**2) # print(sonlar) # print(sonlar_kvadrati) # ============================================================================= dostlar = [] print("5 ta eng yaqin do'stingi kim") for n in range(5): dostlar.append(input(f"{n+1}-do'stingizning ismini kiriting >>> ")) print(dostlar) for dost in dostlar: print(dost)
48a9412e7f52551538fd6ab8d577e3ad644f0c5b
heyiamluke/Flask-sudoku-app
/app/sudopy.py
6,609
3.734375
4
import re class InvalidInputError(BaseException): pass class Sudoku: """ Attributes ---------- puzzle : str or list Input sudoku puzzle. Can be formated as either a concatenated string with empty squares represented as '.' or as a list with 0 indicating an empty square. """ def __init__(self, puzzle): self._NROWS = 9 self._NCOLS = 9 if isinstance(puzzle, str): pattern = r'^[0-9\.]*$' puzzle = puzzle.strip('\n') if len(puzzle) == 81 and re.match(pattern, puzzle): self.puzzle = self._from_string(puzzle) else: raise InvalidInputError("the puzzle {} is not a valid input for the solver.".format(puzzle)) elif isinstance(puzzle, list): self.puzzle = self._from_list(puzzle) def __str__(self): if isinstance(self.puzzle, type(None)): return repr(self) else: # output = '+-----+-----+-----+\n' output = '+' + ('-' * 7 + '+') * 3 + '\n' for i, row in enumerate(self.puzzle): output += '| {0} {1} {2} '.format(self._print_zero(row[0]), self._print_zero(row[1]), self._print_zero(row[2])) output += '| {0} {1} {2} '.format(self._print_zero(row[3]), self._print_zero(row[4]), self._print_zero(row[5])) output += '| {0} {1} {2} |'.format(self._print_zero(row[6]), self._print_zero(row[7]), self._print_zero(row[8])) output += '\n' if (i + 1) % 3 == 0: output += '+' + ('-' * 7 + '+') * 3 + '\n' return output def _print_zero(self, value): if value: return value else: return '.' def _from_list(self, puzzle_lst): # ensure proper conversion if input is list or list of lists if all(isinstance(sublist, list) for sublist in puzzle_lst): return puzzle_lst # build list of list if input is flat elif all(isinstance(val, int) for val in puzzle_lst): return [puzzle_lst[i * 9: i * 9 + 9] for i in range(self._NROWS)] else: raise ValueError('incorrect input puzzle') def _from_string(self, puzzle_str): # converts string to list since read_from_list is workhorse p = [] for i in range(self._NROWS): row = puzzle_str[i * 9: i * 9 + 9] p.append([int(val) if val != '.' else "" for val in row]) return p def _copy(self): """ make deep copy of puzzle """ return [[val for val in lst] for lst in self.puzzle] def _col(self, col): """ return column from sudoku puzzle """ return [row[col] for row in self.puzzle] def _along_row(self, pos_val): """ check if move valid in row """ if pos_val[2] in (self.puzzle[pos_val[0]][:pos_val[1]] + self.puzzle[pos_val[0]][pos_val[1] + 1:]): return False else: return True def _along_col(self, pos_val): """ check if move valid in column """ col = self._col(pos_val[1]) if pos_val[2] in (col[:pos_val[0]] + col[pos_val[0] + 1:]): return False else: return True def _in_box(self, pos_val): """ check if move valid in sub box """ block_row = pos_val[0] // 3 * 3 block_col = pos_val[1] // 3 * 3 block = [self.puzzle[r][c] for r in range(block_row, block_row + 3) for c in range(block_col, block_col + 3) if r != pos_val[0] or c != pos_val[1]] if pos_val[2] in block: return False else: return True def _check_move(self, pos_val): return (self._along_row(pos_val) and self._along_col(pos_val) and self._in_box(pos_val)) # def _set_initial_state(self): # init_state = set() # for r in range(self._NROWS): # for c in range(self._NCOLS): # if self.puzzle[r][c]: # init_state.add((r, c)) # return init_state def _candidates(self, r, c): candidates = [] for i in range(1, 10): if self._check_move((r, c, i)): candidates.append(i) return candidates def _unassigned(self, grid): for r in range(self._NROWS): for c in range(self._NCOLS): if not grid[r][c]: return (r, c) return (-1, -1) def _unassigned_with_least_candidates(self, grid): min = (10, 10, 10) # impossible values... think of more pythonic way for r in range(self._NROWS): for c in range(self._NCOLS): if not grid[r][c]: n = len(self._candidates(r, c)) if n == 1: return (r, c) if n < min[2]: min = (r, c, n) if min != (10, 10, 10): return min[:2] else: return (-1, -1) def _next(self, grid, r, c): for i in range(1, 10): if self._check_move((r, c, i)): grid[r][c] = i if self._solve(grid): return True grid[r][c] = 0 return False def _solve(self, grid): """ use backtracking to solve sudoku """ r, c = self._unassigned_with_least_candidates(grid) if r == -1 and c == -1: return True return self._next(grid, r, c) def show(self): print(self) def solve(self): # make a copy original = self._copy() if self._solve(self.puzzle): solution = Sudoku(self.puzzle) self.puzzle = original return solution else: raise InvalidInputError("This sudoku is not solveable") def to_list(self): return [item for sublist in self.puzzle for item in sublist] def validate(self): p = self.puzzle for r in range(self._NROWS): for c in range(self._NCOLS): if p[r][c]: if not self._check_move((r, c, p[r][c])): return False return True
e2d4c5772af227d2c690894e3740ac00d06a7497
shiqi0128/My_scripts
/python_study/Py28_0410_file_exception/lm_08_examples.py
711
3.5625
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- @Time : 2020/4/10 21:53 @Auth : 可优 @File : lm_08_examples.py @IDE : PyCharm @Motto: ABC(Always Be Coding) @Email: keyou100@qq.com @Company: 湖南省零檬信息技术有限公司 @Copyright: 柠檬班 ------------------------------------------------- """ # 判断用户输入的是否为整数, 如果是返回True, 否则返回False def is_int_num(num): try: # result = int(num) int(num) # return True except Exception as e: return False else: return True if __name__ == '__main__': one_num = input("请输入一个整数: ") print(is_int_num(one_num))
376df870cd3dcfd824f87d36071494a8fb4d1c89
ddipp/Euler_solutions
/p028.py
1,005
3.875
4
#!/usr/bin/env python3 # =============================================================================== # Starting with the number 1 and moving to the right in a clockwise direction # a 5 by 5 spiral is formed as follows: # # [21] 22 23 24 [25] # 20 [7] 8 [9] 10 # 19 6 [1] 2 11 # 18 [5] 4 [3] 12 # [17] 16 15 14 [13] # # It can be verified that the sum of the numbers on the diagonals is 101. # What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral # formed in the same way? # =============================================================================== def GRing(n): s = 1 yield [1] while s < n: s += 2 yield [s**2, s**2 - 1 * (s - 1), s**2 - 2 * (s - 1), s**2 - 3 * (s - 1)] def solution(): summ = 0 ring = GRing(1001) for i in ring: summ += sum(i) return summ if __name__ == '__main__': print(solution())
2d727571c09629051cfac47637852c4a54c6d962
Shiv2157k/leet_code
/goldman_sachs/reverse_string.py
629
4.15625
4
class String: def reverse(self, s: str) -> str: """ Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param s: :return: """ left, right = 0, len(s) - 1 while left < right: s[left], s[right] = s[right], s[left] left += 1 right -= 1 return s if __name__ == "__main__": string = String() print(string.reverse(["s", "h", "i", "v", "a"])) print(string.reverse(["m", "a", "l", "a", "y", "a", "l", "a", "m"])) print(string.reverse(["h", "y", "d", "e", "r", "a", "b", "a", "d"]))
c0920d729875e86a6fa1c17d255899fdf76a90a1
timHollingsworth/hackerRank
/fibonacci_modified.py
1,084
4.03125
4
""" We define a modified Fibonacci sequence using the following definition: Given terms and where , term is computed using the following relation: For example, if term and , term , term , term , and so on. Given three integers, , , and , compute and print term of a modified Fibonacci sequence. Note: The value of may far exceed the range of a -bit integer. Many submission languages have libraries that can handle such large results but, for those that don't (e.g., C++), you will need to be more creative in your solution to compensate for the limitations of your chosen submission language. Input Format A single line of three space-separated integers describing the respective values of , , and . Constraints may far exceed the range of a -bit integer. Output Format Print a single integer denoting the value of term in the modified Fibonacci sequence where the first two terms are and . """ A,B,N = [int(x) for x in input().split(' ')] if N==1: print(A) if N==2: print(B) else: for i in range(2,N): F=A + B*B A=B B=F print(F)
6d33eb52597c502afda84b35d218751138437870
thaheer-uzamaki/assignment-10
/evenword.py
279
4.09375
4
def printWords(s): s = s.split(' ') for word in s: if len(word)%2==0: print(word) st = 'Print every word in this sentence that has an even number of letters' printWords(st)
c207de36344576b99a1c80fb1bf8a3ff36ac7e2e
The-bug-err/30DaysOfCode
/Day3.py
773
4.03125
4
""" Usage : Just copy paste the content of the script in the iPython interperter, or just call the script. The scripts written are only for study purpose. Author: Vivek Rana Date: 12-Aug-2016 About Script: Write some thing about script here. https://www.hackerrank.com/challenges/30-operators """ def main(): mealCost = eval(input("Enter Meal Cost : ")) tipPercent = eval(input("Enter tip Percentage : ")) taxPercent = eval(input("Enter tax Percentage : ")) tip = mealCost * tipPercent/100 tax = mealCost * taxPercent/100 total = mealCost + tip + tax print("The total meal cost is",round(total),"dollars.") return if __name__ == '__main__': main() input("Press any button to exit.")
7a122b84563a4e8ae5f9389cfd879a5e6607c7cc
eselyavka/python
/leetcode/solution_718.py
1,248
3.625
4
#!/usr/bin/env python import unittest class Solution(object): def findLength(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: int """ m = len(A) n = len(B) matrix = [[0] * (n+1) for _ in range(m+1)] for i in range(m): for j in range(n): if A[i] == B[j]: matrix[i][j] = matrix[i-1][j-1] + 1 return max([max(row) for row in matrix]) class TestSolution(unittest.TestCase): def test_findLength(self): solution = Solution() self.assertEqual(solution.findLength([1, 2, 3, 2, 1], [3, 2, 1, 4, 7]), 3) self.assertEqual(solution.findLength([1], [1]), 1) self.assertEqual(solution.findLength([6, 3, 7], [1, 3, 2]), 1) self.assertEqual(solution.findLength([1, 2, 2, 3], [4, 2, 2, 6]), 2) self.assertEqual(solution.findLength([1, 2, 2, 3, 5, 6, 7], [4, 2, 2, 6, 5, 6, 7]), 3) self.assertEqual(solution.findLength([1, 2, 2, 3, 5, 6, 7, 8], [4, 2, 2, 6, 5, 6, 7, 10]), 3) self.assertEqual(solution.findLength([0, 0, 0, 0, 1], [1, 0, 0, 0, 0]), 4) if __name__ == '__main__': unittest.main()
419111fcf9a784bee74fcdcfd6516a2dcef61f62
friskaayu/Jogja-Python-Scripting-Specialist
/Kalkulator sederhana.py
757
3.953125
4
print("ini adalah kalkulator sederhana") while True: a = int (input ("Masukan angka pertama: ")) b = int (input ("Masukan angka kedua: ")) print("pilih operasi") print("1. Penjumlahan") print("2. Pengurangan") print("3. Perkalian") print("4. Pembagian") c = (input ("masukan pilihan (1/2/3/4) : ")) if c == '1': print (a, "+" , b, "=", a+b) elif c == '2': print (a, "-" , b, "=", a-b) elif c == '3': print (a, "*" , b, "=", a*b) elif c == '4': print (a, "/" , b, "=", a/b) else : print("masukan salah") d = (input ("hitung lagi ? (Ketik N untuk berhenti): ")) if d == 'N': break else : True
a312e1a0c9430540843bd38875e0eb886354967a
cowboii/Grupp-vning_Medelv-rde
/Gruppövning_Medelvärde.py
857
4.09375
4
def medelvärde(): num_max = 0 num_min = 0 sum = 0 count = 0 while True: store = input("Skriv in ett värde: ") try: store = float(store) except: print('Invalid input') break if store == 0: break else: sum += store count += 1 if count == 1: num_max, num_min = store, store continue else: if store < num_min: num_min = store if store > num_max: num_max = store if count > 2: count -= 2 sum -= num_max sum -= num_min return sum / count elif num_max or num_min and count > 0: return sum / count else: return 0 if __name__ == "__main__": print(medelvärde())
115a728fbaf2e81ad57e2e8eb35bbbcfe7c47ea9
80000v/iforj
/qa/mypaginator.py
2,318
3.734375
4
# -*- coding: utf-8 -*- class InvalidPage(Exception): pass class PageNotAnInteger(InvalidPage): pass class EmptyPage(InvalidPage): pass class MyPaginator(object): def __init__(self, object_list, per_page): self.object_list = object_list self.per_page = int(per_page) # 多少个一分 self.num_pages = 1 # 能拆多少个 self.num = None self.number = None self.page_list = None self.page_range = None def validate_number(self, number): """ Validates the given 1-based page number. """ try: number = int(number) except (TypeError, ValueError): raise PageNotAnInteger('That page number is not an integer') if number < 1: raise EmptyPage('That page number is less than 1') if number > self.get_num_pages(): if number == 1: pass else: raise EmptyPage('That page contains no results') return number def get_num_pages(self): # 可以分成多少页 self.num = len(self.object_list) num_pages = self.num / self.per_page if self.num % self.per_page > 0: self.num_pages = num_pages + 1 else: self.num_pages = num_pages return self.num_pages def page(self, number): """得到第number页""" self.number = self.validate_number(number) # 分页查询列表 bottom = (self.number - 1) * self.per_page up = bottom + self.per_page self.page_list = self.object_list[bottom: up] # 已拆分的列表 if self.num_pages < 5: # 如果能拆的页面小于5 self.page_range = range(1, self.num_pages+1) else: if self.number >3: self.page_range = range(self.number-2, min(self.number+3, self.num_pages+1)) else: self.page_range = range(1, 6) # if __name__ == '__main__': # x = MyPaginator([11,2,3,4,5,6,7,8,9,10,11,12,13,14,15], 2) # page = 4 # x.page(page) # print x.num_pages # print "第%s页的列表%s"% (page,x.page_list) # print "分页按钮%s"%x.page_range
e28007f043d51a6832678bab3f1e51d0b5fe317b
krishnareddygajjala/flash
/Practice/programs/logest_substring.py
691
3.609375
4
def scantillrepeat(line): found = '' for char in line: if not char in found: found = found + char else: break return found def findlongest(f): for line in f: longestfound = '' longestfoundlen = 0 for k in range(len(line)): candidate = scantillrepeat(line[k:]) if len(candidate) > longestfoundlen: longestfound = candidate longestfoundlen = len(candidate) print len(candidate) print longestfound print longestfound st = ['ABCDDEFGHIJKLMM12345677TUVWXYZZ'] st1 = "experience" findlongest(st)
d2de30f45c9ae756e690fe4695774555af8ca7e4
gomba66/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
3,947
4
4
#!/usr/bin/python3 """ Module of a function that determine the perimeter of an island """ def island_perimeter(grid): """ Function that determine the perimeter of a grid""" total = 0 for b in range(len(grid)): for a in range(len(grid[b])): # left corner if (a == 0) and (b == 0): if grid[b][a] == 1: total = total + 2 if grid[b][a + 1] == 0: total = total + 1 if grid[b + 1][a] == 0: total = total + 1 # right corner elif (a == len(grid[b]) - 1) and b == 0: if grid[b][a] == 1: total = total + 2 if grid[b + 1][a] == 0: total = total + 1 if grid[b][a - 1] == 0: total = total + 1 # lower-left corner elif a == 0 and b == (len(grid) - 1): if grid[b][a] == 1: total = total + 2 if grid[b][a + 1] == 0: total = total + 1 if grid[b - 1][a] == 0: total = total + 1 # lower-right corner elif b == (len(grid) - 1) and a == (len(grid[b]) - 1): if grid[b][a] == 1: total = total + 2 if grid[b - 1][a] == 0: total = total + 1 if grid[b][a - 1] == 0: total = total + 1 # top edge elif (b == 0 and a > 0) and a < (len(grid[b]) - 1): if grid[b][a] == 1: total = total + 1 if grid[b][a - 1] == 0: total = total + 1 if grid[b + 1][a] == 0: total = total + 1 if grid[b][a + 1] == 0: total = total + 1 # left edge elif (b > 0 and b < (len(grid) - 1)) and ((a == 0) and a < len(grid[b]) - 1): if grid[b][a] == 1: total = total + 1 if grid[b - 1][a] == 0: total = total + 1 if grid[b][a + 1] == 0: total = total + 1 if grid[b + 1][a] == 0: total = total + 1 # right edge elif (b > 0 and (b < len(grid) - 1)) and (a == len(grid[b]) - 1): if grid[b][a] == 1: total = total + 1 if grid[b - 1][a] == 0: total = total + 1 if grid[b][a - 1] == 0: total = total + 1 if grid[b + 1][a] == 0: total = total + 1 # bottom edge elif (b == len(grid) - 1) and a > 0 and a < len(grid[b]) - 1: if grid[b][a] == 1: total = total + 1 if grid[b][a - 1] == 0: total = total + 1 if grid[b - 1][a] == 0: total = total + 1 if grid[b][a + 1] == 0: total = total + 1 # cases that are neither edges nor corners elif (b > 0 and b < len(grid) - 1) and (a > 0 and a < len(grid[b]) - 1): if grid[b][a] == 1: if grid[b][a - 1] == 0: total = total + 1 if grid[b][a + 1] == 0: total = total + 1 if grid[b - 1][a] == 0: total = total + 1 if grid[b + 1][a] == 0: total = total + 1 return total
d8569dd8a758faf9185c5b8b9c5a465a521aaaf8
dragosnechita/python_learning
/nested_list/build/lib/nested_list.py
778
4.375
4
"""This is the "nester.py" module and it provides one function called print_lol() which prints lists that may or may not include nested lists.""" def print_lol (the_list, want_indent=False, list_indent=0): """This function takes a positional argument called "the_list", which is any Python list (of - possibly - nested lists). Each data item in the provided list is (recursively) printed to the screen on it's own line. The list_indent argument refers to the indentation of the lists, if need be""" for item in the_list: if isinstance(item, list): print_lol(item, want_indent, list_indent+1) else: if want_indent: for tab_stop in range(list_indent): print("\t", end='') print(item)
b557e585df1bc4551bc4cbac96eb16a3501be608
iabdullahism/python-programming
/Day02/CheckingLeap_year.py
779
4.3125
4
# Make a function to find whether a year is a leap year or no, return True or False #Defining the function with argument and default def Leap_Year(Year_Data): #Defining function With one argument if((Year_Data % 4==0) and (Year_Data % 100 !=0)): #if value of year is divisible by 4 and not divisible by 100 then it is a leap year return True #if condition true return value true elif(Year_Data % 400 == 0): #if value of year is divisible by 400 then it is leap year return True #if condition true return value true else: return False #if condition False return value false Year_Data=int(input("enter Year>")) #call the function by passing one argument My_Leap_Year=Leap_Year(Year_Data) print ( My_Leap_Year)
075fd348b13f02764a910ee395436a7d301b4d33
chirkovi/openweathermap
/json_request_temp.py
1,929
3.515625
4
import datetime import requests import statistics # import json def get_json(url="http://api.openweathermap.org/data/2.5/forecast"): return requests.get(url, params=parameters).json() def get_temperature(input_list): temperature_dict = {} for weather in input_list: date = datetime.datetime.strptime(weather['dt_txt'], '%Y-%m-%d %H:%M:%S').date() if date in temperature_dict: temperature_dict[date].append(weather['main']['temp']) else: temperature_dict[date] = [weather['main']['temp']] return temperature_dict def get_max_temperature(input_list): max_temperature_dict = {} morning_hour = {9, 12} for weather in input_list: date_time = datetime.datetime.strptime(weather['dt_txt'], '%Y-%m-%d %H:%M:%S') date = date_time.date() hour = date_time.time().hour if date in max_temperature_dict and hour in morning_hour: max_temperature_dict[date].append(weather['main']['temp']) elif hour in morning_hour: max_temperature_dict[date] = [weather['main']['temp']] return max_temperature_dict def print_temperature(temp_dict, max_temp_dict): print("Average temperature") for day, temp in temp_dict.items(): temp = statistics.mean(temp) print(day, '{0:.{1}f}'.format(temp, 2)) print("\nMorning temperature") for day, max_temp in max_temp_dict.items(): max_temp = statistics.mean(max_temp) print(day, '{0:.{1}f}'.format(temp, 2)) if __name__ == "__main__": parameters = {'id': '524901', 'mode': 'json', 'units': 'metric', 'appid': '03f90859bfa5b3b6d0c0c63e54c61172'} # print(json.dumps(get_json(), indent=4, sort_keys=True)) # Print JSON data json_list = get_json()['list'] max_temperature = get_max_temperature(json_list) temperature = get_temperature(json_list) print_temperature(temperature, max_temperature)
39f5ea5cc288c97dce36cc9ba1f8b4e77bfb67fe
eduardobrennand/estrutura_de_decisao
/21.py
1,182
4.0625
4
""" Faça um Programa para um caixa eletrônico. O programa deverá perguntar ao usuário a valor do saque e depois informar quantas notas de cada valor serão fornecidas. As notas disponíveis serão as de 1, 5, 10, 50 e 100 reais. O valor mínimo é de 10 reais e o máximo de 600 reais. O programa não deve se preocupar com a quantidade de notas existentes na máquina. Exemplo 1: Para sacar a quantia de 256 reais, o programa fornece duas notas de 100, uma nota de 50, uma nota de 5 e uma nota de 1; Exemplo 2: Para sacar a quantia de 399 reais, o programa fornece três notas de 100, uma nota de 50, quatro notas de 10, uma nota de 5 e quatro notas de 1. """ import math valor_original = int(input('Valor do saque: ')) notas_100 = int(valor_original / 100) valor = valor_original - (100 * notas_100) notas_50 = int(valor / 50) valor = valor - (50 * notas_50) notas_10 = int(valor / 10) valor = valor - (10 * notas_10) notas_5 = int(valor / 5) valor = valor - (5 * notas_5) notas_1 = int(valor / 1) print(f'Para sacar {valor_original}, são necessárias {notas_100} notas de 100, {notas_50} notas de 50, {notas_10} notas de 10, {notas_5} notas de 5, {notas_1} notas de 1.')
e5e64467dd2b4c8475286dac60058c55b1b40566
Aglorios17/Bootcamp_Python
/day00/ex09/guess.py
905
4.03125
4
import sys import random secret = random.randint(1, 99) print("This is an interactive guessing game!\nYou have to enter a number between 1 and 99 to find out the secret number.\nType 'exit' to end the game.\nGood luck!\n") i = 0 a = 0 exit = "exit" NB_ESSAIS_MAX = 0 while True and i == 0: print("What's your guess between 1 and 99?") b = input(">>") if b == exit: print("Goodbye!") i = 1 if b.isdigit is False: print("That's not a number.") i = 1 if i == 0 and b.isdigit() is True: a = int(b) if a == 42: print("The answer to the ultimate question of life, the universe and everything is 42.\nCongratulations! You got it on your first try!") i = 1 elif a < secret and b.isdigit() is True: print("Too low!") elif a > secret: print("Too high!") elif a == secret: print("Congratulations, you've got it!\nYou won in",NB_ESSAIS_MAX + 1 ,"attempts!") i = 1 NB_ESSAIS_MAX += 1
6c9d66a86a02ae5c1bf3d2f6c17f5199e19312f9
zuwannn/Python
/Sorting and Searching/BinarySearch_Recursive.py
1,087
4.15625
4
# Binary Search ''' Recursive Method binarySearch(arr, x, low, high) if low > high return False else mid = (low + high) / 2 if x == arr[mid] return mid else if x > arr[mid] // x is on the right side return binarySearch(arr, x, mid + 1, high) else // x is on the right side return binarySearch(arr, x, low, mid - 1) ''' def BS_recursive(array, x, low, high): if high >= low: mid = low + (high - low)//2 #if found at mid, then return it if array[mid] == x: return mid #search the left half elif array[mid] > x: return BS_recursive(array, x, low, mid-1) #search the right half else: return BS_recursive(array, x, mid + 1, high) else: return -1 list = [19,2,31,45,6,11,121,27] # x is the number to find x = 2 result = BS_recursive(list, x, 0, len(list)-1) if result != -1: print("element is paresent at index " + str(result)) else: print("no found")
459d35a0132ca0e6e2613e3bc36715a3fff7b225
roma-kisel/text-highlighting
/syn.py
6,560
3.640625
4
"""IPP 2016/2017 Project 2 Script highlights some parts of input text using html tags. Information about highlighting is stored in the format file which contains regexes and their format parameters in the following way: IFJ-regex1<HT+>[param_list1]<LF> IFJ-regex2<HT+>[param_list2]<LF> ... IFJ-regexn<HT+>[param_listn]<LF>? HT - (horizontal tab) LF - (new line) [param_list] is list of parametrs which are represents html tags and it must be specified in the following way: param1, param2, param3 ... etc. Parameters must be separated from each other by comma followed by any number of spaces or horizontal tabs Some parameters can take a value that must be specified in this way param:value The following table contains available parameters, their values and corresponding open tags: | Parameter | value | open_tag | |-----------|-------------------------------------|----------------| | bold | no | <b> | | italic | no | <i> | | underline | no | <u> | | teletype | no | <tt> | | size | number in range [1-7] | <font size=*> | | color | hex number in range [000000-FFFFFF] | <font color=*> | * - is a parametr value Available script options: --help print this message --input=filename specify input file (stdin if option wasn't passed) --output=filename specify output file (stdout if option wasn't passed) --format=filename specify format file --br insert <br /> tag before each LF char """ import sys import os import re from getopt import getopt from getopt import GetoptError from collections import deque from ipp_syn import exit_codes from ipp_syn.format_file import FormatFile from ipp_syn.format_file import FormatFileError __author__ = 'Roman Kiselevich (xkisel00@stud.fit.vutbr.cz)' def error_print(*args, **kwargs): """Is similar like print() but print message to stderr""" print(*args, file=sys.stderr, **kwargs) def get_args(): """Returns program options as dictionary {'option': value}""" opts_dictionary = {} try: options, args = getopt(sys.argv[1:], '', ['help', 'input=', 'output=', 'br', 'format=']) if args: # args list is not empty raise GetoptError( 'invalid program argument \'' + args[0] + '\'') opts_list = [opt[0] for opt in options] if len(opts_list) != len(set(opts_list)): raise GetoptError('cannot combine two or more same options') for arg in sys.argv[1:]: if (arg[2:] != 'help' and arg[2:] != 'br' and not re.match(r'\w+=.+', arg[2:])): raise GetoptError('bad option \'' + arg + '\'') except GetoptError as opt_error: error_print(sys.argv[0], ': ', end='', sep='') error_print(opt_error) sys.exit(exit_codes.BAD_ARGUMENTS) for opt in options: opts_dictionary[opt[0][2:]] = opt[1] return opts_dictionary if __name__ == '__main__': opts = get_args() if 'help' in opts: print(re.sub(r'\n', r'\n ', __doc__)) sys.exit(exit_codes.SUCCESS) if 'input' in opts: try: input_file = open(opts['input'], encoding='utf-8') input_file_content = input_file.read() input_file.close() except IOError as io_error: io_error.strerror = 'cannot open file for reading' error_print(sys.argv[0], io_error.strerror, sep=': ', end=' ') io_error.filename = '\'{0}\''.format(io_error.filename) error_print(io_error.filename) sys.exit(exit_codes.BAD_INPUT) else: input_file_content = sys.stdin.read() if 'output' in opts: try: output_file = open(opts['output'], 'wt', encoding='utf-8') except IOError as io_error: io_error.strerror = 'cannot open file for writing' error_print(sys.argv[0], io_error.strerror, sep=': ', end=' ') io_error.filename = '\'{0}\''.format(io_error.filename) error_print(io_error.filename) sys.exit(exit_codes.BAD_OUTPUT) else: output_file = sys.stdout if 'format' in opts: try: format_file = FormatFile(opts['format']) except IOError as io_error: output_file.write(input_file_content) output_file.close() sys.exit(exit_codes.SUCCESS) except FormatFileError as format_error: error_print(sys.argv[0], format_error, sep=': ') output_file.close() sys.exit(exit_codes.BAD_FORMAT) else: if 'br' in opts: input_file_content = re.sub( r'\n', '<br />\n', input_file_content) output_file.write(input_file_content) output_file.close() sys.exit(exit_codes.SUCCESS) if os.path.getsize(format_file.name) == 0: # format file is empty if 'br' in opts: input_file_content = re.sub( r'\n', '<br />\n', input_file_content) output_file.write(input_file_content) output_file.close() sys.exit(exit_codes.SUCCESS) pos_tag_deque = deque() close_tags = [] for regex in format_file: for match in regex.finditer(input_file_content): if not match.group(0): continue for param in format_file[regex]: pos_tag_deque.append((match.start(), param.open_tag)) close_tags.append((match.end(), param.close_tag)) for close_tag in reversed(close_tags): pos_tag_deque.append(close_tag) del close_tags pos_tag_deque = deque( sorted(pos_tag_deque, key=lambda pos_tag: (pos_tag[0], pos_tag[1][1]) if pos_tag[1][1] == '/' else (pos_tag[0], pos_tag[1][0]) ) ) for index, char in enumerate(input_file_content): while pos_tag_deque and index == pos_tag_deque[0][0]: output_file.write(pos_tag_deque[0][1]) pos_tag_deque.popleft() if char == '\n' and 'br' in opts: output_file.write('<br />') output_file.write(char) while pos_tag_deque: output_file.write(pos_tag_deque[0][1]) pos_tag_deque.popleft() output_file.close()
08874412a7e9241acf74c06ae98ca5c37315f554
zhangyan612/mkl
/input/listener.py
548
3.53125
4
# listen for human command from input.speech_text import speech_recognition_services as stt from input.text_command import api_ai as nlu # voice_txt = stt.recognize_bing() ''' list of possible voice command - search for 'search text' - look up computers and compare them, find the one with best value - create a restful software to get data from web pages ''' voice_txt ='google best way to learn coding' answer, action, parameters = nlu.api_conversation().get_answer(voice_txt) # for simplicity print(answer) print(action) print(parameters)
0db08de4a9d7d864aa223d97c0d5914c1276acd7
daniel-reich/ubiquitous-fiesta
/JBTLDxvdzpjyJA4Nv_6.py
276
3.578125
4
def super_reduced_string(txt): p = 0 while len(txt) != p: p, i = len(txt), 1 while i < len(txt): if txt[i] == txt[i-1]: txt = txt[:i-1] + txt[i+1:] else: i += 1 return txt or "Empty String"
53ac965cc995212f9609a8bdce3e62b55c2efd59
harishassan85/python-assignment-
/assignment#2/question3.py
105
3.640625
4
# Write a program which print the length of the list? list = ["sheraz", "arain"] print(len(list))
b43848fca78db12c06b9de93a18de0370c1845e1
davutaktas27/deneme
/recursif.py
458
3.828125
4
def topla(liste): toplam=0 for i in liste: toplam+=i return toplam liste=[7,6,5] print(topla(liste)) def recursif(liste): if len(liste)==0: return 0 else: return liste[0]+ recursif(liste[1:]) print("recursif",recursif([3,6,8])) #yerel ve global değişkenler a=10 b=13 def fonka(): global b b=6 b=8 a=8 print("Yerel a= b=",a,b) print("Global a= b=",a,b) fonka() print("Global a= b=",a,b)
06e6c5430b16a0762bfc9b9d4a7c0e8c38c8f893
bluedawn123/Study
/homework/kyokwaseo/08/8-16.py
515
3.75
4
#요소추가 #☆☆☆☆append 사용 ☆☆☆☆☆ import pandas as pd indexes = ["apple", "orange", "banana", "strberry", "kiwi"] datas = [10, 5, 8, 12, 3] series = pd.Series(datas, index = indexes) #인덱스가 "pineapple"이고, 데이터가 12인 요소를 series에 추가해라. x = pd.Series([12], index = ["pineapple"]) series = series.append(x) print(series) ''' apple 10 orange 5 banana 8 strberry 12 kiwi 3 pineapple 12 dtype: int64 ''' #추가완료
7de6cabc9b7f1a7dbd8b046cc3ec563402aa9708
palash247/AlgoExpertProblems
/moderate/youngest_common_ancestor/program.py
1,589
3.703125
4
# This is an input class. Do not edit. class AncestralTree: def __init__(self, name): self.name = name self.ancestor = None # before seeing the solution # def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo): # # Write your code here. # desc1_path = get_ancestor_path(descendantOne) # desc2_path = get_ancestor_path(descendantTwo) # i = 0 # while i<len(desc1_path) and i<len(desc2_path): # if desc1_path[i].name == desc2_path[i].name: # i += 1 # else: # break # return desc1_path[i-1] # def get_ancestor_path(node): # path = [] # while node: # path.insert(0,node) # node = node.ancestor # return path # after seeing the solution def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo): # Write your code here. desc1_depth = get_ancestor_depth(descendantOne) desc2_depth = get_ancestor_depth(descendantTwo) if desc1_depth<desc2_depth: return parse_depth_wise(descendantOne, descendantTwo, desc2_depth-desc1_depth) else: return parse_depth_wise(descendantTwo, descendantOne, desc1_depth - desc2_depth) def get_ancestor_depth(node): depth = 0 while node: node = node.ancestor depth += 1 return depth def parse_depth_wise(old_node, young_node, diff): while diff>0: young_node = young_node.ancestor diff-=1 while young_node.name != old_node.name: young_node = young_node.ancestor old_node = old_node.ancestor return young_node
3554923396ae97493cce66f1f57a44691bed967a
tonny62/Deadlock
/Untitled.py
1,451
3.515625
4
import tkinter as tk global num_rect num_rect = 0 class App: def __init__(self,master): frame = tk.Frame(master,width = 400,height=300) frame.pack_propagate(0) # frame.grid_propagate(0) label1 = tk.Label(frame,text ="Display Area").grid(row=1,column=1) self.display_area = tk.Canvas(frame,width=400,height=300,bg="#ECECEC") self.display_area.grid(column=1,row=2,rowspan=7,padx=5,pady=5) label2 = tk.Label(frame,text ="Name").grid(row=2,column=2) res_name = tk.Entry(frame) res_name.grid(row=2,column=3,padx=5) label3 = tk.Label(frame,text = "instances").grid(row=3,column=2) res_instance = tk.Entry(frame).grid(row=3,column=3,padx=5) self.b_add_resource = tk.Button(frame, text="Add resource",command=self.add_rect) self.b_add_resource.grid(column=2,row=4,sticky="E"+"W",columnspan=2) self.b_add_process = tk.Button(frame,text="Add process") self.b_add_process.grid(column=2,row=5) frame.pack() def say_hi(self): print("Hi") def add_rect(self): global num_rect x = 175 y = 25 + num_rect*75 mytext = self.display_area.create_text(x+60,y+25,text = "R"+str(num_rect)) coord = x,y,x+50,y,x+50,y+50,x+50,y+50,x,y+50 res1 = self.display_area.create_polygon(coord,fill="blue") num_rect = num_rect+1 top = tk.Tk() app = App(top) top.mainloop()
fdd6781a8a3eace75ee316095356fb84a9b5dcac
catomania/Random-late-night-time-wasters
/HackerRank_Puzzles/the-minion-game_v2.py
940
3.796875
4
# https://www.hackerrank.com/challenges/the-minion-game # Stuart: consonants # Kevin: vowels # this passes all the tests but I'm a tiny bit miffed that we can't use len() without the timing out on the tests... word = str(raw_input()) word_length = int(len(word)) vowel_counter = 0 consonant_counter = 0 count_up = 0 for x in xrange(0, len(word)): if word[x] in ["A", "E", "I", "O", "U"]: # string will contain only capital letters # how to mathematically count up the possible vowel combinations vowel_counter += ((word_length)-(count_up)) # don't use len here, that takes too much processing time else: consonant_counter += ((word_length)-(count_up)) count_up += 1 # you use this instead of len because it takes less processing time if vowel_counter > consonant_counter: print "Kevin " + str(vowel_counter) elif consonant_counter > vowel_counter: print "Stuart " + str(consonant_counter) else: print "Draw"
f34401bf1467edb2fbabcf106fee5b265af08ec9
Craksy/aoc-2020
/day-7/solution.py
1,349
3.765625
4
#!/usr/bin/env python3 with open('./input.txt') as fp: puzzle_input = [rule.strip() for rule in fp.readlines()] def parse_rule(rule): """ return a (clr, rules) tuple where clr is the bag color, and rules is a dict that maps {color: count} """ bag_color, contains = rule.split(' bags contain ') subrules = {} for sr in contains.split(', '): if sr == 'no other bags.': subrules = None else: sr = sr.split() count = int(sr[0]) color = ' '.join(sr[1:3]) subrules[color] = count return bag_color, subrules rule_dict = {} for rule in puzzle_input: k,v = parse_rule(rule) rule_dict[k] = v def can_be_in(target): """return a list of all colors of bag which `target` can be in """ return [color for color,rules in rule_dict.items() if rules and target in rules] def possible_outer(target): possible = [] parents = can_be_in(target) possible.extend(parents) for p in parents: possible.extend(possible_outer(p)) return set(possible) def get_bag_count(target): rules = rule_dict[target] return 0 if not rules else sum(v+get_bag_count(k)*v for k,v in rules.items()) print('Possible outer bags:', len(possible_outer('shiny gold'))) print('Total inner bag count:', get_bag_count('shiny gold'))
72726a42c17b10a15eaa9b58b2bd7221f054e847
piyush09/LeetCode
/Search a 2D Matrix II.py
779
3.921875
4
def searchMatrix(matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if (matrix is None or len(matrix) < 1 or len(matrix[0]) < 1): return False row = 0 column = len((matrix)[0]) - 1 # Iterating till col is greater than 0 and till last row is reached while (column >= 0 and row <= len(matrix) - 1): if (target == matrix[row][column]): # If value found, return value return True elif (target < matrix[row][column]): # If target is less, decrement column column -= 1 elif (target > matrix[row][column]): # If target is more, increment row row += 1 return False matrix = [[-1,3]] target = 3 print (searchMatrix(matrix, target))
2634c9be5b2da2f9ba81ba53cb29f79c9ec8aae3
Gnanender-reddy/python_program
/AlgorithmPrograms/anagram.py
424
3.96875
4
""" @Author : P.Gnanender Reddy @Since : Dec'2019 @Description:This code is for anagram checking. """ from com.bridgelabz.AlgorithmPrograms.util import anagram s1=int(input("enter 1st string"))#input from user s2=input("enter 2nd string") #input from user anagram(s1,s2) #anagram function is called here #=======================================================================================================================
a820054bae29eab02ee77eb1be31be4f54a3f926
EpicRowan/Code-Challenges
/Python/factorial.py
96
3.859375
4
def recursive_factorial(num): if num == 1: return 1 return num * recursive_factorial(num-1)
e3ef1f06c78e149143404d48cd31c41ec06e481c
UniInfinity/autho_files
/classAs.py
1,710
3.8125
4
# import datetime # d1 = datetime.datetime(2018, 5, 3) # d2 = datetime.datetime(2018, 6, 1) # print(d1>d2) # print(d1<d2) # print(d1!=d2) '''-------------------------------------''' # str1 = "10-02-2019" # str2 = "12-03-2022" # l1 = str1.split("-") # l2 = str2.split("-") '''------------------------------------------''' # d1 = "20170101" # d2 = "20170102" # print(d2>d1) # print(d2<d1) # print(d2==d1) '''----------------------------------------------''' # def compare(date1, date2): # date1_parts = date1.split('/') # d1, m1, y1 = int(date1_parts[0]), int(date1_parts[1]), int(date1_parts[2]) # date2_parts = date2.split('/') # d2, m2, y2 = int(date2_parts[0]), int(date2_parts[1]), int(date2_parts[2]) # return (y1, m1, d1) > (y2, m2, d2) # compare("25/01/2017","12/12/2017") '''-----------------------------------------------------------''' def compare(dateOne, dateTwo): #Break up the date into its components day = int(dateOne[0:2]) month = int(dateOne[3:5]) year = int(dateOne[6:10]) dayTwo = int(dateTwo[0:2]) monthTwo = int(dateTwo[3:5]) yearTwo = int(dateTwo[6:10]) #Compare the years first if(year > yearTwo): return True elif(year < yearTwo): return False else: #If the years are equal, then compare the months if(month > monthTwo): return True elif(month < monthTwo): return False else: #If the days are equal, return False since it's strictly greater, else, return the appropriate value. if(day > dayTwo): return True else: return False compare("25/01/2017","12/12/2017")
23fd53b00df008f258406461458f98f54b53cd28
AkramKalaee/carla-aebs
/carla-aebs/utils/pid.py
684
3.5
4
# Implementation of PID control class PID(): def __init__(self, Kp=1.0, Ki=0.0, Kd=0.0): self.Kp = Kp self.Ki = Ki self.Kd = Kd self.PTerm = 0.0 self.ITerm = 0.0 self.DTerm = 0.0 self.last_error = 0.0 def step(self, target, feedback): error = target - feedback delta_error = error - self.last_error self.PTerm = self.Kp * error self.ITerm += self.Ki * error self.DTerm = self.Kd * delta_error self.last_error = error self.output = max(0.0, self.PTerm + self.ITerm + self.DTerm) self.output = min(1.0, self.output) return self.output
75693bfcaede590512da7cae5d3639d16045caf2
Mohit130422/python-code
/19.py
284
4.0625
4
#nested if/else- calculate leap year year= int(input("enter no")) if(year%400==0): print("leap year") else: if(year%4==0): if(year%100!=0): print("leap year") else: print("No leap year") else: print("Not") #run
0cf43ac459d99058afb254eea0e6355234415a08
TGITS/programming-workouts
/erri/python/lesson_20/fizzbuzz.py
477
3.875
4
def est_divisible_par_3(n): reste = n % 3 return reste == 0 def est_divisible_par_5(n): reste = n % 5 return reste == 0 def fizzbuzz(n): fb = "" if est_divisible_par_3(n): fb = fb + "Fizz" if est_divisible_par_5(n): fb = fb + "Buzz" if fb == "" : fb = str(n) return fb if __name__ == "__main__": resultat = "" for n in range(1, 101): resultat = resultat + fizzbuzz(n) + " " print(resultat)
54b4a39618b07fb23309d82ecab21f26d2568d57
gannaramu/Coursera-The-Raspberry-Pi-Platform-and-Python-Programming-for-the-Raspberry-Pi
/week4.py
878
3.890625
4
# Build a circuit using your Raspberry Pi that causes an # LED to blink when a push button is NOT pressed. # However, the LED should stay on continuously when the push button IS pressed. import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) ledPin = 18 buttonPin = 17 GPIO.setup(ledPin, GPIO.OUT) # LED pin set as output GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up while True: try: if GPIO.input(buttonPin): # when button is not Pressed GPIO.output(ledPin, GPIO.LOW) time.sleep(1) GPIO.output(ledPin, GPIO.HIGH) time.sleep(1) else: # when button is Pressed GPIO.output(ledPin, GPIO.HIGH) except KeyboardInterrupt: GPIO.cleanup() # cleanup all GPIO print("\n Stopped") exit()
6a33a085d391be0c8a0984f50aacc0b058dfa21a
dariyaMakh/TeamProject
/ship.py
1,232
3.5
4
import pygame class Ship(): def __init__(self, ai_settings, screen): # Initializes ship and sets its initial position self.screen = screen self.ai_settings = ai_settings # Ship downloading and getting rectangle self.image = pygame.image.load('images/ship1.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() # New ship appears in bottom self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom # Saving actual ship center coordinates self.center = float(self.rect.centerx) # Movement flag self.moving_right = False self.moving_left = False def update(self): if self.moving_right and self.rect.right < self.screen_rect.right: self.center += self.ai_settings.ship_speed_factor elif self.moving_left and self.rect.left > 0: self.center -= self.ai_settings.ship_speed_factor self.rect.centerx = self.center def blit(self): # pictures ship in current position self.screen.blit(self.image, self.rect) def center_ship(self): self.center = self.screen_rect.centerx
468240dd3beb54a0625a459e1b25f6744157291e
aisuluudb/Chapter3Task3
/Task3.py
104
3.546875
4
# list = [1,2,3,4,5,6] list1 = [1, 2, 3, 4, 5] list_move = [list1[-1]] + list1[:-1] print(list_move)
cd3cb09a3c57c8db90b406791e1c87a5768d3e25
SparkCat23/TrabsonSegundaPython
/trabsonLP_13_11/trabson.py
10,775
3.515625
4
from datetime import date class Pessoa(): def __init__(self,nome,email,celular): self.nome = nome self.email = email self.celular = celular def __str__(self): return str(self.nome) def altera_celular(self,cel): if type(cel) == str: self.celular = cel return True else: return False def altera_email(self,email): if type(email) == str: self.email = email return True else: return False def altera_nome(self,nome): if type(nome) == str: self.nome = nome return True else: return False def retorna_celular(self): return self.celular def retorna_email(self): return self.email def retorna_nome(self): return self.nome class Usuario(): def __init__(self,ra,senha): self.ra = ra self.senha = senha def altera_ra(self,ra): if type(ra) == str: self.ra = ra return True else: return False def altera_senha(self,senha): if type(senha) == str: self.senha = senha return True else: return False def retorna_ra(self): return self.ra def retorna_senha(self): return self.senha class Aluno(Pessoa,Usuario): def __init__(self,nome,email,celular,ra,senha,sigla_curso): Pessoa.__init__(self, nome, email, celular) Usuario.__init__(self, ra,senha) self.sigla_curso = sigla_curso self.matriculas = [] def disciplinas_aluno(self): disciplinas=[] for m in self.matriculas: disciplinas.append(m.disciplina.nome) return disciplinas def matricular(self,Matricula): # carregando nomes das Disciplinas disciplinas = [] for d in self.matriculas: disciplinas.append(d.disciplina.nome) # validação if Matricula.disciplina.nome not in disciplinas: self.matriculas.append(Matricula) return True else: print("-- Matrícula já cadastrada --") return False def confirmar_matricula(self,ConfDisciplina): # carregando nomes das disciplinas disciplinasAluno = [] for d in self.matriculas: disciplinasAluno.append(d.disciplina.nome) # se a disciplina estiver na lista do aluno if ConfDisciplina.disciplina.nome in disciplinasAluno: for c in range(0,len(disciplinasAluno)): if ConfDisciplina.disciplina.nome == disciplinasAluno[c]: # alteração da data de confirmação ConfDisciplina.data_confirmacao = date.today() print("-- Matrícula Confirmada --") return True else: print("-- Matricula Não Existe --") return False def cancelar_matricula(self,CancelDisciplina): # carregando nomes das disciplinas disciplinasAluno = [] for d in self.matriculas: disciplinasAluno.append(d.disciplina.nome) # se a disciplina estiver na lista do aluno if CancelDisciplina.disciplina.nome in disciplinasAluno: for c in range(0,len(disciplinasAluno)): if CancelDisciplina.disciplina.nome == disciplinasAluno[c]: # alteração da data de cancelamento CancelDisciplina.data_cancelamento = date.today() print("-- Matrícula Cancelada --") return True else: print("-- Matricula Não Existe --") return False class Professor(Pessoa,Usuario): def __init__(self,nome,email,celular,ra,senha,apelido): Pessoa.__init__(self,nome,email,celular) Usuario.__init__(self,ra,senha) self.apelido = apelido self.disciplinasProf = [] def adiciona_disciplina(self,addDisciplina): # carregando nomes das disciplinas discProf = [] for d in self.disciplinasProf: discProf.append(d.nome) # se a disciplina não estiver cadastrada ainda if addDisciplina.nome not in discProf: self.disciplinasProf.append(addDisciplina) return True else: print("-- Disciplina já cadastrada --") return False def remove_disciplina(self,delDisciplina): # carregando nomes das disciplinas discProf = [] for d in self.disciplinasProf: discProf.append(d.disciplina.nome) # se a disciplina estive cadastrada para o professor if delDisciplina.disciplina.nome in discProf: for x in range(0,len(discProf)): if delDisciplina.disciplina.nome == discProf[x]: # alteração da data de confirmação discProf.remove(x) print("-- Disciplina Removida --") return True else: print("-- Disciplina não Ecziste --") return False def disciplinas_professor(self): disciplinas=[] for d in self.disciplinasProf: disciplinas.append(d.nome) return disciplinas def carga_horaria_total(self): total = 0 for d in self.disciplinasProf: total += d.carga_horaria return total class Matricula(): def __init__(self,Aluno,Disciplina,data_matricula): y = int(data_matricula[0:4]) m = int(data_matricula[5:7]) d = int(data_matricula[9:11]) self.aluno = Aluno self.disciplina = Disciplina self.data_matricula = date(y,m,d) self.data_confirmacao = None self.data_cancelamento = None def __str__(self): mat = str(self.aluno)+"--"+str(self.disciplina)+".\nData de Matrícula: "+str(self.data_matricula) return mat def altera_aluno(self,aluno): if type(aluno) == Aluno: self.aluno = aluno return True else: return False def altera_disciplina(self,disciplina): if type(disciplina) == Disciplina: self.disciplina = disciplina return True else: return False def retorna_aluno(self): return self.aluno def retorna_disciplina(self): return self.disciplina class Disciplina(): def __init__(self,nome,carga_horaria,teoria,pratica,ementa,competencias,habilidades,conteudo,bibliografia_basica,bibliografia_complementar): self.nome = nome self.carga_horaria = carga_horaria self.teoria = teoria self.pratica = pratica self.ementa = ementa self.competencias = competencias self.habilidades = habilidades self.conteudo = conteudo self.bibliografia_basica = bibliografia_basica self.bibliografia_complementar = bibliografia_complementar def __str__(self): return str(self.nome) def altera_nome(self,nome): if type(nome) == str: self.nome = nome return True else: return False def altera_carga_horaria(self,carga_horaria): if type(carga_horaria) == int: if carga_horaria <= 0: print("-- Inserção Inválida! A carga horária não pode ser menor ou igual a ZERO --") return False else: self.carga_horaria = carga_horaria print("-- Carga Horária Alterada --") return True else: return False def altera_teoria(self,teoria): if type(teoria) == int: if teoria <= 0: print("-- Inserção Inválida! A carga horária não pode ser menor ou igual a ZERO --") return False else: self.teoria = teoria print("-- Carga Horária Alterada --") return True else: return False def altera_pratica(self,pratica): if type(pratica) == int: if pratica <= 0: print("-- Inserção Inválida! A carga horária não pode ser menor ou igual a ZERO --") return False else: self.pratica = pratica print("-- Carga Horária Alterada --") return True else: return False def altera_ementa(self,ementa): if type(ementa) == str: self.ementa = ementa return True else: return False def altera_competencias(self,competencias): if type(competencias) == str: self.competencias = competencias return True else: return False def altera_habilidades(self,habilidades): if type(habilidades) == str: self.habilidades return True else: return False def altera_conteudo(self,conteudo): if type(conteudo) == str: self.conteudo = conteudo return True else: return False def altera_bibliografia_basica(self,bibliografia_basica): if type(bibliografia_basica) == str: self.bibliografia_basica = bibliografia_basica return True else: return False def altera_bibliografia_complementar(self,bibliografia_complementar): if type(bibliografia_complementar) == str: self.bibliografia_complementar = bibliografia_complementar return True else: return False def retorna_nome(self): return self.nome def retorna_carga_horaria(self): return self.carga_horaria def retorna_teoria(self): return self.teoria def retorna_pratica(self): return self.pratica def retorna_ementa(self): return self.ementa def retorna_competencias(self): return self.competencias def retorna_pratica(self): return self.habilidades def retorna_conteudo(self): return self.conteudo def retorna_bibliografia_basica(self): return self.bibliografia_basica def retorna_bibliografia_complementar(self): return self.bibliografia_complementar
2b9c99064c2a8c9d842c7fb6a104b32c86562359
jemtca/CodingBat
/Python/Logic-1/without_doubles.py
624
4.09375
4
# return the sum of two 6-sided dice rolls, each in the range 1..6 # however, if noDoubles is true, if the two dice show the same value, increment one die to the next value, wrapping around to 1 if its value was 6 def without_doubles(die1, die2, no_doubles): sum = 0 if not no_doubles or die1 != die2: sum = die1 + die2 else: if die1 >= 1 and die1 <= 5: die1 += 1 sum = die1 + die2 else: die1 = 1 sum = die1 + die2 return sum print(without_doubles(2, 3, True)) print(without_doubles(3, 3, True)) print(without_doubles(3, 3, False))
ac579a89b795c033c12acd81496883a942c538ad
luisdossantos/semester-UdeM
/Natural Language Processing course/main.py
8,265
3.703125
4
# coding: utf-8 ######################################################### #LIBRARIES import numpy as np from random import randrange from collections import Counter import nltk import re, csv from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier import time import sys import spacy import pandas as pd #IMPORT DATA # globals blog = 'blog' classe = 'class' # init the spacy pipeline # !!! desactivate components if you only need tokenization # (as a default, you get pos tagging, parsing, etc.) !!! print("\nSpacy load") nlp_train = spacy.load("en_core_web_sm", disable=["parser", "tagger", "ner"]) nlp_test = spacy.load("en_core_web_sm", disable=["parser", "tagger", "ner"]) print('Done..') # reading a csv file (from stdin) with panda is easy # question: why from stdin ? # memory load: initial csv x 2 (roughly) # but possible to stream with the chunksize parameter (read the doc) print('\nConversion en pandas data frame') df_train = pd.read_csv('train_posts.csv', names=[blog,classe]) df_test = pd.read_csv('test_split01.csv', names=[blog,classe]) print('Done..') # Example #print(df_train.sample(5)) # of course, you can iterate line by line # note that in this example, there is only tokenization done (no normalisation) ''' for index, row in df_train.iterrows(): sent = nlp_train(row[blog]) words = [tok.text for tok in sent] print("{}\t{}\t[{}]: {}".format(index, row[classe], len(words), " ".join(words[:10]))) ''' #Creer une liste contenant les differents labels (categories) different_labels = [0, 1, 2] ''' ALGO 2 : NAIVE BAYES''' ################## PREPROCESSING ################## t1 = time.clock() print('\nCreation du dictionnaire lie au vocabulaire...') count = Counter() t100 = time.clock() #Pour chaque commentaire (on ne prend que les X 1ers commentaires) N_comments_took_in_account = 10000 for index, row in df_train.head(n=N_comments_took_in_account).iterrows(): if (index%1000 == 0) : print('\n\n\n ################################ TRAIN : CREATION DU DICTIONNAIRE %f ################################' % ((index/N_comments_took_in_account)*100)) if (index != 0): t101=time.clock() print('Temps restant estime : ', ( int((round(t101 - t100, 2)*100)/((index/N_comments_took_in_account)*100) - round(t101 - t100, 2))), 's') #On recupere chaque commentaire (sans le label) sent = nlp_train(row[blog]) #Tokenization words = [tok.text for tok in sent] #En minuscule for i in range (len(words)) : words[i] = words[i].lower() count.update(words) print('Done') #nltk.download('stopwords') stop_nltk = nltk.corpus.stopwords stop_words = set(stop_nltk.words('english')) for elem in stop_words : del count[elem] #Mots differents cutoff = 20 vocab = [word for word in count if count[word] > cutoff] print('\nTaille du vocabulaire : ', len(vocab)) ################## TRAIN : FEATURES SET AVEC LAPLACIAN SMOOTHING ################## t10 = time.clock() features_set_train = [] d = len(vocab) alpha = 0.008 t100 = time.clock() for index, row in df_train.head(n=N_comments_took_in_account).iterrows(): if (index%1000 == 0) : print('\n\n\n ################################ TRAIN : BAG OF WORDS %f ################################' % ((index/N_comments_took_in_account)*100)) if (index != 0): t101=time.clock() print('Temps restant estime : ', ( int((round(t101 - t100, 2)*100)/((index/N_comments_took_in_account)*100) - round(t101 - t100, 2))), 's') #On recupere chaque commentaire (sans le label) sent = nlp_train(row[blog]) #Tokenization words_train_set_comment_index = [tok.text for tok in sent] #En minuscule for i in range (len(words_train_set_comment_index)) : words_train_set_comment_index[i] = words_train_set_comment_index[i].lower() #Nb de mots pour chaque commentaire N = len(words_train_set_comment_index) #Dictionnaire pour le commentaire index count_vocab_train_set_comment_index = Counter(words_train_set_comment_index) ''' AVEC LAPLACE #features_for_one_example = [0]*(len(vocab)) features_for_one_example=[] for j in range (len(vocab)) : features_for_one_example.append((count_vocab_train_set_comment_index[vocab[j]] + alpha)/(N + alpha*d)) ''' features_for_one_example = [0]*(len(vocab)) for j in range (len(vocab)) : if (count_vocab_train_set_comment_index[vocab[j]] != 0) : features_for_one_example[j] = count_vocab_train_set_comment_index[vocab[j]] features_set_train.append(features_for_one_example) t11 = time.clock() print('\n\n\nFeatures set pour train cree en : ', round(t11 - t10, 2), 's') t12 = time.clock() features_set_train = np.array(features_set_train) t13 = time.clock() print('Features set de train converti en array en : ', round(t13 - t12, 2), 's\n') t14 = time.clock() features_set_test = [] for index, row in df_test.iterrows(): if (index%1000 == 0) : print('\n\n\n ################################ TEST : BAG OF WORDS %f ################################' % ((index/df_test.shape[0])*100)) if (index != 0): t101=time.clock() print('Temps restant estime : ', ( int((round(t101 - t100, 2)*100)/((index/df_test.shape[0])*100) - round(t101 - t100, 2))), 's') #On recupere chaque commentaire (sans le label) sent = nlp_test(row[blog]) #Tokenization words_test_set_comment_index = [tok.text for tok in sent] #En minuscule for i in range (len(words_test_set_comment_index)) : words_test_set_comment_index[i] = words_test_set_comment_index[i].lower() #Nb de mots pour chaque commentaire N = len(words_test_set_comment_index) #Dictionnaire pour le commentaire index count_vocab_test_set_comment_index = Counter(words_test_set_comment_index) features_for_one_example = [0]*(len(vocab)) for j in range (len(vocab)) : if (count_vocab_test_set_comment_index[vocab[j]] != 0) : features_for_one_example[j] = count_vocab_test_set_comment_index[vocab[j]] features_set_test.append(features_for_one_example) t15 = time.clock() print('\n\n\nFeatures set pour test cree en : ', round(t15 - t14, 2), 's') t16 = time.clock() features_set_test = np.array(features_set_test) t17 = time.clock() print('Features set de test converti en array en : ', round(t17 - t16, 2), 's\n') ################## MODELE (comparaison avec le Naive Bayes de Scikit) ################## gnb = GaussianNB() #clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0) print('\nFit model') gnb.fit(features_set_train, df_train.head(n=N_comments_took_in_account)['class']) #clf.fit(features_set_train, df_train.head(n=N_comments_took_in_account)['class']) print('Done...') print('\nPred model') y_pred = gnb.predict(features_set_test) #y_pred = clf.predict(features_set_test) print('Done...') print('\nTRAIN : Nombre de commentaire pour chaque classe') dico_taux_classes_train = {class_name : 0 for class_name in (different_labels)} for current_index_label in (df_train.head(n=N_comments_took_in_account)['class']) : dico_taux_classes_train[current_index_label] += 1 print('\n', dico_taux_classes_train) print('\nTEST : Nombre de commentaire pour chaque classe') dico_taux_classes_test = {class_name : 0 for class_name in (different_labels)} for current_index_label in (df_test['class']) : dico_taux_classes_test[current_index_label] += 1 print('\n', dico_taux_classes_test) print('\nNombre de predictions pour chaque classe') dico_taux_pred_classes = {class_name : 0 for class_name in (different_labels)} for current_pred_index in (y_pred) : dico_taux_pred_classes[current_pred_index] += 1 print('\n', dico_taux_pred_classes) print("\n\nThe training accuracy is : {:.1f} % ".format(100*np.mean(y_pred == df_test['class']))) t2 = time.clock() print('\nTIME for algo 2 : ', round(t2 - t1, 2), 's\n\n')
b1c1ab314843b8c6c0e9f7eb4f11e0d15b3f221e
Bhardwaj999/algorithms
/behavioral.py
7,989
3.578125
4
"""BEHAVIORAL DESIGN PATTERN - observer - visotor - itrator - strategy - chain of responsibility """ """OBSERVER DESIGN PATTERN PROBLEM * subjedts to be monitored * observers to be notified SCENARIO * core temperatures of reactors at a power plant * registered observers to be notified SOLUTION * subjet -- abstrat class (attach/detach/notify) * concrete subjects RELATED * singleton """ class Subject(object): #Represents what is being 'observed' def __init__(self): self._observers = [] #This is hwere references to all the observers are being kept #Note that this is a one-to-many relationships: there will be one subject to be observed by multiple _observers def attach(self, observer): if observer not in self._observers: #If the observer is not already in the observers list self._observers.append(observer) #append the observer to the list def detach(self, observer): #Simply remove the observer try: self._observers.remove(observer) except ValueError: pass def notify(self, modifier=None): for observer in self._observers: #For all the observers in the list if modifier != observer: #Don't notify the observer who is actually updating the temperature observer.update(self) #Alert the observers! class Core(Subject): #Inherits from the Subject class def __init__(self, name=""): super(Core, self).__init__() self._name = name #Set the name of the core self._temp = 0 #Initialize the temperature of the core @property #Getter that gets the core temperature def temp(self): return self._temp @temp.setter #Setter that sets the core temperature def temp(self, temp): self._temp = temp #Notify the observers when ever somebody changes the core temperature self.notify() class TempViewer: def update(self, subject): #Alert method that is invoked when the notify() method in a concrete subject is invoked print("Temperature Viewer: {} has Temperature {}".format(subject._name, subject._temp)) # #Let's create our subjects # c1 = Core("Core 1") # c2 = Core("Core 2") # #Let's create our observers # v1 = TempViewer() # v2 = TempViewer() # #Let's attach our observers to the first core # c1.attach(v1) # c1.attach(v2) # #Let's change the temperature of our first core # c1.temp = 80 # c1.temp = 90 """VISITOR DESIGN PATTERN PROBLEM * new operations * existing classes * all dynamically done SCENARIO * house class * HVAC specialist - visitor type 1 * electrician -- visitor type 2 SOLUTION * new operations * various elements of an existing """ class House(object): def accept(self, visitor): """Interface to accept a visitor""" #Triggers the visiting operation! visitor.visit(self) def work_on_hvac(self, hvac_specialist): print(self, "worked on by", hvac_specialist) #Note that we now have a reference to the HVAC specialist object in the house object! def work_on_electricity(self, electrician): print(self, "worked on by", electrician) #Note that we now have a reference to the electrician object in the house object! def __str__(self): """Simply return the class name when the House object is printed""" return self.__class__.__name__ class Visitor(object): """Abstract visitor""" def __str__(self): """Simply return the class name when the Visitor object is printed""" return self.__class__.__name__ class HvacSpecialist(Visitor): """Concrete visitor: HVAC specialist""" def visit(self, house): house.work_on_hvac(self) #Note that the visitor now has a reference to the house object class Electrician(Visitor): """Concrete visitor: electrician""" def visit(self, house): house.work_on_electricity(self) #Note that the visitor now has a reference to the house object # #Create an HVAC specialist # hv = HvacSpecialist() # #Create an electrician # e = Electrician() # #Create a house # home = House() # #Let the house accept the HVAC specialist and work on the house by invoking the visit() method # home.accept(hv) # #Let the house accept the electrician and work on the houe by invoking the visit() # home.accept(e) """ITERATOR PATTERN PROBLEM * the traversal interfaces of an aggregate object -- getting crowded SCENARIO * our custom iterator based on a built-in python iterator: zip() * german counting words * only up to a certain point SOLUTION * isolation * interface * tracking * recommendation RELATED PATTERNS composite """ def count_to(count): """Our iterator implementation""" #Our list numbers_in_german = ["eins", "zwei", "drei", "vier", "funf"] #Our built-in iterator #Creates a tuple such as (1, "eins") iterator = zip(range(count), numbers_in_german) #Iterate through our iterable list #Extract the German numbers #Put them in a generator called number for position, number in iterator: #Returns a 'generator' containing numbers in German yield number #Let's test the generator returned by our iterator # for num in count_to(3): # print(f'{num}') """STRATEGY PATTERN PROBLEM * need for dynamically chainge the behavior of an object SCENARIO * abstract stragegy class with a default set of behaviors * concrete stragegy class with new behaviors SOLUTION * the types module in Python """ import types #Import the types module class Strategy: """The Stragegy Pattern class""" def __init__(self, function=None): self.name = "Default Strategy" #If a reference to a function is provided, replace the execute() method with the given function def execute(self): #This gets replaced by another version if another strategy is provided """The default method that prints the name of the strategy being used""" print("{} is used".format(self.name)) #Replacement method 1 def strategy_one(self): print("{} is used to execute method 1".format(self.name)) #Replacement method 2 def strategy_two(self): print("{} is used to execute method 2".format(self.name)) # #Let's create our default strategy # s0 = Strategy() # #Let's execute our default strategy # s0.execute() # #Let's create the first variation of our default strategy by providing a new behavior # s1 = Strategy(strategy_one) # #Let's set its name # s1.name = "Strategy One" # #Let's execute the strategy # s1.execute() # s2 = Strategy(strategy_two) # s2.name = "Strategy Two" # s2.execute() """CHAIN OF RESPONSIBILITY PROBLEM *one request -- various type of processing SCENARIO * integer value * handler -- find out range SOLUTION * abstract handler -- successor * concrete handler -- checks if it can handle the request RELATED PATTERNS * composite """ class Handler: #Abstract handler """Abstract handler""" def __init__(self, successor): self._successor = successor #Define who sithe next handler def handle(self, request): handled = self._handle(request) #If handled, stop here #Otherwise, keep going if not handled: self._successor.handle(request) def _handle(self, request): raise NotImplementedError("Must provide implementation in subclass!") class ConcreteHandler(Handler): #Inherits from the abstract handler """Concrete handler 1""" def _handle(self, request): if 0 < request <= 10: #Provide a condition for handling print("Request {} handled in handler 1".format(request)) return True #Indicates that the request has been handled class DefaultHandler(Handler): """Default handler""" def _handle(self, request): """If there is no handler available""" #No condition checking since this is a default Handler print("End of chain, no handler for {}".format(request)) return True #Indicates that the request has been handled class Client: #Using handlers def __init__(self): self.handler = ConcreteHandler(DefaultHandler(None)) #Create handlers and use them in a sequence you want #Note that the default handler has no successor def delegate(self, requests): #Send your requests one at a time for handlers to handle for request in requests: self.handler.handle(request) #Create a client c = Client() #Create request requests = [2, 5, 30] #Send the requests c.delegate(requests)
ee3d7c04ca7d61375e0543346b9607453d69a514
H-Anna/pytorpedo
/player.py
4,989
3.5625
4
from ship import * import sys '''A-J betűkhöz''' from string import ascii_uppercase BOARD_UPPER_BOUND = 10 BOARD_LOWER_BOUND = 0 BOARDRANGE = range(BOARD_LOWER_BOUND,BOARD_UPPER_BOUND) ABC = ascii_uppercase[BOARD_LOWER_BOUND:BOARD_UPPER_BOUND] class Player: '''Adattagok: __board = {} dictionary ; Kulcs: A-J, érték: lista 0-9. Azokat a mezőket tárolja, amelyekre még lehet lőni __ships = [] list ; 5 db hajó. Ha egy hajó elsüllyed, kiveszi a listából. Ha üres a lista, vége a játéknak. ''' #Ellenőrzi, létezik-e ez a cella def isCellInputCorrect(self, cell): if cell == "Q" or cell == "QUIT": sys.exit() return (not any(ltr in cell[1:] for ltr in ABC)) and (cell[0] in ABC) and (int(cell[1:]) in BOARDRANGE) def __init__(self, name): self.__name = name self.__board = {} self.__ships = [] for letter in list(ABC): #Új oszlopot hoz létre self.__board[letter] = [] for n in BOARDRANGE: #Új sort hoz létre self.__board[letter].append(n) def getName(self): return self.__name def getShips(self): return self.__ships def printShips(self): print("A hajók helyzete:") for x in self.__ships: x.printRange() def getBoard(self): return self.__board def addShip(self, length): newship = Ship(length) self.__ships.append(newship) return newship '''Hajó letételekor ne indexeljünk a játéktéren kívül''' def stayWithinBounds(self, head, length, horizontal): tmp = 0 '''Ha a hajó vízszintes, akkor az oszlopokat kell vizsgálni; ha függőleges, akkor a sorokat''' if horizontal: tmp = list(ABC).index(head[0]) else: tmp = int(head[1:]) if (tmp + length-1) > BOARD_UPPER_BOUND - 1: return -1 else: return 1 '''Megnézi, hogy van-e az adott cellán hajó, ha igen, visszatér vele''' def checkCellForShip(self, cell): for s in self.__ships: if cell in s.getRange(): return s return None '''Megjelöli az adott cellát, tehát kiveszi a lehetséges cellák közül''' def markCellOnBoard(self, cell): self.__board[cell[0]].remove(int(cell[1:])) '''Meg van-e jelölve már az adott cella?''' def isCellUnmarkedOnBoard(self, cell): return (int(cell[1:]) in self.__board[cell[0]]) def setShipLocation(self, ship, head, horizontal = False, omit_print = False): if not(self.isCellInputCorrect(head)): print("Hiba: Nem megfelelő input") return False '''A hajó celláit tartalmazó lista''' temp = [] '''A betű''' ltr = head[0] '''A betű helye az ABC-ben''' ltr_place = list(ABC).index(head[0]) '''A szám''' num = int(head[1:]) '''Alaphelyzetben a program a "head" cellát úgy veszi, mintha a bal szélső/legészakibb cella lenne. (Pl. ha a head B2, és a hajó vízszintes, akkor a hajó cellái: B2, C2, D2...) Ha így a hajó kilógna a pályáról, akkor a program megfordítja az irányát. (Ha a head J5, és a hajó vízszintes, akkor a cellák: J5, I5, H5...) A correction egy szorzó, ami segít a programnak eldönteni, merre iteráljon.''' correction = self.stayWithinBounds(head, ship.getLength(), horizontal) '''Vízszintes iterálás a betűkön ; Függőleges iterálás a számokon''' if horizontal: for idx in range(ltr_place, ltr_place + (ship.getLength() * correction), correction): cell = ABC[idx] + str(num) temp.append(cell) else: for n in range(num, num + (ship.getLength() * correction), correction): cell = ltr + str(n) temp.append(cell) '''Található-e a megadott tartományban másik hajó?''' anothership = False for c in temp: if self.checkCellForShip(c) != None: anothership = True break '''Ha igen, akkor nem lehet oda letenni új hajót.''' if anothership: if not(omit_print): print("!! A cellák valamelyikében már van hajó, próbált újra.") else: '''Cellák beállítása''' ship.setRange(temp) '''Ha van másik hajó -> a hajó elhelyezése sikertelen (return False)''' return not(anothership) '''Ha nincs több hajó a listában, akkor vége a játéknak''' def checkEndCondition(self): if len(self.__ships) == 0: print("A(z) " + self.__name + " nevű játékos elsüllyedt.") return True else: print(self.__name + " játékosnak " + str(len(self.__ships)) + " hajója van még vízen.") return False '''Megvizsgálja a torpedózott cellát''' def checkForHit(self, cell): if not(self.isCellInputCorrect(cell)): print("Hiba: Nem megfelelő input") return False '''Ha erre a cellára még nem lőttek''' if self.isCellUnmarkedOnBoard(cell): self.markCellOnBoard(cell) s = self.checkCellForShip(cell) if s == None: print("Nem talált...") else: s.removeFromRange(cell) print("Talált!") if len(s.getRange()) == 0: s.sinking() self.__ships.remove(s) del s return True else: '''Ha erre a cellára már lőttek''' print("Ez a cella már ismert.") return False
c813607ae4b9d46863d8944687f5a3aa82d457f2
enesozi/ProjectEuler
/Solutions for Problems 1-25/P7/P7.py
293
3.953125
4
import sys def main(arg): n = int(arg) k = 1 while(n): k+=1 if(isPrime(k)): n-=1 print(k) def isPrime(p): for f in range(2,p): if(p%f == 0): return False; return True; if __name__ == "__main__": main(sys.argv[1])
5cc7296fa5db2e687334227f83f165c05710e1df
LibertyDream/algorithm_data_structure
/solution/array/no_3_2_duplicate_num_no_change.py
1,448
3.96875
4
'''题目三-2:不修改数组找出重复的数字。 在一个长度为n+l的数组里的所有数字都在1~n的范围内,所以数组中至少有一个数字是重复的。 请找出数组中任意一个重复的数字,但不能修改输入的数组。 ------- Example: input:[2,3,5,4,3,2,6,7] output: 2 or 3 -------- 注意交流,问清功能需求(任意一个重复数字还是所有重复数字)和效率需求(时间优先,空间优先) ''' def duplicate(arr:list)-> int: if arr is None: return -1 if len(arr) == 0: return -1 for x in arr: if x < 1 or x > len(arr) - 1: return -1 start = 1 end = len(arr) - 1 while end >= start: mid = start + (end - start) // 2 counts = __count_num(arr, start, mid) if counts > (mid - start + 1): if start == end: return start end = mid else: start = mid + 1 print(start, end) return -1 def __count_num(arr, start,end): if arr is None: return -1 count = 0 for x in arr: if x >= start and x <= end: count += 1 return count if __name__ == "__main__": arr = [] arr1 = None arr2 = [2,3,5,4,8,2,6,7] arr3 = [2,3,5,4,3,2,6,7] print(duplicate(arr)) print(duplicate(arr1)) print(duplicate(arr2)) print(duplicate(arr3))
d9d17aef725c05a8171755adb092843613411b1b
slacksky/ptyhon-basic-talleres
/retow2.py
1,911
3.796875
4
""" Taller 2.3 Distancia mas corta # Jorge Vivas Mayo 16-21 """ import math def main(): ##global var area testing processes ##function area def hipotenusa(A,B):##para calcular longitud de cuerda de la polea C=(((A)**2)+((B)**2))**(1/2) return C def circunferencia(d):##para calcular longitud de cuerda de la polea p=2*math.pi*(d/100)#perimetro en metros de la rueda, (d/100para pasar de cm a m) return p def vueltas(p,rec):##permitro del circulo y recorrido de la polea, regresa n de vueltas (rad?) Nvue=rec/p return Nvue def chewies(Nvue):##redondea hacia arriba por si acaso Nchew=math.ceil(Nvue/3) return Nchew def velo_rueda(rec,t):#recorrido mts, tiempo en mins,veolcidad lineal de la rueda en Cms/seg velol=(rec*100)/(t*60) return velol ##input area ##TODO: add input and float transforation for each #L=3 ##mts default unit, longintud del puente L=float(input("cual es el largo del puente, en metros?\n")) #d=50 ##cms tranformar antes de usar d=float(input("cual es el diametro de la polea en cm?\n")) #t=3 ##tiempo de cierre en min transformar antes d eusar t=float(input("cual es el tiempo en mins para que cierre con seguridad?\n")) ##results area p=circunferencia(d) print("perimetro: ", round(p,4)," metros") rec=hipotenusa(L,L) print("recorrido de la cuerda de la polea para cerrar: ", round(rec,4)," metros") Nvue=vueltas(p,rec) print("vueltas requeridas para cerrar, ", round(Nvue,4)," vueltas") Nchew=chewies(Nvue) print("se requiren unos, ",Nchew," kashykianos, tan grandes como chewbacca") velol=velo_rueda(rec,t) print("la velocidad requerida para cerrar, con seguridad, en ", round(t,0)," mins, es como minimo,", round(velol,4), " cms/seg") if __name__ == "__main__": main()
a326df4bcb03ca9155729ec5ced2a7a9dccac81f
hwakabh/codewars
/Python/8/HowDoICompareNumbers/how_do_i_compare_numbers.py
296
3.90625
4
import sys def what_is(x): if x == 42: return 'everything' elif x == 42 * 42: return 'everything squared' else: return 'nothing' if __name__ == "__main__": if len(sys.argv) == 2: print(what_is(x=int(sys.argv[1]))) else: sys.exit(1)
0969ccbc24107c7ba4ca59193dce95b7d19e383c
lucasffgomes/Python-Intensivo
/seçao_04/exercicios_seçao_04/exercicio_31.py
320
4.15625
4
""" Leia um número inteiro e imprima o seu antecessor e o seu sucessor. """ print("Vamos mostrar o ANTECESSOR e o SUCESSOR.") numero = int(input("Digite um número: ")) antecessor = numero - 1 sucessor = numero + 1 print(f"O número é o {numero}, seu ANTECESSOR é {antecessor} e seu SUCESSOR é {sucessor}.")
398ec05ff160003ab5529d25aa5520aef69b72fa
suhairmu/pythonprograms
/Flow Controls/decision making/positive or negative.py
188
4.125
4
num=int(input("Enter a number:")) if(num<0): print(num,"is negative") elif(num>0): print(num,"is positive") elif(num==0): print(num,"is Zere") else: print(num,"is invalid")
7c50d6ab0717cf9dd41e8c62558942c427a302b0
madeibao/PythonAlgorithm
/PartB/py判断链表是否有环.py
611
3.765625
4
class ListNode(object): def __init__(self, x): self.val =x self.next = None class Solution(): def circle(self,head): if head==None or head.next==None: return False fast = head slow = head while fast.next and fast.next.next: fast = fast.next.next slow = slow.next if slow==fast: return True return False if __name__=='__main__': s = Solution() n2 = ListNode(2) n3 = ListNode(3) n4 = ListNode(4) n5 = ListNode(5) n6 = ListNode(6) n7 = ListNode(7) n2.next = n3 n3.next = n4 n4.next = n5 n5.next = n6 n6.next = n7 n7.next = n4 print(s.circle(n2))
d8f5a1ac4583b2eb6afe9b51c9f80e0f620d4c75
lintonjr/algoritmos_orlewilson
/29-05-2019/2-H).py
255
3.765625
4
# Matéria: Algoritmos # Professor: Orlewilson # Alunos: Linton Junior 182120246, Caio Cezar, Paulo Ricardo while True: n = int(input("Insira um número: ")) print('-' * 30) for c in range(1, 11): print(f'{n} x {c} = {n*c}') print('-' * 30)
e0d353205c33b6ad97af88ccb1a50d5ae13d38a3
shartrooper/My-python-scripts
/py tricks/Python3Dictmergin.py
457
4.4375
4
# How to merge two dictionaries # in Python 3.5+ >>> x = {'a': 1, 'b': 2} >>> y = {'b': 3, 'c': 4} >>> z = {**x, **y} >>> z {'c': 4, 'a': 1, 'b': 3} # In Python 2.x you could # use this: >>> z = dict(x, **y) >>> z {'a': 1, 'c': 4, 'b': 3} # In these examples, Python merges dictionary keys # in the order listed in the expression, overwriting # duplicates from left to right. # # See: https://www.youtube.com/watch?v=Duexw08KaC8
8fcd672fe1078bcbce336f57069c37bd6e2e7fb4
darlcruz/python-challenge-solutions
/Darlington/phase-2/LIST/day 40 challenge/qtn10.py
190
4.09375
4
#Python program access the index of a list. nums = [5, 15, 35, 8, 98] for num_index, num_val in enumerate(nums): print(num_index, num_val) # #key = [4, 7, 9, 45, 34,56] #for index
665891f544c202b5e07042f6ec5d5f7ea646f696
ShangruZhong/leetcode
/Backtracking/79.py
1,701
3.8125
4
""" 79. Word Search Search word horizontally or vertically in the grid @date: 2016/11/01 """ class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ m = len(board) n = len(board[0]) visited = [([0] * n) for i in range(m)] # !!!: initial 2d matrix, avoid shallow copy for i in xrange(m): for j in xrange(n): if self.backtracking(board, word, 0, i, j, visited): return True return False def backtracking(self, board, word, word_index, x, y, visited): """ @params: word_index: character index of word <x, y>: location of point in board visited: flag """ if word_index == len(word): return True # success if x < 0 or y < 0 or x >= len(board) or y >= len(board[0]): return False # out of border if visited[x][y]: return False # have visited, cut if board[x][y] != word[word_index]: return False visited[x][y] = 1 res = self.backtracking(board, word, word_index + 1, x - 1, y, visited) or \ self.backtracking(board, word, word_index + 1, x, y + 1, visited) or \ self.backtracking(board, word, word_index + 1, x + 1, y, visited) or \ self.backtracking(board, word, word_index + 1, x, y - 1, visited) # if true return directly, pruning to reduce complexity, otherwise exceeds time limit visited[x][y] = 0 return res s = Solution() print s.exist(["ABCE","SFCS","ADEE"],"ABCCED")
8745a797b8c7cc21581ea62fbe20d929b4d40a89
Grae-Drake/euler-redux
/problem_12.py
1,505
3.875
4
"""Solve Project Euler Problem 12. Problem statement: The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be: 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? https://projecteuler.net/problem=12 """ import argparse from datetime import datetime from typing import List from tools import factors def solution(limit: int) -> int: """Generate triangle numbers and their factors till we count 500.""" triangle = 1 n = 2 while True: num_factors = len(factors(triangle)) if num_factors > limit: return triangle triangle += n n += 1 if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("limit", help="limit, default to 5", default=5, type=int, nargs='?') args = parser.parse_args() clock_start = datetime.now() answer = solution(args.limit) clock_end = datetime.now() print("The answer is {} for input {}.".format(answer, args.limit)) print("Execution time was {}.".format(clock_end - clock_start))
2050e670ad6fa7908c5551e5034c753b534584e8
jarod117/algorithm009-class01
/Week_02/top-k-frequent-elements.py
1,066
3.703125
4
# python字典(哈希) # 1. 统计数组中每个元素出现的次数; # 2. 对字典进行排序; # 2. 返回出现频率前k高的元素; # class Solution: # def topKFrequent(self, nums: List[int], k: int) -> List[int]: # dicts = collections.defaultdict(int) # # dicts = collections.Counter(nums) # res = [] # for i in nums: # dicts[i] += 1 # print(dicts) # dicts_new = sorted(dicts.items(), key = lambda x: x[1], reverse = True) # print(dicts_new) # for key, value in dicts_new: # print(key) # res.append(key) # return res[:k] # python堆实现 # 1. 统计数组中所有元素的出现次数; # 2. 使用堆对数据进行处理,即可得到按从小到大的顺序的数组 # 3. 返回出现频率前k高的元素; class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: import heapq as hq dicts = collections.Counter(nums) return hq.nlargest(k, dicts.keys(), key = dicts.get)
0f47b7eb455b6edbc394f0c70e6ee2a9ec62befa
ay91911/programers
/level1/3진법.py
407
3.703125
4
n=45 ''' 1) divmod() : 몫과 나머지를 같이 반환해주는 함수 2) int(x, base) : base 진법으로 구성된 str 형식의 수를 10진법으로 변환해 줌 python의 int 함수는 진법 변환을 지원합니다. ''' def solution(n): answer='' while n >= 1: n, rest = divmod(n, 3) answer += str(rest) answer = int(answer, 3) return answer print(solution(n))
dfade170f47eccf837eba8aabe7a10f4b69b6d64
Rav2326/python_bootcamp
/kolekcje/wisielecrozwiazanie.py
1,062
3.625
4
<<<<<<< HEAD slowo = "python" wynik = ["_" for x in slowo] szanse = len(slowo) + 3 #czyli slowo + 3 szanse print(slowo) print(wynik) while True: if szanse == 0: print("Przegrałeś") break znak = input("Wprowadź znak: ") if znak not in slowo: szanse -= 1 i = 0 for litera in slowo: if znak == litera: wynik[i] = znak i += 1 if wynik == slowo: #print("Wygrałeś! ") - wlacz to i zastanow co jest zle #break ======= slowo = "python" wynik = ["_" for x in slowo] szanse = len(slowo) + 3 #czyli slowo + 3 szanse print(slowo) print(wynik) while True: if szanse == 0: print("Przegrałeś") break znak = input("Wprowadź znak: ") if znak not in slowo: szanse -= 1 i = 0 for litera in slowo: if znak == litera: wynik[i] = znak i += 1 if wynik == slowo: #print("Wygrałeś! ") - wlacz to i zastanow co jest zle #break >>>>>>> origin/master print(wynik)
18e91bc2a5af74a31a776cbca80ba7278915b662
domGitDev/MissingNumbers
/missing_numbers.py
862
4.0625
4
def find_missing(A, m, B, n): """ This function find missing numbers in A using B param A: list param m: int param B: list param n: int return: sorted list """ def validate(): def check_type(obj): if not isinstance(obj, (list, tuple, set)): return False return True if not A or not B: return False if m > n or m < 0 or n < 0: return False if not check_type(A) or not check_type(B): raise TypeError( 'Expected list or tuple. A is %s and B is %s.' % (type(A), type(B))) return True if not validate(): return None A = sorted(A) B = sorted(B) missing = set() j = 0 prev = None for val in B: if j > m: missing.add(val) elif val != A[j]: missing.add(val) # occurrency in A is greater than in B while prev == A[j]: j += 1 else: j += 1 return sorted(missing)
be58cdb7f0f0007740bb033912b91a5e0d158703
sipakhti/code-with-mosh-python
/CS 112 Spring 2020/Three Card Poker.py
4,785
4.25
4
def straight_flush(one, two, three): """Returns True if its a straight flush""" # three combination of cards (a,b,c), (b,a,c), (c,a,b) combo1 = (one + two + three) / 3 == one combo2 = (one + two + three) / 3 == two combo3 = (one + two + three) / 3 == three # to calculate the midlde card middle_card = (one + two + three) / 3 # to make sure that the cards are of the same type i.e Clubs,Diamonds,Hearts,Spades if 12 < middle_card < 15 or 25 < middle_card < 28 or 38 < middle_card < 41: return False else: pass # for Clubs if one / 13 <= 1 and two / 13 <= 1 and three / 13 <= 1: if combo1 or combo2 or combo3: return True else: return False # for Diamonds elif (one / 13 <= 2 and one >= 14) and (two / 13 <= 2 and two >= 14) and (three / 13 <= 2 and three >= 14): if combo1 or combo2 or combo3: return True else: return False # for Hearts elif (one / 13 <= 3 and one >= 27) and (two / 13 <= 3 and two >= 27) and (three / 13 <= 3 and three >= 27): if combo1 or combo2 or combo3: return True else: return False # for Spades elif (one / 13 <= 4 and one >= 40) and (two / 13 <= 4 and two >= 40) and (three / 13 <= 4 and three >= 40): if combo1 or combo2 or combo3: return True else: return False else: return False def three_of_a_kind(one, two, three): """return True if all the cards are of the same rank""" # same rank cards have a difference which is a multiple of 13 combo1 = abs(one-two) % 13 == 0 combo2 = abs(two-three) % 13 == 0 if combo1 and combo2: return True return False def straight(one, two, three): """ Returns True if three cards are in sequence""" if straight_flush(one, two, three): return False # if two contigous suited cards and one different kind card in sequence where the lone card is smaller if (abs(one - two) % 12 == 0 or abs(one - three) % 12 == 0 or abs(two - three) % 12 == 0): return True # if two contigous suited cards and one different kind card in sequence where the lone card is larger if (abs(one - two) % 14 == 0 or abs(one - three) % 14 == 0 or abs(two - three) % 14 == 0): return True # if all three are in a series but of different kinds if (abs(one - two) % 14 == 0 or abs(one-three) % 14 == 0) and (abs(two-three) % 14 == 0): return True # to make the code more cleaner the last IF logic is saved in three variables because the code # is lenghty owing to the fact that the difference increases as the difference in the Kinds increase # and due to limition of not using loops the code is repetitive diff12 = abs(one - two) == 12 or abs(one - three) == 12 or abs(two - three) == 12 diff25 = abs(one - two) == 25 or abs(one - three) == 25 or abs(two - three) == 25 diff40 = abs(one - two) == 40 or abs(one - three) == 40 or abs(two - three) == 40 # if the central card is of a different kind and the same kind cards are seperated if (abs(one - two) == 2 or abs(one - three) == 2 or abs(two - three) == 2) and (diff12 or diff25 or diff40): return True return False def flush(one, two, three): """Returns True if all cards are of the same kind""" # demaracation of boundries clubs = one <= 13 and two <= 13 and three <= 13 diamonds = 13 < one <= 26 and 13 < two <= 26 and 13 < three <= 26 hearts = 26 < one <= 39 and 26 < two <= 39 and 26 < three <= 39 spades = 39 < one <= 52 and 39 < two <= 52 and 39 < three <= 52 if clubs: return True elif diamonds: return True elif hearts: return True elif spades: return True return False def pair(one, two, three): """ Returns True if ONLY two cards are of the same rank""" # different combinations that could result in a pair combo1 = abs(one-two) % 13 == 0 combo2 = abs(two - three) % 13 == 0 combo3 = abs(one-three) % 13 == 0 # check to see if all are same or not if three_of_a_kind(one, two, three): return False if combo1: return True elif combo2: return True elif combo3: return True return False def high_card(one, two, three): """Returns True if no other scenario satisfies the argument""" if straight_flush(one, two, three) or three_of_a_kind(one, two, three) or straight(one, two, three) or flush(one, two, three) or pair(one, two, three): return False return True
207cff98bce1041d94ffbb5b13ddc888db2935a0
mmkmou/auf-django-users
/lib/utils.py
714
3.6875
4
# -*- encoding: utf-8 -*- import random, crypt def password_crypt( password ): """reçoit un mot de passe et le renvoie crypté (md5). Ne fait rien si le mot de passe semble être déjà crypté ; renvoie 'x' si le mot de passe est vide ou déjà égal à 'x'""" if password in ( None, '', 'x' ): return "x" # mot de passe "invalide" elif password[0:3] == '$1$': # TODO : une regex plus restrictive return password # mot de passe déjà crypé else: salt = "$1$" + '' \ .join( [ random.choice( 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ) for i in xrange(8) ]) return crypt.crypt( password, salt )
0124d302390d548b5cd2b07eda971d8b7a99d7be
arp6695/lsys
/src/classes/lsys.py
6,086
3.84375
4
""" Lindenmeyer System (lsys) class definition. By: Alex Piazza Lessons courtesy of Wikipedia https://en.wikipedia.org/wiki/L-system A Lindenmeyer system is a way of rewriting strings. The symbols within these strings change according to rules, and, when interpreted as commands to be executed by a turtle, produce fractal images. L-Systems have: An Alphabet: A collection of Symbols that, along with the ruleset, collectivly comprise the L-System An Angle: The default angle that the turtle should turn Expressed by an float value 0-360, interpreted as degrees NOTE: I've seen lsys' angles be expressed as a divisor of 360 e.g. If the lsys angle = 6, then the angle which turtle will turn is 360/6 degrees, or 60 degrees In this implementation, the L-System's angle is the angle that the turtle will turn, both left and right. An Axiom: A symbol or string of symbols that represents the initial state of the system A Symbol is a string token, and are either: A Constant: symbol which is not mapped to any string by the ruleset, and is therefore never changed A Variable: symbol which is mapped to a resultant string of other symbols in some way. There's no hard and fast trait that defines a symbol as a constant or variable within this L-System alphabet. i.e. Symbols are constant or vary by convention; this distinction is not specified in this system. Implicitly, a constant is defined as a variable that maps only to itself. Ruleset: 'rules' describing how symbols change from iteration to iteration. Specficially, this will be represented by a dictionary with the following key/val pairs: <symbol, rule> Where 'symbol' is a variable symbol and 'rule' is a rule object (see rule.py): """ class Lsys( object ): def __init__( self, name, angle, axiom, ruleset ): """ Constructor Args: name: A string identifier representing this L-System. angle: The default angle that the turtle should turn. axiom: The default string that will be operated upon ruleset: The map of tokens to rules that transform those tokens. Raises: IOError: If any of the parameters are improperly typed. """ if not isinstance(axiom, str): raise IOError("Axiom must be a string.") if not isinstance(ruleset, dict): raise IOError("Ruleset must be a dictionary.") if not isinstance(angle, float) and not isinstance(angle, int): raise IOError("Angle must be an float") if not isinstance(name, str): raise IOError("Name must be a string") self.name = name self.angle = angle self.axiom = axiom self.ruleset = ruleset self.vars = [] self.alphabet = self.genAlphabet() def __repr__( self ): """ Create and return the string representation of an lsys object. Return: Console-friendly string representation of an L-System. """ result = "Name: {0}\nAngle: {1} degrees\nAlphabet: {2}\nAxiom: {3}\n{4}" rule_string = "" for var in self.ruleset.keys(): rule = self.ruleset[var] for context in rule.productions.keys(): left_context = ("" if context.left == "/*" else "{} < ".format(context.left)) right_context = ("" if context.right == "/*" else " > {}".format(context.right)) cases = rule.productions[context] case_string = "" for i in range(len(cases.results)): probability_string = "" if cases.probabilities[i] == 1 else "({}%) ".format(round(cases.probabilities[i] * 100, 2)) case_string += "{}{}; ".format( probability_string, cases.results[i]) rule_string += "{0}{1}{2} -> {3}\n".format(left_context, var, right_context, case_string) if len(self.alphabet) == 0: self.alphabet = self.genAlphabet() alphabet_string = "" for sym in self.alphabet: alphabet_string += "{} ".format(sym) return result.format( self.name, self.angle, alphabet_string, self.axiom, rule_string ) def getVars(self): """ Return every variable associated with this lsys. """ if self.vars == []: for var in self.ruleset.keys(): self.vars += var return self.vars def genAlphabet(self): """ Create and return the alphabet of this lsys. Returns: A list containing every symbol that this L-System could generate. """ result = [] for var in self.ruleset.keys(): if var not in result: result.append(var) for context in self.ruleset[var].productions.keys(): cases = self.ruleset[var].productions[context] for string in cases.results: for symbol in string: if symbol not in result: result.append(symbol) return result def isComplete(self): """ Check if this L-System object has been populated compeltely and correctly. Returns: True if the lsys has valid and complete fields. False otherwise. """ return len(self.name) > 0 and len(self.axiom) > 0 and len(self.ruleset) > 0 and self.angle is not 0 def getResult( self, var, left_token, right_token ): """ Get the resultant string, given the right and left tokens Args: var: A variable symbol in this lsys' alphabet rotken: A symbol in the lsys' alphabet, to the right of 'var' ltoken: A symbol in the lsys' alphabet, to the left of 'var' """ return self.ruleset[var].getResult( left_token, right_token ) def getEmptyLsys(): """ Create and return an lsys with default params """ return Lsys( str(), int(), str(), dict() )
4482a3552052401bc1a818bcdb63b7c362eddd0b
benmoseley/FBPINNs
/fbpinns/util/io.py
1,661
3.796875
4
""" Helper I/O functions """ import os import shutil import glob def get_dir(directory): """ Creates the given directory if it does not exist. """ if not os.path.exists(directory): os.makedirs(directory) return directory def clear_dir(directory): """ Removes all files in the given directory. """ # important! if None passed to os.listdir, current directory is wiped (!) if not os.path.isdir(directory): raise Exception(f"{directory} is not a directory") if type(directory) != str: raise Exception(f"string type required for directory: {directory}") if directory in ["..",".", "","/","./","../","*"]: raise Exception("trying to delete current directory, probably bad idea?!") for f in os.listdir(directory): path = os.path.join(directory, f) try: if os.path.isfile(path): os.remove(path) elif os.path.isdir(path): shutil.rmtree(path) except Exception as e: print(e) def clear_files(glob_expression): """ Removes all files matching glob expression. """ for f in glob.glob(glob_expression): if os.path.isfile(f): os.remove(f) def remove_dir(directory): """ Recursively removes directory. """ # important! if not os.path.isdir(directory): raise Exception(f"{directory} is not a directory") if type(directory) != str: raise Exception(f"string type required for directory: {directory}") if directory in ["..",".", "","/","./","../", "*"]: raise Exception("trying to delete current directory, probably bad idea?!") shutil.rmtree(directory)
b8177772b0c2aac907c6b5139d0fa6d3f02b1e36
JaxLuo0405/CS542-Final
/Code/src/data_processing_draft.py
3,223
3.515625
4
# This code will be used to pre-possessing the data. import numpy as np import pandas as pd from pandas import DataFrame from collections import defaultdict import sklearn as sk from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor world_happiness = pd.read_csv ('../data/world-happiness-report.csv') world_happiness_shape = world_happiness.shape # print(world_happiness) world_happiness_2021 = pd.read_csv ('../data/world-happiness-report-2021.csv') world_happiness_2021_shape = world_happiness_2021.shape # print(world_happiness_2021) # there are 373 null values in world_happiness and we currently find which country the null value belongs to # and replace it with the mean of the column of that country. # 1. create a dictionary with keys of countries and values of their data: world_happiness_dict = defaultdict() for row in range(world_happiness_shape[0]): value = world_happiness.loc[row].tolist() keys = world_happiness_dict.keys() current_country = world_happiness.loc[row][0] if (current_country in world_happiness_dict.keys()): world_happiness_dict[current_country].append(value[1:]) else: world_happiness_dict[current_country] = [value[1:]] # We delte the countries with only one row of values, for which we cannot find the current column mean. country_with_one_row_data = [] for country in world_happiness_dict.keys(): if len(world_happiness_dict.get(country)) == 1: country_with_one_row_data.append(country) print("the countries with only one row of data are:", country_with_one_row_data) print("We delete these 5") for country in country_with_one_row_data: world_happiness_dict.pop(country, None) # 2. find all "nan" value and replace it with the current mean of the column of the country: # traverse all the keys in the dictionary and for each country, for country in world_happiness_dict.keys(): df = pd.DataFrame(world_happiness_dict.get(country)) for column in range (1,10) : mean_value=df[column].mean() df[column].fillna(value=mean_value, inplace=True) world_happiness_dict[country] = df # test: print(world_happiness_dict.get("Algeria")) #3. construct a dataframe to extract 80% of the data as the training data and 20% as the testing data. # There are 166 countries within the dataset # Within the dataset, there are in total 1949 data entries print(len(world_happiness_dict.keys())) total = 0 training_set = [] testing_set = [] for country in world_happiness_dict.keys(): total_data = world_happiness_dict.get(country) train, test = train_test_split(total_data, test_size=0.2, random_state=50, shuffle=True) training_set.append(train) testing_set.append(test) training_data = pd.concat(training_set) testing_data = pd.concat(testing_set) print("Training data dimensions: ", training_data.shape) print("Testing data dimensions: ", testing_data.shape) print(training_data) ''' # Create a Random Forest Regressor object from Random Forest Regressor class: RFreg = RandomForestRegressor(n_estimators = 50, random_state = 0) x_train = training_data[2:] y_train = training_data[1] RFreg.fit(x_train, y_train) print(training_data) '''
6f277a1d9c57f4db1dff8a29df583347f9df354c
jpallavi23/Smart-Interviews
/06_SI_Basic-Hackerrank/45_Print pyramid pattern.py
535
4.15625
4
''' Print pyramid pattern. See example for more details. Input Format First line of input contains a single integer N - the size of the pyramid. Constraints 1 <= N <= 50 Output Format For the given integer, print pyramid pattern. Sample Input 0 5 Sample Output 0 * *** ***** ******* ********* ''' size = int(input()) for itr in range(1, size+1): temp = 0 for ctr in range(1, (size - itr) + 1): print(end=" ") while temp != (2 * itr - 1): print("*", end="") temp += 1 print("\r")
8d59bc8820255766247f65bc16a683ce519212af
shaneebavaisiar/pythonDjangoLuminar
/pyhtoncollections/listprograms/listiteration.py
120
3.5
4
lst=[50,30.2,True,'hello',25,50] for num in lst: print(num) # or # for i in range(0,len(lst)): # print(lst[i])
ff55704be2f7eed8718a6ca091620dacf282781f
DanielMevs/Analyzing-More-CSV-Files-with-Python
/csv_movies.py
7,974
3.6875
4
#Daniel Mevs import csv #returns a list of top rated films def get_rating_list(rating_list): with open('imdb-top-rated.csv', 'r', encoding='utf-8') as rating_file: file_content = csv.reader(rating_file) next(file_content) temp_tup = () for row in file_content: temp_tup = temp_tup + (int(row[0]), row[1], int(row[2]), float(row[3]),) rating_list.append(temp_tup) temp_tup = () return rating_list #returns a list of top grossing films def get_gross_list(gross_list): with open('imdb-top-grossing.csv', 'r', encoding='utf-8') as gross_file: file_content = csv.reader(gross_file) next(file_content) temp_tup = () for row in file_content: temp_tup = temp_tup + (int(row[0]), row[1], int(row[2]), float(row[3]),) gross_list.append(temp_tup) temp_tup = () return gross_list #returns a list of cast members def get_cast_list(cast_list): with open('imdb-top-casts.csv', 'r', encoding='utf-8') as cast_file: file_content = csv.reader(cast_file) next(file_content) temp_tup = () for row in file_content: temp_tup = tuple(row) #print("\n",temp_tup) cast_list.append(temp_tup) temp_tup = () return cast_list #returns a dictionary of top rated films def get_rating_dict(rating_list): rating_dict = {} rating_dict = {(column[1], column[2]) : (column[0],column[3]) for column in rating_list} return rating_dict #returns a dictionary of top grossing films def get_gross_dict(gross_list): gross_dict = {(column[1], column[2]) : (column[0], column[3]) for column in gross_list} return gross_dict #returns a dictionary of a cast def get_cast_dict(cast_list): cast_dict = {(column[0], int(column[1])) : (column[2:]) for column in cast_list} return cast_dict def director_count(cast_dict, rating_dict): #rating_dict can apply to top-rated as well as top-grossing dictionaries count = {} rating_keys = set(rating_dict.keys()) #gets the keys for rating for key in rating_keys: try: name = cast_dict[key][0] #gets the name of the director except KeyError: continue #print(name) count[name] = count.get(name, 0) + 1 #second parameter of .get() method specifies the value returned if the value if key is not found. #in this way, it counts how many times a director is mentioned by assigning a value and incrimenting # print(count[name]) temp_list = [] for name, number in count.items(): temp_list.append((number, name)) director_list = sorted(temp_list, reverse=True) print(director_list) return director_list def get_actor_dict(cast_dict): actor_dict = {} #dictionary with actor as key and movie(s) as value for movie, cast in cast_dict.items(): for actor in cast[1:]: #starts at [1:] because starting at [0:] would give you directors if actor in actor_dict: actor_dict[actor].append(movie) #this condition runs if there are already actors in the dictionary and it appends new ones else: actor_dict[actor] = [movie] #this condtion runs if there are no known actors in the list and it add is to the dictionary return actor_dict def actor_rating_count(actors_dict, rating_dict): #counts the number of times a given actor appears in top-rated movies count = {} rating_keys = set(rating_dict.keys()) #gets keys to rating for (actor, movies) in actors_dict.items(): for movie in movies: if movie in rating_keys: count[actor] = count.get(actor, 0) + 1 temp_list = [] for name, number in count.items(): temp_list.append((number, name)) #print(temp_list) actor_rating_list = sorted(temp_list, reverse=True) return actor_rating_list def actor_grossing_count(gross_dict, cast_dict): actor_gross = {} for movie in gross_dict.keys(): try: gross_amount = gross_dict[movie][1] except IndexError: continue try: actors = cast_dict[movie][1:] except KeyError: continue cast_length = len(actors) for i, actor in enumerate(actors): actor_gross[actor] = actor_gross.get(actor, 0) + (((2**(cast_length-i))* gross_amount) / 31) #formula to allocate earnings per actor temp_list = [] for amt, actr in actor_gross.items(): temp_list.append((actr, amt)) actor_grossing_list = sorted(temp_list, reverse=True) return actor_grossing_list def print_director_rating(directors): print('Directors with most movies in top-rated list') top_border = '-'*50 print(top_border) print('{:<20s} | {:<5s}'.format('Directors', 'Count')) print('{:<20s} | {:<5s}'.format('-'*20, '-'*5)) for i, row in enumerate(directors): print(i+1, ' ', '{:<20s} | {:<5d}'.format(row[1], row[0])) if i == 5: #condition that will allow only the top 5 to be printed break print('\n\n') def print_director_grossing(directors): print('Directors with most movies in top-grossing list') top_border = '-'*50 print(top_border) print('{:<20s} | {:<5s}'.format('Directors', 'Count')) print('{:<20s} | {:<5s}'.format('-'*20, '-'*5)) for i, row in enumerate(directors): print(i+1, ' ', '{:<20s} | {:<5d}'.format(row[1], row[0])) if i == 5: #condition that will allow only the top 5 to be printed break print('\n\n') def print_actor_grossings(actors): print('Actors with most gross-earnings in top-grossing list') top_border = '-'*50 title_border = '-'*20 print(top_border) print('{:<20s} | {:<5s}'.format('Actor', 'Amount Grossed')) print('{:<20s} | {:<20s}'.format(title_border, title_border)) for i, row in enumerate(actors): print(i+1, ' ', '{:<20s} | {:<20.2f}'.format(row[1], row[0])) if i == 5: #condition that will allow only the top 5 to be printed break print('\n\n') def print_actor_rating(actors): print('Actors with most movies in top-rated list') top_border = '-'*50 title_border = '-'*20 print(top_border) print('{:<20s} | {:<5s}'.format('Actor', 'Appearances in top-rated')) print('{:<20s} | {:<5s}'.format(title_border, title_border)) for i, row in enumerate(actors): print(i+1, ' ', '{:<20s} | {:<5d}'.format(row[1], row[0])) if i == 5: #condition that will allow only the top 5 to be printed break print('\n\n') def main(): rating_list = [] rating_list = get_rating_list(rating_list) #print(rating_list) gross_list = [] gross_list = get_gross_list(gross_list) #print(gross_list) cast_list = [] cast_list = get_cast_list(cast_list) #print(cast_list) rating_dict = get_rating_dict(rating_list) print(rating_dict) gross_dict = get_gross_dict(gross_list) #print(gross_dict) cast_dict = get_cast_dict(cast_list) #print(cast_dict) top_rated_director = director_count(cast_dict, rating_dict) #creates a dictionary of top-rated directors top_grossing_director = director_count(cast_dict, gross_dict) #creates a dictionary of top-rated directors actor_dict = get_actor_dict(cast_dict) #creates a dictionary of actors top_rated_actors = actor_rating_count(actor_dict, rating_dict) top_grossing_actors = actor_grossing_count(gross_dict, cast_dict) #print(top_rated_actors) print_director_rating(top_rated_director) print_director_grossing(top_grossing_director) print_actor_rating(top_rated_actors) print_actor_grossings(top_grossing_actors) if __name__ == '__main__': main()
a646f863ad1ba5eec32777c208af14f8d1020b21
Nekenhei/CursoPython_NextU
/Modulo 5/Actividad 2.1.py
700
3.890625
4
from abc import abstractmethod, ABC class Figura(ABC): def __init__(self,nombre): self.nombre = nombre @abstractmethod def area(self): pass def perimetro(self): pass class Rectangulo(Figura): def __init__(self,nombre,base,altura): super().__init__(nombre) self.base = base self.altura = altura def area(self): return self.base*self.altura def perimetro(self): return 2*(self.base+self.altura) rect = Rectangulo("Rectangulo 1",3.0,4.0) cuad = Rectangulo("Cuadrado Unitario",1.0,1.0) print("El rectangulo"+rect.nombre+"tiene area de"+str(rect.area)+"y perimetro de"+str(rect.perimetro))
0a3d2da97a5346e98bebb60323007b48ae466b11
jpablolima/Machine_Learning_Deep_Learning
/histogramaAmigos.py
945
3.921875
4
# -*- coding: utf-8 -*- #________ Importar para alterar a fonte padrão__________# from __future__ import unicode_literals #_______________________________________________________# from matplotlib import pyplot as plt from collections import Counter num_friends = [100,49,41,40,25,75,60,6,70,61, 11,91,24,92,87, 40,7,42,52,100, 59,68,93,4,2, 20,3,84,66,81, 61,26,33,23,77, 84,13,38,23,22, 73,33,87,7,76, 45,78,70,91,55, 25,76,67,92,52] friend_counts = Counter(num_friends) xs = range(101) # valor maior é 100 ys = [friend_counts[x] for x in xs] # altura é somente # amigos num_points=len(num_friends) largest_value = max(num_friends) smallest_value = min(num_friends) sorted_values = sorted(num_friends) smallest_value = sorted_values[1] second_largest_value = sorted_values[-2] plt.bar(xs,ys) plt.axis([0,101,0,25]) plt.title("Histograma da Contagem de Amigos") plt.xlabel("# de amigos") plt.ylabel("# de pessoas") plt.show()
4c75ccb3ee78c92b637bd5c58cace970f758d86c
Alighorashi95/Python-learning
/ProjectEuler/Problem1.py
114
3.609375
4
i = 0 for k in range(0, 1000): if k % 3 == 0 or k % 5 == 0: i += k else: continue print(i)
54afcc3930bfaf9e2c5afa953cbcdd0438dd1e35
smahs/euler-py
/20.py
767
4.15625
4
#!/usr/bin/python2 """ Statement: n! means n x (n - 1) x ... x 3 x 2 x 1 For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ from unittest import TestCase, main class Problem20(object): def __init__(self, bound): self.bound = bound def fn(self): return sum(map(int, str(reduce(lambda i, j: i*j, xrange(*self.bound))))) class TestProblem20(TestCase): def setUp(self): self.bound = (1, 100) self.answer = 648 def test_main(self): self.assertEqual(Problem20(self.bound).fn(), self.answer) if __name__ == '__main__': main()
311f1a877ef41c0b7decf8894fe99c806c7951bd
reedcwilson/exercises
/python/isogram/isogram.py
226
3.9375
4
def is_isogram(string): # extract letters and lowercase them chars = [c.lower() for c in string if c.isalpha()] # eliminate any duplicates and compare the size of strings return len(set(chars)) == len(chars)
04bc0d4a727beaaa75f844d6846283fd7cf1951b
pedh/CLRS-Solutions
/codes/sort.py
1,977
4.25
4
""" Sort. """ import random def insertion_sort(array): """Insertion sort.""" length = len(array) for i in range(1, length): val = array[i] while i > 0 and array[i - 1] > val: array[i] = array[i - 1] i -= 1 array[i] = val return array def selection_sort(array): """Selection sort.""" length = len(array) for i in range(length - 1): val = array[i] k = i for j in range(i + 1, length): if array[j] < val: k = j val = array[j] array[i], array[k] = array[k], array[i] return array def merge_sort(array): """Merge sort.""" def merge(array, left, mid, right): left_subarray = array[left: mid + 1] right_subarray = array[mid + 1: right + 1] j = 0 k = 0 for i in range(left, right + 1): if j > mid - left: array[i: right + 1] = right_subarray[k:] break elif k >= right - mid: array[i: right + 1] = left_subarray[j:] break if left_subarray[j] <= right_subarray[k]: array[i] = left_subarray[j] j += 1 else: array[i] = right_subarray[k] k += 1 def merge_rec(array, left, right): if left >= right: return mid = (left + right) // 2 merge_rec(array, left, mid) merge_rec(array, mid + 1, right) merge(array, left, mid, right) merge_rec(array, 0, len(array) - 1) return array def main(): """The main function.""" array = list(range(20)) random.shuffle(array) print(array) insertion_sort(array) print(array) random.shuffle(array) print(array) selection_sort(array) print(array) random.shuffle(array) print(array) merge_sort(array) print(array) if __name__ == "__main__": main()
56faa539d6cc86e3fa50e08bdae1e66a7fb1226e
js1294/ECM-1400-Programming
/CA2/ex1.py
378
3.84375
4
"""This is exercise 1.""" __author__ = "Jack Shaw" def vat(pretax_price: float, kids=False, category="miscellaneous") -> float: """This will calculate the total price of a purchase including tax.""" tax = 0.2 if (kids is True and category == "clothing") or category == "food": tax = 0 price = pretax_price + pretax_price * tax return price
538a220abfaaf52de36efedac9519432bed95913
Alex19-91/Python
/Lesson_2/2.3.1.py
552
4.21875
4
month = int(input('Введите номер месяца (от 1 до 12):')) while month<1 or month>12: month = int (input('Введите номер месяца (от 1 до 12):')) month_list = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] if month==month_list[0] or month==month_list[1]or month==month_list[2]: print('Winter') elif month==month_list[3] or month==month_list[4] or month==month_list[4]: print('Spring') elif month==month_list[6] or month==month_list[7] or month==month_list[8]: print('Summer') else: print ('Autumn')
cc386251ac263a80756c3c03c020d8f4fa067d66
daniel-reich/turbo-robot
/vYYfFAAfjoc8crCqu_17.py
424
4.15625
4
""" Write a function to create a Christmas tree based on height `h`. ### Examples tree(1) ➞ [ "#" ] tree(2) ➞ [ " # ", "###" ] tree(5) ➞ [ " # ", " ### ", " ##### ", " ####### ", "#########" ] tree(0) ➞ [] ### Notes N/A """ def tree(h): return [" "*(h-i)+"#"*(2*i-1)+" "*(h-i) for i in range(1,h+1)]
145cda1e6574dd16ff6270a27dffc42903870816
pansinyoung/python-lint
/151_Best_Time_to_Buy_and_Sell_Stock_III.py
1,010
3.9375
4
""" 151. Best Time to Buy and Sell Stock III Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Example Example 1 Input : [4,4,6,1,1,4,2,5] Output : 6 Notice You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). """ class Solution: def maxProfit(self, prices): if not prices or len(prices) <= 1: return 0 n = len(prices) p1 = [0 for _ in prices] p2 = [0 for _ in prices] min_price = prices[0] for i in range(1, n): p1[i] = max(prices[i] - min_price, p1[i-1]) min_price = min(min_price, prices[i]) max_price = prices[n - 1] for i in range(n - 2, -1, -1): p2[i] = max(max_price - prices[i], p2[i + 1]) max_price = max(max_price, prices[i]) return max([p1[i] + p2[i] for i in range(n)])
a4fd75e00b2aca633622ed130f0e5096d3d9c419
Aasthaengg/IBMdataset
/Python_codes/p02391/s128485204.py
182
3.828125
4
input_line1 = raw_input() work = input_line1.split(' ') ret = 'a == b' if int(work[0]) < int(work[1]): ret = 'a < b' if int(work[0]) > int(work[1]): ret = 'a > b' print(ret)
d430b560aee2e7bb1902aa2375d17b6ebff752c0
ParkerLLF/LanQiaoCode_Python
/蓝桥杯官网试题/基础练习/杨辉三角.py
339
3.515625
4
def triangles(num): n = [1] while num > 0: for i in range(len(n)): print(n[i], end=' ') # 将列表转为要求的格式 n = [1] + [n[i] + n[i+1] for i in range(len(n) - 1)] + [1] num -= 1 print() # 换行 if __name__ == '__main__': n = int(input()) triangles(n)
c7876b4a1691e10e7a795f01c44c995d0af46504
tyree88/PythonRefreshers
/python3/exerciseFiles/Functions/defining.py
456
3.546875
4
def main(): # parathenese are used for passing parameters # we are passing in 5 to the function kitten(5) x = kitten() print(x) # returns none - all functions return a value - until kitten has a return def kitten(n): print(f'{n} meow') # tests for value equality # this __name__ is the name of the file # when it is imported. however it is NOT imported and using the main file if __name__ == '__main__': main()
178311204140105166ec2a7212a72be557835f7f
uiandwe/TIL
/algorithm/backjoon/37.etc/10809/acmicpc11723/11723.py
525
3.53125
4
def solution(arr): d = [0 for x in range(21)] ret_arr = [] for op in arr: if op[0] == "add": d[op[1]] = 1 elif op[0] == "check": ret_arr.append(d[op[1]]) elif op[0] == "remove": d[op[1]] = 0 elif op[0] == "toggle": d[op[1]] ^= 1 elif op[0] == "all": for i in range(len(d)): d[i] = 1 elif op[0] == "empty": for i in range(len(d)): d[i] = 0 return ret_arr
9c338d3548f66e5186aefed58814ebcacbabdc03
rvsp/Python3-reference
/Class & Objects/5_polymorphism.py
556
3.984375
4
''' Owner: Venkatasubramanian Topic: Polymorphism ''' class Parrot: def fly(self): print("Parrot can fly") def swim(self): print("Parrot can't swim") class Penguin: def fly(self): print("Penguin can't fly") def swim(self): print("Penguin can swim") # common interface def flying_test(t): t.fly() def swim_test(t): t.swim() #instantiate objects blu = Parrot() peggy = Penguin() blu1 = Parrot() # passing the object flying_test(blu) flying_test(peggy) swim_test(peggy) swim_test(blu1)
a6805846141351bec449f740dcfb01ab65e467ce
LukeBarry/stats
/monte_carlo.py
1,527
4.375
4
'''This script demonstrates simulations of die flipping''' import random # let's create a fair die object that can be rolled: class Coin(object): '''this is a simple fair die, can be pseudorandomly rolled''' sides = ('1', '2', '3', '4', '5', '6') last_result = None def flip(self): '''call die.flip() to flip the die and record it as the last result''' self.last_result = result = random.choice(self.sides) return result # let's create some auxilliary functions to manipulate the coins: def create_coins(number): '''create a list of a number of coin objects''' return [Coin() for _ in xrange(number)] def flip_coins(coins): '''side effect function, modifies object in place, returns None''' for coin in coins: coin.flip() def count_1(flipped_coins): return sum(coin.last_result == '1' for coin in flipped_coins) def count_2(flipped_coins): return sum(coin.last_result == '2' for coin in flipped_coins) def count_3(flipped_coins): return sum(coin.last_result == '3' for coin in flipped_coins) def count_4(flipped_coins): return sum(coin.last_result == '4' for coin in flipped_coins) def count_5(flipped_coins): return sum(coin.last_result == '5' for coin in flipped_coins) def count_6(flipped_coins): return sum(coin.last_result == '6' for coin in flipped_coins) def main(): coins = create_coins(1000) for i in xrange(100): flip_coins(coins) print(count_1(coins)) if __name__ == '__main__': main()
4256193ae9b1c8d5d08f3798ce9a4fc379ebf3a9
Klose6/Leetcode
/84_largest_rectangle_in_histogram.py
844
3.84375
4
""" 84 largest rectangle in histogram The stack maintain the indexes of buildings with ascending height. Before adding a new building pop the building who is taller than the new one. The building popped out represent the height of a rectangle with the new building as the right boundary and the current stack top as the left boundary. Calculate its area and update ans of maximum area. Boundary is handled using dummy buildings """ def largest_rectangle(heights): res = 0 stack = [-1] # in case when the len(stack) == 1 for line 21 heights.append(0) # add one more element for final check for i in range(len(heights)): while heights[i] < heights[stack[-1]]: h = heights[stack.pop()] w = i - stack[-1] - 1 res = max(res, h * w) stack.append(i) heights.pop() return res print largest_rectangle([2, 1, 5, 6, 2, 3]) # 10
87e14157ae0dea228a10534e185410be8c04fd8f
huci12/python
/nam1/Lect/exceptionTest.py
702
3.71875
4
#파이썬 예외 처리 try/ except try: val = "10.5" n = int(val) except: print("오류") try: val = "10.5" n = int(val) except ValueError as e: print("오류발생 {}".format(e)) try: idx = [] idx[0] = 100 except IndexError as e: print("오류발생 {}".format(e)) try: idx = [] idx[0] = 100 except Exception as e: print("오류발생 {}".format(e)) pass print("OK") try: n = "10" v = int(n) except: print("오류발생") else: print("정상동작") try: files = open("sameple.txt","r") n = "10.5" v = int(n) except: print("오류발생") finally: files.close() print("최종 도착")
029d038999f696c26d11c16de31042500302ff88
guoweifeng216/python
/python_design/pythonprogram_design/Ch6/6-1-E29.py
365
4.03125
4
while True: try: n = int(input("Enter a nonzero integer: ")) reciprocal = 1 / n print("The reciprocal of {0} is {1:,.3f}".format(n, reciprocal)) break except ValueError: print("You did not enter a nonzero integer. Try again.") except ZeroDivisionError: print("You entered zero. Try again.")
39a57b9c793ac12f9fac0d8ceeb3d1930b0d00c6
NinjaNed/ProjectEulerPythonSolutions
/Problem 2.py
839
3.828125
4
#!/usr/bin/env python __author__ = 'Ned Udomkesmalee' # By considering the terms in the Fibonacci sequence whose values do not exceed four million, # find the sum of the even-valued terms. def problem2(): print("Find the sum of the even-valued Fibonacci terms up to n.") while True: n = raw_input("What is n? ") try: n = int(n) if n > 0: fib_nums = [0, 1] n = 1 while fib_nums[n] < n: fib_nums += [fib_nums[n] + fib_nums[n-1]] n += 1 print("Answer = %i" % sum([i for i in fib_nums[:-1] if i % 2 == 0])) break else: print "*** n must be positive. ***" except ValueError: print "*** %s is not a valid integer. ***" % n problem2()
dc6e8e9bcc139399ad84a6c319261b1158c397c5
ICC3103-202110/proyecto-01-gavrilov_zumaeta
/counterattack.py
3,679
3.828125
4
from random import shuffle from console import Console class Counterattack: def __init__(self,adversary,character): self.__adversary=adversary self.__character=character @property def adversary(self): return self.__adversary @adversary.setter def adversary(self,name): self.__adversary=name @property def character(self): return self.__character @character.setter def character(self,name): self.__character=name @property def succes(self): return self.__succes def master_of_counterattack(self,player,adversary,action): print("{} you have been COUNTERATTACKED by {}".format(player,adversary)) if action=="Murder": self.countess(player) if (action=="Extortion" or action=="Foreign Help"): self.block_stealing_help(player) def defy_counterattack(self,list_of_players,player,action,table_deck): print("\nDoes anybody want to DEFY this COUNTERATTACK?") challengers=[] for other_player in list_of_players: if other_player.status!="Challenging": add=input("{} PRESS 1 if you want to CHALLENGE, press any other key otherwise ".format(other_player)) if add=="1": challengers.append(other_player) if len(challengers)==0: action.action_succes=False print("Nobody challenged you") self.master_of_counterattack(player,self.__adversary,action.action_status) return 0 shuffle(challengers) challenger=challengers[0] action.activity_log.append("{} challenged {}'s counterattack".format(challenger,self.__adversary)) print("{} you have been CHALLENGED by {}".format(self.__adversary,challenger)) win=False for card in self.adversary.cards: if (card.out_of_game==False and card.influence==self.__character): win=True print("{} you have WON the CHALLENGE and get to complete the counterattack".format(self.__adversary)) action.activity_log.append("{} won challenge and got to complete counterattack".format(self.__adversary)) table_deck.deck.append(card) self.__adversary.cards.remove(card) table_deck.assign_cards_player(self.__adversary,1,table_deck.deck) input("{} press ANY KEY to see your new card".format(self.__adversary)) self.__adversary.see_cards() input("PASS computer to {} AND PRESS ANY KEY to continue".format(challenger)) Console.clear() challenger.resign_card() Console.clear() action.action_succes=False self.master_of_counterattack(player,self.__adversary,action.action_status) if win==False: print("{} you have LOST the CHALLENGE".format(self.__adversary)) action.activity_log.append("{} won the challenge and got to stop the counterattack".format(challenger)) input("PASS computer to {} AND PRESS ANY KEY to continue".format(self.__adversary)) Console.clear() self.__adversary.resign_card() Console.clear() self.__adversary.status=None @succes.setter def succes(self,value): self.__succes=value def countess(self,player): print("Therefore {} you have LOST 3 COINS".format(player)) player.coins=-3 def block_stealing_help(self,player): print("Therefore {} you WON'T GET ANY COINS".format(player))
2a6ce9ab7369cd067c0d12cc9ace71d5110aff8e
nicokuzak/leetcode
/medium/dp/maximal_square.py
1,369
3.765625
4
""" Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. Example 1: Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] Output: 4 Example 2: Input: matrix = [["0","1"],["1","0"]] Output: 1 Example 3: Input: matrix = [["0"]] Output: 0 Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 300 matrix[i][j] is '0' or '1'.""" from typing import List class Solution: import math def maximalSquare(self, matrix: List[List[str]]) -> int: dp = [[0]*len(matrix[0]) for _ in range(len(matrix))] m = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if i == 0 or j == 0: dp[i][j] = int(matrix[i][j]) m = max(m, int(matrix[i][j])) elif matrix[i][j] == '0': dp[i][j] = 0 else: up, left, diag = dp[i-1][j], dp[i][j-1], dp[i-1][j-1] if up > 0 and left > 0 and diag > 0: n = int(math.sqrt(min(up, left, diag))+1)**2 dp[i][j] = n m = max(m, n) else: dp[i][j] = 1 m = max(m, 1) return m
89d57ee71cd031ca7b87229fcf432a97e19e45ca
najohns3/Assignment_05
/CDInventory.py
2,490
3.703125
4
#------------------------------------------# # Title: CDInventory.py # Desc: Starter Script for Assignment 05 # Change Log: (Who, When, What) # DBiesinger, 2030-Jan-01, Created File # NJohnson, 2021-Aug-08, updated #------------------------------------------# # Declare variabls strChoice = '' # User input dic = {} # TODO replace list of lists with list of dicts strFileName = 'CDInventory.txt' # data storage file objFile = None # file object # Get user Input print('The Magic CD Inventory\n') while True: # 1. Display menu allowing the user to choose: print('[1] Load Inventory from File\n[2] Add CD\n[3] Display Current Inventory') print('[4] Delete CD from Inventory\n[5] Save Inventory to file\n[x] Exit') strChoice = input('1, 2, 3, 4, 5 or x: ').lower() # convert choice to lower case at time of input print() if strChoice == 'x': # 5. Exit the program if the user chooses so break if strChoice == '1': with open('CDInventory.txt','r') as f: data = f.read() print (data) # TODO Add the functionality of loading existing data pass elif strChoice == '2': # no elif necessary, as this code is only reached if strChoice is not 'exit' # 2. Add data to the table (2d-list) each time the user wants to add data strID = input('Enter an ID: ') strTitle = input('Enter the CD\'s Title: ') strArtist = input('Enter the Artist\'s Name: ') intID = int(strID) #populate dictionary dic[intID] = {'title':strTitle, 'artist':strArtist} elif strChoice == '3': # 3. Display the current data to the user each time the user wants to display the data for intID in dic: print(intID, dic[intID]['title'], dic[intID]['artist']) elif strChoice == '4': rownumber = input('Enter number row you would like to delete: ') intID2 = int(rownumber) del dic[intID2] #TODO Add functionality of deleting an entry pass elif strChoice == '5': # 4. Save the data to a text file CDInventory.txt if the user chooses so f= open('CDInventory.txt','w') f.write(str(dic)) f.close() else: print('Please choose either 1, 2, 3, 4, 5 or x!')
ddb648c235b31e1d769d27005bdca16d0d9b4791
osama1998H/standerdLearnd-string
/q47.py
170
3.9375
4
string = input("enter the text: ") string_list = [i for i in string] string_list[0] = string_list[0].lower() text = "" for i in string_list: text += i print(text)
03ad1559fc72138a0c5768f7efc9b6d1704affbe
zyavuz610/learnPython_inKTU
/python-100/127_example-projects.py
990
3.796875
4
""" Seri: Örneklerle Python Programlama ve Algoritma Önceki dersler: değişkenler ve operatörler koşul ifadeleri: if,else veri yapıları: string, liste döngüler: for, while, iç içe döngüler fonksiyonlar, fonksiyon parametreleri, örnekler modüller, kendi modülümüzü yazmak datetime, math, örnekler tuple veri yapısı, tuple üzerinde işlemler Python - 127 : Örnek Projeler (önceki konuları kullanarak yapılabilen) ------------------------------------------------- Problem 1: tp = (3,-1,4,3,6,-2,-5,-1) max,min product, ardışıl 2 elemanın çarpımları arasında max ve min bul ------------------------------------------------- Problem 2: bir sayı alalım: 1 * 2 * *** 3 * *** ***** 4 * *** ***** ******* şekli ekrana yaz, alanı bul ------------------------------------------------- Problem 3 tp = (5,2,4,8,9) min-max = 2,9 eksik sayılar: 3,6,7 ekrana yaz 2:** 3:- 4:**** 5:***** 6:- 7:- 8:******** 9:********* """