blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
a31404839569a834ca98b6551ea8ef9e803df3e4
manhar336/manohar_learning_python_kesav
/Datatypes/sets/sets_methods.py
3,325
4.28125
4
#Union Method print("union method1:",set([1,2,3,4,5]).union(set((6,7,8,9)))) #it will combine 2 sets {1, 2, 3, 4, 5, 6, 7, 8, 9} a=(10,20,30,40) b=(40,50,60) print("union method2:",set(a).union(set(b))) #Intersection x=(10,20,30,40) y=(40,50,60) print("Intersection method",set(x).intersection(set(y))) #it will give common number #Difference print("Difference method:",set(x).difference(set(y))) #it will print only uniq values of set x,it will do difference and print only x which not exitst in y c=[1,2,3,4,5] d=[1,2,3,4,5,6,7] print("printing difference value",set(c).difference(set(d))) #Symmetric difference print("symmetric difference method",set(x).symmetric_difference(y)) #It will print uniq values of set x and uniq values of set y #Note:in difference print only uniq values of x and in symmetric difference print uniq value of x and uniq value of y #Update Method s1 = set([1,2,3,4,5]) s1.update(set([5,6,7])) print("update method",s1) #Intersection_update s2 = set([1,2,3,4,5]) s2.intersection_update([5,6,7]) print("intersection update",s2) #Note intersection update and intersection both are same #Different update s3=set([1,2,3,4,5]) s3.difference_update([5,6,7]) print("difference_update",s3) #Note in difference update it will print only uniq values #Symmetric difference update s4=set([1,2,3,4,5]) s4.symmetric_difference_update([5,6,7]) print("symmetric difference_update",s4) #Note in symmetric difference update it will print uniq values of 2 sets #add method s5 = set([1,2,3,4]) s5.add('test') print("add method",s5) #Remove method s6 = set([1,2,3,4]) s6.remove(4) print("remove method",s6) #if you want to remove element if its does not exist it will throw exception #Discard method s7 = set([1,2,3,4,5]) s7.discard(5) print("discard ",s7) s7.discard(8) print("discard ",s7) #Note in discard method if element does not exist it wont throw any exception but in remove method it will give type error #pop() method s8 = set([1,2,3,4,5]) s8.pop() #in set pop method it will delete 1st element but in list method it will delete last element print(s8) #in set pop method we can not pass argument if we pass it will thrpugh exception #issubset method() s9 = set([1,2,3,4]) print("is subset method:",s9.issubset(s9)) #Here condition is same means both sets have same value s10 = set([10,20,30]) s11 = set([6,7,8,9]) print("is subset method1:",s10.issubset(s9)) #Here 2 sets are different means values are not same ,so condition is false print("is subset method2:",s9.issubset(s11)) #Here condition is false s12 = set([10,20,30,40,50]) print("is subset method3:",s10.issubset(s12)) #Here condition is True #Issuperset method() s13 = set([1,2,3,4,5]) print("is superset method1",s13.issuperset([1,2,3,4,5])) #Here condition is True because both sets are mathcing s14 = set([1,2,3,4,5]) s15= set([1,2,3,4,5,6,7]) print("is superset method2:",s14.issuperset(s15)) ##Here condition is false because s14 set is not mathcing with s15 s16 = set([1,2,3,4,5,6,7]) s17= set([1,2,3,4]) print("is superset method3:",s16.issuperset(s17)) #Here condition is True because s16 elements are matching with s17 #Copy() method s18 = set([1,2,3,4,5,6,7]) s19 = s18.copy() print(s18,id(s18),type(s18)) print(s19,id(s19),type(s19)) print(s18 is s19) #condition is false because both have different id's
ef93cf0f13e5acde0d39c4ad424f0ace6d02d9a7
wcu201/Leetcode
/Google/Longest Consecutive Sequence.py
856
3.796875
4
''' Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Your algorithm should run in O(n) complexity. Example: Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. ''' class Solution: def longestConsecutive(self, nums: List[int]) -> int: dic = set(nums) maxCount = 0 while dic: key = dic.pop() count = 1 left, right = key-1, key+1 while left in dic: count+=1 dic.remove(left) left-=1 while right in dic: count+=1 dic.remove(right) right+=1 maxCount = max(maxCount, count) return(maxCount)
b607216b3145ce9e174b263209bb3f62a077f853
mfilipelino/python-notes
/sort/insertion.py
903
3.796875
4
from unittest import TestCase from sort.insertion import insertion_sort class TestInsertionSort(TestCase): def test_list_empty(self): self.assertEqual(insertion_sort([]), []) def test_list_one_item(self): self.assertEqual(insertion_sort([1]), [1]) self.assertEqual(insertion_sort(['a']), ['a']) def test_list_two_items(self): self.assertEqual(insertion_sort([1, 2]), [1, 2]) self.assertEqual(insertion_sort([2, 1]), [1, 2]) def test_list_multi_items(self): self.assertEqual(insertion_sort([1, 2, 3]), [1, 2, 3]) self.assertEqual(insertion_sort([1, 3, 2]), [1, 2, 3]) self.assertEqual(insertion_sort([3, 2, 1]), [1, 2, 3]) def test_list_multi_items(self): self.assertEqual(insertion_sort([5, 3, 1, 2, 4]), [1, 2, 3, 4, 5]) self.assertEqual(insertion_sort(['e', 'c', 'a', 'b', 'd']), list('abcde'))
ef6d1b80eeeba446f5322df4b171fecf0be72a1a
palindrome1311/Cracking-cracking-the-coding-interview
/8.2.py
1,155
3.8125
4
def getpath(mat): path=[] visited=set() rows = len(mat)-1 cols= len(mat[0])-1 if(isValid(mat,rows,cols,path,visited)): return path return None def isValid(mat,rows,cols,path,visited): #out of bounds check or obstacle check if(cols < 0 or rows < 0 or not mat[rows][cols]): return False point = (rows,cols) if(point in visited): return False print(point) atOrigin = (rows==0) or (cols==0) if(isValid(mat,rows - 1,cols, path,visited) or isValid(mat,rows,cols - 1, path,visited) or atOrigin ): path.append(point) return True visited.add(point) return False mat = [[ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 ], [ 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 ], [ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 ], [ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ], [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ], [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]] #top left to bottom right print(getpath(mat))
23f42b9f1825a55b58eeec6a85a13fdca1f00875
veeteeran/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/rectangle.py
4,550
3.59375
4
#!/usr/bin/python3 """Docstring for Rectangle class""" from models.base import Base class Rectangle(Base): """Rectangle class inherits from Base""" def __init__(self, width, height, x=0, y=0, id=None): """ Init method for Rectangle class Parameters: width: width of Rectangle height: height of Rectangle x: x value y: y value id: an id """ self.width = width self.height = height self.x = x self.y = y super().__init__(id) @property def width(self): """getter method for width""" return self.__width @width.setter def width(self, value): """ setter method with type and value check Parameter: value: width of rectangle """ if type(value) is not int: raise TypeError("width must be an integer") if value <= 0: raise ValueError("width must be > 0") self.__width = value @property def height(self): """getter method for height""" return self.__height @height.setter def height(self, value): """ setter method with type and value check Parameter: value: height of rectangle """ if type(value) is not int: raise TypeError("height must be an integer") if value <= 0: raise ValueError("height must be > 0") self.__height = value @property def x(self): """getter method for x""" return self.__x @x.setter def x(self, value): """ setter method with type and value check Parameter: value: x value of rectangle """ if type(value) is not int: raise TypeError("x must be an integer") if value < 0: raise ValueError("x must be >= 0") self.__x = value @property def y(self): """getter method for y""" return self.__y @y.setter def y(self, value): """ setter method with type and value check Parameter: value: y value of rectangle """ if type(value) is not int: raise TypeError("y must be an integer") if value < 0: raise ValueError("y must be >= 0") self.__y = value def area(self): """Return are of a rectangle""" return self.__width * self.__height def display(self): """Prints to stdout the Rectangle instance with the character #""" print('\n' * self.__y, end="") for row in range(self.__height): print(' ' * self.__x, end="") print('#' * self.__width) def __str__(self): """Override __str__ method""" s = "[Rectangle] ({:d}) {:d}/{:d} - {:d}/{:d}" s = s.format(self.id, self.__x, self.__y, self.__width, self.__height) return s def update(self, *args, **kwargs): """Assigns an argument to each Rectangle attribute""" my_list = [None, None, None, None, None] for i in range(len(args)): my_list[i] = args[i] if my_list[0] is not None: self.id = args[0] elif 'id' in kwargs: self.id = kwargs['id'] if my_list[1] is not None: self.__width = args[1] elif 'width' in kwargs: self.__width = kwargs['width'] if my_list[2] is not None: self.__height = args[2] elif 'height' in kwargs: self.__height = kwargs['height'] if my_list[3] is not None: self.__x = args[3] elif 'x' in kwargs: self.__x = kwargs['x'] if my_list[4] is not None: self.__y = args[4] elif 'y' in kwargs: self.__y = kwargs['y'] def to_dictionary(self): """Returns the dictionary representation of a Rectangle""" new_dict = {} for key in self.__dict__.keys(): if 'width' in key: new_dict['width'] = self.__dict__[key] elif 'height' in key: new_dict['height'] = self.__dict__[key] elif 'x' in key: new_dict['x'] = self.__dict__[key] elif 'y' in key: new_dict['y'] = self.__dict__[key] elif 'id' in key: new_dict['id'] = self.__dict__[key] return new_dict
fbb5837c706aaab28022b81ce89628c86fa7b6d2
srikanthpragada/PYTHON_27_AUG_2020
/demo/libdemo/thread_demo.py
328
3.8125
4
from threading import Thread class PrintThread(Thread): def run(self): for i in range(1, 11): print("Child", i) def print_numbers(): for i in range(1, 20): print(i) t1 = PrintThread() t1.start() t2 = Thread(target=print_numbers) t2.start() for n in range(1, 20): print("Main ", n)
8c190675df895f5d9a2885694f3930f2c4b4eac6
aroraakshit/coding_prep
/pacific_atlantic_water_flow.py
3,744
4.03125
4
class Solution(object): # 196ms, Credits - https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/90739/Python-DFS-bests-85.-Tips-for-all-DFS-in-matrix-question. def pacificAtlantic(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ if not matrix: return [] self.directions = [(1,0),(-1,0),(0,1),(0,-1)] m = len(matrix) n = len(matrix[0]) p_visited = [[False for _ in range(n)] for _ in range(m)] a_visited = [[False for _ in range(n)] for _ in range(m)] result = [] for i in range(m): # p_visited[i][0] = True # a_visited[i][n-1] = True self.dfs(matrix, i, 0, p_visited, m, n) self.dfs(matrix, i, n-1, a_visited, m, n) for j in range(n): # p_visited[0][j] = True # a_visited[m-1][j] = True self.dfs(matrix, 0, j, p_visited, m, n) self.dfs(matrix, m-1, j, a_visited, m, n) for i in range(m): for j in range(n): if p_visited[i][j] and a_visited[i][j]: result.append([i,j]) return result def dfs(self, matrix, i, j, visited, m, n): # when dfs called, meaning its caller already verified this point visited[i][j] = True for dir in self.directions: x, y = i + dir[0], j + dir[1] if x < 0 or x >= m or y < 0 or y >= n or visited[x][y] or matrix[x][y] < matrix[i][j]: continue self.dfs(matrix, x, y, visited, m, n) # 104ms, Credits: leetcode: same idea, launch DFS from two edges per ocean, amazing design! class Solution: def pacificAtlantic(self, matrix: 'List[List[int]]') -> 'List[List[int]]': if not matrix: return [] r = len(matrix) c = len(matrix[0]) visitedP = [[False]*c for i in range(r)] visitedA = [[False]*c for i in range(r)] stackP=[] stackA=[] for i in range(c): stackP.append([0,i]) stackA.append([r-1,i]) for i in range(1,r): stackP.append([i,0]) for i in range(r-1): stackA.append([i,c-1]) while(stackP): i,j = stackP.pop() visitedP[i][j]=True if((i+1)<r and matrix[i][j]<=matrix[i+1][j] and not visitedP[i+1][j]): stackP.append([i+1,j]) if((i-1)>=0 and matrix[i][j]<=matrix[i-1][j] and not visitedP[i-1][j]): stackP.append([i-1,j]) if((j+1)<c and matrix[i][j]<=matrix[i][j+1] and not visitedP[i][j+1]): stackP.append([i,j+1]) if((j-1)>=0 and matrix[i][j]<=matrix[i][j-1] and not visitedP[i][j-1]): stackP.append([i,j-1]) while(stackA): i,j = stackA.pop() visitedA[i][j]=True if((i+1)<r and matrix[i][j]<=matrix[i+1][j] and not visitedA[i+1][j]): stackA.append([i+1,j]) if((i-1)>=0 and matrix[i][j]<=matrix[i-1][j] and not visitedA[i-1][j]): stackA.append([i-1,j]) if((j+1)<c and matrix[i][j]<=matrix[i][j+1] and not visitedA[i][j+1]): stackA.append([i,j+1]) if((j-1)>=0 and matrix[i][j]<=matrix[i][j-1] and not visitedA[i][j-1]): stackA.append([i,j-1]) outlist=[] for i in range(r): for j in range(c): if visitedP[i][j] and visitedA[i][j]: outlist.append([i,j]) return outlist
c1175e91542c3a0d9351d30096253073c43f0c10
alex-stefa/thor
/thor/enum.py
2,266
3.75
4
#!/usr/bin/env python """ Simple enumeration type implementation in Python """ __author__ = "Alex Stefanescu <alex.stefa@gmail.com>" __copyright__ = """\ Copyright (c) 2013 Alex Stefanescu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # see http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python def enum(*sequential, **named): """ Creates an enumeration. Can receive both sequential and named parameters. Example: Numbers = enum('ONE', 'TWO', 'THREE', FOUR='four', FIVE=555) Numbers.ONE >> 0 Numbers.TWO >> 1 Numbers.THREE >> 2 Numbers.FOUR >> 'four' Numbers.FIVE >> 555 Numbers.str[Numbers.ONE] >> 'ONE' Numbers.str[0] >> 'ONE' Numbers.str[Numbers.FOUR] >> 'FOUR' Numbers.str['four'] >> 'FOUR' Numbers.values >> [0, 1, 2, 'four', 555] Numbers.keys >> ['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE'] """ enums = dict(list(zip(sequential, list(range(len(sequential))))), **named) reverse = dict((value, key) for key, value in enums.items()) enums['str'] = reverse enums['values'] = reverse.keys() enums['keys'] = reverse.values() return type('Enum', (), enums)
643d48b116918c8b7096936e0830723a3775fb33
alui07/Technical-Interview
/LeetCode/Python/NumSquares.py
891
3.6875
4
""" 279. Perfect Squares Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. """ class Solution(object): def numSquares(self, n): """ :type n: int :rtype: int """ if n == 1: return 1 nums, root = [1], int(math.sqrt(n)) for i in range(1, n): factors = [] for j in range(1, root+1): if j**2-1 == i: factors.append(1) elif i-j**2 >= 0: factors.append(nums[i-j**2] + 1) else: break nums.append(min(factors)) return nums[n-1]
be03b227f58829ab907a993e0f655e25e77f03c6
kamojiro/atcoderall
/beginner/079/B.py
121
3.71875
4
N = int(input()) a = 2 b = 1 if N == 1: print(1) else: for _ in range(N-1): a, b = b, a + b print(b)
1259bffe8240c1b0523bb816565829db10d6caaa
Godsmith/adventofcode
/aoc/year2020/day15/day15.py
484
3.609375
4
def last_number2(numbers, count): locations = {} for i, number in enumerate(numbers): locations[number] = i while len(numbers) < count: numbers.append(len(numbers) - 1 - locations[numbers[-1]] if numbers[-1] in locations else 0) locations[numbers[-2]] = len(numbers) - 2 return numbers[-1] print(last_number2([0, 5, 4, 1, 10, 14, 7], 2020)) print(last_number2([0, 5, 4, 1, 10, 14, 7], 30000000))
516c66837f0cc8948eb6e5350ecfb16b8b0e9530
DaVinci42/LeetCode
/19.RemoveNthNodeFromEndofList.py
771
3.796875
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: if not head or n < 1: return None right = head for _ in range(0, n - 1): if right.next: right = right.next else: return None left: ListNode = None while right.next: right = right.next if left == None: left = head else: left = left.next if not left: return head.next else: left.next = left.next.next return head
a1425d169f8a5819814a64b7d53a3b005186bd6c
WangGewu/LeetCode
/python/007.py
346
3.546875
4
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ x = str(x) x=x[::-1] if x[-1]=='-': x='-'+x res=int(x[0:-1]) else: res=int(x) if -2**31<res<2**31-1: return res return 0
6c021f5e56a5e078a0bf896e74492bc5f77bd231
zhiyunl/lcSolution
/0020validParentheses.py
1,951
3.90625
4
""" Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true Idea: 1. traditionally, use stack, push when (, [, {, pop when ),],}. 2. if there is only '(' and ')', we can use a simple counting method map '(' to +1, and ')' to -1. linear scan counting, cnt should be non-negative along the way, zero when terminating. 3. extend to all types. use cnt[3] to monitor each type ( [ { consider "([)]", record the lru type, should be cleared first before clearing other type. recursion is needed, which is not efficient. """ class Solution: def isValid(self, s: str) -> bool: stack = [] m = { '{': '}', '[': ']', '(': ')' } for i in s: if i in m: stack.append(m[i]) # push the back one for comparing later else: if len(stack) == 0: return False else: elem = stack.pop() if i != elem: return False else: continue return len(stack) == 0 def isBalancedSimple(self, s: str) -> bool: m = { '(': 1, ')': -1, } cnt = 0 for i in s: cnt = cnt + m[i] if cnt < 0: return False return cnt == 0 teststr = "[(())]" paraTest = "(((())))" sol = Solution() print(sol.isBalancedSimple(s=paraTest))
ad904dadfd53c96771768a93980804b15297a816
akashghanate/OpenCV
/imageManipulation/thresholding.py
1,393
3.875
4
#thresholding is converting an image into it's binary form #cv2.threshold(image, Threshold value, Max value, Threshold type) #NOTE: image is first converted to grayscale before thresholding import cv2 import numpy as np # threshold types # cv2.THRESH_BINARY # cv2.THRESH_BINARY_INV # cv2.THRESH_TRUNC # cv2.THRESH_TOZERO # cv2.THRESH_TOZERO_INV input=cv2.imread('/home/akashkg/OpenCV/images/shapes.png',0) cv2.imshow("Original",input) cv2.waitKey() #vlaues below 127 goes to 0 (black) everything above goes to 255 (white) ret,thres=cv2.threshold(input,127,255,cv2.THRESH_BINARY) cv2.imshow("Threshold Binary",thres) cv2.waitKey() #vlaues below 127 goes to 255 everything above goes to 0 (reverse of above) ret,thres=cv2.threshold(input,127,255,cv2.THRESH_BINARY_INV) cv2.imshow("Threshold Binary Inverse",thres) cv2.waitKey() #vlaues above 127 are truncated (held) at 127 ret,thres=cv2.threshold(input,127,255,cv2.THRESH_TRUNC) cv2.imshow("Threshold TRUNC",thres) cv2.waitKey() #vlaues below 127 goes to 0, above are unchanged ret,thres=cv2.threshold(input,127,255,cv2.THRESH_TOZERO) cv2.imshow("Threshold TOZERO",thres) cv2.waitKey() #vlaues below 127 are unchanged , above goes to 0 ret,thres=cv2.threshold(input,127,255,cv2.THRESH_TOZERO_INV) cv2.imshow("Threshold TOZERO Inverse",thres) cv2.waitKey() cv2.destroyAllWindows() #better way is using adaptive thresholding
5bfd5cec22633300b2704fef578b15e8d5ffc551
Nyapy/TIL
/04_algorithm/Programmers/거듭제곱.py
294
3.75
4
three = [0] n = 9 num = 0 length = 0 while num < n: tem = 3**num tem_list = [] for i in three: tem_list.append(tem+i) length += 1 if length == n : break three = three + tem_list if length == n: break num+= 1 print(three[n])
71a652032cedf5dd889990cd89bad96b82f0be93
valmsmith39a/u-data-structures-algorithms
/p1-text-calls/Task3.py
5,111
4.1875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixed line telephones in Bangalore. Fixed line numbers include parentheses, so Bangalore numbers have the form (080)xxxxxxx.) Part A: Find all of the area codes and mobile prefixes called by people in Bangalore. - Fixed lines start with an area code enclosed in brackets. The area codes vary in length but always begin with 0. - Mobile numbers have no parentheses, but have a space in the middle of the number to help readability. The prefix of a mobile number is its first four digits, and they always start with 7, 8 or 9. - Telemarketers' numbers have no parentheses or space, but they start with the area code 140. Print the answer as part of a message: "The numbers called by people in Bangalore have codes:" <list of codes> The list of codes should be print out one per line in lexicographic order with no duplicates. Part B: What percentage of calls from fixed lines in Bangalore are made to fixed lines also in Bangalore? In other words, of all the calls made from a number starting with "(080)", what percentage of these calls were made to a number also starting with "(080)"? Print the answer as a part of a message:: "<percentage> percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore." The percentage should have 2 decimal digits """ """ Own Notes Part A: # Find the telephone codes called by fixed line numbers in Banglore # Get all calls with outbound numbers from fixed lines from Bangalore # From calls from Bangalore, get the codes from the inbound numbers # fixed line: check for 0 # mobile: check for 7, 8, 9 # telemarketers: check for 140 # one per line # lexicographic order (abc) with no duplicates Steps: # iterate through each call # in each outbound number, look for Bangalore # get the inbound number for the call from Bangalore # get the code from the inbound number """ FIXED_BANGALORE = '080' TELE_CODE = '140' FIXED = ('0') MOBILE = ('7', '8', '9') TELE = ('140') numbers_called_by_fixed_bangalore = [] codes = [] # Get all called-to numbers (inbound) with called-from numbers (outbound) from Bangalore for call in calls: number_from = call[0] number_to = call[1] if number_from.startswith('('): fixed_area_code = number_from[number_from.find('(')+1: number_from.find(')')] if fixed_area_code == FIXED_BANGALORE: numbers_called_by_fixed_bangalore.append(number_to) # Get the codes from the numbers called by fixed line numbers from Bangalore for num in numbers_called_by_fixed_bangalore: if num.startswith('('): fixed_area_code = num[num.find('(')+1: num.find(')')] codes.append(fixed_area_code) elif num.startswith(MOBILE): mobile_code = num[: num.find(' ') - 1] codes.append(mobile_code) elif num.startswith(TELE): codes.append(TELE_CODE) # remove duplicates codes = list(set(codes)) codes.sort(key=int) print('PART A') print('\n') print('The numbers called by people in Bangalore have codes:') for code in codes: print(code) """ TASK 3A Runtime Analysis Get the numbers called by fixed lines in Bangalore, the for loop takes O(a) time. Get the codes from the numbers called by fixed lines in Bangalore, the for loop takes O(b) time. Filter out duplicate numbers by using Python's set function which takes O(c) time Construct a list by using Python's list function which takes O(d) time https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt Runtime is: O(a) + O(b) + O(c) + O(d) Simplify by taking the largest number of elements (a), runtime is O(a). """ """ Part B (own notes): What percentage of calls from fixed lines in Bangalore are made to fixed lines also in Bangalore? In other words, of all the calls made from a number starting with "(080)", what percentage of these calls were made to a number also starting with "(080)"? Fixed Lines also in Bangalore / Calls from fixed lines in bangalore Objective: Find percentage of calls from Bangalore are also to Bangalore Steps: # Find all calls from Bangalore # Of the calls from Bangalore, find the calls that are also to Bangalore # Compute percentage """ BANGALORE = '(080)' number_of_calls_from_bangalore = 0 number_of_calls_from_and_to_bangalore = 0 for call in calls: call_from = call[0] if BANGALORE in call_from: number_of_calls_from_bangalore += 1 call_to = call[1] if BANGALORE in call_to: number_of_calls_from_and_to_bangalore += 1 percent_of_calls_from_bangalore_to_bangalore = round(number_of_calls_from_and_to_bangalore / number_of_calls_from_bangalore, 2) * 100 print('\n') print('PART B') print('{} percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore.'.format(percent_of_calls_from_bangalore_to_bangalore)) """ TASK 3B Runtime Analysis For loop takes O(n) time """
6b1d067686afd07990f44a105ba34999f0dd2206
ZhangShuang666/course_system
/src/service/admin_service.py
1,483
3.84375
4
from src.models import School, Teacher def create_school(): school_name = input("请输入学校名称:") obj = School(school_name) obj.save() def show_school(): print("=========学校========") school_list = School.get_all_school_list() for item in school_list: print(item.schoolName) def create_teacher(): print("=========创建老师========") print("学校列表") school_list = School.get_all_school_list() for k, obj in enumerate(school_list, 1): print(k, obj) sid = int(input("请选择学校选项:")) school_obj = school_list[sid-1] name = input("请输入教师姓名") teacher_obj = Teacher(name, school_obj.nid) teacher_obj.save() def show_teacher(): print("=========教师列表========") teacher_list = Teacher.get_all_teacher_list() for item in teacher_list: print(item) def show_choice(): show = """ 1. 创建学校 2. 查看学校 3. 创建老师 4. 查看老师 """ print(show) def main(): choice_list = { '1': create_school, '2': show_school, '3': create_teacher, '4': show_teacher, } show_choice() while True: choice = input("请输入选项:") if choice not in choice_list: print("输入错误,请重新选择") continue func = choice_list[choice] func() if __name__ == '__main__': main()
c201fea752866167819c4cbe68fa483ff591f4db
Kyrk/Automate-the-Boring-Stuff-Code
/Chapter 7 - Pattern Matching with Regular Expressions/pwStrength.py
1,672
4.53125
5
#!/usr/bin/env python3 '''Program with function that uses regular expressions to make sure the password string passed as a parameter is strong. A 'strong' password contains the following: - At least 8 characters long - Contains both uppercase and lowercase characters - Contains at least one digit ''' import re def pwStrength(pw): # Regexs lenRegex = re.compile(r'\w{8,}') upperRegex = re.compile(r'[a-z]') lowerRegex = re.compile(r'[A-Z]') numRegex = re.compile(r'\d') strength = 0 # Check password length if lenRegex.search(pw) == None: print('Password should be at least 8 characters long.') else: strength += 1 # Check for both uppercase and lowercase characters if upperRegex.search(pw) == None or lowerRegex.search(pw) == None: print('Password should contain both uppercase and lowercase', 'characters.') else: strength += 1 # Check for at least one digit if numRegex.search(pw) == None: print('Password should contain at least one digit.') else: strength += 1 # Print strength results if strength == 0: print('Your password sucks.') elif strength == 1: print('Your password is weak.') elif strength == 2: print('Your password is okay.') elif strength == 3: print('Your password is strong.') print() # Test cases pwStrength('witch') # 0 pwStrength('witch1') # 1 pwStrength('Witch') # 1 pwStrength('witchbby') # 1 pwStrength('witch123') # 2 pwStrength('Witch1') # 2 pwStrength('Witchbby') # 2 pwStrength('Witch123') # 3 pwStrength('Witch1234') # 3
ef3354d49c9e4fe1024ec3357b5018b4e9333189
FunWithPythonProgramming/coding-bat-exercises
/week_1_Jan_28/lucky_sum/miguel_lucky_sum_solution.py
315
3.859375
4
def lucky_sum(int_one, int_two, int_three): if int_one == 13: return 0 elif int_two == 13: return int_one elif int_three == 13: return int_one + int_two else: return int_one + int_two + int_three lucky_sum(1, 2, 3) # 6 lucky_sum(1, 2, 13) # 3 lucky_sum(1, 13, 3) # 1
1f7ae9a68384675289ffdff7a60cd721370cda61
AndresNunezG/ejercicios_python_udemy
/ejercicio_17.py
647
4.03125
4
""" Ejercicio 17. - Escribir una lista que encuentre el menor número de una lista """ #Lista a determinar el menor elemento lista = [12, 20, 17, 21, -16, 21, 2.0, -2.3, 0] #Determinar menor elemento def lista_menor(lista): min_elem = 10e6 indice = 0 for ind, num in enumerate(lista): if num < min_elem: min_elem = num indice = ind return (min_elem, indice) menor, indice = lista_menor(lista) print(f'De la lista {lista}') print(f'El menor elemento es {menor}, en la posición {indice + 1}') #También se puede usar el método min() print('El elemento mínimo de la lista es: ', min(lista))
ae9175050cd84fc23102e5f4d3f0f523991ac686
connorourke/lammps_potenial_fitting
/bond_types.py
1,011
3.65625
4
class BondType(): """ Class for each bond type. """ def __init__(self, bond_type_index, label, spring_coeff_1, spring_coeff_2): """ Initialise an instance for each bond type in the structure. Args: bond_type_index (int): Integer value given for the bond type. label (str): Identity of the bond atoms format "element_1_index-element_2_index spring", where element_1 is the core, and element_2 is the shell. Returns: None """ self.bond_type_index = bond_type_index self.label = label self.spring_coeff_1 = spring_coeff_1 self.spring_coeff_2 = spring_coeff_2 def bond_string(self): return_str = 'bond_coeff {} {:6.2f} {:6.2}'.format(self.bond_type_index, self.spring_coeff_1, self.spring_coeff_2) return return_str
73d48b983bf412caac2783a231d403ea0bd3983f
KarinaMapa/Exercicios-Python-Decisao
/ex.11.py
737
3.828125
4
salario = float(input('Digite seu salário: ')) if salario <= 280: novo_salario = (salario*1.2) aumento = 20 diferenca = novo_salario-salario elif 280 < salario < 700: novo_salario = (salario*1.15) aumento = 15 diferenca = novo_salario-salario elif 700 < salario < 1500: novo_salario = (salario*1.1) aumento = 10 diferenca = novo_salario-salario else: novo_salario = (salario*1.05) aumento = 5 diferenca = novo_salario-salario print('Seu salário antes do reajuste era de: R$ {:.2f}'.format(salario)) print('O percentual de aumento aplicado foi de: {}%'.format(aumento)) print('O aumento foi de R$ {:.2f}'.format(diferenca)) print('Seu novo salário é de R$ {:.2f}'.format(novo_salario))
1108ca9aa8bd18026389658239903670218c2d8e
leson238/python
/Student projects/Restaurant/backend.py
3,019
3.96875
4
class Restaurant: def __init__(self, name, address, average_price, distance, nationality): self.name = name self.address = address self.average_price = average_price self.distance = distance self.nationality = nationality def __str__(self): return f"{self.name} : {self.address} {self.average_price}$ {self.distance} miles {self.nationality}" class Restaurants: def __init__(self): self._add_restaurant() def _add_restaurant(self): self.restaurant_list = [] with open('restaurants.txt', 'r') as f: while True: line = f.readline() try: name, address, price, distance, nationality = line.split( ',') price = float(price) distance = float(distance) self.restaurant_list.append(Restaurant( name, address, price, distance, nationality)) except ValueError: break def view(self): return self.restaurant_list def search_by_location(self, n=3): sort_by_location = sorted( self.restaurant_list, key=lambda x: x.distance) return sort_by_location[:min(n, len(sort_by_location))] def search_by_price(self, n=3, lowest=True): sort_by_price = sorted(self.restaurant_list, key=lambda x: x.average_price) if lowest: return sort_by_price[:min(n, len(sort_by_price))] return sort_by_price[-min(n, len(sort_by_price)):] def search(self, name, address, avgp, distance, nation): result = [] if name: result += [r for r in self.restaurant_list if ( name.lower() in r.name.lower())] if address: if result: result = [r for r in result if ( address.lower() in r.address.lower())] else: result += [r for r in self.restaurant_list if ( address.lower() in r.address.lower())] if nation: if result: result = [r for r in result if ( nation.lower() in r.nationality.lower())] else: result += [r for r in self.restaurant_list if ( nation.lower() in r.nationality.lower())] if avgp: if result: result = [r for r in result if r.average_price <= float(avgp)] else: result += [r for r in self.restaurant_list if r.average_price <= float(avgp)] if distance: if result: result = [r for r in result if r.distance <= float(distance)] else: result += [r for r in self.restaurant_list if r.distance <= float(distance)] return list(set(result))
bcd9ff9e967c67c0b0ac2c5306b7b141ffa86912
JerryChii/PycharmProjects
/QuickStart/FunctionTest.py
1,381
4.09375
4
#!/usr/bin/python # -*- coding: UTF-8 -*- print '======================================' # 给变量赋初值 def printinfo(name, age = 10): "打印任何传入的字符串" print "Name: ", name print "Age ", age return # 指定变量名赋值 printinfo(age=50, name="miki") # 不定长参数 def printinfo(arg1, *vartuple): "打印任何传入的参数" print "输出: " print arg1 for var in vartuple: print var return # 调用printinfo 函数 printinfo(10) printinfo(70, 60, 50) print '======================================' #lambda sum = lambda arg1, arg2 : arg1 + arg2 print sum("a", "b") print '======================================' import sys print sys.path # !/usr/bin/python # -*- coding: UTF-8 -*- print '======================================' Money = 2000 def AddMoney(): #Money += 1是一个表达式,这说明默认已经声明了一个局部变量Money # 想改正代码就取消以下注释: global Money Money += 1 print Money AddMoney() print Money #或者这样 def AddMoney(): Money = 1 Money += 1 print Money AddMoney() print Money print '======================================' import math content = dir(math) print content print '======================================' tetkk = 100 def tet(): kk = 1 print globals().keys() print locals().keys() tet()
8b28cd817abc775a86d102aefc63d649bb8c1ff7
daniel-reich/ubiquitous-fiesta
/t2WH2HdrQhCcJrezL_11.py
235
3.546875
4
def eda_bit(start, end): s = [] for i in range(start,end+1): if i%3==0 and i%5==0: s.append('EdaBit') elif i%3==0: s.append('Eda') elif i%5==0: s.append('Bit') else: s.append(i) return s
25ea922f2490c1aa7964472c7ba340ab04f3549a
Fettes/PythonLearning
/Yield/try_yield_01.py
191
3.765625
4
def fab(max_num): n1, a, b = 0, 0, 1 while n1 < max_num: yield b # 使用 yield # print b a, b = b, a + b n1 = n1 + 1 for n in fab(5): print(n)
8cbf4dc8dbeaed221143a80522ac885ced51697c
apatel3112/SC_FinalProject
/Movie_GUI.py
24,425
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 6 15:48:09 2019 @author: Anusha """ """ Created on Mon Dec 2 16:38:47 2019 This file creates a GUI application that allows for user input of movie paramteres on mupltiple pages @author: bento """ import tkinter as tk from tkinter import font as tkfont from PIL import Image, ImageTk class Genre_Button(): ''' This class creates allows for the creation of a checkbutton to be put onto the genre page inputs: frame- the page frame that the button will be added to image_file - image to added too checkbutton text - text describing button font - font of text row - row # on genre page col - column # on genre page hg - highlight background color of button padx - horizantal spacing around button pady - vertical spacing around button bg - button background color w - width of image on button h - height if image on button cs - column span of button outputs: checkbutton added to page ''' def __init__(self, frame, image_file, text, font, row, col, hg, padx, pady, bg, w, h, cs): # resize the original input image image_resize(image_file, w, h) self.text = text self.image = Image.open(image_file) self.image = ImageTk.PhotoImage(self.image) # define var to store 0 or 1 for if button is checked or not self.var = tk.IntVar() # generate checkbutton self.gen_button = tk.Checkbutton(frame, text=text, image=self.image, font=font, compound=tk.TOP, variable=self.var, highlightbackground=hg, borderwidth=2, bg=bg) # specify button position on page self.gen_button.grid(row=row, column=col, padx=padx, pady=pady, columnspan=cs) def image_resize(image, new_width, new_height): ''' this function takes in an image and resizes to the specified width and height ''' # open image as object and assign to var img img = Image.open(image) # set resize ratios based on the new width and height width, height = img.size a = width/new_width b = height/new_height # resize image based on resize ratios img = img.resize((int(width/a), int(height/b))) # save image under its original file_name img.save(image) class Movie_GUI(tk.Tk): ''' this class runs sets up the GUI window and stack page frames so that the user may move from page to page ''' def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title("What to Watch") self.title_font = tkfont.Font(family='Helvetica', size=24, weight="bold", slant="italic") # page fonts self.gen_font = tkfont.Font(size=12) self.entry_font = tkfont.Font(size=12) self.decade_font = tkfont.Font(size=15) #self.attributes('-fullscreen', True) self.configure(background='white') self.start_page_font = tkfont.Font(size=15) # stack page frames in container and raise the frame being used # to the top of the stack container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne, PageTwo, PageThree, PageFive, PageSix, PageSeven, PageEight, PageNine): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame("StartPage") def show_frame(self, page_name): '''raise the page_name frame to the top of the container ''' frame = self.frames[page_name] frame.tkraise() def close(self): ''' close the GUI window ''' self.destroy() class StartPage(tk.Frame): ''' this class defines the first page of the GUI and allows the user to visit all other pages by clicking on their page name ''' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Sorting Categories", bg="white", font=controller.title_font) label.grid(row=0, column=1) self.configure(background='white') w = 40 h = 6 bg = "dark grey" sticky = None font = controller.start_page_font # creat button for each page and set command to show page button1 = tk.Button(self, text="Movie/TV", width=w, height=h, font=font, bg=bg, command=lambda: controller.show_frame("PageOne")) button1.grid(row=1, column=0, pady=30, padx=40, sticky=sticky) button2 = tk.Button(self, text="Genre", width=w, height=h, font=font, bg=bg, command=lambda: controller.show_frame("PageTwo")) button2.grid(row=1, column=1, pady=20, sticky=sticky) button3 = tk.Button(self, text="Time Span",width=w, height=h, font=font, bg=bg, command=lambda: controller.show_frame("PageThree")) button3.grid(row=1, column=2, pady=20, padx=40, sticky=sticky) button5 = tk.Button(self, text="Movies/TV Match", width=w, height=h, font=font, bg=bg, command=lambda: controller.show_frame("PageFive")) button5.grid(row=2, column=0, pady=20, sticky=sticky) button6 = tk.Button(self, text="Actor Match", width=w, height=h, font=font, bg=bg, command=lambda: controller.show_frame("PageSix")) button6.grid(row=2, column=1, pady=20, padx=40, sticky=sticky) button7 = tk.Button(self, text="Director Match", width=w, height=h, font=font, bg=bg, command=lambda: controller.show_frame("PageSeven")) button7.grid(row=2, column=2, pady=20, padx=40, sticky=sticky) button8 = tk.Button(self, text="Rating", width=w, height=h, font=font, bg=bg, command=lambda: controller.show_frame("PageEight")) button8.grid(row=3, column=0, columnspan=2, pady=20, sticky=sticky) button9 = tk.Button(self, text="Movie/TV Length", width=w, height=h, font=font, bg=bg, command=lambda: controller.show_frame("PageNine")) button9.grid(row=3, column=1, columnspan=2, pady=20, padx=40, sticky=sticky) button10 = tk.Button(self, text="Submit", width=25, height=3, font=font, bg=bg, command=controller.close) button10.grid(row=4, column=1, padx=10, pady=20, sticky=sticky) self.grid_columnconfigure((0, 1, 2), weight=1) self.grid_rowconfigure((0, 1, 2, 3), weight=1) class PageOne(tk.Frame): ''' this class defines the first input page where the user checks a box for Movie or TV, and each box input is stored in two variables ''' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(background='white') label = tk.Label(self, text="Movie or TV?", font=controller.title_font, bg="white") label.grid(row=0, column=0, columnspan=2) bg = "dark gray" button = tk.Button(self, text="Back to HomePage", width=30, height=3, bg=bg, command=lambda: controller.show_frame("StartPage")) button.grid(row=2, column=0, columnspan=2) next_button = tk.Button(self, text="Next Page>", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageTwo")) next_button.grid(row=2, column=1, pady=10) prev_button = tk.Button(self, text="<Previous Page", width=30, height=3, bg=bg, command=lambda: controller.show_frame("StartPage")) prev_button.grid(row=2, column=0, pady=10) w = 380 h = 300 image_resize("Movie.jpg", w, h) movie_image = Image.open("Movie.jpg") self.moviephoto = ImageTk.PhotoImage(movie_image) bg = 'white' global movie_var, TV_var movie_var = tk.IntVar() movie = tk.Checkbutton(self, text='Movie', variable=movie_var, image=self.moviephoto, padx=35, bg=bg, borderwidth=2) movie.grid(row=1, column=0, padx=20, pady=10) image_resize("TV.png", w, h) TVimage = Image.open("TV.png") self.TVphoto = ImageTk.PhotoImage(TVimage) TV_var = tk.IntVar() tv = tk.Checkbutton(self, text='TV', variable=TV_var, image=self.TVphoto, padx=35, bg=bg, borderwidth=2) tv.grid(row=1, column=1, padx=20, pady=10) self.grid_columnconfigure((0, 1), weight=1) self.grid_rowconfigure((0, 1, 2), weight=1) class PageTwo(tk.Frame): ''' This class allows the user input of genre and stores the results ''' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(background='white') bg = "dark gray" label = tk.Label(self, text="Genres", font=controller.title_font, bg="white").grid(row=0, column=3) button = tk.Button(self, text="Back to HomePage", width=30, height=3, bg=bg, command=lambda: controller.show_frame("StartPage")) button.grid(row=5, column=3, pady=10) prev_button = tk.Button(self, text="<Previous Page", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageOne")) prev_button.grid(row=5, column=1, pady=10, columnspan=2) next_button = tk.Button(self, text="Next Page>", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageThree")) next_button.grid(row=5, column=4, pady=10, columnspan=2) w = 118 h = 79 hg = "black" padx = 40 pady = 20 bg = "white" global genre_var genre_var = [0]*27 row = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4] col = [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5] cs = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2] genre_pic = ['Documentary', 'Short', 'Animation', 'Comedy', 'Romance', 'Sport', 'Action', 'News', 'Drama', 'Fantasy', 'Horror', 'Music', 'War', 'Crime', 'Western', 'Sci-Fi', 'Family', 'Adventure', 'History', 'Biography', 'Mystery', 'Thriller', 'Musical', 'Film Noir', 'Game Show', 'Talk Show', 'Reality TV'] font = controller.gen_font for i in range(len(genre_var)): genre_var[i] = Genre_Button(self, genre_pic[i]+'.png', genre_pic[i], font=font, row=row[i], col=col[i], padx=padx, pady=pady, bg=bg, w=w, h=h, hg=hg, cs=cs[i]) self.grid_columnconfigure((0, 1, 2, 3, 4), weight=1) self.grid_rowconfigure((0, 1, 2), weight=1) class PageThree(tk.Frame): ''' This class allows the user to input a time preiod for the movies to be recommended ''' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(background='white') bg = "dark gray" label = tk.Label(self, text="Movie/TV Time Period", bg="white", font=controller.title_font) label.pack(pady=20) button = tk.Button(self, text="Back to HomePage", width=30, height=3, bg=bg, command=lambda: controller.show_frame("StartPage")) button.pack(side=tk.BOTTOM, pady=40) prev_button = tk.Button(self, text="<Previous Page", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageTwo")) prev_button.pack(side=tk.LEFT) next_button = tk.Button(self, text="Next Page>", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageFive")) next_button.pack(side=tk.RIGHT) self.time = [] start_label = tk.Label(self, text="Start Date", font=8, bg="white") start_label.pack() self.start = tk.Entry(self, width=25, font=14) self.start.pack(pady=20) end_label = tk.Label(self, text="End Date", font=8, bg="white") end_label.pack() self.end = tk.Entry(self, width=25, font=14) self.end.pack(pady=20) submit = tk.Button(self, text='Add', command=self.show_entry, font=controller.entry_font) submit.pack() def show_entry(self): self.time.append(self.start.get()) self.time.append(self.end.get()) message = tk.Message(self, text=self.start.get()+'-'+self.end.get(), font=12) message.pack(side=tk.LEFT, padx=20) self.start.delete(0, tk.END) self.end.delete(0, tk.END) class PageFive(tk.Frame): ''' This class allows the input of movie or TV titles that will be used to generate similar movies or TV shows ''' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(background='white') bg = "dark gray" label = tk.Label(self, text="Movie Match", bg="white", font=controller.title_font) label.pack() label1 = tk.Label(self, text="(Enter previously watched movie titles)", font=8, bg="white") label1.pack() button = tk.Button(self, text="Back to HomePage", width=30, height=3, bg=bg, command=lambda: controller.show_frame("StartPage")) button.pack(side="bottom", pady=40) prev_button = tk.Button(self, text="<Previous Page", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageThree")) prev_button.pack(side='left') next_button = tk.Button(self, text="Next Page>", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageSix")) next_button.pack(side='right') self.photo = [] self.t = tk.Entry(self, width=50, font=12) self.t.pack(pady=50) self.movies = [] submit = tk.Button(self, text='Add', command=self.show_entry, bg=bg, font=controller.entry_font) submit.pack() def show_entry(self): self.movies.append(self.t.get()) im = tk.Message(self, text=self.t.get(), bg="white", font=8) im.pack(side=tk.LEFT, padx=10) self.t.delete(0, tk.END) class PageSix(tk.Frame): ''' This class allows input of actors the user would like to see in the recommended movies ''' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(background='white') label = tk.Label(self, text="Actor Match", bg="white", font=controller.title_font) label.pack() label1 = tk.Label(self, text="(Enter actor names you would like to see)", bg="white", font=8) label1.pack() bg = "dark gray" button = tk.Button(self, text="Back to HomePage", width=30, height=3, bg=bg, command=lambda: controller.show_frame("StartPage")) button.pack(side="bottom", pady=40) prev_button = tk.Button(self, text="<Previous Page", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageFive")) prev_button.pack(side='left') next_button = tk.Button(self, text="Next Page>", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageSeven")) next_button.pack(side='right') self.actors = [] self.t = tk.Entry(self, width=50, font=12) self.t.pack(pady=50) submit = tk.Button(self, text='Add', command=self.show_entry, bg=bg, font=controller.entry_font) submit.pack() def show_entry(self): self.actors.append(self.t.get()) message = tk.Message(self, text=self.t.get(), bg="white", font=8) message.pack(side=tk.LEFT) self.t.delete(0, tk.END) class PageSeven(tk.Frame): ''' This class allows input of directors the user would like to see in the recommended movies ''' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(background='white') label = tk.Label(self, text="Director Match", bg="white", font=controller.title_font) label.pack() label1 = tk.Label(self, text="(Enter director names you would like to see)", bg="white", font=8) label1.pack() bg = "dark gray" button = tk.Button(self, text="Back to HomePage", width=30, height=3, bg=bg, command=lambda: controller.show_frame("StartPage")) button.pack(side="bottom", pady=40) prev_button = tk.Button(self, text="<Previous Page", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageSix")) prev_button.pack(side='left') next_button = tk.Button(self, text="Next Page>", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageEight")) next_button.pack(side='right') self.directors = [] self.t = tk.Entry(self, width=50, font=12) self.t.pack(pady=50) submit = tk.Button(self, text='Add', command=self.show_entry, bg=bg, font=controller.entry_font) submit.pack() def show_entry(self): self.directors.append(self.t.get()) message = tk.Message(self, text=self.t.get(), bg="white", font=8) message.pack(side=tk.LEFT) self.t.delete(0, tk.END) class PageEight(tk.Frame): ''' This class allows for the user to input a rating threshold for the movies to be recommended ''' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(background='white') label = tk.Label(self, text="Movie Rating", bg="white", font=controller.title_font) label.grid(row=0, column=1) bg = "dark gray" button = tk.Button(self, text="Back to HomePage", width=30, height=3, bg=bg, command=lambda: controller.show_frame("StartPage")) button.grid(row=5, column=1, pady=20) prev_button = tk.Button(self, text="<Previous Page", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageSeven")) prev_button.grid(row=5, column=0, pady=20) next_button = tk.Button(self, text="Next Page>", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageNine")) next_button.grid(row=5, column=2, pady=20) bg = "white" global min_rating, max_rating label_min = tk.Label(self, text="Set Minimum Acceptable Rating", bg="white", font=9).grid(row=1, column=1) min_rating = tk.IntVar() min_scale = tk.Scale(self, from_=0, to=10, variable=min_rating, bg=bg, borderwidth=0, length=610, width=25, orient=tk.HORIZONTAL, font=controller.gen_font) min_scale.grid(row=2, column=1) label_max = tk.Label(self, text="Set Maximum Acceptable Rating", bg="white", font=9).grid(row=3, column=1) max_rating = tk.IntVar() max_scale = tk.Scale(self, from_=0, to=10, variable=max_rating, bg=bg, borderwidth=0, length=610, width=25, orient=tk.HORIZONTAL, font=controller.gen_font) max_scale.grid(row=4, column=1) self.grid_columnconfigure((0, 1, 2), weight=1) self.grid_rowconfigure((0, 1, 2, 3, 4), weight=1) class PageNine(tk.Frame): ''' This class allows the input of a desired time length for the movie or TV show ''' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(background='white') label = tk.Label(self, text="Movie/TV Length", bg="white", font=controller.title_font) label.grid(row=0, column=1, columnspan=2) bg = "dark gray" button = tk.Button(self, text="Back to HomePage", width=30, height=3, bg=bg, command=lambda: controller.show_frame("StartPage")) button.grid(row=2, column=1, columnspan=2) prev_button = tk.Button(self, text="<Previous Page", width=30, height=3, bg=bg, command=lambda: controller.show_frame("PageEight")) prev_button.grid(row=2, column=0, columnspan=2) next_button = tk.Button(self, text="Finish", width=30, height=3, bg=bg, command=controller.close) next_button.grid(row=2, column=2, columnspan=2) w = 40 h = 4 bg = "white" ab = None global time1, time2, time3, time4 time1 = tk.IntVar() t1 = tk.Checkbutton(self, text="Under 1 Hour", width=w, height=h, font=controller.decade_font, bg=bg, activebackground=ab, variable=time1) t1.grid(row=1, column=0) time2 = tk.IntVar() t2 = tk.Checkbutton(self, text="1-2 Hours", width=w, height=h, font=controller.decade_font, bg=bg, activebackground=ab, variable=time2) t2.grid(row=1, column=1) time3 = tk.IntVar() t3 = tk.Checkbutton(self, text="2-3 Hours", width=w, height=h, font=controller.decade_font, bg=bg, activebackground=ab, variable=time3) t3.grid(row=1, column=2) time4 = tk.IntVar() t4 = tk.Checkbutton(self, text="Over 3 Hours", width=w, height=h, font=controller.decade_font, bg=bg, activebackground=ab, variable=time4) t4.grid(row=1, column=3) self.grid_columnconfigure((0, 1, 2), weight=1) self.grid_rowconfigure((0, 1, 2), weight=1) def GUI_Movie(): ''' This function runs the GUI and loads its value into movie_input variable ''' app = Movie_GUI() app.mainloop() genres = [] for i in range(len(genre_var)): genres.append(genre_var[i].var.get()) e_type = [movie_var.get(), TV_var.get()] movies = app.frames['PageFive'].movies actors = app.frames['PageSix'].actors directors = app.frames['PageSeven'].directors time_period = app.frames['PageThree'].time rating_threshold = [min_rating.get(), max_rating.get()] movie_length = [time1.get(), time2.get(), time3.get(), time4.get()] movie_input = [e_type, genres, movies, actors, directors, time_period, rating_threshold, movie_length] return movie_input if __name__ == "__main__": movie_input = GUI_Movie() print(movie_input) # references: https://stackoverflow.com/questions/7546050/switch-between-two-frames-in-tkinter
56f68f69740de55331a8485e08f0e7ee5e977611
coloriordanCIT/PycharmProjects_Mac_Desktop
/PDA_A02/venv/Main.py
9,344
3.921875
4
''' Project B Programming for Data Analytics Haithem Alfi @author: colinoriordan @StudentID: R00133939 @Email: colin.r.oriordan@mycit.ie @class: SD3B Project objective is to produce an application and report that allows the user to explore some of the most interesting aspects of the IMDB dataset, using Pandas where possible as a means of analysing the data and incorporating visualization as method of illustrating the results. Accompanying this application is a short report, which includes a summary of the findings, mainly showing the graphical output generated by the application. ''' # import modules import sys import numpy as np import pandas as pd from bidict import bidict def main_menu(): ''' The starting point of the execution of the application. Purpose is to display a menu of options to the user, and to control the flow of the application depending on the user's selection. ''' # Verifies the program is being run with python version 3.0 or later if sys.version_info[0] < 3: raise Exception("Python 3 or a more recent version is required.") # create the boolean variable close to decide when our loop ends close = False # menu is displayed as long as close is false ( until user selects exit ) while close is False: # we display our menu on screen print("\n\n1. Most successful directors or actors") print("2. Film comparison") print("3. Analyse the distribution of gross earnings") print("4. Genre Analysis") print("5. Earnings and IMDB scores") print("6. Exit") # get user choice input in range 1-6 choice = get_num_input(1, 7, False) # select a function call based on user's response' if choice == 1: most_successful() elif choice ==6: close = True # program terminated sys.exit() def get_num_input(lower_boundary, higher_boundary, roman): ''' Using the parameters of lower & higher boundary, the function gets the user's input within this range and returns it. Function will loop until the user enters a value that is of the correct data type in the specified range. :param lower_boundary: lower boundary of valid integer values :param higher_boundary: higher boundary of valid integer values :param roman: boolean that indicates if the selection is in roman numerals :return choice: the valid user selection ''' # create bi-directional dictionary of roman numeral to integer roman_integer_bidict = bidict({ "i": 1, "ii": 2, "iii": 3, "iv": 4, "v": 5, "vi": 6, "vii": 7, "viii": 8, "ix": 9, "x": 10 }) # create the boolean variable valid_int to determine if user input is valid. valid_input = False # loop the users input until a valid response in range is entered while valid_input is False: # if the range is not in roman numerals i.e. integers if not roman: # throws exception if the response is not an integer try: choice = int(input("\nPlease select one of the above options:")) except ValueError: print("\nThis is not a valid data type response. " f"Integer {lower_boundary} to {higher_boundary-1}.") continue # print error if response is not in correct range 1-6 if choice in range(lower_boundary, higher_boundary): valid_input = True else: print("\nThis integer response is not in range " f"{lower_boundary} to {higher_boundary-1}.") # else if the range is in roman numerals elif roman: # reads user input choice = input("\nPlease select one of the above options:") # if the user's input is numeric or a decimal -> print error & loop back to input if choice.isnumeric() or choice.isdecimal(): print("\nThis numeric or decimal data type is not a valid roman numeral response in range " f"{roman_integer_bidict.inv[lower_boundary]} to " f"{roman_integer_bidict.inv[higher_boundary-1]}.") continue # else the users input is a string/character type else: # change the user's input to lower case choice.lower() # if the user's choice is a roman numeral, take this value & assign # it's corresponding integer value to choice variable. if choice in roman_integer_bidict: choice = roman_integer_bidict[choice] # if the corresponding integer value is in the correct range, this is valid. if choice in range(lower_boundary, higher_boundary): valid_input = True # error printed if the user enters a roman numeral that is not in range & loop back to input. else: print("\nThis roman numeral response is not in range " f"{roman_integer_bidict.inv[lower_boundary]} to " f"{roman_integer_bidict.inv[(higher_boundary-1)]}.") # error printed if the user enters a string, that's not a roman numeral & loop back to input else: print("\nThis is not a roman numeral response in range " f"{roman_integer_bidict.inv[lower_boundary]} to " f"{roman_integer_bidict.inv[higher_boundary-1]}.") return choice def most_successful(): ''' Sub menu to display sub options of most successful Actor / Director to user. Controls the flow of the application under the most successful option depending on the user's input choice. ''' # we display our menu on screen print("\ni. Top Directors") print("ii. Top Actors") # get user choice input in range i to ii # Execution will loop here until a valid response is received. choice = get_num_input(1, 3, True) # set our display text based on user option if choice == 1: text = "directors" else: text = "actors" print(f"\nPlease enter the number of top {text}, based on gross movie income, you would like to see." f"\nInteger value 1 to {get_num_directors()}.") # proceed based on user choice of director or actor if choice == 1: # get user limit input, with data validation # i.e. num no greater than number of directors limit = get_num_input(1, (get_num_directors()+1), False) # create data frame from our data set df = pd.read_csv("/Users/colinoriordan/PycharmProjects/PDA_A02/venv/movie_metadata.csv") # create data frame from desired columns df_dir_gross = df[["director_name", "gross"]] # group data frame by director name sorted_df = df_dir_gross.groupby("director_name") # set display option of results to integer - was printing in sci. notation pd.set_option('display.float_format', lambda x: '%d' % x) # get the sum of the gross per director summed_df = sorted_df['gross'].sum() # put the series into ascending order ascending_df = summed_df.sort_values(ascending=False) # print results limited to user input print() print(ascending_df[:limit]) else: # get user limit input, with data validation # i.e. num no greater than number of actors limit = get_num_input(1, (get_num_actors() + 1), False) # create data frame from our data set df = pd.read_csv("/Users/colinoriordan/PycharmProjects/PDA_A02/venv/movie_metadata.csv") # create data frames from desired columns df_actor1_gross = df[["actor_1_name", "gross"]] df_actor2_gross = df[["actor_2_name", "gross"]] df_actor3_gross = df[["actor_3_name", "gross"]] # concatenate the data frames frames = [df_actor1_gross, df_actor2_gross, df_actor3_gross] concatenated_df = pd.concat(frames) print(concatenated_df) ''' # group data frame by director name sorted_df = concatenated_df.groupby("") # set display option of results to integer - was printing in sci. notation pd.set_option('display.float_format', lambda x: '%d' % x) # get the sum of the gross per director summed_df = sorted_df['gross'].sum() # put the series into ascending order ascending_df = summed_df.sort_values(ascending=False) # print results limited to user input print() print(ascending_df[:limit]) ''' def get_num_directors(): ''' Function which calculates the number of directors in the movies_metadata data set. :return: the number of directors in the data set ''' df = pd.read_csv("/Users/colinoriordan/PycharmProjects/PDA_A02/venv/movie_metadata.csv") df_dir_gross = df[["director_name", "gross"]] sorted_df = df_dir_gross.groupby("director_name") return len(sorted_df) def get_num_actors(): ''' :return: ''' main_menu()
b9d2b0498293c978e79f30d5500e6ae0bcf39037
PdxCodeGuild/class_emu
/Code/Kevin/Misc Practice/Linked Lists/Push.py
694
4.15625
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): # Pushing the data to the top of the stack. Today?->You->Are->How->World!->Hello new_node = Node(new_data) new_node.next = self.head self.head = new_node def printlist(self): temp = self.head full_word = "" while(temp): full_word += temp.data temp = temp.next print(f"Full Word: {full_word}") mylinkedList = LinkedList() mylinkedList.push("Hello ") mylinkedList.push("world ") mylinkedList.printlist()
ded0465eb4046dff3fa4ecfca6e3df18088166be
shirleyxx/Leetcode
/P133.py
706
3.734375
4
""" # Definition for a Node. class Node: def __init__(self, val, neighbors): self.val = val self.neighbors = neighbors class Solution: def __init__(self): # Dictionary to save the visited node and it's respective clone # as key and value respectively. This helps to avoid cycles. self.cloned = {} def cloneGraph(self, node: 'Node') -> 'Node': if node in self.cloned: return self.cloned[node] clone_node = Node(node.val, []) self.cloned[node] = clone_node if node.neighbors: clone_node.neighbors = [self.cloneGraph(n) for n in node.neighbors] return clone_node
c1fe6beca5205441d0cd0e6f46d03d49503a436c
javiermms/cs1.3
/word_jumble.py
3,638
3.796875
4
import time start = time.process_time() def get_file_lines(filename='/usr/share/dict/words'): """Return a list of strings on separate lines in the given text file with any leading and trailing whitespace characters removed from each line.""" # Open file and remove whitespace from each line with open(filename) as file: lines = [line.strip() for line in file] return lines def sort_dictionary(all_dictionary_words): word_dic = dict() for word in all_dictionary_words: sorted_words = ''.join(sorted(word.lower())) word_dic[sorted_words] = word return word_dic def sort_words(words): jumble_sorted = [] for word in words: sorted_words = ''.join(sorted(word.lower())) jumble_sorted.append(sorted_words) return jumble_sorted def get_specific_indexes(array): inner_arr = [] whole_arr = [] for element in range(len(array)): for index, letter in enumerate(array[element]): if letter == 'O': inner_arr.append(index) whole_arr.append(inner_arr) inner_arr = [] return whole_arr def get_word_count_and_size(array): new_array = [] for element in array: new_array.append(len(element)) return new_array def unjumble_words(jumble_sorted, word_dic): answers = [] for word in jumble_sorted: for key in word_dic.items(): if key[0] == word: answers.append(key[1]) return answers def solve_word_jumble(words, circles, final, word_dic, jumble_sorted): """Solve a word jumble by unscrambling four jumbles, then a final jumble. Parameters: - words: list of strings, each is the scrambled letters for a single word - circles: list of strings, each marks whether the letter at that position in the solved anagram word will be used to solve the final jumble. This string contains only two different characters: 1. O (letter "oh") = the letter is in the final jumble 2. _ (underscore) = the letter is not in the final jumble - final: list of strings in the same format as circles parameter that shows how the final jumble's letters are arranged into a word or phrase.""" # unjumbles word answers = unjumble_words(jumble_sorted, word_dic) # gets needed indexes to get letters whole_arr = get_specific_indexes(circles) # gets the letter where the circles are letter = "" count = 0 #keep it on array until incremented to next for element in whole_arr: #element is [2,4] for _, num_in_array in enumerate(element): #num in array 2 then 4 letter += answers[count][num_in_array] count += 1 return answers def main(): sorted_dic = sort_dictionary(get_file_lines()) # Word Jumble 1. Cartoon prompt for final jumble: # "Farley rolled on the barn floor because of his ___." words1 = ['TEFON', 'SOKIK', 'NIUMEM', 'SICONU'] circles1 = ['__O_O', 'OO_O_', '____O_', '___OO_'] final1 = ['OO', 'OOOOOO'] sorted_jumble = sort_words(words1) print(solve_word_jumble(words1, circles1, final1, sorted_dic, sorted_jumble)) # # Word Jumble 2. Cartoon prompt for final jumble: "What a dog house is." words2 = ['TARFD', 'JOBUM', 'TENJUK', 'LETHEM'] circles2 = ['____O', '_OO__', '_O___O', 'O____O'] final2 = ['OOOO', 'OOO'] sorted_jumble = sort_words(words2) print(solve_word_jumble(words2, circles2, final2, sorted_dic, sorted_jumble)) if __name__ == '__main__': main() print('Time:'+' '+str(time.process_time() - start))
14d85a9438091d02535a7b1b84cef2b4a29716eb
Abhayghoghari/internship
/q1-avg of 5 num.py
307
4.28125
4
print('enter value and find average number') n1= int(input('enter 1st number: ')) n2= int(input("enter 2nd number: ")) n3= int(input("enter 3rd number: ")) n4= int(input("enter 4th number: ")) n5= int(input("enter 5th number: ")) s=n1+n2+n3+n4+n5 avg=s/5 print("your average number is",avg) input()
30850cf5649e2369e56dc5f355211685df805f01
ratedr360/pdsnd_github
/Bikeshare_analysis.py
7,991
4.125
4
import time import pandas as pd import numpy as np import calendar CITY_DATA = { 'Chicago': 'chicago.csv', 'New York City': 'new_york_city.csv', 'Washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of city (str) month - name of the month to filter by, or "None" to apply no month filter (str) day - name of the day of week to filter by, or "None" to apply no day filter """ print('\nHello! Let\'s explore some US bikeshare data!') #get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs print('-'*30) print ('*Cities-Bike data*\n') print ( 'Chicago') print ( 'New York City') print ( 'Washington') print('-'*30) while True: city = input("\nWhich city would you like to filter by? See above\n").title() if city not in ('Chicago','New York City', 'Washington'): print("Incorrect input,See above options.") continue else: print('Great!!, now next step\n') break #get user input for month (None, january, february, ... , june) print('-'*30) print ('Select Month filters\n') print ( 'January') print ( 'February') print ( 'March') print ( 'April') print ( 'June') print ( 'None') print('-'*30) while True: month = input('Select from above options. Type None for no filters\n').title() if month not in ('January', 'February', 'March', 'April', 'May', 'June', 'None'): print("Incorrect input,See above options.") continue else: print('Great!!, now next step\n') break #get user input for day of week (None, monday, tuesday, ... sunday) print('-'*30) print ('Select day filters\n') print ( 'Sunday') print ( 'Monday') print ( 'Wednesday') print ( 'Thursday') print ( 'Friday') print ( 'None') print('-'*30) while True: day = input("Do you want to filter by day? If yes select above. Type None for no filters \n").title() if day not in ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'None'): print("Incorrect input,See above options.") continue else: break print ('\n**Analysis for**-', city.upper()) print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of city (str) month - name of the month to filter by, or "None" to apply no month filter (str) day - name of the day of week to filter by, or "None" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ # Loading city data into file df = pd.read_csv(CITY_DATA[city]) df['Start Time'] = pd.to_datetime(df['Start Time']) df['month'] = df['Start Time'].dt.month #Extract month from date time and create a column df['d_week'] = df['Start Time'].dt.weekday_name #Gives name of the week and create a column df['start-end'] = df['Start Station'].str.cat(df['End Station'], sep=' -- ') #Combining start and end station for better reporting # filter by month if applicable if month != 'None': # Created a dictionary that houses the values for months months = { 'January' : 1, 'February' : 2, 'March' : 3, 'April' : 4, 'May' : 5, 'June' : 6} month = months[month] # Filtered month data frame if specified df = df[df['month'] == month] # Filtered day data frame if specified if day != 'None': # filter by day of week to create the new dataframe df = df[df['d_week'] == day.title()] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('**General overivew**\n') #display the most common month common_month = df['month'].mode()[0] print('Most common month:', calendar.month_name[int(common_month)]) #using calendar import to display name #display the most common day of week common_day = df['d_week'].value_counts(dropna =True).reset_index()['index'][0] print('Most common day:', common_day) #display the most common start hour df['hour'] = df['Start Time'].dt.hour common_hour = df['hour'].mode()[0] #mode returns the highest value in a series print('Most common hour:', common_hour) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('**Trips and Stations analysis**\n') # display most popular start station Start_Station = df['Start Station'].value_counts(dropna =True).reset_index()['index'][0] print('\nMost popular start station-:', Start_Station.capitalize()) #display most popular end station End_Station = df['End Station'].value_counts(dropna =True).reset_index()['index'][0] print('\nMost popular end station-:', End_Station.capitalize()) #display most popular combination of start station and end station trip popular_round_trip_stations = df['start-end'].mode().to_string(index = False) print('\nMost common round trip station-: {}.'.format(popular_round_trip_stations)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('**Trip duration**\n') #display total trip duration total_trip_duration = np.sum(df['Trip Duration']) print('Total trip duration-:', round((total_trip_duration/(60*60*24*365)),0), " Years") #display average trip duration average_trip_duartion = np.mean(df['Trip Duration']) print('Average trip duartion-:', round((average_trip_duartion/60),2), " Minutes") print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('**User Stats**\n') #Display different user categories print ('User type-') user_count = df['User Type'].value_counts(dropna =True) print(user_count) try: earliest_birth_year = str(int(df['Birth Year'].min())) print('\nEarliest birth year:', earliest_birth_year) except KeyError: print("\nEarliest birth Year:\nData not available for Washington city.") try: most_recent_birth_year = str(int(df['Birth Year'].max())) print('\nMost recent birth year:', most_recent_birth_year) except KeyError: print("\nMost recent birth year:\n Data not available for Washington city.") try: most_common_birth_year = df.groupby('Birth Year')['Birth Year'].count() print('\nMost common birth year:', str(int(most_common_birth_year.index[0]))) except KeyError: print("\nMost common birth year:\n Data not available for Washington city.") print('-'*40) def user_data(df): '''Displays raw data based on user selection of city for analysis''' u_data = input('\n Would you like to see indiviudal trip data? Type - Yes/No\n').title() curr_row = 0 while True: if u_data == 'No': return elif u_data == 'Yes': print(df[curr_row: curr_row + 5]) curr_row = curr_row + 5 else: print('Incorrect input. Please type -Yes/No\n') u_data = input('\nWould you like to see more data? Type - Yes/No \n').title() def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) user_data(df) program_restart = input('\n Would you like to analyze again? Type - Yes/No.\n').title() if program_restart != 'Yes': break if __name__ == "__main__": main()
4f9564eca5f03faa2141319eed0dc88d0e23c7f5
CNieves121/lps_compsci
/class_samples/3-7_forloops/PartnerPractice.py
398
4.40625
4
""" colors = ["red", "blue", "green", "purple"] ages = [14, 15, 15, 16, 16, 13, 18, 14, 15, 15, 14] # 5 - how do we remove an item from the list? print(colors) del colors[2] print(colors) """ colors = ["red", "blue", "green", "purple"] ages = [14, 15, 15, 16, 16, 13, 18, 14, 15, 15, 14] # 6 - what happens when we use the append() function? print(colors) colors.append("orange") print(colors)
c46b3e12f80dcdc94892ee2990ecf3c4bcf0f5c4
juanchixd/Curso-python
/Listas.py
264
4.0625
4
lista = [12, "World", True, "oración", [21, "Hello"]] valor = lista [1] print(valor) valor2 = lista[4][1] print(valor2) lista[1] = 1 print(lista) var2 = lista[-1] print(var2) var3 = lista[0:2] #no incluye el elemento 2 print(var3) var4 = lista[0:5:2] print(var4)
251d529268ed35832a12c1e556ff62ac7607158b
Joombey/project
/function.py
2,388
3.6875
4
import sqlite3 as sql import calendar import datetime #user = input() class SQL: def __init__(self, user): self.User = 'name'+str(user) def open_conn(self): self.conn = sql.connect("base_db.sqlite") self.cur = self.conn.cursor() return self.conn, self.cur def close_conn(self, conn, cur): self.conn.commit() self.cur.close() self.conn.close() def get_conn(self): conn, cur = self.open_conn() cur.execute("CREATE TABLE IF NOT EXISTS %s (income INTEGER, residue INTEGER, daily_res INTEGER, data TEXT)" %self.User) self.close_conn(conn, cur) def add_income(self, value): conn, cur = self.open_conn() cur.execute("UPDATE %s SET income = %s WHERE data = %s" %(self.User, value, str(datetime.datetime.now())[:10].replace('-', ''))) self.close_conn(conn, cur) def add_residue(self, value): conn, cur = self.open_conn() cur.execute("UPDATE %s SET residue = %s WHERE data = %s" %(self.User, value, str(datetime.datetime.now())[:10].replace('-', ''))) self.close_conn(conn, cur) def add_data(self): conn, cur = self.open_conn() temp = str(datetime.datetime.now())[:10].replace('-', '') print(temp) cur.execute("INSERT INTO %s (data) VALUES (%s)" %(self.User, temp)) self.close_conn(conn, cur) def add_result(self): conn, cur = self.open_conn() now = datetime.datetime.now() temp = str(now)[:10].replace('-', '') days = calendar.monthrange(now.year, now.month)[1] cur.execute("SELECT (income) FROM %s WHERE data = %s" %(self.User, temp)) for i in cur: temp_income = i[0] cur.execute("SELECT (residue) FROM %s WHERE data = %s" %(self.User, temp)) for i in cur: temp_residue = i[0] cur.execute("UPDATE %s SET daily_res = %d" %(self.User, (temp_income - temp_residue)/days)) self.close_conn(conn, cur) def select_result(self): conn, cur = self.open_conn() cur.execute("SELECT (daily_res) FROM %s WHERE data = %s" %(self.User, str(datetime.datetime.now())[:10])) for i in cur: daily_res_send = i[0] if cur.fetchall() == (): daily_res_send = 'Неполный ввод' self.close_conn(conn, cur) return daily_res_send
ff7825225222d401ddf19233b9b3a79e10831504
shahmk/Algorithms
/Longest Pal.py
697
3.875
4
def longest_pal(str): n=len(str) #initialize Opt Table Opt=[[0 for i in range(n)] for j in range(n) ] for i in range(n): Opt[i][i] = 1 # define sil as length of substring interval [i,j] sil=(j-i +1) # compute Opt table entry for each starting index i and each sil for sil in range(2, n+1): for i in range(n-sil+1): j = i+sil-1 if (str[i] == str[j] and sil == 2): Opt[i][j] = 2 elif (str[i] == str[j]): Opt[i][j] = Opt[i+1][j-1] + 2; else: Opt[i][j] = max(Opt[i][j-1], Opt[i+1][j]) return Opt[0][n-1] str1="aibohphobia" print str1,"has longest palindrome substring length:" print longest_pal(str1)
7f695c13678e2de0d7669a5123a28b170583e2f7
superyang713/pcookbook
/07_functions/02_write_functions_that_only_accept_keyword_arguments.py
496
3.65625
4
""" Problem: You want a function to only accept certain arguments by keyword. Solution: It is easy to implement if you place the keyword arguments after a * argument or a single unnamed *. """ # Example 1: Note that * argument can only appear as the last positional # argument in a function definition. A ** argument can only appear as the last # argument. def recv(maxsize, *, block): """ Receives a message """ pass # recv(1024, True) --> TypeError recv(1024, block=True)
22d61d76e4b73e30afde7874d99971b0d786726f
1GBattle/gab_locator
/.idea/gag_functions/get_gag.py
1,001
3.578125
4
def get_gag(line_in_file, operators, operators_in_string, operands): split_line = line_in_file.split() data_types = [] for character in split_line: if character in operators: operators_in_string.append(character) elif isinstance(character, str) or isinstance(character, int) or isinstance(character, float): operands.append(character) for item in operands: if item.isdigit(): data_types.append('number') else: data_types.append('string') operand_1_data_type, operand_2_data_type = data_types operand_1, operand_2 = operands gag_to_return = f"Operand 1 data type:{operand_1_data_type}, " \ f"Operand 2 data type:{operand_2_data_type}, " \ f"Operator: {operators_in_string}, " \ f"Operand 1: {operand_1} Operand 2: {operand_2}" data_types.clear() operators_in_string.clear() operands.clear() return gag_to_return
5b1c4ff05a833b1358e9249037090b8afc70d57b
ShayLn/py-fighter
/screens/scores.py
2,737
4.125
4
''' High Score Screen This screen is shown at end of game after pressing on scoreboard button. Takes data from other_data/highscores.txt and creates a score board of top 10 players. Used Roberts Text, Menu and Button functions @author: Rokas ''' import pygame from classes.generalfunctions import quitGame from classes.generalfunctions import loadScoreList from classes.text import Text from classes.menu import Button from classes.menu import Menu # Loading the background image in to a variable. background = pygame.image.load('graphics/menu/scoreboard.png') def scoreBoard(screen, delay): ''' Function which creates a screen where a score bored is displayed by using the values from highscores.txt. ''' # establishing a clock for the screen clock = pygame.time.Clock() # Creating width and height variables. width = screen.get_width() height = screen.get_height() # loading a list from game over screen with the newest scores. score_list = loadScoreList() if len(score_list) < 10: n_scores = len(score_list) else: n_scores = 10 # Creating text objects for n highest scores. Header = Text(screen, (width // 2, height // 8), 50, f'TOP {n_scores} SCORES', 'purple') score_objects = [] for k in range(n_scores): index = - 1 * (k + 1) score_objects.append( Text(screen, (width // 2, 120 + (k * 40)), 35, f'{score_list[index][0]} = {score_list[index][1]}') ) # Creating a button for going back to the game over screen. back = Button(screen, 'Back', (400, 585), (lambda: 'go_back'), 25, (126, 64)) menu = Menu(screen, Header, False, back) # Creating a loop for the scoreboard screen. run = True while run: clock.tick(delay) for event in pygame.event.get(): # Send each event to the start menu if event.type == pygame.QUIT: # Detecting user pressing quit button, if X pressed, # break loop and quit screen. quitGame() # Checking if the Back button is being pressed. elif (event.type == pygame.MOUSEBUTTONDOWN) or \ (event.type == pygame.MOUSEBUTTONUP): button_press = menu.do(event) if button_press == 'go_back': run = False # Bliting background image. screen.blit(background, (0, 0)) # Bliting text objects and button to screen. for score_object in score_objects: score_object.display() menu.display() pygame.display.flip()
8b9b217ab70bb9667998b6dc15f6089f015c3fa7
pavelbrnv/Coursera
/PythonBasis/week07/task09.py
685
3.59375
4
inFile = open('input.txt', 'r', encoding='utf8') n = int(inFile.readline().strip()) common_languages = set() all_languages = set() for pupil_index in range(n): m = int(inFile.readline().strip()) pupil_languages = set() for language_index in range(m): language = inFile.readline().strip() pupil_languages.add(language) all_languages.add(language) if pupil_index == 0: common_languages = pupil_languages else: common_languages &= pupil_languages inFile.close() print(len(common_languages)) for language in common_languages: print(language) print(len(all_languages)) for language in all_languages: print(language)
5f6b3eb50500a11ed3a2a93a514ef31c2f8c4250
BrunoCerberus/Algoritmo
/Ex78.py
738
3.5625
4
""" Programa que recebe um vetor de 20 posicoes e um valor x qualquer O programa devera fazer uma busca de x no vetor, caso encontre, exibir a posicao do vetor juntamente com o valor, caso nao, mostrar uma mensa- gem de erro. """ from random import randint vetor = [] for i in range(0,20): vetor.append(randint(-100,100)) print("O vetor tem",len(vetor),"elementos!") while True: try: x = int(input("Selecione um valor inteiro: ")) except ValueError: print("Valor invalido inserido, tente novamente!") continue break if vetor.count(x): # se o valor x existir no vetor for i in range(len(vetor)): if vetor[i] == x: print("vetor[",i,"]=",vetor[i]) else: print("O valor",x,"nao existe no vetor") print(vetor)
84363766857f0d258ea001be59087308f0d50091
phoenix9373/Algorithm
/2020/백준문제/수학3/5086_배수와 약수.py
250
3.796875
4
while True: a, b = map(int, input().split()) if a == b == 0: break ans = '' if (a // b) * b == a: ans = 'multiple' elif (b // a) * a == b: ans = 'factor' else: ans = 'neither' print(ans)
ae0f3eeba843f7eaa2b216f82d35fd0ad6e48e92
RaptorPatrolContinuum/An
/OldStuff/MiraExternalsold.py
16,118
3.59375
4
from math import * from inspect import * import ast file = open('INP.txt', 'r') basis = open('Basis.txt', 'r+') memory = open('Memory.txt', 'r+') def ARB(function, replacelist): ''' ANSWER: need to map everything to concept space then ARB is just a basis remapping god fucking damn it I hate writing one function I just want to abstract as fast as possible FML IF I HAD A CONVERTER TO CONCEPT SPACE STRUCTURE I COULD DO THIS ALMOST INSTANTLY example: for x in alg1: f1.append(x[1]) use replacelist: alg1:alg2 f1:f2 then eval: for x in alg2: f2.append(x[1]) problem: sometimes it replaces the wrong thing! EX: for r in alg1: g1.append(r[1]) with: r:x g1:f1 I would get: fox x in alf1: f1.append(x[1]) idea: use syntax hax (I need to keep a fucking library god damn it) know what is a var and what isn't a var idea: use positionals (would be too complicated?) ''' NEWEVAL = [] return NEWEVAL def SynSplit(string): ''' function so I can make ABStractreplace better idea: feed lines in split each line: EX: for r in alg1: g1.append(r[1]) with: r:x g1:f1 try: for r in alg1: split into: [for| |r| |in| |alg1:] [g1|.append(| r | [|1|] |)] ''' return def M_(thestr): ANS = [] i = 0 for x in thestr: ANS.append([str(i),x]) i += 1 return ANS def Minv_(thestr): ANS = [] i = 0 for x in thestr: ANS.append([x,str(i)]) i += 1 return ANS def Q_(unknown): return [[unknown,unknown]] def CantorPair(x,y): return (1/2)*(x+y)*(x+y+1)+y def CantorInv(z): w = floor((sqrt(8*z+1)-1)/2) t = (w*w+w)/2 y = z - t x = w - y return [x,y] def fCheck(fcandidate): ANS = True ''' an object is not a function when: one element of the fcandidate is not a pair check if each element of fcandidate is of size 2 ''' for obj in fcandidate: if len(obj) != 2: ANS = False return ANS def toString(f): ''' assume f is a finite function of the form for all x in f, x = [a,b] return a string that is the range of f "in order" ''' ANS = "" if fCheck(f) == False: print("f1 is function? toString", fCheck(f1)) return for x in f: ANS = ANS + x[1] print("hoping lists retain some kind of order",f,ANS) return ANS def Beta_(obj): ''' fuck this is an almost useless function here we make the basis = \rchi_obj union obj ''' ANS = [] i = 0 for x in obj: ANS.append(x) ANS.append([x,i]) i += 1 for y in range(i): #oh shit this is crazy because by the Duality theorem + kuratowski pair lemma that means these are actual numbers ANS.append([y,y]) return ANS def rchi(obj): ANS = [] i = 0 for x in obj: ANS.append(str(i)) i += 1 return ANS def Address(basis,obj): ''' assume: basis is a list obj is a list of pairs ''' Interim = [] for x in obj: #print("wat is x?", x, type(x), basis) #print("Cantor Data", basis.index(x[0]),basis.index(x[1])) Interim.append(CantorPair(basis.index(x[0]),basis.index(x[1]))) ANS="1".zfill(int(max(Interim))+1) #print("need Interim Data", Interim) Interim = list(filter(lambda x: x != max(Interim), Interim)) for x in Interim: ANS = ANS[:int(x)] + "1" + ANS[int(x)+1:] ANS = int(ANS[::-1], 2) return ANS def AddressFunc(index,obj): ''' index is a finitefunction going from objects -> rchi objects object is the finitefunction we are addressing takes a function and optionally an index returns the address NOTE: THIS FUNC TAKES THE ALGORITHM OF THE OBJECT option: algorithm before or after? let obj be an arbitrary object (string or list) let index be a written function of the form: func => \rchi+func ''' Interim = [] for x in obj: Interim.append(CantorPair(int(RelEval(index,x[0])[0]),int(RelEval(index,x[1])[0]))) ANS="1".zfill(int(max(Interim))+1) #print("need Interim Data", Interim) Interim = list(filter(lambda x: x != max(Interim), Interim)) for x in Interim: ANS = ANS[:int(x)] + "1" + ANS[int(x)+1:] ANS = int(ANS[::-1], 2) return ANS def AutoVisionHAX(AVlist,replacementlist): ''' some hax because I'm a dumbass ''' ANS = [] for x in AVlist: ANS.append([RelEval(replacementlist,[str(int(x[0]))])[0],RelEval(replacementlist,[str(int(x[1]))])[0]]) return ANS def AutoVision(number,Lval): #print("==========statspls", number,Lval) #print("plsonlyonce",Lval,Lval == 1) ''' this is for ''' ANS = [] binary = "{0:b}".format(number)[::-1] #print("number, binary", number, binary, Lval) #print("thebin",binary) #print("first index must match", str(binary).index('1')) #so we're going the right direction if Lval == 1: #print("right choice!") indexer = 0 for d in str(binary): if d == '1': #print("what is index?", indexer, CantorInv(indexer)) ANS.append(CantorInv(indexer)) indexer += 1 else: ''' for each one, construct the part recursively: go down 1 Lval ''' print("ABUSE THE COMPRESSION THEOREM!") if ANS == []: #print("stats", number,Lval) print("ANS IS []???!?!?!?!?!") return ANS def Compose(f1,f2): ''' do f2 THEN f1 like the way it's written! ''' #check if f1,f2 are functions: if fCheck(f1) == False or fCheck(f2) == False: print("f1 is function? COMPOSE", fCheck(f1), "f2 is function?", fCheck(f2)) return ALG = [] for x in f2: for y in f1: if x[1] == y[0]: ALG.append([x[0],y[1]]) return ALG def RelEval(f1,arglist): ''' "RELationEval" evals f1 using arglist and returns list f1 is finite function arg is singleton question: "composing" using list vs 1 obj ''' ANS = [] for y in arglist: for x in Compose(f1,Q_(y)): ANS.append(x[1]) return ANS #print(RelEval([[1,2],[2,2],[7,8]],[1,2,7])) def M_Compose(alg1, alg2): ''' do ALG2 THEN ALG1!!!! problem: what if alg2 or alg1 don't map to functions??? say that alg1 or alg2 are not mapped to funcs alg1 and alg2 should be inspectors of functions.... ''' ALG = [] f1 = [] f2 = [] #construct f1 and f2 for x in alg1: f1.append(x[1]) for x in alg2: f2.append(x[1]) #check if they are functions if fCheck(f1) == False or fCheck(f2) == False: print("f1 is function? M_COMPOSE", fCheck(f1), "f2 is function?", fCheck(f2)) return #compose them return Compose(f1,f2) def PreImage(f1): ANS = [] #check if f is a function: if fCheck(f1) == False: print("f1 is function? PREIMAGE", fCheck(f1)) return #reverse pair ordering: for x in f1: ANS.append([x[1],x[0]]) return ANS def Inspector_M(y): ''' Inspector (y) = M_(y) compose M_^(-1)(y) (here we assume that y is already M_y!!!!!) ''' #check if y is a function: if fCheck(y) == False: print("y is function? INSPECTOR", fCheck(y)) return return Compose(y,PreImage(y)) def Elem_My(x,y): ''' #1: why is this important? >>>ALL THE FUNCTIONS ARE IN THE CONCEPT SPACE this function says if x in y or not: idea: Q_(x) compose Inspector(y) Inspector (y) = M_(y) compose M_^(-1)(y) ''' if len(Compose(Q_(x),Inspector_M(y))) > 0: return True else: return False def VisionBasis(basis,vision): ANS = [] if fCheck(vision) == False: print("vision is function?", fCheck(vision)) return for x in vision: ANS.append([basis[int(x[0])],basis[int(x[1])]]) return ANS def TrySI(E_G,E_H): ''' E_G,E_H figure out of E_G or E_H is bigger then we know that bigger cannot inject into smaller step #1: organize nodes by # of connections we know that if a node connects to 5 objects, we cannot biject it to a node that only connects <5 objects ''' if len(E_G) > len(E_H): bigger = E_G else: bigger = E_H dictsize = for x in bigger: return def pairfinder(string,charpair): #delete pairs: thefuckinganswer = [] i = 1 #we start at 1 because we are already using for loop AKA for loop assumes we already have 1 level index = 0 maxi = 0 for x in string: if x == charpair[0]: thefuckinganswer.append([index,i]) if i > maxi: maxi = i i+= 1 if x == charpair[1]: i= i - 1 thefuckinganswer.append([index,i]) index += 1 return [thefuckinganswer,maxi] def pairfinderSTRING(finderlist,string): ''' takes pairfinder and the original string and returns the right morphemes ''' ANS = [] Indexers = {} for y in range(1,finderlist[1]+1): Indexers[y] = [] for x in finderlist[0]: #print("flist", finderlist) #print("cstats", x, Indexers[x[1]],x[0]) ''' why is Indexers[x[1]] have a keyerror wtf ''' Indexers[x[1]].append(x[0]) for y in range(1,finderlist[1]+1): for z in range(0,len(Indexers[y])): if z % 2 == 0: ANS.append(string[Indexers[y][z]:Indexers[y][z+1]+1]) return ANS def Cheat(string): #take a string and return a list of strings that represent the important morphemes: #punctuation: #.?!,;:-—)}]'"... #line break #paragraph break(?) #FUCKING USE CASES FOR "'" Morphemes = [] sentencedelimiters = [".", "?", "!"] #... SentenceStartPos = 0 SentenceStartPosList = [] #every even is start and odd is close for each pair pairdelimiters=["(", ")", "{", "}", "[", "]", "\"", "\"", " ", " "] pairdelimiterpos={} #EACH PAIR CHAR NEEDS ITS OWN START POS for pair in pairdelimiters: #use dictionaries pairdelimiterpos[pair + "On"]= 0 pairdelimiterpos[pair + "Location"]= [-1] #starts at -1 so that it gets the first word even though there is no space[might be a problem] pairdelimiterpos[pair + "List"]= [] pairdelimiterpos["AllList"] = [-1,-1] #starts at -1 so that it gets the first word even though there is no space[might be a problem] splicedelimiters=[",", ";", ":", "-", "—", "\n"] SpliceStartPos = 0 for g in range(0,len(pairdelimiters)): if g % 2 == 0 and pairdelimiters[g] != " ": toappend = pairfinderSTRING(pairfinder(string,[pairdelimiters[g],pairdelimiters[g+1]]),string) if len(toappend) != 0: Morphemes.append(toappend) i = 0 for x in string: if i == len(string)-1: #check if last morpheme is already in the list: inside = 0 try: Morphemes.index(string[pairdelimiterpos["AllList"][-1]+1:]) except(ValueError,IndexError): #print("already inside!","\n",string[pairdelimiterpos["AllList"][-1]+1:],"\n", Morphemes) inside = 1 if inside == 0: #get the last morpheme: Morphemes.append(string[pairdelimiterpos["AllList"][-1]+1:]) #you need a hierarchy to get sentence start pos to ignore pairdelimiter rules if x in splicedelimiters: if max(SentenceStartPos,SpliceStartPos) in range(pairdelimiterpos["AllList"][-2],pairdelimiterpos["AllList"][-1]+1) and len(pairdelimiterpos["AllList"])>=4: #find one that isn't in most recent pair k = 1 for y in SentenceStartPosList: K = len(SentenceStartPosList) if SentenceStartPosList[K-k] not in range(pairdelimiterpos["AllList"][-2],pairdelimiterpos["AllList"][-1]+1): delimstart = SentenceStartPosList[K-k] else: delimstart = 0 k += 1 else: delimstart = max(SentenceStartPos,SpliceStartPos) Morphemes.append(string[delimstart:i+1]) #keep track of everything pairdelimiterpos["AllList"].append(i) SpliceStartPos = i if x in pairdelimiters: ''' THEY ARE BEING TREATED AS A SINGLE INSTEAD OF AS A PAIR ''' if x == " " or x == "\"": #append the slice from the last location to this location Morphemes.append(string[pairdelimiterpos[x + "Location"][-1]+1:i]) #make note of the last location pairdelimiterpos[x + "Location"].append(i) #keep track of everything pairdelimiterpos["AllList"].append(i) else: #if it's on for this particular character, slice the string then turn off if pairdelimiterpos[pairdelimiters[pairdelimiters.index(x)-1] + "On"] == 1: pairdelimiterpos[pairdelimiters[pairdelimiters.index(x)-1] + "On"] = 0 #slice the string and append to Morphemes Morphemes.append(string[pairdelimiterpos[pairdelimiters[pairdelimiters.index(x)-1] + "Location"][-1]:i+1]) #add to both location lists pairdelimiterpos[pairdelimiters[pairdelimiters.index(x)-1] + "Location"].append(i) #keep track of everything pairdelimiterpos["AllList"].append(i) else: pairdelimiterpos[x + "Location"].append(i) #be smart about how to turn this on: if pairdelimiters.index(x)%2 == 0: pairdelimiterpos[x + "On"] = 1 if x in sentencedelimiters: #know the last .?! , (if any) then cut between first and last .?! #ignore pair delimiters if SentenceStartPos in range(pairdelimiterpos["AllList"][-2],pairdelimiterpos["AllList"][-1]+1) and len(pairdelimiterpos["AllList"])>=4: #find one that isn't in most recent pair k = 1 for y in SentenceStartPosList: K = len(SentenceStartPosList) if SentenceStartPosList[K-k] not in range(pairdelimiterpos["AllList"][-2],pairdelimiterpos["AllList"][-1]+1): delimstart = SentenceStartPosList[K-k] else: delimstart = 0 k += 1 else: delimstart = SentenceStartPos Morphemes.append(string[delimstart:i+1]) #keep track of everything pairdelimiterpos["AllList"].append(i) #NEW #adding this line since words "stuck" next to punctuation get lost: #Morphemes.append(string[pairdelimiterpos["AllList"][-1]:i+1]) SentenceStartPos = i+1 SentenceStartPosList.append(i+1) i += 1 #Morphemes return Morphemes ############################################################## #TESTING STAGE #print("basislist", basislist) #print("fml", Address(basislist,M_(inputtext))) #print(AutoVision(Address(basislist,M_(inputtext)),1)) #test #f2 = [[4,5],['r','g'],[1,3],[7,7],["t","y"],[555,33],[8746,8946]] #f1 = [[3,1],['g','t'],['r','y'],['y',"art"],[7,7],[90,9],[0,9],['o','o']] #print(f1) #print(f2) #print(Compose(f1,f2)) #print(M_Compose(M_(f1),M_(f2))) #print(PreImage(f1)) #print("more tests!") #print(M_(f2)) #print(Inspector_M(M_(f2))) #print(Elem_My(['r','g'],Inspector_M(M_(f2)))) #print(Elem_My([''],Inspector_M(M_(f2))))
1af790332e8b6e0f9205ebde9fcdca3d649ebc42
darshankrishna7/NTU_reference
/NTU/CZ1003 Intro To Computational Thinking/Tutorial/max_min_recur.py
1,423
4.0625
4
# Write two functions maxInList(aList) and minInList(aList) that return # the maximum and minimum value in a list of integers, aList, respectively. # You have to implement the two functions by using recursion. # Notice that max() and min() functions for lists are not allowed. import os import random def maxInList(aList): #Left final data in list means the max value if len(aList) == 1: return aList[0] else: #Python's ternary condition operator aList.pop(1) if (aList[0] > aList[1]) else aList.pop(0) return maxInList(aList) def minInList(aList): #Left final data in list means the max value if len(aList) == 1: return aList[0] else: #Python's ternary condition operator aList.pop(1) if (aList[0] < aList[1]) else aList.pop(0) return minInList(aList) def userInput(): try: aList = [ int(i) for i in input("Input a list of numbers with spacing: ").split()] except ValueError: print("[Error]\tPlease input numbers and a spacing only") return False return aList while 1: aList = userInput() #Loop again if user input number numbers if type(aList) == bool: continue #Create a new list since list is stored a address like pointers pop in one function affect the whole list aList_min = aList[:] #Get the Max and Min of the list maxNum = maxInList(aList) minNum = minInList(aList_min) print("Max value: {} \nMin value: {}".format(maxNum, minNum)) break
a5e99641706643931304846fb8e1295e8451391f
CloudChaoszero/Data-Analyst-Track-Dataquest.io-Projects
/Probability-Statistics-Beginner/Introduction to probability-48.py
2,251
3.9375
4
## 1. Probability basics ## # Print the first two rows of the data. print(flags[:2]) most_bars = flags["bars"].idxmax most_bars_country = flags["name"][most_bars] print(most_bars_country) highest_population = flags["population"].idxmax highest_population_country = flags["name"][highest_population] print(highest_population_country) ## 2. Calculating probability ## total_countries = flags.shape[0] orange_probability = flags[flags["orange"] == 1].shape[0] / total_countries stripe_probability = flags[flags["stripes"] > 1].shape[0] / total_countries ## 3. Conjunctive probabilities ## five_heads = .5 ** 5 ten_heads = .5 **10 hundred_heads = .5 **100 ## 4. Dependent probabilities ## # Remember that whether a flag has red in it or not is in the `red` column. red_countries_count = flags[flags["red"]==1].shape[0] total_countries = flags.shape[0] three_red = (red_countries_count/total_countries) * (red_countries_count-1)/(total_countries-1) * (red_countries_count-2)/(total_countries-2) ## 5. Disjunctive probability ## start = 1 end = 18000 def count_evenly_divisible(start, end, div): divisible_count = 0 for i in range(start,end+1): if (i % div) == 0: divisible_count +=1 return(divisible_count) hundred_prob = count_evenly_divisible(start, end, 100) / end seventy_prob = count_evenly_divisible(start, end, 70) / end ## 6. Disjunctive dependent probabilities ## stripes_or_bars = None red_or_orange = None length = flags.shape[0] #Finding the probability of a flag having red or orange as a color. red = flags[flags["red"]==1].shape[0] orange = flags[flags["orange"]==1].shape[0] red_and_orange = flags[(flags["red"]==1) & (flags["orange"]==1)].shape[0] red_or_orange = (red/length) + (orange/length)-(red_and_orange)/length #Finding the probability of a flag having at least one stripes or at least one bars stripes = flags[flags["stripes"]>=1].shape[0] bars = flags[flags["bars"]>=1].shape[0] stripes_and_bars = flags[(flags["stripes"]>=1) & (flags["bars"]>=1)].shape[0] stripes_or_bars = (stripes/length) + (bars/length)-(stripes_and_bars)/length ## 7. Disjunctive probabilities with multiple conditions ## heads_or = None all_three_tails = (1/2 * 1/2 * 1/2) heads_or = 1 - all_three_tails
e6da34831a48a98c7ab7bfb73575cccba22e88c4
amyjberg/algorithms
/python/merge-sort.py
1,596
4.25
4
# merge sort algorithm: # divide into subarrays of one element # merge every two subarrays together so they stay sorted # continue merging every two subarrays until we just have one sorted array def mergeSorted(listA, listB): pointerA = 0 pointerB = 0 merged = [] while pointerA < len(listA) and pointerB < len(listB): # we break out of the loop once one pointer finishes its list if listA[pointerA] < listB[pointerB]: merged.append(listA[pointerA]) # modifies original list pointerA += 1 elif listB[pointerB] < listA[pointerA]: merged.append(listB[pointerB]) pointerB += 1 else: # they are equal, so we can add and increment both merged = merged + [listA[pointerA], listB[pointerB]] pointerA += 1 pointerB += 1 # when we break out of the while loop, we might have some extra unmerged elements in one of the arrays if pointerA < len(listA): # we have leftover A elements to append return merged + listA[pointerA:] elif pointerB < len(listB): return merged + listB[pointerB:] else: # we finished both return merged def split(list): mid = Math.floor(len(list) / 2) leftHalf = list[0:mid] rightHalf = list[mid:] return [leftHalf, rightHalf] def mergeSort(list): if len(list) == 1 | len(list) == 0: return list else: halves = split(list) left = halves[0] right = halves[1] # recursive call on each half, so each half will get split into half until we get to our base case with length 1, when we will start merging them return merge(mergeSort(left), mergeSort(right))
5bf9e79ddf0b7ad1ec9ed9c7f37de1e1858e9ec9
SophieEchoSolo/PythonHomework
/Lesson12/teamD112_prog2.py
4,446
4.28125
4
""" Author: Sophie Solo and Kyle Howell Course: CSC 121 Assignment: Lesson 12 - Program 2 Description: teamD112_prog2.py - This program will generate a test and answer key, administer the test, and grade the test """ def grade_test(student_response_list, answer_list): """ Function used to grade the test taken by the student. Will take the number of correct answers, then divide it by the length of the answer list times 100 to determine a percentage. """ # creates variable to use for grading k = 0 correct_ans = 0 # variable that increments for every correct answer given # while loop to compare student answers to correct answers # loop occurs as long as the number of given answers is less than the length of the answer list while k < len(answer_list): # if the student's answer is the same as the answer of the corresponding question on the answer list, one is added to the correct_ans variable if student_response_list[k] == answer_list[k]: correct_ans += 1 # will increment regardless of whether a student's answer is correct or not until the number of answers given is the same as the length of the answer list. k += 1 percent_correct = ((correct_ans)/(len(answer_list))*100) print(f"You got {percent_correct}% right on the Test") # main function that first generates a test using one user's inputs (The "Professor"), then has a second user (the "Student") take the test. if __name__ == "__main__": # main function print("Welcome to the Multiple Choice Test Generator!") print("First, Professor, you need to tell me the answers to your test.") # Get user input for number of questions q_number = int( input("How many questions do you want to ask on the test you are creating? ")) # Create empty answer list answer_list = [] # While loop to ask for answers to the test and to validate the inputs are correct i = 0 while i != q_number: ans = input("What is the answer to question " + str(i+1) + "(A, B, C, D, or E)?: ") # Uses .upper to ensure code can handle both upper and lower case # appends the answer to the answer list if any valid answer is entered if ans.upper() in ["A", "B", "C", "D", "E"]: answer_list.append(ans.upper()) i += 1 # will execute if the user entered anything other than a valid answer, displaying an error message then asking the question again while ans.upper() != "A" and ans.upper() != "B" and ans.upper() != "C" and ans.upper() != "D" and ans.upper() != "E": print( "Sorry, but that is not a valid answer. You must enter A, B, C, D, or E.") ans = input("What is the answer to question " + str(i+1) + "(A, B, C, D, or E)?: ") # appends the answer to the answer list if any valid answer is entered if ans.upper() in ["A", "B", "C", "D", "E"]: answer_list.append(ans.upper()) i += 1 print("Okay, the Test is now Ready for Students to take the Test.") # Get student answers print("Welcome student! Good Luck on Your test!") # Create variables for student j = 0 student_response_list = [] # While loop to ask for answers from the student and to validate the inputs are correct while j < len(answer_list): student_ans = input("What is the answer to question " + str(j+1) + "(A, B, C, D, or E)?: ") # Uses .upper to ensure code can handle both upper and lower case if student_ans.upper() in ["A", "B", "C", "D", "E"]: student_response_list.append(student_ans.upper()) j += 1 while student_ans.upper() != "A" and student_ans.upper() != "B" and student_ans.upper() != "C" and student_ans.upper() != "D" and student_ans.upper() != "E": print( "Sorry, but that is not a valid answer. You must enter A, B, C, D, or E.") student_ans = input("What is the answer to question " + str(j+1) + "(A, B, C, D, or E)?: ") if student_ans.upper() in ["A", "B", "C", "D", "E"]: student_response_list.append(student_ans.upper()) j += 1 # invokes the grade_test function at the end of the program grade_test(student_response_list, answer_list)
a7f294083b725c86ff98ac4921c41eba036832a9
ttvang22/totalbillcostandbillsplit
/billsplitter.py
1,439
4.1875
4
print "Hello, this system is to help split bills among roommate" #Define roommate roommatename1 = raw_input("What is the first roommate name? ") roommatename2 = raw_input("What is the second roommate name? ") roommatename3 = raw_input("What is the third roommate name? ") roommatename4 = raw_input("What is the fourth roommate name? ") #Define Who is paying everybody = (roommatename1 , roommatename2 , roommatename3 , roommatename4) print everybody, "is all the people who are splitting the monthly bill" #Define All Bills and Cost mortgage_or_houserent = int(raw_input("Please enter monthly mortgage or house rent bills")) electricitybill = int(raw_input("Please enter eletricity bills ")) waterbill = int(raw_input("Please enter water bills ")) phonebill = int(raw_input("Please enter phone bills ")) cablebill = int(raw_input("Please enter cable bills ")) print "So your mortgage or rent is", mortgage_or_houserent, "eletricity bill is", electricitybill, "water bill is", waterbill, " phone bill is", phonebill, " and cable bill is", cablebill total_bill =sum([mortgage_or_houserent, electricitybill, waterbill, phonebill, cablebill]) print "Your total bill will be", total_bill, 'dollars' #Split Bill split_bill= total_bill/4 print "Everybody should pay", split_bill, "dollars per roommate this month for bills" #End print "I hope I can help ease eveyone monthly bill payment with this program"
746b4b9ac02cd307a5e6432d4fc99751fdfa780d
121910313014/LAB-PROGRAMS
/L7-NUMBER OF NODES.py
1,159
4.15625
4
#NUMBER OF NODES #class for nodes class Node: #constructor for creating nodes def __init__(self,data): self.data=data self.next=None #class for LinkedList class LinkedList: #constructor for initialising LinkedList def __init__(self): self.head=None #method for appending nodes def addNode(self,data): n=Node(data) if self.head is None: self.head=n return c=self.head while c.next: c=c.next c.next=n return #method for displaying list def display(self): c=self.head while c: print(c.data) c=c.next #method for finding length of list def length(self): c=self.head k=0 while c: k+=1 c=c.next return k l=LinkedList()#creating instance of class LinkedList l.addNode(1) l.addNode(2) l.addNode(3) l.addNode(4) l.addNode(5) print('the elements are:') l.display() print('length of list is',l.length())#printing length of list
0ca2e60dc6c0f9e8646a938551c64e0a9cb24005
Djam290580/lesson_6
/lesson_8/practic_8.6.except.py
1,373
3.890625
4
# Exception обязательно указывать, т.е. OwnError является помком от Exception class OwnError(Exception): def __init__(self, txt): self.txt = txt inp_data = input('Only positive numbers - ') # Задача отсечь все отрицательные значения и получать только положительные # Блок try содержит инструкции, которые могут привести к возникновению исключения # а в блоке except реализован его перехват. try: inp_data = int(inp_data) if inp_data < 0: raise OwnError('Negative number!!!') # Создается объект собственного класса исключения с помощью оператора raise # except(ошибок) может быть много except ValueError: print('Not string!!!') except OwnError as err: # err - это псевдоним!!! print(err) # else выполняется когда все хорошо, else можно использовать для явного вывода - все хорошо else: print(f'Res = {inp_data}') # finally выполняется всегда, независимо от того пошло все хорошо или плохо finally: print('Game over')
f718e572c0d7faeda3d69958410402418638aabd
Tadele01/Competitive-Programming
/Week-03/construct_bst_from_preorder.py
643
3.546875
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def bstFromPreorder(self, preorder: list[int]) -> TreeNode: if len(preorder) == 0: return None left, right = [], [] root = TreeNode(preorder[0]) for i in range(1, len(preorder)): if preorder[i] < root.val: left.append(preorder[i]) else: right.append(preorder[i]) root.left = self.bstFromPreorder(left) root.right = self.bstFromPreorder(right) return root
82b1f6abcd4adf6781cf4a75659a15d222fe7361
michaelwro/linalg-python
/examples/genSPDSystemExample.py
1,763
4.40625
4
""" EXAMPLE GENSPDSYSTEM: linalg-python Generate a dense, symmetric positive-definite system of linerar equations. SPD systems are commonly solved using iterative solvers. By: Michael Wrona Student, B.S. Aerospace Engineering Iowa State University (Ames, IA) """ import numpy as np def genSPDSystem(n): """ GENERATE SYMMETRIC-POSITIVE-DEFINITE SYSTEM OF LINEAR EQUATIONS Given a system size 'n,' generate a dense SPD system of linear equations with dimensions A[n, n] and b[n]. Return coefficient matrix 'A' and RHS vector 'b' This can be used to test iterative solvers that need SPD systems >>> n = 3 # System size A, b = genSPDSystem(n) # Return coefficients & RHS of system Uses method found on Stack Overflow forum: https://math.stackexchange.com/a/358092 """ if type(n) != int: print("INPUT 'n' TYPE MUST BE 'int' IN ROUTINE 'genSPDSystem()'") return Atemp = np.random.rand(n, n) # Generate random coef. matrix 'A' Atrans = np.zeros([n, n], dtype="float64") A = np.zeros([n, n], dtype="float64") # Compute transpose for i in range(n): for j in range(n): Atrans[i, j] = Atemp[j, i] # Compute matrix multiplication for i in range(n): for j in range(n): out = 0 for k in range(n): out += (Atemp[i, k] * Atrans[k, j]) + n A[i, j] = out b = np.random.rand(n) # Generate RHS vector 'b' return A, b """ To confirm the system is positive-definite, the determinant of the coefficient matrix should be positive and non-singular """ n = 3 A, b = genSPDSystem(n) print("Coefficient matrix:") print(A) print("\nSolution/LHS:") print(b) print("Det(A) = %0.8f" % (np.linalg.det(A)))
53524b3199aa1cf0063f1d61d359df054ad8db1d
whiteydoublee/Python
/Ch06/sub1/StockAccount.py
852
3.625
4
from Ch06.sub1.Account import Account #Inheritance : class 이름(상속할 부모 클래스이름) class StockAccount(Account): def __init__(self,bank,id,name,balance,stock,amount,price): super().__init__(bank,id,name,balance) self.stock = stock self.amount = amount self.price = price def sell(self,amount, price): self._balance+=amount*price def buy(self,amount,price): self._balance -=amount*price def show(self): print('-------------------------------------') print('은행명: ', self._bank) print('계좌번호: ', self._id) print('입금주: ', self._name) print('현재잔액: ', self._balance) print('주식종목:',self.amount) print('주식가격:',self.price) print('-------------------------------------')
318f87e73389aeeb7aea98d25e3c1ab174ca42b6
zzandland/Algo-DS
/Python/Amazon_2020_03/optimal_utilization.py
5,566
3.875
4
# Given 2 lists a and b. Each element is a pair of integers where the first integer represents the unique id and the second integer represents a value. Your task is to find an element from a and an element form b such that the sum of their values is less or equal to target and as close to target as possible. Return a list of ids of selected elements. If no pair is possible, return an empty list. # Example 1: # Input: a1 = [[1, 2], [2, 4], [3, 6]] b1 = [[1, 2]] target1 = 7 # Output: [[2, 1]] # Explanation: # There are only three combinations [1, 1], [2, 1], and [3, 1], which have a total sum of 4, 6 and 8, respectively. # Since 6 is the largest sum that does not exceed 7, [2, 1] is the optimal pair. # Example 2: # Input: a2 = [[1, 3], [2, 5], [3, 7], [4, 10]] b2= [[1, 2], [2, 3], [3, 4], [4, 5]] target2 = 10 # Output: [[2, 4], [3, 2]] # Explanation: # There are two pairs possible. Element with id = 2 from the list `a` has a value 5, and element with id = 4 from the list `b` also has a value 5. # Combined, they add up to 10. Similarily, element with id = 3 from `a` has a value 7, and element with id = 2 from `b` has a value 3. # These also add up to 10. Therefore, the optimal pairs are [2, 4] and [3, 2]. # Example 3: # Input: a3 = [[1, 8], [2, 7], [3, 14]] b3 = [[1, 5], [2, 10], [3, 14]] target3 = 20 # Output: [[3, 1]] # Example 4: # Input: a4 = [[1, 8], [2, 15], [3, 9]] b4 = [[1, 8], [2, 11], [3, 12]] target4 = 20 # Output: [[1, 3], [3, 2]] # from typing import List # from collections import defaultdict # import sys # class Solution: # def binarySearch(self, a: List[int], b: List[int], target: int) -> List[int]: # A, B = sorted(a, key=lambda x: x[1]), sorted(b, key=lambda x: x[1]) # if len(A) < len(B): short, long = A, B # else: short, long = B, A # def bs(nums: List[int], rem: int) -> int: # left, right = 0, len(nums)-1 # while left < right: # mid = left + (right-left)//2 # if nums[mid][1] == rem or (nums[mid+1][1] > rem and nums[mid][1] < rem): # return mid # if nums[mid][1] < rem: left = mid+1 # else: right = mid # return left if nums[left][1] < rem else left-1 # d = defaultdict(list) # for i, sn in enumerate(short): # j = bs(long, target-sn[1]) # if j != -1: # pair = [sn[0], long[j][0]] if short == A else [long[j][0], sn[0]] # d[sn[1]+long[j][1]].append(pair) # return sorted(d[max(d.keys())], key=lambda x:x[0]) # def twoPointers(self, a: List[int], b: List[int], target: int) -> List[int]: # A, B = sorted(a, key=lambda x: x[1]), sorted(b, key=lambda x: x[1]) # M, N = len(A), len(B) # m, n, max_, output = 0, N-1, -sys.maxsize-1, [] # while m < M and n >= 0: # sum_ = A[m][1] + B[n][1] # print() # if sum_ > target: n-=1 # else: # if sum_ > max_: # max_ = sum_ # output = [] # output.append([A[m][0], B[n][0]]) # cnt = n # while cnt >= 1 and B[cnt][1] == B[cnt-1][1]: # output.append([A[m][0], B[cnt-1][0]]) # cnt-=1 # m+=1 # return output # def main(): # res = Solution().twoPointers(a, b, target) # print(res) from typing import List import bisect def brute_force(a: List[List[int]], b: List[List[int]], target: int) -> List[List[int]]: """ >>> brute_force(a1, b1, target1) [[2, 1]] >>> brute_force(a2, b2, target2) [[2, 4], [3, 2]] >>> brute_force(a3, b3, target3) [[3, 1]] >>> brute_force(a4, b4, target4) [[1, 3], [3, 2]] """ # organize pairs by sum -> exclude sums over the target O(a*b) O(max(a, b)) res = [] seen = set() mxSum = float('-inf') for i, n1 in a: for j, n2 in b: sm = n1 + n2 if sm <= target and (i, j) not in seen: if sm > mxSum: seen.clear() res.clear() mxSum = sm if sm == mxSum: res.append([i, j]) seen.add((j, i)) # return the array from the biggest sum within the target val return res def binary_search(a: List[List[int]], b: List[List[int]], target: int) -> List[List[int]]: ''' >>> brute_force(a1, b1, target1) [[2, 1]] >>> brute_force(a2, b2, target2) [[2, 4], [3, 2]] >>> brute_force(a3, b3, target3) [[3, 1]] >>> brute_force(a4, b4, target4) [[1, 3], [3, 2]] ''' # make sure that b is longer than a if len(a) > len(b): a, b = b, a # sort b to use binary search on it O(b log b) b.sort(key=lambda x: x[1]) res = [] seen = set() mxSum = float('-inf') # iterate a O(a) -> O(a log b) tmp = [val for _, val in b] for i, n in a: rest = target - n # binary search for b ele equal or smaller than target - O(log b) idx = bisect.bisect_left(b, tmp) if tmp[idx] > mxSum: res.clear() seen.clear() mxSum = tmp[idx] j = b[idx][0] if tmp[idx] == mxSum and (i, j) not in seen: res.append([i, j]) seen.append((j, i)) return res if __name__ == '__main__': import doctest doctest.testmod()
ab3d768830aa63824722b59464c52ee4be0b53fa
FGolOV/rot
/main.py
1,647
3.59375
4
num=int(input('Введите число, состоящее только из цифр 6 и 9 ')) #Функция принмимает на вход целое число def rot(num): #Объявляем ф-цию num_list=[] #Создаем пустой список while num>0: #Цикл, который преобразует целое число в список путем внесения в список остатка от деления числа на 10 num_list.append(num%10) num//=10 num_list.reverse() #Цикл, очевидно, вносит цифры в список задом наперед, переврнем полученный список lenght_of_num_list= len(num_list) #Передадим длину списка-числа в переменную for i in range (lenght_of_num_list): #Условие, при котором программа дальше выполняться не будет if num_list[i]!=6 and num_list[i]!=9: # print('Вы ввели не соответсвующее условию число') exit() for i in range (lenght_of_num_list): #Цикл, находящий внутри списка-числа 6 наибольшего разряда и меняющий ее на 9 if num_list[i]==6: num_list[i]=9 break num_list_int= int("".join([str(l) for l in num_list])) #Цикл, преобразующий список обратно в число return num_list_int print('Результат вращения- ',rot(num)) #Вызов функции
a1c54d0c0bad8b68d39c2f9f3af4d86a2587f9a6
adhitizki/List_Spinner
/soal_2.py
929
4
4
def counter_clockwise(masukan): list_baru = [] #untuk list yang nanti digunakan untuk mengisi list yang sudah diputar for i in range(len(masukan[0])-1,-1,-1): #untuk memberikan index pada baris dimana ketika diputar akan menjadi kolom list_baris = [] #membuat list untuk baris baru yang sudah diputar for j in range(len(masukan)): #untuk memberikan index pada kolom dimana ketika diputar akan menjadi baris list_baris.append(masukan[j][i]) #menambahkan angka untuk satu dengan tiap kolom yang dari baris sebelumnya list_baru.append(list_baris) #list baru yang merupakan list hasil counter clock wise return list_baru #mengembalikan nilai fungsi awal list_awal = [[1,2,3], [4,5,6], [7,8,9]] print(counter_clockwise(list_awal)) for i in counter_clockwise(list_awal): #supaya menampilkan dengan setelah baris ter-enter print(i)
22e4b80cec5d87cd7fba527a129ff4e0030c7665
frankwwu/machine-learning-exercise
/coursera-machine-learning-python/ex5/linear_reg_cost_function.py
1,045
4.1875
4
import numpy as np def linear_reg_cost_function(theta, X, y, l): """ Compute cost and gradient for regularized linear regression with multiple variables. Parameters ---------- theta : ndarray, shape (n_features,) Linear regression parameter. X : ndarray, shape (n_samples, n_features) Samples, where n_samples is the number of samples and n_features is the number of features. y : ndarray, shape (n_samples,) Labels. l : float Regularization parameter. Returns ------- j : numpy.float64 The cost of using theta as the parameter for linear regression. grad : ndarray, shape (n_features,) The gradient of using theta as the parameter for linear regression. """ m = X.shape[0] j = 1.0 / (2 * m) * np.sum(np.square(X.dot(theta) - y)) + 1.0 * l / (2 * m) * np.sum(np.square(theta[1:])) mask = np.eye(len(theta)) mask[0, 0] = 0 grad = 1.0 / m * X.T.dot(X.dot(theta) - y) + 1.0 * l / m * (mask.dot(theta)) return j, grad
07e3b9829b4df69813d316f8d7a7539493a37bbf
juliachristensen/PS239T_Fall2019
/04_python-basics/15_Errors.py
11,683
3.671875
4
# coding: utf-8 # # Errors and Exceptions # # **Time** # - teaching: 10 min # - exercises: 10 min # # **Questions**: # - "How do a read an error message?" # - "What do the error messages mean?" # - "How do a fix an error?" # - "What if I still can't figure it out?" # # **Learning Objectives**: # # * To be able to read a traceback, and determine the following relevant pieces of information: # * The file, function, and line number on which the error occurred # * The type of the error # * The error message # * To be able to describe the types of situations in which the following errors occur: # * `SyntaxError` and `IndentationError` # * `NameError` # * `IndexError` and `TypeError` # * `IOError` # * Debug code containing an error systematically. # # ***** # # ## Every programmer encounters errors # * both those who are just beginning, and those who have been programming for years. # * Encountering errors and exceptions can be very frustrating at times # * But understanding what the different types of errors are # and when you are likely to encounter them can help a lot. # * Once you know *why* you get certain types of errors, # they become much easier to fix. # # ## Errors in Python come in specific form, called a [traceback](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#traceback). # # Let's examine one: # In[1]: import errors_01 errors_01.favorite_ice_cream() # - This particular [traceback](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#traceback) has two levels. # - You can determine the number of levels by looking for the number of arrows on the left hand side. # - The last level is the actual place where the error occurred. # - The other level(s) show what function the program executed to get to the next level down. # # So, in this case, the program: # # 1. first performed a [function call](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#function-call) to the function `favorite_ice_cream`. # # 2. Inside this function, the program encountered an error on Line 7, when it tried to run the code `print ice_creams[3]`. # # ## Long Tracebacks # # > Sometimes, you might see a traceback that is very long -- sometimes they might even be 20 levels deep! # > This can make it seem like something horrible happened, # > but really it just means that your program called many functions before it ran into the error. # > Most of the time, # > you can just pay attention to the bottom-most level, # > which is the actual place where the error occurred. # # So what error did the program actually encounter? # # ## Python tells us the category or [type of error](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#type-of-error) # # In this case, it is an `IndexError`. Python then prints a more detailed error message (in this case, it says "list index out of range"). # # - If you encounter an error and don't know what it means, it is still important to read the traceback closely. # - That way, if you fix the error, but encounter a new one, you can tell that the error changed. # - sometimes just knowing *where* the error occurred is enough to fix it, even if you don't entirely understand the message. # # # ## Python reports a [syntax error](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#syntax-error) when it can't understand the source of a program. # # - People can typically figure out what is meant by text with no punctuation, # but people are much smarter than computers. # - If Python doesn't know how to read the program, # it will just give up and inform you with an error. # For example: # In[4]: def some_function() msg = "hello, world!" print(msg) return msg # - Here, Python tells us that there is a `SyntaxError` on line 1, # and even puts a little arrow in the place where there is an issue. # - In this case the problem is that the function definition is missing a colon at the end. # # ## Indentation is meaningful in Python # - If we fix the problem with the colon, # we see that there is *also* an `IndentationError`, # which means that the lines in the function definition do not all have the same indentation: # In[ ]: def some_function(): msg = "hello, world!" print(msg) return msg # - Both `SyntaxError` and `IndentationError` indicate a problem with the syntax of your program, # but an `IndentationError` is more specific: # it *always* means that there is a problem with how your code is indented. # # ## Tabs and Spaces # # > A quick note on indentation errors: # > they can sometimes be insidious, # > especially if you are mixing spaces and tabs. # > Because they are both [whitespace](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#whitespace), # > it is difficult to visually tell the difference. # > The IPython notebook actually gives us a bit of a hint, # > but not all Python editors will do that. # > In the following example, # > the first two lines are using a tab for indentation, # > while the third line uses four spaces: # In[ ]: def some_function(): msg = "hello, world!" print(msg) return msg # ## A `NameError`, and occurs when you try to use a variable that does not exist # # For example: # In[5]: print(a) # Why did you get this error? # # - you might have meant to use a [string](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#string), but forgot to put quotes around it: # In[6]: print(hello) # - or you just forgot to create the variable before using it. # - In the following example, # `count` should have been defined (e.g., with `count = 0`) before the for loop: # In[7]: for number in range(10): count = count + number print("The count is: " + str(count)) # - or you might have made a typo when you were writing your code. # In[ ]: Count = 0 for number in range(10): count = count + number print("The count is: " + str(count)) # ## Type and Index Errors # # - Next up are errors having to do with containers (like lists and dictionaries) and the items within them. # - If you try to access an item in a list or a dictionary that does not exist, # then you will get an error. # In[ ]: letters = ['a', 'b', 'c'] print("Letter #1 is " + letters[0]) print("Letter #2 is " + letters[1]) print("Letter #3 is " + letters[2]) print("Letter #4 is " + letters[3]) # Here, Python is telling us that there is an `IndexError` in our code, meaning we tried to access a list index that did not exist. # # A similar error occurs when we confuse types; that is, when we try to use a [method](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#method) or syntax relevant to one type on another type that doesn't like it. # In[ ]: a_dictionary = {'beyonce', 'is', 'the', 'greatest'} a_list = [a_dictionary] a_list['name'] # ## File Errors # # - The last type of error we'll cover today are those associated with reading and writing files: `IOError`. # # - If you try to read a file that does not exist, # you will recieve an `IOError` telling you so. # In[ ]: file_handle = open('myfile.txt', 'r') # - One reason for receiving this error is that you specified an incorrect path to the file. # - Or you could be using the "read" flag instead of the "write" flag. # In[ ]: file_handle = open('myfile.txt', 'w') file_handle.read() # ## Challenges 1: Reading Error Messages # # Read the traceback below, and identify the following pieces of information about it: # # 1. How many levels does the traceback have? # 2. What is the file name where the error occurred? # 3. What is the function name where the error occurred? # 4. On which line number in this function did the error occurr? # 5. What is the type of error? # 6. What is the error message? # In[ ]: import errors_02 errors_02.print_friday_message() # ## Challenge 2. Identifying Syntax Errors # # 1. Read the code below, and (without running it) try to identify what the errors are. # 2. Run the code, and read the error message. Is it a `SyntaxError` or an `IndentationError`? # 3. Fix the error. # 4. Repeat steps 2 and 3, until you have fixed all the errors. # In[ ]: def another_function print "Syntax errors are annoying." print"But at least python tells us about them!" print "So they are usually not too hard to fix." # ## Challenge 3. Identifying Variable Name Errors # # 1. Read the code below, and (without running it) try to identify what the errors are. # 2. Run the code, and read the error message. What type of `NameError` do you think this is? In other words, is it a [string](https://github.com/dlab-berkeley/python-intensive/blob/master/Glossary.md#string) with no quotes, a misspelled variable, or a variable that should have been defined but was not? # 3. Fix the error. # 4. Repeat steps 2 and 3, until you have fixed all the errors. # In[ ]: for number in range(10): # use a if the number is a multiple of 3, otherwise use b if (Number % 3) == 0: message = message + a else: message = message + "b" print(message) # ## Challenge 4. Identifying Item Errors # # 1. Read the code below, and (without running it) try to identify what the errors are. # 2. Run the code, and read the error message. What type of error is it? # 3. Fix the error. # In[ ]: seasons = ['Spring', 'Summer', 'Fall', 'Winter'] print('My favorite season is ', seasons[4]) # ## Debugging Strategies # # ### Know what it's supposed to do # # The first step in debugging something is to *know what it's supposed to do*. "My program doesn't work" isn't good enough: in order to diagnose and fix problems, we need to be able to tell correct output from incorrect. If we can write a test case for the failing case --- i.e., if we can assert that with *these* inputs, the function should produce *that* result --- then we're ready to start debugging. If we can't, then we need to figure out how we're going to know when we've fixed things. # # ### Start with a simplified case. # # If you're writing a multi-step loop or function, start with one case and get to work. Then ask what you need to do to generalize to many cases. # # ### Divide and conquer # # We want to localize the failure to the smallest possible region of code. The smaller the gap between cause and effect, the easier the connection is to find. Many programmers therefore use a **divide and conquer** strategy to find bugs, i.e., if the output of a function is wrong, they check whether things are OK in the middle, then concentrate on either the first or second half, and so on. # # ### Change One Thing at a Time, For a Reason # # Replacing random chunks of code is unlikely to do much good. (After all, if you got it wrong the first time, you'll probably get it wrong the second and third as well.) Good programmers therefore *change one thing at a time, for a reason*. They are either trying to gather more information ("is the bug still there if we change the order of the loops?") or test a fix ("can we make the bug go away by sorting our data before processing it?"). # # Every time we make a change, however small, we should re-run our tests immediately, because the more things we change at once, the harder it is to know what's responsible for what. # # ### Outside Resources # # If you've tried everything you can think of to logically fix the error and still don't understand what Python is trying to tell you, now the real searching begins. Go to Google and copy/paste the error, you're probably not the only one who has run into it!
1455321388ca58a8a23eeefbf286638bdd41de33
n18013/programming-term2
/src/algo-p2/task20180807_q04.py
542
4.09375
4
#変数fruitsに辞書を代入してください # ('apple'というキーに対し'りんご'という値、'banana'というキーに対し'バナナ'という値のふたつ) fruits = {'apple': 'りんご', 'banana':'バナナ'} #辞書fruitsのキー「banana」に対応する値を出力してください print('バナナ') #辞書fruitsを用いて、「appleは◯◯という意味です」となるように出力してください for name in fruits.items(): print('appleは' + 'アップル' + 'という意味です。')
45887d1553d33ec93227b561618c66356b78153c
JulianMW/python-resources
/data-structures/heapify_max.py
895
4.09375
4
def heapify_helper(arr, n, i): largest = i # Initialize largest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists and is # greater than root if l < n and arr[i] < arr[l]: largest = l # See if right child of root exists and is # greater than root if r < n and arr[largest] < arr[r]: largest = r # Change root, if needed if largest != i: arr[i],arr[largest] = arr[largest],arr[i] # swap # Heapify the root. heapify_helper(arr, n, largest) def heapify(arr): n = len(arr) for i in range(n//2, -1, -1): heapify_helper(arr, n, i) # Finally, to print the heap in order: for i in range(len(arr)): arr[0], arr[-1] = arr[-1], arr[0] print(arr.pop()) heapify_helper(arr, len(arr), 0)
29a2d5e47ea97b04bb1162604eb016673c7fff60
flame4ost/Python-projects
/§7(178-250)/z180.py
268
3.640625
4
import math n = (int(input("Введите число n "))) i = 3 for i in range(n): x = i*i*i-3*i*n*n+n print(i,'. ',x) if (frac(x/3)==0) and (odd(round(x//3))): s = s+x print(x, ' - утроенное нечетное') print("s = ", s)
700065aec87bf2f9514e2d1c7f1e75377c6d8463
bayramcicek/language-repo
/p014_dictionary.py
2,949
4.0625
4
#!/usr/bin/python3.6 # created by cicek on 07.08.2018 22:06 ages = {"dave":34, "ahmet":65} print(ages["dave"]) # 34 list = {5:90, 1:34, 2:[11,99,65], 3:777} print(list[5]) # 90 print(list[2][1]) # 99 ages = {"Dave": 24, "Dave": 42, "John": 58} print(ages["Dave"]) # 42 duplicate key, used the last value myDic = {"hey":"merhaba", "hola":"selam"} print(myDic["hola"]) # selam # print(myDic["selam"]) # KeyError: 'selam' empty = {} print(empty) # {} # print(empty[0]) # keyError # Only immutable objects can be used as keys to dictionaries. Immutable objects are those that can't be changed. # So far, the only mutable objects you've come across are lists and dictionaries. # Trying to use a mutable object as a dictionary key causes a TypeError. # Immutable objects (sabit/değiştirilemeyen)= cannot be changed after it's created # mutable objects (değiştirilebilen)= that can change their value # Here's the list of class that are immutable:/hashable # # 1. Bool # 2. int # 3. float # 4. tuple # 5. str # 6. frozen set # # And Here's the list of class that are mutable:/unhashable # # 1. list # 2. set # 3. dict # One way to test whether a variable is mutable or not is to copy it to a new variable, then change the first variable: # > a = 8 # > b = a # > a += 2 # > print(a) # 10 # > print(b) # 8 # > # Integers are immutable, since a change to 'a' was not a change in 'b'. # # > a = "hello" # > b = a # > a = "goodbye" # > print(a) # "goodbye" # > print(b) # "hello" # > # Strings are immutable, since a change to 'a' was not a change in 'b'. # # > a = ['do', 're', 'mi'] # > b = a # > a.append('fa') # > print(a) # ['do', 're', 'mi', 'fa'] # > print(b) # ['do', 're', 'mi', 'fa'] # > # Lists are mutable, since a change to 'a' was also a change to 'b'. # unhashable = something that can't be stored in dictionaries An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method). # A list is unhashable because its contents can change over its lifetime # bad_dict = { # [1, 2, 3]: "one two three", # } # TypeError: unhashable type: 'list' if True: # uppercase letter "F" print("s") squares = {1:1, 2:4, 3:"error", 4:16} squares[8] = 64 squares[3] = 9 squares[9] = 81 squares[7] = 49 # This code is to show that # DICTIONARIES are NOT ordered. # Clear hash signs in rows below # one by one and observe # how the resulting output behaves # each time a new key is added # in an unordered manner. squares["orange"] = "blue" squares["apple"] = "green" squares[5] = 25 squares["peach"] = squares["orange"] print(squares) nums = { 1: "one", 2: "two", 3: "three", } print(1 in nums) print("three" in nums) print(4 not in nums) # True pairs = {1: "apple", "orange": [2, 3, 4], True: False, None: "True", } print(pairs.get("orange")) print(pairs.get(7)) print(pairs.get(12345, "not in dictionary")) # LIST.GET (A, "ALTERNATIVE RETURN") print(pairs.get(1)) # False
70b353b2b4b7a018a9d814c593545ad2909e353d
vivianmaxine/hello-flask
/main_form_values.py
1,731
3.671875
4
from flask import Flask, request #request object allows us to access data in request user sent to server #via python #POST refers to a methods parameter via request.form['param_name'] app = Flask(__name__) app.config['DEBUG'] = True """GOAL 1: Change Index Handler so it returns HTML that consists of form that user can interact with""" #Create global variable form = """ <!DOCTYPE html> <html> <head> <title>Hello Flask Form</title> </head> <body> <form method="post"> <label for salutation>Salutation:</label> <select id="salutation" name="salutation"> <option value="Mr. ">Mr.</option> <option value="Miss ">Miss</option> <option value="Ms. ">Ms.</option> <option value="Ms. ">Ms.</option> </select> <p><label for first_name>First Name:</label> <input id="first_name" type="text" name="user_name"></p> <p><label for origin_city>City of Origin:</label> <input id="origin_city" type="text" name="origin_city"></p> <input type="submit"> </form> </body> </html> """ @app.route("/") def index(): return form """GOAL 2: Write code to handle our submission to allow a form to be processed (can customize values to be printed)""" @app.route("/form-inputs") def display_form_inputs(): return form @app.route("/form-inputs", methods=['POST']) def print_form_values(): #use get request object by using request.args.get with name resp = "" for field in request.form.keys(): resp += "<b>{key}</b>: {value}<br>".format(key=field, value=request.form[field]) return resp """ #For POST request, data not exposed in URL: http://127.0.0.1:5000/hello """ app. run()
9b7bee441f4d306e9cabbd8d31368c8201d72be4
pankaj307/Data_Structures_and_Algorithms
/LinkedList/reverseLinkedList.py
578
4.125
4
import my_LinkedList def reverse(l1): cur = l1.head prev = None while cur: nxt = cur.next cur.next = prev prev = cur cur = nxt l1.head = prev def reverseRecursive(cur,prev): if cur is None: return prev nxt = cur.next cur.next = prev return reverseRecursive(nxt,cur) l1 = my_LinkedList.LinkedList() l1.insert(10) l1.insert(20) l1.insert(30) print('Recursive') l1.head = reverseRecursive(l1.head,None) l1.printList() print() print('Iterative') reverse(l1) l1.printList()
6e02ca47369b3f7205d8dd119dfe8f3944051b80
itspratham/Python-tutorial
/Python_Contents/Sample_Programs/ll.py
2,330
4.03125
4
# class Node: # def __init__(self, data): # self.data = data # self.next = None # # # class LL: # def __init__(self): # self.head = None # # def append(self, data): # headd = self.head # if self.head is None: # self.head = Node(data) # return # while headd.next is not None: # headd = headd.next # headd.next = Node(data) # return # # def print_list(self): # headd = self.head # while headd: # print(headd.data) # headd = headd.next # return # # def middle_element(self): # dict_map = dict() # headd = self.head # length = 0 # while headd: # length = length + 1 # dict_map[length] = headd.data # headd = headd.next # lee = length // 2 # return dict_map[lee] # # def find_the_third_element(self): # try: # a_list = [] # headd = self.head # while headd: # a_list.append(headd.data) # headd = headd.next # return a_list[-2] # except: # return "" # # def reverse_list(self): # prev = None # current = self.head # while current is not None: # next = current.next # current.next = prev # prev = current # current = next # self.head = prev # # # ll = LL() # ll.append("A") # ll.append("B") # ll.append("C") # ll.append("D") # ll.append("E") # ll.append("F") # ll.append("G") # ll.append("H") # ll.print_list() # # print(ll.middle_element()) # # print(ll.find_the_third_element()) # print("===============") # ll.reverse_list() # ll.print_list() # # def second_max(arr): # maxx = -999999 # second_max = arr[0] # for i in range(len(arr)): # if arr[i] > maxx: # maxx = arr[i] # for j in range(len(arr)): # if arr[j] != maxx and arr[j] > second_max: # second_max = arr[j] # return second_max # # # print(second_max([3, 4, 44, 56, 77, 78, 2])) class MEthod_Overloading: def ssum(self, a, b, c=0): return a + b + c def ssum(self, a, b): return a + b v = MEthod_Overloading() print(v.ssum(a=4, b=5, c=7))
45f298202f0e1384d387d8e9886b89fc4022803d
lacekim/Nueral_Networks
/ch6.py
2,501
3.546875
4
import matplotlib.pyplot as plt import nnfs import numpy as np from nnfs.datasets import vertical_data, spiral_data from ch4 import Activation_ReLU from ch5 import Layer_Dense, Activation_Softmax, Loss_CategoricalCrossentropy nnfs.init() X, y = spiral_data(samples=100, classes=3) # Create dataset X, y = vertical_data(samples=100, classes=3) # Create model dense1 = Layer_Dense(2, 3) # first dense layer, 2 inputs activation1 = Activation_ReLU() dense2 = Layer_Dense(3, 3) # second dense layer, 3 inputs, 3 outputs activation2 = Activation_Softmax() # Create loss function loss_function = Loss_CategoricalCrossentropy() # Helper variables lowest_loss = 9999999 # some initial value best_dense1_weights = dense1.weights.copy() best_dense1_biases = dense1.biases.copy() best_dense2_weights = dense2.weights.copy() best_dense2_biases = dense2.biases.copy() for iteration in range(10000): # Update weights with some small random values dense1.weights += 0.05 * np.random.randn(2, 3) dense1.biases += 0.05 * np.random.randn(1, 3) dense2.weights += 0.05 * np.random.randn(3, 3) dense2.biases += 0.05 * np.random.randn(1, 3) # Perform a forward pass of the training data through this layer dense1.forward(X) activation1.forward(dense1.output) dense2.forward(activation1.output) activation2.forward(dense2.output) # Perform a forward pass through activation function # it takes the output of second dense layer here and returns loss loss = loss_function.calculate(activation2.output, y) # Calculate accuracy from output of activation2 and targets # calculate values along first axis predictions = np.argmax(activation2.output, axis=1) accuracy = np.mean(predictions==y) # If loss is smaller - print and save weights and biases aside if loss < lowest_loss: print('New set of weights found, iteration:', iteration, 'loss:', loss, 'acc:', accuracy) best_dense1_weights = dense1.weights.copy() best_dense1_biases = dense1.biases.copy() best_dense2_weights = dense2.weights.copy() best_dense2_biases = dense2.biases.copy() lowest_loss = loss # Revert weights and biases else: dense1.weights = best_dense1_weights.copy() dense1.biases = best_dense1_biases.copy() dense2.weights = best_dense2_weights.copy() dense2.biases = best_dense2_biases.copy() plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap='brg') plt.show()
efee66f212089430f30441c932c6406ff94410a9
gjwlsdnr0115/algorithm-study
/data-structure/Queue.py
544
3.75
4
# 1. use deque # add, del: O(1) from collections import deque # deque init dq = deque([]) # add data dq.append(1) dq.append(2) dq.append(3) dq.append(4) print(dq) # deque([1, 2, 3, 4]) print(dq.popleft()) # 1 print(dq.popleft()) # 2 print(dq.popleft()) # 3 print(dq.popleft()) # 4 print(dq) # deque([]) # 2. use queue import queue # queue init q = queue.Queue() # add data q.put(1) q.put(2) q.put(3) q.put(4) print(q.get()) # 1 print(q.get()) # 2 print(q.get()) # 3 print(q.get()) # 4 l = [1, 2, 3, 4] l3 = l + l.reverse()
5abd1b96411db367eb2aabe511b62942deef4e14
DmitriyA13/Chess-knight
/knight.py
874
4
4
""" knight""" def Enter(x): while True: try: int(x) if int(x) > 0: break else: print('cannot be less than zero or equals zero') return Enter(input('try again >')) except ValueError: print('entered not numbers') return Enter(input('try again >')) return int(x) uprightStart = Enter(input('Upright Start >')) horizontallyStart = Enter(input('Horizontally Start >')) print('-'*20) uprightFinish = Enter(input('Upright Finish >')) horizontallyFinish = Enter(input('Horizontally Finish >')) if abs(uprightStart-uprightFinish) == abs(horizontallyStart-horizontallyFinish) or uprightStart == uprightFinish or horizontallyStart == horizontallyFinish or abs(uprightStart-uprightFinish)+abs(horizontallyStart-horizontallyFinish) > 3: print('NO') else: print('YES') input()
34a34f0bc4b721674f7c41c26f3bf02a8b192046
Timur597/First6team
/6/Tema2(if,elife,else)/12.if_0.py
57
3.71875
4
aa=10 bb=5 if aa>bb: print("aa+2") else: print("bb+2")
ad7a8704fdc738c00868f9dd50607f1d9bd0d9a5
GAURAV-GAMBHIR/pythoncode
/5.8.py
243
3.625
4
print("\n\n") list4 = [input("Enter element : ") for x in range(10)] x = input("\nEnter element to be deleted : ") for y in range(len(list4)): if x==list4[y] : del list4[y] break; print("After deletion : ",list4)
bdcd03389298becf48e714c054677171f959c10d
lizzzcai/leetcode
/python/greedy/0402_Remove_K_Digits.py
1,913
3.703125
4
''' 13/05/2020 402. Remove K Digits - Medium Tag: Stack, Greedy Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. Note: The length of num is less than 10002 and will be ≥ k. The given num does not contain any leading zero. Example 1: Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. Example 2: Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. Example 3: Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0. ''' from typing import List # Solution class Solution1: ''' Time complexity : O(n) Space complexity : O(n) ''' def removeKdigits(self, num: str, k: int) -> str: q = [] for x in num: while k and q and q[-1] > x: q.pop() k -= 1 q.append(x) # if still k>0, remove from last if k: q = q[:-k] # remove the leading 0 idx = 0 while idx < len(q) and q[idx] == '0': idx += 1 return ''.join(q[idx:]) or '0' # Unit Test import unittest class TestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_testCase(self): for Sol in [Solution1()]: func = Sol.removeKdigits self.assertEqual(func("1432219",3), '1219') self.assertEqual(func("10200",1), '200') self.assertEqual(func("10",2), '0') self.assertEqual(func("9",1), '0') self.assertEqual(func("112",1), '11') if __name__ == '__main__': unittest.main()
126497ab4bccf3aac6d5f1152a0c86459271cc34
suhang319/exercise
/作业/作业.py
1,935
3.5625
4
#_*_ coding:utf-8 _*_ #@Time :2020-12-1920:21 #@Author :lemon_suhang #@Email :1147967632@qq.com #@File :作业.py #@Software:PyCharm # 1.5层打印,外层循环 m=5 m=1 # 内层循环控制个数你n<=m m=1 while m<=5: n=1 while n<=m: print("*",end='') n +=1 print() m +=1 # 字符串去重 # str1 ="aabbbcddef" str2='' for i in str1: if str1.count(i)==1: str2+=i print(str2) # 100被3整除的数 list =[] for i in range(1,101): if i % 3 ==0: list.append(i) print(list) # 列表去重 列表[1,2,3,4,3,4,2,5,5,8,9,7],将此列表去重, # 得到一个唯一元素的列表 list =[1,2,3,4,3,4,2,5,5,8,9,7] list2=[] for i in list: if i not in list2: list2.append(i) print(list2) list1 = [1,1] m =1 n = int(input("输入")) while m<=n: num = list1[-1] + list2[-2] list1.append(num) m +=1 print(list1) str1 = 'welocme to super&Test' str2 = str1.split(' ')[-1] print(str2) list1 =str2.split('&') resuil =''.join(list1) print(resuil) # str1 = 'welocme to super&Test' # str2= [] # # for i in str1.split(" "): # i = list(i) # # n =0 # while n < len(i)/2: # i[n],i[len(i)-n-1]=i[len(i)-n-1],i[n] # n +=1 # str2.append(''.join(i)) # result = ''.join(str2[::-1]) # print(result) str1 = 'welocme to super&Test' str2 = [] for i in str1.split(' '): i = list(i) #实现单个字符串反转 n = 0 while n < len(i)/2: i[n],i[len(i)-n-1] = i[len(i)-n-1],i[n] n += 1 # 将反转后字符串拼接,然后追加到新列表中 str2.append(''.join(i)) # 倒叙输出并通过空格隔开每次反转后的字符串 result = ' '.join(str2[::-1]) print(result) str1 = 'abcdef' str2 = list(str1) n =0 while n <len(str2)/2: tmp = str2[n] str2[2]=str2[len(str2)-n-1] str2[len(str2)-n-1]=tmp n ==1 print(str2,str1) print("".join(str2))
62f8d684cadaaacc2318897ae4adb67c742f8f6f
alexandraback/datacollection
/solutions_5738606668808192_1/Python/ppsreejith/c.py
1,208
3.625
4
from collections import defaultdict primes = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541] T = int(input()) N, J = map(int, raw_input().split()) x = int("1"+"0"*(N-2)+"1", 2) ans = defaultdict(list) def add_factor(coin, fact): ans[coin].append(str(fact)) def remove_coin(coin): if coin in ans: ans.pop(coin) def find_factor(num): for prime in primes: if num % prime == 0: return prime return False while len(ans) < J: x += 2 coin = bin(x)[2:] for base in xrange(2, 11): no = int(coin, base) fac = find_factor(no) if fac: add_factor(coin, fac) else: remove_coin(coin) break print "Case #1:" for coin in ans: print "%s %s" % (coin, " ".join(ans[coin]))
52a1dc0793292a96915c0928606fd75af1117253
poppindouble/AlgoFun
/length_last_word.py
520
4.03125
4
""" In python, str.split() if we specifiy the seperator for example, "1,2,3,,,4".split(',') we will get ['1', '2', '3', '', '', '4'] if we don't specific the seperator for example " 1 2 3 4".split(' ') you will get ['1', '2', '3', '4'] https://docs.python.org/3/library/stdtypes.html#str.split """ class Solution: def lengthOfLastWord(self, s): if not len(s.split()): return 0 return len(s.split()[-1]) def main(): print(Solution().lengthOfLastWord("hello world")) if __name__ == "__main__": main()
bc198d2b00d521e91e4bc6d860d5d0d3254c507b
Yuandi888/algorithm014-algorithm014
/Week_04/122_Best_Time_to_Buy_and_Sell_Stock_II.py
982
3.71875
4
# 122. Best Time to Buy and Sell Stock II # 122. 买卖股票的最佳时机 II # 采用贪心算法 class Solution: def maxProfit(self, prices: List[int]) -> int: all = 0 for i in range(len(prices)-1): if prices[i] < prices[i+1]: all += prices[i+1] - prices[i] return all # https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/yi-xing-dai-ma-xing-neng-da-dao-100-by-jamleon/ # 速度最快,prices[i] - prices[i-1] > 0 比 prices[i] > prices[i-1] 快 class Solution: def maxProfit(self, prices: List[int]) -> int: return sum(prices[i] - prices[i-1] for i in range(1, len(prices)) if prices[i] - prices[i-1] > 0) # https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/122mai-mai-gu-piao-de-zui-jia-shi-ji-ii-pythonyi-x/ class Solution: def maxProfit(self, prices: List[int]) -> int: return sum(x-y for x, y in zip(prices[1:], prices) if x-y > 0)
d0d6a49b6bf947dfa9c96f9d594d1c5abd25d664
thenavdeeprathore/LearnPython3
/06_2_data_structure_tuple/Tuple_Functions.py
1,850
4.59375
5
""" Important Functions of Tuple: --------------------------- I. To get Information about Tuple: 1) len : Returns the number of elements present in the tuple 2) count : Returns the number of occurrences of specified item in the tuple 3) index : Returns the index of first occurrence of the specified item II. Ordering Elements of Tuple: 4) reversed : To reverse order of elements of any data types by creating a new object 5) sorted : To sort order of elements of any data types by creating a new object """ # I. To get Information about Tuple: # len() x = (10, 20, 30, 40, 50, 10, 20, 10) print(len(x)) # 8 # count() print(x.count(10)) # 3 print(x.count(90)) # 0 # index() # Note: If the specified element not present in the tuple then we will get ValueError. # print(x.index(100)) # ValueError: 100 is not in tuple print(x.index(10)) # 0 print(x.index(50)) # 4 # Another way of doing index search is: # tuple_name.index(element, start, end) # start (Optional) - The position from where the search begins. {index} # end (Optional) - The position from where the search ends. {len(tuple_name)} print(x.index(10, 2, 6)) # 5 # II. Ordering Elements of Tuple: # reversed() # Note: we can't reversed using the same object, we must create a new object to reverse a tuple t = (40, 10, 50, 30, 20) r = reversed(t) t1 = tuple(r) print(t) # (40, 10, 50, 30, 20) print(t1) # (20, 30, 50, 10, 40) # sorted() # Note: we can't sorted using the same object, we must create a new object to sort a tuple # Ascending order t = (40, 10, 50, 30, 20) s = sorted(t) t1 = tuple(s) print(t) # (40, 10, 50, 30, 20) print(t1) # (10, 20, 30, 40, 50) # Descending order t = (40, 10, 50, 30, 20) s = sorted(t, reverse=True) t1 = tuple(s) print(t) # (40, 10, 50, 30, 20) print(t1) # (50, 40, 30, 20, 10)
75858326d14f1cb4c5347ff3e6edbe02529dc10e
RaymondHealy/Karahl_Codespace
/CS 1/Labs/Lab8/dna.py
3,685
3.5625
4
from linked_code import * """----------------------------<Required Functions>----------------------------""" def convert_to_nodes(dna_string): dna_string = dna_string.strip() if dna_string == '': return None else: return Node(dna_string[0].upper(), convert_to_nodes(dna_string[1:])) def convert_to_string(dna_seq): if dna_seq == None: return '' else: return dna_seq.value + convert_to_string(dna_seq.rest) """Returns a bool indicating whether or not the 2 sequences are identical""" def is_match(dna_seq1, dna_seq2): if dna_seq1 == None == dna_seq2: return True elif dna_seq1 == None or dna_seq2 == None: return False elif dna_seq1.value != dna_seq2.value: return False else: return is_match(dna_seq1.rest, dna_seq2.rest) """Returns a boolean value indicating wether or not the 2 sequences are valid pair sequences""" def is_pairing(dna_seq1, dna_seq2): if dna_seq1 == None == dna_seq2: return True elif dna_seq1 == None or dna_seq2 == None: return False elif not IsValidPair(dna_seq1.value, dna_seq2.value): return False else: return is_pairing(dna_seq1.rest, dna_seq2.rest) """Returns a boolean value indicating whether or not the sequence is palindromic""" def is_palindrome(dna_seq): return is_match(dna_seq, reverseTailRec(dna_seq)) """Replaces value at idx with base recursively and non-destructively""" def substitution(dna_seq, idx, base): if dna_seq == None: raise IndexError("Sequence Index Out of Range") if idx > 0: return Node(dna_seq.value, substitution(dna_seq.rest, idx - 1, base)) else: return Node(base.upper(), dna_seq.rest) """Inserts <<dna_seq2>> at index <<idx>> in <<dna_seq>>""" def insertion(dna_seq1, dna_seq2, idx): if idx == 0: return cat(dna_seq2, dna_seq1) elif dna_seq1 == None: raise IndexError("Sequence Index Out of Range") else: return Node(dna_seq1.value, insertion(dna_seq1.rest, dna_seq2, idx - 1)) """ <<segment_size>> characters from <<dna_seq>> starting with index <<idx>>""" def deletion(dna_seq, idx, segment_size): if segment_size == 0: return dna_seq elif dna_seq == None: raise IndexError("Sequence Index Out of Range") elif idx > 0: return Node(dna_seq.value, deletion(dna_seq.rest, idx - 1, segment_size)) else: return deletion(dna_seq.rest, 0, segment_size - 1) def duplication(dna_seq, idx, segment_size): if segment_size == 0: return dna_seq elif dna_seq is None: raise IndexError("Sequence Index Out of Range") elif idx > 0: return Node(dna_seq.value, duplication(dna_seq.rest, idx - 1, segment_size)) elif segment_size > 0: temp = insertAt(segment_size - idx, dna_seq.value, dna_seq) if segment_size -1 > 0: return Node(dna_seq.value, duplication(temp.rest, idx - 1, segment_size - 1)) else: return Node(dna_seq.value, temp.rest) """----------------------------------------------------------------------------""" """-----------------------------<Helper Functions>-----------------------------""" def IsValidPair(char1, char2): char1 = char1.strip()[0].upper() char2 = char2.strip()[0].upper() if char1 == 'G' and char2 == 'C': return True elif char1 == 'C' and char2 == 'G': return True elif char1 == 'T' and char2 == 'A': return True elif char1 == 'A' and char2 == 'T': return True else: return False """----------------------------------------------------------------------------"""
f3a82a9881f9618e4ccb88e315a9f7e75cee8af9
burcekrbrk/GlobalAIHubPythonCourse_Burce-Karabork
/HW2.py
262
3.90625
4
dict = {"KullanıcıAdı": "Burçe", "Şifre":1234} a= str(input("Kullanıcı adı giriniz: ")) b= int(input("Şifre giriniz: ")) if dict["KullanıcıAdı"]==a and dict["Şifre"]==b: print("Tebrikler") else: print("Şifre veya kullanıcı adı hatalı")
af071de08043b70c2217492a0c62c79a12c5a6b5
k2mv/AdventOfCode2020
/18/18_2.py
4,000
3.5625
4
file_input = open("input1218.txt", "r") #file_input = open("test_input.txt", "r") lines = file_input.readlines() # LIST METHODS # append(this), count(of_this) # extend(iterable_to_append) # index(of_first_this), insert(at_pos) # pop() default: idx -1 # remove(first_of_this), reverse(), sort() # DICT METHODS # assignment: a_dict[key] = value # get(key), keys() returns list, values() returns list # pop(key_to_delete), returns deleted value # STRING METHODS # str.strip() returns (DOESN'T MODIFY) str with leading/trailing whitespace removed # str.count("x", start=0) returns the number of times "x" appears in str # str.find("pat") returns the index of the first occurrence of the specified pattern # str.startswith(), str.endswith() returns Bool # str.split("c") returns list of strings split by separator (default: any whitespace) def process_input(lines): ret = [] for l in lines: ret.append(l.split()) return ret def operate(operator, left, right): if operator == '+': answer = left + right left = answer operator = None right = None if operator == '*': answer = left * right left = answer operator = None right = None return answer def eval_line(line): buffer = [] mult_buffer = [] operator = None left = None right = None for chunk in line: if chunk.isnumeric(): chunknum = int(chunk) if left is None: left = chunknum else: if operator == '+': right = int(chunk) left = left + right operator = None right = None #if operator == '*': elif chunk.count('(') > 0: while chunk[0] == '(': buffer.append((left, operator, mult_buffer)) mult_buffer = [] left = None operator = None chunk = chunk[1:] left = int(chunk) elif chunk.count(')') > 0: right_paren_count = 0 while chunk[-1] == ')': right_paren_count += 1 chunk = chunk[:-1] right = int(chunk) if operator == '+': right = left + right else: pass for _ in range(right_paren_count): mult_buffer.append(right) right = mult_dump(mult_buffer) left, operator, mult_buffer = buffer.pop() if operator == '+': right = left + right #print(f'XXX left={left}, operator={operator}, mult_buffer={mult_buffer}, buffer={buffer}') left = right operator = None right = None ''' left = operate(operator, left, right) for _ in range(right_paren_count): right = left left, operator, mult_buffer = buffer.pop() if operator is None: left = right operator = None right = None else: left = operate(operator, left, right) operator = None right = None ''' elif chunk == '+': operator = '+' elif chunk == '*': mult_buffer.append(left) left = None operator = None right = None #print(f'left={left}, operator={operator}, mult_buffer={mult_buffer}, buffer={buffer}') mult_buffer.append(left) if len(mult_buffer) > 0: left = mult_dump(mult_buffer) #print(left) return left def mult_dump(mult_buffer): accum = 1 for item in mult_buffer: accum *= item return accum inp = process_input(lines) accum = 0 #eval_line(inp[0]) for eq in inp: accum += eval_line(eq) print(accum) file_input.close() ''' SCRATCH PAD RIGHT HERE '''
c3d779ce587514b746220eb317ee03b81928b41f
supatel/bin2image
/bin2image.py
1,885
3.703125
4
import cv2 # Not actuallfile_array necessarfile_array if file_arrayou just want to create an image. import argparse import numpy as np def parse_args(): parser = argparse.ArgumentParser( add_help=True, ) # file_arrayour arguments here if len(sfile_arrays.argv) == 1: parser.print_help() # sfile_arrays.exit(0) # options = -1; else: options = parser.parse_args() return options #Construct and Parse The Argument parser = argparse.ArgumentParser() parser.add_argument("-i", "--image", required = False, help = "Path to the binarfile_array image") parser.add_argument("-w", "--width", required = False, help = "width of image ex. 320 in 320x160 image") parser.add_argument("-ht", "--height", required = False, help = "height of image ex. 160 in 320x160") args = vars(parser.parse_args()) print('args') print(args) if args["image"] == None: # take blank image rgb if no input is provided blank_image = np.zeros((32,16,3), np.uint8) blank_image[:,0:5] = (250,0,0) # (B, G, R) blank_image[:,5:10] = (0,225,0) blank_image[:,10:16] = (0,0,200) #open binarfile_array file to write f = open("binfile.bin","wb") arr = blank_image.tobytes() f.write(arr) f.close() print('successfullfile_array saved bin') f = open("binfile.bin","rb") file_array = np.fromfile("binfile.bin",dtype='uint8') width = 32 height = 16 else: f = open(args["image"],"rb") file_array = np.fromfile(args["image"],dtype='uint8') width = int(args["width"]) height = int(args["height"]) output_Image = file_array.reshape(width,height,3) # np.arrafile_array_equal(file_array.reshape(32,16,3), file_array) shape = output_Image.shape print('image shape = ') print(shape) # print(file_array) f.close() cv2.imwrite('output.png',output_Image) cv2.imshow('file_array',output_Image) cv2.waitKey(0) cv2.destroyAllWindows() print('complete')
162cb05c63de85d431ab3efcdba8d96ce41d62c4
prd81/bomberman
/run.py
2,327
3.703125
4
""" Main module """ from random import choice from time import sleep from os import system as do from board import Board from person import Person from game import game def welcome(): """ Welcome screens """ do('clear') time = 3 for i in range(time, 0, -1): for j in (i, ' '): do('clear') print('Welcome to BombermanXtreme') print('Game begins in .....', j) sleep(0.5) do('clear') print('Start...') sleep(0.5) do('clear') def main(): """ Main method """ welcome() def new(level): """ Initialising method """ xlev = Board(level) xen, eco = [], 1<<level for i in range(eco): i += 0 blx, bly = choice(Board.eloc) xen += [Person('E', blx, bly)] Board.eloc.remove((blx, bly)) return xlev, xen def reset(): """ Resetting reference """ xlives, xlevel, xscore = 3, 1, 0 return xlives, xlevel, xscore lives, level, score = reset() boa, eny = new(level) hscore = 10 while True: per = Person('B', 1, 1) stat, lives, level, score = game((lives, level, score, boa, per, eny)) per.set(per.blx, per.bly, ' ') if stat == 'out': lives -= 1 if not lives: print('Game Over.') else: print('OOPS!! Remaining LIVES : %d. Loading...'%lives) sleep(3) continue elif stat == 'cross': level += 1 if level == Board.mlevel + 1: print('Victory!') else: print('Yeah, LEVEL %d completed! Loading...'%(level - 1)) sleep(3) boa, eny = new(level) continue elif stat == 'quit': print('Game quit.') print('Your SCORE :', score) if score > hscore: hscore = score print('NEW HIGHSCORE!') query = 'New Game? (y/N) : ' sinp = input(query).lower() if sinp == 'y': lives, level, score = reset() boa, eny = new(level) else: do('clear') print('Goodbye. See you soon.') sleep(1) do('clear') break main()
fb8b8bbbb90d4638c0d11ffc8b01f3bdf961c4bb
hwang033/job_algorithm
/py/cci_4.3_binary_tree_minimal_order.py
673
3.921875
4
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def create_binary_tree_from_list(l): if not l: return None mid = len(l)/2 root = Node(l[mid]) root.left = create_binary_tree_from_list(l[:mid]) root.right = create_binary_tree_from_list(l[mid+1:]) return root def tree_traverse(root, des="root"): if root == None: return print root.val, des tree_traverse(root.left, "%s's left" %root.val) tree_traverse(root.right, "%s's right" %root.val) if __name__ == "__main__": root = create_binary_tree_from_list([1,2,3,4,5]) tree_traverse(root)
f1440aa672848e4a45b814aaf98788ce7d2cb8a4
paalso/mipt_python_course
/4_arithmetics_and_lists/9.py
284
3.5
4
# http://judge.mipt.ru/mipt_cs_on_python3_2016/labs/lab5.html#o9 # Упражнение № 9 # =============== hours = int(input()) data = list(map(int, input().split())) k = int(input()) maximum = max([sum(data[i:i + k]) for i in range(hours - k + 1)]) print(maximum)
3cfb075958f24ab01e90794e6261e34e35ee78a4
Yohenba18/Advance-Programing-Practices
/week-2/zero.py
331
3.671875
4
def shift_zero(arr, n): count = 0 for i in range(n): if arr[i] != 0: arr[count] = arr[i] count+=1 while count<n: arr[count] = 0 count+=1 arr = [3, 4, 0, 0, 0, 6, 2, 0, 6, 7, 6, 0, 0, 0, 9, 10, 7, 4, 4, 5, 3, 0, 0, 2, 9, 7, 1] n = len(arr) shift_zero(arr,n) print(arr)
1b64e7adb54c25f6a798bd14171089b0b7453992
tggithub619/Codewars_Python
/8 kyu Is this my tail.py
272
3.53125
4
#https://www.codewars.com/kata/56f695399400f5d9ef000af5/train/python def correct_tail(body, tail): return body.endswith(tail) # return body[-1] == tail # #sub = body[len(body)-len(tail)] # if sub == tail: # return True # else: # return False
f86a80b921cdf49c58b308b142e558edb8f99310
yurinmk/python
/Faculdade/exercicioSequencia.py
391
3.890625
4
def sequecia(inicio, fim): #Cria uma lista vazia lista = [] #lista.append incrementa o item a lista for i in range(inicio,fim+1): lista.append(i * i) print(lista) def main(): inicioDaSequencia = int(input("nº de início da sequência = ")) fimDaSequencia = int(input("nº de fim da sequência = ")) sequecia(inicioDaSequencia,fimDaSequencia) main()
0307e65004a5db61af506448757ff39433ee0182
AG-Systems/MicroProjects
/Essay-Auriga/EssayTyper2.py
630
3.65625
4
import wikipedia import re import random testVar = raw_input("Please input the topic you want the computer write for you: ") print("If you want to best results, please choose the number 2 down below. ") LengthX = raw_input("Please input the length of your essay. Pick 1-10: ") print wikipedia.summary(testVar, sentences=LengthX) str = wikipedia.summary(testVar, sentences=LengthX) strf = str.split(" ") print(" \n ") text_file = open("EssayTyper.txt", "w") for x in range(0, len(str)): chain = random.choice(strf) print(random.choice(strf)) text_file.write(chain) text_file.write(" ") text_file.close()
2fd7755579fcbb6f572c05b6ed9063df2ef091af
chenjiunhan/JAQQRobotKingdom
/world/ptt/test.py
335
3.65625
4
import re s = "第 01~22 行" print(re.search(r"第 ([0-9]+)~([0-9]+) 行", s).group(1)) def findnth(string, substring, n): parts = string.split(substring, n) if len(parts) <= n or n <= 0: return -1 return len(string) - len(parts[-1]) - len(substring) s2 = "aaabbbbbbbaaabbbbbbbaaa" print(findnth(s2, "aaa", 4))
4406bd314cc72273053a7b4cf58f3ff6a373f78a
sekar5in/experiments
/LearnPython/tkintermodule.py
302
3.765625
4
#!/usr/local/bin/python3 # This is basic GUI window creation using tkinter module. from tkinter import * class Window(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.master = master root = Tk() app = Window(root) root.mainloop()
9f8efe04c89d644b9b7365b4b5ae5394f302d55e
ZhiCheng0326/SJTU-Python
/Reverse list.py
472
3.90625
4
def main(): old_list = [] while True: x = raw_input("Please input a number:") if x == "c": break else: print "Enter 'c' to exit!" a = old_list.append(x) reverse_list(old_list) def reverse_list(l): temp = 0 for i in range(len(l)/2): temp = l[i] l[i] = l[-1+ i * (-1)] l[-1+ i * (-1)] = temp print l main()
73cb1171bd992ecc890e51f3d5e627240e247f69
atomextranova/leetcode-python
/Template/segment_tree.py
2,139
3.515625
4
class SegmentTree(object): # 总结 # 区间操作,修改值或者一段的值 # 询问区间性质:最大,最小,和。。 def __init__(self, start, end, cur_sum=0): self.start = start self.end = end self.cur_sum = cur_sum self.left = self.right = None @classmethod def build(cls, start, end, array): if start > end: return None node = SegmentTree(start, end, array[start]) if start == end: return node mid = (start + end) // 2 left = cls.build(start, mid, array) right = cls.build(mid + 1, end, array) node.left = left node.right = right node.cur_sum = left.cur_sum + right.cur_sum return node @classmethod def modify(cls, index, value, root): if root is None: return if root.start == root.end: root.cur_sum = value return if root.left.end >= index: cls.modify(index, value, root.left) else: cls.modify(index, value, root.right) root.cur_sum = root.left.cur_sum + root.right.cur_sum return @classmethod def query(cls, start, end, root): if root.start > end or root.end < start: return 0 if start <= root.start and root.end <= end: return root.cur_sum return cls.query(start, end, root.left) + \ cls.query(start, end, root.right) class Solution: """ @param: A: An integer array """ def __init__(self, A): # do intialization if necessary self.root = SegmentTree.build(0, len(A) - 1, A) """ @param: start: An integer @param: end: An integer @return: The sum from start to end """ def query(self, start, end): # write your code here return SegmentTree.query(start, end, self.root) """ @param: index: An integer @param: value: An integer @return: nothing """ def modify(self, index, value): # write your code here SegmentTree.modify(index, value, self.root)
d5335bc09cb9720c99ab3a13880eb238ad76a7c3
SARWAR007/PYTHON
/Python Projects/list_extend.py
489
3.71875
4
list1 = [10,20,30,40] #list1.extend([50,60,70]) list1.count(10) print(list1.count(10)) x = list1.index(40,1,len(list1)) print("List index",x) print(list1) tuple1 =(10,20,30,40) #print(tuple1) print(max(list1)) print(max(tuple1)) list1.pop(2) print(list1) list1.remove(10) print(list1) list1[1]=50 print(list1) list1 = [2,3,4] list2 = list1.copy() print(id(list1)) print(id(list2)) print(list2 is list1) list5 = [1,3,5,6,7,7] print(set(list5)) list5.clear() print(list5)
32546e86c13be2425cc72e4147585ca8260a85c5
hjqjk/python_learn
/test/main/wrapper/wrapper2.py
1,228
3.78125
4
#!/usr/bin/env python #_*_ coding:utf-8 _*_ #装饰器 #当调用装饰器对函数进行装饰,想对原函数调用前后进行修改,为方便自定义修改,传入两个函数参数 def Filter(before_func,after_func): def outer(main_func): def wrapper(arg1,arg2): before_result = before_func(arg1) #调用原函数前的操作 if before_result != None: return before_result #如果有返回,后边就不执行了 main_result = main_func(arg1,arg2) #调用原函数 if main_result != None: return main_result #如果有返回,后边就不执行了 after_result = after_func(arg2) #调用原函数后的操作 if after_result != None: return after_result return wrapper return outer def before_func(arg): print 'before',arg #return 'B' def after_func(arg): print 'after',arg return 'A' @Filter(before_func, after_func) #传入函数引用 def func1(arg1,arg2): print 'main',arg1,arg2 #return 'Main' print func1('hello','python') #装饰器也可以定义成一个类
a24c0c0ece273c93d43935e3108f5955dc5fe0f2
elgaspar/tkinter-tutorial
/examples/dialogs/hello-world.py
330
3.5625
4
import tkinter from tkinter import ttk, messagebox def do_hello_world(): messagebox.showinfo("Important Message", "Hello World!") root = tkinter.Tk() big_frame = ttk.Frame(root) big_frame.pack(fill='both', expand=True) button = ttk.Button(big_frame, text="Click me", command=do_hello_world) button.pack() root.mainloop()
49e390a8901bf1139ba74cd61efc69f751f633c2
testcg/python
/code_all/day12/exercise02.py
656
4.4375
4
""" 父类:车(品牌,速度) 创建子类:电动车(电池容量,充电功率) """ class Car: def __init__(self, brand, speed): self.brand = brand self.speed = speed class ElectricCars(Car): # 1. 子类构造函数参数:父类参数+子类参数 def __init__(self, brand, speed, battery_capacity, charging_power): # 2. 通过super调用父类构造函数 super().__init__(brand, speed) self.battery_capacity = battery_capacity self.charging_power = charging_power bc = Car("奔驰", 220) print(bc.__dict__) am = ElectricCars("艾玛", 180, 10000, 220) print(am.__dict__)
d92ca2eba5017a0bcebcb25d659c7aab8402bb7a
qmnguyenw/python_py4e
/geeksforgeeks/python/basic/21_15.py
2,015
4.59375
5
Python Set | update() **update()** function in set adds elements from a set (passed as an argument) to the set. > **Syntax :** > set1.update(set2) > Here set1 is the set in which set2 will be added. > > **Parameters :** > Update() method takes only a single argument. The single argument can be a > set, list, tuples or a dictionary. It automatically converts into a set and > adds to the set. > > **Return value :** This method adds set2 to set1 and returns nothing. **Code #1 :** __ __ __ __ __ __ __ # Python program to demonstrate the # use of update() method list1 = [1, 2, 3] list2 = [5, 6, 7] list3 = [10, 11, 12] # Lists converted to sets set1 = set(list2) set2 = set(list1) # Update method set1.update(set2) # Print the updated set print(set1) # List is passed as an parameter which # gets automatically converted to a set set1.update(list3) print(set1) --- __ __ Output : {1, 2, 3, 5, 6, 7} {1, 2, 3, 5, 6, 7, 10, 11, 12} **Code #2 :** __ __ __ __ __ __ __ # Python program to demonstrate the # use of update() method list1 = [1, 2, 3, 4] list2 = [1, 4, 2, 3, 5] alphabet_set = {'a', 'b', 'c'} # lists converted to sets set1 = set(list2) set2 = set(list1) # Update method set1.update(set2) # Print the updated set print(set1) set1.update(alphabet_set) print(set1) --- __ __ Output : {1, 2, 3, 4, 5} {1, 2, 3, 4, 5, 'c', 'b', 'a'} Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
5e14273bb3b0e42022010274e89b75760489713a
atulasati/scripts_lab_test
/calc_weekly_pay/hr.py
1,027
3.796875
4
from employee import HR print ("Devoir 4 Anthony Ilunga") print ("Utilisation de classe et module. Script pour manipuler des employé(e)s).\n") hr_direcotory = HR(name='directory') while(True): command = "\n-------------------------------------------\n" command += "1 - Add employees to the directory\n" command += "2 - Display employee salary\n" command += "3 - Display employee age\n" command += "4 - Display all employees\n" command += "5 - Quit\n" command += "Input a command: " command = input (command) if command.strip() == "1": while True: hr_direcotory.add_employee() more_employee = input ("Do you want to enter another employee? (y or Y) ") if more_employee.strip() != "y": break elif command.strip() == "2": hr_direcotory.display_employee_salary() elif command.strip() == "3": hr_direcotory.return_employee_age() elif command.strip() == "4": hr_direcotory.display_all_employees() elif command == "5": break else: print("Invalid command.\n") input("Press Enter key to exit.")
7a8668ea497bb53f1c4ebaf8e27d247f04ca86d4
VitaliStanilevich/Md-PT1-40-21
/Tasks/ProkopovichKL/Самостоятельная 1.py
2,732
3.984375
4
text = 'five thirteen two eleven seventeen two one thirteen ten four eight five nineteen' # Преобразуем в список. text = text.split(' ') print(text) # Словарь для сравнения элементов - перемешан для того, чтобы последующий список # с цифрами был не по порядку. numbers = {'eighteen':18, 'nineteen':19, 'twenty':20, 'five':5, 'six':6, 'eleven':11, 'twelve':12, 'sixteen':16, 'thirteen':13,'seven':7, 'eight':8, 'nine':9, 'ten':10, 'fourteen':14, 'fifteen':15, 'seventeen':17, 'one':1, 'two':2, 'three':3, 'four':4} # Сравниваем словарь со списком new_dict = {} # Создаём новый пустой словарь for key, value in numbers.items(): for i in text: # Сравниваем ключи со словаря 'numbers' с элементами списка 'text' if i == key: new_dict[key] = value print(new_dict) # Я не ожидал такого, но словарь получился без повторных элементов. new_text = list(new_dict.values()) # Вычленяем список с "цифрами" из 'new_dict'. print(new_text) new_text_sorted = sorted(new_text) # Сортируем список по функции 'sorted()' print(new_text_sorted) # Пытаемся вывести числа: сначала умножение, а потом сложение, # и опять по кругу. Было сложно, но зато 'debag' освоил. for i in range(len(new_text_sorted)): i = i*2 # При втором прохождении цикла эта строка нам поможет. a = new_text_sorted[i] * new_text_sorted[i+1] print(a, end = ' ') # Строки 29-30 мне понадобились, чтобы избавиться от "IndexError: list index out of range" if i >= len(new_text_sorted)-2: break else: b = new_text_sorted[i+1] + new_text_sorted[i+2] print(b, end = ' ') # Это решения суммы нечётных элементов списка. small = [] # Создаю новый список для заполнения нечетными числами. for i in range(len(new_text_sorted)): if i >= len(new_text_sorted): # Это наш прерыватель цикла. break c = new_text_sorted[i] # Присваиваем переменной числовое значение 'i' if c % 2 != 0: small.append(new_text_sorted[i]) # Добавляем нечетный элемент в новый список print(small) print('\nСумма нечётных -', sum(small))