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
1dae77273c6bce5a786e08ff7f79a8f8dea57771
JiangFengJason/LeetCodePractice
/SolutionsPY/JumpGame.py
531
3.546875
4
class Jump: def canJump(self, nums) -> bool: if not nums: return False c = len(nums) pos = [0] * c pos[0] = 1 temp = nums[0] pos[1:1+nums[0]] = [1]*nums[0] for i in range(1, c-1): if pos[i] != 0 and i+1+nums[i]>temp: pos[i+1:i+1+nums[i]] = [1]*nums[i] temp = i+1+nums[i] if temp >= c: break if pos[c-1] == 1: return True else: return False
68b1c7bfd28d3074932dc2eda69c0e77cb00efe5
Aadhya-Solution/PythonExample
/for_examples/for_add_numbers.py
405
3.515625
4
import pdb import logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='add_num/add_num.log', filemode='w') n=input("Enter N:") if n==0: logging.warning("Given Number is 0") logging.info("N:{}".format(n)) c=0 for i in range(n): c=c+i logging.info("i:{}--c:{}".format(i, c)) logging.info("C:{}".format(c)) print("Sum:",c)
ea43ef8caf69949ece0b5c34d602b84284cbda4e
Kaushaldevy/sort
/Bubble.py
453
3.921875
4
import time import random start = time.time() def bubbleSort(arr): for j in range(len(arr)-1): for i in range(len(arr)-1): if arr[i] > arr[i+1]: temp = arr[i] arr[i] = arr[i+1] arr[i+1] = temp arr = random.sample(range(100,100000),500) #arr = [] #arr = [1] #arr = [1,2] #arr = [4,4,4,4,4,4,4] #arr = [1,2,3,4,5,6,7,8,9] #arr = [9,8,7,6,5,4,3,2,1] #arr = [1,3,3,3,3,3,3] bubbleSort(arr) end = time.time() print(arr) print(end-start)
3b9748738cc95b44f3027be51fcd904811f49ab8
kambiz-kalhor/python--euler-project
/problem 45/problem 45 - 30 seconds.py
369
3.671875
4
import time startTime = time.time() listh=[] n=0 for i in range (1,100000): p = ((i*((3*i)-1))/2) h = (i*((2*i)-1)) listh.append(h) if p in listh: print (p) n=n+1 if n ==3: break print ("finish") executionTime = (time.time() - startTime) print('Execution time in seconds: ' + str(executionTime))
195a58e9df2ca54cbb82c57c50875af8ed393231
MarioMartReq/coding-interview
/arrays/rotate-matrix.py
788
4.5625
5
'''You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. ''' # Explanation: to rotate a matrix, you can reverse it and then transpose it # This procedure does exactly that. # matrix[::-1] reverses the matrix # then, the * separates the column list into a different argument # then, the zip takes the first (then the second, third...) element from each list and makes it list class Solution: def rotate(matrix): matrix[::] = list(zip(*matrix[::-1])) if __name__ == '__main__': matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Solution.rotate(matrix) print(matrix)
3fc16fab61213e98c81bc9637c96697f2fc0bf10
daniel-reich/ubiquitous-fiesta
/q5jCspdCvmSjKE9HZ_16.py
168
3.703125
4
def lcm_of_list(numbers): n = 1 for i in numbers: n = (n*i)//gcd(n,i) return n ​ def gcd(a,b): if(b==0): return a else: return gcd(b,a%b)
1585fcf0b62b9e9acb267aaaafac1433765a15e8
khelwood/advent-of-code
/2018/03_slice.py
952
3.671875
4
#!/usr/bin/env python3 import sys import re import itertools from collections import Counter, namedtuple Claim = namedtuple('Claim', 'id left top width height') Claim.__iter__ = lambda self : itertools.product( range(self.left, self.left + self.width), range(self.top, self.top + self.height) ) def make_claim(line, ptn=re.compile('#%@%,%:%x%$'.replace('%', r'(\d+)'))): m = ptn.match(re.sub(r'\s+','',line)) if not m: raise ValueError(repr(line)) return Claim(*map(int, m.groups())) def main(): claims = [make_claim(line) for line in sys.stdin.read().splitlines()] land = Counter() for claim in claims: land.update(claim) overlapcount = sum(v > 1 for v in land.values()) print("Overlap count:", overlapcount) for claim in claims: if all(land[p] <= 1 for p in claim): print("Correct claim ID:", claim.id) if __name__ == '__main__': main()
a3c1aec2682bbcb62a4590c044b863bb56ce1a5b
limapedro2002/PEOO_Python
/Lista_04/Guilherme Ferreira/q1Clista4.py
118
3.5625
4
def conc(*strings): x = "" for str in strings: x += "" + str return x print(conc('o','lho'))
8242e7dab080fbae6c6b68abd901376661146bd0
lil-mars/pythonProblems
/algorithms/Linear search/lsearch.py
679
3.859375
4
def binary_search(item_list, item): first = 0 last = len(item_list) - 1 found = False mid = 0 while first <= last and not found: mid = (first + last) // 2 if item_list[mid] == item: found = True else: if item < item_list[mid]: last = mid - 1 else: first = mid + 1 print('YES') test_cases = int(input()) for case in range(test_cases): quantity = int(input()) numbers = [int(num) for num in input().split()] searched_num = int(input()) if numbers.count(searched_num) > 0: binary_search(numbers, searched_num) else: print('NO')
50caaaef3b60643ae0dc74b3fd3d8cc1e8784e40
aziza-calm/python_course_1_faki
/turtle_1/post_code.py
4,335
3.9375
4
import turtle import math # Constants STEP_SIZE = 30 DIAGONAL_STEP_SIZE = math.sqrt(2) * STEP_SIZE def draw_symbol(symbol, coords): """ :param symbol: symbol to draw :param coords: left upper corner coords """ turtle.penup() if symbol == '0': turtle.goto(coords[0], coords[1]) turtle.pendown() turtle.forward(STEP_SIZE) turtle.right(90) turtle.forward(STEP_SIZE * 2) turtle.right(90) turtle.forward(STEP_SIZE) turtle.right(90) turtle.forward(STEP_SIZE * 2) turtle.right(90) elif symbol == '1': turtle.goto(coords[0], coords[1] - STEP_SIZE) turtle.pendown() turtle.left(45) turtle.forward(DIAGONAL_STEP_SIZE) turtle.right(135) turtle.forward(STEP_SIZE * 2) turtle.left(90) elif symbol == '2': turtle.goto(coords[0], coords[1]) turtle.pendown() turtle.forward(STEP_SIZE) turtle.right(90) turtle.forward(STEP_SIZE) turtle.right(45) turtle.forward(DIAGONAL_STEP_SIZE) turtle.left(135) turtle.forward(STEP_SIZE) elif symbol == '3': turtle.goto(coords[0], coords[1]) turtle.pendown() turtle.forward(STEP_SIZE) turtle.right(135) turtle.forward(DIAGONAL_STEP_SIZE) turtle.left(135) turtle.forward(STEP_SIZE) turtle.right(135) turtle.forward(DIAGONAL_STEP_SIZE) turtle.left(135) elif symbol == '4': turtle.goto(coords[0], coords[1]) turtle.pendown() turtle.right(90) turtle.forward(STEP_SIZE) turtle.left(90) turtle.forward(STEP_SIZE) turtle.left(90) turtle.forward(STEP_SIZE) turtle.left(180) turtle.forward(2 * STEP_SIZE) turtle.left(90) elif symbol == '5': turtle.goto(coords[0] + STEP_SIZE, coords[1]) turtle.pendown() turtle.right(180) turtle.forward(STEP_SIZE) turtle.left(90) turtle.forward(STEP_SIZE) turtle.left(90) turtle.forward(STEP_SIZE) turtle.right(90) turtle.forward(STEP_SIZE) turtle.right(90) turtle.forward(STEP_SIZE) turtle.right(180) elif symbol == '6': turtle.goto(coords[0] + STEP_SIZE, coords[1]) turtle.pendown() turtle.right(135) turtle.forward(DIAGONAL_STEP_SIZE) turtle.left(45) turtle.forward(STEP_SIZE) turtle.left(90) turtle.forward(STEP_SIZE) turtle.left(90) turtle.forward(STEP_SIZE) turtle.left(90) turtle.forward(STEP_SIZE) turtle.left(180) elif symbol == '7': turtle.goto(coords[0], coords[1]) turtle.pendown() turtle.forward(STEP_SIZE) turtle.right(135) turtle.forward(DIAGONAL_STEP_SIZE) turtle.left(45) turtle.forward(STEP_SIZE) turtle.left(90) elif symbol == '8': turtle.goto(coords[0], coords[1]) turtle.pendown() turtle.forward(STEP_SIZE) turtle.right(90) turtle.forward(STEP_SIZE * 2) turtle.right(90) turtle.forward(STEP_SIZE) turtle.right(90) turtle.forward(STEP_SIZE * 2) turtle.right(180) turtle.forward(STEP_SIZE) turtle.left(90) turtle.forward(STEP_SIZE) elif symbol == '9': turtle.goto(coords[0] + STEP_SIZE, coords[1] - STEP_SIZE) turtle.pendown() turtle.right(180) turtle.forward(STEP_SIZE) turtle.right(90) turtle.forward(STEP_SIZE) turtle.right(90) turtle.forward(STEP_SIZE) turtle.right(90) turtle.forward(STEP_SIZE) turtle.right(45) turtle.forward(DIAGONAL_STEP_SIZE) turtle.left(135) else: print(f'Unknown symbol "{symbol}"') if __name__ == "__main__": screensize = turtle.screensize() current_x = int(-screensize[0] / 2) + 10 current_y = int(screensize[1] / 2) - 10 turtle.shape('turtle') turtle.color('blue') turtle.width(5) input_seq = input('Please input sequence to draw: ') for symbol in input_seq: draw_symbol(symbol, [current_x, current_y]) current_x += 2 * STEP_SIZE input('Press any key...')
7dc74a301f7e7875aac134d3d6eee700c7b01a82
avhirupc/LeetCode
/problems/Pattern : Untagged/Implement Stack using Queues.py
980
4.125
4
from collections import deque class MyStack: def __init__(self): """ Initialize your data structure here. """ self.q=deque([]) def push(self, x: int) -> None: """ Push element x onto stack. """ self.q.append(x) def pop(self) -> int: """ Removes the element on top of the stack and returns that element. """ lq=len(self.q) for i in range(lq-1): v=self.q.popleft() self.q.append(v) return self.q.popleft() def top(self) -> int: """ Get the top element. """ return self.q[-1] def empty(self) -> bool: """ Returns whether the stack is empty. """ return len(self.q)==0 # Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty()
40e05bad49e93a3794914977f3e522d301757d22
nhat117/Pythonproject
/car.py
405
3.6875
4
class Vehicle: name = "" kind = "car" color = "" value = 100.000 def description(self): return "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value) car1 = Vehicle() car1.name = "Merc" car1.color = "Red" car1.value = 100000 car2 = Vehicle() car2.name = "BMW" car2.color = "Beige" car2.value = 200000 print(car1.description()) print(car2.description())
01670b536bd487a44d02d9a1f89f18d208b4f884
TaichiSky/python_like
/src/day09_funcAdvance1.py
2,029
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- 'advanced features of the function' __author__ = 'dogsky' import os ###generate list formula list_a = range(11) print('list = ',list(list_a)) #compute the square of each number(List or tuple) print() list_aa = [x * x for x in list_a] print('x*x of list = ',list_aa) #list odd of 1-10 print() list_odd = [x for x in list_a if x % 2 == 1] print('odd of 1-10 = ',list_odd) #convert list_a to str of list print() list_as = map(str, list_a) print('convert list_a to str of list = ',[x for x in list_as]) #combination of str print() comStr1 = 'abc' comStr2 = '123' list_combin = [x + y for x in comStr1 for y in comStr2] print('combination of comStr1 to comStr2 = ',list_combin) #list of map print() map_info = {'name':'luckydog','height':'178cm','hobby':'swimming'} list_info = [k + '=' + v for k, v in map_info.items()] print('list of map_info = ',list_info) #list the files and directories under the current location print() list_dirFile = [dirFile for dirFile in os.listdir('.')] print('list the files and directories = ',list_dirFile) ##map | map(op, value) print() def func1 (n) : return n * 2 -1 test_list = range(1,11) print('after map(func1, test_list) = ',list(map(func1, test_list))) ##filter print() def is_odd(n) : return n % 2 == 1 print('filter(is_odd, list_a) = ',list(filter(is_odd, list_a)) ,'\n map(is_odd, list_a) = ',list(map(is_odd, list_a))) ##sorted/sort print() list_sort1 = [66,12, 6, -12, 9, -21] list_sort1.sort() list_sort2 = [66,12, 6, -12, 9, -21] print('after list_sort1.sort() = ',list_sort1 ,'\n after sorted(list_sort2) = ',sorted(list_sort2) ,'\n after sorted(list_sort2, key = abs) = ',sorted(list_sort2, key = abs)) print() list_sortA = ['bob', 'about', 'Zoo', 'Credit'] print('after sorted(list_sortA) = ',sorted(list_sortA) ,'\n after sorted(list_sortA, key = str.lower) = ',sorted(list_sortA, key = str.lower) ,'\n after sorted(list_sortA, key = str.lower, reverse = True) = ',sorted(list_sortA, key = str.lower, reverse = True))
6884890d17ad71278f330b43c8d3afe17bceb032
veronicarose27/playerset2
/index03.py
148
3.5
4
m=input() l=list(m) p=len(m) k=[] o=(p)//3 if(p<=3): k.append(l[0]) else: for i in range(0,o+1): k.append(l[i*3]) print("".join(k))
b96dd7321e1e718535019efb21456944af269878
LauroJr/Python_projeto01
/Exercícios_Lógica_python/AC_7_lógica_2º_exercício.py
318
3.875
4
si = 0 m = 0 i = 1 while i != 0: i = int(input("Digite sua idade: ")) si = si+i if i > 0: m = m+1 if si > 0: mi = si/m print("A média das idades somadas é: ",mi,". A soma é: ",si," anos") else: print("Não é possível resumir a conta pois não há entradas coerentes")
0075ed1eb20964cca065d6d37370e3b10496ebbf
Jeremy277/exercise
/资料data/pyth自学预习7.11-7.30/demo13随机生成验证码程序for语句改进.py
362
3.9375
4
#1.实现随机生成n位验证码(字母 数字 下划线) import random import string all_chars = string.ascii_letters + string.digits + '_' i = 1 n = int(input('请输入验证码位数:')) #定义一个空字符串变量 pwd = '' #控制循环次数 for i in range(n): char = random.choice(all_chars) pwd = pwd + char print(pwd)
c22c90e86a477d8f608cf113795c669c30d06030
NathanLaing/word-chain
/word_chain.py
7,361
4.03125
4
""" word_chain.py @autor Nathan Laing and Sam Fleury """ import sys from collections import deque word_to_index = {} index_to_word = {} class Node: """ A class for the nodes of the graph. """ def __init__(self, word, parent, cost): """ Initialises the Node class objects :param word: The word this node is going to store :param parent: The Node that you traversed to this node from in the graph :param cost: The total cost to get here from the starting word """ self.word = word self.parent = parent self.cost = cost def __str__(self): return "Word: " + self.word def dif(word_a, word_b): """ Our own method for edit distance for strings of the same length. :param word_a: The first word to be compared :param word_b: The second word to be compared :return: The edit distance between the words (how many single char edits you have to make to get from word_a => word_b) """ i = 0 difs = 0 while i < len(word_a): if word_a[i] != word_b[i]: difs += 1 i += 1 return difs def make_graph(words): """ Generates the adjacency matrix used to store which words are 1 edit distance away from others :param words: A list of words to be added into the graph :return: A 2D list set up as an adjacency matrix where 1 represents an edge and 0 represents the lack of an edge """ graph = [[0] * len(words) for i in range(len(words))] i = 0 while i < len(words): j = 0 while j < len(words): if dif(words.get(i), words.get(j)) == 1: graph[i][j] = 1 j += 1 i += 1 return graph def find_min(starting_word, target_word, graph): """ Finds the minimum word chain between two words. Uses an algorithm based off of Dijkstra's algorithm :param starting_word: The starting word of the word chain :param target_word: The word you want to end up at :param graph: The adjacency matrix used to represent the relationships between the words :return: The minimum word chain or a not possible message """ global index_to_word global word_to_index queue = deque() visited = [] root = Node(word=starting_word, parent=None, cost=1) queue.append(root) current = root while current.word != target_word: if queue: current = queue.popleft() visited.append(current.word) edges = [j for j, x in enumerate(graph[(word_to_index.get(current.word))]) if x == 1] for i in range(len(edges)): if index_to_word.get(edges[i]) not in visited: new_node = Node(index_to_word.get(edges[i]), current, current.cost + 1) queue.append(new_node) else: return starting_word + " " + target_word + " not possible" answer = [] while True: answer.insert(0, current.word) if current.parent is None: break else: current = current.parent return ' '.join(answer) def find_chain_of_len(starting_word, target_word, chain_length, graph): """ Finds a word chain between two words that is of the given length. Based off of a depth first limited search :param starting_word: The word that the word chain should begin with :param target_word: The word that the chain should end with :param chain_length: The length of the chain (also controls the depth of the search) :param graph: The adjacency matrix used to represent the relationships between the words :return: A word chain of the given length or a not possible message """ global index_to_word global word_to_index root = Node(word=starting_word, parent=None, cost=1) queue = deque() visited = [[]] queue.append(root) while queue: current = queue.popleft() visited.append(get_chain(current)) if current.word == target_word and current.cost == chain_length: answer = [] while True: answer.insert(0, current.word) if current.parent is None: break else: current = current.parent return ' '.join(answer) elif current.cost < chain_length: edges = [j for j, x in enumerate(graph[(word_to_index.get(current.word))]) if x == 1] for i in range(len(edges)): check_path = get_chain(current) check_path.append(index_to_word.get(edges[i])) if check_path not in visited and index_to_word.get(edges[i]) not in get_chain(current): if index_to_word.get(edges[i]) != target_word: new_node = Node(index_to_word.get(edges[i]), current, current.cost + 1) queue.appendleft(new_node) elif current.cost + 1 == chain_length: new_node = Node(index_to_word.get(edges[i]), current, current.cost + 1) queue.appendleft(new_node) return starting_word + " " + target_word + " " + str(chain_length) + " not possible" def get_chain(node): """ Gets the chain of steps to how you got to this node. :param node: The end node of the chain :return: answer (the chain from root to current node) """ answer = [] while True: answer.append(node.word) if node.parent is None: break else: node = node.parent return answer def main(): """ The main method. This reads in the parameters from the command line and the words from the text file to be used. It Then sets up the needed variables and calls the appropriate graph search method (based on chain length). :return: """ global word_to_index global index_to_word if len(sys.argv) < 3: print("Please enter a word to chain from and a word to chain to.") elif len(sys.argv) > 4: print("Please enter only a starting word, target word and chain length.") else: starting_word = sys.argv[1] target_word = sys.argv[2] if len(sys.argv) == 4: chain_length = int(sys.argv[3]) if dif(starting_word, target_word) > (chain_length + 1): print(starting_word + " " + target_word + " " + str(chain_length) + " not possible") return else: chain_length = -1 i = 0 line = sys.stdin.readline() while line: line = line.rstrip('\n') line = line.lower() word_to_index.update({line: i}) index_to_word.update({i: line}) i += 1 line = sys.stdin.readline() if starting_word not in word_to_index.keys() or target_word not in word_to_index.keys(): print(starting_word + " " + target_word + " " + str(chain_length) + " not possible") return else: graph = make_graph(index_to_word) if chain_length == -1: print(find_min(starting_word, target_word, graph)) else: print(find_chain_of_len(starting_word, target_word, chain_length, graph)) if __name__ == "__main__": main()
56c433173caccab62794d09ae8102d62c53c68b4
koiic/python_mastery
/myrange.py
470
3.609375
4
#Implementing my version of the ramge function def myrange(first, second=None, step=1): if second is None: current = 0 maxnum = first else: current = first maxnun = second if step > 0: while current < maxnum: yield current current += step else: while current > maxnum: yield current current += step print(list(myrange(5)))
d6e0884b603aeb9d3e521c5c9c16b86a3e8373d8
akimi-yano/algorithm-practice
/lc/1722.MinimizeHammingDistanceAfter.py
5,871
4.125
4
# 1722. Minimize Hamming Distance After Swap Operations # Medium # 66 # 2 # Add to List # Share # You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order. # The Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed). # Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source. # Example 1: # Input: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]] # Output: 1 # Explanation: source can be transformed the following way: # - Swap indices 0 and 1: source = [2,1,3,4] # - Swap indices 2 and 3: source = [2,1,4,3] # The Hamming distance of source and target is 1 as they differ in 1 position: index 3. # Example 2: # Input: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = [] # Output: 2 # Explanation: There are no allowed swaps. # The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. # Example 3: # Input: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]] # Output: 0 # Constraints: # n == source.length == target.length # 1 <= n <= 105 # 1 <= source[i], target[i] <= 105 # 0 <= allowedSwaps.length <= 105 # allowedSwaps[i].length == 2 # 0 <= ai, bi <= n - 1 # ai != bi # This solution works ! - union find ! class Solution: def union(self, x, y): x = self.find(x) y = self.find(y) if x != y: if x < y: self.roots[y] = x else: self.roots[x] = y def find(self, x): if x == self.roots[x]: return x self.roots[x] = self.find(self.roots[x]) return self.roots[x] def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int: target_idx = {} for i, val in enumerate(target): if val not in target_idx: target_idx[val] = set([]) target_idx[val].add(i) # print(target_idx) self.roots = [i for i in range(len(source))] for from_node, to_node in allowedSwaps: self.union(from_node, to_node) # print(self.roots) for i in range(len(self.roots)): self.find(i) # print(self.roots) i = 0 while i < len(source): if source[i] != target[i]: if source[i] in target_idx: found_idx = None for idx in target_idx[source[i]]: # print(f"checking idx {i} and {idx}") if self.roots[i] == self.roots[idx]: # print(f"swapping {source[i]} and {source[idx]}") source[i], source[idx] = source[idx], source[i] found_idx = idx break if found_idx is not None: target_idx[source[idx]].remove(found_idx) i -= 1 i += 1 ans = 0 # print(source) # print(target) for i in range(len(source)): if source[i] != target[i]: ans += 1 return ans # This approach does not work # bug because # - we must use set([]) as the value of the target index dictionary for duplicate cases # - after swapping we need to do i -= 1 to go back to make sure the index we just swapped is a value move # code above is a solution that works! # class Solution: # def union(self, x, y): # x = self.find(x) # y = self.find(y) # if x != y: # if x < y: # self.roots[y] = x # else: # self.roots[x] = y # def find(self, x): # if x == self.roots[x]: # return x # self.roots[x] = self.find(self.roots[x]) # return self.roots[x] # def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int: # target_idx = {val: i for i, val in enumerate(target)} # self.roots = [i for i in range(len(source))] # for from_node, to_node in allowedSwaps: # self.union(from_node, to_node) # # print(self.roots) # for i in range(len(self.roots)): # self.find(i) # # print(self.roots) # for i in range(len(source)): # if source[i] != target[i]: # if source[i] in target_idx: # idx = target_idx[source[i]] # # print(f"checking idx {i} and {idx}") # if self.roots[i] == self.roots[idx]: # # print(f"swapping {source[i]} and {source[idx]}") # source[i], source[idx] = source[idx], source[i] # for i in range(len(source)): # if source[i] != target[i]: # if source[i] in target_idx: # idx = target_idx[source[i]] # # print(f"checking idx {i} and {idx}") # if self.roots[i] == self.roots[idx]: # # print(f"swapping {source[i]} and {source[idx]}") # source[i], source[idx] = source[idx], source[i] # ans = 0 # for i in range(len(source)): # if source[i] != target[i]: # ans += 1 # return ans
cffb81271ba9f100472901d7c10b19880cd8191c
nitishkrishna/my_stuff
/python/algos/well_known_algos/BreadthFirstSearch.py
1,034
4.0625
4
""" graph represented as an adjacency list """ from Queue import Queue g = {'A': set(['B', 'C']), 'B': set(['A', 'D', 'E']), 'C': set(['A', 'F']), 'D': set(['B']), 'E': set(['B', 'F']), 'F': set(['C', 'E'])} class BFS(): def __init__(self): pass def breadth_first_search(self, graph, start_node): visited_nodes = set() to_visit_queue = Queue() to_visit_queue.put(start_node) while to_visit_queue.qsize() > 0: cur_vertex = to_visit_queue.get() if cur_vertex not in visited_nodes: neighbors = graph.get(cur_vertex, None) if neighbors: for neighbor in neighbors: if neighbor not in visited_nodes: to_visit_queue.put(neighbor) visited_nodes.add(cur_vertex) return visited_nodes if __name__ == '__main__': bfs = BFS() v_nodes = bfs.breadth_first_search(g, 'A') print v_nodes
8e0840b08dea4e4ec6519a70fa771ac9be1e4e69
licht5/TEST
/qunar/database.py
793
3.578125
4
#!/usr/bin/python3 import pymysql # 打开数据库连接 db = pymysql.connect("localhost", "root", "0801", "RUNOOB") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 cursor.execute("SELECT sname FROM STUDENT WHERE ssex='FE'") cursor.execute("CREATE TABLE COURSE (CNO CHAR (4) PRIMARY KEY ,CNAME CHAR(40) NOT NULL ,CPNO CHAR (4),CEDIT SMALLINT ,FOREIGN KEY (CPNO) REFERENCES COURSE(CPNO) )") cursor.execute("CREATE TABLE SC (SNO CHAR(9),CNO CHAR (4) ,GRADE SMALLINT ,PRIMARY KEY(SNO,CNO),FOREIGN KEY (CPNO) REFERENCES COURSE(CPNO),FOREIGN KEY (SNO) REFERENCES STUDENT(sno))") # 使用 fetchone() 方法获取单条数据. data = cursor.fetchone() print("seslect : %s " % data) # 关闭数据库连接 db.close()
4732805df8782ff3763a23e07e692ae328f28afb
ewelkaw/tic_tac_toe
/minimax_alg.py
1,676
3.59375
4
from math import inf as infinity from collections import namedtuple from const import Player from game import Game def evaluate(game: Game) -> bool: if game.finished and game.winner == "o": return 1 elif game.finished and game.winner == "x": return -1 else: return 0 def choose_best_move(game: Game, depth: int, player: Player) -> list: if player.player_name == "computer": best = [-1, -1, -infinity] else: best = [-1, -1, +infinity] if depth == 0 or not game.available_fields: score = evaluate(game) return [-1, -1, score] for field in game.available_fields: new_game = game.copy() new_game.update_single_field(player.mark, field) if player.mark == "x" and player.player_name == "computer": score = choose_best_move(new_game, depth - 1, Player(mark='o', player_name="user")) elif player.mark == "x" and player.player_name == "user": score = choose_best_move(new_game, depth - 1, Player(mark='o', player_name="computer")) elif player.mark == "o" and player.player_name == "computer": score = choose_best_move(new_game, depth - 1, Player(mark='x', player_name="user")) elif player.mark == "o" and player.player_name == "user": score = choose_best_move(new_game, depth - 1, Player(mark='x', player_name="computer")) score[0], score[1] = field if player.player_name == "computer": if score[2] > best[2]: best = score # max value else: if score[2] < best[2]: best = score # min value return best
33c2113d91c16223af2bea7896bb3a86c73756ba
ivan-yosifov88/python_basics
/More While Loop Excercise/01. Dishwasher.py
867
3.9375
4
detergent = int(input()) total_detergent = detergent * 750 command = input() dishwasher_counter = 0 detergent_over = False sum_plates = 0 sum_pots = 0 while not command == "End": number_of_dishes = int(command) dishwasher_counter += 1 if dishwasher_counter < 3: sum_plates += number_of_dishes total_detergent -= number_of_dishes * 5 elif dishwasher_counter == 3: total_detergent -= number_of_dishes * 15 sum_pots += number_of_dishes dishwasher_counter = 0 if total_detergent < 0: detergent_over = True break command = input() if detergent_over: print(f"Not enough detergent, {abs(total_detergent)} ml. more necessary!") else: print("Detergent was enough!") print(f"{sum_plates} dishes and {sum_pots} pots were washed.") print(f"Leftover detergent {total_detergent} ml.")
2af0d783f9c5cb2a1ea8b99414021b33cd0007f9
RaniaMahmoud/SW_D_Python
/Sheet4/S4/P18.py
132
3.515625
4
from functools import reduce as r def simulateReduce(L1): return r(lambda x,y:x+y,L1) l1=[5,8,6,1,3,4] print(simulateReduce(l1))
65b349711cc37ff28e8e5123d09745218062f160
suitendaal/RailNL
/PythonFunctions/DijkstraAlgorithm.py
1,417
4.21875
4
def algorithmDijkstraFunction(graph, start, end): """algorithm get the best route between two stations""" bestPath = None score = 0 for path in graph.allRoutes: # If the path has the given begin- and endstation, calculate the score. if (path[0][0] == start and path[0][-1] == end) or (path[0][-1] == start and path[0][0] == end): # Calculate amount of critical connections. criticalPathCounter = 0 for i in range(len(path[0]) - 1): if [path[0][i], path[0][i+1]] in graph.criticalConnections: criticalPathCounter += 1 # Calculate the critical percentage. newScore = 100 * criticalPathCounter / len(path[0]) if newScore > score: score = newScore bestPath = path return bestPath def algorithmDijkstra(graph): """Also known as Sven's algorithm, returns the best paths for between every station""" bestPaths = [] for i in range(len(graph.allStations)): for j in range(i + 1, len(graph.stationNames)): # Calculate the best path between every begin- and endstation. newPath = algorithmDijkstraFunction(graph, graph.stationNames[i], graph.stationNames[j]) # Append the route to the list. if newPath != None: bestPaths.append(newPath) return bestPaths
5425a4a118866201859c2d0983014796e69859b6
emmas0507/lintcode
/lowest_common_ancestor.py
1,602
3.953125
4
class Node(object): def __init__(self, value, parent=None, left=None, right=None): self.value = value self.parent = parent self.left = left self.right = right def print_node_list(node_list): for n in node_list: print(n.value) def get_path(root, target): curr_list = [root] while len(curr_list) > 0: print('curr_list is ') print_node_list(curr_list) curr_node = curr_list[-1] if curr_node.value == target: break else: curr_list = curr_list[:(-1)] if curr_node.left is not None: curr_list = curr_list + [curr_node.left] if curr_node.right is not None: curr_list = curr_list + [curr_node.right] print('target node is {}'.format(curr_node.value)) path = [] while curr_node is not None: path = [curr_node.value] + path curr_node = curr_node.parent return path def lowest_common_ancestor(root, target1, target2): path1 = get_path(root, target1) path2 = get_path(root, target2) print('path1 and path2 are {}, {}'.format(path1, path2)) common_path = [] for i in range(min(len(path1), len(path2))): if path1[i] == path2[i]: common_path = common_path + [path1[i]] return common_path node5 = Node(5) node6 = Node(6) node3 = Node(3) node7 = Node(7, None, node5, node6) node4 = Node(4, None, node3, node7) node4.parent = None node3.parent = node4 node7.parent = node4 node5.parent = node7 node6.parent = node7 print(lowest_common_ancestor(node4, 6, 7))
243ae5a9d9538322a362c7cf5f53c515b005e13b
lukeolson/cs450-f20-demos
/demos/upload/toshow2/Relative cost of matrix factorizations.py
992
3.515625
4
#!/usr/bin/env python # coding: utf-8 # # Relative cost of matrix factorizations # In[1]: import numpy as np import numpy.linalg as npla import scipy.linalg as spla import matplotlib.pyplot as pt from time import time # In[2]: n_values = (10**np.linspace(1, 3.25, 15)).astype(np.int32) n_values # In[9]: for name, f in [ ("lu", spla.lu_factor), ("qr", npla.qr), ("svd", npla.svd) ]: times = [] print("----->", name) for n in n_values: print(n) A = np.random.randn(n, n) start_time = time() f(A) times.append(time() - start_time) pt.plot(n_values, times, label=name) pt.grid() pt.legend(loc="best") pt.xlabel("Matrix size $n$") pt.ylabel("Wall time [s]") # * The faster algorithms make the slower ones look bad. But... it's all relative. # * Is there a better way of plotting this? # * Can we see the asymptotic cost ($O(n^3)$) of these algorithms from the plot?
2fd0342e9038a5a67fc2ed79e704e9fa3ebe5c7d
ben-spiller/pysys-sample
/test/correctness/MyApp_cor_001/Input/test.py
78
3.625
4
print('Hello world') x = 1235 if 123 == x: print ('Nay') else: print ('Yey')
8e549033f4eb67ba0b88d4704037e5186c1cf7d9
cry999/AtCoder
/beginner/003/B.py
418
3.765625
4
def trump(S: str, T: str)->bool: for s, t in zip(S, T): if s == t: continue elif s == '@' and t in 'atcoder': continue elif t == '@' and s in 'atcoder': continue else: return False return True if __name__ == "__main__": S = input() T = input() yes = trump(S, T) print('You can win' if yes else 'You will lose')
28971ac19be7dff6c8e826f3b5b27c2526147ce3
shlok57/CodeDatabase
/Random/Subsets.py
449
4.03125
4
''' generate subsets and sort alphabetically ''' def give_subset(string): subsets = [] actual = [] helper(string, subsets, 0, actual) return actual def helper(string, subsets, i, actual): # print subsets, " ", i if i == len(string): actual.append(subsets) else: helper(string, subsets, i+1, actual) helper(string, subsets + [string[i]], i+1, actual) r = give_subset("abc") print sorted(r, key=lambda x: (len(x),x))
6342eeb82b24787349998a60011a036951ef8cff
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_84/264.py
2,051
3.625
4
#!/usr/bin/python blue = [] red = [] #white = [] def ispossible(x,y): global blue,red # try: # print '>',(x>=0) and (y>=0) # print (y+1 <len(blue)) # print (len(blue[y])>x+1) # print (blue[y][x]=='#' or blue[y][x+1]=='#' or blue[y+1][x]=='#' or blue[y+1][x+1]=='#') # print '<',(red[y][x]==' ' and red[y][x+1]==' ' and red[y+1][x]==' ' and red[y+1][x+1]==' ') # except: # None return (x>=0) and (y>=0) \ and (y+1<len(blue)) \ and (len(blue[y])>x+1) \ and (blue[y][x]=='#' and blue[y][x+1]=='#' and blue[y+1][x]=='#' and blue[y+1][x+1]=='#') \ and (red[y][x]==' ' and red[y][x+1]==' ' and red[y+1][x]==' ' and red[y+1][x+1]==' ') def mark(x,y, c): global red, blue if (c=='@'): red[y] = red[y][:x] + "/\\" + red[y][x+2:] red[y+1] = red[y+1][:x] + "\\/" + red[y+1][x+2:] else: red[y] = red[y][:x] + " " + red[y][x+2:] red[y+1] = red[y+1][:x] + " " + red[y+1][x+2:] # for x in range(bx,bx+2): # red[y][x] = c def dotest(x,y): global red, blue if y>=len(blue): return True nx = x+1 ny = y if (nx>=len(blue[0])): nx = 0 ny = ny+1 if ispossible(x,y): # print "possible",x,y mark(x,y,'@') if dotest(nx,ny): return True mark(x,y,' ') if blue[y][x]=='#': return False return dotest(nx,ny) else: # print x,y # print blue[y] if blue[y][x]=='#' and red[y][x]==' ': return False return dotest(nx,ny) def display(): import sys global red,blue ln = 0 for line in red: for i in range(len(line)): if blue[ln][i]=='.': sys.stdout.write(blue[ln][i]) else: sys.stdout.write(line[i]) print "" ln = ln+1 import sys sys.setrecursionlimit(100000) TESTCASES = input() for tcase in range(1,TESTCASES+1): sy = input() sx = input() blue = [] red = [] # print tcase, sy, sx blue = [raw_input() for l in range(sy)] red = [' '*sx for l in range(sy)] print "Case #%d:"%tcase # print blue # print red # if dotest(0,0): if dotest(0,0): display() else: print "Impossible" # for l in range(sy): # line = raw_input() # blue[l] = line # print 'line:', line
b295f5d307f6e64e52923f463f33575ea77c59cf
harshitbhat/Data-Structures-and-Algorithms
/GeeksForGeeks/DS-Course/000-Mathematics/016.digits-in-factorial.py
872
3.671875
4
# Naive - TLE # class Solution: # def digitsInFactorial(self,N): # def factIt(n): # res = 1 # for i in range(1,n+1): # res *= i # return res # def countDigits(n): # temp = n # ans = 0 # while temp: # temp = temp // 10 # ans += 1 # return ans # return countDigits(factIt(N)) # Approach: # floor value of log base 10 increased by 1, of any number, gives the # number of digits present in that number. import math class Solution: def digitsInFactorial(self,N): if N < 0: return 0 if N == 1: return 1 digits = 0 for i in range(2,N+1): digits += math.log10(i) return math.floor(digits) + 1
fbc464fbed152ecda8fcb8885f9a01613796dcae
HanchengZhao/Leetcode-exercise
/398. Random Pick Index/reservor_sampling.py
1,156
4
4
import random class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type numsSize: int """ self.nums = nums def pick(self, target): """ :type target: int :rtype: int """ result = -1 count = 0 for i in xrange(len(self.nums)): if self.nums[i] == target: if random.randint(0, count) == 0: # chance of 1/count result = i #it will gaurantee that the first occurrence will be selected since randint(0, 0) = 0 count += 1 return result ''' reservoir sampling Consider the example in the OJ {1,2,3,3,3} with target 3, you want to select 2,3,4 with a probability of 1/3 each. 2 : It's probability of selection is 1 * (1/2) * (2/3) = 1/3 3 : It's probability of selection is (1/2) * (2/3) = 1/3 4 : It's probability of selection is just 1/3 So they are each randomly selected. ''' # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.pick(target) # https://www.youtube.com/watch?v=s_Za9GlD0ek
a9cf8d768725fcd80bdaacc3e97acf7ed275c0f8
DigBaseball/python-challenge
/PyPoll/main.py
3,123
4.03125
4
# ___________________________________ # # ~ ~ ~ IMPORT SOME MODULES ~ ~ ~ # # Import the os module so we can can create a path to the data file import os # Import the csv module so we can read the data file import csv # _____________________________________ # # ~ ~ ~ CREATE SOME VARIABLES ~ ~ ~ # # Create and initialize the total number of votes cast total_votes = 0 # Create and initialize a list of candidates who received votes candidate_names = [] # Create and initialize a list of the total number of votes each candidate won candidate_votes = [] # Create and initialize variable for identifying the vote total of the winning candidate winner_votes = 0 # Create and initialize a variable for identifying the name of the winning candidate winner = "" # Create a variable for printing the analysis analysis = "" # ________________________________________ # # ~ ~ ~ GRAB AND ANALYZE OUR DATA ~ ~ ~ # # Path to collect data from the Resources folder election_csv = os.path.join('..', 'Resources', 'election_data.csv') # Read in the CSV file with open(election_csv, 'r') as csvfile: # Split the data on commas election_data = csv.reader(csvfile, delimiter=',') # Skip the header next(election_data) # Start the loop! for vote in election_data: # Increment the number of votes total_votes += 1 # If the current candidate has already received votes, find their position in the list of candidate names and use this value to count this vote if vote[2] in candidate_names: candidate_index = candidate_names.index(vote[2]) candidate_votes[candidate_index] = int(candidate_votes[candidate_index]) + 1 # If the current candidate hasn't received votes yet, add their name to the list of candidates and count their first vote else: candidate_names.append(vote[2]) candidate_votes.append("1") # ______________________________________________ # # ~ ~ ~ PERFORM ANALYSIS AND PRINT OUPUT ~ ~ ~ # # Add the overal vote total to the analysis analysis = "Total Votes: " + str(total_votes) # Analyze the lists of candidates and their vote totals for candidate in candidate_names: # Summarize each candidate's performance analysis = analysis + ( f"\n{candidate}: {round(int(candidate_votes[candidate_names.index(candidate)])/total_votes*100,4)}% ({candidate_votes[candidate_names.index(candidate)]})") # Find the winner if int(candidate_votes[candidate_names.index(candidate)]) > winner_votes: winner_votes = int(candidate_votes[candidate_names.index(candidate)]) winner = candidate # Add the winner to the analysis analysis = analysis + (f"\nWinner: {winner}") # Print the analysis to the terminal print(analysis) # ____________________________________________ # # ~ ~ ~ OUTPUT ANALYSIS TO A NEW FILE ~ ~ ~ # # Specify the file to write to output_data = open("data.txt", "w+") # Print the analysis to the file output_data.write(analysis) # Finish storing the file output_data.close()
599e3e4758166c2b1f93e67c5eed268f6fd61638
Kevinxu99/NYU-Coursework
/CS-UY 1114/Homework/HW5/sx670_hw5_q4.py
243
3.703125
4
w=input("Enter a word:") w1=w.lower() count=0 for i in range(0,len(w1)): if(w1[i]=='a' or w1[i]=='e' or w1[i]=='o' or w1[i]=='u' or w1[i]=='i'): count+=1 print(w,"has",count,"vowels and",(len(w)-count),"consonants")
351ffdf70e3303e85c1dc113ec1997aa6cc8ce75
ashwani8958/Python
/PyQT and SQLite/M3 - Basics of Programming in Python/program/function/3_verdict.py
433
3.625
4
#Do i have the enough money to splurge on the latest iphone? def verdict(m1,m2,m3): total = m1 + m2 + m3 if total >= 15000: print("Yes! you can get a new smartphone!") else: print("Sorry, you can buy the smartphone!") return gift = int(input("Gift money from family: Rs. ")) saving = int(input("saving: Rs. ")) internship = int(input("Money from internship: Rs. ")) verdict(gift,saving,internship)
89b97983bcc43231cc7e0e4aea20aeb227d5de14
mohdsohail-Bestpeers/Python-Projects
/inheritance/hybride_inheri_with_super.py
524
3.828125
4
#Hybride inheritance with super() class rahul(): def __init__(self): print("rahul is a principle of school ") class sanjay(rahul): def __init__(self): super().__init__() print("sanjay teach English subject") class salman(rahul): def __init__(self): super().__init__() print("salman teach maths subject") class student(salman): def __init__(self): super().__init__() print("student study only Maths subject") #create object of student obj=student()
8163d6c4079b3d73eb69e2fecc726abc14560911
victordomene/ram-paxos
/paxos/receivers/receiver.py
2,002
3.640625
4
""" This module defines the abstract class of a receiver. It provides all of the functionality that is implemented by a specific type of receiver. In Paxos, we will allow some different types of communication, but all of them must present this interface. Notice that a single machine may need to use all of the functionality of a Proposer, Learner or Acceptor. For this reason, these methods are all accessible. """ from abc import abstractmethod class Receiver(): def __init__(self): return @abstractmethod def serve(self): """ Starts an instance of the server defined by Receiver. @param host: the host in which server will run @param port: the port in the given host """ return @abstractmethod def handle_prepare(self): """ This method should be used exclusively by an Acceptor. Responds appropriately to a prepare request. This will send back a promise or a refusal of a promise. """ return @abstractmethod def handle_accept(self): """ This method should be used exclusively by an Acceptor. Responds appropriately to an accept request. This will send Accepted requests to the learners (or do nothing if we cannot accept). """ return @abstractmethod def handle_promise(self): """ This method should be used exclusively by a Proposer. Responds appropriately to a promise. It must keep track of the promises this proposer has seen so far, and if everyone in the quorum accepts, it must issue Accept Requests. """ return @abstractmethod def handle_refuse(self): """ This method should be used exclusively by a Proposer. Responds appropriately to a refusal of a promise. This must stop the current proposal. """ return @abstractmethod def handle_learn(self): """ This method should be used exclusively by a Learner. Responds appropriately to a learnrequest. This must check that enough people have accepted this value for this decree, and if so, it must add the decree to a "law book". """ return
163cd2003b814999419d11e19b683fa12c6208d6
songseonghun/kagglestruggle
/python3/001-050/008-len.py
287
3.71875
4
# the 'len ' bulit-in function list_var = [1,2,3,4,5] str_var = 'Hello, wolrd' dict_var = {"a":100, "b":200} print(len(list_var)) #5 - 리스트 안의 변수 수 print(len(str_var)) #12 = 글자 수 띄어쓰기 포함 print(len(dict_var)) #2 = 딕셔너리변수 갯수
81d1fcf1b53c8aafbb894f1ba1c7efa59d223a28
Jonathan-aguilar/DAS_Sistemas
/Ago-Dic-2019/Ricardo_Romero_Medina/Practica1/Practica_6-9.py
256
3.671875
4
lugar_favorito={ 'Friki Plaza':'Ricardo', 'Cine':'Jose', 'Biblioteca':'Juan' } lugar=lugar_favorito.keys() nombre=lugar_favorito.values() val=lugar_favorito.items() for lugar,nombre in val: print(lugar,'Es el lugar favorito de ',nombre)
53ffd293531d1ca6bfe39539d3cf830fbe2fa735
SimasRug/Learning_Python
/Chapter 1/P5.py
153
3.96875
4
import math cities = int(input('How many cities? ')) num = math.factorial(cities) print('For ', cities, ' cities there are ', num, ' possible routes')
4a0adbd60248443f71c1c6f8ed45fc10129ee9f2
arghadeep25/Neural-Network-Activation-Functions
/relu.py
406
3.53125
4
import numpy as np class ReLU(): def __init__(self): self.val = np.arange(-20, 20, .1) def function(self): zero = np.zeros(len(self.val)) y = np.max([zero, self.val], axis=0) return y, self.val def derivative(self): val_func, _ = self.function() val_func[val_func<=0.0] = 0 val_func[val_func>0.0] = 1 return val_func, self.val
69c0582b8c78585d961a69e798717939c64d3bb0
basfl/yt_dynamic_programing_python_js
/invert_tree/python_impl/tree/node.py
273
3.546875
4
class NewNode: """ A Node containing data , left and right pointers """ def __init__(self, data): self.data = data self.right = self.left = None def __str__(self): return f'data={self.data} left={self.left} right={self.right}'
b4c03f24705768c77640c5223327b60bc8300d95
rafaelperazzo/programacao-web
/moodledata/vpl_data/3/usersdata/104/424/submittedfiles/ex1.py
370
3.828125
4
# -*- coding: utf-8 -*- from __future__ import division a=input('Digite o primeiro termo:') b=input('Digite o segundo termo:') c=input('Digite o terceiro termo:') delta=(b**2)-(4*a*c) if delta<0: print('A equação não possui raízes reais') if delta>=0: x=((-b)+(delta**0.5))/(2*a) y=((-b)-(delta**0.5))/(2*a) print('%.2f'%x) print('%.2f'%y)
edb1f6b6665f1afb000afde8f180bc742c17cb9d
ShyZhou/LeetCode-Python
/343.py
2,288
4.03125
4
# Integer Break """ Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. Example 1: Input: 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1. Example 2: Input: 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. Note: You may assume that n is not less than 2 and not larger than 58. """ # DP, O(n^2) class Solution(object): def integerBreak(self, n): """ :type n: int :rtype: int """ if n == 1: return 0 max_prod = [0] * (n + 1) for num in range(2, n + 1): max_prod[num - 1] = max(max_prod[num - 1], num - 1) for i in range(1, int(num / 2) + 1): max_prod[num] = max(max_prod[i] * max_prod[num - i], max_prod[num]) return max_prod[n] # O(n) # 正整数从1开始,但是1不能拆分成两个正整数之和,所以不能当输入。 # 那么2只能拆成 1+1,所以乘积也为1。 # 数字3可以拆分成 2+1 或 1+1+1,显然第一种拆分方法乘积大为2。 # 数字4拆成 2+2,乘积最大,为4。 # 数字5拆成 3+2,乘积最大,为6。 # 数字6拆成 3+3,乘积最大,为9。 # 数字7拆为 3+4,乘积最大,为 12。 # 数字8拆为 3+3+2,乘积最大,为 18。 # 数字9拆为 3+3+3,乘积最大,为 27。 # 数字10拆为 3+3+4,乘积最大,为 36。 # .... # 那么通过观察上面的规律,我们可以看出从5开始,数字都需要先拆出所有的3,一直拆到剩下一个数为2或者4,因为剩4就不用再拆了,拆成两个2和不拆没有意义,而且4不能拆出一个3剩一个1,这样会比拆成 2+2 的乘积小。这样我们就可以写代码了,先预处理n为2和3的情况,然后先将结果 res 初始化为1,然后当n大于4开始循环,结果 res 自乘3,n自减3,根据之前的分析,当跳出循环时,n只能是2或者4,再乘以 res 返回即可 class Solution(object): def integerBreak(self, n): """ :type n: int :rtype: int """ if n <= 3: return n - 1 res = 1 while n > 4: res *= 3 n -= 3 return res * n
f7145134ce878d5fce0c0d05960bfba9868d28c4
Foknetics/AoC_2018
/day11/day11-2.py
1,492
3.5625
4
SERIAL_NUMBER = 5034 GRID_SIZE = 300 GRID_SIZE += 1 def power_level(x, y): rack_id = x+10 power_level = rack_id*y power_level += SERIAL_NUMBER power_level = power_level * rack_id try: power_level = int(str(power_level)[-3]) except IndexError: power_level = 0 return power_level - 5 #output = '' power = {} for x in range(1, GRID_SIZE+1): for y in range(1, GRID_SIZE+1): power[(x, y)] = power_level(x, y) # output += str(power[(x,y)]).center(4) # output += '\n' #print(output) best_cell = (0, 0, 0) best_power = 0 for x in range(1, GRID_SIZE): for y in range(1, GRID_SIZE): test_power = 0 #test_includes = [] for size in range(GRID_SIZE-max(x, y)): #print(x, y, size+1) new_column_x = x+size for new_column_y in range(y, y+size+1): test_power += power[(new_column_x, new_column_y)] #test_includes.append((new_column_x, new_column_y)) for new_row_x in range(x, x+size): test_power += power[(new_row_x, new_column_y)] #test_includes.append((new_row_x, new_column_y)) #print(test_includes, test_power) if test_power > best_power: best_cell = (x, y, size+1) best_power = test_power print('The best',best_cell[2],'x',best_cell[2],'square has the top left fuel cell of', (best_cell[0],best_cell[1]), 'with', best_power, 'power')
63dade1b2b593eb6cef59c7d431f84506a55f946
CaptainSherry49/Python-Project-Beginner-to-Advance
/57 Coroutines In Python.py
977
3.625
4
def searcher(): import time # Some 5 sec time consuming code executed book = 'Sherry This is a book in which there are lots of stuff' time.sleep(5) while True: text = (yield) if text in book: print('Your Text is in book') else: print('I cannot found your text') # this is not a function this Coroutines search = searcher() next(search) search.send('Sherry') input('Press any key') search.send('Me') search.close() # ---------------- Challenge -------------- # letters = ['Sherry', 'Hamza', 'Asad', 'Furqan', 'Zulqarnain', 'Salman', 'Rafi', 'Ibrar', 'Babar', 'Sagar', 'Uzair'] def challenge(): print('Started From here') while True: text = (yield) if text in letters: print(f'Your name is in letters list on {letters.index(text)} index') else: print('Name not found') task = challenge() next(task) user = input('Enter Name: ') task.send(user)
54b87482e295b759eb23ec9e3717c961de463f68
Pjoter-B/spyder
/1_Simple_Linear_Regression.py
1,103
3.9375
4
# Simple Linear Regression - data years of experience vs salary and relationship import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1] # Train test split from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=0) # Fitting Simple Linear Regression to the Training set from sklearn.linear_model import LinearRegression lr = LinearRegression() lr.fit(X_train,y_train) # Predicting predictions = lr.predict(X_test) # Visualization plt.scatter(X_train, y_train, color='red') plt.plot(X_train, lr.predict(X_train),color='blue') plt.title('Salary vs Experience (Training Set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show() # Test set results plt.scatter(X_test, y_test, color='red') plt.plot(X_train, lr.predict(X_train),color='blue') plt.title('Salary vs Experience (Test Set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show()
36d463b47b9587991c54fdd539f5ba6203a15fc5
ranierelm/Python_exercise
/ex029.py
204
3.71875
4
vel = int(input('A qual velocidade você passou no radar? ')) valor = (vel - 80) * 7 if vel > 80: print(f'Você foi multado! \nValor da multa: R${valor}') else: print('Velocidade permitida!')
fe87f45df5f4939468c40dd7a18df44e0cf129b5
vinnicius-martins/Treinamento-Python
/ex040.py
216
3.90625
4
n1 = float(input("Digite a primeira nota: ")) n2 = float(input("Digite a segunda nota: ")) m = (n1 + n2)/2 if m < 5: print("REPROVADO") elif m >=5 and m < 7: print("RECUPERAÇÃO") else: print("APROVADO")
525776a784c9e311a06d5f67480761164c61bb24
3ntropia/pythonDojo
/list/list7/testSortList.py
542
3.578125
4
import unittest from list.list7 import sortList class MyTestCase(unittest.TestCase): def test_not_sorted(self): self.assertEqual(sortList.is_sorted([2, 9, 3, 8]), False) def test_not_sorted_letters(self): self.assertEqual(sortList.is_sorted(['d', 'a', 'h']), False) def test_is_sorted(self): self.assertEqual(sortList.is_sorted([4, 5, 6]), True) def test_is_sorted_letters(self): self.assertEqual(sortList.is_sorted(['g', 'h', 'i']), True) if __name__ == '__main__': unittest.main()
9d51b5eb35f38cf0d59621e392deb349b623e70c
Dummy-Bug/Love-Babbar-DSA-Cracker-Sheet
/Binary Trees/26.2 LCA of a Binary Tree Recursive.py
982
3.578125
4
class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': self.ans = None self.find_lca(root,p,q) return self.ans def find_lca(self,root,p,q): # mainain three flag variables ,mid for root and left,right for children. if not root: return False if root == p or root == q: # if root node is one of the given nodes then mark mid = True mid = True else: mid = False left = self.find_lca(root.left,p,q) # recurse left subtree for the node right = self.find_lca(root.right,p,q) if mid + right + left >= 2: # if any node have any two variables true means we that would be LCA node. self.ans = root return (mid or left or right) # if any is true then it means we have found atleast one of the given nodes.
20e41786bca24aec0e4b4d582385564653bce1dc
toyijiu/300_python_questions
/300_questions_python/11_arithmetic_progression.py
72
3.609375
4
#用公式产生一个11的等差数列 print([x*11 for x in range(10)])
4f554404afe9d4406c18e7ef7ed1ded7de0cc9ce
englishta/python
/machine learning/analysis/ana1.py
413
3.953125
4
# %% #zipの使い方 seq1 = ['foo', 'bar', 'baz'] seq2 = ['one', 'two', 'three'] #for x, y in zip(seq1, seq2): # print(x, y) for i, (a, b) in enumerate(zip(seq1, seq2)): print(i, a, b) zipped = zip(seq1, seq2) a, b = zip(*zipped)#分解する print(a) print(b) # %% #set a = {1, 2, 3, 4, 5} b = {3, 4, 5, 6, 7, 8} wa = a.union(b)#a | b seki = a.intersection(b)# a & b print(wa) print(seki) # %%
1c0661b98621a2795e923cc3133b928a5f336905
amitkayal/Deep_learning_CNN
/ConvolutionalNeuralNetworks.py
9,030
3.859375
4
# Build Convolutional Neural Networks #Import Keras package. # Sequential pakage is used to initilize our neural network from keras.models import Sequential from keras.layers import Dropout ''' # Conv2D is used to make first step in CNN that is adding convolutional layers. # Since we are working on image, and images are 2D unlike video which are 3D(3rd dimention is time). # So we will w=be using Conv2D pakage. ''' from keras.layers import Conv2D #MaxPooling : Build step 2 that is pooling step from keras.layers import MaxPooling2D ''' # Flatten : Used to build step 3, that is converting all pooled feature maps that we have created through # convolution and max pooling into this large feature vector and that will become input layer to fully connected layer. ''' from keras.layers import Flatten # Dense : Used to add fully connected layer in artifical neural network from keras.layers import Dense # Initialising the CNN classifier = Sequential() # Step 1 : Convolution ''' # Here order of input_shape parameter is important. Since we are using tensorflow backend the order is 2D array dimension followed by number od channels. # And it will be otherwise in theno backend. Number of channel = 3 for color image and 2 for black n white channel # Next important parameter is activation function, we are using "relu" activation function as we dont want any negative pixel value in feature maps. # We need to remove these negative pixels in order to have non linearity in our CNN. ''' classifier.add(Conv2D(32, 3, 3, input_shape = (128,128,3), activation = 'relu')) # Step 2: Pooling ''' # Poolong step will reduce the size of feature map. We take 2X2 sub table and slide over feature map and each time we take max of four cells. # Taking max is called max pooling, and we slide this sub table with stride of 2 not with stride of 1. Which will result in reduced size feature map. # Size of feature map is divided by 2. We apply max pooling on all the feature maps and this will obtain next layer called pooling layer. ''' classifier.add(MaxPooling2D(pool_size=(2,2))) # Adding a second convolutional layer classifier.add(Conv2D(32, 3, 3, activation='relu')) classifier.add(MaxPooling2D(pool_size=(2,2))) # Adding a 3rd convolutional layer classifier.add(Conv2D(64, 3, 3, activation='relu')) classifier.add(MaxPooling2D(pool_size=(2,2))) # Step 3: Flattening ''' # Taking all pooled feature maps and put them into a single vector. This vector will be huge. # This single vector will be intput to ANN layer. # 1) Why dont we lose special structure by flattering these feature map: That is because by creating feature maps we extracted the special structure information by getting high numbers in feature maps. # These high numbers represents special structure in image and these high numbers preserved by convotutiona and max pooling step. # 2) Why dont we take all pixels and flatten them without appling previous steps ? : If we do so then each pixel will represent one pixel independently. So we get information about only # one pixel not that how this pixel is connected to other pixels around it. So we dont and any information about special structure around this pixel. ''' classifier.add(Flatten()) # Step 4: Full Connection ''' Builing classic ANN composed of fully connected layer. In previous step we have created huge single vector that can be used as input layer of ANN. Because ANN can be a good classifier of non linear problem. ''' classifier.add(Dense(units=128, activation='relu')) classifier.add(Dropout(rate=0.5)) classifier.add(Dense(units=1, activation='sigmoid')) # Step 5 : Compile CNN classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Step 6: Fitting image to CNN ''' We need to perform image augmentation step that basically means image pre-processing to prevent over fitting. And that can be done by ImageDataGenerator(). In case of images model need to lots of images to find and generalize some correlation between the images. And that is where image augmentation is used. Image augmentation trick will create many batches of image and in each batch it will apply some random transformation on randomally selected images like roatation, filliping, shifting, shearing them etc.. Due to this transformation model will get many diverse images inside these batches, therefore lot more material to train. The transformation are random so model will not find same image across the batches. ''' from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) training_set = train_datagen.flow_from_directory('C:\\Users\\Chandan.S\\Desktop\\DeepLearning\\CNN\\dataset\\training_set', target_size=(128, 128), batch_size=32, class_mode='binary') test_set = test_datagen.flow_from_directory('C:\\Users\\Chandan.S\\Desktop\\DeepLearning\\CNN\\dataset\\test_set', target_size=(128, 128), batch_size=32, class_mode='binary') classifier.fit_generator(training_set, steps_per_epoch=8000, epochs=25, validation_data=test_set, validation_steps=2000) #------------------------------------------------------------------------------------------------------- ''' Our CNN model is ready we see that model is having accuracy of 88% of test set. Moving further I will show one application of this CNN model. In which we will try to predict one single image. Wheather it is cat or dog. We have two images one of cat and other one of dog. And same we will be predicting using this model. Data present at dataset\single_prediction ''' # Making single prediction #Import numpy for pre-processing the image so that it can be excepted by predict method import numpy as np from keras.preprocessing import image # Load the impage on which we want to do the prediction. ''' load_img : Funtion used to load the image. This function require 2 argument. 1st argument : Path of the image. 2nd argument : targest side, that must be same as we have used in training. Here we have used 128X128 image for training so predict funtcion will also expect the same size. ''' test_image = image.load_img('C:\\Users\\Chandan.S\\Desktop\\DeepLearning\\CNN\\dataset\\single_prediction\\cat_or_dog_1.jpg',target_size=(128, 128)) ''' After importing we can see that the size and type of test_image as shown below. test_image: type = Image Size = (128, 128) ''' # Adding 3rd dimension ''' We see that test_image is 2 dimensional, here we need to add one more dimension. That is because input layer of CNN has 3 dimension, input_shape = (128,128,3). So we need to 3rd dimention to test_image and that is for color. This can be done by img_to_array() ''' test_image = image.img_to_array(test_image) ''' After adding 3rd dimension test_image will become as: test_image: type = Image Size = (128, 128, 3) : Now test_image became 3 dimensional of size (128,128,3) same as CNN input layer. ''' # Add 4th dimension ''' THis 4th dimension crossponds to batch. Function of neural network cannot accept single input image. It only accepts inputs in a batch, even if batch contains only one image. Here we will have 1 batch on one input but we can have several batches of several inputs. expand_dims() : This function takes two images. 1st argument = test_image and 2nd argument is axis which represent index of new dimention. ''' test_image = np.expand_dims(test_image, axis=0) ''' After adding 4th dimension test_image will become as: test_image: type = Image Size = (1,128, 128, 3) : Now test_image became 3 dimensional of size (128,128,3) same as CNN input layer. ''' # Prediction result = classifier.predict(test_image) ''' classifier.predict(test_image) Out[41]: array([[1.]], dtype=float32) Here result of prediction is 1. Need to figure out what 1 crossponds, Cat or dog. ''' # To know mapping ''' To know the mapping we will use class_indices attribute that will tell us the mapping between string cat and dog and their numeric value. ''' training_set.class_indices ''' training_set.class_indices Out[43]: {'cats': 0, 'dogs': 1} ''' # So here we see that our model prediction is correct. Model has predicted "1" and that crossponds to dog. if result[0][0] == 1: prediction = 'Dog' else: prediction = 'Cat'
8571e01b97dffe8b2438c0ad009c7569b55b58eb
jfharney/ornl-poller
/practice/pet.py
461
3.671875
4
class Pet(object): def __init__(self,name,species): self.name = name self.species = species def getName(self): return self.name def getSpecies(self): return self.species def __str__(self): return "%s is a %s" % (self.name, self.species) def main(): print 'in pet main' p = Pet("polly","parrot") print p.getName() if __name__ == "__main__": main()
8085ad7b719b62c3f255b6c586ffcdb80327de50
Aftabkhan2055/Machine_Learning
/python1/quadratic.py
382
3.9375
4
import math a=int(input("enter the no")) b=int(input("enter the no")) c=int(input("enter the no")) d=b**2-4*a*c if d<0: print(" root are imaginary",d) elif d==0: root=math.sqrt(d)/2*a print("root are equal",root) else: root1=-b+math.sqrt(d)/2*a root2=-b-math.sqrt(d)/2*a print("seprateroot",root1) print("seprateroort",root2)
2c2303fad210e9542808b282f1385b6b76255b63
sebito91/challenges
/exercism/python/archive/space-age/space_age.py
1,643
3.78125
4
""" Module to return the 'earth' time on different planets """ # -*- coding: utf-8 -*- from __future__ import unicode_literals class SpaceAge(object): """ structure to handle our time conversion """ def __init__(self, seconds=0): """ Instantiate our space_age calculator """ self._seconds = float(seconds) self._earth = 31557600.0 @property def seconds(self): """ return the seconds we've stored at instantiation """ return self._seconds def on_earth(self): """ Return time on earth """ return float("{:.2f}".format(self._seconds / self._earth)) def on_mercury(self): """ Return time on mercury """ return float("{:.2f}".format(self._seconds / (self._earth * 0.2408467))) def on_venus(self): """ Return time on venus """ return float("{:.2f}".format(self._seconds / (self._earth * 0.61519726))) def on_mars(self): """ Return time on mars """ return float("{:.2f}".format(self._seconds / (self._earth * 1.8808158))) def on_jupiter(self): """ Return time on jupiter """ return float("{:.2f}".format(self._seconds / (self._earth * 11.862615))) def on_saturn(self): """ Return time on saturn """ return float("{:.2f}".format(self._seconds / (self._earth * 29.447498))) def on_uranus(self): """ Return time on uranus """ return float("{:.2f}".format(self._seconds / (self._earth * 84.016846))) def on_neptune(self): """ Return time on neptune """ return float("{:.2f}".format(self._seconds / (self._earth * 164.79132)))
bce631569f3e2d95d0b176179c8c137006c7ce95
zzinsane/algos
/countRangeSum.py
2,916
3.578125
4
""" Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive. Note: A naive algorithm of O(n2) is trivial. You MUST do better than that. Example: Given nums = [-2, 5, -1], lower = -2, upper = 2, Return 3. The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2. """ import time class Solution(object): cache_mapping = {} max_idx = [] min_idx = [] def get_from_cach(self, limit, lower, upper): cache = self.cache_mapping.get(limit, {}) return cache.get((lower, upper), None) def recursive(self, nums, limit, lower, upper): self.total += 1 if limit < 0: return 0 if self.max_idx[limit] < lower or self.min_idx[limit] > upper: return 0 v = self.get_from_cach(limit, lower, upper) if v is not None: return v if limit == 0: if lower<=nums[0]<=upper: return 1 else: return 0 ranges1 = self.recursive(nums, limit-1, lower, upper) ranges2 = self.recursive(nums, limit-1, lower-nums[limit], upper-nums[limit]) if lower<=nums[limit]<=upper: ranges2 +=1 final = ranges1 + ranges2 cache = self.cache_mapping.get(limit, {}) cache[(lower, upper)] = final self.cache_mapping[limit] = cache return final def countRangeSum(self, nums, lower, upper): """ :type nums: List[int] :type lower: int :type upper: int :rtype: int """ self.total = 0 nums = sorted(nums) if len(nums) > 0: self.max_idx = range(0, len(nums)) self.min_idx = range(0, len(nums)) minimal = 0 for idx, i in enumerate(nums): if i <0: self.max_idx[idx] = i self.min_idx[idx] = self.min_idx[idx-1] + i if idx >0 else i minimal += i else: self.max_idx[idx] = max(self.max_idx[idx-1] + i if idx > 0 else i, i) self.min_idx[idx] = minimal value = self.recursive(nums, len(nums) - 1, lower, upper) print self.total return value solution = Solution() array = [14, -30, 22, 8, 3, 20, -11, 8, 7, -9, -7, -13, -5, -22, 11, 23, 15, 29, -17, -27, -2, 14, 14, 11, 22, -14, -27, -5, -9, -21, 22, 3, 12, 7, -13, 14, -23, -16, 12, -4, 21, -8, -18, 22, 17, -19, -22, 8, 2, -2, 24, -12, -24, -16, -2, 19, 7, 7, -20, 8] start = int(time.time()*1000) print solution.countRangeSum(array, 39, 88) print int(time.time()*1000) - start array = [1135,-1067,-557,1629,-136,151,676,-1470,-1031,-1973,1120,291,-35,2923,1313,-105,-878,2201,1123,-1283,-263,-500,87,-2735,538,2582,2866,-1587,-1118,1201,-2280,-2372,2106,1527,-2671,-1446,-2139,-47,-218,1879,-2411,1687,-1125,-406,2155,566,600,-814,-903,-144,453,-1976,-1898,-2802,-2031,-816,2253,1456,623,847] start = int(time.time()*1000) print solution.countRangeSum(array, -5604, -3813) print int(time.time()*1000) - start print solution.countRangeSum([], 0, 0) print solution.countRangeSum([-2, 5, 1], -2, 2)
2abdfaedcef487323adf8c1eb73c20b37210035a
DreamOfTheRedChamber/leetcode
/Python/SweepLine/MyCalendarIII.py
1,150
3.625
4
# Definition for a binary tree node. import heapq import unittest # Read about enumerate in python from collections import defaultdict from typing import List from sortedcontainers import SortedSet, SortedList class MyCalendarThree: def __init__(self): self.sortedBoundaries = SortedList(key=lambda x: (x[0], x[1])) return def book(self, start: int, end: int) -> int: self.sortedBoundaries.add((start, 1)) self.sortedBoundaries.add((end, -1)) count = 0 maxIntersect = 0 for point in self.sortedBoundaries: if point[1] == 1: count += 1 maxIntersect = max(maxIntersect, count) else: count -= 1 return maxIntersect class MyCalendarIII(unittest.TestCase): def test_Leetcode(self): myCalendar = MyCalendarThree() print(myCalendar.book(10, 20)) print(myCalendar.book(50, 60)) print(myCalendar.book(10, 40)) print(myCalendar.book(5, 15)) print(myCalendar.book(5, 10)) print(myCalendar.book(25, 55)) if __name__ == '__main__': unittest.main()
e18dceced9cd2309f1ea7972e6f41a22392e5977
lucasayres/python-tools
/tools/reverse.py
241
4.1875
4
# -*- coding: utf-8 -*- def reverse(input): """Reverse the order of a list or string. Args: input (str/list): List or String. Returns: str/list: Return a reversed list or string. """ return input[::-1]
44d88e151517c747ef5d8e590a8f4569d224c5a2
egjallo/holbertonschool-higher_level_programming-1
/0x07-python-test_driven_development/4-print_square.py
634
3.984375
4
#!/usr/bin/python3 """ This is the "4-print_square" module for the Holberton School Higher Level Programming track. The 4-print_square module supplies one function, matrix_divided(). For example, >>> print_square(4) #### #### #### #### """ def print_square(size): """ Prints a square made with the char `#`. """ if type(size) is not int: raise TypeError("size must be an integer") elif size < 0: raise ValueError("size must be >= 0") elif size > 0: print(('#' * size + '\n') * size, end="") if __name__ == "__main__": import doctest doctest.testfile("tests/4-print_square.txt")
52f0e54bcc1ed76f6bdbde46ebf83da745676b28
priyanshkedia04/Codeforces-Solutions
/Part A/A and B and Chess.py
337
3.65625
4
lower = dict(zip(list('qrbnp'), [9,5,3,3,1])) upper = dict(zip(list('QRBNP'), [9,5,3,3,1])) white = 0 black = 0 for i in range(8): for j in input(): if j in lower: black += lower[j] elif j in upper: white += upper[j] if black > white: print('Black') elif black < white: print('White') else: print('Draw')
34ad8ab18fa3253fd1469bae2366d4d2548380db
BABIN2D/Employee-Eligiblity-
/Employee.py
4,987
3.859375
4
# ask user to provide input for age gender and physical disability. # if anyone is above the age of 45 the work in urban areas, all female workers # work in urban areas, any disabled person work in urban areas rest # will work any location # ask for qualification, the following are the criteria and accordingly # the post offered to those criterias. # 12 pass = peon # graduate = clerk # pg- in MSC = R&D, M.COM = FINANCE, MCA = IT , MBA = Marketing / HR / FINANCE # There are only the above posts available age = int(input('Enter Age\t')) if 18 <= age <= 60: print('The following are the qualification and the post\noffered on those qualifications\nMSC\tR&D\nM.COM\tFINANCE\nMCA\tIT\nMBA\tMARKETING/FINANCE/HR\nGraduation\tClarical\n12 Pass\tPeon') qualification = input('Please enter your qualification\t') if qualification in('MSC','M.COM','MCA','MBA','12 Pass','Graduate'): print('you are eligible for work ') if qualification == "MSC": print('Work available in R&D Department') gender = input('Enter Gender\t') choice = input('Do you have any disability?\t') if choice in ('YES',"Yes",'y','yes','Y'): print('Wrok in Urban Area') elif gender in('Female','FEMALE','F','f') or age >= 45: print('You are eligible for working in Urban .\nCome down to our nearest branch of an interview session') else: print('You are eligible for working in any location.\nCome down to our nearest branch of an interview session') if qualification == "M.COM": print('Work available in FINANCE Department') gender = input('Enter Gender\t') choice = input('Do you have any disability?\t') if choice in ('YES',"Yes",'y','yes','Y'): print('Wrok in Urban Area') elif gender in('Female','FEMALE','F','f') or age >= 45: print('You are eligible for working for Urban location.\nCome down to our nearest branch of an interview session') else: print('You are eligible for working in any location.\nCome down to our nearest branch of an interview session') if qualification == "MCA": print('Work available in IT Department') gender = input('Enter Gender\t') choice = input('Do you have any disability?\t') if choice in ('YES',"Yes",'y','yes','Y'): print('Wrok in Urban Area') elif gender in('Female','FEMALE','F','f') or age >= 45: print('You are eligible for working for Urban location.\nCome down to our nearest branch of an interview session') else: print('You are eligible for working in any location.\nCome down to our nearest branch of an interview session') if qualification == "MBA": print('Work available in FINANCE/MARKETING/HR Department') gender = input('Enter Gender\t') choice = input('Do you have any disability?\t') if choice in ('YES',"Yes",'y','yes','Y'): print('You are eligible for working for Urban location.\nCome down to our nearest branch of an interview session') elif gender in('Female','FEMALE','F','f') or age >= 45: print('You are eligible for working for Urban location.\nCome down to our nearest branch of an interview session') else: print('You are eligible for working in any location.\nCome down to our nearest branch of an interview session') if qualification == "Graduate": print('Work available in Clarical Department') gender = input('Enter Gender\t') choice = input('Do you have any disability?\t') if choice in ('YES',"Yes",'y','yes','Y'): print('Wrok in Urban Area') elif gender in('Female','FEMALE','F','f') or age >= 45: print('You are eligible for working in Urban .\nCome down to our nearest branch of an interview session') else: print('You are eligible for working in any location.\nCome down to our nearest branch of an interview session') if qualification == "12 Pass": print('Work available for Peon ') gender = input('Enter Gender\t') choice = input('Do you have any disability?\t') if choice in ('YES',"Yes",'y','yes','Y'): print('Wrok in Urban Area') elif gender in('Female','FEMALE','F','f') or age >= 45: print('You are eligible for working in Urban .\nCome down to our nearest branch of an interview session') else: print('You are eligible for working in any location.\nCome down to our nearest branch of an interview session') else: print('No Work Available for"%s"qualification'%qualification) else: print('You are not elligable for work')
e54b209801aa23895bbff5cc96547e58a4aea656
Constadine/Misc
/other/time.py
351
3.8125
4
hours = int(input("Δώσε ώρες: ")) minutes = int(input("...λεπτά: ")) seconds = int(input("...και δευτερόλεπτα: ")) if hours < 10: hours = "0" + str(hours) if minutes < 10: minutes = "0" + str(minutes) if seconds < 10: seconds = "0" + str(seconds) print(str(hours) + ":" + str(minutes) + ":" + str(seconds))
fd0b1700bb7f1edf956cab204426826a53e6e66f
brucehzhai/Python-JiangHong
/源码/Pythonpa/ch12/listbox.py
497
3.84375
4
from tkinter import * #导入tkinter模块所有内容 root = Tk(); root.title("Listbox") #窗口标题 v = StringVar() v.set(('linux','windows','unix')) lb = Listbox(root, selectmode=EXTENDED, listvariable = v) lb.pack() for item in ['python','tkinter','widget']: lb.insert(END,item) #列表框 lb.curselection() #选择项目的索引位置:('2', '3') for i in lb.curselection():print(lb.get(i), end=' ') #输出选择项目:unix python root.mainloop()
586eb9438e244f912e9c086789ea3f6481ac4a25
tagler/MIT_Computer_Science_Python
/exam_midterm.py
4,004
4.03125
4
# -*- coding: utf-8 -*- """ PROBLEM 1 Write a simple procedure, myLog(x, b), that computes the logarithm of a number x relative to a base b. For example, if x = 16 and b = 2, then the result is 4 - because 2^4=16. If x = 15 and b = 3, then the result is 2 - because 3^2 is the largest power of 3 less than 15. In other words, myLog should return the largest power of b such that b to that power is still less than or equal to x. x and b are both positive integers; b is an integer greater than or equal to 2. Your function should return an integer answer. """ def myLog(x, b): ''' x: a positive integer b: a positive integer; b >= 2 returns: log_b(x), or, the logarithm of x relative to a base b. ''' total = b count = 1 while True: if total > x: count = count - 1 break count = count + 1 total = total * b return count """ PROBLEM 2 Write a Python function that returns the sublist of strings in aList that contain fewer than 4 characters. For example, if aList = ["apple", "cat", "dog", "banana"], your function should return: ["cat", "dog"] This function takes in a list of strings and returns a list of strings. Your function should not modify aList. """ def lessThan4(aList): ''' aList: a list of strings ''' newList = [] for word in aList: if len(word) < 4: newList.append(word) return newList """ PROBLEM 3 Write a recursive Python function, given a non-negative integer N, to calculate and return the sum of its digits. Hint: Mod (%) by 10 gives you the rightmost digit (126 % 10 is 6), while doing integer division by 10 removes the rightmost digit (126 / 10 is 12). This function has to be recursive; you may not use loops! This function takes in one integer and returns one integer. """ def sumDigits(N): ''' N: a non-negative integer ''' if N < 10: return N return sumDigits(N/10) + N%10 """ PROBLEM 4 Write a Python function that returns a list of keys in aDict with the value target. The list of keys you return should be sorted in increasing order. The keys and values in aDict are both integers. (If aDict does not contain the value target, you should return an empty list.) This function takes in a dictionary and an integer and returns a list. """ def keysWithValue(aDict, target): ''' aDict: a dictionary target: an integer ''' newList = [] for x in aDict: if aDict[x] == target: newList.append(x) return newList """ PROBLEM 5 Write a Python function called satisfiesF that has the specification below. Then make the function call run_satisfiesF(L, satisfiesF). Your code should look like: run_satisfiesF(L, satisfiesF) For your own testing of satisfiesF, for example, the following test function f and test code: def f(s): return 'a' in s L = ['a', 'b', 'a'] print satisfiesF(L) print L Should print: 2 ['a', 'a'] Paste your entire function satisfiesF, including the definition, in the box below. After you define your function, make a function call to run_satisfiesF(L, satisfiesF). Do not define f or run_satisfiesF. Do not leave any debugging print statements. For this question, you will not be able to see the test cases we run. This problem will test your ability to come up with your own test cases. """ def satisfiesF(L): """ Assumes L is a list of strings Assume function f is already defined for you and it maps a string to a Boolean Mutates L such that it contains all of the strings, s, originally in L such that f(s) returns True, and no other elements Returns the length of L after mutation """ result = [] for x in L: result.append( f(x) ) for x in range(len(L)-1, -1 , -1): if result[x] == False: del L[x] return( len(L) ) def f(s): return 'a' in s L = ['a', 'b', 'a'] print satisfiesF(L) print L
7c7ce615831c6ccef1d0bdeea4a03b44567cc779
taha717/python
/cheeking py3_file.py
1,475
4.21875
4
import os # Setting variables one = 1 comment_char = "#" space = " " comment = "comment" code_line = "line" total_line = "line" plural = "s" # Initialising line counters comment_counter = 0 code_counter = 0 line_counter = 0 # Getting file name from user file_name = input("Please enter the name of file to checked: ") # Checking if the file exists file_exists = os.path.exists(file_name) # Opens file if it exists if file_exists: the_file = open(file_name) # Initalising for loop and total line counter for each_line in the_file: line_counter += one # Removing spaces if a line starts with a space if each_line.startswith(space): each_line.strip() # Counting comment lines if each_line.startswith(comment_char): comment_counter += one # Counting code lines elif each_line[0].isalnum(): code_counter += one # Making "line" strings plural if comment_counter != one: comment = comment + plural if code_counter != one: code_line = code_line + plural if line_counter != one: total_line = total_line + plural print("{} contains {} {} and {} {} of code out of {} {} in total.".format(file_name, comment_counter, comment, code_counter, code_line, line_counter, total_line)) else: print("Sorry, I can't see a file called {}.".format(file_name)) the_file.close()
3f49f9750d7211b8f0e4a391af5b3cd2531c108d
Bara-Ga/SmartninjaCourse
/python_00100_datatypes_calculator/example_00130_show_types_quiz.py
368
3.734375
4
print type(str(1)) print str(1) eingabe_1 = "1" eingabe_2 = "2" print 3+4 print eingabe_1 + eingabe_2 # concat print int(eingabe_1) + int(eingabe_2) print float(eingabe_1) + float(eingabe_2) resultat_1 = int(eingabe_1) + int(eingabe_2) resultat_2 = float(eingabe_1) + float(eingabe_2) print resultat_1 == resultat_2 print resultat_1 is resultat_2 print 1 is 1
954bfeb1f35c90f1ad4b3b3b25d4d49f43302d7e
Pratyaksh7/Dynamic-Programming
/Longest Common Subsequence/Problem2.py
698
3.71875
4
# 2. Longest Common Substring -> means continuous sequence def longestSubstring(X,Y, n,m): # Initialization of first row and first column of the t matrix for i in range(n+1): for j in range(m+1): if i==0 or j==0: t[i][j] = 0 for i in range(1, n+1): for j in range(1, m+1): if X[i-1] == Y[j-1]: # comparing the 1st letter of both strings # t[i][j] = 1 + lcs(X,Y,n-1, m-1) t[i][j] = 1+t[i-1][j-1] else: t[i][j] = 0 return t[n][m] X = "abdefg" Y = "abcefg" n = len(X) m = len(Y) t= [[0 for j in range(m+1)] for i in range(n+1)] print(longestSubstring(X,Y, n,m))
dc1fa99bcb723fc22f603d40ddbb9ce89fa1321c
ishanlal/data-structures-and-algorithms
/Data Structures/problem_3.py
8,836
3.609375
4
import sys from queue import PriorityQueue from functools import total_ordering dic_ = {} class Tree: def __init__(self, data=None): self.root = Node(data, None, None, None) def get_root(self): return self.root def set_root(self, node): self.root = node @total_ordering class Node: def __init__(self, value=None, freq=None, left=None, right=None): self.value = value self.freq = freq self.left = left self.right = right def get_value(self): return self.value def set_value(self, value): self.value = value def set_left_child(self, node): self.left = node def set_right_child(self, node): self.right = node def get_left_child(self): return self.left def get_right_child(self): return self.right def has_left_child(self): return self.left is not None def has_right_child(self): return self.right is not None def __eq__(self, other): return (self.freq == other.freq) def __lt__(self, other): return (self.freq < other.freq) def huffman_encoding(data): freq_table = dict() for i in data: if i in freq_table: freq_table[i] += 1 else: freq_table[i] = 1 SL = PriorityQueue() K = freq_table.keys() for key in K: SL.put(Node(key, freq_table[key], None, None)) tr_ = Tree(None) while SL.qsize() > 1: low_node_1 = SL.get() low_node_2 = SL.get() freq_sum = low_node_1.freq + low_node_2.freq new_node = Node(None, freq_sum, None, None) new_node.set_left_child(low_node_1) new_node.set_right_child(low_node_2) tr_.set_root(new_node) SL.put(new_node) ret_tree = SL.get() generateEncoding(ret_tree, "") ret_encd = "" for letter in data: ret_encd = ret_encd + dic_[letter] return ret_encd, ret_tree def generateEncoding(root, stringgg): if (( not root.has_left_child()) and ( not root.has_right_child()) and root.value != None): dic_[root.value] = stringgg if stringgg == "": dic_[root.value] = "1" return else: if root.has_left_child(): generateEncoding(root.get_left_child(), stringgg+"0") if root.has_right_child(): generateEncoding(root.get_right_child(), stringgg+"1") def huffman_decoding(data,tree): current = tree ret_string = "" for i in range(len(data)): if (data[i] == '0') : if current.has_left_child(): current = current.get_left_child() else: if current.has_right_child(): current = current.get_right_child() if ((not current.has_left_child()) and (not current.has_right_child()) ): ret_string = ret_string + current.value current = tree return ret_string if __name__ == "__main__": codes = {} # Testcase 1 data_1 = "" a_great_sentence = data_1 if ((a_great_sentence == None) or (a_great_sentence == "")): print("Enter valid data!") else: print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence))) print ("The content of the data is: {}\n".format(a_great_sentence)) encoded_data, tree = huffman_encoding(a_great_sentence) print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2)))) print ("The content of the encoded data is: {}\n".format(encoded_data)) decoded_data = huffman_decoding(encoded_data, tree) print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data))) print ("The content of the encoded data is: {}\n".format(decoded_data)) # Testcase 2 data_2 = None a_great_sentence = data_2 if ((a_great_sentence == None) or (a_great_sentence == "")): print("Enter valid data!") else: print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence))) print ("The content of the data is: {}\n".format(a_great_sentence)) encoded_data, tree = huffman_encoding(a_great_sentence) print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2)))) print ("The content of the encoded data is: {}\n".format(encoded_data)) decoded_data = huffman_decoding(encoded_data, tree) print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data))) print ("The content of the encoded data is: {}\n".format(decoded_data)) # Testcase 3 data_3 = "The bird is the word" a_great_sentence = data_3 if ((a_great_sentence == None) or (a_great_sentence == "")): print("Enter valid data!") else: print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence))) print ("The content of the data is: {}\n".format(a_great_sentence)) encoded_data, tree = huffman_encoding(a_great_sentence) print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2)))) print ("The content of the encoded data is: {}\n".format(encoded_data)) decoded_data = huffman_decoding(encoded_data, tree) print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data))) print ("The content of the encoded data is: {}\n".format(decoded_data)) #Testcase 4 data_4 = "AAAAAAABBBCCCCCCCDDEEEEEE" a_great_sentence = data_4 if ((a_great_sentence == None) or (a_great_sentence == "")): print("Enter valid data!") else: print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence))) print ("The content of the data is: {}\n".format(a_great_sentence)) encoded_data, tree = huffman_encoding(a_great_sentence) print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2)))) print ("The content of the encoded data is: {}\n".format(encoded_data)) decoded_data = huffman_decoding(encoded_data, tree) print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data))) print ("The content of the encoded data is: {}\n".format(decoded_data)) #Testcase 5 data_5 = "aaaa" a_great_sentence = data_5 if ((a_great_sentence == None) or (a_great_sentence == "")): print("Enter valid data!") else: print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence))) print ("The content of the data is: {}\n".format(a_great_sentence)) encoded_data, tree = huffman_encoding(a_great_sentence) print("encoded data {}".format(encoded_data)) print("tree {}".format(tree)) print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2)))) print ("The content of the encoded data is: {}\n".format(encoded_data)) decoded_data = huffman_decoding(encoded_data, tree) print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data))) print ("The content of the encoded data is: {}\n".format(decoded_data)) #Testcase 6 data_6 = "a" a_great_sentence = data_6 if ((a_great_sentence == None) or (a_great_sentence == "")): print("Enter valid data!") else: print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence))) print ("The content of the data is: {}\n".format(a_great_sentence)) encoded_data, tree = huffman_encoding(a_great_sentence) print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2)))) print ("The content of the encoded data is: {}\n".format(encoded_data)) decoded_data = huffman_decoding(encoded_data, tree) print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data))) print ("The content of the encoded data is: {}\n".format(decoded_data)) #Testcase 7 data_7 = "aaaa" a_great_sentence = data_7 if ((a_great_sentence == None) or (a_great_sentence == "")): print("Enter valid data!") else: print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence))) print ("The content of the data is: {}\n".format(a_great_sentence)) encoded_data, tree = huffman_encoding(a_great_sentence) print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2)))) print ("The content of the encoded data is: {}\n".format(encoded_data)) decoded_data = huffman_decoding(encoded_data, tree) print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data))) print ("The content of the encoded data is: {}\n".format(decoded_data))
03c9a3f9cd906088b50a2397b9ce3c4b049c0c31
dm36/interview-practice
/interview_cake/permutations.py
3,204
4.15625
4
# All permutations of a string with the same length as the original string # Take a string "abc": # Take away a character- say a- so that we now have the string "bc" # Form all permutations of bc ["bc", "cb"] (recursively) # For each permutation of bc, concatenate a at every possible spot in the string, so for bc: # ["abc", "bac", "bca"] # Same idea for cb, concatenate a at every spot: # ["acb", "cab", "cba"] # Say we took the character b away instead so that we now had the string "ac" # All permutations of ac ["ac", "ca"] # For each permutation of ac, concatenate b at every spot in the string so for ac: # ["bac", "abc", "acb"] # Same idea for ca, concatenate b at every spot # ["bca", "cba", "cab"] # So technically we'd only have to do this process once. def permutation(str): if len(str) == 1: return str char = str[0] remainder = str[1:] remainder_perms = permutation(remainder) perms = [] for perm in remainder_perms: # +1 to handle "bc" + "a" or "bca" # for the above example- i would be 2, perms[:i] would be "bc", # char would be a and perm[i:] would be the "" (empty string) # if perm was "c" and char was "b": # first loop i would be 0, perm[:i] would be "", char would be # b and perm[i:] would be "c" so "bc" # second loop i would be 1, perm[:i] would be c, char would be b # and perm[i:] would be "" so "cb" for i in range(len(perm)+1): perms.append(perm[:i] + char + perm[i:]) # if len(perm) == 1: # perms.append(perm + char) # perms.append(char + perm) # else: # for i in range(len(perm)): # perms.append(perm[:i] + char + perm[i:]) # perms.append(perm + char) return perms # itertools implementation def permutations(iterable, r=None): # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) --> 012 021 102 120 201 210 # tuple of iterable so "abc" -> ("a", "b", "c") pool = tuple(iterable) # 3 in this case n = len(pool) # also 3 in this case r = n if r is None else r if r > n: return # indices would be [0, 1, 2] indices = range(n) # indices in reverse? [2, 1, 0] cycles = range(n, n-r, -1) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return # another itertools implementation # def permutations(iterable, r=None): # pool = tuple(iterable) # n = len(pool) # r = n if r is None else r # for indices in product(range(n), repeat=r): # if len(set(indices)) == r: # yield tuple(pool[i] for i in indices) print permutation("abc") print len(permutation("cats")) for perm in permutations("abc"): print perm
e91bfa8a9d596db19b6bbdb024135193577c3a4b
BenGeissel/Movie_Industry_Insights_Module_1_Project
/Module_1_Project/tmdb_clean.py
5,965
3.53125
4
# Import libraries with proper aliases import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import csv # Create function to fix numerical data; Budget and Gross have '$' and ','; Change to integer def budget_gross_number_fix(dataframe, column): ''' Function to fix the format of money values in the dataframe. Removes '$' and ',' and changes to integer type Input: Dataframe and Column that has data in this format Output: None. Data in dataframe is changed ''' dataframe[column] = dataframe[column].apply(lambda x: x.replace('$', '')) dataframe[column] = dataframe[column].apply(lambda x: x.replace(',', '')) dataframe[column] = dataframe[column].astype('int') return None def clean(file): ''' Function to clean the TMDB Budgets Data CSV File. Input: CSV File name as string Output: Cleaned DataFrame ''' # Read in the TMDB Budgets Data tmdb_budgets_df = pd.read_csv(file) # Combine Movie and Release Date to account for remakes or movies with same name tmdb_budgets_df['movie_date'] = tmdb_budgets_df.movie + ' ' + tmdb_budgets_df.release_date # Apply budget_gross_number_fix function to the three necessary columns budget_gross_number_fix(tmdb_budgets_df, 'production_budget') budget_gross_number_fix(tmdb_budgets_df, 'domestic_gross') budget_gross_number_fix(tmdb_budgets_df, 'worldwide_gross') # Create column for binned budgets tmdb_budgets_df['binned_budget'] = pd.cut(x=tmdb_budgets_df['production_budget'], bins= [0, 500000, 1000000, 5000000, 10000000, 25000000, 50000000, 100000000, 500000000]) # Data Assumption: Only movies that actually go to the box office. Not straight to Netflix or DVD because of 0 gross value. # Filter out movies with 0 gross domestic or worldwide tmdb_budgets_df = tmdb_budgets_df[tmdb_budgets_df.domestic_gross != 0] tmdb_budgets_df = tmdb_budgets_df[tmdb_budgets_df.worldwide_gross != 0] return tmdb_budgets_df def plot_budget_sizes(dataframe): ''' Function to plot the budget distribution in order to determine budget binning Input: Cleaned dataframe Output: Plot of budget distribution. ''' fig = plt.figure(figsize = (8,5)) sns.distplot(dataframe.production_budget, bins = 50, color = 'darkred', kde = True); plt.xlabel("Budget in 100,000,000's") plt.ylabel('% of Movies Produced') plt.title('Budget Spread', fontsize = 20) plt.show() return None # Define bin labels in easy to read format bins_labels = ['($0, $500K]', '($500K, $1M]', '($1M, $5M]', '($5M, $10M]', '($10M, $25M]', '($25M, $50M]', '($50M, $100M]', '($100M, $500M]'] def domestic_ROI(dataframe): ''' Function to calculate domestic ROI from TMDB data. Pivots the data and creates a dictionary used for plotting. Input: Cleaned dataframe Output: Dictionary with label keys and domestic ROI values for plotting. ''' dataframe['Gross_ROI'] = ((dataframe.domestic_gross - dataframe.production_budget) / dataframe.production_budget) tmdb_budgets_domestic_pivot_df = pd.pivot_table(dataframe, index = 'movie_date', columns = 'binned_budget', values = 'Gross_ROI', aggfunc = 'sum') domestic_roi_by_budget = tmdb_budgets_domestic_pivot_df.mean() domestic_roi_dict = {} for label in tmdb_budgets_domestic_pivot_df.columns: domestic_roi_dict[str(label)] = domestic_roi_by_budget[label] domestic_roi_dict = dict(zip(bins_labels, list(domestic_roi_dict.values()))) return domestic_roi_dict def worldwide_ROI(dataframe): ''' Function to calculate worldwide ROI from TMDB data. Pivots the data and creates a dictionary used for plotting. Input: Cleaned dataframe Output: Dictionary with label keys and worldwide ROI values for plotting. ''' dataframe['Worldwide_ROI'] = ((dataframe.worldwide_gross - dataframe.production_budget) / dataframe.production_budget) tmdb_budgets_worldwide_pivot_df = pd.pivot_table(dataframe, index = 'movie_date', columns = 'binned_budget', values = 'Worldwide_ROI', aggfunc = 'sum') worldwide_roi_by_budget = tmdb_budgets_worldwide_pivot_df.mean() worldwide_roi_dict = {} for label in tmdb_budgets_worldwide_pivot_df.columns: worldwide_roi_dict[str(label)] = worldwide_roi_by_budget[label] worldwide_roi_dict = dict(zip(bins_labels, list(worldwide_roi_dict.values()))) return worldwide_roi_dict def plot_ROI(domestic_dict, worldwide_dict): ''' Function to plot domestic and worldwide ROI by budget bins. Input: Domestic and worldwide plotting dictionaries from domestic_ROI and worldwide_ROI functions. Output: Plot of domestic and worldwide ROI by budget bins ''' fig = plt.figure(figsize=(20, 10)) X = np.arange(len(domestic_dict)) ax = plt.subplot(111) ax.set_facecolor('lightgray') ax.bar(X, domestic_dict.values(), width=0.3, color='darkblue') ax.bar(X+0.3, worldwide_dict.values(), width=0.3, color='blue', alpha = .7) ax.legend(('Domestic','Worldwide'), fontsize = 20) plt.xticks(X, domestic_dict.keys(), fontsize = 12) plt.title("ROI by Budget", fontsize=40) plt.ylabel('ROI', fontsize = 25) plt.xlabel('Budget', fontsize = 25) plt.tight_layout() plt.show() return None
2f081d12548518050ed4e70fd4fd3d57f57a2159
aherzfeld/udacity_cs101
/Unit5/problem_set_optional/shift_n_letters.py
701
3.796875
4
# Write a procedure, shift_n_letters which takes as its input a lowercase # letter, a-z, and an integer n, and returns the letter n steps in the # alphabet after it. Note that 'a' follows 'z', and that n can be positive, #negative or zero. def make_alphabet(): p = [] i = 0 while len(p) < 26: p.append(chr(ord('a') + i)) i = i + 1 return p def shift_n_letters(letter, n): p = make_alphabet() from_start = 0 if p.index(letter) + n <= 25: return p[p.index(letter) + n] from_start = n - (26 - p.index(letter)) return p[from_start] print shift_n_letters('s', 1) #>>> t print shift_n_letters('s', 2) #>>> u print shift_n_letters('s', 10) #>>> c print shift_n_letters('s', -10) #>>> i
18e393e221345ad06e17c5f9f8a0c07b120a683f
AndriiLatysh/ml_course
/python_4/point.py
946
3.828125
4
import math class Point: def __init__(self, x, y): self.x_coordinate = x self.y_coordinate = y def calculate_distance_to_origin(self): distance = math.sqrt(self.x_coordinate ** 2 + self.y_coordinate ** 2) return distance def move(self, x_shift, y_shift): self.x_coordinate += x_shift self.y_coordinate += y_shift def __repr__(self): point_str = f"({self.x_coordinate}, {self.y_coordinate})" return point_str class ColoredPoint(Point): def __init__(self, x, y, color): super().__init__(x, y) self.__color = color def recolor(self, color): self.__color = color def __repr__(self): colored_point_str = super().__repr__() + f" {self.__color}" return colored_point_str cp = ColoredPoint(1, 1, "red") print(cp) cp.move(2, 3) print(cp) print(cp.calculate_distance_to_origin()) print(cp._ColoredPoint__color)
c7183bf73a4bec8aeaa1e04463e0649ea0699982
Halverson-Jason/cs241
/week2/check02b.py
609
3.71875
4
def prompt_file(): return input("Enter file: ") def open_file(file_name): return open(file_name, "r") def get_lines(user_file): line_counter = 0 word_counter = 0 for line in user_file: word_counter += len(line.split()) line_counter += 1 word_line_count = [line_counter,word_counter] return word_line_count def main(): user_file = open_file(prompt_file()) word_line_count = get_lines(user_file) print("The file contains %d lines and %d words." % (word_line_count[0], word_line_count[1])) user_file.close() if __name__ == "__main__": main()
0c823eee30a2b5d26e28ac04b61ff205c1eedb35
hashtagallison/Python
/Practice_STP/Examples_Notes/Ch6.2_STP.py
4,747
4.40625
4
# https://www.theselftaughtprogrammer.io # Cory Althoff - The Self-taught Programmer # Chapter 6.2 pg 92 - More String Manipulation # hashtagallison - Practice 2019-04-08 #------------------------------------------- #------------------------------------------- # EXAMPLE: pg 92-93 #------------------------------------------- # TIP---> You can use the "split" method to spearate one string into two or more strings. # > Specify the parameter that you would like to use for splitting (such as ".") print("Hello. Yes!".split(".")) #------------------------------------------- # EXAMPLE: pg 93-94 #------------------------------------------- # TIP---> The "join" method lets you add new characters between every character in a string. # > You can turn a list of strings into a single string by calling the "join" method on an empty string and passing in the list as a parameter first_three = "abc" result = "+".join(first_three) print(result) words= ["The", "fox", "jumped", "over", "the", "fence", "." ] one = "".join(words) print(one) #using join to separate each word with a space (note the space printed before the period on the output) one = " ".join(words) print(one) #------------------------------------------- # EXAMPLE: pg 94 #------------------------------------------- # TIP---> You can use the "strip" method to remove leading and trailing whitespace from a string. s = " The " s = s.strip() print(s) #------------------------------------------- # EXAMPLE: pg 94-95 #------------------------------------------- # TIP---> The "replace" method replaces every occurrence of a string with another string. # > First parameter is the string to replace, the second parameter is what it will be replaced with. equ = "All animals are equal." equ = equ.replace("a", "@") print(equ) #------------------------------------------- # EXAMPLE: pg 95 #------------------------------------------- # TIP---> You can get the index of the first occurance of a character in a string with the "index" method. # > Pass the character that you are looking for as a parameter. # > Python raises an exception if the index method does not match. (ValueError) print("animals".index("m")) # Using exception handling if unsure there will be a match try: print("animals".index("z")) except: print("Not found.") #------------------------------------------- # EXAMPLE: pg 96 #------------------------------------------- # TIP---> The "in" and "not in" keywords check if a string is in another string # > Returns either True or False print("Cat" in "Cat in the hat.") print("Bat" in "Cat in the hat.") print("Potter" not in "Harry") #------------------------------------------- # EXAMPLE: pg 96-97 #------------------------------------------- # TIP---> If you use quotes inside of a string, you will get a syntax error (InvalidSyntax) # > You may fix this error by prefacing the quotes with backslashes \ # > Escaping a string means putting a symbol in front of a character that normally has a special # meaning in Python. It lets Python know that, in the instance, the quote is meant to represent a character. print("She said \"Surely.\"") print('She said \"Surely.\"') # You do NOT need to escape single quotes within double quotes. print("She said 'Surely.'") # You can put double quotes inside of single quotes (instead of escaping with a \) print('She said "Surely."') #------------------------------------------- # EXAMPLE: pg 98 #------------------------------------------- # TIP---> Putting "\n" inside of a string represents a new line. print("line1\nline2\nline3") #------------------------------------------- # EXAMPLE: pg 98-100 #------------------------------------------- # TIP---> Slicing is a way to return a new iterable from a subset pf the items in another iterable. # > You want to include the index to STOP slicing at, which means +1 of the last index you want returned. # Slicing a list: fict = ["Tolstoy", "Camus", "Orwell", "Huxley", "Austin"] print(fict[0:3]) # Slicing a string: ivan = "In place of death there was light." print(ivan[0:17]) print(ivan[17:33]) # TIP---> If your start index was zero, you can leave the start index empty # > If your end index is the index of the iterable, you can leave the end index empty # > Leaving both the start and end index empty, returns the original iterable print(ivan[:17]) print(ivan[17:]) print(ivan[:])
0057cb293f457c6234f188c18a34e4a25ea6f9b7
guruv22/Test_Scripts
/test.py
3,055
3.796875
4
# a = "abc" # b = "abc" # print(a) # print(b) # print(id(a)) # print(id(b)) # print("----------------") # # print(id(a+"x")) # # print(id(b+"x")) # # print(a+"x") # print(b+"x") # print(id(a+"x")) # print(id(b+"x")) # print(id(a+"x")) # print(id(b+"x")) # a = "abc" # b = "abc" # # # print(a+"x") # # print(b+"x") # # print(a+"x" == b+"x") # # print(a+"x" is b+"x") # print(a) # print(b) # print(id(a)) # print(id(b)) # print(a == b) # print(a is b) # print("----------------") # # print(id(a+"x")) # # print(id(b+"x")) # # print(a+"x") # print(b+"x") # print(id(a+"x")) # print(id(b+"x")) # i = 4 # d = 4.0 # s = 'HackerRank ' # # Declare second integer, double, and String variables. # j = input("Enter integer: ") # e = input("Enter float: ") # t = input("Enter string: ") # print(i+int(j)) # print(round((d+float(e)),2)) # print(s+t) # Read and save an integer, double, and String to your variables. # Print the sum of both integer variables on a new line. # Print the sum of the double variables on a new line. # Concatenate and print the String variables on a new line # The 's' variable above should be printed first. # #!/bin/python3 # # import math # import os # import random # import re # import sys # # # if __name__ == '__main__': # n = int(input()) # for i in range(1,11): # print("{} x {} = {}".format(n, i, n*i)) # import string # a = list(string.ascii_lowercase) # b = "how are you" # # # print(set(list(a))) # out_list = set(a) - set(list(b)) # # print(''.join(out_list)) # # x = set(list(b)) # y = list(b) # # # x[0] = 'a' # y[0] = 'a' # print (y[0]) # str = "abcdef" # print(str[::-1]) # # # a = ['a', 'b', 'c'] # print(''.join(a)) # str=input("Enter the string:\n") # print("{} {}".format(str[::2],str[1::2])) # class Demo: # def __new__(cls): # print("Demo's __new__() invoked") # return super(Demo,cls).__new__(cls) # # def __init__(self): # print("Demo's __init__() invoked") # # class Derived_Demo(Demo): # def __new__(cls): # print("Derived_Demo's __new__() invoked") # return super(Derived_Demo,cls).__new__(cls) # # def __init__(self): # print("Derived_Demo's __init__() invoked") # # obj1 = Derived_Demo() # obj2 = Demo() # def getMoneySpent(keyboards, drives, b): # # # # Write your code here. # # # max_amt = 0 # # for kb in keyboards: # for dr in drives: # tot = kb + dr # if tot > max_amt and tot <= b: # max_amt = tot # # if max_amt == 0: # return -1 # else: # return max_amt # # # if __name__ == '__main__': # b = 10 # # n = 2 # # m = 3 # # keyboards = [3, 1] # # drives = [5, 2, 8] # # # # # The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items # # # # moneySpent = getMoneySpent(keyboards, drives, b) # print(moneySpent) #!/bin/python3 import sys # n = int(input().strip()) # a = list(map(int, input().strip().split(' ')))
5bcf1fe446ef2c12036549395deff411683e5c9b
QingfengTang/Algorithms-and-Data-Structures
/剑指offer/sort.py
6,435
3.984375
4
''' 将一组数按照大小排序 !!!note:当列表作为参数在函数间传递时,对列表的修改要注意深浅拷贝 例如 对于列表array 在函数中进行array[i]=value 这种修改时为深拷贝,会对原来的array进行修改 而对于array=[value]时为浅拷贝,这是array的变化不会影响原来的array ''' class Sort(): # array一维列表 def BubbleSort(self, array): ''' 冒泡排序 时间复杂度O(n^2) 1.将a[j]和a[j+1]比较大的放后面,依次遍历一遍,大的数就在尾端冒泡 2.由于每次遍历大的数已经放好,所以对末尾已经排号的就不再排序 ''' for i in range(len(array)): # 每排一次需要一次循环 for j in range(len(array)-i-1): # 此处-i是因为对已经排好的就不再动了 # -1是由于采用了array[j+1]防止越界 if array[j] > array[j+1]: temp = array[j] array[j] = array[j+1] array[j+1] = temp return array def CountingSort(self, array): ''' 计数排序 桶排序的最简单形式 O(n+k) k为桶的个数或者最大值 1.根据array的值域设置桶的个数并初始化,要求每一个桶内只有一个元素 2.按照桶统计array中的元素出现的次数 3.按照桶的顺序和元素出现的次数输出 ''' result = [] # 根据array的值域来设定桶数 buckets = [0 for i in range(10)] # 装桶,统计频率 ''' # 有更简单的写法 for i in range(len(array)): for j in range(len(buckets)): if array[i] == j: buckets[j] += 1 ''' for i in array: buckets[i] += 1 # 按照桶的顺序输出元素 for i in range(len(buckets)): while buckets[i] > 0: result.append(i) buckets[i] -= 1 return result def BucketSort(self, array): ''' 桶排序 ''' return array def QuickSortMain(self, array): ''' 快排序 分而治之的递归排序 1.在array中确定一个基准base,一般为首元素 2.先从右往左移动即array[j]>base,否则 将小于base的array[j]赋给array[i],此时array[i]原来的值并没有消失而是在base中 3.从左往右移动即array[i]<base,否则将大于base的array[i]给array[j],此时array[j]在1中已经移动了,所以不存在消失问题 4.当左右两个指针相遇时将base放在此时的位置,这时base的左边小于base右边大于base 5.同理递归左边序列和右边序列 ''' low = 0 high = len(array) - 1 result = self.QuickSortFunc(array, low, high) return result def QuickSortFunc(self, array, low, high): i = low j = high if i < j: # 定义基准值 temp = array[i] # 当左右指针相遇时退出 while i != j: # 由于基准值选的是array[i]所以先从右往左 # 从右往左,将大于等于base的放在右 while j>i and array[j]>=temp: j -= 1 array[i] = array[j] # 从左往右 while j>i and array[i]<temp: i += 1 array[j] = array[i] # 将基准值放在左右指针相遇处 array[i] = temp self.QuickSortFunc(array, low, i-1) self.QuickSortFunc(array, i+1, high) return array def HeapSort(self, array): ''' 堆排序 ''' if not array: return None # 构建最大堆 for i in range((len(array)-1-1)//2, -1, -1): self.CreateMaxHeap(array, i, len(array)) # for i in range((len(array)-1), 0, -1): temp = array[0] array[0] = array[i] array[i] = temp self.CreateMaxHeap(array, 0, i) return array def CreateMaxHeap(self, array, index, length): ''' 创建最大堆 ''' left_index = 2*index+1 right_index = 2*index+2 if left_index < length: left_val = array[left_index] if right_index >= length: max_index = left_index max_val = left_val else: right_val = array[right_index] if left_val > right_val: max_index = left_index max_val = left_val else: max_index = right_index max_val = right_val if array[index] < max_val: array[index], array[max_index] = array[max_index], array[index] self.CreateMaxHeap(array, max_index, length) return array def MergeSort(self, array): ''' 并归排序 NlogN 1.采用分而治之的策略,将array不断的二分一直到一个元素 2.合并,依次比较left和right的大小,并移动值小的指针 ''' if len(array) <= 1: return array middle = len(array) // 2 left = self.MergeSort(array[:middle]) right = self.MergeSort(array[middle:]) return self.MergeFun(left, right) def MergeFun(self, left, right): ''' 并归排序的 合并部分 ''' temp = [] lpoint = 0 rpoint = 0 while lpoint < len(left) and rpoint < len(right): if left[lpoint] < right[rpoint]: temp.append(left[lpoint]) lpoint += 1 else: temp.append(right[rpoint]) rpoint += 1 if lpoint == len(left): temp += right[rpoint:] else: temp += left[lpoint:] return temp if __name__ == '__main__': array = [2,5,3,8,5,7,4,9] solution = Sort() result = solution.HeapSort(array) print(result)
6aef77ed808d0014c4ebdd52aacdb2fda8595b40
eduardonery1/Coding-Interview
/4. Trees and Graphs/4.4-Check_Balanced.py
1,437
3.8125
4
from graph import Node def findHeight(node, height=0) -> int: if node: height += 1 left_height = findHeight(node.left, height=height) right_height = findHeight(node.right, height=height) return max(left_height, right_height) return height def isBalanced(node, balanced_left=True, balanced_right=True) -> bool: # 1 # 2 3 # 4 6 5 # 7 # left_height = findHeight(node.left) right_height = findHeight(node.right) if not abs(left_height - right_height) > 1: if node.left: balanced_left = isBalanced(node.left) if node.right: balanced_right = isBalanced(node.right) return balanced_left and balanced_right return False if __name__=="__main__": test = Node(1, Node(2, Node(4), Node(6, right=Node(7))), Node(3, right=Node(5, Node(8)))) test2 = Node(1, left=Node(2, left=Node(4), right=Node(6, right=Node(7))), right=Node(3, right=Node(5))) assert(isBalanced(test)==False) assert(isBalanced(test2)==True)
7407046760510cc60cd8d0683abaf4881bc04957
CarlosDNieto/python-snipps
/Data Science From Scratch/Chapter 1/01_FriendSuggester.py
6,276
3.59375
4
from __future__ import division # integer division is lame from collections import Counter from collections import defaultdict # * Book: Data Science From Scratch by Joel Grus # * This intro in from the page 22 (pdf page) # * Title: Data Scientist You May Know Suggester # Teorical Objective: Finding Key Connectors # Practical Objective: Make a "people you make know" suggester based on the mutual friends # and mutual interests. # * What have I learned from this py file: # - Make a "Data Scientist You May Know" suggester for a Data Science Social Network. # - Make a list of "friends" for each user from a conection list of tuples. # - Managed to show friends of a friend list from friendship list of tuples. # - Transform a list of tuples (user_id, interest) to a dictionary {interest:user_ids} # - Transform a list of tuples (user_id, interest) to a dictionary {user_id:interests} # List of users with id and name users = [ { "id": 0, "name": "Hero" }, { "id": 1, "name": "Dunn" }, { "id": 2, "name": "Sue" }, { "id": 3, "name": "Chi" }, { "id": 4, "name": "Thor" }, { "id": 5, "name": "Clive" }, { "id": 6, "name": "Hicks" }, { "id": 7, "name": "Devin" }, { "id": 8, "name": "Kate" }, { "id": 9, "name": "Klein" } ] # List of friendships, paired id's friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4), (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)] # Add a list of friends for each user for user in users: user["friends"] = [] # Populate the friends lists with friendships data for i, j in friendships: users[i]["friends"].append(users[j]) # add i as a friend of j users[j]["friends"].append(users[i]) # add j as a friend of i def number_of_friends(user): """How many friends does the _user_ have?""" return len(user["friends"]) # length of the friends_id list total_conections = sum(number_of_friends(user) for user in users) # 24 num_users = len(users) # length of the users list avg_connections = total_conections / num_users # 2.4 # create a list (user_id, number_of_friends) num_friends_by_id = [(user["id"], number_of_friends(user)) for user in users] # each pair is (user_id, num_friends) # [(1, 3), (2, 3), (3, 3), (5, 3), (8, 3), # (0, 2), (4, 2), (6, 2), (7, 2), (9, 1)] def friends_of_friend_ids_bad(user): # foaf is short for "friend of a friend" return [foaf["id"] for friend in user["friends"] # for each of user friends for foaf in friend["friends"]] # for each of _their_ friends # When we call this on users[0] (Hero), it produces: # [0, 2, 3, 0, 1, 3] print("friends_of_friend_ids_bad(users[0]) output:") print(friends_of_friend_ids_bad(users[0])) # # it includes 2 times the user_id 0 and 2 times the user_id 3 # print [friend["id"] for friend in users[0]["friends"]] # [1, 2] # print [friend["id"] for friend in users[1]["friends"]] # [0, 2, 3] # print [friend["id"] for friend in users[2]["friends"]] # [0, 1, 3] def not_the_same(user, other_user): """Two users are not the same if they have different ids""" return user["id"] != other_user["id"] def not_friends(user, other_user): """other_user is not a friend if he's not in user["friends"]; that is, if he's not_the_same as all the people in user["friends"]""" return all(not_the_same(friend, other_user) for friend in user["friends"]) def friends_of_friend_ids(user): return Counter(foaf["id"] for friend in user["friends"] for foaf in friend["friends"] if not_the_same(user, foaf) and not_friends(user, foaf)) print("\nfriends_of_friend_ids(users[0]) output:") print(friends_of_friend_ids(users[0])) # list of interests (user_id, interest): interests = [ (0, "Hadoop"), (0, "Big Data"), (0, "HBase"), (0, "Java"), (0, "Spark"), (0, "Storm"), (0, "Cassandra"), (1, "NoSQL"), (1, "MongoDB"), (1, "Cassandra"), (1, "HBase"), (1, "Postgres"), (2, "Python"), (2, "scikit-learn"), (2, "scipy"), (2, "numpy"), (2, "statsmodels"), (2, "pandas"), (3, "R"), (3, "Python"), (3, "statistics"), (3, "regression"), (3, "probability"), (4, "machine learning"), (4, "regression"), (4, "decision trees"), (4, "libsvm"), (5, "Python"), (5, "R"), (5, "Java"), (5, "C++"), (5, "Haskell"), (5, "programming languages"), (6, "statistics"), (6, "probability"), (6, "mathematics"), (6, "theory"), (7, "machine learning"), (7, "scikit-learn"), (7, "Mahout"), (7, "neural networks"), (8, "neural networks"), (8, "deep learning"), (8, "Big Data"), (8, "artificial intelligence"), (9, "Hadoop"), (9, "Java"), (9, "MapReduce"), (9, "Big Data") ] # Find users with a certain interest def data_scientist_who_like(target_interest): return [user_id for user_id, user_interest in interests if user_interest == target_interest] # this works but it has to examine the whole list of interests for every search. # So, we'll better off building an index from interests to users # dictionary of user_ids by interest # keys are interests, values are lists of user_ids with that interest user_ids_by_interest = defaultdict(list) for user_id, interest in interests: user_ids_by_interest[interest].append(user_id) # dictionare of interests by user_id interests_by_user_id = defaultdict(list) for user_id, interest in interests: interests_by_user_id[user_id].append(interest) # Now is easy to find interests in common between users # - Iterate over the users interests. # - For each interest iterate over the over users with that interest. # - Keep count of how many times we see each other user. def most_common_interests_with(user): return Counter(interested_user_id for interest in interests_by_user_id[user["id"]] for interested_user_id in user_ids_by_interest[interest] if interested_user_id != user["id"]) print(most_common_interests_with(users[0]))
c094cf8704df88dc7d7b5770fc88424a02a41c39
I-will-miss-you/CodePython
/Curso em Video/Duvidas/d013.py
416
3.6875
4
#Importando biblioteca: from tkinter import * #Definindo função: def onClick(): print('Você clicou no botão OK!') #Código da gui: janela = Tk() #Cria botão com texto = "OK" e comando associado: aoClicarOk() bt_ok = Button(janela, text='OK', command=onClick) #Usa-se pack() como gerenciador de layout bt_ok.pack(side=TOP) janela.title(' Janela ') janela.geometry('250x50+300+300') janela.mainloop()
93af342cace874760c40e024616f66967d7a86fe
adannogueira/Curso-Python
/Exercícios/ex096.py
354
4.0625
4
# Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno # retangular (largura e comprimento) e mostre a área do terreno. def área(l, c): print(f'Área: {l * c}m²') if __name__ == '__main__': print('Para cálculo da área do terreno, informe:') área(int(input('Largura: ')), int(input('Comprimento: ')))
76955c53a7338aed39142e1ab160eafc47a7b171
jupmarsat/codewars_kata_python3
/What is between.py
1,205
4.21875
4
#!/usr/bin/python3 #CODEWARS Kata exercise: What is between? #https://www.codewars.com/kata/55ecd718f46fba02e5000029/train/python #Tests Passed: 54 #Tests Failed: 0 #Instructions: Complete the function that takes two integers (a, b, where a < b) #and return an array of all integers between the input parameters, including them.## def between(a,b): empty = [] x = range(a,b+1) for y in x: empty.append(y) return(empty) #test print(between(3,7)) #Sample Python3 Codewars solution, single line for loop #have to return list, otherwise you will get "range(a,b)" def between(a,b): return list(x for x in range(a, b + 1)) print(between(3, 7)) #from https://blog.teamtreehouse.com/python-single-line-loops #learning to do single line loops def long_words(lst): words = [] for word in lst: if len(word) > 5: words.append(word) return words jsfk = ["sdfsdf", "sdfsdfsdf", "sdf", "Ssdfsdffsd",'ff'] print(long_words(jsfk)) ##each word will be returned from [for] this list only if the length of this word is > 5 def long_words(lst): return [word for word in lst if len(word) > 5] print(long_words(jsfk))
86b2a025483f0c697bc1facb1da689d27a8a06ba
LucasAraujoBR/Python-Language
/pythonProject/Python Basic/aula9.py
515
4.3125
4
""" Aula 9 - Entrada de dados (input) """ name = input('Whats your name? ') #input sempre retorna string! print(f'your name is {name}, and your type is ' f'{type(name)}.') age = input("Whats your age? ") print(f"{name} have {age} years old.") yearsOfBirth = 2021 - int(age) print(f'{name} he was born in {yearsOfBirth}') """ Mini calculadora """ num_1 = input("Whats a fisrt number? ") num_2 = input("Whats a second number? ") print(f'the sum of {num_1} and {num_2} results in: ',int(num_1)+ int(num_2))
b3b678f5c4fd0df65368905728e95f5ef9b75530
atozzini/CursoPythonPentest
/PycharmProjects/ExerciciosGrupo/exercicio084.py
517
4.03125
4
pizza = ["mussarela", "tomate", "calabresa", "oregano", "farinha", "molho"] if "mussarela" in pizza: print("mussarela adicionada") if "tomate" in pizza: print("tomate adicionado") if "calabresa" in pizza: print("calabresa adicionada") if "oregano" in pizza: print("oregano adicionado") if "farinha" in pizza: print("farinha adicionada") if "molho" in pizza: print("molho adicionado") # os comandos acima verificam se o ingrediente esta na lista pizza, se sim ele printa # o texto logo abaixo
ff262b7961eccb0a355b3a0a5c19218500e56c76
zhouli01/python_test01
/sum_a_b.py
203
4.15625
4
#!/usr/bin/python3 # coding:utf-8 a = int(input('请输入a的值:')) b = int(input('请输入b的值:')) ''' a = a^b b = a^b a = b^a ''' a,b=b,a print("交换后的值:" ,a , b )
c5c48cfe17ae7da95d9d391fb50e7df89230650a
MateusCohuzer/Exercicios-do-Curso-em-Video
/Curso_em_Video_Exercicios/ex009.py
490
3.75
4
n = int(input('Qual número você quer ver a tabuada? ')) print('=' * 10) print('{} X {} = {}'.format(n, 1, n*1)) print('{} X {} = {}'.format(n, 1, n*2)) print('{} X {} = {}'.format(n, 1, n*3)) print('{} X {} = {}'.format(n, 1, n*4)) print('{} X {} = {}'.format(n, 1, n*5)) print('{} X {} = {}'.format(n, 1, n*6)) print('{} X {} = {}'.format(n, 1, n*7)) print('{} X {} = {}'.format(n, 1, n*8)) print('{} X {} = {}'.format(n, 1, n*9)) print('{} X {} = {}'.format(n, 1, n*10)) print('='* 10)
cfffdcab48b26afdb68cbfd0d757583caa2ad526
KarashDariga/week1
/45.py
94
3.578125
4
for x in range(2, 6): # [2...6) print(x) # for x in range(a, b+1) [a...b] # print(x)
ccf4ccea0b71fc80a6bdfd345bba0c40ea1e5f1f
freelikeff/my_leetcode_answer
/leet/309answer.py
826
3.65625
4
#!D:\my_venv\Scripts python # -*- coding: utf-8 -*- # @Time : 2019/10/3 8:55 # @Author : frelikeff # @Site : # @File : 309answer.py # @Software: PyCharm from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: # 因为交易次数限制为正无穷,所以k的情况等于k-1 thedaybeforeyester = [0, -prices[0]] # 用第0天初始化 yesterday = [max(0, prices[1] - prices[0]), max(-prices[0], -prices[1])] for i in range(2, len(prices)): today = [max(yesterday[0], yesterday[1] + prices[i]), max(yesterday[1], thedaybeforeyester[0] - prices[i])] thedaybeforeyester, yesterday = yesterday, today return yesterday[0] if __name__ == '__main__': s = Solution() inpt = [1, 2] print(s.maxProfit(inpt))
b0a6884ef31e7bd6dcdf7d312d44dff60247676c
CuiFengming/Call_center_data_Analysis
/daily_call_count_forecast/preprocessing.py
3,295
3.625
4
import pandas from pandas import Series, DataFrame, read_csv from sklearn.preprocessing import LabelEncoder def preprocessing(target_column): # Load dataset(csv) & 지역은 서울에 한정 dataset = pandas.read_csv('./dataset_final.csv') dataset = dataset[:][(dataset['Area_code'] == '002-')] # Classify y values to 'Pizza', 'Burger', 'Chicken', 'Total' pizza_y = [] burger_y = [] chicken_y = [] total_y = [] n_x_column = 28 y_col_list = list(dataset.columns)[n_x_column : ] for i in range(len(dataset)): tem_y_value = 0 for y in y_col_list: tem_y_value += list(dataset[y])[i] # y value 브랜드에 상관없이, 통합해서 보기 위함 total_y.append(tem_y_value) pizza_y.append(list(dataset['DOMINOPIZZA'])[i] + list(dataset['MRPIZZA'])[i] + list(dataset['PIZZAHUT'])[i] + list(dataset['PIZZAMARU'])[i] + list(dataset['KFC'])[i]) burger_y.append(list(dataset['BURGERKING'])[i]) chicken_y.append(list(dataset['BHC'])[i] + list(dataset['BBQ'])[i] + list(dataset['GOOBNE'])[i] + list(dataset['NENE'])[i] + list(dataset['CKNIA'])[i]) dataset= pandas.DataFrame({'Day' : list(dataset['Day']), 'DOW' : list(dataset['DOW']), 'is_holiday' : list(dataset['is_holiday']), 'Avg_tem' : list(dataset['Avg_tem']), 'High_tem' : list(dataset['High_tem']), 'Low_tem' : list(dataset['Low_tem']), 'is_fog' : list(dataset['is_fog']), 'is_rain' : list(dataset['is_rain']), 'is_yellow_dust' : list(dataset['is_yellow_dust']), 'is_snow' : list(dataset['is_snow']),'is_sport_KBO' : list(dataset['is_sport_KBO']), 'is_sport_NBA' : list(dataset['is_sport_NBA']), 'is_sport_PREMIER' : list(dataset['is_sport_PREMIER']), 'is_sport_K1' : list(dataset['is_sport_K1']), 'bigmac_local_price' : list(dataset['bigmac_local_price']), 'bigmac_dollar_price' : list(dataset['bigmac_dollar_price']), 'Product_price_index' : list(dataset['Proudct_price_index']), 'Consumer_price_index' : list(dataset['Consumer_price_index']), 'KTB_avg_1year' : list(dataset['KTB_avg_1year']), 'KTB_avg_3year' : list(dataset['KTB_avg_3year']), 'exchange_rate_dollar' : list(dataset['exchange_rate_dollar']), 'exchange_rate_pound' : list(dataset['exchange_rate_pound']), 'exchange_rate_euro' : list(dataset['exchange_rate_euro']), 'kospi' : list(dataset['kospi']), 'DOMINOPIZZA' : list(dataset['DOMINOPIZZA']), 'MRPIZZA' : list(dataset['MRPIZZA']), 'BHC' : list(dataset['BHC']), 'y_pizza' : pizza_y, 'y_burger' : burger_y, 'y_chicken' : chicken_y, 'y_total' : total_y}) # y값 : pizza에 한정지어서 우선 진행 dataset = dataset[['Day', 'DOW', 'is_holiday', 'Avg_tem', 'High_tem', 'Low_tem', 'is_fog', 'is_rain', 'is_yellow_dust', 'is_snow','is_sport_KBO', 'is_sport_NBA', 'is_sport_PREMIER', 'is_sport_K1', 'bigmac_local_price','bigmac_dollar_price','Product_price_index','Consumer_price_index','KTB_avg_1year','KTB_avg_3year', 'exchange_rate_dollar','exchange_rate_pound','exchange_rate_euro','kospi', target_column]] # String(DOW) to float col_name_list = list(dataset) values = dataset.values encoder = LabelEncoder() values[:,1] = encoder.fit_transform(values[:,1]) dataset = pandas.DataFrame(values) dataset.columns= col_name_list return(dataset)
691d2ee31ec543bcfbf88089f06140691a3235c7
EliMendozaEscudero/ThinkPython2ndEdition-Solutions
/Chapter 4/Exercise4-2.py
945
4.1875
4
import polygon import turtle def draw_a_petal(turt,arc): """It draws one petal of the flower turt:The turtle instance arc:The angle of the arcs. """ for i in range(2): polygon.arc(turt,100,arc) turt.lt(180-arc) def paint_flower(turt,petals): """It draws a flower of n petals turt:The turtle instance. petals:The number of petals. """ arc=((petals-2)*180)/(petals*2) print(arc) for i in range(petals): draw_a_petal(turt,arc) turt.rt(360.0/petals) def move(t, length): """It moves Turtle (t) forward (length) units without leaving a trail. Leaves the pen down. """ t.pu() t.fd(length) t.pd() if __name__=='__main__': pat = turtle.Turtle() pat.speed(0) pat.lt(180) move(pat,250) paint_flower(pat,7) pat.lt(180) move(pat,250) paint_flower(pat,11) move(pat,250) paint_flower(pat,22) turtle.mainloop()
3b553604f43a79c29da5770975c3cf69b5b2f453
yuanrunsen/Sword-to-offer
/src/sort_and_search/004.py
3,929
4.03125
4
# 归并排序 def merge_sort(array, start, end): if not array or start is None or end is None: return # 当递归到最后只剩1个或两个元素时 排序 if end-start <= 1: if array[start] > array[end]: array[end], array[start] = array[start], array[end] return start else: # 拆分递归 mid = (start+end)//2 start_left = merge_sort(array, start, mid) start_right = merge_sort(array, mid+1, end) # 记录原始起始坐标 src_start_left = start_left # 初始化一个数组 来临时存储每段排序后的值 # 可以优化成只初始化一次,长度与原数组相同, # 然后按照原数组下标进行存值 # 就不用每次递归都重复的初始化 temp = [0 for i in range(end-start+1)] temp_index = 0 while start_left <= mid and start_right <= end: if array[start_left] < array[start_right]: temp[temp_index] = array[start_left] start_left += 1 else: temp[temp_index] = array[start_right] start_right += 1 temp_index += 1 while start_left <= mid: temp[temp_index] = array[start_left] temp_index += 1 start_left += 1 while start_right <= end: temp[temp_index] = array[start_right] temp_index += 1 start_right += 1 # 把临时数组复制到原数组 for i in range(len(temp)): array[src_start_left+i] = temp[i] return src_start_left # 面试题51:数组中的逆序对 # 题目:在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组 # 成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。 # 方法:实际上就是归并排序的应用, 区别就是 最小段里统计一次逆序对数, 较小段的时候 需要保存的不再是 # 最左边的下标, 而是最右边的下标,用大值进行比较,再保存一次逆序对数,不断的递归, 这样段内不会重复 # 段外也不会漏。 def inverse_pairs(array, start, end): if not array or start is None or end is None: return # 优化临时数组只初始化一次 temp = [0 for i in range(end-start+1)] count = [0] _inverse_pairs(array, start, end, temp, count) return count[0] def _inverse_pairs(array, start, end, temp, count): # 当递归到最后只剩1个或两个元素时 排序, 统计逆序对数 if end-start <= 1: if array[start] > array[end]: array[end], array[start] = array[start], array[end] count[0] += 1 return end else: # 拆分递归 mid = (start+end)//2 end_left = _inverse_pairs(array, start, mid, temp, count) end_right = _inverse_pairs(array, mid+1, end, temp, count) # 记录原始结束坐标 src_end_right = end_right temp_index = end_right # 从大到小比较 按下标给temp赋值 while end_left >= start and end_right >= mid+1: if array[end_left] > array[end_right]: temp[temp_index] = array[end_left] end_left -= 1 count[0] += end_right-(mid+1)+1 else: temp[temp_index] = array[end_right] end_right -= 1 temp_index -= 1 while end_left >= start: temp[temp_index] = array[end_left] temp_index -= 1 end_left -= 1 while end_right >= mid+1: temp[temp_index] = array[end_right] temp_index -= 1 end_right -= 1 # 把临时数组复制到原数组 for i in range(temp_index+1, src_end_right+1): array[i] = temp[i] return src_end_right
690e8c100adc3b07cdc5177bab13277d2e467db2
balintdorner/exam-basics
/oddavg/odd_avg_test.py
638
3.546875
4
import unittest from odd_avg import * class TestOddAvg(unittest.TestCase): def test_odd_average_empt_list(self, integer = []): odd_avg = OddAvg() integer = [] self.assertEqual(odd_avg.odd_average(integer), 0) def test_odd_average_only_odd(self, integer = []): odd_avg = OddAvg() integer = [2, 6, 10] self.assertEqual(odd_avg.odd_average(integer), 6) def test_odd_average_integers(self, integer = []): odd_avg = OddAvg() integer = [1, 2, 3, 7, 12, 16] self.assertEqual(odd_avg.odd_average(integer), 10) if __name__ == '__main__': unittest.main()
9d021767cf4ab8be787c2a83273be893a45336a5
anti401/python1
/python1-lesson7/loto.py
2,733
3.625
4
# coding : utf-8 # детали задания в task.txt import random class Ticket: def __init__(self): # генерируем 15 случайных чисел numbers = set() while len(numbers) < 15: numbers.add(random.randint(1, 90)) # сохраняем в отсортированном виде как список и кортеж self.numbers_list = list(numbers) self.numbers_list.sort() self.numbers_orig = tuple(self.numbers_list) def print_ticket(self): """Вывод карточки таблицей с прочерками""" numbers = [str(num).zfill(2) if num in self.numbers_list else ' -' for num in self.numbers_orig] for i in range(3): print(' '.join(numbers[i::3])) def __gt__(self, other): """Перегруженный оператор > для зачёркивания номера""" if other in self.numbers_list: self.numbers_list.remove(other) return True else: return False user_ticket = Ticket() comp_ticket = Ticket() out_numbers = {0} new_number = 0 operation = '' while operation != 'q': # получаем новый уникальный номер while new_number in out_numbers: new_number = random.randint(1, 90) out_numbers.add(new_number) print('\nНовый бочонок: {}, осталось {} штук.'.format(new_number, 91 - len(out_numbers))) print('Ваша карточка:') user_ticket.print_ticket() print('Карточка компьютера:') comp_ticket.print_ticket() operation = input("Зачеркнуть цифру? (y/n/q) - ") # вычёркиваем номер на карточке компьютера comp_ticket > new_number # вычёркиваем номер на карточке игрока if operation == 'y' and not (user_ticket > new_number): print('Вы проиграли! (бочонка нет на вашей карточке)') break if operation == 'n' and user_ticket > new_number: print('Вы проиграли! (бочонок был на вашей карточке)') break if operation not in set('yn'): break # объявляем победителя, если чья-то карточка пуста if len(user_ticket.numbers_list) == 0 and len(comp_ticket.numbers_list) == 0: print('Ничья!') break if len(user_ticket.numbers_list) == 0: print('Победа ваша!') break if len(comp_ticket.numbers_list) == 0: print('Победа компьютера!') break
f1230981091c81e811888dde0220a9055dec1c03
niefy/LeetCodeExam
/explore_easy/dynamic_programming/MaxProfit.py
1,246
3.90625
4
""" https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/23/dynamic-programming/55/ 题目:买卖股票的最佳时机 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 注意你不能在买入股票前卖出股票。 示例 1: 输入: [7,1,5,3,6,4] 输出: 5 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 @author Niefy @date 2018-09-25 """ class MaxProfit: def maxProfit(self, prices):#依次遍历,记录之前的最小股价和最大收益,遍历每项检查是否可能超过最大收益 """ :type prices: List[int] :rtype: int """ length = len(prices) if length <= 1: return 0 minPrice = prices[0] maxProfit = 0 for x in prices: if x <= minPrice: minPrice = x else: maxProfit = max(maxProfit, x - minPrice) return maxProfit #测试代码 t=MaxProfit() print(t.maxProfit([7,1,5,3,6,4]))
70becfda5c39f6de278654fb9a5e5b8d35c40f3f
ikramulkayes/University_Practice
/practice69.py
240
3.6875
4
def convert_to_list(square_matrix_dict): lst = [] for k,v in square_matrix_dict.items(): lst.append(v) return lst square_matrix_dict = {1 : [1,2,3] , 2 : [4,5,6] , 3 : [7,8,9] } print(convert_to_list(square_matrix_dict))
6b7f19ab22fa5c4665550582e71698e2827e3bdf
anyone27/Automate-the-Boring-Stuff
/diceRoller.py
283
3.875
4
import random dice1 = 0 dice2 = 0 def roll(): dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) print("First dice rolled was a " + str(dice1)) print("Second dice rolled was a " + str(dice2)) print("Together these total " + str(dice1 + dice2)) roll()
1704a78c28588f21bea3175e9169b9a5b938deb4
rvkeerthana/myprogram2
/B10.py
126
3.734375
4
import math def countDigit(n): return math.floor(math.log(n,10)+1) n=34567890 print("number of digits: %d %(countDigit(n)))
4301a9f6a244a660ea5dda8004711adb8a0fe08b
ramonvaleriano/python-
/Cursos/Curso Em Video - Gustavo Guanabara/Curso em Vídeo - Curso Python/Exercícios/desafio_067.py
301
3.90625
4
# Program: desafio_067.py # Author: Ramon R. Valeriano # Description: # Updated: 29/09/2020 - 17:52 while True: number = int(input('Digite um número: ')) if number<0: break n = 0 print('='*30) for i in range(1, 11): n = i * number print(f'{i:2} * {number:2} = {n:3}')