blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7ea462ab48138a58f7ec2fcc9621c9ff0123b91a
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Trees/Binary Tree To DLL/binary_tree_to_dll.py
2,995
4.3125
4
""" Binary trees are a type of data tree data structure in which a node can only have 0,1 or 2 children only. Linked list is a type of linear data structure in which one object/node along with data, also contains the address of next object/node. Doubly linked list is a type of linked list in which a node points to both the element before it, and after it. A binary tree can be converted to a doubly linked list based on in order traversal, where left and right pointers point to prev and next element Eg :- 10 / \ 12 15 /\ / 25 30 36 can be converted to the doubly linked list 25 <-> 12 <-> 30 <-> 10 <-> 36 <-> 15 We have used an iterative approach here, keeping the track of head and tail of the doubly linked list, recursively solving left subtree, then redirecting the pointers to connect the last element and the current element, and finally recursively solving the right subtree """ class Node: """Class, to define node of the binary tree and dll, has data, left, and right as attributes""" def __init__(self, value): self.data = value self.left = None self.right = None def binary_tree_to_dll(node, head, tail): """This function converts a binary tree to a doubly linked list with recursive approach input: tree root or node, head and tail pointer of DLL returns : the head and tail of the the linked lists """ if node == None: return head, tail head, tail = binary_tree_to_dll( node.left, head, tail ) # converting the left subtree # updating the tail of the list to point towards current node if head == None: head = node else: tail.right = node node.left = tail tail = node # shifting the tail to the latest node head, tail = binary_tree_to_dll( node.right, head, tail ) # converting the right subtree return head, tail def print_list(head): """ iterates over the linked list prints the data elements input : head of the linked list prints the elements, does not return anything """ while head != None: print(head.data, end=" ") head = head.right # DRIVER CODE if __name__ == "__main__": root = Node(10) root.left = Node(12) root.right = Node(15) root.left.left = Node(25) root.left.right = Node(30) root.right.left = Node(36) head, tail = None, None head, tail = binary_tree_to_dll(root, head, tail) print("\nEquivaltent doubly linked list : ", end="") print_list(head) print("\n") # Extra examples for testing """ root = Node(-5) root.left = Node(10) root.right = Node(2) # ans : 10 -5 2 """ """ root = Node(3) root.left = Node(5) root.right = Node (7) root.left.left = Node(9) root.left.right = Node(11) root.right.left = Node(13) root.right.right = Node(15) root.left.left.left = Node(17) # ans : 17 9 5 11 3 13 7 15 """
true
28b801fcac4ab98370601886f27c42a5609535f0
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Backtracking/Sudoku Solver/sudoku.py
2,810
4.125
4
def print_grid(arr): for i in range(9): for j in range(9): print(arr[i][j], end=" "), print() # Function to Find the entry in the Grid that is still not used def find_empty_location(arr, l): for row in range(9): for col in range(9): if arr[row][col] == 0: l[0] = row l[1] = col return True return False # Returns True or false which indicates whether any assigned entry in the specified row matches the given number. def used_in_row(arr, row, num): for i in range(9): if arr[row][i] == num: return True return False # Returns True or false which indicates whether any assigned entry in the specified column matches the given number. def used_in_col(arr, col, num): for i in range(9): if arr[i][col] == num: return True return False # Returns true/false which indicates whether any assigned entry within the specified 3x3 box matches the given number def used_in_box(arr, row, col, num): for i in range(3): for j in range(3): if arr[i + row][j + col] == num: return True return False # Returns true or false which indicates whether it will be valid to assign num to the given row, column. def check_location_is_safe(arr, row, col, num): # Check if 'num' is not already placed in current row,current column and current 3x3 box return ( not used_in_row(arr, row, num) and not used_in_col(arr, col, num) and not used_in_box(arr, row - row % 3, col - col % 3, num) ) def solve_sudoku(arr): # 'l' is a list variable that keeps the record of row and col in find_empty_location Function l = [0, 0] # If there is no unassigned location,then we are done if not find_empty_location(arr, l): return True # Assigning list values to row and col that we got from the above Function row = l[0] col = l[1] for num in range(1, 10): if check_location_is_safe(arr, row, col, num): arr[row][col] = num if solve_sudoku(arr): return True # failure, unmake & try again arr[row][col] = 0 # this triggers backtracking return False # Driver main function to test above functions if __name__ == "__main__": grid = [] r = [] print( "Please enter the values present in the cell and value = 0 for the unassigned cell" ) for i in range(0, 9): k = input().split() m = [int(i) for i in k] grid.append(m) print("the sudoku is (unsolved one)") print(grid) print("this is the solved sudoku 👇") if solve_sudoku(grid): print_grid(grid) else: print("no solution exists ")
true
61cceb2f1eb17b506be7da7bd67c2f8404a6b4ce
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/leetcode/Subtree_of_another_Tree.py
1,208
4.15625
4
# Given two non-empty binary trees s and t, check whether tree t has exactly the same structure # and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all # of this node's descendants. The tree s could also be considered as a subtree of itself. # # Example 1: # Given tree s: # # 3 # / \ # 4 5 # / \ # 1 2 # Given tree t: # 4 # / \ # 1 2 # Return true, because t has the same structure and node values with a subtree of s. # Example 2: # Given tree s: # # 3 # / \ # 4 5 # / \ # 1 2 # / # 0 # Given tree t: # 4 # / \ # 1 2 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: def preOrder(node): if not node: return "null" return ( "-" + str(node.val) + "-" + preOrder(node.left) + "-" + preOrder(node.right) + "-" ) return preOrder(t) in preOrder(s)
true
de89caf4b942e789f946e8fb69bb933bdb883f9c
bgoonz/UsefulResourceRepo2.0
/_Job-Search/InterviewPractice-master/InterviewPractice-master/Python/capsLock.py
517
4.15625
4
# Complete the pressAForCapsLock function below. def pressAForCapsLock(message): letters = [] found = False for i in message: if i is "a" or i is "A": found = not found continue if found is True: letters.append(i.upper()) else: letters.append(i) result = "".join(letters) return result def main(): message = input("Enter a word or phrase: ") pressAForCapsLock(message) if __name__ == "__main__": main()
true
1d52e5100932c35be77dca0eedf505cf6bc6fdae
bgoonz/UsefulResourceRepo2.0
/_RESOURCES/my-gists/MAIN_GIST_FOLDER/76acedd4d2/76acedd4d2c1d58a424e1fe33a9aa011af6c62d3908fdeee020629a38a6f599f/08-LongestSemiAlternatingSubString.py
1,861
4.28125
4
# You are given a string s of length n containing only characters a and b. # A substring of s called a semi-alternating substring if it does not # contain three identical consecutive characters. # Return the length of the longest semi-alternating substring. # Example 1: Input: "baaabbabbb" | Output: 7 # Explanation: "aabbabb" # Example 2: Input: "abaaaa" | Output: 4 # Explanation: "abaa" # time complexity: O(n) # space complexity: O(1) def longest_semialternating_ss(s): length = len(s) if not s or length == 0: return 0 if length < 3: return length beginning = 0 end = 1 # first character comparison_char = s[0] # count the occurrence of the first char count_first_char = 1 max_length = 1 while end < length: end_char = s[end] if end_char == comparison_char: # add one to char count count_first_char += 1 # if char found at least two times if count_first_char == 2: x = end - beginning + 1 if x > max_length: max_length = x elif count_first_char > 2: # reset beginning pointer beginning = end - 1 else: comparison_char = end_char count_first_char = 1 if end - beginning + 1 > max_length: max_length = end - beginning + 1 end += 1 return max_length # alternate solution def longest_semi(s): max_length = 0 left = 0 for right in range(len(s)): if right - left + 1 >= 3 and s[right] == s[right - 1] == s[right - 2]: left = right - 1 max_length = max(max_length, right - left + 1) return max_length # 7 print(longest_semialternating_ss("baaabbabbb")) # 4 print(longest_semialternating_ss("abaaaa"))
true
215f93970c2e5982b41356f0381d785563c06962
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/my-gists/_CURRENT/edcbe51ff1/prime.py
261
4.21875
4
# if a number is prime or not def prime_num(): value = int(input('please type a number: ')) for num in range(2,value): if value % num == 0: return f'{value} is not a prime number' return f'{value} is a prime number' print(prime_num())
false
446eded13c97935e5b53597b35ec1118e0a4df91
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/my-gists/ARCHIVE/by-extension/python/merge_sort.py
1,728
4.21875
4
import timeit from random import randint def merge_sort(collection, length, counter): if len(collection) > 1: middle_position = len(collection) // 2 left = collection[:middle_position] right = collection[middle_position:] counter = merge_sort(left, length, counter) counter = merge_sort(right, length, counter) left_index, right_index, index = 0, 0, 0 while (left_index < len(left)) and (right_index < len(right)): if left[left_index] < right[right_index]: collection[index] = left[left_index] left_index += 1 else: collection[index] = right[right_index] right_index += 1 index += 1 while left_index < len(left): collection[index] = left[left_index] left_index += 1 index += 1 while right_index < len(right): collection[index] = right[right_index] right_index += 1 index += 1 counter += 1 print("Step %i -->" % counter, left, "<-->", right) if len(collection) == length: return collection, counter return counter def visualization(): counter = 0 length = 10 collection = [randint(0, length) for _ in range(length)] print("Initial list:", collection) print("Visualization of algorithm work.") collection, counter = merge_sort(collection, length, counter) print("Final list:", collection) print("Total numbers of passages:", counter) def main(): elapsed_time = timeit.timeit(visualization, number=1) print("Elapsed time: ", round(elapsed_time, 7), "sec.") if __name__ == "__main__": main()
true
891e45259cac6b0f22ac6d993dfb527569b2931b
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/PYTHON_PRAC/learn-python/src/control_flow/test_while.py
960
4.53125
5
"""WHILE statement @see: https://docs.python.org/3/tutorial/controlflow.html @see: https://docs.python.org/3/reference/compound_stmts.html#the-while-statement The while loop executes as long as the condition remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to). """ def test_while_statement(): """WHILE statement""" # Let's raise the number to certain power using while loop. number = 2 power = 5 result = 1 while power > 0: result *= number power -= 1 # 2^5 = 32 assert result == 32
true
d729ab8c086b66934ac65d667801a3e8a0b6dcd2
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/Lambda-Resource-Static-Assets/2-resources/_External-learning-resources/02-pyth/algorithms-master/algorithms/graph/prims_minimum_spanning.py
943
4.1875
4
""" This Prim's Algorithm Code is for finding weight of minimum spanning tree of a connected graph. For argument graph, it should be a dictionary type such as graph = { 'a': [ [3, 'b'], [8,'c'] ], 'b': [ [3, 'a'], [5, 'd'] ], 'c': [ [8, 'a'], [2, 'd'], [4, 'e'] ], 'd': [ [5, 'b'], [2, 'c'], [6, 'e'] ], 'e': [ [4, 'c'], [6, 'd'] ] } where 'a','b','c','d','e' are nodes (these can be 1,2,3,4,5 as well) """ import heapq # for priority queue # prim's algo. to find weight of minimum spanning tree def prims_minimum_spanning(graph_used): vis = [] s = [[0, 1]] prim = [] mincost = 0 while len(s) > 0: v = heapq.heappop(s) x = v[1] if x in vis: continue mincost += v[0] prim.append(x) vis.append(x) for j in graph_used[x]: i = j[-1] if i not in vis: heapq.heappush(s, j) return mincost
false
067b10f83c7b00d42b1d23184af4b6e3ce29a732
bgoonz/UsefulResourceRepo2.0
/GIT-USERS/ashishdotme/programming-problems/python/recursion-examples/06-product-of-list.py
598
4.34375
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ Created by Ashish Patel Copyright © 2017 ashish.me ashishsushilpatel@gmail.com """ """ Write the below function recursively # prod(L): number -> number # prod(L) is the product of numbers in list L # should return 1 if list is empty def prod(L): product, i = 1,0 while i < len(L): product = product * L[i] i = i + 1 return product """ def product_list(numbers): if numbers == []: return 1 elif len(numbers) == 1: return numbers[0] else: return numbers[0] * product_list(numbers[1:]) print(product_list([3, 2, 2]))
true
2f21c4f01170a9826b62ac8773cf607df88b1b88
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/Lambda-Resource-Static-Assets/2-resources/_External-learning-resources/02-pyth/algorithms-master/algorithms/matrix/crout_matrix_decomposition.py
1,298
4.125
4
""" Crout matrix decomposition is used to find two matrices that, when multiplied give our input matrix, so L * U = A. L stands for lower and L has non-zero elements only on diagonal and below. U stands for upper and U has non-zero elements only on diagonal and above. This can for example be used to solve systems of linear equations. The last if is used if to avoid dividing by zero. Example: We input the A matrix: [[1,2,3], [3,4,5], [6,7,8]] We get: L = [1.0, 0.0, 0.0] [3.0, -2.0, 0.0] [6.0, -5.0, 0.0] U = [1.0, 2.0, 3.0] [0.0, 1.0, 2.0] [0.0, 0.0, 1.0] We can check that L * U = A. I think the complexity should be O(n^3). """ def crout_matrix_decomposition(A): n = len(A) L = [[0.0] * n for i in range(n)] U = [[0.0] * n for i in range(n)] for j in range(n): U[j][j] = 1.0 for i in range(j, n): alpha = float(A[i][j]) for k in range(j): alpha -= L[i][k] * U[k][j] L[i][j] = float(alpha) for i in range(j + 1, n): tempU = float(A[j][i]) for k in range(j): tempU -= float(L[j][k] * U[k][i]) if int(L[j][j]) == 0: L[j][j] = float(0.1 ** 40) U[j][i] = float(tempU / L[j][j]) return (L, U)
true
e00af86d7504f79df399d6008c017ff23a9a36c0
bgoonz/UsefulResourceRepo2.0
/_MY_ORGS/Web-Dev-Collaborative/blog-research/Data-Structures/1-Python/stack/valid_parenthesis.py
556
4.125
4
""" Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. """ def is_valid(s: str) -> bool: stack = [] dic = {")": "(", "}": "{", "]": "["} for char in s: if char in dic.values(): stack.append(char) elif char in dic: if not stack or dic[char] != stack.pop(): return False return not stack
true
92c60c6141e1215c2d130b9d37bccf2a1e9b8ada
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Arrays/Divisor Sum/divisor_sum.py
633
4.40625
4
""" Aim: Calculate the sum of all the divisors of the entered number and display it. """ # function to find out all divisors and add them up def divisorSum(n): temp = [] for i in range(1, n + 1): # condition for finding factors if n % i == 0: temp.append(i) # adding all divisors return sum(temp) # getting the input n = int(input()) # printing the result print(divisorSum(n)) """ COMPLEXITY: Time Complexity -> O(N) Space Complexity -> O(1) Sample Input: 6 Sample Output: 12 Explaination: Divisors/Factors of 6 are --> 1,2,3 and 6. Adding them up --> 1+2+3+6 = 12. """
true
b75d2ff11f681b2d8ceb3896c14de6257e2ed051
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Trees/Expression Tree Evaluation/expression_tree_evaluation.py
2,499
4.625
5
# The expression tree is a binary tree in which each internal node corresponds to the operator like +,-,*,/,^ and # each leaf node corresponds to the operand so for example expression tree for 3 + ((5+9)*2) - 3,5,9,2 will be leaf nodes # and +,+,* will be internal and root nodes. It can be used to represent an expression. # It can be calculated to a single value, by performing the operator in the node on its children operands. # for example, a node (*) having two children nodes (4) and (5), can be evaluated as 4*5 = 20, so, # the subtree with (*) as root node, can be replaced with a single node (20) # Here we have followed a recursive approach to first evaluate the left and right child of an operator to a single value as in the above example, # and then evaluate that operation itself, finally returning the evaluated value calculated with the eval() function of python. class Node: """Class to define tree nodes, this has a value attribute to store the value, and left and right attributes to point to the left and right child respectively""" def __init__(self, value): self.value = value self.right = None self.left = None def expression_tree_evaluation(node): """A recursive function which evaluates the expression subtree passed to it and returns the evaluated value""" if node == None: # Node doesn't exist return 0 if node.left == None and node.right == None: # leaf node containing an operand return node.value # node is an operator left_child = expression_tree_evaluation(node.left) right_child = expression_tree_evaluation(node.right) return eval(str(left_child) + node.value + str(right_child)) # DRIVER CODE if __name__ == "__main__": # Expression in the example : (5*4)+(100-2) root = Node("+") root.left = Node("*") root.left.left = Node("5") root.left.right = Node("4") root.right = Node("-") root.right.left = Node("100") root.right.right = Node("20") print("\nExpression : (5*4)+(100-2)") print("\nEvaluation : ", expression_tree_evaluation(root), "\n") # Other examples which can be similarly created and tested :- # 3 + ((5+9)*2) = 31 """ root = Node('+') root.left = Node('3') root.right = Node('*') root.right.right = Node('2') root.right.left = Node('+') root.right.left.left = Node('5') root.right.left.right = Node('9') """ # 3 + (2 * 6) + 5 * (4 + 8) = 75
true
e3624ed59b0788f845692017723c3004bf6480fb
bgoonz/UsefulResourceRepo2.0
/_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/Overflow/_Learning/02_unordered_lists.py
1,506
4.40625
4
# In order to implement an unordered list, we will construct what is commonly known as a # Linked List. We need to be sure that we can maintain the relative positioning of the # items. However, there is no requirement that we maintain that positioning in contiguous # memory. # ----------------------------------------------------------------------------------------- # The basic building block for the linked list implementation is the node. Each node object # must hold at least two pieces of information. First, the node must contain the list item # itself. We will call this the data field of the node. In addition, each node must hold a # reference to the next node. # ----------------------------------------------------------------------------------------- class Node: def __init__(self, value): self._value = value self._next = None # Sometimes called 'grounding the node' @property def value(self): return self._value @value.setter def value(self, value): self._value = value @property def next(self): return self._next @next.setter def next(self, value): self._next = value class LinkedList: def __init__(self): self._head = None @property def head(self): return self._head @head.setter def head(self, value): self._head = value a = Node(45) a.value = 10 print(a.value) linked_list = LinkedList() linked_list.head = a print(linked_list.head.value)
true
3761502dbbdf79559a617c2c053a009aaa29e8d1
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/Overflow/Beginners-Python-Examples-master/useful_scripts/password_generator.py
1,410
4.15625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # Now-a-days, hashes of our passwords are # flowing on internet, but to avoid password # getting discovered by whoever got their hands # on them, a password should contain: # 1. Least 8 characters # 2. No words, instead randomly chosen characters # 3. Characters i'm refering to are, numbers, # uppercase/lowercase letters, punctuation's # This will protect password against, dictionary/brute force attacks import random, string, sys # List of characters, alphabets, numbers # to choose from data_set = list(string.ascii_letters) + list(string.digits) + list(string.punctuation) # generates a random password # very strong due to random ness # primary protection against dictionary attack on hash tables def generate_random_password(n): # For password to be strong it should # be at least 8 characters long if n < 8: return "Invalid Input,\nPassword should be at least 8 characters long!" # Chooses a random character from data_set # after password of given length is created # returns it to user password = "" for x in range(n): password += random.choice(data_set) return password # Test while True: usr = raw_input("Exit(press e), or Length: ").lower() if usr == "e": sys.exit() print("Generated password: " + generate_random_password(int(usr)) + "\n")
true
54b4af276b100f7461cc66399402005726a15b79
bgoonz/UsefulResourceRepo2.0
/_OVERFLOW/Resource-Store/01_Questions/_Python/pigLatin.py
601
4.15625
4
# Pig Latin Word Altering Game # function to convert word in pig latin form def alterWords(): wordToAlter = str(input("Word To Translate : ")) alteredWord = ( wordToAlter[1:] + wordToAlter[0:2] + "y" ) # translating word to pig latin if len(wordToAlter) < 46: print(alteredWord) else: print("Too Big . Biggest Word in English Contains 45 characters.") # main interaction code while True: startOrEnd = str(input("Start or End : ")) if startOrEnd == "Start": print(" ") print(alterWords()) continue else: quit()
true
bb1075bd0a0bcaf938e4f45eeb705dbdb751df42
bgoonz/UsefulResourceRepo2.0
/_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/learn-python/src/functions/test_lambda_expressions.py
1,342
4.59375
5
"""Lambda Expressions @see: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions Small anonymous functions can be created with the lambda keyword. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope. """ def test_lambda_expressions(): """Lambda Expressions""" # This function returns the sum of its two arguments: lambda a, b: a+b # Like nested function definitions, lambda functions can reference variables from the # containing scope. def make_increment_function(delta): """This example uses a lambda expression to return a function""" return lambda number: number + delta increment_function = make_increment_function(42) assert increment_function(0) == 42 assert increment_function(1) == 43 assert increment_function(2) == 44 # Another use of lambda is to pass a small function as an argument. pairs = [(1, "one"), (2, "two"), (3, "three"), (4, "four")] # Sort pairs by text key. pairs.sort(key=lambda pair: pair[1]) assert pairs == [(4, "four"), (1, "one"), (3, "three"), (2, "two")]
true
893f815791a090130faf05d42e959acd64ebcb25
bgoonz/UsefulResourceRepo2.0
/_MY_ORGS/Web-Dev-Collaborative/blog-research/Data-Structures/1-Python/map/word_pattern.py
1,175
4.25
4
""" Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. Example 1: Input: pattern = "abba", str = "dog cat cat dog" Output: true Example 2: Input:pattern = "abba", str = "dog cat cat fish" Output: false Example 3: Input: pattern = "aaaa", str = "dog cat cat dog" Output: false Example 4: Input: pattern = "abba", str = "dog dog dog dog" Output: false Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space. Reference: https://leetcode.com/problems/word-pattern/description/ """ def word_pattern(pattern, str): dict = {} set_value = set() list_str = str.split() if len(list_str) != len(pattern): return False for i in range(len(pattern)): if pattern[i] not in dict: if list_str[i] in set_value: return False dict[pattern[i]] = list_str[i] set_value.add(list_str[i]) else: if dict[pattern[i]] != list_str[i]: return False return True
true
ae27520913674390e809620c54463d13c4e88d63
bgoonz/UsefulResourceRepo2.0
/GIT-USERS/TOM-Lambda/CS35_IntroPython_GP/day3/intro/11_args.py
2,852
4.34375
4
# Experiment with positional arguments, arbitrary arguments, and keyword # arguments. # Write a function f1 that takes two integer positional arguments and returns # the sum. This is what you'd consider to be a regular, normal function. <<<<<<< HEAD def f1(a, b): return a + b ======= def f1(a, b): return a + b >>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea print(f1(1, 2)) # Write a function f2 that takes any number of integer arguments and prints the # sum. Google for "python arbitrary arguments" and look for "*args" <<<<<<< HEAD def f2(*args): sum = 0 for i in args: sum += i return sum print(f2(1)) # Should print 1 print(f2(1, 3)) # Should print 4 print(f2(1, 4, -12)) # Should print -7 ======= def f2(*args): sum = 0 for i in args: sum += i return sum print(f2(1)) # Should print 1 print(f2(1, 3)) # Should print 4 print(f2(1, 4, -12)) # Should print -7 >>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea print(f2(7, 9, 1, 3, 4, 9, 0)) # Should print 33 a = [7, 6, 5, 4] # What thing do you have to add to make this work? <<<<<<< HEAD print(f2(*a)) # Should print 22 ======= print(f2(*a)) # Should print 22 >>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea # Write a function f3 that accepts either one or two arguments. If one argument, # it returns that value plus 1. If two arguments, it returns the sum of the # arguments. Google "python default arguments" for a hint. <<<<<<< HEAD def f3(a, b=1): return a + b print(f3(1, 2)) # Should print 3 print(f3(8)) # Should print 9 ======= def f3(a, b=1): return a + b print(f3(1, 2)) # Should print 3 print(f3(8)) # Should print 9 >>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea # Write a function f4 that accepts an arbitrary number of keyword arguments and # prints out the keys and values like so: # # key: foo, value: bar # key: baz, value: 12 # # Google "python keyword arguments". <<<<<<< HEAD def f4(**kwargs): for k, v in kwargs.items(): print(f'key: {k}, value: {v}') # Alternate: # for k in kwargs: # print(f'key: {k}, value: {kwargs[k]}') ======= def f4(**kwargs): for k, v in kwargs.items(): print(f"key: {k}, value: {v}") # Alternate: # for k in kwargs: # print(f'key: {k}, value: {kwargs[k]}') >>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea # Should print # key: a, value: 12 # key: b, value: 30 f4(a=12, b=30) # Should print # key: city, value: Berkeley # key: population, value: 121240 # key: founded, value: "March 23, 1868" f4(city="Berkeley", population=121240, founded="March 23, 1868") <<<<<<< HEAD d = { "monster": "goblin", "hp": 3 } ======= d = {"monster": "goblin", "hp": 3} >>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea # What thing do you have to add to make this work? f4(**d)
true
de268aba734cf2c5da11ead13b3e83802fd39809
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/ciriculumn/week-17/python/my-intro-BG/2/Module14FileMissingErrorChallengeSolution.py
1,112
4.34375
4
# import libraries we will use import sys # Declare variables filename = "" fileContents = "" # Ask the user for the filename filename = input("PLease specify the name of the file to read ") # open the file, since you may get an error when you attempt to open the file # For example the file specified may not exist # put a try except statement around the command try: myFile = open(filename, "r") # I am using a boolean variable to determine if the file was found # That waythe code will only attempt to read the file if it was found succesfully fileFound = True # Handle the FileNotFoundError except FileNotFoundError: print("Could not locate file " + filename) fileFound = False # Other errors could occur, perhaps the file is coorupte, or I do not have permissions on the file except: error = sys.exc_info() print(error) fileFound = False # if the file was opened successfully read the contents and display the contents to the user if fileFound: # Get the file contents into a string fileContents = myFile.read() print(fileContents) # print the results
true
a05b3c15ce1004e4df54f1425f52c445d7ee97ef
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/Data-Structures/1-Python/strings/decode_string.py
1,207
4.15625
4
# Given an encoded string, return it's decoded string. # The encoding rule is: k[encoded_string], where the encoded_string # inside the square brackets is being repeated exactly k times. # Note that k is guaranteed to be a positive integer. # You may assume that the input string is always valid; No extra white spaces, # square brackets are well-formed, etc. # Furthermore, you may assume that the original data does not contain any # digits and that digits are only for those repeat numbers, k. # For example, there won't be input like 3a or 2[4]. # Examples: # s = "3[a]2[bc]", return "aaabcbc". # s = "3[a2[c]]", return "accaccacc". # s = "2[abc]3[cd]ef", return "abcabccdcdcdef". def decode_string(s): """ :type s: str :rtype: str """ stack = [] cur_num = 0 cur_string = "" for c in s: if c == "[": stack.append((cur_string, cur_num)) cur_string = "" cur_num = 0 elif c == "]": prev_string, num = stack.pop() cur_string = prev_string + num * cur_string elif c.isdigit(): cur_num = cur_num * 10 + int(c) else: cur_string += c return cur_string
true
c98e8b74c3374fb90d5ebe1b75c661147b793a10
bgoonz/UsefulResourceRepo2.0
/_RESOURCES/my-gists/__CONTAINER/36edf2915f/36edf2915f396/cloning a list.py
247
4.125
4
# Python program to copy or clone a list # Using the Slice Operator def Cloning(li1): li_copy = li1[:] return li_copy # Driver Code li1 = [4, 8, 2, 10, 15, 18] li2 = Cloning(li1) print("Original List:", li1) print("After Cloning:", li2)
true
7c74890541d696de85faa5a01f6838e86909e460
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_Another-One/ArithmeticAnalysis/NewtonRaphsonMethod.py
944
4.125
4
# Implementing Newton Raphson method in python # Author: Haseeb from sympy import diff from decimal import Decimal from math import sin, cos, exp def NewtonRaphson(func, a): """ Finds root from the point 'a' onwards by Newton-Raphson method """ while True: x = a c = Decimal(a) - (Decimal(eval(func)) / Decimal(eval(str(diff(func))))) x = c a = c # This number dictates the accuracy of the answer if abs(eval(func)) < 10 ** -15: return c # Let's Execute if __name__ == "__main__": # Find root of trignometric fucntion # Find value of pi print("sin(x) = 0", NewtonRaphson("sin(x)", 2)) # Find root of polynomial print("x**2 - 5*x +2 = 0", NewtonRaphson("x**2 - 5*x +2", 0.4)) # Find Square Root of 5 print("x**2 - 5 = 0", NewtonRaphson("x**2 - 5", 0.1)) # Exponential Roots print("exp(x) - 1 = 0", NewtonRaphson("exp(x) - 1", 0))
true
8d010e336acfd86fe9c1660ec0a8daa5e96c9d97
DYarizadeh/My-Beginner-Python-Codes-
/Factoral.py
241
4.15625
4
def Factoral(): n = int(input("Input a number to take the factoral of: ")) if n < 0: return None product = 1 for i in range (1,n+1): product *= i print(i,product) Factoral()
true
91d5e51709447c56ac07dffdddf2af84c08faa98
hitulshah/python-code-for-beginners
/list.py
1,485
4.3125
4
#fibonacci sequence # term = int(input('Enter terms:')) # n1 = 0 # n2 = 1 # if term <= 0 : # print('Please enter valid term') # elif term == 1 : # print(n1) # else : # for i in range(term) : # print(n1) # x = n1 + n2 # n1 = n2 # n2 = x #list and files examples # fname = input("Enter file name: ") # fh = open(fname) # count = 0 # for line in fh: # if not line.startswith('From'): # continue # if line.startswith('From:'): # continue # else: # line = line.split() # line = line[1] # print(line) # count += 1 # print("There were",count,"lines in the file with From as the first word") #fname = raw_input("Enter file name: ") # fh = open(fname) # lst = list() # list for the desired output # for line in fh: # to read every line of file romeo.txt # word= line.rstrip().split() # to eliminate the unwanted blanks and turn the line into a list of words # for element in word: # check every element in word # if element in lst: # if element is repeated # continue # do nothing # else : # else if element is not in the list # lst.append(element) # append # lst.sort() # sort the list (de-indent indicates that you sort when the loop ends) # print lst # print the list
true
d429625575170c30a12a6fed8853dccc3adf4897
ojaaaaas/llist
/insertion.py
1,246
4.28125
4
#to insert a node in a linked list class Node: def __init__(self,data): self.data = data self.next = None class linkedList: def __init__(self): self.head = None #in the front def push(self,new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node #adding a node after a given node def push2(self,new_data,prev): new_node = Node(new_data) if not prev: return None new_node = Node(new_data) new_node.next = prev.next prev.next = new_node def printList(self): if Node is None: return None temp = self.head while(temp): print(temp.data) temp = temp.next #deletion of a complete linked list def deleteList(self): temp = self.head while(temp): del temp.data temp = temp.next print("deleted successfully") if __name__=="__main__": llist = linkedList() llist.head = Node(4) second = Node(5) third = Node(6) llist.head.next = second second.next = third llist.push(8) llist.printList() print("deleting linked list") llist.deleteList()
true
08e5bc3146fe645582fc769a88c5171b3e81a4ed
myhabr/HW2
/task2_def_var1.py
844
4.25
4
#Вариант 1, функции #Даны четыре действительных числа: x1, y1, x2, y2. #Напишите функцию distance(x1, y1, x2, y2), вычисляющая расстояние между точкой (x1,y1) и (x2,y2). #Считайте четыре действительных числа и выведите результат работы этой функции. x1, y1, x2, y2 = map(float, input("Введите x1, y1, x2, y2 через пробелы\n").split()) print("Переданные аргументы: \n", "x10 = ", x1, " ; ", "y1 = ", y1, "\n", "x2 = ", x2, " ; ", "y2 = ", y2, "\n") def distance(x1, y1, x2, y2): a = x2 - x1 b = y2 - y1 return ((a **2 + b ** 2) ** 0.5) print("Расстояние между точками (x1,y1) и (x2,y2): ", distance(x1,y1,x2,y2))
false
aebf92f28db51768c9367bb0eb9ff48a7a5fe176
Pyrodox/EasterDay_AlmostAnyYear
/Date_of_Easter.py
1,388
4.25
4
from Shift15.Restart_Function import confirm_restart print("Calculate the date for Easter for a certain year.") def easterdate(user_input): if user_input == 1954 or user_input == 1981 or user_input == 2049 or user_input == 2076: user_input = user_input - 7 a = user_input % 19 b = user_input % 4 c = user_input % 7 d = (19 * a + 24) % 30 e = (2 * b + 4 * c + 6 * d + 5) % 7 return 22 + d + e else: a = user_input % 19 b = user_input % 4 c = user_input % 7 d = (19 * a + 24) % 30 e = (2 * b + 4 * c + 6 * d + 5) % 7 return 22 + d + e def printdate(datenum, year): if datenum > 31: return "The date for Easter is April " + str(datenum - 31) + "th, " + str(year) + "." else: return "The date for Easter is March " + str(datenum) + "th, " + str(year) + "." while True: while True: year_input = int(input("Choose the year: ")) if isinstance(year_input, int) is True and year_input in range(1900, 3000): break else: print("Please enter a valid integer for a year that is between 1900 and 2099.") continue print(printdate(easterdate(year_input), year_input)) if confirm_restart() == "yes": continue else: break
false
c20b3f2791e46bdf8d0d36a231cb910eb308d7e6
exequielmoneva/Small-Python-Exercises
/Small Python Exercises/impresion en triangulo.py
377
4.1875
4
#Calculate and print the number (without using strings) in order to create a triangle until N-1 for i in range(1,int(input("Insert the size of the triangle: "))): print((10**(i)//9)*i)#This is a way to get the number without the str() """ Explanation for (10**(i)//9)*i: example for number 2: 10**2 = 100 100/22 = 11,11111111111111 but 100//22 = 11 and 11*2 = 22 """
true
5a1b3b9c6ea33d83ac87571a95d83d4f7cf36d5f
daniel-dc-cd/AMMAshi-Saudi-Digital-Academy---Data-Science-Immersive---Bootcamps
/07_week/02_day_assignment/05_intermediate_function_1.py
2,279
4.21875
4
#============================================ # Arwa Ashi - HW 2 - Week 7 - Oct 19, 2020 #============================================ # random.random() returns a random floating number between 0.000 and 1.000 # random.random() * 50 returns a random floating number between 0.000 and 50.000, i.e. scaling the range of random numbers. # random.random() * 25 + 10 returns a random floating number between 10.000 and 35.000, # round(num) returns the rounded integer value of num # ================================================== # 1- Complete the randInt function import random def randInt(min= 0 ,max= 0): if max == 0 and min == 0: num = random.random() * 100 elif max != 0 and min == 0: if max > 0: num = random.random() * max else: return "ERROR: please enter a +ve value !" elif min != 0 and max == 0: if min > 0: num = random.random() * (100 - min) + min else: return "ERROR: please enter a +ve value !" elif min !=0 and max !=0: if max > min: num = random.random() * (max - min) + min else: return "ERROR: min is greater than max, please reorder them !" return round(num) # If no arguments are provided, the function should return a random integer between 0 and 100. test_randInt_01 = randInt() print(test_randInt_01) # If only a max number is provided, # the function should return a random integer between 0 and the max number. test_randInt_02 = randInt(max=50) print(test_randInt_02) # If only a min number is provided, # the function should return a random integer between the min number and 100 test_randInt_03 = randInt(min=50) print(test_randInt_03) # If both a min and max number are provided, # the function should return a random integer between those 2 values test_randInt_04 = randInt(min=50, max=500) print(test_randInt_04) # 2- Account for any edge cases (e.g. min is greater than max, max is less than 0) # min is greater than max test_randInt_edge_01 = randInt(min=10, max=5) print(test_randInt_edge_01) # max is less than 0 test_randInt_edge_02 = randInt(max=-9) print(test_randInt_edge_02) test_randInt_edge_03 = randInt(min=-9) print(test_randInt_edge_03)
true
7282997020b9c81cf7591af4d63f81a124617bc9
daniel-dc-cd/AMMAshi-Saudi-Digital-Academy---Data-Science-Immersive---Bootcamps
/07_week/03_day_assignment/assignment_module_1.py
1,186
4.46875
4
#=================================================== # Arwa Ashi - HW 3 - Week 7 - Oct 19, 2020 #=================================================== #================================================================== # In each cell complete the task using basic Python functions #================================================================== # 1- print the numbers between 1 and 100 for i in range(100): print(i+1) # 2- print the numbers between 1 and 100 divisible by 8 for i in range(100): if((i+1)%8 == 0): print(i+1) else: next # 3- Use a while loop to find the first 20 numbers divisible by 5 start = 1 count = 0 while count<20: if (start%5==0): print(start) count+=1 start +=1 # 4- Here is an example function that adds two numbers def simple_adding_function(a,b): return a + b print(simple_adding_function(3,4)) # 5- Create a function that evaluates if a number is prime (you can not use a list of known primes). Only allow values between 0 and 100. def prime(a): for i in range(2,a): if((a%(i) == 0)&(a!=(i))): return(a," is not Prime") return(a," is a prime number") print(prime(13))
true
97c85007fd951698ae1461901a5b81daf46c59e5
2narayana/Automate-the-boring-stuff-with-Python---Practical-projects
/005 - PasswordLocker.py
1,566
4.4375
4
#! python3 # This program saves passwords and sends to the clipboard the desired password when executed. # To open it, we type "5 - PasswordLocker" <argument> on cmd prompt. # "5 - PasswordLocker.bat" must be downloaded along with PasswordLocker.py so that the command above works. PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6', 'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt', 'luggage': '12345'} import sys, pyperclip if len(sys.argv) < 2: print('Usage: python PasswordLocker.py [account] - copy account password') sys.exit() if sys.argv[1] == 'new': print('Insert account name (Or nothing to quit):') newAccount = input() if newAccount == '': sys.exit() else: print('Insert the password. (I won\'t look, I promise!)') newPassword = input() PASSWORDS[newAccount] = newPassword print('Password successfully registered.') # Because we didn't use actual files in this program, the new password won't be saved. # We would need a file containing the PASSWORDS dictionary to save it, and open the file in the program. # The objective with this feature is to test the argv's logic. else: account = sys.argv[1] # sys.argv[0] is always a string containing the program's filename. if account in PASSWORDS: pyperclip.copy(PASSWORDS[account]) print('Password for ' + account + ' copied to clipboard.') else: print('There is no account named ' + account + '. To register it, execute the program with \'new\' as argument')
true
a145c849ce706b4943e412b66b740df18c9c42b0
AEI11/PythonNotes
/circle.py
652
4.125
4
# create a class class Circle: # create a class variable pi = 3.14 # create a method (function defined inside of a clas) with 2 arguments #self is implicitly passed # radius is explicitly passed when we call the method def area(self, radius): # returns the class variable on the class * radius (what we explicitly pass) raised to the power of 2 return Circle.pi * radius ** 2 # create an instance of the class circle = Circle() pizza_area = circle.area(6) print(pizza_area) teaching_table_area = circle.area(18) print(teaching_table_area) round_room_area = circle.area(5730) print(round_room_area)
true
e8fff60820753fa85e18992c5b3b850be01405f1
Hya-cinthus/GEC-Python-camp-201806-master
/level2/level2Exercises.py
1,630
4.3125
4
#Ex. 1 #write a function that tests whether a number is prime or not. #hint: use the modulo operator (%) #hint: n=1 and n=2 are separate cases. 1 is not prime and 2 is prime. #Ex. 2 #write a function that computes the Least Common Multiple of two numbers #Ex. 3 #write a program that prints this pattern, using a nested for loop: * * * * * * * * * * * * * * * * * * * * * * * * * #extension: write a function that prints this pattern for any length #(the one above would be considered to have length 5) #Ex. 4 #fibonacci.py #write a function that prints out the first n #fibonacci numbers #1,1,2,3,5,8,13,21,... #f(n) = f(n-1) + f(n-2) #Ex. 5 #englishToPigLatin.py #function: a recipe that takes inputs and produces outputs #script: a sequence of instructions #write a function that takes an english word and translates it #into Pig Latin #pig latin: take the first letter of an english word, put it at the end, #and add "ay" #examples: #hello -> ellohay #why -> hyway #highway -> ighwayhay #next, write a function that takes a pig latin word, #and translates it into english. #after that, modify both functions so that they can take in a sentence #or paragraph, and translate either into pig latin or into english. mySentence = "today is a very nice good and also fun day" #Ex. 6 #sortList.py #sorts a list from smallest to largest theList = [-5,-23,5,-100,23,-6] #expected output: [-100,-23,-6,-5,5,23] #Ex. 7 #pascalTriangle.py #print the n-depth Pascal Triangle #An example of 5-depth output: [1] [2, 2] [3, 3, 3] [4, 4, 4, 4] [5, 5, 5, 5, 5]
true
6415ea8be338eb96b5d04a49f6241733265954b5
Hya-cinthus/GEC-Python-camp-201806-master
/level1/noMultiplesOf3-demo.py
336
4.4375
4
#noMultiplesOf3.py #write a program that prints out all numbers #from 0 to 100 #that are NOT multiples of 3. #modulo operator: the remainder of a division #print(3%3) #gives us 0 #print(4%3) #gives us 1 #print(5%3) #gives us 2 #print(6%3) #gives us 0 (6 is divisible by 3) x = 0 for x in range(101): if (x%3!=0): print(x)
true
08ebfd6a2aa1f2dd12850d272b99609b3a0e8a84
tatsuyaokunaga/diveintocode-term0
/03-02-python-set.py
1,217
4.28125
4
course_dict = { 'AIコース': {'Aさん', 'Cさん', 'Dさん'}, 'Railsコース': {'Bさん', 'Cさん', 'Eさん'}, 'Railsチュートリアルコース': {'Gさん', 'Fさん', 'Eさん'}, 'JS': {'Aさん', 'Gさん', 'Hさん'}, } def find_person(want_to_find_person): """ 受講生がどのコースに在籍しているかを出力する。 まずはフローチャートを書いて、どのようにアルゴリズムを解いていくか考えてみましょう。 """ # ここにコードを書いてみる for key in course_dict.keys(): if want_to_find_person <= course_dict[key]: print(key+'に'+str(want_to_find_person)+'は在籍しています。') elif len(want_to_find_person & course_dict[key]) > 0: print(key+'に'+str(want_to_find_person & course_dict[key]) + 'のみ在籍しています。') else: print(key+'に'+str(want_to_find_person)+'は在籍していません。') def main(): want_to_find_person = {'Cさん', 'Aさん'} print('探したい人: {}'.format(want_to_find_person)) find_person(want_to_find_person) if __name__ == '__main__': main()
false
b274ae7106e79fb4d9a8185fd5af8046c75b3982
spyderlabs/OpenSource-2020
/Python/bubble_sort.py
2,385
4.28125
4
""" This is a function that takes a numeric list as a parameter and returns the sorted list. It does not modify the given list, as it works with a copy of it. It is a demonstrative algorithm, used for informational and learning purposes. It is open to changes, but keep the code clear and understandable, as its main purpose is not to be efficient, but to be a learning tool. Try keeping the code commented, explaining every functionality, and respecting PEP-8. Keep variable names clear and not general, so the code is easyli understandable (it is ok to use i for iterator, aux or temp, but just don't name every variable x, a, b, c, y) Make sure the modified function passes all assertion tests, but feel free to add more if you can think of extra cases that are not covered. """ from copy import deepcopy def bubble_sort(given_list): """ Takes a list as a parameter, returns the given list but sorted. :param given_list: A numerical list :return sorted_list: The given list, sorted using bubble sort """ sorted_list = deepcopy(given_list) # Copies the list in a temporary list that will be sorted is_sorted = False # Considers the list not sorted by default while not is_sorted: # Executes the code while the list is not sorted is_sorted = True # At the beginning of the loop, considers the list as sorted for i in range(1, len(sorted_list)): # Iterates trough all items of the list if sorted_list[i-1] > sorted_list[i]: # If it finds 2 items in the wrong order... is_sorted = False # ...considers the list not sorted... aux = sorted_list[i-1] # ... and swaps the elements in order to put them in the right order sorted_list[i-1] = sorted_list[i] sorted_list[i] = aux return sorted_list # Finally, the sorted list is returned def test_bubble_sort(): assert bubble_sort([]) == [] assert bubble_sort([1]) == [1] assert bubble_sort([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] assert bubble_sort([1, 2, 3, 3, 3, 3, 3]) == [1, 2, 3, 3, 3, 3, 3] assert bubble_sort([1.23, 1.32, 3.89, 2.333]) == [1.23, 1.32, 2.333, 3.89] assert bubble_sort([1, 9, 2, 8, 3, 7, 4, 6, 5]) == [1, 2, 3, 4, 5, 6, 7, 8, 9] test_bubble_sort()
true
f2871acea16906fa59c0d086375ae0fe1975f937
spyderlabs/OpenSource-2020
/Python/binary_search.py
1,968
4.28125
4
print('''INSTRUCTIONS FOR ADAPTED CODE: can run a binary search in the following ways: 1) in python shell: run code as is 2) in your terminal: open a command line / terminal cd to the path of binary_search.py type your list (e.g. 1 2 4 10 12) and key (e.g. 4) in the following way: python binary_search.py -e 1 2 4 10 12 -k 4 3) directly by writing on the script activate lines 22 - 26 and change the sorted_list and key parameters deactivate lines 28 - 32 run code \n ''') import argparse ap = argparse.ArgumentParser() # ap.add_argument("-e", "--sorted_list", \ # default = [1,2,5,12,122,232,1334,1445,3240], nargs = '+', # help="add integer list of data in sorted order in default (line 4)") # ap.add_argument("-k", "--key", default = 12, type=int, # help="enter key to search") ap.add_argument("-e", "--sorted_list", \ default = '', nargs = '+', help="add integer list of data in sorted order in default (line 4)") ap.add_argument("-k", "--key", default = '', help="enter key to search") args = vars(ap.parse_args()) def binary_search(arr, n, key): low = 0 high = n-1 while low <= high: mid = (low+high)//2 if arr[mid] == key: return mid+1 elif arr[mid] < key: low = mid+1 else: high = mid-1 return -1 if __name__ == "__main__": # n = int(input('Enter number of Elements: ')) arr = list( map( int, input('Enter data in sorted order: ').split() ) ) \ if args["sorted_list"] == '' else args["sorted_list"] key = int(input('Enter key to search: ')) if args["key"] == '' else args["key"] n = len(arr) x = binary_search(arr, n, key) if x == -1: print('Element not found') else: print("Element found at position ", x)
true
37c0b5c7bff1a01f8ff8f4220ca0813e12e45137
RajatRajdeep/DSA
/Sorting/insertion_sort.py
358
4.25
4
def insertion_sort(arr): for i in range(1, len(arr)): val = arr[i] j = i-1 while val<arr[j] and j>=0: arr[j+1] = arr[j] j-=1 arr[j+1] = val return arr if __name__ == "__main__": arr = [1, 2, 0, 10, 5, 0, -1, -100, 19, 10, 0] print("Using Insertion Sort : ", insertion_sort(arr))
false
0ba8ab8dd079c11acd0440120bdaf321250b7c15
Deepanshus98/D_S_A
/btLEFTVIEWOFBT.py
1,160
4.28125
4
# A class to store a binary tree node class Node: def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right # Recursive function to print the left view of a given binary tree def leftView(root, level=1, last_level=0): # base case: empty tree if root is None: return last_level # if the current node is the first node of the current level if last_level < level: # print the node's data print(root.key, end=' ') # update the last level to the current level last_level = level # recur for the left and right subtree by increasing the level by 1 last_level = leftView(root.left, level + 1, last_level) last_level = leftView(root.right, level + 1, last_level) return last_level if __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.right = Node(4) root.right.left = Node(5) root.right.right = Node(6) root.right.left.left = Node(7) root.right.left.right = Node(8) leftView(root)
true
31c35ef90615947354bc91315d77e85935ce1922
Deepanshus98/D_S_A
/BSTsearchgivenkeyinBST.py
1,700
4.25
4
# A class to store a BST node class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right # Recursive function to insert a key into a BST def insert(root, key): # if the root is None, create a new node and return it if root is None: return Node(key) # if the given key is less than the root node, recur for the left subtree if key < root.data: root.left = insert(root.left, key) # if the given key is more than the root node, recur for the right subtree else: root.right = insert(root.right, key) return root # Recursive function to search in a given BST def search(root, key, parent): # if the key is not present in the key if root is None: print("Key Not found") return # if the key is found if root.data == key: if parent is None: print("The node with key", key, "is root node") elif key < parent.data: print("The given key is the left node of the node with key", parent.data) else: print("The given key is the right node of the node with key", parent.data) return # if the given key is less than the root node, recur for the left subtree; # otherwise, recur for the right subtree if key < root.data: search(root.left, key, root) else: search(root.right, key, root) if __name__ == '__main__': root = None keys = [15, 10, 20, 8, 12, 16, 25] for key in keys: root = insert(root, key) search(root, 25, None)
true
52014cac130bed41ee581f4656a31cbf4009276b
garethkusky/CityCourseSpring
/week8/eliminateDupes.py
743
4.21875
4
__author__ = 'acpb968' #Write a function that returns a new list by eliminating the duplicate values in the list. Use the #following function header: #def eliminateDuplicates(lst): #Write a test program that reads in a list of integers, invokes the function, and displays the result. #Here is the sample run of the program: #Enter ten numbers: 1 2 3 2 1 6 3 4 5 2 #The distinct numbers are: 1 2 3 6 4 5 def main(): list=[int(x) for x in input("Enter ten Numbers: ").split()] distinct=eliminateDuplicates(list) print("the distinct Numbers are: ", distinct) def eliminateDuplicates(lst): list2=[] for x in range (0,len(lst)): if list2.index(lst(x))==False: list2.append[lst(x)] return list2 main()
true
f3c08fc78df72a2000b8b69d6e5024f5b0006694
zenmeder/leetcode
/222.py
1,307
4.125
4
#!/usr/local/bin/ python3 # -*- coding:utf-8 -*- # __author__ = "zenmeder" # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def countNodes(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 visited = {} def dfs(root): self.h += 1 visited[root] = True if not root.left: if self.h == self.height: self.count += 1 else: self.flag = 1 if root.left and root.left not in visited and not self.flag: dfs(root.left) self.h -= 1 if root.right and root.right not in visited and not self.flag: dfs(root.right) self.h -= 1 self.count, self.h, self.height, self.flag, p= 0, 0, 1, 0,root while root.left: self.height += 1 root = root.left dfs(p) return 2**(self.height-1)+self.count-1 a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) d = TreeNode(4) e = TreeNode(5) # a.left = b # a.right = c # b.left = d # b.right = e print(Solution().countNodes(a))
false
cb620a7862c383c7a43123f2c3c9bf0473e3db60
DiksonSantos/GeekUniversity_Python
/157_Tipagem_de_Dados_Dinamixa_x_Estatica.py
531
4.125
4
""" Tipagem Dinamica -> Quer dizer que não precisa definir uma variavel x=10 como inteira, o Python já sabe disso. Não é como no Java por exemplo. Tipagem Estatica -> Java , que já define na criação da variavel qual sera seu tipo Ex: int, str, e por ai vai. Como esta linguagem (Java) por exemplo, é compilada, O Java não te deixa nem compilar seu código se perceber que esta com um problema desses. O processo no Java é = Compilar+Rodar. No Python ele já vai num lance só, e já roda. (Linguagem interpretada). """
false
fdd12c6a9553c670c3a6dac9e03db551e202e698
DiksonSantos/GeekUniversity_Python
/Continuacao_Do_Curso_Em_Python_3_8/Aula_167_OperadorWalrus.py
619
4.40625
4
''' Permite fazer a atrb e retorno de val numa unica expressão ''' #Sintax: # -> variavel := expressão print(nome := "Dikson") #3.7 print(nome, 'Santos') ''' #3.7 cesta = [] fruta = input('Fruta: ') while fruta != 'Jaca': cesta.append(fruta) fruta = input('Informe a fruta: ').capitalize() if fruta == 'Jaca': print(cesta) ''' # Python 3.8 -> Uma Economia de Linhas Significativa: cesta = [] while(fruta := input('Diga Uma Fruta: ').upper()) != 'JACA': cesta.append(fruta) #Poŕem auqi esta parte NÃO funcionou da mesma forma :/ #if fruta == 'JACA': # print(cesta)
false
431587b9650f3ba79d44cd5522c5ed4f67669931
DiksonSantos/GeekUniversity_Python
/37_Modulo_Collections_Counter.py
1,279
4.15625
4
from collections import Counter '''A Função Counter enumera as ocorrencias dentro de Tuplas Dicionarios Ou Listas (qualquer um destes (ou os ITERAVEIS)''' lista = (1,1,1,1,1,2,2,2,2,23,3,3,3,3,3,4,4,4,4,45,5,5,5,5,) res = Counter(lista) print(res) #Imprimiu -> 1 apareceu 5 vezes. 3= 5 Ocorrencias. E assim por diante Meu_nome = 'Gow Dikson' print(Counter(Meu_nome)) #Letra 'o' Aparece 2x no meu nome, o restante 1x Texto = '''É possível acessar seus cursos da Udemy em diversos dispositivos e plataformas , ( PLAtaFORMAS ) tanto em desktops/notebooks Windows e Mac, como dispositivos móveis Android e iOS. Para isso, são necessários os requisitos de sistema a seguir.''' #Quantas vezes cada letra aparece na String ou No Texto print(Counter(Texto)) #Divide o texto em palavras para cada espaço entre elas. Quant_Palavr = Texto.split() #Trasnforma tudo em Minusculo Quant_PalavrLOW= Texto.lower() #Conta todas aspalavras transformadas em nanicas. Quantas = Quant_PalavrLOW.count('plataformas') #Quantidade de palavras em que o texto foi dividido print(len(Quant_Palavr), "-> É a quantidade de Palavras") print('Quantas Palavras: ', Quantas) print(Counter(Quant_Palavr).most_common(3)) #O .mostcommon com parametro3 mostra as 3 palavras que mais aparecem no Texto.
false
6634a1bb9b694dd57b222e06598f10ca7d2485ca
DiksonSantos/GeekUniversity_Python
/57_Set_Comprehension.py
860
4.34375
4
#Set Comprehension lista = [1,2,3] set = {1,2,3} num = {num for num in range(0,9)} #print(num) numeros = {x**2 for x in range(10)} #print(numeros) #Convertendo Dicionario em Lista: #No caso da variavel 'numeros' NÃO deu certo. Precisam haver chaaves e valores para se especificar que se quer. chave_valor = {'Chave':'Valor', 'Seg':'Segmento'} Lista_num = list(chave_valor.values()) #Pode especificar .key , .values , .items #print(Lista_num) #https://www.pythoncentral.io/convert-dictionary-values-list-python/ ''' vari = 0 in range(10) for I in range(0,10): print(I,end=' ') ''' numeros__ = [[x**2 for x in range(10)]] #print(numeros__) #Outra maneira mais dirta Economiza uma linha. print([[x**2 for x in range(10)]]) #Pra fazer um Dicionario: dicio = {x: x**2 for x in range(10)} #Apenas Especificque o 'x' como sendo a chave print(dicio)
false
239e12a7516b0d1217ef1585ca81db8ce03ce270
DiksonSantos/GeekUniversity_Python
/131_Escrevendo_Em_Arquivos_CSV.py
2,152
4.125
4
""" # Writer gera Um Objeto para que possamos escrever num arquivo CSV. #Writerow -> Escreve Linha Por Linha. Este método Recebe Uma Lista. from csv import writer # Aqui na abertura o 'w' Se usado Num mesmo arquivo (Já escrito), vai apaga-lo e Re-escrever Tudo. # O 'a' Acrescenta o que for digitado de novo ao que já existe no CSV. # Com o 'a' ele também Repetiu o Cabeçalho do arquivo. with open('filmes.csv', 'a') as Arquivo: escritor = writer(Arquivo) #Uma variavel iniciada com Nada Dentro. filme = None #Esta Var precisa existir antes do Loop While para ser possivel usa-la Lá. #Aqui é inserção do cabeçalho (PRIMEIRA_LINHA), Mas, não é obrigatorio. #Aqui a Linha do Cabeçalho esta antes do Loop pois o Cabeçalho só é escrito UMA vez. escritor.writerow(['Titulo', 'Genero', 'Duração']) while filme != 'sair': filme = input('Nome Do Filme: ') if filme != 'sair': genero = input('Informe o Genero Do Filme: ') duracao = input("Duração do Filme: ") #Recebe estes 3 Inputs como Uma Lista inserindo-as a Cada Linha: escritor.writerow([filme, genero, duracao]) """ # DictWrite -> Agora ao Inves de Listas, vamos Criar Dicionarios: from csv import DictWriter with open('Filmes2.csv', 'w') as Movie: cabecalho = ['Titulo', 'Genero', 'Duration'] #Este fieldnames aqui é do tipo Kwargs Escritor_CSV = DictWriter(Movie, fieldnames=cabecalho)# Fieldnames é Nome dos Campos, ou COlunas. #Metodo Apenas para escrever o Cabeçalho; Escritor_CSV.writeheader() File_ = None while File_ != 'sair': File_ = input('Nome Do filme: ') if File_ != 'sair': Genero = input("Digite o Genero do Filme: ") Duration = input("Duração Do Filme: ") #As Chaves do Dicionario Devem Ser exatamente iguais ás do Cabeçalho (Ali em cima). #Metodo Apenas para escrever as Linhas: #Do_Cabeçalho : Da Var , ... Escritor_CSV.writerow({"Titulo": File_, "Genero": Genero, "Duration": Duration})
false
ec8d40b6b6ccd56c2762f861b966a5eee56904a4
DiksonSantos/GeekUniversity_Python
/23_AND_OR_NOT_IS.py
1,058
4.375
4
''' Estruturas Logicas ''' ''' numeros = int(input("Digite_Numero")) #numeros = [10,20,30] Mais_Numeros = [10,40,50] if numeros not in Mais_Numeros: print("Não Tem") else: print("Tem") ''' ''' for x in numeros: if x in Mais_Numeros: print("Tem") if x not in Mais_Numeros: print("Não Tem") ''' ''' #FAZENDO UMA PIZZA: requested_toppings =["Anchovas", "Cogumelos","Cheese"] available_toppings = ["Queijo", "Molho Branco","Anchovas", "Cogumelos"] for requested_topping in requested_toppings: if requested_topping in available_toppings: print("Adding " + requested_topping + ".") else: print("Sorry, we don't have " + requested_topping + ".") print("\nFinished making your pizza!") ''' ativo = True #ativo = False logado = False #logado = True if ativo or logado: print("Pronto Para Logar") if ativo is True: print("Ativo no Sistema") if ativo and logado: #Forem TRUE print("Bem Vindo User") if not ativo: print("Ative seu sistema") if not logado: print("Digite sua senha")
false
01be969de4bcf42b9d0227b7629baa5cec4b98e3
tonyraymartinez/pythonProjects
/areaCalc.py
1,649
4.21875
4
import math shape = raw_input("What shape will you be getting the area for?\n"+ "enter 'r' for rectangle,\n"+ "enter 's' for square,\n"+ "enter 'c' for circle,\n"+ "enter 'e' for ellipse\n"+ "enter 't' for triangle\n: ") shape = shape.lower() if shape == 'r': #check if shape is rectangle and calculate input height = raw_input("Enter the height of your rectangle: ") width = raw_input("Enter the width of your rectagle: ") area = int(height)*int(width) print "The area of your rectangle is %s square units." %area elif shape == 's': #check if shape is square and calculate input height = raw_input("Enter the height of your square: ") area = int(height)**2 print "The area of your square is %s square units." %area elif shape == 'c': #check if shape is circle and calculate input radius = raw_input("Enter the radius of the circle: ") area = math.pi*(int(radius)**2) print "The area of your circle is %s square units." %area elif shape == 'e': #check if shape is ellipse an calculate input height = raw_input("Enter the height of your ellipse: ") width = raw_input("Enter the width of your ellipse: ") area = int(height)*int(width)*math.pi print "The area of your ellipse is %s square units." %area elif shape == 't': #check if shape is triangle and calculate input" base = raw_input("Enter the base of your triangle: ") height = raw_input("Etner the height of your triangle: ") area = (int(base)*int(height))/2 print "The area of your triangle is %s square units." %area else: print "You did not enter a valid option."
true
89f1563c1efac611e9df0e3dd06327762a221a81
vnpavlukov/Study
/Books/2_Vasilev_Python_on_exaples/Test_13_3.18_proizvodnaya.py
656
4.15625
4
def D(f): # функция для вычисления производной def df(x, dx=0.001): return (f(x + dx) - f(x)) / dx return df def f1(x): # функция для дифференцирования return x ** 2 def f2(x): return 1 / (1 + x) def show(F, Nmax, Xmax, dx, f): for i in range(Nmax + 1): x = i * Xmax / Nmax print(F(x), F(x, dx), f(x), sep=' -> ') F1 = D(f1) F2 = D(f2) print("Производная (x ** 2)' = 2x:") show(F1, 5, 1, 0.01, lambda x: 2 * x) print("Производная (1 / (1 + x))' =- 1 / (1 + x) ** 2):") show(F1, 5, 1, 0.01, lambda x: -1 / (1 + x) ** 2)
false
1992808b41d66492a3180d7e832509a10d730ec8
vnpavlukov/Study
/Geekbrains/2 четверть/html_css/1 четверть/Основы языка Python/pavlukov_vladimir_dz4/task_5_sum_of_numbers.py
751
4.15625
4
"""5. Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти четные числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех элементов списка. Подсказка: использовать функцию reduce().""" from functools import reduce even_list_100_1000 = [num for num in range(100, 1000 + 1) if num % 2 == 0] print(even_list_100_1000[:10]) print(even_list_100_1000[-10:]) product_of_evens = reduce(lambda a, b: a * b, even_list_100_1000) print(product_of_evens)
false
7cf88548d9e1f63dc4531020d4620234eccd2852
vnpavlukov/Study
/Geekbrains/1 четверть/Основы языка Python/pavlukov_vladimir_dz1/task_5_economic_efficiency.py
1,403
4.21875
4
"""5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.""" # revenue = int(input('Revenue: ')) # expenses = int(input('Expenses ')) revenue = 1000 expenses = 500 if revenue > expenses: print('Прибыль') profitability = revenue / expenses print('Рентабельность компании:', profitability) # employees = int(input("Количество сотрудников: ")) employees = 5 # по умолчанию 5ть сотрудников для теста rent = (revenue - expenses) / employees print('Прибыль на одного сотрудника:', rent) else: print('Убыток')
false
c0b8f30f7560d6f0fef0ca9cb7202a050758d896
glenjantz/DojoAssignments
/Python/pythonfundamentals/trypython/tuplepractice.py
465
4.1875
4
capitals = {} #create an empty dictionary then add values capitals["svk"] = "Bratislava" capitals["deu"] = "Berlin" capitals["dnk"] = "Copenhagen" # print capitals # print capitals["svk"] # for data in capitals: # print data # for key in capitals.iterkeys(): # print key # for val in capitals.itervalues(): # print val for key,data in capitals.iteritems(): print key, " = ", data for key,data in capitals.iteritems(): print key, " = ", data
false
4ff3a8c5abab7e8f59c7151d15dc9a74a0dd7ff0
glenjantz/DojoAssignments
/pythonreview/oop/car.py
1,349
4.15625
4
# Create a class called Car. In the__init__(), allow the user to specify the following attributes: price, speed, fuel, mileage. # If the price is greater than 10,000, set the tax to be 15%. Otherwise, set the tax to be 12%. # Create six different instances of the class Car. In the class have a method called display_all() that returns all the information about the car as a string. # In your __init__(), call this display_all() method to display information about the car once the attributes have been defined. class Car(object): def __init__(self,price,speed,fuel,mileage): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage if self.price > 10000: self.tax = 0.15 else: self.tax = 0.12 self.display_all() def display_all(self): print "This cars price is " + str(self.price) + " and this cars max speed is " + self.speed + " and this cars tank starts " + self.fuel \ + " and this cars gas mileage is " + self.mileage + " and this cars tax was " + str(self.tax) + " %" car1 = Car(1000,"55mph","empty","15mpg") car2 = Car(2000,"60mph","empty","20mpg") car3 = Car(4000,"70mph","half","25mpg") car4 = Car(8000,"100mph","half","25mpg") car5 = Car(10000,"90mph","full","50mpg") car6 = Car(16000,"100ph","full","60mpg")
true
da0157620558c8403cb9ce95cb9cc6ef883c4b58
mmweber2/hackerrank
/dropbox.py
1,850
4.21875
4
# Based on a problem from Dropbox: # http://hr.gs/redbluebluered def wordpattern(pattern, input, word_map=None): """Determines if pattern matches input. Given a pattern string and an input string, determine if the pattern matches the input, such that each character in pattern maps to a substring of input. Examples: abba, redbluebluered: matches abc, redbluebluered: matches abcdab, tobeornottobe: matches aba, nonrepeating: doesn't match Args: pattern: string, the input to match. input: string, the full string to check substrings. Returns: 1 if there exist any mappings such that pattern matches input, 0 otherwise. """ if not word_map: word_map = {} if pattern == "": # Out of characters to check; has the full input been matched? return 1 if input == "" else 0 current_letter = pattern[0] if current_letter in word_map: # Letter exists earlier in the pattern word = word_map[current_letter] if input.startswith(word): return wordpattern(pattern[1:], input[len(word):], word_map) # Don't recurse if this appearance doesn't match the previous one return 0 # TODO: Range can be smaller than this for length in xrange(1, len(input)): # Make a copy so that this mapping is only used for this recursive path temp_map = word_map.copy() temp_map[current_letter] = input[:length] if wordpattern(pattern[1:], input[length:], temp_map): return 1 return 0 # Passing cases print wordpattern("abba", "redbluebluered") print wordpattern("abcdab", "tobeornottobe") print wordpattern("xx", "xyzxyz") print wordpattern("aba", "same word same") # Failing cases print wordpattern("aba", "nopatternhere") print wordpattern("a", "abc")
true
b12a2d50c75c115b4141a90ecb3228e97678ef12
3people/sorting-visualizer
/sorting.py
1,557
4.125
4
from animate import draw def bubbleSort(data): data_length = len(data) for i in range(data_length - 1): for j in range(data_length - i - 1): if data[j] > data[j+1]: data[j], data[j+1] = data[j+1], data[j] draw(j+1, data) def selectionSort(data): data_length = len(data) for i in range(data_length - 1): least = i for j in range(i+1, data_length): if data[j] < data[least]: least = j if i != least: data[i], data[least] = data[least], data[i] draw(i+1, data) def insertionSort(data): data_length = len(data) for i in range(1, data_length): j = i - 1 key = data[i] while data[j] > key and j >= 0: data[j+1] = data[j] j = j - 1 data[j+1] = key draw(j+1, data) def heapify(data, index, size): largest = index left = 2 * index + 1 right = 2 * index + 2 if left < size and data[left] > data[largest]: largest = left if right < size and data[right] > data[largest]: largest = right if largest != index: data[largest], data[index] = data[index], data[largest] heapify(data, largest, size) draw(largest, data) def heapSort(data): data_length = len(data) for i in range(data_length // 2 - 1, -1, -1): heapify(data, i, data_length) for i in range(data_length-1, 0, -1): data[0], data[i] = data[i], data[0] heapify(data, 0, i) return data
false
bf556141a20e2fe990dd93a720de386c23623877
aktersabina122/Story_Generator_Python
/Story_generator_Python.py
1,162
4.4375
4
# Challenge One (Input and String Formatting) # You and a partner will try to use your knowledge of Python to create a MadLib function. # HOW-TO: Create a multi-line string variable called my_story which contains a short story about an animal in a specific borough of New York, performing some action involving one specific type of food. # TODO: Ask the user through the command line for their picks for 'animal', 'borough', 'action' and 'food' # TODO: Create a Python program that swaps those items in your story # TODO: Print the user's story to the command line #==================================================================================================== print("Welcome to the story generator") animal = input("What's your favorite animal?\n") borough = input("Which borough do you live in, or what's your favorite one, if you don't live in NYC?\n") action = input("What's your favorite activity at dinner time?\n") food = input("What's your favorite food?\n") storyTemplate = "There's an {0} from {1} going to {2} and then going to eat some {3}".format(animal, borough, action, food) print(storyTemplate)
true
0698789bdda90a3f1b455a79375c6950c6d63bd9
caalive/PythonLearn
/stroperate/shoppingcar2.py
1,570
4.125
4
product_list = [('Iphone',5900), ('Mac Pro',12000), ('Coffee',50), ('Book',40)] shopping_list = []; def print_product_list(): for index,item in enumerate(product_list): print(index,item) def print_shopping_list(): for item in shopping_list: print(item) salary = input("Input your salary:") if salary.isdigit(): salary = int(salary) while True: print_product_list() user_choice = input("选择你要购买的商品编号或按下 q 退出>>:") if user_choice.isdigit(): user_choice = int(user_choice) if user_choice >=0 and user_choice < len(product_list): if salary < int(product_list[user_choice][1]): print("Yor salary is not enough to buy it!!") else: item = product_list[user_choice] shopping_list.append(item) # print("Added %s to your shopping cart!!"%product_list[user_choice]) salary -= item[1] print("Added %s to your shopping cart,Your current balanace is \033[31;1m%s\033[0m"%(item,salary)) else: print("could not find code [%s] product"%user_choice) elif(user_choice == 'q'): print("-------------------ShoppingList-------------------") print_shopping_list() print("Your current balanace is \033[31;1m%s\033[0m" %(salary)) exit() else: print("Invalid input!!")
true
d06ee8dbbe3ee90a32dea1db820f7dc9102e4eb9
wbabicz/lpthw-exercises
/ex15.py
681
4.3125
4
# from sys import argv # script, filename = argv # # Opens the filename passed in and assigns it to the variable txt. # txt = open(filename) # # Prints out the name of the file. # print " Here's your file %r:" % filename # # Reads the text from file and prints it. # print txt.read() #print "Type the filename again:" # Assigns the filename to another variable. #file_again = raw_input("> ") # # Opens the file and assigns it to another variable. #txt_again = open(file_again) # Opens, reads and prints the file. #print txt_again.read() print "Enter a filename to print:" filename = raw_input("> ") txt = open(filename) print txt.read() close (txt)
true
01217e399dc5d841f9423affbf46f513c574ec88
Darshan-code-tech/CMPE282
/set_get.py
637
4.1875
4
class Getter_Setter(object): def __init__(self,name,age): self.name = name self.age = age self.__var = 13 def college(self): print(self.name , self.age) def setter(self,nums): self.__var = nums def getter(self): return self.__var if __name__ == "__main__": c1 = Getter_Setter("Darshan",18) print(c1.name,c1.age) ''' #if __name__ == "__main__": c1 = Getter_Setter("Darshan",18) print(c1.age) print(c1.name) c1.__var = 20 print("Check getter_setter : ", c1.__var) c1.age = 20 print("New Age is : ", c1.age) c1.college() '''
false
1ceeab4b174534c56451b46d31881141a641f2d2
Shruthi410/coffee-machine
/main.py
2,462
4.21875
4
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { "ingredients": { "water": 250, "milk": 100, "coffee": 24, }, "cost": 3.0, } } resources = { "water": 300, "milk": 200, "coffee": 100, } def is_sufficient(order_ingredients): """Returns true when all the ingredients are available.""" for item in order_ingredients: if order_ingredients[item] >= resources[item]: print(f"Sorry there is not enough {item}.") return False return True def calculate_coins(): """ calculates inserted coins """ print("Insert coins") total = int(input("How many quaters: ")) * 0.25 + int(input("how many dimes: ")) * 0.10 + int(input("how many nickels: ")) * 0.05 + int(input("how many pennies: ")) * 0.01 return total def is_transaction_successful(money_received, drink_cost): """ Checks if the money received is sufficient to make coffee. If not returns money""" global total_money if money_received >= drink_cost: refund = round(payment - drink["cost"], 2) total_money += drink["cost"] print(f"Here is ${refund} dollars in change.") return True else: print("Sorry that's not enough money. Money refunded.") return False def make_coffee(order_ingredients): """ Makes coffee and deduct the ingredients from resources. """ for item in order_ingredients: resources[item] -= order_ingredients[item] print(f"Enjoy you {choice}! ☕") return resources[item] total_money = 0 switch = True while switch: choice = input("What would you like to have? (espresso, latte, cappuccino): ") if choice == "off": switch = False elif choice == "report": print(f"water: {resources['water']}ml") print(f"Milk: {resources['milk']}ml") print(f"Coffee: {resources['coffee']}g") print(f"Money: ${total_money}") else: drink = MENU[choice] if is_sufficient(drink["ingredients"]): payment = calculate_coins() if is_transaction_successful(payment, drink["cost"]): make_coffee(drink["ingredients"])
true
ea2adc967d52fdd81ba44c29677ccba708393979
JB0925/Python_Syntax
/words.py
991
4.375
4
from typing import List my_words = ['cat', 'dog', 'ear', 'car', 'elephant'] def uppercase_words(words: List[str] = my_words) -> None: """Print out each string in a list in all caps""" for word in words: print(word.upper()) print(uppercase_words()) def only_words_that_start_with_e(words: List[str] = my_words) -> None: """This function will only print out words that begin with the letter e, whether uppercase or lowercase.""" for word in words: if word[0].lower() == 'e': print(word.upper()) print(only_words_that_start_with_e()) def only_certain_letters(accepted_letters: List[str] = ['c', 'd'], words: List[str] = my_words) -> None: """This function will only print out words in uppercase that begin with one of the letters in accepated letters.""" for word in words: if word[0].lower() in accepted_letters: print(word.upper()) print(only_certain_letters())
true
72c0ab964261776ef9d679c41932c345fd3dbdd5
Rikoairlan57/Mesin-Sorting
/app.py
1,603
4.21875
4
from selection_sort import selectionsort from bubble_sort import bubblesort from merge_sort import mergesort from insertion_sort import insertionsort while True: print("# Menu") print("1. Selection Sort") print("2. Bubble Sort") print("3. Merge Sort") print("4. Insertion Sort") print("5. Credit Title") print("0. keluar program") menu = input("pilih menu : ") if menu == "0": break elif menu == "1": selectionsort num = int(input("masukan berapa banyak angka: ")) list3 = [int(input()) for x in range(num) ] print("sebelum di terurut: ", list3) selectionsort(list3) print("sesudah di urut: ",list3) elif menu == "2": bubblesort num = int(input("masukan berapa banyak angka: ")) list2 = [int(input()) for x in range(num)] print("sebelum berurut", list2) mergesort(list2) print("yang sudah berurut: ", list2) elif menu == "3": mergesort num = int(input("masukan berapa banyak angka: ")) list1 = [int(input()) for x in range(num)] print("sebelum berurut", list1) mergesort(list1) print("yang sudah berurut: ", list1) elif menu == "4": insertionsort num = int(input("masukan berapa banyak angka: ")) my_list = [int(input()) for x in range(num)] print("sebelum berurut", my_list) insertionsort(my_list) print("yang sudah berurut: ", my_list) elif menu == "5": print("Rikoairlan") print("program selesai berjalan, sampai jumpa")
false
2f94e530bd1c00a5b185f33996d7eb3f64879d36
AnupBagade/Hackerrank
/Algorithms/String/reverse_string.py
341
4.375
4
""" Reverse a string using recurssion """ def reverse_string(s): if len(s) == 0: return s else: return reverse_string(s[1:]) + s[0] if __name__ == '__main__': input_string = input('Please enter string to be reversed ') result = reverse_string(input_string) print('String reversed - {}'.format(result))
true
2472183f0d0853dfe2a3949e784b8bdc5d23f289
AnupBagade/Hackerrank
/Algorithms/DailyinterviewPro/longest_consecutive_sequence.py
1,206
4.28125
4
""" You are given an array of integers. Return the length of the longest consecutive elements sequence in the array. For example, the input array [100, 4, 200, 1, 3, 2] has the longest consecutive sequence 1, 2, 3, 4, and thus, you should return its length, 4. def longest_consecutive(nums): # code. print longest_consecutive([100, 4, 200, 1, 3, 2]) [1, 3, 6, 7, 5, 0, 4] """ def longest_consecutive(num): res = [0] cons_res = [] status = False for val in num: if val - 1 in num: if val < max(res): continue if not status: cons_res.append(val) val = val - 1 while val in num: cons_res.append(val) val = val - 1 status = True if status and len(res) <= len(cons_res): res = cons_res[::] cons_res = [] status = False return len(res) if __name__ == '__main__': print(longest_consecutive([1, 3, 5, 7, 9])) print(longest_consecutive([100, 4, 200, 1, 3, 2])) print(longest_consecutive([1, 3, 6, 7, 5, 0, 4])) print(longest_consecutive([100, 99, 98]))
true
04633470b57fcf55cae2fd005a87fed153ab1509
eidehua/ctci-practice
/Python/Data Structures/Arrays and Strings/1.1.py
2,839
4.3125
4
# Implement an algorithm to determine if a string has all unique characters. # What if you cannot use additional data structures? # assumption: assume uppercase and lowercase are different characters def has_unique_chars(str): counts = {} # dictionary to see if we have seen the character already for i in range(0, len(str)): char = str[i] if char in counts: return False counts[char] = True return True print has_unique_chars("HIiiH") assert has_unique_chars("HIiiH") == False print has_unique_chars("HiI") assert has_unique_chars("HiI") == True ''' Input is a string of length n Time Complexity: O(n), since in the worst case we need to look at the entire string Space Complexity: O(n), to store all the unqiue chars in our counts dictionary ''' # Improved solution (from book): there are only a finite amount of different characters that exist. # So while the string may be arbitrarily large, we only need a O(1) extra space to check if characters are duplicated # Assume 256 possible unique characters (ASCII) # function ord() would get the int value of the char. # And in case you want to convert back after playing with the number, function chr() does the trick. def has_unique_chars_2(str): if len(str) > 256: return False char_set = [False for i in range(256)] # list comprehension, for creating a boolean array all initialized to false for i in range(0, len(str)): char_val = ord(str[i]) if (char_set[char_val]): return False char_set[char_val] = True return True print("=====") print has_unique_chars_2("HIiiH") assert has_unique_chars_2("HIiiH") == False print has_unique_chars_2("HiI") assert has_unique_chars_2("HiI") == True ''' Input is a string of length n Time Complexity: O(n), since in the worst case we need to look at the entire string Space Complexity: O(1), to count duplicate chars, we only need storage for all the possible chars. (Which is 256, which is a constant) ''' #What if you cannot use additional data structures? #Have to compare each char with every other char. def has_unique_chars_extra(str): for i in range(0, len(str)): curr_char = str[i] for j in range(i + 1, len(str)): compare_char = str[j] if (curr_char == compare_char): return False return True print("=====") print has_unique_chars_extra("HIiiH") assert has_unique_chars_extra("HIiiH") == False print has_unique_chars_extra("HiI") assert has_unique_chars_extra("HiI") == True ''' Input is a string of length n Time Complexity: O(n**2), since we need to compare every character with every other character Slightly less than n**2 iterations, however. (Because we only have to check each pair once) Space Complexity: O(1). Did not use any extra space '''
true
f24cdb1fe4f60c375ecdc0d39ce7d32d7ee561de
Logeist/Projects
/Solutions/calc.py
458
4.125
4
def main(): a = float(input("Enter your first term: ")) b = float(input("Enter your second term: ")) op = input("Enter your operation (valid: + - * /): ") for i in op: if i == '+': result = a + b print(result) elif i == '-': result = a - b print(result) elif i == '*': result = a * b print(result) elif i == '/': result = a / b print(result) else: print("Invalid operation!") if __name__ == "__main__": main()
false
0809ca6802fee1cc1ef0974245103df2d39998c4
insidepower/pythontest
/s60/009stringMani.py
718
4.28125
4
txt = "I like Python" print txt[2:6] # like print txt.find("like") # 2 if txt.find("love") == -1: print "What's wrong with you?" print txt.replace("like", "love") ## new string print txt.upper() # I LIKE PYTHON print "Length", len(txt) ## 13 txt2 = "" if txt2: print "txt2 contains characters" else: print "txt2 doesn't contain characters" ## this line printed url= " http://www.mopius.com " url= url.strip() #r remove space at the back if url.startswith("http://"): print url, "is a valid URL" ## this line printed webServiceInput= " 1, 2, 3, 4" print webServiceInput.replace(" ", "") # no space txt = "one;two;three" print txt.split(";") # ['one', 'two', 'three']
true
46bc17759e7b3472aa698890b6efb858a43cef88
Snehasis124/PythonTutorials
/ForLoop.py
332
4.4375
4
#10TH PROGRAM #INTRODUCTION TO FORLOOP new_list = ['Hello' , 'Good Morning'] word = input("Add your word ") new_list.append(word) for value in new_list: print(value) # A DEMO PROGRAM def menu(list, question): for entry in list: print( 1 + list.index(entry), print (")") + entry ) return input(question) - 1
true
2287851d9eae7e8571f9b5af63db2d5d9fd800f1
jamiejamiebobamie/CS-1.3-Core-Data-Structures
/project/CallRoutingProject_scenario1.py
1,719
4.28125
4
""" SCENARIO #1 As there is no order to the routes in the route file, the entirety of the file has to be read. Open the file. Iterate through it. Searching each digit of each route. If the program reaches the end of a route, we check to see if that route is cheaper than the current lowest price and change the lowest to that route's cost if it is. Finally returning the lowestRouteCost when all routes in the route file have been read. Call the function in the terminal with the desired phone number to lookup. This function assumes their is a fixed route file list of 100,000 routes that is hardcoded into the function. """ import os import sys routes = '/Users/jamesmccrory/documents/dev/CS-1.3-Core-Data-Structures/project/data/routeLists/route-costs-1000000.txt' def iterateThroughRoutesFile(routesFile, phoneNumber): """Time complexity: O(n**2), n being the number of routes and the length of their digits. Space complexity: O(1), the lowestRouteCost variable.""" lowestRouteCost = float('inf') for line in open(routesFile):# O(n) i = 0 # index route, cost=line.split(",")# O(n) while route[i] == phoneNumber[i] and i < len(route) - 1:# O(n) i += 1 else: if i == len(route) - 1: cost = float(cost.strip("\n")) #O(n) if lowestRouteCost > cost: lowestRouteCost = cost return phoneNumber + ", " + str(lowestRouteCost) if lowestRouteCost != float('inf') else phoneNumber + ", " +"0" if __name__ == "__main__": phoneNumber = str(sys.argv[1]) with open("output_logs/route-costs-1.txt", "w+") as f: f.write(str(iterateThroughRoutesFile(routes, phoneNumber)))
true
ab289ec04193676086b1d75f52bcb24277a51d3e
go2bed/python-simple-neural-network
/com.chadov/MathFormulaNeuralNetwork.py
1,608
4.25
4
from numpy import * # Teaching the computer to predict the output # of a mathematical expression without "knowing" # exact formula (a+b)*2 class NeuralNetwork(object): def __init__(self): random.seed(1) self.weights = 2 * random.random((2, 1)) - 1 # Takes the inputs and corresponding # outputs and trains the network num times # During each iteration we calculate the output using # the "think" method, calculate the error and adjust the weights # using the formula: adjustment = 0.01 * error * input def train(self, inputs, outputs, num): for iteration in range(num): output = self.think(inputs) error = outputs - output adjustment = 0.01 * dot(inputs.T, error) # T is the transpose of the matrix # it transposes the matrix from horizontal to vertical self.weights += adjustment # Calculates the weighted sum using the formula: # weight1 * input1 + weight 2 * input2 def think(self, inputs): return dot(inputs, self.weights) neural_network = NeuralNetwork() inputs = array([[2, 3], [1, 1], [5, 2], [12, 3]]) outputs = array([[10, 4, 14, 30]]).T number_of_iterations = 10000 print("Train our network 10000 times\n") neural_network.train(inputs, outputs, number_of_iterations) print("Try to think with array[15,2]\n") print(neural_network.think(array([15, 2]))) print("now our network work like it knows the formula (a + b)* 2 ") print("What T does mean : we ' ll print outputs\n") print(outputs) print("and print it without T\n") print(array([[10, 4, 14, 30]]))
true
3a0bddbcaf7d7237f96b889d784d988007b52000
EvgenMaevsky/prometheus_py
/super-fibonacci.py
308
4.125
4
def super_fibonacci(n,m): fibonacci_list=[] for step in range(m): fibonacci_list.append(1) for j in range(n+1): last_element = 0 for i in range(m): last_element+=fibonacci_list[i+j] fibonacci_list.append(last_element) return(fibonacci_list[n-1]) print(super_fibonacci(9, 3))
false
c280d8d38c950ece6999026b6aa9705c35a24e21
josethz00/python_basic
/numbers.py
723
4.25
4
import math pi = math.pi print('{:.2f}'.format(pi)) #formating decimal numbers by the right way print(f'{pi:.4f}') #formating decimal numbers by a simple way num1 = input("Please enter the first number") #this way, the value will be gotten as default(as a string) num2 = input("Please enter the second number") #this way, the value will be gotten as default(as a string) print(num1 + num2) #result:concat strs num_1 = float(input("Please enter the first number")) #here there is a conversion to float been made num_2 = float(input("Please enter the first number")) #here there is a conversion to float been made print(num1 + num2)#result: concat strs too print(float(num1) + float(num2)) #result: sum of the two numbers
true
950d8358a2248895e9262524ce4a657150a26276
cvvlvv/Python_Exercise
/Day_2.py
688
4.125
4
# coding: utf-8 # Day 2: # Prime Factorization - Have the user enter a number and find all Prime Factors (if there are any) and display them. # In[ ]: def PrimeFactors (): n = int(input("Please give a number.")) PrimeFactors = [] prime = [] for i in range(2,n+1): for j in range(2,i): if i%j == 0: break else: prime.append(i) i = 0 while i<len(prime): if n%prime[i] == 0: PrimeFactors.append(prime[i]) n = n/prime[i] else: i = i+1 for i in range(0,len(PrimeFactors)-1): print("%s *"%(PrimeFactors[i]), end=" ") print(PrimeFactors[-1])
true
2a7c353e880dfc5d4212f874ecac167e484b0fd9
LouiseCerqueira/python3-exercicios-cursoemvideo
/python3_exercicios_feitos/Desafio065.py
785
4.21875
4
#Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média #entre todos os valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário #se ele quer ou não continuar a digitar valores. soma = 0 contador = 0 media = maior = menor = 0 resp = 'S' while resp in 'S': num = int(input('Digite um número: ')) soma+=num contador +=1 if contador == 1: maior = menor = num else: if num > maior: maior = num if num < menor: menor = num resp = str(input('Quer continuar? [S/N] ')).upper().strip()[0] media = soma/contador print(f'Você digitou {contador} números e a média foi {media}') print(f'O maior número foi {maior} e o menor {menor}')
false
be93860585ad761e0d7ec698b524d8736735f00b
LouiseCerqueira/python3-exercicios-cursoemvideo
/python3_exercicios_feitos/Desafio059.py
1,055
4.28125
4
# Crie um programa que leia dois valores e mostre um menu na tela: #[1] somar [2] multiplicar [3] maior [4] novos números [5] sair do programa #Seu programa deverá realizar a operação solicitada em cada caso from random import randint val1 = int(input('Valor 1: ')) val2 = int(input('Valor 2: ')) print('='*10) print('''O que você quer fazer? [1] Somar [2] Multiplicar [3] Maior [4] Novos Números [5] Sair do Programa''') açao = 0 print('='*10) while açao != 5: açao = int(input('Código: ')) if açao == 1: print(f'A soma de {val1} e {val2} é: {val1+val2:.1f}') if açao == 2: print(f'Multiplicando {val1} com {val2}, obtemos: {val1*val2:.1f}') if açao == 3: if val1>val2: print(f'Entre {val1} e {val2} o maior número é: {val1}') else: print(f'Entre os valores {val1} e {val2} o maior é: {val2}') if açao == 4: novo1 = randint(0,10) novo2 = randint(0,10) print(f'Os novos valores são {novo1} e {novo2}') print('Programa finalizado')
false
39eda1352d4fee20921bd18bdeb7d4cbf9c1cc3b
xytracy/python
/ex15.py
358
4.25
4
from sys import argv script,filename=argv txt= open(filename) #open is a command taht reaads our text file print"here's your file %r:" %filename print txt.read() #the "." (dot) is to add a command print"type the filename again:" file_again=raw_input(">") txt_again=open(file_again) print txt_again.read() txt.close() txt_again.close()
true
acedccda8b6286d03e1813e0df26c8ff05565e6b
danielgulloa/CTCI
/Python/Chapter1/check_Permutation.py
459
4.25
4
''' Implement a function which reverses a string (The original question is Implement a function void reverse(char+ str) in C or C++ which reverses a null-terminated string) ''' def reverse(mystring): newstr=""; n=len(mystring) for i in range(n): newstr+=mystring[n-i-1] return newstr; testCases=['anagram', 'hello', '', 'whatever', 'another test case'] for case in testCases: print "String: "+case+" is reversed and the result is "+reverse(case)
true
42e2b68c7dcf1e750f63220c8441f7296c337b37
HarishGajjar/Python-Projects-for-beginners
/calculator.py
416
4.28125
4
num1 = float(input("Enter first number: ")) op = input("Enter operator sign: ") num2 = float(input("Enter second number: ")) if op == "+": print(num1, "+", num2 ,"=", num1+num2) elif op == "-": print(num1, "-", num2 ,"=", num1-num2) elif op == "*": print(num1, "*", num2 ,"=", num1*num2) elif op == "/": print(num1, "/", num2 ,"=", num1/num2) else: print("Invalid input.Try again!")
false
980d1824dc8c6d9ecd0744025d777ccc0c559465
mcdonald5764/CTI110
/P5T2_FeetToInches_DarinMcDonald.py
492
4.3125
4
# Convert inches to feet # 10/30 # CTI-110 P5T2_FeetToInches # Darin McDonald # # Set a conversion value # Get input from the user on how many feet there are # Multiply feet and the conversion varible to get feet to inches # Display how many inches per foot inches_per_foot = 12 def main(): feet = int(input('Enter a number of feet: ')) print(feet, 'equals', feet_to_inches(feet), 'inches.') def feet_to_inches(feet): return feet * inches_per_foot main()
true
2b9f0439ddf165d662c5c8e9d351f23105e6adf5
mcdonald5764/CTI110
/P3HW2_Shipping_McDonald.py
1,215
4.375
4
# CTI-110 # P3HW2 - Shipping Charges # Darin McDonald # 9/27 # # Get a number of pounds input from the user # Check to see if the weight is less than or equal to 2 # Display the cost of the weight multipled by the first rate per pound # Check to see if the weight is more than 2 but less than or equal to 6 # Display the cost of the weight multipled by the second rate per pound # Check to see if the weight is more than 6 but less than or equal to 10 # Display the cost of the weight multipled by the third rate per pound # If none of these are true the weight is greater than 10 # Display the cost of the weight multipled by the last rate per pound print("Welcome to The Fast Freight Shipping Company!") weight = float(input("How much does the package way in pounds(lbs)?: ")) if weight <= 2: print("This package will cost $", format(weight * 1.50, '.2f'), "to ship!") elif weight > 2 and weight <= 6: print("This package will cost $", format(weight * 3.00, '.2f'), "to ship!") elif weight > 6 and weight <= 10: print("This package will cost $", format(weight * 4.00, '.2f'), "to ship!") else: print("This package will cost $", format(weight * 4.75, '.2f'), "to ship!")
true
39800d6716379faff17289213dbd0c9da03dca1b
Chayanonl3m/BlackBelt_level1
/workshop_assign/workshop1.py
351
4.40625
4
birthday ={ "Albert Einstein" : "9/12/1995", "Benjamin Franklin" : "16/2/1990", "Ada Lovelace" : "26/11/2011", } print ("Welcome to the birthday dictionary. We know the birthdays of: ") for key,value in birthday.items(): print (key) name = input("Who's birthday do you want to look up?") if name in birthday: print (name +"'s birthday is "+birthday[name])
false
3a05a1b5aa614dff3bc38af5550c24787799b870
gaul/src
/interview/needles.py
1,094
4.15625
4
#!/usr/bin/env python '''\ Given two strings, remove all characters contained in the latter from the former. Note that order is preserved. For example: "ab", "b" -> "a" "abcdabcd", "acec" -> "bdbd" What is the run-time of your algorithm? How much memory does it use? Is it optimal? linear search with memcpy: O(nh**2) linear search without memcpy: O(nh) sort then binary search: O(n log n + h log n) table lookup: O(n + h) ''' def remove_needles(haystack, needles): needles_set = frozenset(needles) return ''.join(c for c in haystack if c not in needles_set) def remove_needles_test(haystack, needles, expected): actual = remove_needles(haystack, needles) assert actual == expected def main(): remove_needles_test('', '', ''); remove_needles_test('a', '', 'a'); remove_needles_test('', 'a', ''); remove_needles_test('ab', 'b', 'a'); remove_needles_test('bab', 'b', 'a'); remove_needles_test('bab', 'a', 'bb'); remove_needles_test('abcdabcd', 'acec', 'bdbd'); if __name__ == '__main__': main()
true
08ac0896c2ba4ffa89ecccca61971fb93c1db3ab
negaryuki/phyton-class-2019
/Homework/Assignment - BMI.py
493
4.34375
4
print("Welcome to Negar's BMI calculator !\n (^o^)/") print('Please enter your weight(Kg):') weight = float(input()) print('Almost there, now please enter your height(m):') height = float(input()) BMI = weight / (height * height) print('and your BMI is: ', BMI) if BMI <= 18.5: print('Result is : Underweight :(') elif 18.5 < BMI <= 25: print('Result is : Normal :) Great !') elif 25 < BMI < 30: print('Result is : Overweight :(') else: print('Result is : Obesity :,((')
true
d078650393b437da6f97ab813e133f232c466912
kmusgro1/pythonteachingcode
/P1M4kristymusgrove.py
695
4.125
4
# [ ] create, call and test the str_analysis() function statement = "" def str_analysis(statement): while True: statement = input("enter a word or number: ") if statement.isdigit(): statement=int(statement) if statement > 99: print(statement,"is a big number") break else: print(statement,"is a small number") break else: if statement.isalpha(): print(statement,"is all alpha") break else: print(statement,"is neither a number or alpha") return statement str_analysis(statement)
true
e432237f67c107fe532b66635511262226b941be
vpc20/python-strings-and-things
/CharacterFrequency.py
1,473
4.28125
4
# Write a function that takes a piece of text in the form of a string and returns the letter # frequency count for the text. This count excludes numbers, spaces and all punctuation marks. # Upper and lower case versions of a character are equivalent and the result should all be in # lowercase. # # The function should return a list of tuples (in Python) or arrays (in other languages) # sorted by the most frequent letters first. Letters with the same frequency are ordered # alphabetically. For example: # # letter_frequency('aaAabb dddDD hhcc') # will return # # [('d',5), ('a',4), ('b',2), ('c',2), ('h',2)] from collections import Counter def letter_frequency(text): counter = Counter(''.join([ch for ch in text.lower() if ch.isalpha()])) l = list(tuple(counter.items())) l.sort(key=lambda x: (-x[1], x[0])) return l # from collections import Counter # from operator import itemgetter # # def letter_frequency(text): # items = Counter(c for c in text.lower() if c.isalpha()).items() # return sorted( # sorted(items, key=itemgetter(0)), # key=itemgetter(1), # reverse=True # ) # from collections import Counter # def letter_frequency(text): # return sorted(Counter(filter(str.isalpha, # text.lower()) # ).most_common(), # key=lambda t:(-t[1],t[0])) print(letter_frequency('abc b cc dd')) print(letter_frequency('wklv lv d vhfuhw phvvdjh'))
true
fea80af6d6eeaae82c2ca1dbdcc09824037d6a10
lorian-fate/environment
/FILE/files/proof_project.py
2,142
4.125
4
#Ejercicio 3 #Escribir un programa que guarde en un diccionario los precios de las frutas de la tabla, #pregunte al usuario por una fruta, un número de kilos y muestre por pantalla el precio #de ese número de kilos de fruta. Si la fruta no está en el diccionario debe mostrar un #mensaje informando de ello. #Fruta Precio #Plátano 1.35 #Manzana 0.80 #Pera 0.85 #Naranja 0.70 #platano : {'precio':19, 'peso':36} #=========================================================================== exit_number = 0 dictionary_fruits = {'sandia':{'WEIGHT':'12', 'PRICE':'$42'}, 'payaya':{'WEIGHT':'19', 'PRICE':'$14'}} while exit_number != 1: only_fruit_dictionary = {} list_fruits = ['WEIGHT', 'PRICE'] print('============================================================================') enter_number = int(input("1._Press '2' to add a new fruit: \n2._Press '3' to look for a fruit: \n4._Press '4' to see our stock: \n3._Press '1' to go out: \nSelect a option: ")) print('============================================================================') if enter_number == 2: fruin_name = input('Enter the fruit name: ') for i in list_fruits: fruit_data = input(F'Enter the {i}: ') only_fruit_dictionary[i] = fruit_data dictionary_fruits[fruin_name] = only_fruit_dictionary for key, value in dictionary_fruits.items(): print(key, value) print(only_fruit_dictionary) elif enter_number == 3: sedated_fruit = input('Enter the fruit name: ') if sedated_fruit in dictionary_fruits.keys(): print(f'{list(dictionary_fruits.keys())[list(dictionary_fruits.values()).index(dictionary_fruits[sedated_fruit])]}: {dictionary_fruits[sedated_fruit]}') else: print(f'We doesnt have the fruit requested: {sedated_fruit}') elif enter_number == 4: for key, value in dictionary_fruits.items(): print(key, value) elif enter_number == 1: break print('============================================================================') print('=========================== PROGRAM SHUTDOWN =============================') print('============================================================================')
false
3a71f044ad80d32140424a35875893031f4628a5
Enid-Sky/python-fundamentals
/appendMethod.py
729
4.75
5
# Call .append() on an existing list to add a new item to the end # With append you can add integers, dictionaries, tuples, floating points, and any objects. # Python lists reserve extra space for new items at the end of the list. A call to .append() will place new items in the available space. mixed = [1, 2] # initial list mixed.append(3) # integer mixed.append("flour") # string mixed.append(5.0) # float mixed.append({"greeting": "hello"}) # dictionary mixed.append((1, "hello", 5.0)) # tuple print(f'mixed: {mixed}') # NOTE: Using append is equivalent to the following operation # SLICE OPERATION: numbers = [1, 2, 3] numbers[len(numbers):] = 4 print(f'numbers: {numbers}')
true
4e81722ba13316ddac1e06937e2cd90648b46bbd
rlaecio/CursoEmVideo
/aulas/aula07a.py
658
4.125
4
n1 = float(input('Digite o primeiro numero: ')) n2 = float(input('Digite o segundo numero: ')) s = n1 + n2 print('A soma de {} e {} é igual a {}' .format(n1, n2, s)) s = n1 - n2 print('A subtração de {} por {} é igual {}' .format(n1, n2, s)) s = n1 * n2 print('A mutiplicação de {} por {} é igual a {}' .format(n1, n2, s)) s = n1 / n2 print('A divisão de {} e {} é igual a {}' .format(n1, n2, s)) s = n1 ** n2 print('A potencia de {} e {} é igual a {}' .format(n1, n2, s)) s = n1 // n2 print('A divisão inteira de {} e {} é igual a {}' .format(n1, n2, s)) s = n1 % n2 print('O resto da divisão de {} e {} é igual a {}' .format(n1, n2, s))
false
ed3dbf83cd4ff785dcff60effe7a85128d81f0bf
nniroula/Python_Data_Structures
/26_vowel_count/vowel_count.py
870
4.125
4
def vowel_count(phrase): """Return frequency map of vowels, case-insensitive. >>> vowel_count('rithm school') {'i': 1, 'o': 2} >>> vowel_count('HOW ARE YOU? i am great!') {'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1} """ new_dict = dict() for letters in phrase: letters = letters.lower() if letters == 'a': new_dict[letters] = phrase.count(letters) elif letters == 'e': new_dict[letters] = phrase.count(letters) elif letters == 'i': new_dict[letters] = phrase.count(letters) elif letters == 'o': new_dict[letters] = phrase.count(letters) elif letters == 'u': new_dict[letters] = phrase.count(letters) return new_dict print(vowel_count('rithm school')) print(vowel_count('HOW ARE YOU? i am great!'))
false
d3168910671560a02d8267ebf6dcecf09ef156b1
Eli-liang-liang/python_code
/Algorithms/queue.py
931
4.15625
4
class Queue(): # 初始化队列为空列表 def __init__(self): self.queue1 = [] # 判断队列是否为空,返回布尔值 def is_empty(self): pass # 返回队列头部元素(即将出队的那个) def top(self): return(self.queue1[0]) # 返回队列的大小 def size(self): return len(self.queue1) # 把新的元素堆进队列里面(程序员喜欢把这个过程叫做入队…) def enqueue(self, item): self.queue1.append(item) # 把队列头部元素弹出来(程序员喜欢把这个过程叫做出队……) def dequeue(self): self.queue1.pop(0) myqueue = Queue() myqueue.enqueue(9) myqueue.enqueue(7) myqueue.enqueue(1) myqueue.enqueue(8) myqueue.enqueue(2) print(myqueue.top()) myqueue.dequeue() print(myqueue.top()) myqueue.dequeue() print(myqueue.top()) myqueue.dequeue()
false
2d14fbb76b0c71fadb9a4ab965b5b6e3d31924dd
ellelater/Baruch-PreMFE-Python
/Level_1/Level_1_ROOT_FOLDER/1.2/1.2.10/n1.2.10.py
827
4.4375
4
""" This program demonstrates the time cost of creating lists with for-loop and comprehension. """ import time def main(): # 10a creates the list with for-loop start1 = time.time() lst1 = [] for i in range(10000000): if i % 10 == 0: lst1.append(i) print "Time cost of loop:", time.time() - start1 # 2.32 sec # 10b creates the list with comprehension start2 = time.time() lst2 = [i for i in range(10000000) if i % 10 == 0] print "Time cost of comprehension:", time.time() - start2 # 1.85 sec """ The comprehension is a little faster than for-loop because the program looks up the list and does an append operation in each iteration, whereas in comprehension the construction is done more compactly. """ if __name__ == '__main__': main()
true
6900f2506f65c3924e81c990fb17ad572af5f0f6
ellelater/Baruch-PreMFE-Python
/level4/4.1/4.1.1/4.1.1_main.py
2,468
4.5625
5
''' This program is to demonstrate string functions. ''' s = ' The Python course is the best course that I have ever taken. ' # 4.1.1 a Display the length of the string. print 'The length of the string is {0}'.format(len(s)) # 4.1.1 b Find the index of the first 'o' in the string. print "The index of the first 'o' in the string is {0}".format(s.find('o')) # 4.1.1 c Trim off the leading spaces only. print "To trim off the leading spaces only: {0}".format(s.lstrip()) # 4.1.1 d Trim off the trailing spaces only. print "To trim off the trailing spaces only: {0}".format(s.rstrip()) # 4.1.1 e Trim off both the leading and trailing spaces. ss = s.strip() # 4.1.1 f Fully capitalize the string. print "Fully capitalize the string: {0}".format(ss.upper()) # 4.1.1 g Fully lowercase the string. print "Fully lowercase the string: {0}".format(ss.lower()) # 4.1.1 h Display the number of occurrence of the letter 'd' and of the work 'the'. d = ss.find('d') the = ss.find('the') print "The number of occurrence of the letter 'd' is {0} and of the work 'the' is {1}".format(d, the) # 4.1.1 i Display the first 15 characters of the string. print "The first 15 characters of the string are {0}".format(ss[:15]) # 4.1.1 j Display the last 10 characters of the string. print "The last 10 characters of the string are {0}".format(ss[-10:]) # 4.1.1 k Display characters 5-23 of the string. print "Characters 5-23 of the string are {0}". format(ss[4:24]) # 4.1.1 l Find the index of the first occurrence of the word 'course'. print "The index of the first occurrence of the word 'course' is {0}".format(ss.find('course')) # 4.1.1 m Find the index of the second occurrence of the word 'course'. first_course = ss.find('course') print "The index of the second occurrence of the word 'course' is {0}".format(ss.find('course', first_course+1)) # 4.1.1 n Find the index of the second to last occurrence of the letter 't', # between the 7th and 33rd characters in the string. occ = [] for i in xrange(6, 33): # find the 7th to 33rd characters if ss[i] == 't': # use a loop to find the occurrence of 't' occ.append(i) print "The indexes of the second to last occurrence of the letter 't' " \ "between 7th and 33rd characters are {0}".format(occ[1:]) # 4.1.1 o Replace the period (.) with an exclamation point (!). print ss.replace('.', '!') # 4.1.1 p Replace all occurrences of the word 'course' with 'class'. print ss.replace('course', 'class')
true
0f518da02a2c3835460a45a752ab4a6f2cceddd3
530893915/Algorithm-and-data-structure-
/排序/快速排序(Python程序员面试算法宝典).py
1,329
4.15625
4
#coding:utf8 # 快速排序:通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。 # 从数列中挑出一个元素,称为 “基准”(pivot); # 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作; # 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。 # 这里的代码演示的是两头向中间扫描进行排序 def quick_sort(lists,left,right): if left >= right: return lists key = lists[left] low = left high = right while left < right: while left < right and lists[right] >= key: right -= 1 lists[left] = lists[right] while left < right and lists[left] <= key: left += 1 lists[right] = lists[left] lists[right] = key quick_sort(lists,low,left-1) quick_sort(lists,left+1,high) return lists lists = [84, 83, 88, 87, 61, 50, 70, 60, 80] print(quick_sort(lists,0,8))
false
d4b5a7c35bef700a79030ff18060cb42998b43d2
haibincoder/PythonNotes
/leetcode/478.py
1,451
4.28125
4
""" 478. 在圆内随机生成点 给定圆的半径和圆心的 x、y 坐标,写一个在圆中产生均匀随机点的函数 randPoint 。 说明: 输入值和输出值都将是浮点数。 圆的半径和圆心的 x、y 坐标将作为参数传递给类的构造函数。 圆周上的点也认为是在圆中。 randPoint 返回一个包含随机点的x坐标和y坐标的大小为2的数组。 示例 1: 输入: ["Solution","randPoint","randPoint","randPoint"] [[1,0,0],[],[],[]] 输出: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]] 示例 2: 输入: ["Solution","randPoint","randPoint","randPoint"] [[10,5,-7.5],[],[],[]] 输出: [null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]] """ from typing import List import random import math class Solution: def __init__(self, radius: float, x_center: float, y_center: float): self.x_center = x_center self.y_center = y_center self.redius = radius def randPoint(self) -> List[float]: while True: x_random = random.random() * self.redius y_random = random.random() * self.redius if math.pow(x_random-self.x_center, 2) + math.pow(y_random-self.y_center, 2) <= math.pow(self.redius, 2): result = [x_random, y_random] # 修改符号 return result if __name__ == "__main__": obj = Solution(2, 1, 1) print(obj.randPoint())
false
53fdc52d3af5394a3dcf8ace9ad9c3335b25a6da
haibincoder/PythonNotes
/leetcode/0867.py
913
4.3125
4
""" 给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。 矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。 示例 1: 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[[1,4,7],[2,5,8],[3,6,9]] 示例 2: 输入:matrix = [[1,2,3],[4,5,6]] 输出:[[1,4],[2,5],[3,6]] """ from typing import List class Solution: def transpose(self, matrix: List[List[int]]) -> List[List[int]]: if matrix is None: return [] width = len(matrix[0]) heigh = len(matrix) result = [[0 for i in range(heigh)] for j in range(width)] for col in range(heigh): for row in range(width): result[row][col] = matrix[col][row] return result if __name__ == "__main__": matrix = [[1,2,3],[4,5,6]] solution = Solution() print(solution.transpose(matrix=matrix))
false
318db59f35f6b6334ff53123ba857a79e7cd0be5
danielambr/Curso-Python
/Aula11.py
669
4.125
4
nome = str(input("Insira seu nome\n")).strip() #o método remove os espaços antes do nome print(f"Olá {nome}") nome2 = str(input("Insira seu nome\n")).strip("n") #o método remove os espaços print(f"Olá {nome2}") nome3 = str(input("Insira seu nome\n")).capitalize() #o método coloca a primeira letra em maiúsculo nome4 = str(input("Insira seu nome\n")).upper() # o método coloca todas as letras em maiúsculo # Para deixar o nome em minusculo utilizar o método lower() if nome3 == nome4: print(f"Os nomes: {nome3} e {nome4} são iguais") else: print(f"Os nomes: {nome3} e {nome4} são diferentes")
false
0f778b2a6514a9a7b2218dd688c789f8f09d70fd
bohdan-holodiuk/python_core
/lesson5/hw5/Counting_sheep.py
842
4.3125
4
""" Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present). For example, [True, True, True, False, True, True, True, True , True, False, True, False, True, False, False, True , True, True, True, True , False, False, True, True] """ def count_sheeps(sheep): """ :param sheep: :return: """ return sheep.count(True) if __name__ == '__main__': array1 = [True, True, True, False, True, True, True, True, True, False, True, False, True, False, False, True, True, True, True, True, False, False, True, True] print(count_sheeps(array1), 17, "There are 17 sheeps in total, not %s" % count_sheeps(array1))
true