blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
033c9ed0e4ab5985ede13b265cbff90dd494e8ab
Abdullah99044/forever-young
/tafelmanieren/uren.py
111
3.640625
4
for x in range (-1, 13): print(x , str("am")) for y in range(11,24): print(y , str("pm"))
4439f08b7b33f738eaedeee3f305db4601c26205
mzuleta4/PythonExercism
/python/grains/grains.py
284
3.8125
4
def square(number): if not valid_number(number): raise ValueError("The number isn't between 1 and 64 and should be greater 0") return 2**(number - 1) def valid_number(number): return 0 < number < 65 def total(): return sum(square(x) for x in range(1, 65))
02865c0ff34a718081bb0d4c150b3522dc17ca70
MohnishVS/Guvi-Tasks
/uberbilling.py
1,608
4
4
flg=True while(flg): print("\n\nSelect a Service\n 1.auto\n 2.bike\n 3.car\n 4.exit\n") ch=int(input("enter your choice")) if(ch==1): kms=int(input("enter the distance covered:")) if(kms<=1): price=20 print("the bill amount is",price) elif(kms<=4): rate=18 price=kms*rate print("the bill amount is",price) elif(kms>4): rate=15 price=kms*rate print("the bill amount is",price) else: print("enter the valid options") elif(ch==2): kms=int(input("enter the distance covered:")) if(kms<=1): price=20 print("the bill amount is",price) elif(kms<=4): rate=12 price=kms*rate print("the bill amount is",price) elif(kms>4): rate=15 price=kms*rate print("the bill amount is",price) else: print("enter the valid options") elif(ch==3): kms=int(input("enter the distance covered:")) if(kms<=1): price=20 print("the bill amount is",price) elif(kms<=4): rate=18 price=kms*rate print("the bill amount is",price) elif(kms>4): rate=15 price=kms*rate print("the bill amount is",price) else: print("enter the valid options") elif(ch==4): flg=False else: print("enter the valid options")
b89612c53e36acc983470f2e7aa4856934cea115
BrianFoxDougherty/LabelSum.py
/LabelSum.py
2,417
3.921875
4
import argparse import sys import json from pprint import pprint """ LabelSum.py Author: Brian Fox Dougherty Operation: Given a JSON string which describes a menu, calculate the SUM of the IDs of all "items", as long as a "label" exists for that item. """ debug = 0 # default debug value. if set to 1 we will output operation information jsonFile = "" # location of json file to parse print(" ") print("------------------------------------------------------------------") print("This program uses a command line arg -f to point to a JSON file and will sum up all IDs for an item with a label") print("You also may use the argument -d to turn on debug output.") print("That contains the string 'label'.") print(" ") print("Example without debugging:") print("LabelSum.py \"c:\\temp\\Data.json\"") print(" ") print("Example with debugging:") print("LabelSum.py \"c:\\temp\\Data.json\" -d") print("------------------------------------------------------------------") print(" ") # create argument parser to get file path and debug var parser = argparse.ArgumentParser() # add arguments parser.add_argument("--filepath", "-f", help="set path to json file") parser.add_argument("--debug", "-d", help="turn on debug output", action='store_true') # read arguments args = parser.parse_args() # check for filepath and add it if args.filepath: jsonFile = args.filepath # check for debug and turn on if args.debug: debug = 1 if debug == 1: print("Importing from file: ", jsonFile) with open(jsonFile, "r") as source: jsonSource = source.read() data = json.loads('[{}]'.format(jsonSource)) # load and add bracket to each json object if debug == 1: print("JSON data imported:") pprint(data) #output all data elements print("Output: ") print(" ") for i in data: IdSum = 0 # reset the sum of IDs for every loop MenuList = i["menu"] # drop each json object into a list ItemDict = (MenuList["items"]) # put each list value into a dict for index, item in enumerate(ItemDict): # walk through the values in each dict if str(item) != "None": # exclude null values which are represented as None if 'label' in item: # label exists, sum the ids IdSum = IdSum + item["id"] if debug == 1: print("Adding item id: ", item["id"]) else: if debug == 1: print("No label for id ", item["id"]) print(IdSum) # print the final sum for each item print(" ") print("Finished!")
12e3f51785f6012fbdb1ca3926eedb877a325140
ntkawasaki/python-tutorial
/7_input_and_output.py
8,071
4.65625
5
""" 7. Input and Output """ """ 7.1. Fancier Output Formatting Convert values to string format with str() and repr(). The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax). For objects which don’t have a particular representation for human consumption, str() will return the same value as repr(). Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function. Strings, in particular, have two distinct representations. """ s = "Hello, world!" print(s) repr(s) repr(1/7) x = 10 * 3.25 y = 200 * 200 print("The value of x is {} and the value of y is {}...".format(repr(x), repr(y))) # The repr() of a string adds string quotes and backslashes: hello = "Hello, world\n" print(hello) repr(hello) print(repr(hello)) # The argument to repr() may be any Python object: repr((x, y, ('spam', 'eggs'))) # Two ways to make tables: for x in range(1, 11): print(repr(x).ljust(2), repr(x**2).rjust(3), end=" ") print(repr(x**3).rjust(4)) for x in range(1, 11): print("{0:2d} {1:3d} {2:4d}".format(x, x**2, x**3)) # str.zfill() "12".zfill(4) '-3.14'.zfill(7) '3.14159265359'.zfill(5) # str.format() print('We are the {} who say "{}!"'.format('knights', 'Ni')) # Positional args print('{0} and {1}'.format('spam', 'eggs')) print('{1} and {0}'.format('spam', 'eggs')) # Keyword args print('This {food} is {adjective}.'.format(food='spam', adjective='horrible')) # Positional and keyword args print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg')) # '!a' (apply ascii()), '!s' (apply str()) and '!r' (apply repr()) can be used # to convert the value before it is formatted: contents = 'eels' print('My hovercraft is full of {}.'.format(contents)) print('My hovercraft is full of {!r}.'.format(contents)) # : format specifier import math print("The value of pi is approximately {:.6f}".format(math.pi)) # Passing an integer after the ':' will cause that field to be a minimum number # of characters wide. table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} for name, phone in table.items(): print("{0:10} ==> {1:10d}".format(name, phone)) # To reference values like a variable, reference [keys] and pass the dict print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ' 'Dcab: {0[Dcab]:d}'.format(table)) # Or pass table with ** notation print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) """ 7.1.1 Old String Formatting """ print('The value of PI is approximately %5.3f.' % math.pi) """ 7.2. Reading and Writing Files open() returns a file object, and is most commonly used with two arguments: open(filename, mode). The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted. Normally, files are opened in text mode, that means, you read and write strings from and to the file, which are encoded in a specific encoding. If encoding is not specified, the default is platform dependent (see open()). 'b' appended to the mode opens the file in binary mode: now the data is read and written in the form of bytes objects. This mode should be used for all files that don’t contain text. In text mode, the default when reading is to convert platform-specific line endings (\n on Unix, \r\n on Windows) to just \n. When writing in text mode, the default is to convert occurrences of \n back to platform-specific line endings. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks: """ # Wont actually run with open("workfile.txt") as file: read_data = file.read() read_data file.closed """ If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it. If you don’t explicitly close a file, Python’s garbage collector will eventually destroy the object and close the open file for you, but the file may stay open for a while. Another risk is that different Python implementations will do this clean-up at different times. After a file object is closed, either by a with statement or by calling f.close(), attempts to use the file object will automatically fail. """ file.close() file.read() """ 7.2.1. Methods of File Objects """ f = open('workfile.txt', 'w') f.read() f.read_lines() for line in file: print(line, end=' ') list(f) f.write("This is a test\n") # Must convert other types value = ('the answer', 42) s = str(value) f.write(s) f.tell() """ To change the file object’s position, use f.seek(offset, from_what). The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point. """ f = open('workfile', 'rb+') f.write(b'0123456789abcdef') f.seek(5) # Go to the 6th byte in the file f.read(1) f.seek(-3, 2) # Go to the 3rd byte before the end f.read(1) """ In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2)) and the only valid offset values are those returned from the f.tell(), or zero. Any other offset value produces undefined behaviour. File objects have some additional methods, such as isatty() and truncate() which are less frequently used; consult the Library Reference for a complete guide to file objects. """ """ 7.2.2. Saving Structure with JSON Strings can easily be written to and read from a file. Numbers take a bit more effort, since the read() method only returns strings, which will have to be passed to a function like int(), which takes a string like '123' and returns its numeric value 123. When you want to save more complex data types like nested lists and dictionaries, parsing and serializing by hand becomes complicated. Rather than having users constantly writing and debugging code to save complicated data types to files, Python allows you to use the popular data interchange format called JSON (JavaScript Object Notation). The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing. Reconstructing the data from the string representation is called deserializing. Between serializing and deserializing, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine. """ import json # View JSON string representation json.dumps([1, "simple", "list"]) # Serialize object to text file json.dump(x, f) # Decode object again json.load(f) """ This simple serialization technique can handle lists and dictionaries, but serializing arbitrary class instances in JSON requires a bit of extra effort. The reference for the json module contains an explanation of this. Also see the pickle module """
1452d70d1b1eb0e6f0e791e0d2a3ec0aec3b9e9e
vijaykumar150/homework2
/part- 2.py
116
3.71875
4
a = "Hello" l = list(a) print(l) j=''.join(l) print(j) j1 = ' '.join(l) print(j1) j2 = '_'.join(l) print(j2)
0c5db9c1de0d5f1bfb922d9b4d2d4cda02c0006c
hanbee1123/algo
/DataStructures/Graph/topological_sort.py
1,353
3.90625
4
""" There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return true if you can finish all courses. Otherwise, return false. Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. """ from collections import deque class Solution: def canFinish(self, numCourses: int, prerequisites): if len(prerequisites)==0: return True courses = defaultdict(list) indegrees = [0]*numCourses for i,j in prerequisites: courses[i].append(j) indegrees[j] += 1 counter = 0 q = deque() for k in range(len(indegrees)): if indegrees[k] == 0: q.append(k) while q: val = q.popleft() counter += 1 for k in courses[val]: indegrees[k] -= 1 if indegrees[k] == 0: q.append(k) return counter == numCourses
59794a8b2c9134ae0d5cf381e306fdbae3273c41
hanbee1123/algo
/DataStructures/Priority_Queue_and_HEAP/network_delay_time.py
1,185
3.9375
4
""" You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui,vi,wi) ui is the source node, vi is the target node wi is the time it takes for a signal to travel from source to target We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. if it is impossible for all the n nodes to receive the signal return -1. Input : times[[2,1,1],[2,3,1],[3,4,1]], n=4, k=2 output : 2 """ import heapq def ndt(times,N,K): graph = {} for (u, v, w) in times: graph[u] = [(v, w)] priority_queue = [(0, K)] shortest_path = {} while priority_queue: w, v = heapq.heappop(priority_queue) if v not in shortest_path: shortest_path[v] = w for v_i, w_i in graph[v]: heapq.heappush(priority_queue, (w + w_i, v_i)) if len(shortest_path) == N: return max(shortest_path.values()) else: return -1 if __name__ =="__main__": print(ndt([[1,2,1],[2,1,3]], 2, 2))
13d1c807328218001d5809ac701f25c96e1a9681
hanbee1123/algo
/Algo/Dynamic_programming/coin_change.py
2,144
3.59375
4
""" You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Example 1: Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 """ #Using BFS from collections import deque class Solution: def coinChange(self, coins, amount): if amount ==0: return 0 depth = 0 q = deque([(amount,depth)]) seen = set() while q: val,depth = q.popleft() for c in coins: new_val = val-c if new_val == 0: return depth+1 if new_val not in seen and new_val > 0: seen.add(new_val) q.append((new_val,depth+1)) return -1 # Using DP bottomup class Solution: def coinChange(self, coins, amount): dp= [amount+1] * (amount+1) dp[0]=0 for coin in coins: for i in range(coin, amount+1): if i-coin>=0: dp[i]=min(dp[i], dp[i-coin]+1) return -1 if dp[-1]==amount+1 else dp[-1] class Solution2: def cc(self,coins,amount): self.min_depth = amount+1 self.seen = set() def dfs(depth, amount, coins): if amount == 0: self.min_depth = min(self.min_depth, depth) print(self.min_depth) return for c in coins: new_val = amount - c if new_val >=0: self.seen.add(new_val) dfs(depth+1, new_val, coins) dfs(0,amount,coins) if self.min_depth == amount+1: return -1 else: return self.min_depth if __name__=="__main__": amount=100 coins = [1,2,5] atest = Solution2() print(atest.cc(coins,amount))
1f9966b35de87fb864390ebe817850b2a036959b
hanbee1123/algo
/Algo/Dynamic_programming/climbing_stairs.py
1,032
3.875
4
""" 계단을 올라가고 있다. 이 계단의 꼭대기에 도착하려면 n개의 steps만큼 올라가야 한다. 한번 올라갈 때 마다 1step 또는 2steps 올라갈 수 있다. 꼭대기에 도달하는 방법의 갯수는 총 몇가지 일까요? input: n=2 output = 2 1. 1+1 2. 2 input: n=3, output =3 1. 1+1+1 2. 1+2 3. 2+1 DP using topdown memo = {} def dp_topdown(n): if n == 1: return 1 if n == 2: return 2 if n not in memo: memo[n] = dp_topdown(n-1) + dp_topdown(n-2) if n in memo: return memo[n] return dp_topdown(n-1) + dp_topdown(n-2) DP using bottomup """ def dp_topdown(n): memo = {1:1, 2:2} def dp(n): if n not in memo: memo[n] = dp(n-1)+dp(n-2) return memo[n] dp(n) return memo[n] def dp_bottomup(n): memo = {1:1, 2:2} for i in range(3,n+1): memo[i] = memo[i-1] + memo[i-2] return memo[n] if __name__ == "__main__": print(dp_topdown(5)) print(dp_bottomup(5))
dd57ec22b1e3db12ae7b2b3ac169edb235f32998
hanbee1123/algo
/DataStructures/Hash_Table/longest_consecutive_sequence.py
1,704
3.53125
4
""" 문제: 정렬되어 있지 않은 정수현 배열 nums가 주어졌다. nums원소를 가지고 만들 수 있는 가장 긴 연속된 수의 갯수는 몇개인지 반환하시오 input: nums =[100,4,200,1,3,2] output: 4 (가장 긴 연속된 수 1,2,3,4) 문제 해결: O(nlogn) method: #1. sort the nums #2. then from beginning consecutive sequence. O(n) method using hash table: #1. 100,4,200,1,3,2 [101:T, 5:T, 201:T, 2:T, 4:T, 3:T] # While True, check if element in array has +1 value in dictionary. Dummy code: memo = {} for i in input: memo[i] = 'dummy' counter += 1 max_counter = 0 for i in input: while i+counter in memo: i += 1 max_counter = max(counter, max_counter) return max_counter edge cases: - what if no input? - 0 will be retuned - what if 1 input? - max_counter will be returned = 1 - what is no consecutive? - max_counter will be returned = 1 """ def lcs(nums): memo = {} # put values in nums as keys in hash table for i in nums: memo[i] = True max_counter = 0 for i in nums: if i-1 not in memo: counter = 1 while i + counter in memo: counter += 1 max_counter = max(counter, max_counter) return max_counter if __name__ == "__main__": print(lcs([-6,-1,-1,9,-8,-6,-6,4,4,-3,-8,-1])) #correct answer: # longest = 0 # num_dict = {} # for num in nums: # num_dict[num] = True # for num in num_dict: # if num-1 not in num_dict: # cnt = 1 # target = num+1 # while target in num_dict: # target += 1 # cnt += 1 # longest = max(longest,cnt) # return longest
6ec5322284408552c82b522299977415ee57c9e2
MonikaSophin/python_base
/2.4 tuple.py
422
4
4
""" 2.4 基本数据类型 -- tuple(元组) """ ## 用法与list基本一致,不同的是 # tuple用(), list用[] # tuple不可修改序列元素, list可修改序列元素 # 创建元组 tuple1 = (1, "a", "ss", 1+2j) print(id(tuple1)) tuple1 = 2, "b", "ss1", 2+2j ## 不需要括号也可以 print(id(tuple1)) a = (50) print(type(a)) # 不加逗号,为整型 a = (50,) print(type(a)) # 加上逗号,为元组
ab2a728ab214b390f5e83f460cfe4a85c1a9edc2
serdaraltin/Freelance-Works-2021
/202101161937 - mstfyr (Python - Quiz)/01_source-code/05_project/final_exam-test.py
9,307
3.65625
4
# -*- coding: utf-8 -*- """ EXAM RULES - You are strictly forbidden to share answers with your course mates. - You are not allowed to search for answers on the Internet. You are not allowed to ask for answers in forums or other online communication systems. - Note that, when you find an answer on the web, somebody else will also find it and use it. This means, both of you will submit the exact same answer. This, then, means cheating, no matter you know the other person or not. - If your answers are similar to some other student's answers at a level that proves unethical misconduct, you will FAIL THE COURSE. We don't care whether you know the other person or not, we don't care whether he/she is your friend or not, we don't care who delivered and who received. Both parties fail the course immediately. Moreover, a disciplinary action may follow based on the seriousness of the issue. - You are NOT ALLOWED TO IMPORT any packages. If there are any imports in your submission, we will remove them before grading. - If your file doesn't compile, then you receive 0. Make sure that your indentation is correct. - Do not change the below function definitions. In other words, do not change the function names and the parameters of the functions. You are only allowed to write code within the function scope. - Do not print anything on the screen unless you are asked to. Most questions require you to return a value. Printing that value on the screen is not equal to returning the value. - Do not submit any testing code. DO NOT FORGET TO FILL THE BELOW LINES: My full name is ______________. My student ID is _________. My section is (Mechanical)(Nuclear Energy) Engineering. """ """ Question 1: (10 points) Write a function that takes a list of integers l and an integer value v, and returns whether v exists more than once in l. For example, checkDups([1,2,3,4,3,5,2,3], 5) -> returns False checkDups([1,2,3,4,3,5,2,3], 2) -> returns True checkDups([1,2,3,4,3,5,2,3], 3) -> returns True ``` """ def checkDups(l, v): count = 0 for item in l: if item == v: count+=1 if count > 1: return True return False #print(checkDups([1,2,3,4,3,5,2,3], 5)) #print(checkDups([1,2,3,4,3,5,2,3], 2)) #print(checkDups([1,2,3,4,3,5,2,3], 3)) """ Question 2: (10 points) Write a function that takes a string as input and PRINTS the following pattern on the screen based on the input string: For example: stringShift("burkay") PRINTS the following: burkay urkayb rkaybu kaybur ayburk yburka """ def stringShift(s): x = range(len(s)) for i in x: j = i y = range(i,len(s)) for j in y: print(s[j],end="") z = range(i) for k in z: print(s[k],end="") print() """ Question 3: (10 points) Complete the below function which takes two circles as tuples, and returns True if the circles intersect each other. Two circles intersect if their centers are closer than the sum of their radiuses. The provided tuples are in (a,b,c) format where a and b are the x and y coordinates of a circle, and c is the radius of the circle. For example, intersects((1,1,2), (5,8,1)) -> returns False intersects((1,1,5), (2,3,4)) -> returns True """ import math def intersects(c1, c2): x0 = c1[0] y0 = c1[1] r0 = c1[2] x1 = c2[0] y1 = c2[1] r1 = c2[2] d=math.sqrt((x1-x0)**2 + (y1-y0)**2) if d > r0 + r1 : return False if d < abs(r0-r1): return True if d == 0 and r0 == r1: return True else: return True #print(intersects((1,1,2), (5,8,1))) """ Question 4: (20 points + 10 points bonus) Write the below function that takes a string and applies the following rules repetitively until there is one character left and returns that character: - If the first two characters are "aa" then they are replaced by "b" - If the first two characters are "ba" then they are replaced by "c" - If the first two characters are "ab" then they are replaced by "c" - If the first two characters are "bb" then they are replaced by "a" - If the first character is "c", then it is replaced by the second character. However, if the second character is also "c" then the first "c" is removed. - For everything else, the first character is removed. The input string contains only the letters "a", "b" and "c". For example, the string "aabc" goes through the following transformations: "aabc" -> "bbc" -> "ac" -> "c" Similarly, the string "bacbc" becomes "bacbc" -> "ccbc" -> "cbc" -> "bbc" -> "ac" -> "c" NOTE: If you solve this question in a recursive fashion, you get 10 points bonus! The bonus will be applied if and only if you pass all the other tests. """ def shorten(s): slist = list(s) onechar = s[:1:] if len(s) > 1: print(s,end=" -> ") twochar = s[:2:] if len(s) == 2 and s[1:2:] == "c": slist[0] = '' s = "".join(slist) print(s) return if onechar == "c": temp = slist[0] slist[1] = slist[0] slist[0] = temp if slist[1]== "c": slist[0] = '' s = "".join(slist) return shorten(s) s = "".join(slist) shorten(s) if twochar == "aa": slist[1] = 'b' slist[0] = '' s = "".join(slist) shorten(s) if twochar == "ba": slist[1] = 'c' slist[0] = '' s = "".join(slist) shorten(s) if twochar == "ab": slist[1] = 'c' slist[0] = '' s = "".join(slist) shorten(s) if twochar == "bb": slist[1] = 'a' slist[0] = '' s = "".join(slist) shorten(s) #shorten("aabc") """ Question 5: (20 points) Complete the below function which takes a dictionary d and a key k as arguments and returns a value based on the following rules: 1. If k is not a key of d, then return None. 2. Otherwise, let v be the value of k in d 3. If v exists also as a KEY in d, then set k = v and go to Step 2 4. Otherwise, return v For example, given d={1:3, 3:2, 2:4} and k = 1, your function must return 4. This is because d[1] is 3, and d[3] is 2, and d[2] is 4, and 4 is not a key in d. """ def dictChain(d, k): state = 0 for key in d.keys(): if key == k: state = 1 if state == 0: return None nkey = d[k] while True: state = 0 for key in d.keys(): if key == nkey: state = 1 if state == 0: return nkey nkey = d[nkey] d={1:3, 3:2, 2:4} k = 1 print(dictChain(d,1)) """ Question 6: (30 points) Complete the below function that reads football game scores from a file called "scores.txt" (you can assume it always exists), computes a dictionary where keys are team names and values are the corresponding points, and returns the dictionary. All teams, even if they have obtained 0 points, must be represented in the dictionary. The format of "scores.txt" is as follows (the following is just an example): TeamA TeamB 3 2 TeamA TeamC 2 0 TeamC TeamB 1 1 This means, TeamA won against TeamB by scoring 3 goals versus 2. From this game TeamA obtains 3 points (each win is 3 points) and TeamB obtains 0 points (each lose is 0 points). In the second game TeamA defeated TeamC 2 to 0, and received another 3 points, whereas TeamC received 0 points. Finally, TeamC and TeamB had a draw in the last game and each received 1 point (each draw is 1 point). As a result TeamA obtained 6, TeamB obtained 1 and TeamC obtained 1 points. The function must then return the following dictionary: {"TeamA":6, "TeamB":1, "TeamC":1} You don't know how many teams or games exist in the file. Teams are not guaranteed to play the same number of games. """ def pointCalculator(): input = "TeamA TeamB 3 2\nTeamA TeamC 2 0\nTeamC TeamB 1 1" pointDict = {} for line in input.splitlines(): team1name = line.split(" ")[0] team1goal = int(line.split(" ")[2]) team2name = line.split(" ")[1] team2goal = int(line.split(" ")[3]) team1lastpoint = 0 team2lastpoint = 0 for key in pointDict.keys(): if key == team1name: team1lastpoint = pointDict[team1name] if key == team2name: team2lastpoint = pointDict[team2name] if team1goal > team2goal: pointDict[team1name] = team1lastpoint + 3 if team1goal < team2goal: pointDict[team2name] = team2lastpoint + 3 if team1goal == team2goal: pointDict[team1name] = team1lastpoint + 1 pointDict[team2name] = team2lastpoint + 1 print(pointDict) #pointCalculator()
881fa732e96e88c04ad2fb0622af7aa627e6f93b
andylws/SNU_Lecture_Computing-for-Data-Science
/HW5/P4.py
1,272
3.875
4
""" **Instruction** Write P4 function that reads a file and creates another file with different delimeter. - Assume the input file is delimited with blank(' '). - Output file has comma(',') as a delimeter - Assume there is no consecutive blanks in input file. i.e. ' ', ' ', ' ',... does not appear in the input file. - Filenames of input and ouput file are entered as input of P4 function - there is no return value of P4 function For example, if the input file has below lines, beryllium 4 9.012 magnesium 12 24.305 calcium 20 20.078 strontium 38 87.62 barium 56 137.327 radium 88 226 output file should look like this. beryllium,4,9.012 magnesium,12,24.305 calcium,20,20.078 strontium,38,87.62 barium,56,137.327 radium,88,226 """ def P4(input_filename: str, out_filename: str): ##### Write your Code Here ##### with open(input_filename, 'r') as input_file, open(out_filename, 'w') as output_file: lines = input_file.readlines() split = [] linesMade = [] for line in lines: split.append(line.strip('\n').split()) for line in split: linesMade.append(','.join(line)) result = '\n'.join(linesMade) output_file.write(result) return ##### End of your code #####
fe3b764e6d704aa111a91b292966f2d3b60b5eb3
andylws/SNU_Lecture_Computing-for-Data-Science
/Proj2/P3.py
2,273
3.984375
4
""" **Instruction** Please see instruction document. """ from linked_list_helper import ListNode, create_linked_list, print_linked_list def P3(head: ListNode) -> ListNode: if head is None: return None if head.next is None: return head ''' # Find the number of nodes cnt = 0 curr = head midNode = head while curr != None: curr = curr.next cnt += 1 # Divide into left and right mid = cnt // 2 left = head curr = head cnt = 0 while cnt < mid-1: curr = curr.next cnt += 1 right = curr.next curr.next = None ''' ##### Write your Code Here ##### class SortSLL: def __init__(self, head): self.head = head self.curr = head self.front = ListNode() self.front.next = head self.start = head self.temp = None self.min_val = head.val self.length = 0 def checkLength(self): len_curr = self.head while len_curr != None: len_curr = len_curr.next self.length += 1 def findFront(self): self.temp = self.curr self.min_val = self.curr.val while self.curr.next != None: if self.curr.next.val < self.min_val: self.temp = self.curr self.start = self.curr.next self.min_val = self.curr.next.val self.curr = self.curr.next if self.temp == self.start: self.curr = self.start.next else: self.curr = self.front.next self.front.next = self.start self.temp.next = self.start.next self.start.next = self.curr def sort(self): self.findFront() self.head = self.front.next self.front = self.head self.checkLength() for i in range(self.length - 2): self.findFront() self.front = self.front.next self.start = self.start.next return self.head SLL = SortSLL(head) head = SLL.sort() return head ##### End of your code #####
656d28880463fdd9742a9e2c6c33c2c247f01fbf
andylws/SNU_Lecture_Computing-for-Data-Science
/HW3/P3.py
590
4.15625
4
""" #Practical programming Chapter 9 Exercise 3 **Instruction** Write a function that uses for loop to add 1 to all the values from input list and return the new list. The input list shouldn’t be modified. Assume each element of input list is always number. Complete P3 function P3([5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3]) >>> [6, 5, 8, 4, 3, 4, 3, 7, 5, 3, 2, 8, 2, 4] P3([0,0,0]) >>> [1,1,1] """ def P3(L1: list) -> list: ##### Write your Code Here ##### result = [] for i in L1: result.append(i + 1) return result ##### End of your code #####
a2fa443482a145cb7d6d75e7b3a99e37c2aa0c9d
andylws/SNU_Lecture_Computing-for-Data-Science
/Proj2/P2.py
777
3.921875
4
""" **Instruction** Please see instruction document. """ def P2(parentheses: str) -> bool: ##### Write your Code Here ##### par_list = ['.'] for i in parentheses: if i == '(' or i == '{' or i == '[': par_list.append(i) elif i == ')': if par_list[-1] == '(': par_list.pop() else: return False elif i == '}': if par_list[-1] == '{': par_list.pop() else: return False elif i == ']': if par_list[-1] == '[': par_list.pop() else: return False if par_list == ['.']: return True else: return False ##### End of your code #####
2396c3f164d68a2fe00bef5aee8689254ff072bc
andylws/SNU_Lecture_Computing-for-Data-Science
/HW4/P1.py
444
3.875
4
""" Implement a function that takes a list of integers as its input argument and returns a set of those integers occurring two or more times in the list. >>> P1([1,2,3,1]) {1} >>> P1([1,2,3,4]) set() >>> P1([]) set() >>> P1([1,2,3,1,4,2]) set({1,2}) """ def P1(lst): result = set() noDup = set(lst) for i in lst: if i in noDup: noDup.remove(i) else: result.add(i) return result
fe84b61fe62bf5056bd2d91c2070753ebf22c339
barmi/CodingClub_python
/LV4/Chapter4/start/myArtApp.py
1,737
3.75
4
# myArtApp.py # based on the code from myEtchASketch.py in Python Basics. # 『코딩 클럽 LV1. 모두를 위한 파이썬 기초』의 myEtchASketch.py from tkinter import * #### Set variables. 변수를 정합니다. canvas_height = 400 canvas_width = 600 canvas_colour = "black" x_coord = canvas_width/2 y_coord = canvas_height line_colour = "red" line_width = 5 line_length = 5 ## new variables go here. 새 변수는 여기에 입력합니다. #### Functions. 함수 def move(x, y): global x_coord global y_coord new_x_coord = x_coord + x new_y_coord = y_coord + y ## add the pen_up code here. pen_up 코드는 여기에 입력합니다. canvas.create_line(x_coord, y_coord, new_x_coord, new_y_coord, width=line_width, fill=line_colour) x_coord = new_x_coord y_coord = new_y_coord def move_N(event): move(0, -line_length) def move_S(event): move(0, line_length) def move_E(event): move(line_length, 0) def move_W(event): move(-line_length, 0) def erase_all(event): canvas.delete(ALL) ## add new functions here. 새 함수는 여기에 입력합니다. #### main. 메인 window = Tk() window.title("MyArtApp") canvas = Canvas(bg=canvas_colour, height=canvas_height, width=canvas_width, highlightthickness=0) ## background image code goes here. 배경화면 코드는 여기에 입력합니다. canvas.pack() # bind movement to keys. 키보드 키를 연결합니다. window.bind("<Up>", move_N) window.bind("<Down>", move_S) window.bind("<Left>", move_W) window.bind("<Right>", move_E) window.bind("e", erase_all) # start tkinter's main loop. tkinter의 메인 반복을 시작합니다. window.mainloop()
51dd14daadc02e7518fef366d94ea9df1edecdfd
barmi/CodingClub_python
/LV3/SourceCode/보너스장/MyBreakout/main.py
2,335
3.609375
4
# MyPong의 주된 파일을 만듭니다. from tkinter import * import table, ball, bat, random window = Tk() window.title("MyBreakout") my_table = table.Table(window) # 전역 변수 초기화 x_velocity = 4 y_velocity = 10 first_serve = True # Ball 공장으로부터 볼을 주문합니다 my_ball = ball.Ball(table = my_table, x_speed=x_velocity, y_speed=y_velocity, width=24, height=24, colour="red", x_start=288, y_start=188) # Bat 공장으로부터 배트를 주문합니다 bat_B = bat.Bat(table = my_table, width=100, height=10, x_posn=250, y_posn=370, colour="blue") # Bat 클래스로부터 배트를 주문하지만 이것은 벽돌을 호출하는 것은 아닙니다. bricks = [] b=1 while b < 7: i=80 bricks.append(bat.Bat(table = my_table, width=50, height=20, x_posn=(b*i), y_posn=75, colour="green")) b = b+1 #### 함수: def game_flow(): global first_serve # 첫번째 서브를 기다립니다: if(first_serve==True): my_ball.stop_ball() first_serve = False # 배트에 공이 충돌하는지 감지 bat_B.detect_collision(my_ball, sides_sweet_spot=False, topnbottom_sweet_spot=True) # 벽돌에 공이 충돌하는지 감지 for b in bricks: if(b.detect_collision(my_ball, sides_sweet_spot=False) != None): my_table.remove_item(b.rectangle) bricks.remove(b) if(len(bricks) == 0): my_ball.stop_ball() my_ball.start_position() my_table.draw_score("", " YOU WIN!") # 아래쪽 벽에 공이 충돌하는지 감지 if(my_ball.y_posn >= my_table.height - my_ball.height): my_ball.stop_ball() my_ball.start_position() first_serve = True my_table.draw_score("", " WHOOPS!") my_ball.move_next() window.after(50, game_flow) def restart_game(master): my_ball.start_ball(x_speed=x_velocity, y_speed=y_velocity) my_table.draw_score("", "") # 배트를 제어할 수 있도록 키보드의 키와 연결 window.bind("<Left>", bat_B.move_left) window.bind("<Right>", bat_B.move_right) # 스페이스 키를 게임 재시작 기능과 연결 window.bind("<space>", restart_game) game_flow() window.mainloop()
0eda42b293a5816c846e25cba58e006b19ef3770
barmi/CodingClub_python
/LV2/SourceCode/ch1/myMagic8Ball.py
1,125
3.65625
4
# My Magic 8 Ball import random # 답변을 입력해봅시다. ans1="자! 해보세요!" ans2="됐네요, 이 사람아" ans3="뭐라고? 다시 생각해보세요." ans4="모르니 두려운 것입니다." ans5="칠푼인가요?? 제 정신이 아니군요!" ans6="당신이라면 할 수 있어요!" ans7="해도 그만, 안 해도 그만, 아니겠어요?" ans8="맞아요, 당신은 올바른 선택을 했어요." print("MyMagic8Ball에 오신 것을 환영합니다.") # 사용자의 질문을 입력 받습니다. question = input("조언을 구하고 싶으면 질문을 입력하고 엔터 키를 누르세요.\n") print("고민 중 ...\n" * 4) # 질문에 알맞은 답변을 하는 일에 randint() 함수를 활용합니다. choice=random.randint(1, 8) if choice==1: answer=ans1 elif choice==2: answer=ans2 elif choice==3: answer=ans3 elif choice==4: answer=ans4 elif choice==5: answer=ans5 elif choice==6: answer=ans6 elif choice==7: answer=ans7 else: answer=ans8 # 화면에 답변을 출력합니다. print(answer) input("\n\n마치려면 엔터 키를 누르세요.")
650e11ce5d2d7d32f12a3f22d7a5dc9cecf846e4
jungaSeo/python
/Python02/cal/mathTest.py
756
3.796875
4
''' # 여러 줄 인식 : """ data = """ 안녕하세요. 하하하.. 히히히히힣 """ print(data) print("안녕하세요\n\n하하하..\n\n하하하핳") ''' ''' # 실습 1 # 계산기 a = int(input("숫자 1: ")) b = int(input("숫자 2: ")) print(a,"+",b,"=",a+b) print(a,"-", b,"=",a-b) print(a,"*", b,"=",a*b) print(a,"/", b,"=",a/b) ''' ''' # 기본주석 # 데이터(문자, 숫자) company = '배달의 민족' tel = '010-234-5678' ssn = '880202-2052534' hour = 16 # a = input("숫자1: ") # b = input("숫자2: ") aa = int(input("숫자1: ")) bb = int(input("숫자2: ")) print("입력받은 두 수의 합은:", aa + bb) print() c = input("숫자3: ") # print(aa + c) '''
672a19db7cda79d1d3e3c935385020439cff276f
marauderlabs/leetcode
/easy/897-increasing-order-search-tree.py
811
3.84375
4
# https://leetcode.com/problems/increasing-order-search-tree # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def increasingBST(self, root: TreeNode) -> TreeNode: def inOrder(root: TreeNode, vals: List[int]): if root is None: return inOrder(root.left, vals) vals.append(root.val) inOrder(root.right, vals) vals = [] inOrder(root, vals) # Now we have it in the inorder order in the list cur = newRoot = TreeNode(None) for val in vals: newNode = TreeNode(val) cur.right = newNode cur = cur.right return newRoot.right
d8df108ecad24419cb1f61b344eb42d38529c7b6
Aragami1408/competitive-programming
/codeforces/A/cf791A.py
113
3.53125
4
a,b = tuple(int(x) for x in input("").split(" ")) y = 0 while a <= b: a *= 3 b *= 2 y += 1 print(y)
957430eed1546f073ecaac7e45fd8382b43bdbb1
Givonaldo/POP_URI-JUDGE
/POP_EXEMPLOS/nivel1/Salario.py
990
3.890625
4
''' Created on 5 de dez de 2015 URI Online Judge Salário - 1008 Escreva um programa que leia o número de um funcionário, seu número de horas trabalhadas, o valor que recebe por hora e calcula o salário desse funcionário. A seguir, mostre o número e o salário do funcionário, com duas casas decimais. Entrada O arquivo de entrada contém 2 números inteiros e 1 número com duas casas decimais, representando o número, quantidade de horas trabalhadas e o valor que o funcionário recebe por hora trabalhada, respectivamente. Saída Imprima o número e o salário do funcionário, conforme exemplo fornecido, com um espaço em branco antes e depois da igualdade. No caso do salário, também deve haver um espaço em branco após o $. @author: gilvonaldo ''' NUMERO = int(input()) NUMERO_HORAS_TRABALHADAS = int(input()) VALOR_HORA = float(input()) SALARIO = (VALOR_HORA * NUMERO_HORAS_TRABALHADAS) print ("NUMBER =",NUMERO) print("SALARY = U$ %.2f"%SALARIO)
50be8229b9dbf1c1820e654b12a9bb1224a0dd40
moretanjames/Grav_Sim
/Grav_Sim/movement.py
275
3.5625
4
class Velocity(): ''' Velocity for objects ''' def __init__(self,xspeed = 0, yspeed = 0): self.xspeed = xspeed self.yspeed = yspeed class Coord(): ''' Coordinates for objects ''' def __init__(self, xpos, ypos): self.xpos = xpos self.ypos = ypos
26d257726f861c581e2b50e899efd25e8b1068ff
wwwser11/study_tasks-
/tasks/task7.py
527
3.734375
4
# 7. В функцию передается список списков. Нужно вернуть максимум. который достигает выражение # (a1*a1 + a2*a2 + an*an). Где ai -- максимальный элемент из iго списка. from functools import reduce from itertools import starmap def func(big_list): return reduce(lambda x, y: x + y**2, [0] + list(starmap(max, big_list))) list_of_lists = [[1, 2, 3], [2, 2], [0, 0, 1, 1, 2], [0, 0]] print(func(list_of_lists))
b4baa75a31b415e4e08e24d866b4469288bacbee
amagrabi/ds-preprocess
/dir.py
608
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Helper functions to process directories and files. @author: amagrabi """ import os import shutil import magic def delete_path(path): shutil.rmtree(path) def create_folders(folder_list, path): for folder in folder_list: folder_path = os.path.join(path, folder) if not os.path.exists(folder_path): os.mkdir(folder_path) def print_filetypes(path): for path, subdirs, files in os.walk(path): for file in files: filepath = os.path.join(path, file) print(magic.from_file(filepath))
8df63ced2463425561006248e766d2a6cb8f8be5
ScaredTuna/Python
/Tesco.py
332
3.6875
4
Product = "Pepsi" Quantity = 10 Unit_Price = 1.25 Amount = Quantity * Unit_Price VAT = Amount * 11 / 100 print("Product:", Product) print("Quantity Purchased:", Quantity) print("Unit Price:", Unit_Price) print("----------------------------------") print("Total Bill:", Amount) print("VAT:", VAT) print("Net Amount:", (Amount - VAT))
96bb253cbcac7168c009a01e2b1ebb56f1e537b3
ScaredTuna/Python
/Lists2.py
700
4.0625
4
names = [] choice = "" longest = "" second = "" print("------------------------------------------") while choice != "exit": choice = input("Enter name (exit to quit):") if choice != "exit": names.append(choice) if len(choice) > len(longest): second = longest longest = choice elif len(choice) > len(second): second = choice print("------------------------------------------") i = 0 print("List of Names:") while i < len(names): print(i + 1, ".", names[i]) i += 1 print("") print("Name With the Most Characters:", longest) print("Name With Second Most Characters:", second) print("------------------------------------------")
1e49e98b5f63ff14120531c952868f6841ef56ba
ScaredTuna/Python
/Salary.py
562
3.953125
4
name = input("Enter Name:") salary = int(input("Enter Salary:")) if salary >= 35000: VAT = salary * 21 / 100 if salary < 35000: VAT = salary * 17 / 100 print("----------------------------------------------") print("Name:", name) print("Salary:", salary) print("----------------------------------------------") print("Total VAT:", VAT) print("Net Salary:", (salary - VAT)) print("Monthly Salary:", (salary / 12)) print("Monthly VAT:", (VAT / 12)) print("Monthly Net Salary:", ((salary - VAT) / 12)) print("----------------------------------------------")
b4a85cfa138df5113411b2ce9f52360a3066342d
ScaredTuna/Python
/Results2.py
455
4.125
4
name = input("Enter Name:") phy = int(input("Enter Physics Marks:")) che = int(input("Enter Chemistry Marks:")) mat = int(input("Enter Mathematics Marks:")) tot = phy + che + mat per = tot * 100 / 450 print("-------------------------------------") print("Name:", name) print("Total Marks:", tot) print("Percentage:", per) if per >= 60: print(name, "has Passed") if per < 60: print(name, "has Failed") print("-------------------------------------")
38643b407ca00ff786cc993b12b11fd3a7668656
ScaredTuna/Python
/NestedIf.py
276
3.796875
4
no = int(input("Enter Number:")) print("-----------------------------------") if no > 1000: print("A") if no > 5000: print("C") else: print("E") else: print("B") if no > 500: print("D") print("-----------------------------------")
89db5cdc6027908c848eb4b27f0b54c3774ab387
ianaquino47/Daily-Coding-Problems
/Problem_109.py
376
4
4
# This problem was asked by Cisco. # Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should be swapped, the 3rd and 4th bit should be swapped, and so on. # For example, 10101010 should be 01010101. 11100010 should be 11010001. # Bonus: Can you do this in one line? def swap_bits(x): return (x & 0b10101010) >> 1 | (x & 0b01010101) << 1
c96d92aa08169e386366b7f6798f4460e92dfe32
ianaquino47/Daily-Coding-Problems
/Problem_68.py
1,295
4.03125
4
# This problem was asked by Google. # On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops that have another bishop located between them, i.e. bishops can attack through pieces. # You are given N bishops, represented as (row, column) tuples on a M by M chessboard. Write a function to count the number of pairs of bishops that attack each other. The ordering of the pair doesn't matter: (1, 2) is considered the same as (2, 1). # For example, given M = 5 and the list of bishops: # (0, 0) # (1, 2) # (2, 2) # (4, 0) # The board would look like this: # [b 0 0 0 0] # [0 0 b 0 0] # [0 0 b 0 0] # [0 0 0 0 0] # [b 0 0 0 0] # You should return 2, since bishops 1 and 3 attack each other, as well as bishops 3 and 4. from collections import defaultdict TOP_LEFT_TO_BOTTOM_RIGHT = 0 TOP_RIGHT_TO_BOTTOM_LEFT = 1 def combos(num): return num * (num - 1) / 2 def pairs(bishops, m): counts = defaultdict(int) for r, c in bishops: top_lr, top_lc = (r - min(r, c), c - min(r, c)) top_rr, top_rc = (r - min(r, m - c), c + min(r, m - c)) counts[top_lr, top_lc, TOP_LEFT_TO_BOTTOM_RIGHT] += 1 counts[top_rr, top_rc, TOP_RIGHT_TO_BOTTOM_LEFT] += 1 return sum(combos(c) for c in counts.values())
e2472ed715c6a86dd43db8df6e38e0faa314c9fd
ianaquino47/Daily-Coding-Problems
/Problem_45.py
498
3.796875
4
# This problem was asked by Two Sigma. # Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, implement a function rand7() that returns an integer from 1 to 7 (inclusive). def rand7(): r1, r2 = rand5(), rand5() if r2 <= 3: return r1 elif r2 == 4: if r1 <= 3: return 6 else: return rand7() else: # r2 == 5 if r1 <= 3: return 7 else: return rand7()
0d2e64fe59a76cdf62779241733dd96e1ea5ae0d
ianaquino47/Daily-Coding-Problems
/Problem_73.py
297
4.03125
4
# This problem was asked by Google. # Given the head of a singly linked list, reverse it in-place. def reverse(head): prev, current = None, head while current is not None: tmp = current.next current.next = prev prev = current current = tmp return prev
da7b63be1bd15d4a098be19875876505f7f82f4a
ianaquino47/Daily-Coding-Problems
/Problem_90.py
578
4.03125
4
# This question was asked by Google. # Given an integer n and a list of integers l, write a function that randomly generates a number from 0 to n-1 that isn't in l (uniform). from random import randrange def process_list(n, l): all_nums_set = set() for i in range(n): all_nums_set.add(i) l_set = set(l) nums_set = all_nums_set - l_set return list(nums_set) def random_number_excluing_list(n, l): nums_list = process_list(n, l) idx = randrange(0, len(nums_list)) return nums_list[idx] print(random_number_excluing_list(4, [1, 2, 5]))
328710868aa68a29a7383e18f75727655aeb8076
ianaquino47/Daily-Coding-Problems
/Problem_58.py
1,400
3.875
4
# This problem was asked by Amazon. # An sorted array of integers was rotated an unknown number of times. # Given such an array, find the index of the element in the array in faster than linear time. If the element doesn't exist in the array, return null. # For example, given the array [13, 18, 25, 2, 8, 10] and the element 8, return 4 (the index of 8 in the array). # You can assume all the integers in the array are unique. def shifted_array_search(lst, num): # First, find where the breaking point is in the shifted array i = len(lst) // 2 dist = i // 2 while True: if lst[0] > lst[i] and lst[i - 1] > lst[i]: break elif dist == 0: break elif lst[0] <= lst[i]: i = i + dist elif lst[i - 1] <= lst[i]: i = i - dist else: break dist = dist // 2 # Now that we have the bottom, we can do binary search as usual, # wrapping around the rotation. low = i high = i - 1 dist = len(lst) // 2 while True: if dist == 0: return None guess_ind = (low + dist) % len(lst) guess = lst[guess_ind] if guess == num: return guess_ind if guess < num: low = (low + dist) % len(lst) if guess > num: high = (len(lst) + high - dist) % len(lst) dist = dist // 2
6cebbce8244a78c5a4c28f8ebe28b8064ea6dce1
firas3333/Artificial-Intelegence-Lab
/assignment2/reinforcmentL.py
13,128
3.671875
4
from vehicle import Vehicle import learningUtils # goal vihcle (4,2) means its out # 2 arrays to set the length of a vehicle GOAL_VEHICLE = Vehicle('X', 4, 2, 'H') smallcars = {'X', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'} largecars = {'O', 'P', 'Q', 'R'} # class RushHour has all the moethods and functionts we need to implement A* for solving RushHour (node) class RushHour(object): # constructor to initiate vehicles, board, move, depth of the state , and its value (heuristic) def __init__(self, vehicles, board=None, moved=None, depth=0, value=None): """Create a new Rush Hour board. Arguments: vehicles: a set of Vehicle objects. """ self.board = board self.vehicles = tuple(vehicles) self.moved = moved self.depth = depth self.value = value # overload of equal def __eq__(self, other): return self.vehicles == other.vehicles # overload notequal def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.__repr__()) # comparing board depending on value def __lt__(self, other): return self.value < other.value def __repr__(self): s = '-' * 8 + '\n' for line in self.get_board(): s += '|{0}|\n'.format(''.join(line)) s += '-' * 8 + '\n' return s # using the the array of vehicles (self.vehicles) we creat and return the of the board where in right now def get_board(self): board = [[' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ']] for vehicle in self.vehicles: x, y = vehicle.x, vehicle.y if vehicle.orientation == 'H': for i in range(vehicle.length): board[y][x + i] = vehicle.id else: for i in range(vehicle.length): board[y + i][x] = vehicle.id return board # true if we found solution def solved(self): return GOAL_VEHICLE in self.vehicles def get_hash2(self): yield self.vehicles def get_hash(self): return self.vehicles # our goal vehicle is (X,4,2,H) so if we have X.x==4 we win :D def win(self): for v in self.vehicles: if v.id == 'X': if v.x == 4: return True else: return False # getting all the possible moves in this format [index,move] def get_moves(self): board = self.get_board() moves = [] for index, v in enumerate(self.vehicles): # horizontally orientated vehicle if v.orientation == 'H': # left test if v.x != 0 and board[v.y][v.x - 1] == ' ': moves.append([index, -1]) # right test if v.x + v.length - 1 < 5 and board[v.y][v.x + v.length] == ' ': moves.append([index, 1]) # vertically orientated vehicle else: # up test if v.y != 0 and board[v.y - 1][v.x] == ' ': moves.append([index, -1]) # down test if v.y + v.length - 1 < 5 and board[v.y + v.length][v.x] == ' ': moves.append([index, 1]) return moves def move(self, index, move,values): board = self.get_board() node = RushHour(list(self.vehicles), list(board), (index, move), self.depth + 1) # get the vehicle that needs to be moved vehicle = node.vehicles[index] # move horizontal vehicle if vehicle.orientation == 'H': # generate new row for board node.board[vehicle.y] = list(node.board[vehicle.y]) # right if move > 0: node.board[vehicle.y][vehicle.x] = ' ' node.board[vehicle.y][vehicle.x + vehicle.length] = vehicle.id # left else: node.board[vehicle.y][vehicle.x - 1] = vehicle.id node.board[vehicle.y][vehicle.x + vehicle.length - 1] = ' ' # move vertical vehicle else: # down if move > 0: # new rows for board node.board[vehicle.y] = list(node.board[vehicle.y]) node.board[vehicle.y + vehicle.length] = list(node.board[vehicle.y + vehicle.length]) node.board[vehicle.y][vehicle.x] = ' ' node.board[vehicle.y + vehicle.length][vehicle.x] = vehicle.id # up else: # rows for board node.board[vehicle.y - 1] = list(node.board[vehicle.y - 1]) node.board[vehicle.y + vehicle.length - 1] = list(node.board[vehicle.y + vehicle.length - 1]) node.board[vehicle.y - 1][vehicle.x] = vehicle.id node.board[vehicle.y + vehicle.length - 1][vehicle.x] = ' ' # update self.vehicles node.vehicles = list(node.vehicles) # depends on car orientation we move if node.vehicles[index].orientation == 'H': node.vehicles[index] = Vehicle(node.vehicles[index].id, vehicle.x + move, vehicle.y, vehicle.orientation) elif node.vehicles[index].orientation == 'V': node.vehicles[index] = Vehicle(node.vehicles[index].id, vehicle.x, vehicle.y + move, vehicle.orientation) node.vehicles = tuple(node.vehicles) # calculate the cost estimate node.value = values[tuple([index,move])] return node def get_cost_estimate(self): return self.depth + self.get_min_distance() + self.get_additional_steps() def get_min_distance(self): for v in self.vehicles: if v.id == 'X': return 5 - (v.x + v.length - 1) def get_additional_steps(self): steps = 0 c = 0 for v in self.vehicles: if v.id == 'X': c += 1 origin = v.x + v.length - 1 # check for vehicles in the direct path car x for i in range(1, self.get_min_distance() + 1): # get the i places from the car x index = self.board[origin + i][2] if index != ' ': # get the directly blocking vehicle counter = 0 for i in self.vehicles: if i.id == index: vehicle = self.vehicles[counter] counter += 1 # center large car in path of car x if vehicle.y < 2 < vehicle.y + vehicle.length - 1: steps += 2 # check car blocking is blocked both sides if self.is_blocked(index): steps += 1 # check if those blockers are blocked if self.is_blocked(self.board[vehicle.y - 1][vehicle.x]) and self.is_blocked( self.board[vehicle.y + vehicle.length - 1][vehicle.x]): steps += 1 # blocked no center else: steps += 1 # check if 1st level blocker is blocked on both sides (2nd level blocker) if self.is_blocked(index): steps += 1 # check car blocking is blocked both sides if self.is_blocked(self.board[vehicle.y - 1][vehicle.x]) and self.is_blocked( self.board[vehicle.y + vehicle.length - 1][vehicle.x]): steps += 1 # check blocker's shortest path is blocked elif vehicle.y == 2: if self.is_blocked(self.board[vehicle.y + vehicle.length - 1][vehicle.x]) and \ self.board[vehicle.y - 2][vehicle.x]: steps += 2 elif self.board[vehicle.y + vehicle.length - 1][vehicle.x]: steps += 1 # check blocker's shortest path is blocked else: if self.is_blocked(self.board[vehicle.y - 1][vehicle.x]) and \ self.board[vehicle.y + vehicle.length][vehicle.x]: steps += 2 elif self.board[vehicle.y - 1][vehicle.x]: steps += 1 return steps # checking if the block around me is blocked def is_blocked(self, index): if index == ' ': return False counter = 0 for i in self.vehicles: if i.id == index: vehicle = self.vehicles[counter] counter += 1 # horizontally orientated vehicle if vehicle.orientation == 'H': if vehicle.x == 0 and self.board[vehicle.y][vehicle.x - 1]: return True elif vehicle.x + vehicle.length - 1 == 5 and self.board[vehicle.x][vehicle.y - 1]: return True elif self.board[vehicle.x][vehicle.y - 1] and self.board[vehicle.x][vehicle.x + vehicle.length - 1]: return True # vertically orientated vehicle else: if vehicle.y == 0 and self.board[vehicle.y + vehicle.length - 1][vehicle.x]: return True elif vehicle.y + vehicle.length - 1 == 5 and self.board[vehicle.y - 1][vehicle.x]: return True elif self.board[vehicle.x - 1][vehicle.y] and self.board[vehicle.y + vehicle.length - 1][vehicle.y]: return True def load_file(line): #array to keep track of cars that weve already added to the array of vehicles visitedLOAD = [] #array of the cars regular array vehicles = [] #array for objects of class vehicle (also contains same cars) finalvehicles=[] #6x6 listof lists board = [[' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ']] counter = 0 #loop to read the line charachter by charachter for i in range(0, 6): for j in range(0, 6): #name of the care carid = line[counter] #we decided its simpler to call empty block as white space rather than '.' if carid == '.': board[i][j] = ' ' else: #filling the board with cars(were inserting charachter by character regardless of what it means ) board[i][j] = line[counter] #if its first time we se this car we must store it in vehicles as normal list # vehicles[i]=[carid, row,column,length] if carid not in visitedLOAD and carid != '.': if carid in smallcars: short = 2 vehicles.append([carid, int(i), int(j), int(short)]) else: long = 3 vehicles.append([carid, int(i), int(j), int(long)]) visitedLOAD.append(carid) counter += 1 #checking the board to detirmine car's orientation for car in vehicles: v, h = 'V', 'H' if car[1] + 1 > 5: if car[0] == board[car[1] - 1][car[2]]: car.extend(v) else: car.extend(h) elif car[1] - 1 < 0: if car[0] == board[car[1] + 1][car[2]]: car.extend(v) else: car.extend(h) elif car[0] == board[car[1] - 1][car[2]] or car[0] == board[car[1] + 1][car[2]]: car.extend(v) else: car.extend(h) id, x, y, orientation = car[0],car[2],car[1],car[4] #finalvehicles array of cars wich each car is represented as object from vehicle class vehicle(id,column,row,orientation) finalvehicles.append(Vehicle(id, x, y, orientation)) #create instance of class rushhour that has all the vehicles in it return RushHour(set(finalvehicles))
34d1d4c7e3e16b4cb08fa7f398f89174a30afae8
firas3333/Artificial-Intelegence-Lab
/assignment2/learningUtils.py
1,851
3.671875
4
import random class Move(object): # constructor to initiate vehicles, board, move, depth of the state , and its value (heuristic) def __init__(self,car, direction): """Create a new Rush Hour board. Arguments: vehicles: a set of Vehicle objects. """ self.car = car self.direction = direction self.w = random.randint(1,500) # overload of equal def __eq__(self, other): return self.w == other.w and self.car==other.car and self.direction==other.direction # overload notequal def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.__repr__()) # comparing board depending on value def __lt__(self, other): return self.w < other.w def get_w(self): return self.w def inc_w(self): return self.w+1 def dec_w(self): return self.w-1 def getid(self): return self.car def getdir(self): return self.direction def loadallmoves(path): moves = open(path, "r") allpossiblemove=dict() movess=[] movesclass=[] for line in moves: id,dir=line.split(',') movess.append([int(id),int(dir)]) for m in movess: move=Move(m[0],m[1]) w=move.get_w() allpossiblemove[tuple(m)]=w movesclass.append(move) return allpossiblemove,movesclass def loadoptsol(path): optsol=open(path,"r") puzlsoptsol=dict() i=0 for line in optsol: puzlsoptsol[i]=line i+=1 return puzlsoptsol # # if __name__ == '__main__': # pathformoves="possiblemoves" # pathforopt="optimalsolution" # allpossiblemove, movesclass = loadallmoves(pathformoves) # print(allpossiblemove[tuple([1,-1])])
9b54d192cad797d0121cca02a5bb72cd7f1517fd
tlively/distributed-lightcycle
/game_utils.py
10,672
3.90625
4
""" game_utils.py This contains utility functions and classes necessary for running the game. The three classes defined in the file are Direction, Message and Game State. Direction defines the cardinal directions and allows a player to extrapolate in a given direction given a location. Message encapsulates the inter-client communication. It has multiple Message types that can be created and serialized and deserialized for sending over the wire via protocol buffers. Game State is an object that has the state of the game that each of the players holds. It has various information about the state of the board and methods for initializing the game and running it. There are three other functions in game_utils.py that are used for drawing the lines for the game. """ import sys, random, time, copy, math from enum import Enum import player_pb2 as pb import pygame class Direction(Enum): """ Representation of the four cardinal directions. """ east = 0 north= 1 west = 2 south = 3 def extrapolate(self, loc, dist): """ Returns the location `dist' units away from location `loc'. Args: loc: The (x,y) location tuple from which to extrapolate dist: The distance to extrapolate by Ret: The resulting (x,y) location tuple """ if self == Direction.east: return (loc[0] + dist, loc[1]) elif self == Direction.north: return (loc[0], loc[1] - dist) elif self == Direction.west: return (loc[0] - dist, loc[1]) elif self == Direction.south: return (loc[0], loc[1] + dist) else: assert False class Message(object): """ The Message class encapsulates all of the inter-client communication that is exposed above the level of the Netwok Layer. """ class Type(Enum): start = 1 move = 2 kill = 3 exit = 4 def __init__(self, player, pos, direction, mtype): """ This constructor should not be called directly. Instead, use Message.start, Message.move, or Message.kill. """ assert direction == None or type(direction) is Direction self.player = player self.pos = pos self.direction = direction self.mtype = mtype @staticmethod def start(player): """ Returns a new start message for the given player. """ return Message(player, None, None, Message.Type.start) @staticmethod def move(player, pos, direction): """ Returns a new move message for when the given player moves in the given direction at the given position. """ return Message(player, pos, direction, Message.Type.move) @staticmethod def kill(player): """ Returns a new kill message for when the given player dies. """ return Message(player, None, None, Message.Type.kill) @staticmethod def exit(player): """ Returns a new exit message for when all players die. """ return Message(player, None, None, Message.Type.exit) @staticmethod def deserialize(msg_str): """ Create a Message from its serialized protobuf form. Args: msg_str - The protobuf string Returns: the deserialized Message """ network_msg = pb.GameMsg() network_msg.ParseFromString(msg_str) player = network_msg.player_no pos = None if network_msg.HasField('pos'): pos = (network_msg.pos.x, network_msg.pos.y) direction = None if network_msg.HasField('dir'): direction = Direction(network_msg.dir) mtype = Message.Type(network_msg.mtype) return Message(player, pos, direction, mtype) def serialize(self): """ Serializes the message as a protobuf. Returns: A string representing the message. """ network_msg = pb.GameMsg() network_msg.mtype = self.mtype.value network_msg.player_no = self.player if self.pos: network_msg.pos.x = self.pos[0] network_msg.pos.y = self.pos[1] if self.direction: network_msg.dir = self.direction.value return network_msg.SerializeToString() class GameState(object): """ Internal representation of game state """ def __init__(self, size=(600,600), speed=100): """ Initialize GameState object. Args: size - a length,width tuple of the game board size speed - the speed of the players in px/sec """ self.players_left = [0,1,2,3] start_pos = [(10, 10), (size[0]-10, 10), (size[0]-10, size[0]-10), (10, size[0]-10)] start_dir = [Direction.east, Direction.south, Direction.west, Direction.north] self.state = [[{'pos': p, 'dir': d}] for p,d in zip(start_pos, start_dir)] self.width, self.height = size self.speed = speed def start(self): """ Start the game by copying the initial position of each player into the last slot of their state array. """ start_time = time.time() for p in self.players_left: self.state[p].append(copy.copy(self.state[p][0])) self.state[p][-1]['time'] = start_time def update(self, player): """ Updates the game state by moving each player's position forward. Args: player - the local player number Returns: True if the local player should die, False otherwise """ cur_time = time.time() last_pos = None if player in self.players_left: last_pos = self.state[player][-1]['pos'] # update positions for p in self.players_left: pos = self.state[p][-1]['pos'] d = self.state[p][-1]['dir'] t = self.state[p][-1]['time'] self.state[p][-1]['pos'] = d.extrapolate(pos, (cur_time - t) * self.speed) self.state[p][-1]['time'] = cur_time # do not do collision detection if already dead if player not in self.players_left: return False # check for local player death cur_pos = self.state[player][-1]['pos'] # check b{ounds if cur_pos[0] < 0 or cur_pos[1] < 0 or \ cur_pos[0] >= self.width or cur_pos[1] >= self.height: print 'bounds' return True # check trail collision for p2 in self.players_left: r = range(len(self.state[p2])-1) # modify range for colliding with self if player == p2: r = range(len(self.state[p2])-2) # test collision with each segment for i in r: a = self.state[p2][i]['pos'] b = self.state[p2][i+1]['pos'] if self._intersect(a, b, last_pos, cur_pos): return True # don't die return False def _intersect(self, a1, a2, b1, b2): """ Check for intersection between the line segment between point a1 and a2 and the line segment between b1 and b2. The line segments must be either vertical or horizontal. Returns: True, if the line segments intersect, False, otherwise """ a_vert = a1[0] == a2[0] b_vert = b1[0] == b2[0] # non-lines if a1 == a2 or b1 == b2: return False # both vertical, check colinearity then intersection if a_vert and b_vert: if a1[0] != b1[0]: return False return (a1[1] <= b1[1] and b1[1] <= a2[1]) or \ (a1[1] <= b2[1] and b2[1] <= a2[1]) # both horizontal, check colinearity then intersection if not a_vert and not b_vert: if a1[1] != b1[1]: return False return (a1[0] <= b1[0] and b1[0] <= a2[0]) or \ (a1[0] <= b2[0] and b2[0] <= a2[0]) # special case for continuation if a2 == b1: return False # a vertical, b horizontal if a_vert: return min(a1[1],a2[1]) <= b1[1] and b1[1] <= max(a1[1],a2[1]) and \ min(b1[0],b2[0]) <= a1[0] and a1[0] <= max(b1[0],b2[0]) # b vertical, a horizontal return min(b1[1],b2[1]) <= a1[1] and a1[1] <= max(b1[1],b2[1]) and \ min(a1[0],a2[0]) <= b1[0] and b1[0] <= max(a1[0],a2[0]) def move(self, player, pos, direction, time): """ Update the last point in the player's history and then create a new last point. """ if self.state[player]: self.state[player][-1]['pos'] = pos self.state[player][-1]['dir'] = direction self.state[player][-1]['time'] = time self.state[player].append(copy.copy(self.state[player][-1])) def kill(self, player): """ Remove the given player from the game. """ if player in self.players_left: self.players_left.remove(player) self.state[player] = [] def draw_dashed_line(surf, x1, y1, x2, y2, color, width=1, dash_length=2): dl = dash_length if (x1 == x2): ycoords = [y for y in range(y1, y2, dl if y1 < y2 else -dl)] xcoords = [x1] * len(ycoords) elif (y1 == y2): xcoords = [x for x in range(x1, x2, dl if x1 < x2 else -dl)] ycoords = [y1] * len(xcoords) else: a = abs(x2 - x1) b = abs(y2 - y1) c = round(math.sqrt(a**2 + b**2)) dx = dl * a / c dy = dl * b / c xcoords = [x for x in numpy.arange(x1, x2, dx if x1 < x2 else -dx)] ycoords = [y for y in numpy.arange(y1, y2, dy if y1 < y2 else -dy)] next_coords = list(zip(xcoords[1::2], ycoords[1::2])) last_coords = list(zip(xcoords[0::2], ycoords[0::2])) for (x1, y1), (x2, y2) in zip(next_coords, last_coords): start = (round(x1), round(y1)) end = (round(x2), round(y2)) pygame.draw.line(surf, color, start, end, width) def draw_solid_line(surf, x1, y1, x2, y2, color, width=1): start = (round(x1), round(y1)) end = (round(x2), round(y2)) pygame.draw.line(surf, color, start, end, width) def line(surf, x1, y1, x2, y2, color, dashed=False, width=1): if dashed: draw_dashed_line(surf, x1, y1, x2, y2, color, width) else: draw_solid_line(surf, x1, y1, x2, y2, color, width)
69e6a29d952a0a5faaceed45e30bf78c5120c070
TommyWongww/killingCodes
/Daily Temperatures.py
1,025
4.25
4
# @Time : 2019/4/22 22:54 # @Author : shakespere # @FileName: Daily Temperatures.py ''' 739. Daily Temperatures Medium Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. ''' class Solution(object): def dailyTemperatures(self, T): """ :type T: List[int] :rtype: List[int] """ res = [0] * len(T) stack = [] for i in range(len(T)): while stack and (T[i] > T[stack[-1]]): idx = stack.pop() res[idx] = i-idx stack.append(i) return res
1ae82daf01b528df650bd7e72a69107cdf686a82
TommyWongww/killingCodes
/Invert Binary Tree.py
1,251
4.125
4
# @Time : 2019/4/25 23:51 # @Author : shakespere # @FileName: Invert Binary Tree.py ''' 226. Invert Binary Tree Easy Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off. ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None import collections class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root is not None: nodes = [] nodes.append(root) while nodes: node = nodes.pop() node.left,node.right = node.right,node.left if node.left is not None: nodes.append(node.left) if node.right is not None: nodes.append(node.right) return root
9befa8049cd7c31fd959b6ad7ca652c4e1435d00
jillgower/pyapi
/sqldb/db_challeng.py
2,819
4.21875
4
#!/usr/bin/env python3 import sqlite3 def create_table(): conn = sqlite3.connect('test.db') conn.execute('''CREATE TABLE IF NOT EXISTS EMPLOYEES (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL);''') print("Table created successfully") conn.close() def insert_data(): conn = sqlite3.connect('test.db') conn.execute("INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 )") conn.execute("INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 )") conn.execute("INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )") conn.execute("INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )") conn.commit() print("Records created successfully") conn.close() def print_data(): conn = sqlite3.connect('test.db') cursor = conn.execute("SELECT id, name, address, salary from EMPLOYEES") for row in cursor: print("ID = ", row[0]) print("NAME = ", row[1]) print("ADDRESS = ", row[2]) print("SALARY = ", row[3], "\n") print("Operation done successfully") conn.close() def update_data(): conn = sqlite3.connect('test.db') # find out which row you want to update, so print_data runs first print_data() update_select = input("select row to update:") # what value needs to be changed? print("you can change, NAME, ADDRESS or SALARY") update_stuff = input("Enter NAME ADDRESS OR SALARY:") update_val = input("Enter new value:") if update_stuff == "NAME": cursor = conn.execute("UPDATE EMPLOYEES set NAME= ? where ID = ?", (update_val,update_select)) conn.commit() elif update_stuff == "ADDRESS": cursor = conn.execute("UPDATE EMPLOYEES set ADDRESS= ? where ID = ?", (update_val,update_select)) conn.commit() elif update_stuff == "SALARY": cursor = conn.execute("UPDATE EMPLOYEES set SALARY= ? where ID = ?", (update_val,update_select)) conn.commit() def delete_data(): conn = sqlite3.connect('test.db') #print the table first print_data() line_del = input("Enter line to be deleted") conn.execute("DELETE from EMPLOYEES where id = ?;", (line_del)) conn.commit() print_data() if __name__ == "__main__": create_table() print("="*35) print("Inserting data") insert_data() print("="*35) print("here is your table") print_data() print("="*35) print("lets update it") update_data() print("="*35) print("Lets delete some stuff") delete_data() print("all done with the challenge")
1dcf3d4b3a383247a907379bf32ec77174667fd8
sslaia/belajar_python
/latihan/toko_hider.py
8,906
3.515625
4
import json import datetime import os def menginput_menu(): # mendeklarasikan berbagai variable daftar_menu = [] # fungsi loop memasukkan data menu makanan keluar = False while keluar == False: # menampilkan formulir isian nama_makanan = input("Masukkan nama makanan : ") harga_makanan = int(input("Masukkan harga : ")) daftar_menu.append({"nama": nama_makanan, "harga": harga_makanan}) # bagian berikut hanya memastikan entah masih ada data yang mau dimasukkan # bila ada, maka proses dimulai kembali dari atas # kalau tidak proses dihentikan dan data dimasukkan ke database selesai = input("Selesai? (y/t) ") if selesai == "y": keluar = True # setelah data selesai dimasukkan, data disimpan ke dalam database # with open('toko_menu.txt', 'w') as f: # f.write(str(daftar_menu)) with open('toko_menu.json', 'w') as f: data_menu = {"menu": daftar_menu} json.dump(data_menu, f) def menginput_transaksi(): # mendeklarasikan berbagai variable daftar_transaksi = [] print() kasir = input("Nama kasir : ") print() # mengambil tanggal secara otomatis waktu_umum = datetime.datetime.now() waktu = waktu_umum.strftime("%Y-%m-%d %H:%M:%S") # fungsi loop memasukkan data menu makanan keluar = False while keluar == False: # menampilkan daftar menu print("*" * 75) print("TOKO HIDER\n".center(75)) print("Hilifalawu, Kec. Maniamölö, Kab. Nias Selatan (HP: 085 222 000 000)".center(75)) print("*" * 75) print("Pilihan Menu") print("-" * 25) print("1. Gore Gae -> Rp 1.000") print("2. Gado-Gado -> Rp 1.500") print("3. Kopi susu -> Rp 2.000") print("4. Teh Manis -> Rp 2.500") print("-" * 25) print() # memasukkan transaksi item = input("Makanan (1/2/3/4) : ") jumlah = int(input("Masukkan jumlah : ")) anggota = input("Anggota? (y/t) : ") item_menu = "" harga = 0 if item == "1": item_menu = "Gore Gae" harga = jumlah * 1000 elif item == "2": item_menu = "Gado-Gado" harga = jumlah * 1500 elif item == "3": item_menu = "Kopi Susu" harga = jumlah * 2000 else: item_menu = "Teh Manis" harga = jumlah * 2500 total = 0.00 if harga >= 100000: if anggota == "y": total = harga * 0.20 else: total = harga * 0.15 if harga >= 75000: if anggota == "y": total = harga * 0.10 else: total = harga * 0.075 if harga >= 50000: if anggota == "y": total = harga * 0.05 else: total = harga * 0.025 daftar_transaksi.append({"kasir": kasir, "waktu": waktu, "item": item_menu, "jumlah": jumlah, "total": total}) selesai = input("Selesai? (y/t) ") if selesai == "y": keluar = True # setelah data selesai dimasukkan, data disimpan ke dalam database # with open('toko_transaksi.json', 'a') as f: # f.write(str(daftar_transaksi)) with open('toko_transaksi.json', 'a') as f: data_transaksi = {"transaksi": daftar_transaksi} json.dump(data_transaksi, f) def menginput_anggota(): # mendeklarasikan berbagai variable daftar_anggota = [] keluar = False while keluar == False: # menampilkan formulir isian print() nama = input("Masukkan nama : ") nomor = input("Masukkan nomor : ") daftar_anggota.append({"nama": nama, "nomor": nomor}) selesai = input("Selesai? (y/t) ") if selesai == "y": keluar = True # with open('hider_anggota.txt', 'w') as f: # f.write(str(daftar_anggota)) with open('toko_anggota.json', 'w') as json_file: data_anggota = {"anggota": daftar_anggota} json.dump(data_anggota, json_file) def cek(berkas): return os.path.exists(berkas) def membuat_backup(): print() print("Sebentar yah... sedang membuat backup") # mendeklarasikan berbagai variable daftar_anggota = [] daftar_menu = [] daftar_transaksi = [] # mencek entah berkas data ada toko_hider = cek("toko_hider.json") if (toko_hider == False): print(toko_hider) print("Belum ada database. Saya akan menciptakannya.") elif (toko_hider == True) and (os.stat("toko_hider.json").st_size == 0): print("Belum ada database. Saya akan menciptakannya.") else: # memuat daftar menu yang lama dari database with open("toko_hider.json") as f: json_data = json.load(f) # memuat daftar anggota for i in json_data["anggota"]: nama = i["nama"] nomor = i["nomor"] daftar_anggota.append({"nama": nama, "nomor": nomor}) # memuta daftar menu for i in json_data["menu"]: nama = i["nama"] harga = i["harga"] daftar_menu.append({"nama": nama, "harga": harga}) # membuat daftar transaksi for i in json_data["transaksi"]: kasir = i["kasir"] waktu = i["waktu"] item = i["item"] jumlah = i["jumlah"] total = i["total"] daftar_transaksi.append({"kasir": kasir, "waktu": waktu, "item": item, "jumlah": jumlah, "total": total}) # memuat daftar menu yang baru toko_anggota = cek("toko_anggota.json") if (toko_anggota == False): print("Belum ada anggota baru, yang perlu di-backup.") elif (toko_anggota == True) and (os.stat("toko_anggota.json").st_size == 0): print("Belum ada anggota baru, yang perlu di-backup.") else: with open("toko_anggota.json") as f: data_anggota = json.load(f) # membuat daftar anggota for i in data_anggota["anggota"]: nama = i["nama"] nomor = i["nomor"] daftar_anggota.append({"nama": nama, "nomor": nomor}) toko_menu = cek("toko_menu.json") if (toko_menu == False): print("Belum ada menu baru, yang perlu di-backup.") elif (toko_menu == True) and (os.stat("toko_menu.json") == 0): print("Belum ada menu baru, yang perlu di-backup.") else: with open("toko_menu.json", "r") as f: data_menu = json.load(f) f.close() # membuat daftar anggota for i in data_menu["menu"]: nama = i["nama"] harga = i["harga"] daftar_menu.append({"nama": nama, "harga": harga}) toko_transaksi = cek("toko_transaksi.json") if (toko_transaksi == False): print("Belum ada transaksi baru, yang perlu di-backup.") elif (toko_transaksi == True) and (os.stat("toko_transaksi.json") == 0): print("Belum ada transaksi baru, yang perlu di-backup.") else: with open("toko_transaksi.json") as f: data_transaksi = json.load(f) f.close() # membuat daftar transaksi for i in data_transaksi["transaksi"]: kasir = i["kasir"] waktu = i["waktu"] item = i["item"] jumlah = i["jumlah"] total = i["total"] daftar_transaksi.append({"kasir": kasir, "waktu": waktu, "item": item, "jumlah": jumlah, "total": total}) # membuat backup with open("toko_hider.json", "w") as f: data_toko = {"anggota": daftar_anggota, "menu": daftar_menu, "transaksi": daftar_transaksi} json.dump(data_toko, f) print() print("Selesai. Saohagölö!!!!!!") print("Kembali ke layar pilihan!") print() # Dari sini program mulai exit = False while exit == False: # Menampilkan pilihan operasi print("*" * 40) print("TOKO HIDER\n".center(40)) print() print("Hilifalawu, Maniamölö, Nias Selatan".center(40)) print() print("*" * 40) print("Silakan memilih:") print("1. Memasukkan transaksi") print("2. Memasukkan menu makanan baru") print("3. Memasukkan anggota baru") print("4. Membuat backup data") print("5. Keluar") print("*" * 40) print() pilihan = input("Pilihan Anda: ") if pilihan == "4": membuat_backup() elif pilihan == "3": menginput_anggota() elif pilihan == "2": menginput_menu() elif pilihan == "1": menginput_transaksi() else: exit = True
028fd4df6d1d0722e4e2209bf1ae2159567fcd25
lazyboy8000/algorithms
/binarysearch.py
677
4.0625
4
mylist = [1, 2, 3, 4, 5, 6] def binarySearch(mylist, item): lowIndex = 0 highIndex = len(mylist) - 1 while lowIndex <= highIndex: middleIndex = (lowIndex + highIndex) / 2 print middleIndex # 2, if item == mylist[middleIndex]: return '%d found at position %d' % (item, middleIndex) elif item < mylist[middleIndex]: highIndex = middleIndex - 1 #Set highIndex to middle element || disregard all elements above mid. elif item > mylist[middleIndex]: lowIndex = middleIndex + 1 #Set the lowIndex to the middle element || disregard all element below mid. print binarySearch(mylist, 5)
837f5b80b8fe013676c41c9184b877a1add378b0
lazyboy8000/algorithms
/mergesort2.py
2,634
4
4
# ********************************************************************************** # This function merges leftList & rightList together into finalList. These lists are already sorted. def merge(leftList, rightList): finalList = [] # The final list to hold the sorted list, reset to = [] each time this function is called. leftIndex = 0 #index counter for leftList rightIndex = 0 #index counter for rightList # While the index < length of the list, keep appending the listLEFT and listRIGT to the finalList. while leftIndex < len(leftList) and rightIndex < len(rightList): # If leftList[0] <= rightList[0] - append it to finalList if leftList[leftIndex] <= rightList[rightIndex]: # If left index is less than right index finalList.append(leftList[leftIndex]) # Append to finalList leftIndex += 1 #Increment leftIndex by 1 to look at next value in list. else: finalList.append(rightList[rightIndex]) rightIndex += 1 # If there is any remaining values in leftList or rightList - append it to the finalList finalList += leftList[leftIndex:] finalList += rightList[rightIndex:] return finalList # return the list - [1,2,3,4,5,6] # ********************************************************************************** # This function keeps dividing the list in half, until all elements are in 1 list. # This functions does the SORTING. def mergesort(mylist): #THIS IS THE BASE CASE TO STOP THE RECURSIVE CALLS if len(mylist) <= 1: #When the base case is triggered, start returning mylist print 'mylist,', mylist return mylist #Return [1][2][3][4][5][6] else: midIndex = int(len(mylist) / 2) # The midpoint is used to divide the list in half. print 'mergesort for leftList has been called with mylist', mylist[:midIndex] leftList = mergesort(mylist[:midIndex]) # Keep recursively calling the itself (the function), - print 'mergesort for rightList has been called with mylist', mylist[midIndex:] rightList = mergesort(mylist[midIndex:]) # dividing the list in half, until base case (above) is triggered. print '-----------------------------------------------' #print 'midIndex = ', midIndex #print 'leftlist = ', leftList #print 'rightlist = ', rightList #print '----------------------------------' #eventually : left = [1,2,77] right = [9,21,66] #return merge(leftList, rightList) #Pass the left and right elements to the function 'merge' mylist = [1, 2, 3, 4, 5, 6] print mergesort(mylist)
048cc584eda064b0d148fea8d69843bb26051ed1
thalessahd/udemy-tasks
/python/ListaExercicios1/ex5.py
637
4.15625
4
# -*- coding: utf-8 -*- """ Escreva um programa que receba dois números e um sinal, e faça a operação matemática definida pelo sinal. """ print("Digite o primeiro número:") num1 = float(input()) print("Digite o segundo número:") num2 = float(input()) print("Digite o sinal:") sinal = input() if sinal=="+": resu = num1+num2 print(resu) elif sinal=="-": resu = num1-num2 print(resu) elif sinal=="*": resu = num1*num2 print(resu) elif sinal=="/": try: resu = num1/num2 print(resu) except: print("Não é possível divisão por 0.") else: print("Sinal não reconhecido")
c1f7a2b84099c8c382495cd026cdddd258f18c23
peternara/DELF-local-descriptor-train-pytorch
/test.py
326
3.765625
4
a = [i for i in range(10)] def get(a): while True: for i in range(0, 10, 3): try: if i+3 < 10: yield a[i:i+3] else : raise Exception except: break; b = get(a) for i in range(20): print(next(b))
2ee7f50b026d65adf22a95d9a92c4e0d7cf2d94e
Param3103/IMDB-movie-scrapper
/tests/tests.py
1,226
3.625
4
import unittest import csv import re data = [] with open('IMDBmovies.csv', 'r') as file: csv_reader = csv.reader(file) for line in csv_reader: if len(line) != 0: data.append(line) class Testing_Project(unittest.TestCase): #tests if all movies have been deposited into csv file def test_if_deposited(self): for movie in self.movies: for i in movie: movie[movie.index(i)] = re.sub('\n', '', i) movie[0] = movie[0][14:-1] + ')' self.assertIn(movie, data) # test if each movie value is a pair def test_is_pair(self): for movie in data[0: len(data)]: self.assertEqual(len(movie), 2) #tests if movies have been sorted according to rating def test_if_sorted_rating(self): for movie in data[0: len(data) - 1]: self.assertTrue(movie[1] <= data[data.index(movie) + 1][1]) """ def test_if_sorted_name(self): self.assertTrue(data == sorted(data[0]) def test_if_sorted_released_year(self): for movie in data[0: len(data) - 1]: self.assertTrue(movie[1] <= data[data.index(movie) + 1][1]) """ if __name__ == '__main__': unittest.main()
202bd0898352102599f6e4addccaec7a60b46a8f
amymhaddad/exercises_for_programmers_2019
/flask_product_search/products.py
1,454
4.15625
4
import json #convert json file into python object def convert_json_data(file): """Read in the data from a json file and convert it to a Python object""" with open (file, mode='r') as json_object: data = json_object.read() return json.loads(data) #set json data that's now a python object to projects_json products_json = convert_json_data('products.json') #Use the 'products' key from the products_json dictionary to get a LIST of dictionaries products = products_json['products'] def show_all_products(products): """Display all provects from json file""" display_product = '' #cycle through the list of dictionaries for product in products: #cycle through the dicionaries for category, detail in product.items(): if category == "price": detail = f"${product['price']:.2f}" display_product += f"{category.title()}: {detail}" + "\n" return display_product def one_product(products, itemname): """Return a single product based on user input""" inventory_details = '' for product in products: if product['name'] == itemname: for category, detail in product.items(): if category == 'price': detail = f"${product['price']:.2f}" inventory_details += f"{category.title()}: {detail}" + "\n" return inventory_details print(one_product(products, 'Thing'))
8ec2a87f98be3111440db36b81aaa3051064eecb
amymhaddad/exercises_for_programmers_2019
/product_search/user_input.py
184
3.71875
4
"""Get user input for product item to search""" def get_item_name_from_user(): """Get a name of a product from the user""" return input("What is the product name? ").title()
53fc3227a9c2537217e950a2c85dc57f3d812b2f
VladBe1/Learn_Python
/ex2.py
456
4
4
# numbers = ['3','5','7','9', '10.5'] # print(numbers) # numbers.append("Python") # print(len(numbers)) # print(numbers[0]) # print(numbers[-1]) # print(numbers[1:4]) # numbers.remove("Python") # print(numbers) Weather = { "city": "Moscow", "temperature": "20" } Weather['temperature'] = int(Weather['temperature']) - 5 print(Weather) print(Weather.get("country")) Weather.get("country", "Russia") Weather["date"] = "27.05.2019" print(len(Weather))
6d3c6b5362c47d16b3916607be2896033e321e71
disha111/Python_Beginners
/Assignment 3.9/que2.py
552
4.1875
4
import pandas as pd from pandas.core.indexes.base import Index student = { 'name': ['DJ', 'RJ', 'YP'], 'eno': ['19SOECE13021', '18SOECE11001', '19SOECE11011'], 'email': ['dvaghela001@rku.ac.in', 'xyz@email.com', 'pqr@email.com'], 'year':[2019,2018,2019] } df = pd.DataFrame(student,index=[10,23,13]) print("Default DataFrame :\n",df) df.sort_values('eno',inplace=True) print("After Sorting by Values eno in DataFrame :\n",df) df = df.sort_index() print("After Sorting by Index eno in DataFrame :\n",df) print(df.drop(index=df[df['name']=='DJ'].index,axis=0))
a3bb747fcef01e7c5f885a303d4c0055b1337cd0
disha111/Python_Beginners
/Python Quiz Solution/Q46.py
72
3.5
4
import numpy as np ary = np.array([1,2,3,5,8]) ary = ary+1 print(ary[1])
6ef4e9543d7c7c20bdbb1ffa4976b8c3b6e9b0f5
disha111/Python_Beginners
/extra/scope.py
672
4.15625
4
#global variable a = 10 b = 9 c = 11 print("Global Variables A =",a,", B =",b,", C =",c) print("ID of var B :",id(b)) def something(): global a a = 15 b = 5 #local variable globals()['c'] = 16 #changing the global value. x = globals()['b'] print("\nLocal Variables A =",a,", B =",b,", C =",c,", X =",x) print("Inside func the ID of var B :",id(x)) print('In func from global to local var A changed :',a) print('In func local var B :',b) print('In func local var (X) accessing global var B :',x) something() print('Outside the func global var (A) remains Changed :',a) print('Outside the func after changing global var C :',c)
a7455bef1e99b4c247b6cc082dc2889542497607
disha111/Python_Beginners
/chapters/ch 2/july22.py
1,132
3.875
4
import re search = ''' abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 @#$%^&(*((^&))) 123-456-7896 563-658-7566 456*254&2454 ''' print(r"\tRKU")#Row String to print special command like \n \t etc.... a=r"\tabc"#Row String print(a) ########################## REGULAR EXPRATATION ############################# #pattern = re.compile(r'\W') special characters including \n all printed #pattern = re.compile(r'\w')\w is stands for word include digits, capital and small alpha and _ underscore # OR pattern = re.compile(r'\d') \d stands for digits #pattern = re.compile(r'.') . is stand for all characters accepts new line #pattern = re.compile(r'\D')\D is stands for accepts digits all characters are displayed #pattern = re.compile(r'\s') \s its print whitespace #pattern = re.compile(r'\S')# it prints digits , alpha , underscore , non whitespaces #pattern = re.compile(r'abc') #pattern = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') #pattern = re.compile(r'\d{3}-\d{3}-\d{4}') pattern = re.compile(r'\d{3}.\d{3}.\d{4}') matched = pattern.finditer(search) for match in matched: print(match) print(search[1:4]) #uy5mchd
0e15bc4ef67886f7a066341f6487fa450eb3f94b
disha111/Python_Beginners
/Assignment 3.11/HighestValueFind.py
304
3.59375
4
import pandas as pd df = pd.read_csv('ETH.csv') filt1 = df['Date'].str.contains('2019') filt2 = df['Date'].str.contains('2020') print("highest value of column 'Open' for the year 2019 : ",df.loc[filt1,'Open'].max()) print("highest value of column 'Open' for the year 2020 : ",df.loc[filt2,'Open'].max())
190212bfde32271246fa0e383ccf20f2a78330f3
disha111/Python_Beginners
/chapters/ch 1/july15.py
1,430
3.96875
4
############################ PUBLIC PRIVATE AND PROTECTED EXAMPLE ############################################ class student: _name = None _roll = None __college = None myvar = "RKU1" def __init__(self,name,roll,college): self._name = name self._roll = roll self.__college = college @classmethod def change_myvar(cls): cls.myvar = "RK University" print(cls.myvar) def _displayroll(self): print("roll : ",self._roll) def __privatefun(self): print("college : ",self.__college) def accessprivatefun(self): self.__privatefun() class CEIT(student): def __init__(self,name,roll,college): student.__init__(self,name,roll,college) def display(self): """self._name = "Disha"#variable of the CEIT class self._roll = "19SOECE13021"#variable of the CEIT class self.__college = "RK"#variable of the CEIT class""" print(self._name,"\n",self._roll) #print(self.__college) variable of the CEIT class self._displayroll() #self.__privatefun() Private method of parent class self.accessprivatefun() obj = CEIT('test','12','RKU') obj.display() s1 = student("name",123,"RKU") student.change_myvar() # 1. Normal method or instant method # 2. class Method # is used for changing the state of class->class variables # 3. static method # independent method ->
e4dde5c7d3495bf7adcaf74b9701cb69042c4d6b
disha111/Python_Beginners
/Assignment 1.2/A1.4.py
202
4
4
def showNumbers(limit): for i in range(0,limit+1): if(i%2 == 0): print(i,"EVEN") else: print(i,"ODD") limit = int(input("Enter Limit : ")) showNumbers(limit)
c69e79ced4ab46520eb7e2851edfb53343863015
disha111/Python_Beginners
/Assignment 3.1/que2.py
243
3.953125
4
import numpy as np ls =[] print("Enter Element in Matrix : ") for i in range(0,9): ls.append(int(input())) def display(ls): array = np.array(ls).reshape(3,3) #two-dimensional NumPy array. return array dim = display(ls) print(dim)
a1d9f3efbfe2da86945024de8c87acf6fba5a61b
tonnekarlos/aula-pec-2021
/Semana-5-Ex02-Q01-runcodes.py
416
3.65625
4
def main(): nome = input('') estado_civil = int(input('')) n1 = [] n2 = [] if estado_civil == 2: n1.append(nome) for i in n1: print(len(i)) elif estado_civil == 1: nome2 = input('') n1.append(nome) n2.append(nome2) for i in n1: for w in n2: print(len(i) + len(w)) if __name__ == '__main__': main()
5e5be5dc017ed6d0837d9eb608ac812fcdeebbd5
tonnekarlos/aula-pec-2021
/Semana-5-Ex02-Q03.py
705
3.734375
4
def verifica_numero(n): d = n // 10 u = n % 10 return d, u def main(): # Entrada de dados n = int(input('digite um número entre 10 e 99: ').strip()) # Processamento x = 0 d, u = verifica_numero(n) if 10 <= n <= 99: if d % 2 != 0: x += 1 if u % 2 != 0: x += 1 if d % 2 == 0: x += 0 if u % 2 == 0: x += 0 # Saída de dados if x == 0: print(f'Nenhum dígito é ímpar.') elif x == 1: print(f'Apenas um dígito é ímpar.') elif x == 2: print(f'Os dois dígitos são ímpares.') if __name__ == '__main__': main()
2cfc741cea7bec22ae64cd7b8194636eacedbaeb
tonnekarlos/aula-pec-2021
/Semana-5-Ex01-Q04-runcodes.py
724
3.71875
4
def media(n1, n2, n3, n4, n5): return(n1+n2+n3+n4+n5) / 5 def main(): n1 = float(input("".strip())) n2 = float(input("".strip())) n3 = float(input("".strip())) n4 = float(input("".strip())) n5 = float(input("".strip())) maior = [] if n1 > media(n1, n2, n3, n4, n5): maior.append(n1) if n2 > media(n1, n2, n3, n4, n5): maior.append(n2) if n3 > media(n1, n2, n3, n4, n5): maior.append(n3) if n4 > media(n1, n2, n3, n4, n5): maior.append(n4) if n5 > media(n1, n2, n3, n4, n5): maior.append(n5) print(f'{media(n1,n2,n3,n4,n5):.2f}') for item in maior: print('{:.2f}'.format(item)) if __name__ == '__main__': main()
e323a0fe8e50ad7df9ecf1ce4ffe5ccd5aa5aa9b
tonnekarlos/aula-pec-2021
/T1-Ex04.py
249
4.28125
4
def verifica(caractere): # ord retorna um número inteiro representa o código Unicode desse caractere. digito = ord(caractere) # 0 é 48 e 9 é 57 return 48 <= digito <= 57 print(verifica(input("Digite um caractere: ".strip())))
574b931268a7d7cdf6dd172bfa85068bc6c4364b
sesorov/phonebook_lab
/main.py
1,488
3.796875
4
import sys from interface import BookInterface from additional import Text, GColor PhoneBook = BookInterface() GREEN = GColor.RGB(15, 155, 43) def main_menu(): print(GREEN + Text.BOLD + '*' * 18 + " MAIN MENU " + '*' * 18 + Text.END) print("Please, select an action by choosing its index.\nOperations:") print("[1] Add a new record to a phone book") print("[2] Edit an existing record in a phone book") print("[3] Delete a record from a phone book") print("[4] Show people whose birthday is the next") print("[5] View the whole book") print("[6] View person's age") print("[7] View people older/younger than N years") print("[8] Search") print("[9] Quit") user_input = input("Please, enter the number: ") while user_input not in "123456789": user_input = input(Text.RED + "Please, select a valid number: " + Text.END) if user_input == '1': PhoneBook.add_note() elif user_input == '2': PhoneBook.edit_note() elif user_input == '3': PhoneBook.del_note() elif user_input == '4': PhoneBook.get_closest_birthday() elif user_input == '5': PhoneBook.view_all() elif user_input == '6': PhoneBook.view_age() elif user_input == '7': PhoneBook.view_people_aged() elif user_input == '8': PhoneBook.search_notes() elif user_input == '9': print(GREEN + "See you later!" + Text.END) sys.exit() while True: main_menu()
358cfe68d16aeb8794f21c5e60acfe334f0d6436
svmeehan/FuelEfficiencyCalc
/testSuite.py
614
3.53125
4
import unittest from DistanceTable import * class TestDistanceTable(unittest.TestCase): def test_not_a_valid_file(self): '''Test to make sure an IOError is raised for an invalid file name''' with self.assertRaises(FileNotFoundError): DistanceTable.readCSV(self, 'does-not-exist.csv') #self.assertRaises(IOError, DistanceTable.readCSV, 'does-not-exist.csv') def test_get_a_saved_distance(self): # self.assertEquals() pass def test_get_a_distance_not_yet_calculated(self): pass def test_add_a_new_value_to_table(self): pass #def test_save_ if __name__ == '__main__': unittest.main()
a2a4b44f5e4c0ec04d8ede72e715936ea6aefc1c
dpudovkin84/py-study
/tests/TestExcept_2.py
293
3.890625
4
while True: a=input('Enter number a:') b=input('Enter number b:') try: result= int(a)/int(b) except ZeroDivisionError: print("Zerro division") except ValueError: print("Not a digit") else: print('Square Resutl:',result**2) break
35fa9f1acf78fe291cb15f6c46203cd6768bbc3b
DS-ALGO-S30/Two-Pointers-2
/1_removeDuplicates.py
971
3.671875
4
def solution(nums): ''' Approach: 1. using 3 pointers, slow pointer indicates all values before it are traversed. 2. fast pointer quickly moves to new values and prev=fast and slow moves one step and fast moves to nex and flag=0 3. if flag ==0 then only move make nums[slow]=nums[fast] 4. slow pointer will keep record of the desired lenght. time complexity = O(n) space complexity = O(1) Working on LC= yes ''' prev=0 slow=1 fast=1 flag=0 while(fast<len(nums)): if nums[fast] == nums[prev]: if flag == 0: nums[slow] = nums[fast] slow += 1 fast += 1 flag += 1 else: fast +=1 else: prev=fast nums[slow]=nums[fast] slow += 1 fast +=1 flag = 0 return slow nums=[1,1,1,1,1,1,1,1,1,1,2,2,2,2,3,5,6,6,6] solution(nums) print(nums)
bfe570477d001c7cb5b7e2e9e1e1aa8522e8db47
shubhamrocks888/python_oops
/Polymorphism.py
3,348
4.625
5
## Polymorphism in Python '''Example of inbuilt polymorphic functions :''' # len() being used for a string print(len("geeks")) # len() being used for a list print(len([10, 20, 30])) '''Examples of used defined polymorphic functions :''' def add(x, y, z = 0): return x+y+z print(add(2, 3)) print(add(2, 3, 4)) ## Polymorphism with Inheritance In Python, Polymorphism lets us define methods in the child class that have the same name as the methods in the parent class. In inheritance, the child class inherits the methods from the parent class. However, it is possible to modify a method in a child class that it has inherited from the parent class. This is particularly useful in cases where the method inherited from the parent class doesn’t quite fit the child class. In such cases, we re-implement the method in the child class. This process of re-implementing a method in the child class is known as Method Overriding. class Bird: def intro(self): print("There are many types of birds.") def flight(self): print("Most of the birds can fly but some cannot.") class sparrow(Bird): def flight(self): print("Sparrows can fly.") class ostrich(Bird): def flight(self): print("Ostriches cannot fly.") obj_bird = Bird() obj_spr = sparrow() obj_ost = ostrich() obj_bird.intro() obj_bird.flight() obj_spr.intro() obj_spr.flight() obj_ost.intro() obj_ost.flight() #Output: There are many types of birds. Most of the birds can fly but some cannot. There are many types of birds. Sparrows can fly. There are many types of birds. Ostriches cannot fly. ## Polymorphism with a Function and objects: It is also possible to create a function that can take any object, allowing for polymorphism. In this example, let’s create a function called “func()” which will take an object which we will name “obj”. Though we are using the name ‘obj’, any instantiated object will be able to be called into this function. Next, lets give the function something to do that uses the ‘obj’ object we passed to it. In this case lets call the three methods, viz., capital(), language() and type(), each of which is defined in the two classes ‘India’ and ‘USA’. Next, let’s create instantiations of both the ‘India’ and ‘USA’ classes if we don’t have them already. With those, we can call their action using the same func() function: '''Code : Implementing Polymorphism with a Function''' class India(): def capital(self): print("New Delhi is the capital of India.") def language(self): print("Hindi is the most widely spoken language of India.") def type(self): print("India is a developing country.") class USA(): def capital(self): print("Washington, D.C. is the capital of USA.") def language(self): print("English is the primary language of USA.") def type(self): print("USA is a developed country.") def func(obj): obj.capital() obj.language() obj.type() obj_ind = India() obj_usa = USA() func(obj_ind) func(obj_usa) #Output: New Delhi is the capital of India. Hindi is the most widely spoken language of India. India is a developing country. Washington, D.C. is the capital of USA. English is the primary language of USA. USA is a developed country.
6a225c527bf763828225ead494d4beaa3aebfcad
Smirt1/Clase-Python-Abril
/Funciones.py
609
3.78125
4
# suma = 7 + 8 + 9 # media = suma / 3 # print ("La puntuacion de la clase es: ", media) # def puntuacion (alum1, alum2, alum3): # suma = alum1 + alum2 + alum3 # return suma / 3 # media = puntuacion(7,8,9) # print ("La puntuacion de esta clase es: ", media) # media = puntuacion(10,15,9) # print ("La puntuacion de esta clase es: ", media) def puntuacion (clase): return sum (clase) / len (clase) clase = [7, 8, 9] media = puntuacion (clase) print ("La puntuacion de esta clase es: ", media) clase = [5, 6, 7.5, 10] media = puntuacion(clase) print ("La puntuacion de esta clase es: ", media)
42fab2e2b67d33b344ee1e19fdc2ce537f62f195
Smirt1/Clase-Python-Abril
/Tarea1.py
2,008
4.0625
4
#Escriba en pantalla el tipo de dato que retorna la expresión 4 < 2: # print (4 < 2) #Almacene en una variable el nombre de una persona y al final muestre en la consola el me nsaje: “Bienvenido [nombrePersona]” # usuario = input("Escriba el nombre del usuario: ") # print ("Bienvenido : " + usuario) #Evalúe si un número es par o impar y muestre en la consola el mensaje. # numero = int (input("Escriba el numero: ")) # print (numero % 2) #Almacene dos números y evalúe si el primero es mayor que el segundo. El resultado debe verse en la consola. # numero_a = 2 # numero_b = 4 # resultado = (numero_a > numero_b) # print (resultado) #Convierta dólares a pesos. # cantidad_dolares = 89.75 # tasa = 58.50 # print (cantidad_dolares * tasa) # Convierta grados celsius a Fahrenheit # grados_celcius = int(input ( "Intruzca la temperatura a convertir: ")) # print (grados_celcius * 1.8 + 32) # Almacene cuatro notas 90,95,77, 92 y las promedie. Al final debe decir su calificación en letras A, B,C,D, E ó F. # nota_1 = 90 # nota_2 = 95 # nota_3 = 77 # nota_4 = 92 # promedio = (nota_1 + nota_2 + nota_3 + nota_4) / 4 # print (promedio) # if promedio >= 90 and promedio <= 100: # print("Su nota es A") # elif promedio >= 80 and promedio <= 89: # print ("Su nota es B") # elif promedio >= 70 and promedio <= 79: # print("Su nota es C") # elif promedio >= 60 and promedio <= 69: # print("Su nota es D") # elif promedio >= 50 and promedio <= 59: # print("Su nota es E") # else: # print("Su nota es F") #Que almacene monto, cantidad de cuotas, y porcentaje de interés anual de un préstamo y calcule la cuota mensual. (Amortizar mediante el sistema francés) R = 0 prestamo = float (input ("Ingrese el valor del prestamo: ")) interes = float (input ("Ingrese la tasa solicitada:")) cuotas = int(input ("Ingrese el tiempo a pagar:")) R = prestamo * ((interes * (1 + interes) * cuotas) / ((1 + interes) * cuotas -1)) print ("El valor de la cuota es: %.2f" %R)
9c0cd7be7ad5ad32f43d66d7ccceb2ddfe673a12
Smirt1/Clase-Python-Abril
/IfElifElse.py
611
4.15625
4
#if elif else tienes_llave = input ("Tienes una llave?: ") if tienes_llave == "si": forma = input ("Que forma tiene la llave?: ") color = input ("Que color tiene la llave?: ") if tienes_llave != "si": print ("Si no tienes llaves no entras") if forma == "cuadrada" and color =="roja": print ("Puedes pasar por la Puerta 1") elif forma == "redonda" and color =="amarilla": print ("Puedes pasar por la Puerta 2") elif forma == "triangular" and color == "roja": print ("Puedes pasar por la Puerta 2") else: print ("Tienes la llave equivocada")
cda697bb9039180d04863b553d60092dd24a2f6b
Georgie88/Python-Challenge
/1. PyBank/main.py
3,399
4.1875
4
#dependencies import csv #set file name file_name = 'budget_data_1.csv' #open a file with open(file_name, newline='') as csvfile: #read the file with csv budget_data = csv.reader(csvfile, delimiter=',') #skip the header row next(budget_data) #setting up the variables for the number of months, total revenue, average, greatest increase and decrease Total_Months = 0 Total_Revenue = 0 Revenue_Change = 0 Total_Revenue_Change = 0 Prev_Month_Revenue = 0 Gretest_Revenue_Increase = 0 Greatest_Revenue_IncMonth = "Date1" Gretest_Revenue_Decrease = 0 Greatest_Revenue_DecMonth = "Date2" #looping through each row in the table for row in budget_data: #calculating the total months by incrementing the row count Total_Months += 1 #calculate total revenue Total_Revenue += int(row[1]) #excluding the first month as there will be no revenue change if Prev_Month_Revenue != 0: #calculate revenue change for current month Revenue_Change = int(row[1])-Prev_Month_Revenue #calculate total revenue change Total_Revenue_Change = Total_Revenue_Change + abs(Revenue_Change) #comparing the current change in value to the previous greatest increase in revenue if Revenue_Change > Gretest_Revenue_Increase: #update the greatest increase in revenue to current month Gretest_Revenue_Increase = Revenue_Change Gretest_Revenue_IncMonth = row[0] #comparing the current change in value to the previous greatest decrease in revenue if Revenue_Change < Gretest_Revenue_Decrease: #update the greatest decrease in revenue to current month Gretest_Revenue_Decrease = Revenue_Change Gretest_Revenue_DecMonth = row[0] #assigning the value of current revenue to the variable for using it as previous revenue Prev_Month_Revenue=int(row[1]) #calculating the average revenue change Average_Revenue_Change = round(Total_Revenue_Change/Total_Months,2) #print to terminal all the solution print("Financial Analysis" + '\n' + "-------------------------" + '\n' + "Total Months: " + str(Total_Months) + '\n' + "Total Revenue: $" + str(Total_Revenue) + '\n' + "Average Revenue Change: $" + str(Average_Revenue_Change) + '\n' + "Greatest Increase in Revenue: " + Gretest_Revenue_IncMonth + ", $" + str(Gretest_Revenue_Increase) + '\n' + "Greatest Decrease in Revenue: " + Gretest_Revenue_DecMonth + ", $" + str(Gretest_Revenue_Decrease)) #create output file with open('Results_Budget_1.txt', 'w') as results_2: #creating the output results_2.write("Financial Analysis" + '\n' + "-------------------------" + '\n' + "Total Months: " + str(Total_Months) + '\n' + "Total Revenue: $" + str(Total_Revenue) + '\n' + "Average Revenue Change: $" + str(Average_Revenue_Change) + '\n' + "Greatest Increase in Revenue: " + Gretest_Revenue_IncMonth + ", $" + str(Gretest_Revenue_Increase) + '\n' + "Greatest Decrease in Revenue: " + Gretest_Revenue_DecMonth + ", $" + str(Gretest_Revenue_Decrease))
cb3eda57daa9030fb7d3f4ca6bd842fd06d7033c
yzy1995215/Python
/本科科研/8-03/问题2.py
1,625
4
4
""" 定义一个列表的操作类:Listinfo 包括的方法: 1 列表元素添加: add_key(keyname) [keyname:字符串或者整数类型] 2 列表元素取值:get_key(num) [num:整数类型] 3 列表合并:update_list(list) [list:列表类型] 4 删除并且返回最后一个元素:del_key() """ class Listinfo(object): # 列表操作类 def __init__(self,list1): self.list = list1 def add_key(self,keyname): # 列表元素添加: add_key(keyname) [keyname:字符串或者整数类型] if isinstance(keyname, (str, int)): self.list.append(keyname) return self.list else: return 'Element is not str or int.' def get_key(self,num): # 列表元素取值:get_key(num) [num:整数类型] if num >= 0 and num < len(self.list): return self.list[num] elif num < 0 and num > -len(self.list)-1: return self.list[num] else: return 'Index is out of range.' def update_list(self,list2): # 列表合并:update_list(list) [list:列表类型] self.list.extend(list2) return self.list def del_key(self): # 删除并且返回最后一个元素:del_key() if len(self.list) > 0: return self.list.pop(-1) else: return 'There is no element in Listinfo.' if __name__ == '__main__': list_info = Listinfo([44, 222, 111, 333, 454, 'sss', '333']) print(list_info.add_key('1111')) print(list_info.get_key(4)) print(list_info.update_list(['1', '2', '3'])) print(list_info.del_key())
5ef3862b7db12c4010253c4b76cc7913dcac190b
yzy1995215/Python
/本科科研/7-13/问题1.py
273
3.5625
4
""" 编写一个函数,调用函数返回四位不含0的随机数. """ import random def random_number(figure): num = 0 for i in range(1,figure+1): num = num*10 + random.randint(1,9) return num if __name__ == '__main__': print(random_number(4))
f7561710a33183178c180fc6809c4bbf49df4a37
aldwinhs/Tubes-Daspro
/F07.py
3,067
3.65625
4
# KAMUS # id_ubah : string # ketemu : boolean # nama : integer # jumlah : integer # banyakubah : integer def ubahjumlah(datas2, datas3): # F07-Mengubah Jumlah Gadget atau Consumable pada Inventory ketemu = False while not(ketemu): id_ubah= input("Masukan ID: ") ID = 0 nama = 1 jumlah = 3 if id_ubah[0] == "G" or id_ubah[0] == "C": # Mengecek apakah item gadget atau consumable if id_ubah[0] == "G": for i in range(len(datas2)): if (str(datas2[i][ID])) == id_ubah: ketemu = True cukup = False while not(cukup): banyakubah = int(input("Masukkan Jumlah: ")) if banyakubah < 0: if (datas2[i][jumlah] + banyakubah) < 0: print(-banyakubah, datas2[i][nama], "gagal dibuang karena stok kurang. Stok sekarang:", datas2[i][jumlah], "(< "+ str(banyakubah) +")") else: cukup = True datas2[i][jumlah] = datas2[i][jumlah] + banyakubah print(-banyakubah, datas2[i][nama], "berhasil dibuang. Stok sekarang:", datas2[i][jumlah]) else: #banyakubah >= 0 cukup = True datas2[i][jumlah] = datas2[i][jumlah] + banyakubah print(banyakubah, datas2[i][nama], "berhasil ditambahkan. Stok sekarang:", datas2[i][jumlah]) if not(ketemu): print("Tidak ada item dengan ID tersebut") else: # id_ubah == "C" for i in range(len(datas3)): if (str(datas3[i][ID])) == id_ubah: ketemu = True cukup = False while not(cukup): banyakubah = int(input("Masukkan Jumlah: ")) if banyakubah < 0: if (datas3[i][jumlah] + banyakubah) < 0: print(-banyakubah, datas3[i][nama], "gagal dibuang karena stok kurang. Stok sekarang:", datas3[i][jumlah], "(< "+ str(banyakubah) +")") else: cukup = True datas3[i][jumlah] = datas3[i][jumlah] + banyakubah print(-banyakubah, datas3[i][nama], "berhasil dibuang. Stok sekarang:", datas3[i][jumlah]) else: #banyakubah >= 0 cukup = True datas3[i][jumlah] = datas3[i][jumlah] + banyakubah print(banyakubah, datas3[i][nama], "berhasil ditambahkan. Stok sekarang:", datas3[i][jumlah]) if not(ketemu): print("Tidak ada item dengan ID tersebut") else: print("Tidak ada item dengan ID tersebut") return [datas2, datas3]
d3aec4132ad1f894861652559d9f1ab936bfb6d8
LakshayLakhani/my_learnings
/programs/arrays/left_rotate.py
1,388
3.859375
4
# arr = [1,2,3,4,5] # op = [2,3,4,5,1] # # first = arr[0] # for i in range(len(arr)-1): # arr[i] = arr[i+1] # # arr[-1]=first # # print(arr) # O(nd) -> # arr = [1,2,3,4,5] # # d = 3 # # for i in range(d): # first = arr[0] # for i in range(len(arr)-1): # arr[i] = arr[i+1] # # arr[-1]=first # # print(arr) # # arr = [1, 2, 3, 4, 5] # op = [4, 5, 1, 2, 3] #for 3 # # op = [5, 1, 2, 3, 4] #for 4 # # d = 4 # diff = len(arr) - d # len_arr = len(arr) # # a = [] # # # for i in range(diff): # # a.append(arr[i]) # # for i in arr[-diff:]: # a.append(i) # # for i in range(d): # a.append(arr[i]) # # print(a) #for 3 # O(n) -> time #O(1) -> space # op = [4, 5, 1, 2, 3] #for 3 # # rev_arr = [5,4,3,2,1] # # reverse -> full array # reverse -> (length - d) array # reverse -> left 4 array op = [5, 1, 2, 3, 4] d = 3 # reverse full array - [5,4,3,2,1] # reverse length - d array - [5, 4,3,2,1] # reverse left d arrays - [5, 1,2,3,4] arr = [1,2,3,4,5] def reverse(arr): i = 0 b = len(arr)-1 while i < b: arr[i], arr[b] = arr[b], arr[i] i += 1 b -= 1 return arr # op = [4, 5, 1, 2, 3] #for 3 def rotate_by_d(arr, d): arr = reverse(arr) arr = reverse(arr[:len(arr)-d]) + arr[len(arr)-d:] arr = arr[:len(arr)-d] + reverse(arr[len(arr)-d:]) return arr print(rotate_by_d(arr, d))
ab06ae955363b0ac7fcdfd22f35e9ea6e698d5c3
LakshayLakhani/my_learnings
/programs/binary_search/bs1.py
484
4.125
4
# given a sorted arrray with repititions, find left most index of an element. arr = [2, 3, 3, 3, 3] l = 0 h = len(arr) search = 3 def binary_search(arr, l, h, search): mid = l+h//2 if search == arr[mid] and (mid == 0 or arr[mid-1] != search): return mid elif search <= arr[mid]: return binary_search(arr, l, mid, search) # else search > arr[mid]: else: return binary_search(arr, mid, h, search) print(binary_search(arr, l, h, search))
5857c3f71274a55944187eef5781c0c459ed4db4
LakshayLakhani/my_learnings
/programs/palindrom.py
253
3.9375
4
#recursive way string = "l" l = 0 r = len(string)-1 def check_palindrom(l, r, string): if string[r] != string[l]: return False if l < r: check_palindrom(l+1, r-1, string) return True print(check_palindrom(l, r, string))
e528e6c095c2116ca53d99c34109cc5d09ff56a0
luphord/imgwrench
/imgwrench/commands/frame.py
1,165
3.546875
4
"""Put a monocolor frame around images.""" import click from PIL import Image from ..param import COLOR def frame(image, width, color): """Put a monocolor frame around images.""" frame_pixels = round(width * max(image.size)) new_size = (image.size[0] + 2 * frame_pixels, image.size[1] + 2 * frame_pixels) framed_image = Image.new("RGB", new_size, color) framed_image.paste(image, (frame_pixels, frame_pixels)) return framed_image @click.command(name="frame") @click.option( "-w", "--frame-width", type=click.FLOAT, default=0.025, show_default=True, help="width of the frame as a fraction of the longer " + "image side", ) @click.option( "-c", "--color", type=COLOR, default="white", show_default=True, help="color of the frame as a color name, hex value " + "or in rgb(...) function form", ) def cli_frame(frame_width, color): """Put a monocolor frame around images.""" click.echo("Initializing frame with parameters {}".format(locals())) def _frame(images): for info, image in images: yield info, frame(image, frame_width, color) return _frame
7b3649f5efa47990921e1447c9f1ab3755d9a3a0
dolefeast/Simulation_Intro
/failed/freefall_euler.py
877
3.5
4
import numpy as np import matplotlib.pyplot as plt #Physical variables F = 600 #G * M, abreviated. #Position r0 = 4#Starting distance r_y = r0 #Updatable starting distance r_x = 0 #Horizontal position r_t = r_y - 35 #Earth's radius r = np.array([r_x, r0]) r_norm = np.linalg.norm(r) #Speed v_x = 7 #Horizontal speed v_y = -2 #Inicial speed v = np.array([v_x, v_y]) mu = 0.0 #Air ressistance coefficient dt = 0.01 #Time step plt.axis([-r_norm, r_norm, -r_norm, r_norm]) def get_g(r, F = F): return -F * np.linalg.norm(r)**-3 * r def get_air_ressistance(v, mu=mu): return mu * v def get_acceleration(r, v, F=F): return get_g(r) - get_air_ressistance(v) def main(r = r, v = v): while True: acc = get_acceleration(r, v) v = v + acc * dt r = r + v * dt plt.scatter(r[0], r[1], s = 1) plt.pause(0.05) main() plt.show()
03354fb7eafde52270044aeb96d7b9735907652a
kylesadler/Zn-Polynomial-Factorizer
/factorizer.py
3,792
3.671875
4
from itertools import product from pprint import pformat import sys def main(): coefficients = [1,4,3,0,1,2] run(*coefficients) def run(*coefficients): for p in [2,3,5]: print(f'\n{p}:\n') results = factor(p, coefficients) for result in results: print(list(result[0]), list(result[1])) # def factor(coefficients, mod_coefficients): # TODO make this work with arbitrary ideal mods def factor(p, coefficients): """ coefficients is a list of numbers p is a prime integer (also works with non-primes, just saying) """ coefficients = mod(coefficients, p) degree = get_degree(coefficients) target = polynomial(coefficients) seen = {} possible = [] # loop over polynomials for coef1 in product(*[range(p)]*(degree+1)): coef1 = remove_leading_zeros(coef1) degree1 = get_degree(coef1) if degree1 < 1 or degree1 == degree: continue # if coef1 in seen: # continue # else: # seen[coef1] = 1 # print(degree1) # print(coef1, end=" ") for coef2 in product(*[range(p)]*(degree - degree1+1)): if coef2[0] == 0: continue product_ = multiply(coef1, coef2, p) # print(coef1, coef2, product, coefficients) assert len(coefficients) == len(product_) if coefficients == product_: possible.append((coef1, coef2)) # seen[coef2] = 1 return [ x for x in possible if is_monic(x[0]) and is_monic(x[1]) ] def polynomial(*args): """ args is list of coefficients corresponding to powers (n, ..., 0) or just the numbers (not a list) returns function of polynomial """ if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)): args = args[0] def p(x): output = 0 power = 1 for arg in args[::-1]: output += arg * power power *= x return output return p def multiply(coef1, coef2, p): """ multiplies two sets of coefficients and mods the result by p """ output = [0]*(len(coef1)+len(coef2)-1) for i, a in enumerate(coef1[::-1]): for j, b in enumerate(coef2[::-1]): output[len(output) - i - j - 1] += a*b return mod(output, p) # utility functions def remove_leading_zeros(coefficients): first_non_zero = next((x for x in coefficients if x != 0), None) if first_non_zero == None: return [0] return coefficients[coefficients.index(first_non_zero):] def get_degree(coefficients): """ returns degree of polynomial with given coefficients ex: (1,2,3) are the coefficients of x^2 + 2x + 3 which has degree 2 """ return len(remove_leading_zeros(coefficients)) - 1 def mod(coefficients, n): """ mod coefficients by n """ return remove_leading_zeros([x % n for x in coefficients]) def is_monic(coefficients): return coefficients[0] == 1 def get_matricies(): n = int(sys.argv[1]) for row1 in product(*[range(n)]*3): for row2 in product(*[range(n)]*3): for row3 in product(*[range(n)]*3): matrix = [row1, row2, row3] # print(matrix) det = det3x3(matrix) if det in [2,5]: print(det, pformat(matrix)) def det3x3(m): # m is a matrix return m[0][0] * det2x2(m[1][1], m[1][2], m[2][1], m[2][2]) \ - m[0][1] * det2x2(m[1][0], m[1][2], m[2][0], m[2][2]) \ + m[0][2] * det2x2(m[1][0], m[1][1], m[2][0], m[2][1]) def det2x2(a,b,c,d): return a*d-b*c if __name__ == "__main__": # main() get_matricies()
cca327c9bb2b6f5bcaaeaf09b09c80b07fe15e32
younes-m/Utilitary-Python-Scripts
/spaces_to_under.py
993
3.671875
4
import sys import os """ replaces the spaces in file names by underscores ('_') works with any number of files/folders dragged and dropped on the script""" def newname(path): #returns the path with spaces in the file name replaced with '_' if spaces in the file name, else false output = path.split('\\') output[-1] = output[-1].replace(' ', '_') if ' ' in output[-1] else False return '\\'.join(output) if output[-1] else False r = n = 0 i = 1 while True : try : if newname(sys.argv[i]) : os.rename(sys.argv[i], newname(sys.argv[i])) print ('{0} -> {1}'.format(sys.argv[i].split('\\')[-1], newname(sys.argv[i]).split('\\')[-1])) r += 1 else : print('{0} -> Not renamed'.format(sys.argv[i].split('\\')[-1])) n += 1 i += 1 except IndexError : break input('\ndone, {0} file(s) renamed, {1} file(s) ignored, press enter to close program'.format(r,n))
72a911716ddb5155762d944e69c8ca518297d68b
SAmelekhin/algorithms-1
/search_in_broken_array.py
768
3.75
4
from typing import Any, List, Tuple, Union def broken_search(elements: Union[List[Any], Tuple[Any]], target: Any) -> Any: left, right = 0, len(elements) - 1 while left <= right: mid = (left + right) // 2 if target == elements[mid]: return mid if elements[mid] <= elements[right]: if elements[mid] < target <= elements[right]: left = mid + 1 else: right = mid - 1 else: if elements[left] <= target < elements[mid]: right = mid - 1 else: left = mid + 1 return -1 if __name__ == '__main__': def test(): arr = [19, 21, 100, 101, 1, 4, 5, 7, 12] assert broken_search(arr, 5) == 6
52624832b010752d12893ac8b7044e6ac1c0bad9
chenp0088/git
/cars_4.py
91
3.671875
4
#!/usr/bin/python3 # coding=utf-8 cars = ['bmw','audi','toyota','subaru'] print(len(cars))
99f8aed5acd78c31b9885eba4b830807459383be
chenp0088/git
/number.py
288
4.375
4
#!/usr/bin/env python # coding=utf-8 number = input("If you input a number ,I will tell you if the number is multiplier of ten! Please input the number: ") number = int(number) if number%10 == 0: print("It`s the multiplier of ten!") else: print("It`s not the multiplier of ten!")
2c72bc803695eda04d7faeecfbb8830c3353e23e
chenp0088/git
/age.py
272
4
4
age=40 if age<2: print("He is a baby.") elif 2<=age<4: print("He is a child.") elif 4<=age<13: print("He is a children.") elif 13<=age<20: print("He is a teenager.") elif 20<=age<65: print("He is an adult. ") elif age>65: print("He is an old man")
05ec60a24844022ebc0b28c9b17c13c7b4d2487f
chenp0088/git
/users.py
258
3.734375
4
users=['admin','root','peter','psla','seare'] for user in users: print("Hello "+user+'.') if user=='admin': print("Hello "+user+','"would you like to see a status report?") else: print("Hello Eric,thank you for logging in again")
f2970ec63018d4b56a8a71fe495e726ad5f09bfd
chenp0088/git
/p99-6-11.py
610
3.71875
4
#!/usr/bin/env python # coding=utf-8 cities={ 'taizhou':{ 'country':'china', 'population':'1000 million', 'fact':'水乡,好吃的多', }, 'dongjin':{ 'country':'japan', 'population':'20000 million', 'fact':'鬼子多', }, 'new york':{ 'country':'america', 'population':'90000 million', 'fact':'洋妞多' }, } for city,cities_info in cities.items(): print("\nCitiesname: "+city) print ("\nCountry:"+cities_info['country'].title()+"\nPopulation:"+cities_info['population']+"\nFact:"+cities_info['fact'])
d4ecd2f89f348afd4823274945057ace57de464c
chenp0088/git
/cars_5.py
175
4.03125
4
#!/usr/bin/python3 # coding=utf-8 cars = ['bmw','audi','toyota','subaru'] for car in cars: if car =='bmw': print(car.upper()) else: print(car.title())
3de21f3820b9d9ea0fe8b02b7c7b6893b63ebddb
margomalfait/Informatica5
/07b-Iteraties-While-lus/Blackjack.py
373
3.609375
4
# invoer kaart = int(input('kaart is: ')) totaal = 0 # berekening while totaal < 21 and kaart > 0: totaal += kaart if totaal < 21: kaart = int(input('kaart is: ')) if totaal > 21: antw = 'Verbrand ({})'.format(totaal) if totaal == 21: antw = 'Gewonnen!' if kaart == 0: antw = 'Voorzichtig gespeeld ({})'.format(totaal) # uitvoer print(antw)
a887131116e866ff21d8711061fee32e7117ea97
margomalfait/Informatica5
/Toets/IrrationaleFuncties.py
230
3.796875
4
from math import sqrt # invoer a = float(input('Geef x: ')) # berekening if a < 2: if x == 2: mes = '{:.2f} ∉ dom(f)'.format(a) else: mes = '' elif x < 2: mes = 'x ∉ dom(f)' # uitvoer print(mes)
dd318131a8b9d8e68380bf13ce9a02d0c4b6784f
shashankgupta12/valuefy
/scraper/valuefy.py
884
3.734375
4
# valuefy/valuefy.py URL = 'https://medium.com/' def write_to_file(file_name, url): """This function writes the received url to the received file name.""" with open(file_name, 'a') as myfile: myfile.write('{}\n'.format(url)) def format_internal_url(url): """This function formats an internal path to a valid URL.""" url = url.split('"')[-2] if not url.startswith('https:'): url = ( 'https://medium.com{}'.format(url) if not url.startswith('//medium.com') else 'https:{}'.format(url)) return url def extract_page_html(url): """This function makes a request to the passed url and extracts its html.""" from urllib.request import Request, urlopen request_headers = {'User-Agent': 'Mozilla/5.0'} req = Request(url, headers=request_headers) page = urlopen(req).read() return page
2e64de10c2dc00984708a0e917423883ecb26bad
kulshrestha97/PythonPractice
/gradingstudent.py
322
3.65625
4
n = int(raw_input()) marks = [] newmarks = [] for i in xrange(0,n): m = int(raw_input()) marks.append(m) for i in marks: a = i//5 multiple = (a+1)*5 if ((multiple - i)<3 and i>=38): newmarks.append(multiple) else: newmarks.append(i) print "\n".join(map(str,newmarks))
89454ce7d16599c6e309ea06df4fb4f4d7eb02c6
franloza/hackerrank
/hash_maps/ransom_note.py
822
3.5625
4
#!/bin/python3 import os from collections import Counter # Complete the checkMagazine function below. def checkMagazine(magazine, note): c = Counter(magazine.split(' ')) for word in note.split(' '): count = c.get(word, 0) if count == 0: return "No" else: c[word] -= 1 return "Yes" # Read from input if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') mn = input().split() m = int(mn[0]) n = int(mn[1]) magazine = input().rstrip() note = input().rstrip() res = checkMagazine(magazine, note) fptr.write(str(res) + '\n') fptr.close() # Toy case if __name__ == '__main__': magazine = "give me one grand today night" note = "give one grand today" print(checkMagazine(magazine, note)) # Yes
a89a3d8ea0047d3445add9e48c2d77f7458268b2
marcellinamichie291/crypto_simulator
/strategy/moving_average_double.py
939
3.515625
4
import numpy as np class MovingAverageDoubleStrategy: """ Double moving average strategy. """ def __init__(self, period_1=9, period_2=21, trade_fee=0): if period_1 > period_2: self.period_max = period_1 self.period_min = period_2 else: self.period_max = period_2 self.period_min = period_1 self.trade_fee = trade_fee def should_buy(self, ticker_data): """ Check if we should buy. """ result_min = np.mean(ticker_data[-self.period_min:]) result_max = np.mean(ticker_data[-self.period_max:]) return (result_min * (1 + self.trade_fee) < result_max) def should_sell(self, ticker_data): """ Check if we should sell. """ result_min = np.mean(ticker_data[-self.period_min:]) result_max = np.mean(ticker_data[-self.period_max:]) return (result_min * (1 - self.trade_fee) > result_max)
6bcf17d04fad2916b1ab737e706cb032c4c46381
HenrryAraujo/file-processing-poc
/process_csv_files.py
2,106
3.5
4
#---------------------------------------------------- # Python program to process csv files: # -> Below program is intended to showcase some # Python functionalities to process data # from csv files. # # The program will process any new incoming file and # set its ip detils identifies by file name prefix #---------------------------------------------------- #---------------------------------------------------- # Importing Libraries #---------------------------------------------------- import pandas as pd import csv import os from pathlib import Path #---------------------------------------------------- # Base variables and Initial Global Settings # and Setup variables for Running #---------------------------------------------------- path_run = os.path.dirname(__file__) src_dir_name = '\source_input_files' tgt_file_name = '\processed_output\\Combined.csv' src_input_path= path_run + src_dir_name tgt_output_path = path_run + tgt_file_name #---------------------------------------------------- # Function to Proccess files in source folder #---------------------------------------------------- def get_process_ip_details(source_folder, output_file_path): files = os.listdir(source_folder) textfiles = [file for file in files if file.endswith(".csv")] with open (output_file_path, 'w', newline='') as outfile: writer = csv.writer(outfile) writer.writerow(('Source IP','Environment')) for files in textfiles: df_file = pd.read_csv(os.path.join(source_folder,files), delimiter= None if files.endswith('csv') else '\t') for index, row in df_file.iterrows(): env_name = "".join(filter(lambda x: not x.isdigit(), files)) writer.writerow((row[0], env_name.removesuffix('.csv'))) #---------------------------------------------------- # Triggering main method - for stand alone run #---------------------------------------------------- if Path(src_input_path).is_dir(): get_process_ip_details(src_input_path, tgt_output_path) else: print('Double Check Source Path')
a01c02e5227267010b7bf6ddb54c2502797bb3c6
Akshay7591/Caesar-Cipher-and-Types
/ROT13/ROT13encrypt.py
270
4.1875
4
a=str(input("Enter text to encrypt:")) key=13 enc="" for i in range (len(a)): char=a[i] if(char.isupper()): enc += chr((ord(char) + key-65) % 26 + 65) else: enc += chr((ord(char) + key-97) % 26 + 97) print("Encrypted Text is:") print(enc)