blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
89acbe8d001a6c30b34a0575ed35ca0ebde77b6b
Dzhevizov/SoftUni-Python-Fundamentals-course
/Exercise Basic Syntax, Conditional Statements and Loops/05. Can't Sleep Count Sheep.py
104
3.796875
4
count = int(input()) sheep = 1 while sheep <= count: print(f'{sheep} sheep...',end='') sheep +=1
5e4b0447b2ad2a040ee57276cf4bd226417d6be4
qmnguyenw/python_py4e
/geeksforgeeks/algorithm/medium_algo/1_17.py
11,789
3.6875
4
Maximize count of corresponding same elements in given permutations using cyclic rotations Given two permutations **P1** and **P2** of numbers from **1 to N** , the task is to find the maximum count of corresponding same elements in the given permutations by performing a cyclic left or right shift on **P1**. **Examples:** > **Input:** P1 = [5 4 3 2 1], P2 = [1 2 3 4 5] > **Output:** 1 > **Explanation:** > We have a matching pair at index 2 for element 3. > **Input:** P1 = [1 3 5 2 4 6], P2 = [1 5 2 4 3 6] > **Output:** 3 > **Explanation:** > Cyclic shift of second permutation towards right would give 6 1 5 2 4 3, and > we get a match of 5, 2, 4. Hence, the answer is 3 matching pairs. > Recommended: Please try your approach on _**_{IDE}_**_ first, before moving on to the solution. **Naive Approach:** The naive approach is to check for every possible shift in both the left and right direction count the number of matching pairs by looping through all the permutations formed. _**Time Complexity:** O(N2) _ _**Auxiliary Space:** O(1)_ **Efficient Approach:** The above naive approach can be optimized. The idea is for every element to **store the smaller distance** between positions of this element from the left and right sides in separate arrays. Hence, the solution to the problem will be calculated as the **maximum frequency** of an element from the two separated arrays. Below are the steps: 1. Store the position of all the elements of the permutation **P2** in an array(say **store[]** ). 2. For each element in the permutation **P1** , do the following: * Find the difference(say **diff** ) between the position of the current element in **P2** with the position in **P1**. * If diff is less than 0 then update diff to **(N – diff)**. * Store the frequency of current difference diff in a map. 3. After the above steps, the maximum frequency stored in the map is the maximum number of equal elements after rotation on **P1**. Below is the implementation of the above approach: ## C++ __ __ __ __ __ __ __ // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to maximize the matching // pairs between two permutation // using left and right rotation int maximumMatchingPairs(int perm1[], int perm2[], int n) { // Left array store distance of element // from left side and right array store // distance of element from right side int left[n], right[n]; // Map to store index of elements map<int, int> mp1, mp2; for (int i = 0; i < n; i++) { mp1[perm1[i]] = i; } for (int j = 0; j < n; j++) { mp2[perm2[j]] = j; } for (int i = 0; i < n; i++) { // idx1 is index of element // in first permutation // idx2 is index of element // in second permutation int idx2 = mp2[perm1[i]]; int idx1 = i; if (idx1 == idx2) { // If element if present on same // index on both permutations then // distance is zero left[i] = 0; right[i] = 0; } else if (idx1 < idx2) { // Calculate distance from left // and right side left[i] = (n - (idx2 - idx1)); right[i] = (idx2 - idx1); } else { // Calculate distance from left // and right side left[i] = (idx1 - idx2); right[i] = (n - (idx1 - idx2)); } } // Maps to store frequencies of elements // present in left and right arrays map<int, int> freq1, freq2; for (int i = 0; i < n; i++) { freq1[left[i]]++; freq2[right[i]]++; } int ans = 0; for (int i = 0; i < n; i++) { // Find maximum frequency ans = max(ans, max(freq1[left[i]], freq2[right[i]])); } // Return the result return ans; } // Driver Code int main() { // Given permutations P1 and P2 int P1[] = { 5, 4, 3, 2, 1 }; int P2[] = { 1, 2, 3, 4, 5 }; int n = sizeof(P1) / sizeof(P1[0]); // Function Call cout << maximumMatchingPairs(P1, P2, n); return 0; } --- __ __ ## Java __ __ __ __ __ __ __ // Java program for // the above approach import java.util.*; class GFG{ // Function to maximize the matching // pairs between two permutation // using left and right rotation static int maximumMatchingPairs(int perm1[], int perm2[], int n) { // Left array store distance of element // from left side and right array store // distance of element from right side int []left = new int[n]; int []right = new int[n]; // Map to store index of elements HashMap<Integer, Integer> mp1 = new HashMap<>(); HashMap<Integer, Integer> mp2 = new HashMap<>(); for (int i = 0; i < n; i++) { mp1.put(perm1[i], i); } for (int j = 0; j < n; j++) { mp2.put(perm2[j], j); } for (int i = 0; i < n; i++) { // idx1 is index of element // in first permutation // idx2 is index of element // in second permutation int idx2 = mp2.get(perm1[i]); int idx1 = i; if (idx1 == idx2) { // If element if present on same // index on both permutations then // distance is zero left[i] = 0; right[i] = 0; } else if (idx1 < idx2) { // Calculate distance from left // and right side left[i] = (n - (idx2 - idx1)); right[i] = (idx2 - idx1); } else { // Calculate distance from left // and right side left[i] = (idx1 - idx2); right[i] = (n - (idx1 - idx2)); } } // Maps to store frequencies of elements // present in left and right arrays HashMap<Integer, Integer> freq1 = new HashMap<>(); HashMap<Integer, Integer> freq2 = new HashMap<>(); for (int i = 0; i < n; i++) { if(freq1.containsKey(left[i])) freq1.put(left[i], freq1.get(left[i]) + 1); else freq1.put(left[i], 1); if(freq2.containsKey(right[i])) freq2.put(right[i], freq2.get(right[i]) + 1); else freq2.put(right[i], 1); } int ans = 0; for (int i = 0; i < n; i++) { // Find maximum frequency ans = Math.max(ans, Math.max(freq1.get(left[i]), freq2.get(right[i]))); } // Return the result return ans; } // Driver Code public static void main(String[] args) { // Given permutations P1 and P2 int P1[] = {5, 4, 3, 2, 1}; int P2[] = {1, 2, 3, 4, 5}; int n = P1.length; // Function Call System.out.print(maximumMatchingPairs(P1, P2, n)); } } // This code is contributed by gauravrajput1 --- __ __ ## Python3 __ __ __ __ __ __ __ # Python3 program for the above approach from collections import defaultdict # Function to maximize the matching # pairs between two permutation # using left and right rotation def maximumMatchingPairs(perm1, perm2, n): # Left array store distance of element # from left side and right array store # distance of element from right side left = [0] * n right = [0] * n # Map to store index of elements mp1 = {} mp2 = {} for i in range (n): mp1[perm1[i]] = i for j in range (n): mp2[perm2[j]] = j for i in range (n): # idx1 is index of element # in first permutation # idx2 is index of element # in second permutation idx2 = mp2[perm1[i]] idx1 = i if (idx1 == idx2): # If element if present on same # index on both permutations then # distance is zero left[i] = 0 right[i] = 0 elif (idx1 < idx2): # Calculate distance from left # and right side left[i] = (n - (idx2 - idx1)) right[i] = (idx2 - idx1) else : # Calculate distance from left # and right side left[i] = (idx1 - idx2) right[i] = (n - (idx1 - idx2)) # Maps to store frequencies of elements # present in left and right arrays freq1 = defaultdict (int) freq2 = defaultdict (int) for i in range (n): freq1[left[i]] += 1 freq2[right[i]] += 1 ans = 0 for i in range( n): # Find maximum frequency ans = max(ans, max(freq1[left[i]], freq2[right[i]])) # Return the result return ans # Driver Code if __name__ == "__main__": # Given permutations P1 and P2 P1 = [ 5, 4, 3, 2, 1 ] P2 = [ 1, 2, 3, 4, 5 ] n = len(P1) # Function Call print(maximumMatchingPairs(P1, P2, n)) # This code is contributed by chitranayal --- __ __ ## C# __ __ __ __ __ __ __ // C# program for // the above approach using System; using System.Collections.Generic; class GFG{ // Function to maximize the matching // pairs between two permutation // using left and right rotation static int maximumMatchingPairs(int []perm1, int []perm2, int n) { // Left array store distance of element // from left side and right array store // distance of element from right side int []left = new int[n]; int []right = new int[n]; // Map to store index of elements Dictionary<int, int> mp1=new Dictionary<int, int>(); Dictionary<int, int> mp2=new Dictionary<int, int>(); for (int i = 0; i < n; i++) { mp1[perm1[i]] = i; } for (int j = 0; j < n; j++) { mp2[perm2[j]] = j; } for (int i = 0; i < n; i++) { // idx1 is index of element // in first permutation // idx2 is index of element // in second permutation int idx2 = mp2[perm1[i]]; int idx1 = i; if (idx1 == idx2) { // If element if present on same // index on both permutations then // distance is zero left[i] = 0; right[i] = 0; } else if (idx1 < idx2) { // Calculate distance from left // and right side left[i] = (n - (idx2 - idx1)); right[i] = (idx2 - idx1); } else { // Calculate distance from left // and right side left[i] = (idx1 - idx2); right[i] = (n - (idx1 - idx2)); } } // Maps to store frequencies of elements // present in left and right arrays Dictionary<int, int> freq1=new Dictionary <int, int>(); Dictionary<int, int> freq2=new Dictionary <int, int>(); for (int i = 0; i < n; i++) { if(freq1.ContainsKey(left[i])) freq1[left[i]]++; else freq1[left[i]] = 1; if(freq2.ContainsKey(right[i])) freq2[right[i]]++; else freq2[right[i]] = 1; } int ans = 0; for (int i = 0; i < n; i++) { // Find maximum frequency ans = Math.Max(ans, Math.Max(freq1[left[i]], freq2[right[i]])); } // Return the result return ans; } // Driver Code public static void Main(string[] args) { // Given permutations P1 and P2 int []P1 = {5, 4, 3, 2, 1}; int []P2 = {1, 2, 3, 4, 5}; int n = P1.Length; // Function Call Console.Write(maximumMatchingPairs(P1, P2, n)); } } // This code is contributed by Rutvik_56 --- __ __ **Output:** 1 _**Time Complexity:** O(N) _ _**Auxiliary Space:** O(N)_ Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer **Complete Interview Preparation Course** **.** My Personal Notes _arrow_drop_up_ Save
2868ebd3c5b7fc2cc3f6d9df8b6da152ef120cd3
Ulises-Rosas/Fasta-to-Dictionary
/fast_to_dic.v.2.py
1,952
3.875
4
def fas_to_dic(x): ##fasta file is read file = open(x) ##all lines are stored in a variable file_content = file.readlines() ##an empty variable is created to store lines without the ##newline metacharacter symbol (i.e. "\n") seqs_list = [] ##Given this following loop: for i in file_content: ##newline symbol is ##replaced by nothing seqs_list.append(i.replace("\n", "")) ##here is where keys are going to be stored keys = [] ##likewise, here is where values are going to be stored values = [] i = 0 ##first value for dictionary's keys while(">" in seqs_list[i]): ##if lines start with ">" character, store it ##on the keys list keys.append(seqs_list[i]) ##add a new i value for continuing i += 1 ##here is where just a sequence will be stored JustOneValue = [] ##if lines, however, don't start with ">" character, ##these should be sequence's lines. ##second loop for dictionary's value while((">" in seqs_list[i]) == False): ##So, store them in a list JustOneValue.append(seqs_list[i]) ##add a new i value for continuing i += 1 ##if i is equals to the current length of the total ##amount of lines, then you will get indexing issues. ##So, barely you reach that number, stop or break the ##loop and substract a unit for not getting issues of ##indexing on the first loop if(i == len(seqs_list)): i -= 1 break ##every time you have all lines of a sequence, collapse them in ##a single line values.append("".join(JustOneValue)) return dict(zip(keys, values))
00219c44cadfa178fd8793cdaca2b8595bde5f28
rubiyadav18/Dictinory_questions
/logical question of hachrank.py
262
3.796875
4
def fun(words): a = {} for word in words: s = "".join(sorted(word)) if s in a: a[s].append(word) else: a[s] = [word] return list(a.values()) words=["eat","tea","tan","ate","nat","bat"] print(fun(words))
a5284a2e08de9135c4b64c91c88f4c76a6d62638
jiabin1122/UITest
/utils/randomUtils.py
298
3.59375
4
# -*- coding: utf-8 -*- # @Author: Jiabin import string import random def generate_random_string(count=10): random_string = ''.join(random.sample(string.letters.lower() + string.digits,count)) return random_string def generate_random_int(min, max): return random.randint(min, max)
c7a30bf508f9efc7d1b8419583fd5c5f081f1706
sunoh/korea-OSS-study
/MIT600/PS02 Using Bisection Search to Make the Program Faster.py
664
3.703125
4
balance = 999999 annualInterestRate = 0.18 monthlyPayment = 0 numMonth = 12 remaining = balance lb = balance / 12 ub = balance * (((1+(annualInterestRate /12))**12) / 12) while True: remaining = balance monthlyPayment = (lb+ub)/2.0 for month in range(numMonth-1): remaining -= monthlyPayment remaining += (remaining * annualInterestRate / 12) remaining -= monthlyPayment if round(remaining,2) > 0: lb = monthlyPayment elif round(remaining,2) < 0: ub = monthlyPayment elif round(remaining,2) == 0: break print 'Lowest Payment: ' + str(round(monthlyPayment,2))
5c8cf9e1b9dde05fa0ab11e47342c736cb5b06c3
denyszamiatin/Monopoly2
/player.py
4,130
3.578125
4
import random import field import observers class Player: """ """ def __init__(self, name, color, bank): """ """ self.name = name self.color = color self.bank = bank self.position = 0 self.previous_position = 0 def roll_dice(self): """ Get the result of rolling two dice :return: list of integers """ return tuple([random.randint(1, 6) for _ in range(2)]) @observers.player_observer def make_move(self): ''' Get new player's position ''' self.change_position(sum(self.roll_dice())) return self def change_position(self, position): self.previous_position = self.position self.position = (self.position + position) \ % (field.Field.get_field_count() - 1) def check_bank(self, amount): return self.bank >= abs(amount) def change_balance(self, cost): self.bank += cost def set_ownership(self, field, cost): self.change_balance(cost) field.set_owner(self) field.rent = field.get_rent(0) print('{} owner is {}, bank: {}'.format(field.name, field.owner.name, self.bank)) def get_auction_offer(self): try: offer = int(input('{}, input receive auction offer: '. format(self.name))) if self.check_bank(offer): return offer except ValueError: pass return 0 def _ask_for_buy(self): return input( '{}, do you want to buy this real estate? \n input "yes": ' .format(self.name) ) == 'yes' def buy_real_estate(self, field): ''' A buying real estate :param field: ''' if self._ask_for_buy() and self.check_bank(field.cost): self.set_ownership(field, field.cost) else: self.player_collection.realize_auction(field) @staticmethod def get_player_information(): name = input('input name: ') color = input('input color: ') bank = int(input('input bank: ')) return name, color, bank @staticmethod def create_player(get_player_information=get_player_information): """ Create a player >>> >>> p = Player.create_player(get_player_information=lambda: ('x', 'x', 2000, 0)) >>> p.name 'x' """ return Player(*Player.get_player_information()) class CollectionPlayers: ''' Collection of players ''' def __init__(self, amount_players): ''' :param amount of players ''' self.players = [ Player.create_player() for _ in range(amount_players) ] self.shuffle_players() def shuffle_players(self): """ Returns list of players sorted by roll dice result """ random.shuffle(self.players) def __iter__(self): for player in self.players: yield player def get_max_offer(self, max_offer, winner): is_winner_changed = False for bidder in self.players: offer = bidder.get_auction_offer() if offer > max_offer: max_offer, winner = offer, bidder is_winner_changed = True return is_winner_changed, winner, max_offer def get_auction_winner(self): max_offer, winner = 0, None is_winner_changed = True while is_winner_changed: is_winner_changed, winner, max_offer = \ self.get_max_offer(max_offer, winner) return winner, max_offer @staticmethod def show_auction_winner(name, max_offer): print('auction winner is', name, ', max_offer is:', max_offer) def realize_auction(self, field): print("Let's auction!!!") ''' Conducted an auction to buy real estate ''' winner, max_offer = self.get_auction_winner() self.show_auction_winner(winner.name, max_offer) winner.set_ownership(field, -max_offer)
c7f894ef078102f223c0ba493cb6289263c007cf
qinglujinjin/CS161_Assignment10QL
/reverse_list_QingLu.py
269
3.953125
4
#Author: Qing Lu #Date: 11/06/2019 #Description: Define function to reverses the order of elements in list def reverse_list(lst): """function to reverse elements in a list""" lst.reverse() return lst print(reverse_list([7, -3,12, 9])) #this is a note
5679d54ddaf75c6542baefec30025ac40fed202d
xwang38/groceryPath
/bfs.py
5,131
3.546875
4
row=40 col=40 class Vertex: def __init__(self,x_pos, y_pos, element): self.xPos=x_pos self.yPos=y_pos self.element=element self.visited=False def get_element(self): return self.element def set_element(self, element): self.element=element def get_pos(self): return self.xPos, self.yPos def getVisited(self): return self.visited def setVisited(self): self.visited=True def setUnvisited(self): self.visited=False class Graph: def __init__(self): self.makeGraph() def set_graph(self,new_row, new_col): global row,col row=new_row col=new_col self.makeGraph() def makeGraph(self): #new row or col has to be divisible by 10 global row, col self.graph=[[] for i in range(row)] for i in range(int(row/10)): for j in range(col): self.graph[i].append(Vertex(i,j,'|')) for i in range(int(4*row/10),int(5*row/10)): for j in range(col): self.graph[i].append(Vertex(i,j,'|')) for i in range(int(8*row/10),row): for j in range(col): self.graph[i].append(Vertex(i,j,'|')) for i in range(int(row/10),int(4*row/10)): for j in range(col): if j in [0,int((col-1)/3),int((2*col-2)/3), col-1]: self.graph[i].append(Vertex(i,j,'o')) else: self.graph[i].append(Vertex(i,j,'|')) for i in range(int(row/2),int(8*row/10)): for j in range(col): if j in [0,int((col-1)/3),int((2*col-2)/3), col-1]: self.graph[i].append(Vertex(i,j,'o')) else: self.graph[i].append(Vertex(i,j,'|')) def bfs(self, start, end): self.restoreUnvisited() #compute the BFS path from start to end; start and end should be tuple of x and y coordinate start=self.interpolate(start) end=self.interpolate(end) parent={} queue=[] queue.append(start) start.setVisited() self.last=end while (queue): curV=queue.pop(0) for eleV in self.adjacent(curV): if eleV.get_pos()==end.get_pos(): parent[eleV]=curV self.travelPath=list(self.getPath(parent, start, end)) self.itr_path() if eleV.get_element()=='o': self.last=curV return self.path_length if eleV.getVisited()==False and eleV.get_element()=='|': parent[eleV]=curV queue.append(eleV) eleV.setVisited() def get_lastPop(self): return self.last.get_pos() def getPath(self, parent, start, end): path=[end] while path[-1].get_pos()!=start.get_pos(): #print("current "+str(path[-1].get_pos())) path.append(parent[path[-1]]) return reversed(path) def adjacent(self, myVertex): # adjacent nodes is vertex that is above, left, right or below myVertex if myVertex.get_element==0: return x,y=myVertex.get_pos() neighbors=[] if self.inside(x-1,y): neighbors.append(self.graph[x-1][y]) if self.inside(x+1,y): neighbors.append(self.graph[x+1][y]) if self.inside(x,y-1): neighbors.append(self.graph[x][y-1]) if self.inside(x,y+1): neighbors.append(self.graph[x][y+1]) return neighbors def inside(self, x, y): #if this vertex is within map global row, col if x>=0 and x<=row-1 and y>=0 and y<=col-1: return True return False def iterate(self): #printout the map global row, col for i in range(row): myLine="" for j in range(col): myLine+=str(self.graph[i][j].get_element())+'\t' print(myLine) def itr_path(self): self.path_length=-1 tmp=[] for location in self.travelPath: tmp.append(location.get_pos()) self.path_length+=1 def getItrPath(self): path=[] for location in self.travelPath[1:]: path.append(location.get_pos()) return path def interpolate(self,mytuple): tmp=list(mytuple) return self.graph[tmp[0]][tmp[1]] def restoreUnvisited(self): for i in self.graph: for j in i: j.setUnvisited() def paintPath(self, mylist): #mylist contains points that you need pass; for ele in mylist: if (isinstance(ele,tuple)): self.interpolate(ele).set_element('*') else: for i in ele: if (isinstance(i,tuple)): self.interpolate(i).set_element('*') self.iterate() def get_para(self): global row, col return row,col
9723e0d4478647bbeac0cf9950e00c7dce2b2769
Sindhu-dot-R/Python_excercise
/Fibonassi_series.py
336
4.25
4
def recursive_fibo(n): if n <= 1: return n else: return(recursive_fibo(n-1) + recursive_fibo(n-2)) Num = int(input("enter a positive integer ")) if Num >= 0: print("Fibonacci sequence are:") for i in range(Num): print(recursive_fibo(i)) else : print("please enter a positive number")
13fbc3ed5e4168fbb59ee015c3b7e6c2fb2455e1
banjin/everyday
/questions/fab.py
2,770
3.6875
4
#!/usr/bin/env python # coding:utf-8 """斐波那契数列 """ def fabltion(n): if n < 2: return 1 return fabltion(n-2) + fabltion(n-1) def fabltion2(n): a, b = 0, 1 while n: yield b a, b = b, a + b n -= 1 def fabltion3(n): """斐波契纳数列1,2,3,5,8,13,21............根据这样的规律 编程求出400万以内最大的斐波契纳数,并求出它是第几个斐波契纳数。 n = fabltion3(4000000) for i in n: print(i) """ a, b = 0, 1 count = 0 while b < n: yield b a, b = b, a + b count += 1 print(count, b) def add_dict(dict1, dict2): """ 实现两个字典的相加,不同的key对应的值保留,相同的key对应的值相加后保留,如果是字符串就拼接 intput: dicta = {"a":1,”b”:2,”c”:3,”d”:4,”f”:”hello” } dictb = {“b”:3,”d”:5,”e”:7,”m”:9,”k”:”world”} output: dictc = {“a”:1,”b”:5,”c”:3,”d”:9,”e”:7,”m”:9,”f”:”hello”,”k”:”world”} """ result = {} key1 = set(dict1.keys()) key2 = set(dict2.keys()) in_dict1 = list(key1 - key2) in_dict2 = list(key2 - key1) all_in = key1 & key2 for i in in_dict1: result.update({i: dict1[i]}) for f in in_dict2: result.update({f: dict2[f]}) for a in all_in: t1 = dict1.get(a) t2 = dict2.get(a) if (isinstance(t1, int) and isinstance(t2, int)) or (isinstance(t1, str) and isinstance(t2, str)): result.update({a: t1+t2}) elif isinstance(t1, int) and isinstance(t2, str): result.update({a: str(t1)+t2}) elif isinstance(t1, str) and isinstance(t2, int): result.update({a: str(t2)+t1}) else: pass return result def taozi(): """ 海滩上有一堆桃子,五只猴子来分,第一只猴子把这堆桃子平均分成五份, 多了一个,这只猴子把多的一个扔到了海里,拿走了一份, 第二只猴子把剩下的把四堆桃子合在一起, 又平均分成五份,又多了一个, 它同样把多的一个扔到了海里, 拿走了一份,第三只,第四只,第五只都是这样做的, 问海滩上原来最少有多少桃子 """ i = 0 j = 1 x = 0 while (i < 5): x = 4 * j for i in range(0, 5): if(x % 4 != 0): break else: i += 1 x = (x/4) * 5 + 1 j += 1 print(x) def romanToInt(s): d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} if __name__ == "__main__": taozi()
3f47a758d55f22406f6469b0cedb49667e7badae
jarechalde/BioInformatics
/Assignment_1/Tournament.txt
1,385
3.71875
4
#In this script we will implement the tournament method to find the maximum and minimum of a number list arr = [1,3,4,76,43,2,4,7,8] maxmin = [None,None] maxminl = [None,None] maxminr = [None,None] def findmaxmin(arr,arr0,arr1): #If the array has only one element, its the maximum and minimum at the same time if arr0 == arr1: maxmin[1] = arr[arr0] maxmin[0] = arr[arr0] return maxmin[1],maxmin[0] #If the array has two elements if arr1 == (arr0 + 1): if arr[arr0]>arr[arr1]: maxmin[1]= arr[arr0] maxmin[0] = arr[arr1] else: maxmin[1] = arr[arr1] maxmin[0] = arr[arr0] return maxmin[1],maxmin[0] #If there are more than two elements, we should keep dividing the array recursively #Now we divide the list in two arrmid = (arr0+arr1)/2 maxminl[1],maxminl[0] = findmaxmin(arr,arr0,arrmid) maxminr[1],maxminr[0] = findmaxmin(arr,arrmid+1,arr1) #Now we compare both maximum and minimum found print(maxminl,maxminr) #Minimum if maxminl[0]<maxminr[0]: maxmin[0] = maxminl[0] else: maxmin[0] = maxminr[0] #Maximum if maxminl[1]>maxminr[1]: maxmin[1] = maxminl[1] else: maxmin[1] = maxminr[1] print('Relative max: %i Relative min: %i' %(maxmin[1],maxmin[0])) return maxmin[1],maxmin[0] #Calling the function maxmin = findmaxmin(arr, 0, len(arr)-1) print('Maximum found: %i' %maxmin[1]) print('Minimum found: %i' %maxmin[0])
86fed104d1f7778afca91ce7c09dbeba279b349f
vijonly/100_Days_of_Code
/Day1/band-name-generator.py
180
3.5625
4
print("Welcome to Band Name Generator.") city = input("What's name of city you grew up in?\n") pet = input("What's your pet name?\n") print(f"Your pet name could be {city} {pet}")
02d38b7b4ce5458b118e4da89c2c7218f17fcabf
Raj-1337/guvi
/pro4_10.py
113
3.546875
4
x = [i for i in input()] t = ['d', 'h', 'i', 'n', 'o'] if sorted(x) == t: print('yes') else: print('no')
7ad30d074e9cad179c5af3520b23c72ae7642d87
dnewbie25/Python-Quick-Reference
/Example Exercises/Basic Exercises/7_Seeing_The_World.py
788
4.3125
4
places_to_visit = ['Japan', 'Germany', 'UK', 'Alaska', 'Canada', 'France'] print(places_to_visit) # Prints the original list print(sorted(places_to_visit)) # Sorted alphabetically, without modifying the original list print(places_to_visit) # The original list print(sorted(places_to_visit, reverse=True)) print(places_to_visit) # Origina list places_to_visit.reverse() # Reverse the list from last index to first one print(places_to_visit) places_to_visit.reverse() # Reverse the list again, from last to first index.The list should be the same as the original print(places_to_visit) places_to_visit.sort() # Sort the list alphabetically, forever print(places_to_visit) places_to_visit.sort(reverse=True) # Reverse the list in alphabetical order forever print(places_to_visit)
c7c53aa23a476c731bdc278a1949cdff97dd2530
ymougenel/advent-of-code
/2022/day9/main_test.py
553
3.5
4
import unittest import main class main_test(unittest.TestCase): def test_input_example_1(self): data = main.read_file("inputs/part1.example") self.assertEqual(13, main.solve_part1(data)) def test_input_1(self): data = main.read_file("inputs/part1.input") self.assertEqual(6175, main.solve_part1(data)) """ def test_input_example_2(self): data = main.read_file("inputs/part1.example") self.assertEqual(6175, main.solve_part2(data)) """ if __name__ == '__main__': unittest.main()
799e669f1c76035ddec4a74d1d679915fc7f79a4
pujkiee/python-programming
/player level/power.py
205
3.8125
4
def ispower(n,base): if n==base: return yes if base ==1: return no temp=base while (temp<=n): if temp ==n: return yes temp*= base return no
8a36dbd4b2c51883409297f1b67d851ded474c7a
glucn/Python-Practice
/Lynda_Programming Foundation Real-World Examples/Exercise Files/Ch06/06_01_queues.py
606
3.984375
4
""" A Queue of Groceries to Put Away """ # create a new queue object import queue q = queue.Queue() print(q.empty()) # put bags into the queue q.put('bag1') print(q.empty()) q.put('bag2') q.put('bag3') # get bags from the queue in FIFO order print(q.get()) print(q.get()) print(q.get()) # q.get() # causes an error # create a new queue to hold two items q = queue.Queue(2) print(q.empty()) # put two bags into the two-item queue q.put('bag1') print(q.full()) q.put('bag2') print(q.full()) # try to put an extra bag into the queue q.put_nowait('bag3') # causes an error
ec4082086b5f4cbd431bed42a46b5b43be0cadd8
anpadoma/python_receptury3
/R02/podstawianie_wartości_za_zmienne_w_łańcuchach_znaków/example.py
688
3.5
4
# example.py # # Podstawianie wartości za zmienne w łańcuchach znaków # Klasa przeprowadzająca bezpieczne podstawianie class safesub(dict): def __missing__(self, key): return '{%s}' % key s = '{name} ma {n} wiadomości.' # (a) Proste podstawianie name = 'Gucio' n = 37 print(s.format_map(vars())) # (b) Bezpieczne podstawianie przy brakujących wartościach del n print(s.format_map(safesub(vars()))) # (c) Bezpieczne podstawianie plus sztuczka z ramką n = 37 import sys def sub(text): return text.format_map(safesub(sys._getframe(1).f_locals)) print(sub('Witaj, {name}')) print(sub('{name} ma {n} wiadomości')) print(sub('Twój ulubiony kolor to {color}'))
80772db67541b8aa6d77cbb57edcc1d8c4b9bbdd
aabhishek-chaurasia-au17/python_practice
/list/list-exercise/positive_numbers.py
317
4.09375
4
# Python program to print positive numbers in a list """ Input: list1 = [12, -7, 5, 64, -14] Output: 12, 5, 64 Input: list2 = [12, 14, -95, 3] Output: [12, 14, 3] """ def find_positive(a): for i in a: if i > 0 or i == 0: print(i , end=" ") list1 = [12, -7, 5, 64, -14] find_positive(list1)
819369bb02537b696c5d5979fffbdf624f5d36c5
jazib-mahmood-attainu/Ambedkar_Batch
/W3D4 - python 7/preeti.py
81
3.5
4
n = int(input("Enter a number")) for i in range(n): for j in range():
7acb039cc76a7880f0cc92691b445ea94f2f851a
kuangzipeng/Advanced-Programming
/Homework & Practice/Week4_homework/geometry/volume/cube.py
142
3.625
4
def vol_cube(): len = float(input("请输入立方体的边长:")) vol = len*len*len print("立方体的体积是:",vol)
b9e88d4bf7929751327b818843554b4a7a10f420
andernasc/Python-Desaf-Exerc
/Curso em Video - Python/modulo01/desaf-aula07/desafio12-aula07.py
259
3.5625
4
# DESAFIO 12 - AULA 07 - CALCULANDO DESCONTOS PORCENTAGEM 10% preco = float(input("Qual é o preço do produto? R$ ")) desc = preco - (preco * 10 / 100) input("O produto que custava R$ {:.2f} , com o desconto de 10%, custará R$ {:.2f}".format(preco, desc))
a52b300f570ff68910f8ae60cc9bcb8b014a0034
Daransoto/holbertonschool-machine_learning
/math/0x00-linear_algebra/102-squashed_like_sardines.py
1,701
3.703125
4
#!/usr/bin/env python3 """ This module contains the functions matrix_shape, deepcopy, and cat_matrices. """ def matrix_shape(matrix): """ Function to get the shape of a matrix. """ temp = matrix shape = [] while type(temp) == list: shape.append(len(temp)) temp = temp[0] return shape def deepcopy(matrix): """ Function that creates a deepcopy of a matrix. """ stackM = [matrix] stackA = [] while stackM: currentM = stackM.pop() if stackA: currentA = stackA.pop() else: currentA = [] ans = currentA if type(currentM[0]) == list: for row in currentM: currentA.append([]) stackM.append(row) stackA.append(currentA[-1]) else: currentA.extend(currentM) return ans def cat_matrices(mat1, mat2, axis=0): """ Funtion to concatenate 2 matrices over a given axis. """ shape1 = matrix_shape(mat1) shape2 = matrix_shape(mat2) dim1 = len(shape1) dim2 = len(shape2) if not dim1 == dim2: return None for i in range(dim1): if i == axis: continue if shape1[i] != shape2[i]: return None cpMat1 = deepcopy(mat1) cpMat2 = deepcopy(mat2) auxM1 = [cpMat1] auxM2 = [cpMat2] while axis: helperM1 = [] helperM2 = [] for i in range(len(auxM1)): helperM1.extend(auxM1[i]) helperM2.extend(auxM2[i]) auxM1 = helperM1 auxM2 = helperM2 axis -= 1 for i in range(len(auxM1)): auxM1[i].extend(auxM2[i]) return cpMat1
1b946cee75ccae94eba31665c5a994585b95434f
lyswty/nowcoder-solutions
/2019校招真题编程练习/快手/字符串排序.py
178
3.734375
4
from queue import PriorityQueue m = int(input()) heap = PriorityQueue() for i in range(m): s = input() heap.put(int(s[-6:])) while not heap.empty(): print(heap.get())
b6c24f98119f02383487f4c7ee5812af48270393
aratijadhav/Python
/sum_multiply_6.py
624
4.21875
4
#sum function to add all element in given list def Sum1_Function(list1): add = 0 for val in list1: add = add + val return add #Mult function to multiply all elements in given list def Mult_Function(list1): mul = 1 for val in list1: mul = mul *val return mul if __name__ == "__main__": list1 = [] num = int(raw_input("enter len of list\n")) for x in range(num): a = int(raw_input("Enter List Ele\n")) list1.append(a) Ans1 = Sum1_Function(list1) Ans2 = Mult_Function(list1) print "Addtion is = ",Ans1," Multiplication is = ",Ans2
dd31535b794f3ebe110e38f297ce271de33761d2
sctu/sctu-ds-2019
/1806101005朱强/lab04/test01.py
272
3.921875
4
def reverse_str(input_str): stack = [] target = [] for ch in input_str: stack.append(ch) while len(stack) != 0: ch = stack.pop() target.append(ch) return target if __name__ == '__main__': reverse_str('Hello,World!')
b184e673440bd7a5d33c2bf3b53d95c7a4b445c1
Programmer-Admin/binarysearch-editorials
/Foo Bar Qaz Qux.py
1,475
4.0625
4
""" Foo Bar Qaz Qux LOOK AT OTHER EDITORIAL Three cases: If there is only one unique color: return the length of the string. Now it gets funky. If the frequency are all even or all odd, the answer will be two. Here's my best explanation as to why. At each iteration, we remove one from the frequency of two colors, and add one to the frequency of the last color. Here's an illustration, where R and G are combined. ``` R G B 4 4 4 3 3 5 ``` If we remove one from an even number, it will give an odd number. The same holds when we add one to an even number. So if all frequencies are even on one iteration, they will all be odd on the next, and then even, etc. Following this line of logic, the frequency of each color will eventually be (1,1,1): ``` R G B 4 4 4 3 3 5 2 2 6 1 1 7 2 0 6 1 1 5 2 0 4 1 1 3 2 0 2 1 1 1 ``` And when that happens, we are fucked. Because when we combine two of those colors, we will be left with two identical colors. Here's what happens if they are not all even or odd: ``` R G B 3 4 4 2 3 5 1 2 6 0 1 7 1 0 6 0 1 5 1 0 4 0 1 3 1 0 2 0 1 1 ``` In the final state, one or two numbers will be even, and the rest one will be odd. If two ones are left, we can make our last one, otherwise we already reached our end state. """ from collections import Counter class Solution: def solve(self, quxes): cnt=Counter(quxes) if len(cnt)==1: return len(quxes) if len({x%2 for x in cnt.values()}) == 1: return 2 return 1
ce9d13146abf1d263d1592ee2f791c6e0a545ff1
thapadipendra/awesome-python-script
/net_cut.py
2,655
3.65625
4
#!/usr/bin/env python # this program used to cut internet connection in any network. import scapy.all as scapy import netfilterqueue #previously we become middle of connection snd sniff data using two py file # we can also modify packet and can redirect to different path to fake websit or to download backdoor etc # scapy can used to have modified packet but cant be used to intercept or drop original one ie both packet will be send to target(router) #target(access point) will receive both the packet but execute the one which came first as for modified one it takes time so it redirect for original one. # hence chances are target(router) never execute modified one. # to eliminate this problem queue is used in hacker machine and request are traped inside that queue and never send to target unless modified # queue is then accessed by python program and modified and that is send as request.hence target only receive modified one # same way to modify response ie trap it in queue and modify it and send to target(window machine) # scapy dont allow do above so we use basic setup setting queue and py program to access modify and send # unix has program called ip table installed in it .used in many thing one is allow us to modify routes in the computer . # iptables -I FORWARD -j NFQUEUE --queue-num 0 command in cli for trapping packet.(subprocess can also be used as model to execute that command but here not use for simple system command) # I for chain we want to modify here forward chain which is default chain for packet that come to computer. # nfqueue is netfilter queue use any queue num here 0. # now we need to access this queue and modify in py program so net filter queue module used. # pip install netfilterqueue def process_packet(packet): print(packet) packet.drop()#for drop packet and make this program what it is intended for.cut internet connection. # packet.accept()#for py program to forward packet to destination.alternet to drop. queue=netfilterqueue.NetfilterQueue()#cerate object to interact with queue number 0 as specified as command in unix sys queue.bind(0,process_packet)#used to bind or link this queue variable with system queue which we created with queue num=0.here 0 specifies same. # 0 is que num in sys ie que we want to interact and process_packet is callback fun which will execute for each packet trapped in that queue. queue.run() # should be in mimf to get packet .this program for store in queue and access.drop packet or dont drop(accept) # after you done with work delete ip table you created in unix command # iptables --flush is command in cli of unix sys to delete the table
8007715da412f4abe1b30c5746970eb463cc3d06
marvincosmo/Python-Curso-em-Video
/ex087 - Mais sobre matriz em python.py
1,766
4.21875
4
""" 87 - Aprimore o desafio anterior, mostrando no final: A) A soma de todos os valores pares digitados. B) A soma dos valores da terceira coluna. C) O maior valor da segunda linha.""" # Minha resposta: """ matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] pares = terceira = maior = 0 for l in range(0,3): for c in range(0, 3): matriz[l][c] = int(input(f'Digite um valor para [{l}, {c}]: ')) print('-=' * 30) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') if matriz[l][c] % 2 == 0: pares += matriz[l][c] if matriz[l][c] == matriz[l][2]: terceira += matriz[l][2] if matriz[1][c] == 1: maior = matriz[1][c] else: if matriz[1][c] > maior: maior = matriz[1][c] print() print('-=' * 30) print(f'A soma de todos os valores pares digitados é {pares}.') print(f'A soma dos valores da terceira coluna é {terceira}.') print(f'O maior valor da segunda linha é {maior}.') """ # Resposta do professor: matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] pares = terceira = maior = 0 for l in range(0,3): for c in range(0, 3): matriz[l][c] = int(input(f'Digite um valor para [{l}, {c}]: ')) print('-=' * 30) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') if matriz[l][c] % 2 == 0: pares += matriz[l][c] print() print('-=' * 30) print(f'A soma de todos os valores pares digitados é {pares}.') for l in range(0, 3): terceira += matriz[l][2] print(f'A soma dos valores da terceira coluna é {terceira}.') for c in range(0, 3): if c == 0 or matriz[1][c] > maior: maior = matriz[1][c] print(f'O maior valor da segunda linha é {maior}.')
1fcd69b844fbf468fbe02f84e687c24053cf562a
ideaOwl/rltoolkit
/RLtoolkit/Quickgraph/graph.py
31,286
3.84375
4
# <html><head><title> Graph.py Source Code </title></head><body><pre> """ Source Code for graph.py, a quickgraphing tool for for Python. See http://rlai.cs.ualberta.ca/RLAI/RLtoolkit/graph.html for <a href=graph.html>documentation</a>. The function graph will draw a graph in a window, with each data line given a different color. A graph is a window with various state vars. The simplest way to use this is: graph(data) and then, possibly, graphMore(data) you may also graphLess(color) or specifying the graphname, graph(data, color, graph) graphMore(newdata, color, graph) graphLess(color, graph) The graph involved defaults to the first graph or a newly created graph if there are no graphs yet (or if graph is True). Alternatively, you can make multiple graphs, and specify the graph as a last argument to all graph routines. Data can be a simple list of y's (heights) or a list of list of y's. Or it can be a list of (x y) coordinates, e.g., ((x1 y1) (x2 y2) ...) Or a list of those! The span of the graph is initially set from the data. Alternatively: xGraphLimits(xmin, xmax) does it manually (same for yGraphLimits) xGraphLimits() sets it back to auto Tick marks are initially just at the min and max. Alternatively: xTickmarks([tick1, tick2, tick3 ...]) sets them manually (same for yTickmarks) xTickmarks() sets them back to auto xTickmarks(num) sets them to go from the graph minimum to the maximum by num (call it after you make the graph to use this) Tick marks are specified by values, e.g., xTickmarks(0 .5, 1.0) or by a list of valuelabel pairs, e.g., xTickmarks( (0, "0"), (1.0, "1")) gridgraph(density, graph) creates a grid across the graph graphPointsOnly(graph) makes dots on the graph for each point rather than a continuous line histogram([val1, val2, ...], numbins, minex, maxex, color, hist) creates a histogram of the values. All parameters except the data list are optional histogramMore([val1, val2, ...], numbins, minex, maxex, color, hist) adds another histogram graph on top of the current one When the graph is drawn, you can highlight lines in it to see them better. The space bar turns highlighting on and off. Highlighting will start with the first data line. Use the arrow keys to move to the next or previous lines in the graph. To get rid of a graph: closeGraph(graph) can be called with the graph or its name. If None, the first graph in the list of windows will be closed """ # if we only have the quickgraph package, use g from that. But if the whole # toolkit is installed, use g from that try: from RLtoolkit.G.g import * except: from .g import * import operator import math from functools import reduce class Dataview(Gview): "dataview of graph" def __init__(self, parent, gdViewport): Gview.__init__(self, parent) gdSetViewport(self, gdViewport[0], gdViewport[1], gdViewport[2], gdViewport[3]) gSetCursor(self, 'crosshair') def gClickEventHandler(self, x, y): print(("Clicked at", x, y)) def gKeyEventHandler(self, key): graph = self.parent if key == "Left" or key == "Up": removeHighlight(graph) graph.highlightline = (graph.highlightline - 1) % len(graph.data) drawHighlight(graph) elif key == "Right" or key == "Down": removeHighlight(graph) graph.highlightline = (graph.highlightline + 1) % len(graph.data) drawHighlight(graph) elif key == "space": removeHighlight(graph) graph.highlightp = not graph.highlightp drawHighlight(graph) class Graph(Gwindow): def __init__(self, title="Graph", dataviewtype=Dataview, **kwargs): # (0,40,500,200)): self.dataview = None self.dviewtype = dataviewtype self.maincolor = gBlack self.data = None self.autolimitsx = True # limiting x values from data, self.autolimitsy = True # or from user and tickmarks? self.xmax = 1.0 self.xmin = 0.0 self.ymax = 1.0 self.ymin = 0.0 self.xtickmarks = [] # initial tick marks auto from limits self.ytickmarks = [] self.charstyle = gFont("Geneva", 9, 'normal') self.charwidth = 6 self.charheight = 8 self.ylabelspace = 0 self.xlabelspace = 0 self.zerospace = 15 self.xendspace = 10 self.yendspace = 10 self.ticklength = None self.boxy = False self.pointsonly = False self.griddensity = None self.highlightp = False self.highlightcolor = None self.highlightline = 0 self.lasthighlight = None if not ( 'gdViewport' in kwargs or 'gdViewportR' in kwargs or 'gViewport' in kwargs or 'gViewportR' in kwargs): Gwindow.__init__(self, windowTitle=title, gdViewport=(0, 40, 600, 300)) else: Gwindow.__init__(self, windowTitle=title, **kwargs) self.initGraph() ## The data is a list of lists. Each list is either a list of yvalues or ## a list of xypairs. def initGraph(self): self.xlabelspace = 11 * self.charwidth self.ylabelspace = 10 + self.charheight self.ticklength = self.zerospace / 2 gSetCSScale(self, 0, 0, 1, 1, 'lowerLeft') x1, y1, x2, y2 = gGetViewport(self) self.dataview = self.dviewtype(self, gdViewport=(self.xlabelspace + 1, \ self.yendspace, \ x2 - self.xendspace, \ y2 - self.ylabelspace - 1)) gClear(self.dataview, 'white') gSetCoordinateSystem(self.dataview, self.xmin, self.ymin, self.xmax, self.ymax, 'lowerLeft') self.maincolor = gColorOn(self.dataview) self.highlightcolor = gColorPen(self.dataview, gColorFlip(self.dataview), None, None, 2, 2) def gAcceptNewViewportSize(self): gSetCSScale(self, 0, 0, 1, 1, 'lowerLeft') if isinstance(self, Graph) and self.dataview != None: x1, y1, x2, y2, corner = gGetCoordinateSystem(self) gdSetViewport(self.dataview, \ self.xlabelspace + 1, \ self.yendspace, \ x2 - self.xendspace, \ y2 - self.ylabelspace - 1) gClear(self.dataview, 'white') self.gDrawView() def gDrawView(self): "Draws the graph" gClear(self, 'white') gClear(self.dataview, 'white') self.drawAxes() if self.data != None: for color, dlist in self.data: drawLine(self, dlist, color) if self.highlightp: drawHighlight(self) if self.griddensity != None: gridGraph(None, self) def drawAxes(self): xspace = self.xlabelspace # abs(gOffsetx(self, self.xlabelspace)) yspace = self.ylabelspace # abs(gOffsety(self, self.ylabelspace)) gDrawLine(self, self.xlabelspace, yspace, \ gConvertx(self.dataview, self, self.xmax) + self.xlabelspace, \ yspace, \ self.maincolor) gDrawLine(self, xspace, self.ylabelspace, \ xspace, \ gConverty(self.dataview, self, self.ymax) - self.yendspace, \ self.maincolor) self.drawTickmarks() def drawTickmarks(self): xspace = self.xlabelspace # abs(gOffsetx(self, self.xlabelspace)) yspace = self.ylabelspace # abs(gOffsety(self, self.ylabelspace)) if self.xtickmarks != [] and self.xtickmarks != None: useticks = self.xtickmarks else: useticks = regularizeTickmarks([self.xmin, self.xmax]) if self.xmin <= self.xmax: for x, label in useticks: gx = gConvertx(self.dataview, self, x) + self.xlabelspace gDrawLineR(self, gx, yspace, 0, -self.ticklength, self.maincolor) gDrawText(self, label, self.charstyle, \ gx - (self.charwidth * len(label)) / 2, \ yspace - 5 - self.charheight, self.maincolor) if self.ytickmarks != [] and self.ytickmarks != None: useticks = self.ytickmarks else: useticks = regularizeTickmarks([self.ymin, self.ymax]) if self.ymin <= self.ymax: for y, label in useticks: gy = gConverty(self.dataview, self, y) - self.yendspace gDrawLineR(self, xspace, gy, -self.ticklength, 0, self.maincolor) gDrawText(self, label, self.charstyle, \ xspace - 5 - (self.charwidth * len(label)), \ gy - (self.charheight / 2), self.maincolor) def gKeyEventHandler(self, key): # send key presses to dataview handler self.dataview.gKeyEventHandler(key) def removeNulls(l): for i in range(l.count(None)): l.remove(None) for i in range(l.count([])): l.remove([]) def graph(newdata, color=None, graph=None): # <a name="graph"</a>[<a href="graph.html#graph">Doc</a>] "Establishes some data for a graph, then draws it" if None in newdata or [] in newdata: print("Warning: Some data to be graphed was nil; ignoring") removeNulls(newdata) if newdata == []: print("No graphing data") else: graph = chooseGraph(graph) graph.data = FillInColors(regularizeData(newdata, color)) graph.highlightline = 0 graph.highlightp = False computeLimitsFromData(graph) graph.gDrawView() return graph def regularizeData(data, color=None): "regular form is a list of lines, each of which is a list or list of pairs, preceded by color" if not isinstance(data[0], (tuple, list)): # simple list return [[color, data]] elif isinstance(data[0][0], (tuple, list)): # list of lists of pairs return [[color, d] for d in data] elif len(data[0]) == 2: # list of pairs return [[color, data]] else: # list of lists return [[color, d] for d in data] def FillInColors(data): for colorline in data: if colorline[0] == None: colorline[0] = FirstUnusedColor(data) return data def graphData(graph): "Returns the data plotted in graph, with color stripped away of course" usegraph = chooseGraph(graph) dataonly = [] for color, dlist in usegraph.data: dataonly.append(dlist) return dataonly def FirstX(data): "returns the xvalue of the first point in data" useline = None for line in data: if line != None: useline = line break if useline != None: line = useline[1] if isinstance(line[0], (tuple, list)): firstpoint = line[0][0] else: firstpoint = 1 return firstpoint def FirstY(data): "returns the yvalue of the first point in data" useline = None for line in data: if line != None: useline = line break if useline != None: line = useline[1] if isinstance(line[0], (tuple, list)): firstpoint = line[0][1] else: firstpoint = line[0] return firstpoint def graphMore(newdata, color=None, graph=None): # <a name="graphMore"</a>[<a href="graph.html#graphMore">Doc</a>] addToGraph(newdata, color, graph) def graphPointsOnly(graph=None): graph = chooseGraph(graph) graph.pointsonly = not graph.pointsonly graph.gDrawView() def addToGraph(newdata, color=None, graph=None): # <a name="addtograph"</a>[<a href="graph.html#addtograph">Doc</a>] "Adds additional data to a graph" if newdata == None or reduce(operator.and_, [a == None for a in newdata]): print("No graphing data") else: if None in newdata: print("Warning: Some data to be graphed was nil; ignoring") newdata.remove(None) graph = chooseGraph(graph) graph.data.extend(regularizeData(newdata, color)) graph.data = FillInColors(graph.data) computeLimitsFromData(graph) graph.gDrawView() def graphLess(colorkeyword=None, graph=None): # <a name="graph"</a>[<a href="graph.html#graph">Doc</a>] "Remove a line of data points from the graph. Defaults to last line" if colorkeyword == None: subtractFromGraph(None, graph) else: graph = chooseGraph(graph) removecolor = ColorFromKeyword(colorkeyword) linenum = 0 for color, dlist in graph.data: if color == removecolor: subtractFromGraph(linenum, graph) break else: linenum += 1 else: print(("No such color used in this graph", colorkeyword)) def subtractFromGraph(linenum=None, graph=None): # <a name="subtractfromgraph"</a>[<a href="graph.html#subtractfromgraph">Doc</a>] "Remove a line of data points from the graph. Linenum is from zero or defaults to last line" originalfrontwindow = Win.FrontWindow() graph = chooseGraph(graph) if linenum == None: linenum = len(graph.data) - 1 num = 0 newdata = [] graph.data[linenum:] = graph.data[linenum + 1:] computeLimitsFromData(graph) gDrawView(graph) def xGraphLimits(xmin=None, xmax=None, graph=None): # <a name="xgraphlimits"</a>[<a href="graph.html#xgraphlimits">Doc</a>] graph = chooseGraph(graph) if xmin != None or xmax != None: graph.autolimitsx = False if xmin != None: graph.xmin = xmin if xmax != None: graph.xmax = xmax gSetCoordinateSystem(graph.dataview, graph.xmin, graph.ymin, graph.xmax, graph.ymax, 'lowerLeft') else: graph.autolimitsx = True computeLimitsFromData(graph) graph.gDrawView() def yGraphLimits(ymin=None, ymax=None, graph=None): # <a name="ygraphlimits"</a>[<a href="graph.html#ygraphlimits">Doc</a>] graph = chooseGraph(graph) if ymin != None or ymax != None: graph.autolimitsy = False if ymin != None: graph.ymin = ymin if ymax != None: graph.ymax = ymax gSetCoordinateSystem(graph.dataview, graph.xmin, graph.ymin, graph.xmax, graph.ymax, 'lowerLeft') else: graph.autolimitsy = True computeLimitsFromData(graph) graph.gDrawView() def xTickmarks(xticks=None, graph=None): # <a name="xtickmarks"</a>[<a href="graph.html#xtickmarks">Doc</a>] "Sets the ticks marks and possibly resets limits." graph = chooseGraph(graph) if xticks == None: graph.xtickmarks = None if graph.data != None: computeLimitsFromData(graph) elif isinstance(xticks, (tuple, list)): graph.xtickmarks = regularizeTickmarks(xticks) graph.xmin = min(graph.xmin, MinTickmark(graph.xtickmarks)) graph.xmax = max(graph.xmax, MaxTickmark(graph.xtickmarks)) gSetCoordinateSystem(graph.dataview, graph.xmin, graph.ymin, graph.xmax, graph.ymax, 'lowerLeft') else: # a number if graph.data != None and graph.data != []: ticks = [] i = graph.xmin while i <= graph.xmax: ticks.append(i) i += xticks graph.xtickmarks = regularizeTickmarks(ticks) graph.gDrawView() def yTickmarks(yticks=None, graph=None): # <a name="ytickmarks"</a>[<a href="graph.html#ytickmarks">Doc</a>] "Sets the ticks marks and possibly resets limits." graph = chooseGraph(graph) if yticks == None: graph.ytickmarks = None if graph.data != None: computeLimitsFromData(graph) elif isinstance(yticks, (tuple, list)): graph.ytickmarks = regularizeTickmarks(yticks) if graph.data != None: computeLimitsFromData(graph) else: graph.ymin = min(graph.ymin, MinTickmark(graph.ytickmarks)) graph.ymax = max(graph.ymax, MaxTickmark(graph.ytickmarks)) else: # a number if graph.data != None and graph.data != []: ticks = [] i = graph.ymin while i <= graph.ymax: ticks.append(i) i += yticks graph.ytickmarks = regularizeTickmarks(ticks) graph.gDrawView() def regularizeTickmarks(ticks): useticks = [] for tick in ticks: if isinstance(tick, (tuple, list)): useticks.append(tick) elif isinstance(tick, float): useticks.append([tick, str(round(tick, 3))]) else: useticks.append([tick, str(tick)]) return useticks def MinTickmark(ticks): if ticks != None and ticks != []: if isinstance(ticks[0], (tuple, list)): return ticks[0][0] else: return ticks[0] def MaxTickmark(ticks): if ticks != None and ticks != []: if isinstance(ticks[-1], (tuple, list)): return ticks[-1][0] else: return ticks[-1] colors = [gColorRed(True), gColorGreen(True), gColorBlue(True), gColorBlack(True), \ gColorYellow(True), gColorPink(True), gColorCyan(True), gColorPurple(True), \ gColorMagenta(True), gColorOrange(True), gColorBrown(True), gColorLightBlue(True), \ gColorGray(True), gColorDarkGreen(True), gColorTan(True)] def nthColor( n): # <a name="nthColor"</a>[<a href="graph.html#nthColor">Doc</a>] return colors[n // length(colors)] colorList = {'blue': gBlue, 'red': gRed, 'green': gGreen, 'black': gBlack, 'yellow': gYellow, \ 'pink': gPink, 'cyan': gCyan, 'purple': gPurple, 'magenta': gMagenta, \ 'orange': gOrange, 'brown': gBrown, 'lightBlue': gLightBlue, 'gray': gGray, \ 'darkGreen': gDarkGreen, 'tan': gTan, 'white': gWhite, \ 'lightGray': gLightGray, 'darkGray': gDarkGray} def ColorFromKeyword(colorkeyword): color = colorList.get(colorkeyword, None) if color == None: print(("Unrecognized color keyword:", colorkeyword)) return color def FirstUnusedColor(data): "Returns first color in the list of colors that is least used in data" for permittedTimesUsed in range(100): for color in colors: if TimesColorUsed(color, data) <= permittedTimesUsed: return color def TimesColorUsed(color, data): count = 0 for c, dlist in data: if c == color: count += 1 return count def chooseGraph( graph=None): # <a name="choosegraph"</a>[<a href="graph.html#choosegraph">Doc</a>] "Select a graph based on input 'graph'" global GDEVICE glist = [] for w in GDEVICE.childwindows: if isinstance(w, Graph): glist.append(w) if graph == None: # None given - if first is a graph, use it, else make a new one if glist == []: usegraph = Graph("Graph") else: usegraph = glist[0] elif isinstance(graph, Graph): # already have graph usegraph = graph elif graph == True: usegraph = Graph("Graph") elif isinstance(graph, str): # we have a graph name for g in glist: if g.title == graph: usegraph = g break else: usegraph = Graph(graph) else: print(("Error: can't choose graph", graph)) usegraph = None return usegraph def closeGraph(graph=None): graph.gCloseview() def drawSegment(graph, x1, y1, x2, y2, color): l = [] if graph.boxy: l.append(gDrawLine(graph.dataview, x1, y1, x2, y1, color)) l.append(gDrawLine(graph.dataview, x2, y1, x2, y2, color)) else: l.append(gDrawLine(graph.dataview, x1, y1, x2, y2, color)) return l def draw(graph, ylist, color): l = [] for i in range(len(ylist) - 1): # start from 1 x1 = i + 1 x2 = i + 2 y1 = ylist[i] y2 = ylist[i + 1] l.extend(drawSegment(graph, x1, y1, x2, y2, color)) return l def drawXY(graph, xylist, color): l = [] for i in range(len(xylist) - 1): x1, y1 = xylist[i] x2, y2 = xylist[i + 1] l.extend(drawSegment(graph, x1, y1, x2, y2, color)) return l def calcRadius(graph): x0, y0, xs, ys, corner = gGetCSScale(graph.dataview) radius = xs / 5000.0 if radius < .001: radius = .001 if radius > .02: radius = .02 return radius def drawPoints(graph, ylist, color, highlight): radius = calcRadius(graph) if highlight: radius = 2 * radius l = [] for i in range(len(ylist)): l.append(gDrawDisk(graph.dataview, i + 1, ylist[i], radius, color)) return l def drawPointsXY(graph, xylist, color, highlight): radius = calcRadius(graph) if highlight: radius = 2 * radius l = [] for i in range(len(xylist)): x, y = xylist[i] l.append(gDrawDisk(graph.dataview, x, y, radius, color)) return l def computeLimitsFromData(graph): if graph.autolimitsx: graph.xmin = MinTickmark(graph.xtickmarks) if graph.xmin == None: graph.xmin = FirstX(graph.data) graph.xmax = MaxTickmark(graph.xtickmarks) if graph.xmax == None: graph.xmax = FirstX(graph.data) if graph.autolimitsy: graph.ymin = MinTickmark(graph.ytickmarks) if graph.ymin == None: graph.ymin = FirstY(graph.data) graph.ymax = MaxTickmark(graph.ytickmarks) if graph.ymax == None: graph.ymax = FirstY(graph.data) if graph.autolimitsx or graph.autolimitsy: for color, dlist in graph.data: if not isinstance(dlist[0], (tuple, list)): if graph.autolimitsy: for y in dlist: if y < graph.ymin: graph.ymin = y if y > graph.ymax: graph.ymax = y if graph.autolimitsx: if 1 < graph.xmin: graph.xmin = 1 if len(dlist) > graph.xmax: graph.xmax = len(dlist) else: for x, y in dlist: if graph.autolimitsy: if y < graph.ymin: graph.ymin = y if y > graph.ymax: graph.ymax = y if graph.autolimitsx: if x < graph.xmin: graph.xmin = x if x > graph.xmax: graph.xmax = x if graph.ymin == graph.ymax: print(("Warning: all lines are flat at", graph.ymin)) if graph.ymax > 0: graph.ymin = 0 else: graph.ymin = graph.ymax - 1 gSetCoordinateSystem(graph.dataview, graph.xmin, graph.ymin, graph.xmax, graph.ymax, 'lowerLeft') def gridGraph(griddensit=None, graph=None): # <a name="gridGraph"</a>[<a href="graph.html#gridGraph">Doc</a>] graph = chooseGraph(graph) if griddensit != None: graph.griddensity = griddensit if graph.griddensity == None: graph.griddensity = 5 for x, label in graph.xtickmarks: dx = gdCoordx(graph.dataview, x) if x >= graph.xmin and x <= graph.xmax: for dy in range(gdCoordy(graph.dataview, graph.ymax), \ gdCoordy(graph.dataview, graph.ymin), \ graph.griddensity): gdDrawPoint(graph.dataview, dx, dy, graph.maincolor) for y, label in graph.ytickmarks: dy = gdCoordy(graph.dataview, y) if y >= graph.ymin and y <= graph.ymax: for dx in range(gdCoordx(graph.dataview, graph.xmin), \ gdCoordx(graph.dataview, graph.xmax), \ graph.griddensity): gdDrawPoint(graph.dataview, dx, dy, graph.maincolor) def drawHighlight(graph): if graph.highlightp and graph.highlightline != None: color, data = graph.data[graph.highlightline] graph.lasthighlight = drawLine(graph, data, gColorPen(graph, color, None, None, 2), True) def removeHighlight(graph): if graph.lasthighlight != None: gDelete(graph.dataview, graph.lasthighlight) graph.lasthighlight = None def drawLine(graph, line, color, highlight=False): if isinstance(line[0], (tuple, list)): if graph.pointsonly: return drawPointsXY(graph, line, color, highlight) else: return drawXY(graph, line, color) else: if graph.pointsonly: return drawPoints(graph, line, color, highlight) else: return draw(graph, line, color) # A histogram is a graph, created in a particular way # histogram(data, numbins, minex, maxex, graph) def histogram(data, numbins=None, minex=None, maxex=None, color=None, hist=None): # <a name="histogram"</a>[<a href="graph.html#histogram">Doc</a>] "plots histogram of data, minex <= data < maxex, in a color on a graph named hist" if data == None or data == []: print("No graphing data") elif len(data) == 1: print("Cannot histogram a single datum") else: if minex == None: minex = min(data) mx = max(data) if minex == mx: print("Error: min=max - no histogram possible") else: if isinstance(mx, int) and isinstance(minex, int): if maxex == None: maxex = mx + 1 if numbins == None and (mx - minex) <= 200: numbins = maxex - minex if numbins == None: numbins = 30 if maxex == None: maxex = mx + (.00001 * ((mx - minex) / numbins)) hgraph = chooseGraph(hist) hgraph.boxy = True bins = [0 for i in range(numbins)] numtoosmall = numtoobig = 0 scalefactor = float(numbins) / (maxex - minex) for d in data: bin = int(math.floor((d - minex) * scalefactor)) if bin < 0: numtoosmall += 1 elif bin >= numbins: numtoobig += 1 else: bins[bin] += 1 gdata = [] for i in range(numbins): # prepare list of bin max, # in that bin x = minex + (float(i) / scalefactor) entry = [x, bins[i]] gdata.append(entry) gdata.append( [maxex, bins[numbins - 1]]) # force the last bar to come out graph([gdata], color, hgraph) if numtoosmall != 0: print((numtoosmall, "data points were below the range")) if numtoobig != 0: print((numtoobig, "data points were above the range")) def histogramMore(data, numbins=None, minex=None, maxex=None, color=None, hist=None): # <a name="histogramMore"</a>[<a href="graph.html#histogramMore">Doc</a>] "adds histogram of data, minex <= data < maxex, in a color to a graph named hist" # histogram(data, numbins, minex, maxex, color, hist) if data == None or data == []: print("No graphing data") elif len(data) == 1: print("Cannot histogram a single datum") else: if minex == None: minex = min(data) mx = max(data) if minex == mx: print("Error: min=max - no histogram possible") else: if isinstance(mx, int) and isinstance(minex, int): if maxex == None: maxex = mx + 1 if numbins == None and (mx - minex) <= 200: numbins = maxex - minex if numbins == None: numbins = 30 if maxex == None: maxex = mx + (.00001 * ((mx - minex) / numbins)) hgraph = chooseGraph(hist) hgraph.boxy = True bins = [0 for i in range(numbins)] numtoosmall = numtoobig = 0 scalefactor = float(numbins) / (maxex - minex) for d in data: bin = int(math.floor((d - minex) * scalefactor)) if bin < 0: numtoosmall += 1 elif bin >= numbins: numtoobig += 1 else: bins[bin] += 1 gdata = [] for i in range(numbins): # prepare list of bin max, # in that bin x = minex + (float(i) / scalefactor) entry = [x, bins[i]] gdata.append(entry) gdata.append( [maxex, bins[numbins - 1]]) # force the last bar to come out newdata = regularizeData([gdata], color) hgraph.data.extend(newdata) hgraph.data = FillInColors(hgraph.data) hgraph.gDrawView() if numtoosmall != 0: print((numtoosmall, "data points were below the range")) if numtoobig != 0: print((numtoobig, "data points were above the range")) # Testing stuff """ histogram([1.2, 1.3, 2.5, 6, 20, 1.4, 5, 30, 5.5, 7, 23, 19, 15, 15], 5, None, None, 'red') histogramMore([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30],5, None, None, 'blue') histogramMore([1,2,11,12,13,15,21,22,23,24,25],3, None, None, 'green') xTickmarks([0, 1, 2, 3, 4, 5],"new") yTickmarks([0,5, 10, 15, 20, 25, 30],"new") gridGraph(10,"new") graph([[1,2,3,4,5],[0,1,4,9]],None, "new") xTickmarks([(1,"st"),(2,"ar"),(3,"ts"),(4,"end")], "new") #graph([[1, 2, 3, 4],[(1,1),(2,4),(3,6),(4,8)], [1,4,9, 25]]) g = graph([[0,1,2,3,4],[0,1,4,6,8],[0,1,4,9,27],[0,5,10,15,20],[(0,10),(1,20),(2,30)]], None, "test") xTickmarks(1.5, "test") yTickmarks(10, "test") from math import * def func1 (num): data = [[0. for j in range(num)] for i in range(num)] dx = 2. / (num - 1) y = - 1. for i in range(num): x = - 1 for j in range(num): data[i][j] = abs(exp(-0.5 * (sqr(x) + sqr(y)))) * (1. + (cos(10 * sqrt(sqr(x) + sqr(y))))) x = x + dx y = y + dx return data def sqr (x): return x * x graph(func1(30), graph="Function") """ # </pre></body></html>
2dacc8a5236216d8901875a86b59479197674ad1
Wyrd00/holbertonschool-higher_level_programming
/0x03-python-data_structures/7-add_tuple.py
335
3.828125
4
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): alist = list(tuple_a) blist = list(tuple_b) for i in range(2): alist.append(0) for j in range(2): blist.append(0) sum1 = alist[0] + blist[0] sum2 = alist[1] + blist[1] return (sum1, sum2)
221bc3ec443f7c6ff0d0bddb8b3665347a9815d8
Kids-Hack-Labs/Summer2020
/solutions/week03/app.py
752
3.90625
4
''' Kids Hack Labs Summer 2020 - Week 03 code TaskA: Create an app entry point file ''' #1. Game module import (NOT pygame) from game_env import Game #2. Main function definition # 2.1. Create a Game-type variable # (Remember to pass setup parameters) # 2.2. Call the run() function in the variable def main(): print("entered main()") g = Game((1024, 768), "Week 03") g.run() print("exited main()") #3. Check whether this is the application entry point # (if it is): # 3.1 Call the main() function if __name__ == "__main__": print("Module name is", __name__) main() ''' OBS.: In the future, we will mix in more Python features, so... ...take care of these files well '''
90e96e8773c38e761b62b184c4df89d90a3832a2
CodingGimp/learning-python
/morse.py
959
4.0625
4
''' Let's use __str__ to turn Python code into Morse code! OK, not really, but we can turn class instances into a representation of their Morse code counterparts. I want you to add a __str__ method to the Letter class that loops through the pattern attribute of an instance and returns "dot" for every "." (period) and "dash" for every "_" (underscore). Join them with a hyphen. I've included an S class as an example (I'll generate the others when I test your code) and it's __str__ output should be "dot-dot-dot". ''' class Letter: def __init__(self, pattern=None): self.pattern = pattern def __str__(self): morse = [] for char in self.pattern: if char == '.': morse.append('dot') elif char == '_': morse.append('dash') return '-'.join(morse) class S(Letter): def __init__(self): pattern = ['.', '.', '.'] super().__init__(pattern)
6f328eef16460332ae33e776d633acd0e4318a3d
asmitde/TA-PSU-CMPSC101
/Spring 2017/Homework/Homework3/Q4.py
1,869
4.03125
4
# Question 4 - Find repeated number # Asmit De # 04/28/2017 ######################################## Solution 1 ######################################### # Input n n = int(input('Enter n: ')) # Enter list data user_input = input('Enter the list: ') nums = [int(n) for n in user_input.split()] # Initialize a list of n elements to all False. # present[i] = True/False denotes if the number i+1 # from the nums list is recorded to be present at least once. present = [False] * n # Loop through the numbers in the nums list for e in nums: # Using the number e itself as an index (e-1, because index starts at 0) # of the list present, check if e has already been marked as present (true). if present[e - 1]: # This means that we have come across e earlier. # Hence this is the repeat number. print('The repeated number is:', e) # Break out of the Loop break # Else if the presence of e is marked as false, else: # update it to true - we found the 1st occurrence. present[e - 1] = True ############################################################################################# ######################################## Solution 2 ######################################### # Input n n = int(input('Enter n: ')) # Enter list data user_input = input('Enter the list: ') nums = [int(n) for n in user_input.split()] # Calculate the sum of all the numbers from 1 to n sum_n = n * (n + 1) // 2 # Calculate the sum of the numbers entered sum_all = 0 for e in nums: sum_all += e # The difference between the two will be the repeated number rep = sum_all - sum_n # Display the repeated number print('The repeated number is:', rep) #############################################################################################
bca372788ed1dfe3e92776525d1e3dbfa210e7ad
AllenGFLiu/geektime
/queue/circle_queue.py
1,667
3.765625
4
# 循環队列特性: # 队列最大的特性就是先进先出,后进后出,最形象的比喻就是排队 # 使用數組實現的非循環順序隊列,會存在數據搬移的問題,均攤時間複雜度為O(1) # 使用循環順序隊列可以避免數據搬移,因為是一個環 # # Author: AllenGFLiu # ##################################################### class CircleQueue(): """基于数组的队列,存储的元素个数是固定的。 head指针指示数组内第一个存储元素的位置 tail指针指示数组内最后一个存储元素位置的后边一位 循環隊列的隊空判定條件是head == tail, 隊滿的判定條件是(tail+1)%n == head enqueue : 往尾部插入一个value元素 dequeue : 从头部删除一个元素,并返回值 """ def __init__(self, capacity): self._array = ['*']*capacity self._capacity = capacity self._head = 0 self._tail = 0 def enqueue(self, value): if (self._tail + 1)% self._capacity == self._head: return self._array[self._tail] = value self._tail = (self._tail+1) % self._capacity def dequeue(self): if self._head == self._tail: return return_value = self._array[self._head] self._array[self._head] = '*' self._head = (self._head+1) % self._capacity return return_value def __repr__(self): return ''.join(self._array) if __name__ == '__main__': cq = CircleQueue(5) cq.enqueue('a') cq.enqueue('b') cq.enqueue('c') cq.enqueue('d') print(cq) cq.dequeue() cq.enqueue('e') print(cq)
400f99f20b4b74cc80e31a70d2b7a7d14122898c
gaoyunqing/MetReg
/MetReg/data/data_preprocessor.py
4,853
3.625
4
import numpy as np import sklearn.preprocessing as prep class Data_preprocessor(): """a class for preprocessing data. Implement basic preprocessing operation, including normalization, interplot, outlier preprocessing, wavelet denoise. # (TODO)@lilu: outlier preprocess # (TODO)@lilu: wavelet denoise process .. rubic:: process loop 0. check X, y 1. concat X,y for process 2. split dataset by time order 3. normalization (turn default value to nan) 4. interplot (first spatial, second temporal) 5. separate into inputs and outputs .. Notes: exec only support special dataset frame, such as nd.array, satisfy dimensions, etc. Args: interp (bool, optional): whether interpolate. Defaults to True. normalize (bool, optional): whether normalize. Defaults to True. feat_name (list, optional): list contain name of features. Defaults to ['precipitation','soil temperature','pressure']. fill_value (int, optional): Defaults to -9999. (TODO)@lilu: try different fill value of different features """ def __init__(self, X, y=None, interp=True, normalize=True, fill_value=-9999, feat_name=['precipitation'], ): self.X, self.y = X, y self.fill_value = fill_value self.feat_name = feat_name self.normalize = normalize self.interp = interp # get config self.set_config() def _normalize(self, inputs): """Normalization data using MinMaxScaler .. Notes: Instead normalize on the whole data, we first normalize train data, and then normalize valid data by trained scaler. we believe this is a correct operation to avoid introducing test dataset information before benchmark process. Therefore, the input of this func must have train & valid datasets. """ return prep.MinMaxScaler().fit_transform(inputs) def _interp(self, inputs): """Interplot using mean value. Args: inputs (nd.array): must be timeseries or images. array shape of (timestep,) or (height, width) """ if inputs.ndim == 1: return np.nan_to_num(inputs, nan=np.nanmean(inputs),) elif inputs.ndim == 2: H, W = inputs.shape inputs = np.nan_to_num(inputs.reshape(-1, 1), nan=np.nanmean(inputs)) return inputs.reshape(H, W) def _denoise(self, inputs, flag_features=False): """denoise of inputs, only for features. Args: inputs ([type]): [description] flag_features (bool, optional): flag for identify features and label. """ if not flag_features: raise KeyError('wavelet denoise method not support for label.') else: pass def _cluster(self): pass def __call__(self): """Exec preprocessing process""" # (TODO)@lilu: check X,y # concat X,y for process data = np.concatenate([self.X, self.y], axis=-1) # turn fill value to nan data[data == self.fill_value] = np.nan # interplot data = data.reshape(-1, self.height, self.width) for i in range(data.shape[0]): data[i, :, :] = self._interp(data[i, :, :]) data = data.reshape(-1, self.height, self.width, self.feat_size+1) # normalization if self.normalize: for i in range(self.height): for j in range(self.width): data[:, i, j, :] = self._normalize(data[:, i, j, :]) # separate X, y = data[:, :, :, :-1], data[:, :, :, -1] return X, y def __repr__(self): return str(self.config) def set_config(self): """Set configuration of class.""" self.N, self.height, self.width, self.feat_size = self.X.shape self.config = { 'name': 'auto processor', 'timestep': self.N, 'height': self.height, 'width': self.width, 'feat_size': self.feat_size, 'feat_name': self.feat_name, 'interp': self.interp, 'interp_method': 'mean value', 'normalize': self.normalize, 'normalize_method': 'min max scaler', 'fill_value': self.fill_value } if __name__ == "__main__": X = np.random.random(size=(100, 10, 10, 2)) y = np.random.random(size=(100, 10, 10, 1)) dp = Data_preprocessor(X, y) print(dp)
d394322dec981c8a5fe79875595d58c3134517b5
si21lvi/tallerlogicaprogramacion
/68.py
615
3.71875
4
contadorpositivo=0 contadornegativo=0 contadorpares=0 contadorimpar=0 multiplosdeocho=0 y=int(input("ingresa el numero")) x=int(input("ingresa el numero")) for i in range(y, x+1): if i>0: contadorpositivo=contadorpositivo+1 if i<0: contadornegativo=contadornegativo+1 if i%2==0: contadorpares=contadorpares+1 if i%2!=0: contadorimpar=contadorimpar+1 if i%8==0: multiplosdeocho=multiplosdeocho+1 print("positivo",contadorpositivo) print("negativo",contadornegativo) print("par",contadorpares) print("impar",contadorimpar) print("multiplos de ocho",multiplosdeocho)
c4ad5840422ab62362245296af78e3a37b48a74e
csusb-005411285/CodeBreakersCode
/integer-to-english-words.py
6,498
3.53125
4
# concise class Solution: def __init__(self): self.units = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'} self.teens = {11: 'eleven', 12:'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'} self.tens = {2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety'} def numberToWords(self, num: int) -> str: if num == 0: return "Zero" words = '' billionth, million = divmod(num, 1000000000) millionth, thousand = divmod(million, 1000000) thousandth, hundred = divmod(thousand, 1000) if billionth: words += self.process_three_digits(billionth) + ' Billion' if millionth: words += ' ' + self.process_three_digits(millionth) + ' Million' if billionth else self.process_three_digits(millionth) + ' Million' if thousandth: words += ' ' + self.process_three_digits(thousandth) + ' Thousand' if millionth else self.process_three_digits(thousandth) + ' Thousand' if hundred: words += ' ' + self.process_three_digits(hundred) if thousandth or millionth or billionth else self.process_three_digits(hundred) return words def process_three_digits(self, digits): three_digits = '' hundredth, tens = divmod(digits, 100) # 100, 101, 123, 23, 3, if hundredth: three_digits += self.units[hundredth] + ' Hundred' if tens: three_digits += ' ' + self.process_two_digits(tens) if hundredth else self.process_two_digits(tens) return three_digits.title() def process_two_digits(self, digits): two_digits = '' if digits <= 10: return self.units[digits] if digits < 20: return self.teens[digits] div, mod = divmod(digits, 10) two_digits += self.tens[div] + ' ' + self.units[mod] if self.units[mod] else self.tens[div] return two_digits.title() class Solution: def __init__(self): self.units = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'} self.tens_l20 = {10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen' } self.tens_g20= { 2: 'Twenty', 3: 'Thirty', 4: 'Forty', 5: 'Fifty', 6: 'Sixty', 7: 'Seventy', 8: 'Eighty', 9: 'Ninety'} def numberToWords(self, num: int) -> str: if num == 0: return 'Zero' english_word = '' billion, millionth = divmod(num, 1000000000) million, thousandth = divmod(millionth, 1000000) thousand, hundred = divmod(thousandth, 1000) if billion: english_word += self.two_digits_to_words(billion) + ' Billion' if million: english_word += ' ' + self.three_digits_to_words(million) + ' Million' if billion else self.three_digits_to_words(million) + ' Million' if thousand: english_word += ' ' + self.three_digits_to_words(thousand) + ' Thousand' if billion or million else self.three_digits_to_words(thousand) + ' Thousand' if hundred: english_word += ' ' + self.three_digits_to_words(hundred) if billion or million or thousand else self.three_digits_to_words(hundred) return english_word def three_digits_to_words(self, num): words = '' hundred, other = divmod(num, 100) if hundred and other: words += self.units[hundred] + ' Hundred ' + self.two_digits_to_words(other) elif hundred and other == 0: words += self.units[hundred] + ' Hundred' elif hundred == 0 and other: words += self.two_digits_to_words(other) return words def two_digits_to_words(self, num): word = '' tens, units = divmod(num, 10) if num < 10: word += self.units[num] elif num < 20: word += self.tens_l20[num] else: if tens and units == 0: word += self.tens_g20[tens] elif tens and units: word += self.tens_g20[tens] + ' ' + self.units[units] elif tens == 0 and units: word += self.units[units] return word class Solution: def __init__(self): self.units = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'} self.tens_l20 = {10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen' } self.tens_g20= { 2: 'Twenty', 3: 'Thirty', 4: 'Forty', 5: 'Fifty', 6: 'Sixty', 7: 'Seventy', 8: 'Eighty', 9: 'Ninety'} def numberToWords(self, num: int) -> str: if num == 0: return 'Zero' billion = num//1000000000 million = (num % 1000000000) // 1000000 thousand = (num % 1000000) // 1000 hundred = num%1000 tens = (num % 100) // 10 output = '' if billion: output = self.units[billion] + ' Billion' if million: output += ' ' if billion else '' output += self.three_digits(million) + ' Million' if thousand: output += ' ' if million or billion else '' output += self.three_digits(thousand) + ' Thousand' if hundred: output += ' ' if thousand or million or billion else '' output += self.three_digits(hundred) return output def two_digits(self, num): if num < 10: return self.units[num] elif num < 20: return self.tens_l20[num] else: tens, ones = divmod(num, 10) if tens and not ones: return self.tens_g20[tens] elif tens and ones: return self.tens_g20[tens] + ' ' + self.units[ones] def three_digits(self, num): hundreds, tens = divmod(num, 100) if hundreds and tens: return self.units[hundreds] + ' Hundred' + ' ' + self.two_digits(tens) elif hundreds and not tens: return self.units[hundreds] + ' Hundred' elif not hundreds and tens: return self.two_digits(tens)
026e2b3003ba8e2b8ba0305edb7c8e9a2e471beb
PatrickNyrud/projects
/pirate/config.py
1,841
3.609375
4
import os import sys class config: def __init__(self): self.file_dest = "config\\" self.config = "config.txt" self.keywords = "keywords.txt" self.upcomming = "upcomming.txt" self.isRunning = True while self.isRunning: os.system("cls") print("----------WELCOME-----------\n\n" "1. Edit Movies\n\n" "2. Edit Keywords\n\n" "3. Edit Upcomming\n\n" "4. Exit\n\n" "----------------------------") self.usr_choice = raw_input(">> ") if self.usr_choice == "1": self.edit_file(self.file_dest, self.config, "Movies") elif self.usr_choice == "2": self.edit_file(self.file_dest, self.keywords, "Keywords") elif self.usr_choice == "3": self.edit_file(self.file_dest, self.upcomming, "Releases") elif self.usr_choice == "4": os.system("cls") self.isRunning = False sys.exit(0) else: pass def edit_file(self, dirr, file, title): self.editTrue = True while self.editTrue: os.system("cls") print("----------" + title + "----------\n") self.pos = 0 with open(dirr + file, "r") as f: for lines in f: self.pos += 1 print str(self.pos) + ". " + lines print("----------" + ("-" * len(title)) + "----------" + "\nAdd(1) or Remove(2) a movie or Back(3)") self.ussr_choice = input(">> ") if self.ussr_choice == 1: self.usr = raw_input(">> ") with open(dirr + file, "a") as f: f.write(self.usr + "\n") f.close() elif self.ussr_choice == 2: self.usr = input(">> ") with open(dirr + file, "r") as f: self.movie_liste = list(f) f.close() del self.movie_liste[self.usr - 1] with open(dirr + file, "w") as f: for x in self.movie_liste: f.write(x) f.close() elif self.ussr_choice == 3: self.editTrue = False if __name__ == "__main__": self.start = config()
6936d415229cd9008d354abbec89804d09282339
ryoman81/Leetcode-challenge
/LeetCode Pattern/10. Heap & Priority Queue/215_med_kth_largest_element_in_an_array.py
3,298
4.0625
4
''' Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note: You may assume k is always valid, 1 ≤ k ≤ array's length. ''' # Import helper class maxHeap in this folder from Heap import maxHeap class Solution: ''' THE OPTIMAL CODE VERSION Improvement: Of course you cannot use a third-party module or library Even Java and C++ provide internal data structure of priority queue (binary heap) that you can use But the interviewer won't like you to do that like the belowing answer Let's do it within the solution Thought: Heap: no library introduced - Heapify the input array to a max-heap // O(n) - Extract top (the maximum) k-1 times // O(klogn) Complexity: Time: O(klogn + n) Space: O(1) ''' def findKthLargest(self, nums, k): # we will create a closure function siftDown for heapifying and extracting methods def siftDown (arr, current): # find the index of left and right children left = current * 2 + 1 right = current * 2 + 2 # loop over to sift down this item while left < len(arr): # find the max child to be swapped maxChild = left # check if right is larger than the left if right < len(arr) and arr[right] > arr[left]: maxChild = right # doing a swap to sift down the current if arr[current] < arr[maxChild]: arr[current], arr[maxChild] = arr[maxChild], arr[current] else: return # update index current = maxChild left = current * 2 + 1 right = left + 1 # the first step is to heapify the nums array we will do it in-place of the list i = len(nums) // 2 while i >= 0: siftDown(nums, i) i -= 1 # then we will extract (pop) the top of nums for k-1 times max = 0 for i in range(0, k): max = nums[0] # record the current max value nums[0], nums[-1] = nums[-1], nums[0] # swap top and tail of heap list nums.pop() # pop out the last item siftDown(nums, 0) # sift down the top item to maintain the heap structure # return the final result return max ''' MY CODE VERSION Thought: Heap: using my own maxHeap class - Heapify the input array to a max-heap // O(n) - Extract top (the maximum) k-1 times // O(klogn) Complexity: Time: O(klogn + n) Space: O(n) ''' def findKthLargest1(self, nums, k): # heapify the nums array heap = maxHeap() heap.heapify(nums) kthMax = nums[0] # extract (pop) the top for k-1 times for i in range(0, k): kthMax = heap.extract() return kthMax ''' SIMPLE CODE VERSION Thought: Silly solution, very easy - Sort the input array reversely - return the k-1th element Complexity: Time: O(nlogn) Space: O(1) ''' def findKthLargest2(self, nums, k): nums.sort(reverse=True) return nums[k-1] ## Run code after defining input and solver input1 = [3,2,3,1,2,4,5,5,6] input2 = 4 solver = Solution().findKthLargest print(solver(input1, input2))
572c2c8e6da47783312554464ccbe4e905cad602
jyanko/script-exercise
/python/cs_adjacentElements.py
1,218
4.25
4
#!/usr/local/bin/python3 ################################## # TASK #4 # # Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. # # Example # # For inputArray = [3, 6, -2, -5, 7, 3], the output should be # adjacentElementsProduct(inputArray) = 21. # # 7 and 3 produce the largest product. # def adjacentElementsProduct(inputArray): #print(len(inputArray)) eFirst=0 eLast=len(inputArray) - 1 hiVal=None #print("eLast: " + str(eLast)) for eIndex, eValue in enumerate(inputArray): if eIndex >= eLast: pass # skipping if last element of list detected else: eNext=eIndex + 1 currProduct=inputArray[eIndex] * inputArray[eNext] if hiVal == None or hiVal < currProduct: hiVal = currProduct return hiVal # setup some input lists to run against... inputLists=[ [3, 6, -2, -5, 7, 3], [-23, 4, -3, 8, -12], [4, 9, 2, 1, 7, 10, 5, 3] ] for myList in inputLists: print("Processing: ", myList) hiVal=str(adjacentElementsProduct(myList)) print("=> HiVal: " + hiVal)
92035e7c4b2a6643723ca46945c7e9d5c823a865
saifhamdare/shortcutstopython
/strfunc.py
140
4.0625
4
print('enter your name') name=input('name') print('enter your age ') age=int(input('age')) print('hello',name,'your age is '+str(age))
f0aa4f4ad9e8605df5c175a15288c848b72f5d4a
csun87/dworp
/dworp/observer.py
4,094
3.59375
4
# Copyright 2018, The Johns Hopkins University Applied Physics Laboratory LLC # All rights reserved. # Distributed under the terms of the Modified BSD License. from abc import ABC, abstractmethod import logging import time class Observer(ABC): """Simulation observer Runs after each time step in the simulation. Can be used to collect data for analysis of the simulation. """ logger = logging.getLogger(__name__) def start(self, now, agents, env): """Run the observer after the simulation has been initialized Args: now (int, float): Start time of simulation agents (list): List of agents in the simulation env (object): Environment object for this time index """ pass @abstractmethod def step(self, now, agents, env): """Run the observer after a step of the simulation has finished Args: now (int, float): Current time value agents (list): List of agents in the simulation env (object): Environment object for this time index """ pass def stop(self, now, agents, env): """Run the observer one last time when the simulation has stopped Args: now (int, float): Current time value agents (list): List of agents in the simulation env (object): Environment object for this time index """ pass class ChainedObserver(Observer): """Chain multiple observers into a sequence Args: *observers: Variable length arguments of Observer objects """ def __init__(self, *observers): self.observers = list(observers) def append(self, observer): self.observers.append(observer) def start(self, now, agents, env): for observer in self.observers: observer.start(now, agents, env) def step(self, now, agents, env): for observer in self.observers: observer.step(now, agents, env) def stop(self, now, agents, env): for observer in self.observers: observer.stop(now, agents, env) class KeyPauseObserver(Observer): """Requires a key press to get to the next time step Args: message (string): Optional message for the user start (bool): Optionally pause after initialization stop (bool): Optionally pause when simulation completes """ def __init__(self, message="Press enter to continue...", start=False, stop=False): self.message = message self.start_flag = start self.stop_flag = stop def start(self, now, agents, env): if self.start_flag: input(self.message) def step(self, now, agents, env): input(self.message) def stop(self, now, agents, env): if self.stop_flag: input(self.message) class PauseObserver(Observer): """Pause for x seconds between each time step This does not work with plotting during the simulation. Use dworp.plot.PlotPauseObserver instead. Args: delay (int): Length of delay in seconds start (bool): Optionally pause after initialization stop (bool): Optionally pause when simulation completes """ def __init__(self, delay, start=False, stop=False): self.delay = delay self.start_flag = start self.stop_flag = stop def start(self, now, agents, env): if self.start_flag: self.pause() def step(self, now, agents, env): self.pause() def stop(self, now, agents, env): if self.stop_flag: self.pause() def pause(self): time.sleep(self.delay) class PauseAtEndObserver(Observer): """Pause for x seconds at the end of the simulation This is useful if you want to keep a plot up on the screen. Args: delay (int): Length of delay in seconds """ def __init__(self, delay): self.delay = delay def step(self, now, agents, env): pass def stop(self, now, agents, env): time.sleep(self.delay)
8097210dbbd14099bac36c6fa599fe8c7ed459fd
zhaox12134/datamining_project
/title_analyse.py
1,202
3.53125
4
#文章标题同样涵盖了极大的信息,通过比对以进行判断 import json with open("train_pub.json") as file1: pub = json.load(file1) with open("train_author.json") as file2: author = json.load(file2) dict_writer_title = {} def get_title(): for name in author: for writer in author[name]: for article in author[name][writer]: try: if writer not in dict_writer_title: dict_writer_title[writer]=[pub[article]["title"],] else: dict_writer_title[writer].append(pub[article]["title"]) except: if "title" not in pub[article]: print("文章缺少title字段") pass else: print("其他错误") get_title() for writer in dict_writer_title: print(writer) for title in dict_writer_title[writer]: print(title) #以上只是获取了作者的论文标题信息,还没来得及去重 #而且论文标题的信息过多,包含了不必要的自然语言信息,要按照abstract的处理办法,量化并提取信息
3555664eaf9d833c609208d396daba3f6246daee
daideep/Training_Work
/List.py
654
4.09375
4
#Write a function removeFirstAndLast(list) that takes in a list as an argument and remove the first and last elements from the list. # The function will return a list with the remaining items. def removeFirstAndLast(numbers): new = numbers new.pop(0) # if not new: # return new new.pop(-1) return new print(removeFirstAndLast([1, 4, 8])) print('---------------') # In Python, variables are linked to objects by references. a = [4, 5, 6 ] b = a b[0] = 1 # print(b) print(a) a[2] = 3 print(a) print(b) print('---------------') a = [4, 5, 6] b = a[:] b[0] = 1 a[2] = 3 print(a) print(b) print('---------------')
920ac39be6c4b94f1e53a6a1a66b6731ffe65152
pty902/Resume
/Algorithm/Recursive Call/Hanoi/hanoi_1.py
328
4.0625
4
def hanoi(n, from_pos, to_pos, aux_pos): if n == 1: print(from_pos, "->", to_pos) return hanoi(n-1, from_pos, aux_pos, to_pos) print(from_pos, "->", to_pos) hanoi(n-1, aux_pos, to_pos, from_pos) print("n=1") hanoi(1,1,3,2) print("n=2") hanoi(2,1,3,2) print("n=3") hanoi(3,1,3,2)
48b7ec084bfb7244ca62fbcdaee593790540cda5
felipelfb/Python-Katas
/5 kyu/find_the_unique_string.py
1,127
4.28125
4
# There is an array of strings. All strings contains similar letters except one. Try to find it! # find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) # => 'BbBb' # find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) # => 'foo' # Strings may contain spaces. Spaces is not significant, only non-spaces symbols matters. E.g. string that contains only spaces is like empty string. # It’s guaranteed that array contains more than 3 strings. # https://www.codewars.com/kata/find-the-unique-string/train/python def find_uniq(arr): string1 = get_char_dict(arr[0]) string2 = get_char_dict(arr[1]) if string1 != string2: string3 = get_char_dict(arr[2]) if string3 == string1: return arr[1] else: return arr[0] for string in range(2, len(arr)): string3 = get_char_dict(arr[string]) if string3 != string1: return arr[string] def get_char_dict(string): char_dict = {} for char in string: if char.lower() not in char_dict and char != ' ': char_dict[char.lower()] = 1 return char_dict
fce7e455ae6ea606f591ec34378b8122ca004e8e
bcbarr/homework
/pypoll.py
2,930
3.625
4
import csv import os #variables total_votes = 0 khan_votes = 0 correy_votes = 0 li_votes = 0 tooley_votes = 0 #find the data election_data = os.path.join('Resources', 'election_data.csv') #read the file with open(election_data) as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') #uncomment to print #print(csvreader) # Read the header row first (skip this step if there is no header) csv_header = next(csvreader) #uncomment to show header #print(f"CSV Header: {csv_header}") #read through each row for row in csvreader: total_votes += 1 if row[2] == str("Khan"): khan_votes += 1 if row[2] == str("Correy"): correy_votes += 1 if row[2] == str("Li"): li_votes += 1 if row[2] == str("O'Tooley"): tooley_votes += 1 if khan_votes > correy_votes and khan_votes > li_votes and khan_votes > tooley_votes: winner = ("Khan") if correy_votes > khan_votes and correy_votes > li_votes and correy_votes > tooley_votes: winner = ("Khan") if li_votes > correy_votes and li_votes >khan_votes and li_votes > tooley_votes: winner = ("Khan") if tooley_votes > correy_votes and tooley_votes > li_votes and tooley_votes > khan_votes: winner = ("Khan") print("Election Results") print("------------------------------------------------------------------------------------") print(("Total Votes: ") + str(total_votes)) print("------------------------------------------------------------------------------------") print("Khan: " + "{:.2%}".format(khan_votes/total_votes) + " (" + str(khan_votes) + ")") print("Correy: " + "{:.2%}".format(correy_votes/total_votes) + " (" + str(correy_votes) + ")") print("Li: " + "{:.2%}".format(li_votes/total_votes) + " (" + str(li_votes) + ")") print("O'Tooley: " + "{:.2%}".format(tooley_votes/total_votes) + " (" + str(tooley_votes) + ")") print("------------------------------------------------------------------------------------") print("Winner: " + str(winner)) text_file = open("electrion_results.txt", "w") text_file.write("Election Results\n") text_file.write("-----------------------------------------------------------------\n") text_file.write(("Total Votes: ") + str(total_votes) + "\n") text_file.write("Khan: " + "{:.2%}".format(khan_votes/total_votes) + " (" + str(khan_votes) + ")\n") text_file.write("Correy: " + "{:.2%}".format(correy_votes/total_votes) + " (" + str(correy_votes) + ")\n") text_file.write("Li: " + "{:.2%}".format(li_votes/total_votes) + " (" + str(li_votes) + ")\n") text_file.write("O'Tooley: " + "{:.2%}".format(tooley_votes/total_votes) + " (" + str(tooley_votes) + ")\n") text_file.write("------------------------------------------------------------------------------------\n") text_file.write("Winner: " + str(winner))
5fbc8bd6aaf9faa5b685a6ee9149beb2413b20fc
hvauchar/Tkinter-Database-Management
/back.py
1,983
3.578125
4
import sqlite3 def connect(): conn=sqlite3.connect("polio.db") cur=conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTs polio (id INTEGER PRIMARY KEY , name TEXT , address TEXT , phone_number INTEGER, Age INTEGER , Dose TEXT , V_id INTEGER)") conn.commit() conn.close() def insert(name,address,phone_number,Age,Dose,V_id): from back import calculation conn=sqlite3.connect("polio.db") cur=conn.cursor() cur.execute("INSERT INTO polio VALUES (NULL, ?,?,?,?,?,?)",(name,address,phone_number,Age,Dose,V_id)) conn.commit() conn.close() view() def view(): conn=sqlite3.connect("polio.db") cur=conn.cursor() cur.execute("SELECT * FROM polio") row=cur.fetchall() conn.close() return row def search(name="",address="",phone_number="",Dose="",Age="",V_id=""): conn=sqlite3.connect("polio.db") cur=conn.cursor() cur.execute("SELECT * FROM polio WHERE name=? OR address=? OR phone_number=? OR Dose=? OR Age=? OR V_id=?",(name,address,phone_number,Dose,Age,V_id)) row=cur.fetchall() conn.close() return row def delete(id): conn=sqlite3.connect("polio.db") cur=conn.cursor() cur.execute("DELETE FROM polio where id=?",(id,)) conn.commit() conn.close() def update(id,name,address,phone_number,Dose,Age,V_id): from back import calculation conn=sqlite3.connect("polio.db") cur=conn.cursor() cur.execute("UPDATE polio SET name=? ,address=? , phone_number=? , Dose=? , Age=? , V_id=? where id=?",(name,address,phone_number,Dose,Age,calculation(Age,Dose),id)) conn.commit() conn.close() def calculation(Age,Dose): if Dose==("normal" or "NORMAL"): V_id=int(Age)*1500 return V_id elif Dose==("POLIO" or "polio"): V_id=int(Age)*1800 return V_id elif Dose==("HEPATITIES" or "hepstities"): V_id=int(Age)*2000 return V_id connect()
f6a9c5d9b288af2d37418834927a439c450d3cc0
lnmunhoz/courses
/Python Para Zumbis/Lista de Exercícios III/exercicio03_lucas-nogueira-munhoz_01.py
98
3.96875
4
n = int(input("n: ")) while n < 0 or n > 10: print("Numero Invalido") n = int(input("n: "))
325d470b5cb552b82a9500dc16d148f3c0fc947f
tyrelkostyk/CMPT145
/Ass_08/a8q4.py
1,675
4.09375
4
## Tyrel Kostyk, tck290, 11216033 ## CMPT145-04, Lab Section 04 ## a8q1.py import treenode as tn import treefunctions as tnfun ## NOTE: # I may have misinterpreted the question; I thought that an ordered node was only # ordered if the root was larger than the SUM of the values in the left subtree, # rather than all the values themselves (individually) and same idea for the right # side except less than... My mistake (at least it works tho :p) def ordered(tnode): """ :purpose: Determines if a tree is ordered (left substree < root < right substree) :params: tnode - treenode, already created :post-conditions: none :returns: True, if tnode is ordered. False otherwise """ # simple internal program that calculates sum of a treenode def sum(tnode): if tnode is None: return 0 else: return tn.get_data(tnode) + sum(tn.get_left(tnode)) + sum(tn.get_right(tnode)) if tnode is None: return True else: # assign current value val = tn.get_data(tnode) # check if the next child nodes are none; if so, ensure they aren't accounted for if tn.get_left(tnode) is None: left_sum = val - 1 else: left_sum = sum(tn.get_left(tnode)) if tn.get_right(tnode) is None: right_sum = val + 1 else: right_sum = sum(tn.get_right(tnode)) # if the current node is ordered, recursively check its child nodes if left_sum < val < right_sum: return ordered(tn.get_left(tnode)) and ordered(tn.get_right(tnode)) else: return False
cc2481540a9d2e073cb5580f0b834f3da1eaf03c
AAUCrisp/Python_Tutorials
/Mads/Intro_exercises_2/Exercise_6.py
267
3.75
4
list1 = ["John", "Jenny", "Barbara"] list2 = ["Green", "Red", "Blue"] Length = len(list1)-1 Length2 = len(list2)-1 tal = int(input('Indsæt tal mellem 0 og {} \n'.format(Length2))) def badfunction(): list1[Length] = list2[tal] print(list1) badfunction()
24df4895a44641801388f14a17b105ff0608f2ed
tstwine/PythonCodeChallenges
/prob3.py
457
4.21875
4
# Write a program that gives the user only three tries to guess the correct pin of the accont. tries = 1 #count = 1 #start off the count pin = 1201 userInput = int( input("Please enter your pin:") ) while userInput != pin and tries <= 3: userInput = int( input("Please re-enter your pin:") ) if userInput == pin: tries += 1 break else: tries += 1 if tries >= 3: print("You have exceeded your max tries.") else: print("Welcome person!!")
06fb505b1c09bab81a6014edd7037bda12cb1648
Mattnigma/Learning2Code
/Guess the Number Game.py
909
4.03125
4
#!/usr/bin/env python3 #importing stuff from random import seed from random import randint seed() highnumber=1000 chances=10 print("Guess the number between 1 and "+str(highnumber)+"! You have "+str(chances)+" chances!") guessvar = randint(1,highnumber) def get_valid_input(): stab=input("\n") while stab.isdigit() == False: stab=input("Invalid input, please try again\n") return int(stab) while chances > 0: stab=get_valid_input() chances-=1 if guessvar==stab: print("YOU WIN") chances=0 else: if chances==0: print("\nYou lose. The number was "+str(guessvar)+".") break elif stab>guessvar: print("\nToo high!") else: print("\nToo low!") if chances==1: print("\nLast chance!") else: print("Try again! You have "+str(chances)+" tries left!")
b3abf52708ddf77fa5b8e7841603bcacef1807de
ssbagalkar/PythonDataStructuresPractice
/DP-aditya-verma-playlist/MCM/03_evaluate_expression_to_true_boolean_parenthesization.py
4,009
4.25
4
""" Problem Statement: Evaluate Expression To True-Boolean Parenthesization Recursion Given a boolean expression with following symbols. Symbols 'T' --- true 'F' --- false And following operators filled between symbols Operators & ---boolean AND | --- boolean OR ^ --- boolean XOR Count the number of ways we can parenthesize the expression so that the value of expression evaluates to true. Example: Input: symbol[] = {T, F, T} operator[] = {^, &} Output: 2 The given expression is "T ^ F & T", it evaluates true in two ways "((T ^ F) & T)" and "(T ^ (F & T))" Youtube link --> https://www.youtube.com/watch?v=pGVguAcWX4g&list=PL_z_8CaSLPWekqhdCPmFohncHwz8TY2Go&index=39 Useful link for code - https://www.youtube.com/watch?v=7Gk36fHV38E&t=854s Geeks Link --> https://www.geeksforgeeks.org/boolean-parenthesization-problem-memo-37/ Complexity: Time --> Space --> Verified in Leetcode/InterviewBits--> No """ def solve_recursion(s: str, i: int, j: int, is_true: bool): if i > j: return 0 if i == j: if is_true: return 1 if s[i] == 'T' else 0 else: return 1 if s[i] == 'F' else 0 num_ways = 0 for k in range(i + 1, j, 2): left_true = solve_recursion(s, i, k - 1, is_true=True) left_false = solve_recursion(s, i, k - 1, is_true=False) right_true = solve_recursion(s, k + 1, j, is_true=True) right_false = solve_recursion(s, k + 1, j, is_true=False) if s[k] == '&': if is_true is True: num_ways += left_true * right_true else: num_ways += (left_false * right_false) + (left_false * right_true) + (left_true * right_false) elif s[k] == '|': if is_true is True: num_ways += (left_false * right_true) + (left_true * right_false) + (left_true * right_true) else: num_ways += left_false * right_false elif s[k] == '^': if is_true is True: num_ways += (left_false * right_true) + (left_true * right_false) else: num_ways += (left_false * right_false) + (left_true * right_true) return num_ways # this geeks for geeks is giving me wrong answer ??? def solve_memoization(s: str, i: int, j: int, is_true: int, memo): if i > j: return 0 if i == j: if is_true == 1: return 1 if s[i] == 'T' else 0 else: return 1 if s[i] == 'F' else 0 if memo[i][j][is_true] != -1: return memo[i][j][is_true] temp_ans = 0 for k in range(i + 1, j, 2): if memo[i][k - 1][1] != -1: left_true = memo[i][k - 1][1] else: # Count number of True in left Partition left_true = solve_memoization(s, i, k - 1, 1, memo) if memo[i][k - 1][0] != -1: left_false = memo[i][k - 1][0] else: # Count number of False in left Partition left_false = solve_memoization(s, i, k - 1, 0, memo) if memo[k + 1][j][1] != -1: right_true = memo[k + 1][j][1] else: # Count number of True in right Partition right_true = solve_memoization(s, k + 1, j, 1, memo) if memo[k + 1][j][0] != -1: right_false = memo[k + 1][j][0] else: # Count number of False in right Partition right_false = solve_memoization(s, k + 1, j, 0, memo) # Evaluate AND operation if s[k] == '&': if is_true == 1: temp_ans = temp_ans + left_true * right_true else: temp_ans = temp_ans + left_true * right_false + left_false * right_true + left_false * right_false # Evaluate OR operation elif s[k] == '|': if is_true == 1: temp_ans = temp_ans + left_true * right_true + left_true * right_false + left_false * right_true else: temp_ans = temp_ans + left_false * right_false # Evaluate XOR operation elif s[k] == '^': if is_true == 1: temp_ans = temp_ans + left_true * right_false + left_false * right_true else: temp_ans = temp_ans + left_true * right_true + left_false * right_false memo[i][j][is_true] = temp_ans return temp_ans my_str = "T|T&F^T" n = len(my_str) memo = [[[-1 for _ in range(2)] for _ in range(n + 1)] for _ in range(n + 1)] print(solve_memoization(my_str, 0, n - 1, 1, memo)) print(solve_recursion(my_str, 0, n - 1, True))
c86445a912d7b1cc8c62b58b0834d20f3c63aee1
sindhugudivada/algorithms
/coding_dojo/algos/chapter1_fundamentals/jan-29-2018/linkedlist_toarray.py
429
3.53125
4
from node import Node def createlist(arr): dummy=Node(-1) current=dummy count=0 for i in arr: current.next=Node(i) current=current.next count=count+1 return (dummy.next,count) def createarray(ll): head,count=ll arr=[0]*count while(head): arr[count-1]= head.data count=count-1 head=head.next return arr if __name__=='__main__': abc = createarray(createlist([1,2,3,4])) print abc
82ec22c60a696d9ba16c289fd0eb1b46458672fd
ceden95/self.py
/for_loop2.py
819
4.125
4
#the program creates a list of two numbers- the first is the number of numbers, the second is the number of letters.) def main(): my_str = input("type a sentence with mumbers and letters: ") count_list = numbers_letters_count(my_str) print(count_list) def numbers_letters_count(my_str): """the function return list of number of numbers and number of letters fron my_str :param my_str: str of letters and numbers :my_str type: str :return: list of 2 numbers :rtype: list""" numberCounter = 0 for letter in my_str: if letter.isnumeric() == True: numberCounter += 1 else: continue strlen = len(my_str) letterlen = strlen - numberCounter return ([numberCounter] + [letterlen]) main()
52f507f262a7f29d7f4e7a6f3878f5f5d5e08b4d
jac08h/CurrencyConverter
/main.py
1,698
3.515625
4
from typing import Optional, Tuple from urllib import request from urllib.error import HTTPError import json ConversionData = Tuple[float, str, str] with open("programming/python/currency_converter/freecurrencyapi_key.txt") as fp: key = fp.read().strip() def parse(query: str) -> Optional[ConversionData]: parts = query.split() if len(parts) != 4: print("Invalid query.") return amount, old_currency, to, new_currency = parts if to != "to" or len(old_currency) != 3 or len(new_currency) != 3: print("Invalid query.") return try: float_amount = float(amount) except ValueError: print("Invalid amount.") return return float_amount, old_currency.upper(), new_currency.upper() def convert(data: ConversionData) -> Optional[float]: amount, base, new = data url = f"https://freecurrencyapi.net/api/v1/rates?base_currency={base}&apikey={key}" req = request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) try: api_data = json.loads(request.urlopen(req).read()) except HTTPError: print("Invalid base currency.") return assert len(api_data["data"]) for date, rates in api_data["data"].items(): try: conversion_rate = rates[new] except KeyError: print("Invalid new currency.") return return conversion_rate * amount def loop() -> None: while True: data = parse(input()) if data is None: continue converted = convert(data) if converted is None: continue print(f"{converted:.2f} {data[2]}") if __name__ == '__main__': loop()
f3de14b6c24bbc20f2cbb76dfb1b04d2d19d0837
VirenS13117/Reinforcement-Learning
/Ex0/Assignment1/Simulation.py
2,788
3.9375
4
from Assignment1 import Action, State from random import random import matplotlib.pyplot as plt class Simulation: def __init__(self, grid, policy): self.grid = grid self.policy = policy def plot_cumulative_rewards(self, trial_rewards): average_bar = [] for i in range(len(trial_rewards[0])): sum_rewards = 0 for j in range(10): sum_rewards += trial_rewards[j][i] average_bar.append(sum_rewards / len(trial_rewards)) for i in trial_rewards: plt.plot(i, linestyle='dashed') plt.plot(average_bar, linewidth=3, label=self.policy.name) plt.ylabel('Cumulative reward') plt.xlabel('Steps') plt.legend() plt.show() def transition(self, current_state, action): print("simulating") decision_prob = random() print("decision probability : ", decision_prob) if decision_prob < self.grid.prob: current_state.move(action.action_list[action.action]) elif self.grid.prob < decision_prob < self.grid.prob + (1 - self.grid.prob) / 2: current_state.move(action.get_left_perpendicular()) else: current_state.move(action.get_right_perpendicular()) reward = 0 print("current state : ", current_state.x, " ", current_state.y) if self.grid.is_target(current_state): current_state.__setstate__(self.grid.source[0], self.grid.source[1]) reward = 1 else: reward = self.policy.lookup[current_state.x][current_state.y][action.action] return current_state, reward def simulate(self, num_trials=10, num_steps=10000): trial_rewards = [] for trials in range(num_trials): curr_state = State.State(self.grid.source[0], self.grid.source[1], self.grid) steps_reward = [] cum_sum = 0 for steps in range(num_steps): curr_state_x = curr_state.x curr_state_y = curr_state.y action = self.policy.get_action(curr_state) print("action : ", action) action_object = Action.Action(action) curr_state, reward = self.transition(curr_state, action_object) cum_sum += reward steps_reward.append(cum_sum) if self.policy.name == "Learned": # self.policy.lookup[curr_state_x][curr_state_y][action] = 0.01*reward self.policy.lookup[curr_state_x][curr_state_y][action] \ = max(self.policy.lookup[curr_state_x][curr_state_y][action], 0.01*reward) trial_rewards.append(steps_reward) self.plot_cumulative_rewards(trial_rewards)
c27eaf38175745a2e7e6eb4999c39f950b84c257
kharyal/leetcode
/binary_search/binary_search.py
600
3.609375
4
class Solution(): def binary_search(self, arr, num, start, end): if len(arr)==0: return -1 if end == start and arr[start]==num: return start elif end == start: return -1 if end<start: return -1 mid = (start+end)//2 if num == arr[mid]: return mid elif num<arr[mid]: return self.binary_search(arr, num, start, mid) else: return self.binary_search(arr, num, mid+1, end) sol = Solution() print(sol.binary_search([1,2,3,4,7,9,10], 9, 0, 6))
4f16ff2a5eaf87189ce302db1b26b45bf240c0e9
abhinavsp0730/python-ds
/data_structures/strings/swap_commas_and_dots.py
525
3.53125
4
""" Question : Swap commas and dots in a String Examples: Input : 14, 625, 498.002 Output : 14.625.498, 002 """ # This propler can be solved via two popular ways # Using replace() def Replace(str1): str1 = str1.replace(', ', 'third') str1 = str1.replace('.', ', ') str1 = str1.replace('third', '.') return str1 string = "14, 625, 498.002" print(Replace(string)) # Using maketrans and translate() def Replace(str1): maketrans = str1.maketrans final = str1.translate(maketrans(', .', '., ')) return final
ae21d3f933cba836a7089cf6f0cd61a781250be5
88b67391/AlgoSolutions
/python3-leetcode/leetcode977-squares-of-a-sorted-array.py
336
3.765625
4
from typing import List class Solution: def sortedSquares(self, A: List[int]) -> List[int]: B = sorted(A, key = abs) # sort by absolute values res = list() for elem in B: res.append(elem*elem) return res # below is testing sol = Solution() print(sol.sortedSquares([-4,-2, 3,6]))
b2e2d09f20264bf2d79aeaef7501ec6227a36a1c
WINKAM/Classification-Metrics-Manager
/classification_mm/classification_mm.py
15,548
3.609375
4
def precision(tp_count, fp_count): """Computes Precision (Positive Predictive Values, PPV). Precision is the fraction of examples labeled positive that are correctly classified among true positive and false positive classifier results. Precision = tp_count / (tp_count + fp_count). If tp_count of fp_count are not positive numbers or sum of them is 0, then the function returns 0. Args: tp_count: A count of true positive classifier results (ground truth class label is positive and classifier output is positive). fp_count: A count of false positive classifier results (ground truth class label is negative and classifier output is positive). Returns: Precision (float). """ return a_ab(tp_count, fp_count) def recall(tp_count, fn_count): """Computes Recall (True Positive Rate, TPR, Sensitivity). Recall is the fraction of examples labeled positive that are correctly classified among the total number of positives examples. Recall = tp_count / (tp_count + fn_count). If tp_count of fn_count are not positive numbers or sum of them is 0, then the function returns 0. Args: tp_count: A count of true positive classifier results (ground truth class label is positive and classifier output is positive). fn_count: A count of false negative classifier results (ground truth class label is positive and classifier output is negative). Returns: Recall (float). """ return a_ab(tp_count, fn_count) def specificity(tn_count, fp_count): """Computes Specificity (True Negative Rate, TNF, 1.0 - False Positive Rate). Recall is the fraction of examples labeled negative that are correctly classified among the total number of negative examples. Recall = tn_count / (tn_count + fp_count). If tn_count of fp_count are not positive numbers or sum of them is 0, then the function returns 0. Args: tn_count: A count of true negative classifier results (ground truth class label is negative and classifier output is negative). fp_count: A count of false positive classifier results (ground truth class label is negative and classifier output is positive). Returns: Specificity (float). """ return a_ab(tn_count, fp_count) def accuracy(tp_count, fp_count, fn_count, tn_count): """Computes Accuracy (ACC). Accuracy is the fraction of true classifier results (both true positives and true negatives) among the total number of examples (both positives and negatives). Recall = (tp_count + tn_count) / (tp_count + tn_count + fp_count + fn_count). If the sum of the arguments less than zero, the function returns 0. Args: tp_count: A count of true positive classifier results (ground truth class label is positive and classifier output is positive). fp_count: A count of false positive classifier results (ground truth class label is negative and classifier output is positive). fn_count: A count of false negative classifier results (ground truth class label is positive and classifier output is negative). tn_count: A count of true negative classifier results (ground truth class label is negative and classifier output is negative). Returns: Accuracy (float). """ summ = (tp_count + tn_count + fp_count + fn_count) return (float(tp_count + tn_count) / (tp_count + tn_count + fp_count + fn_count)) if summ > 0 else 0 def f_score(tp_count, fp_count, fn_count, beta): """Computes F-score (F-measure). F-score is a measure of classification quality taking into account both Precision and Recall. F-score = (1 + beta^2) * (Precision * Recall) / (beta^2 * Precision + Recall). Args: tp_count: A count of true positive classifier results (ground truth class label is positive and classifier output is positive). fp_count: A count of false positive classifier results (ground truth class label is negative and classifier output is positive). fn_count: A count of false negative classifier results (ground truth class label is positive and classifier output is negative). beta: A Precision-Recall balance parameter, so Recall is beta times more important than Precision. beta --> 0, F-beta --> Precision; beta --> infinite, F-beta --> Recall. Returns: F-score (float) """ return a_ab((1 + beta**2) * float(tp_count), beta**2 * fn_count + fp_count) def f1_score(tp_count, fp_count, fn_count): """Computes F1-score (F1-measure, balanced F-score, F-score with beta = 1). F1-score is a measure of classification quality taking into account both Precision and Recall. F1-score = 2 * (Precision * Recall) / (Precision + Recall). Args: tp_count: A count of true positive classifier results (ground truth class label is positive and classifier output is positive). fp_count: A count of false positive classifier results (ground truth class label is negative and classifier output is positive). fn_count: A count of false negative classifier results (ground truth class label is positive and classifier output is negative). Returns: F1-score (float). """ return f_score(tp_count, fp_count, fn_count, 1.) def a_ab(a, b): """Computes a / (a + b) for positive numbers. Args: a: A dividend and the first added of a divider. b: The second added of the divider. Returns: The result of calculation of a and b are positive numbers; if a or b is None, it returns none; if a or b is not positive numbers or a + b == 0, it returns 0. """ if a == None or b == None: return None return (float(a) / (a + b)) if (a >= 0 and b >= 0 and a + b > 0) else 0. def compare_2_class(ground_truth, classifier_output): """Compares list of ground truth class labels and list of classifier outputs. Class labels: 1 is positive. 0 is negative. -1 is "Don't Care" class, examples with "Don't Care" label are ignored, so it doesn't lead to true positive, false positive, true negative or false negative. Args: ground_truth: A list or array of ground truth class labels, e.g. [1, 1, -1, 0, 1, 0, -1, 0]. classifier_output: A list or array of classifier outputs, e.g. [0, 1, 1, 1, 0, 1, 1, 0]. Returns: Object of class MetricManager, to get true positive count, false positive count, false negative count, true negative count, accuracy, recall, precision, specificity. """ # if input is numpy array, use numpy to optimize computing is_np_used = ('numpy' in str(type(ground_truth))) if is_np_used: diff = (ground_truth + 3 * classifier_output).tolist() tp_count = diff.count(4) tn_count = diff.count(0) fp_count = diff.count(3) fn_count = diff.count(1) else: tp_count, tn_count, fp_count, fn_count = (0, 0, 0, 0) for gt, mo in zip(ground_truth, classifier_output): if not gt == -1: # is't Don't Care if gt == 1: # positive if mo == gt: tp_count += 1 else: fn_count += 1 else: # negative if mo == gt: tn_count += 1 else: fp_count += 1 return MetricManager(tp_count, fp_count, fn_count, tn_count) class MetricManager: """A class to store basis classification quality metrics and to get metrics such as precision, recall, etc. Attributes: tp_count: A count of true positive classifier results (ground truth class label is positive and classifier output is positive). fp_count: A count of false positive classifier results (ground truth class label is negative and classifier output is positive). fn_count: A count of false negative classifier results (ground truth class label is positive and classifier output is negative). tn_count: A count of true negative classifier results (ground truth class label is negative and classifier output is negative). """ def __init__(self, tp_count, fp_count, fn_count, tn_count = None): """Create a new MetricManager Args: tp_count: A count of true positive classifier results (ground truth class label is positive and classifier output is positive). fp_count: A count of false positive classifier results (ground truth class label is negative and classifier output is positive). fn_count: A count of false negative classifier results (ground truth class label is positive and classifier output is negative). tn_count: A count of true negative classifier results (ground truth class label is negative and classifier output is negative). Returns: Object of class MetricManager. """ self.tp_count = tp_count self.fp_count = fp_count self.fn_count = fn_count self.tn_count = tn_count @property def precision(self): """Computes Precision (Positive Predictive Values, PPV). Precision is the fraction of examples labeled positive that are correctly classified among true positive and false positive classifier results. Precision = tp_count / (tp_count + fp_count). If tp_count of fp_count are not positive numbers or sum of them is 0, then the function returns 0. Returns: Precision (float). """ return a_ab(self.tp_count, self.fp_count) @property def recall(self): """Computes Recall (True Positive Rate, TPR, Sensitivity). Recall is the fraction of examples labeled positive that are correctly classified among the total number of positives examples. Recall = tp_count / (tp_count + fn_count). If tp_count of fn_count are not positive numbers or sum of them is 0, then the function returns 0. Returns: Recall (float). """ return a_ab(self.tp_count, self.fn_count) @property def specificity(self): """Computes Specificity (True Negative Rate, TNF, 1.0 - False Positive Rate). Recall is the fraction of examples labeled negative that are correctly classified among the total number of negative examples. Recall = tn_count / (tn_count + fp_count). If tn_count of fp_count are not positive numbers or sum of them is 0, then the function returns 0. Returns: Specificity (float). """ return a_ab(self.tn_count, self.fp_count) @property def accuracy(self): """Computes Accuracy (ACC). Accuracy is the fraction of true classifier results (both true positives and true negatives) among the total number of examples (both positives and negatives). Recall = (tp_count + tn_count) / (tp_count + tn_count + fp_count + fn_count). If the sum of the arguments less than zero, the function returns 0. Returns: Accuracy (float). """ return accuracy(self.tp_count, self.fp_count, self.fn_count, self.tn_count) if not self.tn_count == None else None @property def f1_score(self): """Computes F1-score (F1-measure, balanced F-score, F-score with beta = 1). F1-score is a measure of classification quality taking into account both Precision and Recall. F1-score = 2 * (Precision * Recall) / (Precision + Recall). Returns: F1-score (float). """ return f1_score(self.tp_count, self.fp_count, self.fn_count) def f_score(self, beta): """Computes F-score (F-measure). F-score is a measure of classification quality taking into account both Precision and Recall. F-score = (1 + beta^2) * (Precision * Recall) / (beta^2 * Precision + Recall). Args: beta: A Precision-Recall balance parameter, so Recall is beta times more important than Precision. beta --> 0, F-beta --> Precision; beta --> infinite, F-beta --> Recall. Returns: F-score (float) """ return f_score(self.tp_count, self.fp_count, self.fn_count, beta) def __str__(self): return 'TP = ' + str(self.tp_count) + '; FP = ' + str(self.fp_count) + '; FN = ' + str(self.fn_count) + (('; TN = ' + str(self.tn_count)) if not self.tn_count == None else '') def __add__(self, other): m = MetricManager(self.tp_count, self.fp_count, self.fn_count, self.tn_count) m.tp_count += other.tp_count m.fp_count += other.fp_count m.fn_count += other.fn_count m.tn_count = (self.tn_count + other.tn_count) if not self.tn_count == None and not other.tn_count == None else None return m def pr_auc(precision_recall_list): """Computes Area Under Precision-Recall Curve (Precision-Recall AUC). Args: precision_recall_list: A Precision-Recall Curve encoded as a list of pairs Precision value, Recall value. Returns: An AUC of a Precision-Recall Curve. """ sorted_pr_list = sorted(precision_recall_list, key=lambda x: (x[1], -x[0])) sorted_pr_list = [(1., 0.)] + sorted_pr_list + [(0., 1.)] auc = 0 for i in range(1, len(sorted_pr_list)): auc += (sorted_pr_list[i][0] + 0.5 * (sorted_pr_list[i][0] - sorted_pr_list[i -1][0])) * (sorted_pr_list[i][1] - sorted_pr_list[i - 1][1]) return auc def average_precision(precision_recall_list): """Computes Average Precision (AP). Args: precision_recall_list: A Precision-Recall Curve encoded as a list of pairs Precision value, Recall value. Returns: A Average Precision value """ sorted_pr_list = sorted(precision_recall_list, key=lambda x: (x[1], -x[0])) sorted_pr_list = [(1., 0.)] + sorted_pr_list + [(0., 1.)] ap = 0 for i in range(1, len(sorted_pr_list)): ap += sorted_pr_list[i][0] * (sorted_pr_list[i][1] - sorted_pr_list[i - 1][1]) return ap def roc_auc(fpr_tpr_list): """Computes Area Under Receiver Operating Characteristics Curve (AUC ROC, AUROC). Args: fpr_tpr_list: A True Positive Rate - False Positive Rate Curve encoded as a list of pairs TPR value, FPR value. Returns: A AUC of a Receiver Operating Characteristics Curve. """ sorted_roc_list = sorted(fpr_tpr_list, key=lambda x: (x[0], x[1])) sorted_roc_list = [(0., 0.)] + fpr_tpr_list + [(1., 1.)] auc = 0 for i in range(1, len(sorted_roc_list)): print(sorted_roc_list[i - 1]) print(sorted_roc_list[i]) print((sorted_roc_list[i][0] - sorted_roc_list[i - 1][0]) * (sorted_roc_list[i][1] + 0.5 * (sorted_roc_list[i - 1][1] - sorted_roc_list[i][1]))) print(' ') auc += (sorted_roc_list[i][0] - sorted_roc_list[i - 1][0]) * (sorted_roc_list[i][1] + 0.5 * (sorted_roc_list[i - 1][1] - sorted_roc_list[i][1])) return auc
7083ba87dd5e685f61f3dbb89e9c3528f674ee18
HebertSam/PythonAssignments
/PythonBasic/findChar.py
224
3.6875
4
def findChar (x, y): newList = [] for i in x: if y in i: newList.append(i) print newList word_list = ['hello', 'world', 'my', 'name', 'is', 'Anna'] char = 'o' findChar(word_list, char)
6695096f785b015491cf9c6241bb7d8f3d4a0bb5
mcleavey/insight
/src/main.py
10,868
3.59375
4
from user import * from datetime import datetime from collections import OrderedDict import sys, logging def translate_time(date, time): """ Translates date and time to timestamp Inputs: date: string in year-month-day format time: string in hour:minute:second format Output: datetime timestamp """ return datetime.strptime(date + ' ' + time, '%Y-%m-%d %H:%M:%S').timestamp() def get_categories_to_index(line): """ Takes the first line of the csv file and outputs a dictionary translating each column heading name to an index ie: "ip" : 0 "date" : 1 "time" : 2 Input: line: string Output: categories_to_index: dictionary mapping column heading to index """ try: categories_to_index = {category: i for i, category in enumerate(line.strip().split(',')[:-1])} except: assert False, f'Error reading CSV file header: {line}' categories_to_index = {} # Check if the header has all the items we need # I don't see a reason we actually need cik/accession/extention for this program, # since we're never actually asked for the filename, but I'm leaving it here as an # indicator that the file has properly formed requests. required = ['ip', 'date', 'time', 'cik', 'accession', 'extention'] valid_file = True # Check if each required element is in the csv file for r in required: assert r in categories_to_index.keys(), f'{r} missing from CSV header' return categories_to_index def get_info_from_line(line, categories_to_index): """ Pull necessary info from csv file single line Inputs: line: string representing the current line of the csv file categories_to_index: dictionary indicating the order of the elements of the line Output: valid_line: bool if the line is in a valid format current_time_stamp: current time as datetime timestamp date_time: current time as string ip: IP address as string """ try: # Split line by commas items = line.strip().split(',')[:-1] # If line doesn't have the expected number of elements, mark it invalid since we don't # know how/why it is mis-formed, and the ip address may be in the wrong spot and meaningless valid_line = len(items) == len(categories_to_index.keys()) current_time_stamp = translate_time(items[categories_to_index['date']], items[categories_to_index['time']]) date_time = items[categories_to_index['date']] + ' ' \ + items[categories_to_index['time']] ip = items[categories_to_index['ip']] except: valid_line = False current_time_stamp = 0 date_time = "" ip = "" return valid_line, current_time_stamp, date_time, ip def process_one_line(line, categories_to_index, prev_time_stamp, inactivity, output_file, first_request_order, expiry_to_ip, current_users): """ Take in one line. Create or update the user session for that line, and also output all the user sessions that have expired. Inputs: line: string representing the current line of the csv file categories_to_index: dictionary indicating the order of the elements of the line prev_time_stamp: time stamp of previous line inactivity: time in seconds after which a session is considered done output_file: file opened for appending output data first_request_order: int current index for this request (increases by 1 for each input line) expiry_to_ip: OrderedDict mapping expiry time to a list of IP addresses due to expire at that time current_users: dictionary mapping IP address to UserSession (for IP address in an active session) Output: current_time_stamp: time stamp of the current line (also calls output_expired_users to write the expired user sessions to file) """ # Check if this line is valid, and get the current time stamp, date-time as a string, # and ip address of the current request valid_line, current_time_stamp, date_time, ip = get_info_from_line(line, categories_to_index) # Exit function if this line is not valid if not valid_line: logging.warning(f'Skipping invalid file line: {line.strip()}') return prev_time_stamp if (current_time_stamp<prev_time_stamp): logging.warning(f'Skipping invalid file line that went backwards in time: {line.strip()}') return prev_time_stamp # Check if this is a new time stamp, compared with previous request if current_time_stamp>prev_time_stamp: # Initialize empty list to hold all IPs expiring at this new time expiry_to_ip[current_time_stamp+inactivity] = [] # Now check which users should be output to file (unless prev_time_stamp is -1, # indicating this is the first time step) if prev_time_stamp!=-1: output_expired_users(current_time_stamp, prev_time_stamp, output_file, expiry_to_ip, current_users) # Check if this is an ongoing session if ip in current_users: # Remove this from list of sessions expiring at old expiry time expiry_to_ip[current_users[ip].expiry_time].remove(ip) # Update user session current_users[ip].new_request(current_time_stamp, date_time, inactivity) # Add to list of sessions expiring "inactivity" seconds from now expiry_to_ip[current_users[ip].expiry_time].append(ip) else: # Create new user session current_users[ip] = UserSession(ip, date_time, current_time_stamp, first_request_order, inactivity) # Add to list of sessions xpiring "inactivity" seconds from now expiry_to_ip[current_time_stamp+inactivity].append(ip) return current_time_stamp def output_expired_users(current_time_stamp, prev_time_stamp, output_file, expiry_to_ip, current_users): """ Outputs the user sessions that have timed out between prev_time_stamp and current_time_stamp Inputs: prev_time_stamp: time stamp of previous line current_time_stamp: time stamp of this line output_file: file opened for appending output data expiry_to_ip: OrderedDict mapping expiry time to a list of IP addresses due to expire at that time current_users: dictionary mapping IP address to UserSession (for IP address in an active session) Output: for each expired session, writes one line to output_file """ num_to_pop = 0 for (expiry_time, ips) in expiry_to_ip.items(): if expiry_time<current_time_stamp: user_sessions_finished = [current_users[ip] for ip in ips] for us in sorted(user_sessions_finished): output_file.write(us.output()) del current_users[us.ip] num_to_pop+=1 else: break for i in range(num_to_pop): expiry_to_ip.popitem(last=False) def alt_output_expired_users(current_time_stamp, prev_time_stamp, output_file, expiry_to_ip, current_users): """ This function is not used in the program. I wrote to Insight with a question about a corner case that wasn't described in the problem description. They told me to select one answer (which is in output_expired_users). This is the solution for the other answer. I've documented this more clearly in my README """ users_timed_out = [] num_to_pop = 0 for (expiry_time,ips) in expiry_to_ip.items(): if expiry_time < current_time_stamp: users_timed_out.extend(ips) num_to_pop+=1 else: break for i in range(num_to_pop): expiry_to_ip.popitem(last=False) for ip in sorted(users_timed_out): output_file.write(current_users[ip].output()) del current_users[ip] def list_remaining(output_file, current_users): """ At end of CSV file, output all the remaining users to output_file Inputs: output_file: file opened for appending output data current_users: dictionary mapping IP address to UserSession (for IP address in an active session) Outputs: writes one line to output_file for each of the remaining user sessions """ # Collect all the users still in the currentUsers dictionary remaining_users = [current_users[ip] for ip in current_users] # Order them by initial request time and output to file for u in sorted(remaining_users): output_file.write(u.output()) def process_all_files(csv_file, inactivity_file, output_file): """ Called directly from main(), with the arguments coming from the command line Input: csv_file: location of the file holding all the EDGAR input data inactivity_file: location of the file holding the inactivity time output_file: location to write output Output: output_file: creates (or clears) file and then writes all results to it """ # Grab the inactivity time (after this amount of time, # a user is automatically assumed to have logged off) with open(inactivity_file) as f: inactivity = int(f.readline()) # Create or clear the output file output=open(output_file, "w+") output.close() current_users = {} # key = IP # value = UserSession (holds ip, times, file count for each user) first_request_order = 0 # Tracks order requests arrive (for determining order to output) expiry_to_ip = OrderedDict() # key = expiry time (as timestamp) # value = list of IPs due to expire at that time # Open the output file to append one line at a time with open(output_file, "a") as output: # Open the csv file to read with open(csv_file) as csv: # Look at the first line of the file. Make sure it has the heading # categories we need (otherwise this fails an assertion), and then # return a dictionary with category_title:index (ie "ip":0) categories_to_index = get_categories_to_index(csv.readline()) # Read first data line line = csv.readline() # Initialize previous time stamp (set this negative, so that first line of # file will register as a new time stamp, later than the previous one) prev_time_stamp = -1 # Go through the csv file line by line, exit loop at EOF while line: # Feed this line to our program. If the line isn't valid, it will return the same # time stamp as the previous line. prev_time_stamp = process_one_line(line, categories_to_index, prev_time_stamp, inactivity, output, first_request_order, expiry_to_ip, current_users) # It's ok that we increment even if it's an invalid line, # since we only ever care about the order. first_request_order+=1 # Read new line and continue loop line = csv.readline() # At the end of the CSV file, output all the still active users list_remaining(output, current_users) if __name__ == "__main__": process_all_files(sys.argv[1], sys.argv[2], sys.argv[3])
1febd9845413e4f85f31417e6b45260666a771e2
KGeetings/CMSC-115
/In Class/Palindrome.py
388
3.984375
4
def cleanUp(x): x = x.lower() for punc in " ,.!@#$%^&*()-=_+{}[]|;:'": x = x.replace(punc, "") return x def isPalindrome(s): s = cleanUp(s) if s == s[::-1]: return True else: return False a = input("What is your word? ") if isPalindrome(a): print("Yay! Your word is a palindrome.") else: print("Nope. Not a palindrome.")
80459809491d2a2602dd63f5e33314808e32ac44
katerhydron/PYTHON
/HelloWorld.py
1,535
4.28125
4
#!/usr/bin/env python #my first python scrit def wrapper(numberOfWordsInLine): #my first python scrit multiplier = 10 print "Hello World"*multiplier print ("the world" " " "is beatutiful") print (2.3 + 8) #printing strings first = "This" second = " Is" third = " Fucking" forth = " Awesome" print ("%s%s%s%s") % (first,second,third,forth) #printing numbers one = 1 two = 2 three = 3 print ("%d...%d...%d...GO!") % (one,two,three) #some logic in printing print ("To! Python! Is it true that 5>2?") logic = 5 > 2 print (logic) print ("-"*75) #putting shit inside other shit string = "Some string with '%s' sting inside" % "string" print "\nYo! I put you a %r inside your string so you can string while you string yo!" % string formatter = "\n %r %r %r %r" print formatter % ("big", "city", "lights", 123) #input = raw_input() #print (input) Text = """When you typed raw_input() you were typing the ( and ) characters which are parenthesis. This is similar to when you used them to do a format with extra variables, as in "%s %s" % (x, y). For raw_input you can also put in a prompt to show to a person so they know what to type.""" #print Text.count array = [] string1 = " " numberOfWordsInLine = 6 begining = 0 end = numberOfWordsInLine for i in Text: string1 = string1+i if i==" ": array.append(string1) string1 = "" for i in range(0,len(array)): if i == end: print ' '.join((array[begining:end])) begining = end end += numberOfWordsInLine
381e20e3433a2b7edbc2dfcd1976184320b8ac58
0kVegas/Python-projects
/Failed hangman.py
1,775
4.09375
4
# -----Imports----- import random # -----Global Variables------ global attempt_count global guess_letters global correct_letters global wrong_letters global wrong_letter_guess_count # -----Potential Words----- potential_words = { 1: 'cat', 2: 'dog', 3: 'bird', 4: 'banana', 5: 'animal', 6: 'location' } # -----Lists----- basic = [1, 2, 3, 4, 5, 6] # -----Word Generator----- list_num = random.randint(1, 7) word = potential_words[list_num] # -----Replacing System----- def word_replace(replace): word_display = "" for letter in replace: if letter in 'abcdefghijklmnopqrstuvwxyz': word_display = word_display + '_' else: word_display = word_display + letter return word_display correct = word_replace(word) # -----Right Words----- def right_words(guess): global correct for letter in guess: if letter in word: correct = correct + guess else: correct = correct return correct # -----Game Display----- def display(): if wrong_letter_guess_count == 0: print("") print(correct) elif wrong_letter_guess_count == 1: print("0") print(correct) elif wrong_letter_guess_count == 2: print('0') print('|') print(correct) elif wrong_letter_guess_count == 3: print(' 0') print('/|') print(correct) elif wrong_letter_guess_count == 4: print(' 0') print('/|\ ') print(correct) elif wrong_letter_guess_count == 5: print(' 0') print('/|\ ') print('/') print(correct) elif wrong_letter_guess_count == 6: print(' 0') print('/|\ ') print('/ \ ') print(correct)
3f936e5b556510ab35efa0898a83bce0cabeb5b3
tripathysamapika5/dsa
/linked_list/doublyLinkedList.py
5,336
4.09375
4
class Node: def __init__(self, value): self.value = value self.prev = None self.next = None class DoublyLinkedList: def __init__(self): self.__size = 0 self.__head = None self.__tail = None def insertStart(self, item): ''' This method inserts an item at the start of linkedlist''' newNode = Node(item) if not self.__head: self.__head = newNode self.__tail = self.__head else: newNode.next= self.__head self.__head.prev = newNode self.__head = newNode self.__size += 1 print("Inserted at start : {}".format(item)) def insertEnd(self, item): ''' This method inserts an item at the end of the linked list''' newNode = Node(item) if not self.__head: self.__head = newNode self.__tail = self.__head else: self.__tail.next = newNode newNode.prev = self.__tail self.__tail = newNode self.__size += 1 print("Inserted at end : {}".format(item)) def remove(self, item): ''' This method removes an node from the linked list if the input matches its data value''' if not self.__head: print("Underflow") elif self.__head == self.__tail and self.__head.value == item: self.__head = None self.__tail = None self.__size -= 1 print("Removed : {}".format(item)) elif self.__head.value == item: self.__head = self.__head.next self.__head.prev = None self.__size -= 1 print("Removed : {}".format(item)) elif self.__tail.value == item: self.__tail = self.__tail.prev self.__tail.next = None self.__size -= 1 print("Removed : {}".format(item)) else: currentNode = self.__head.next prevNode = self.__head while(currentNode): if(currentNode.value == item): prevNode.next = currentNode.next currentNode.next.prev = prevNode self.__size -= 1 print("Removed : {}".format(item)) break prevNode = currentNode currentNode = currentNode.next def traverse(self): ''' This method traverses each node of the lonkedlist ''' if not self.__head: print("Underflow") else: currentNode = self.__head final_str = "DoublyLinkedList : " while(currentNode): final_str= final_str + ' ' + str(currentNode.value) currentNode = currentNode.next print(final_str) def search(self, item): ''' This method returns true if a item is present in the linkedlist else returns false ''' currentNode = self.__head while(currentNode): if currentNode.value == item: return True currentNode = currentNode.next return False def sort(self): ''' This method sorts the items in the linkedlist in ascending order ''' if not self.__head: pass else: currentNode = self.__head while(currentNode): indexNode = currentNode.next while(indexNode): if indexNode.value < currentNode.value: temp = currentNode.value currentNode.value = indexNode.value indexNode.value = temp indexNode = indexNode.next currentNode = currentNode.next def size(self): ''' This method returns the size of the linked list ''' return self.__size if __name__ == '__main__': doublyLinkedList = DoublyLinkedList(); doublyLinkedList.traverse(); print("size : {}".format(doublyLinkedList.size())) doublyLinkedList.insertStart(10); doublyLinkedList.traverse(); print("size : {}".format(doublyLinkedList.size())) doublyLinkedList.remove(10); doublyLinkedList.traverse(); print("size : {}".format(doublyLinkedList.size())) doublyLinkedList.insertEnd(10); doublyLinkedList.traverse(); print("size : {}".format(doublyLinkedList.size())) doublyLinkedList.remove(10); doublyLinkedList.traverse(); print("size : {}".format(doublyLinkedList.size())) doublyLinkedList.insertStart(5); doublyLinkedList.insertStart(10); doublyLinkedList.insertEnd(15); doublyLinkedList.traverse(); print("size : {}".format(doublyLinkedList.size())) doublyLinkedList.remove(15); doublyLinkedList.traverse(); print("size : {}".format(doublyLinkedList.size())) doublyLinkedList.insertStart(-2); doublyLinkedList.insertStart(99); doublyLinkedList.insertEnd(15); doublyLinkedList.traverse(); print("size : {}".format(doublyLinkedList.size())) doublyLinkedList.sort(); doublyLinkedList.traverse(); print("search 1000 : {}".format(doublyLinkedList.search(1000))) print("search 99 : {}".format(doublyLinkedList.search(99)))
2d5c1d615d8d84d760cca1c5604fe5ff4d024d90
kanishkaverma/leetcode
/grokking/sliding window/max_contignous_subarray_negative.py
370
3.828125
4
def maxSubArray( arr): maxsum, currentSum = arr[0], 0 for end in range(len(arr)): currentSum += arr[end] if currentSum < 0: currentSum= 0 if currentSum > maxsum: maxsum = currentSum; return maxsum def main(): print(maxSubArray( [-2,1,-3,4,-1,2,1,-5,4])) main()
0ec541346ba66538c7326df30985b6fd859f89e3
KJRG/JBA-DuplicateFileHandler
/Topics/Args/Theory/main.py
500
4.34375
4
# You can experiment here, it won’t be checked import sys # first, we import the module args = sys.argv # we get the list of arguments if len(args) != 3: print("The script should be called with two arguments, the first and the second number to be multiplied") else: first_num = float(args[1]) # convert arguments to float second_num = float(args[2]) product = first_num * second_num print("The product of " + args[1] + " times " + args[2] + " equals " + str(product))
83f742dffec26bba6a192403fd8538ec11dec2fc
rppy/course
/for_intro.py
155
4.125
4
# iterating through a list for item in [1, 2, 3, 4, 5]: print(item) print() # iterating through a range (generator) for i in range(6): print(i)
5391bbb659c2d7e408a6db4bb09b68347d29d435
LoralieFlint/learning-python
/BuiltInFunctions.py
500
4.21875
4
# built in python functions phrase = "Hello World" # put to upper case print(phrase.upper()) # puts to upper case then checks for upper case and returns boolean print(phrase.upper().isupper()) # checking the length of a string print(len(phrase)) # finding a character by index on a string to get the character returned print(phrase[3]) # finding the index of a character and getting the index returned print(phrase.index("W")) # replacing a word in a string print(phrase.replace("Hello", "Welcome"))
9955d78de624887980fa43ad7832bde09fe888b8
elenaborisova/Python-Fundamentals
/15. Text Processing - Lab/02.repeat_strings.py
98
3.546875
4
words = input().split() result = "".join(map(lambda word: word * len(word), words)) print(result)
f3e86664b2c7e1bd827daf0dc0812e2da96c4464
sccheah/LIN127
/hw1/hw1.py
2,091
3.578125
4
import nltk # returns tuple of total # of words and # 10 most frequent words def get_inaugural_data(filename): words = nltk.corpus.inaugural.words(filename) portrait_freq = nltk.FreqDist(words) return (len(words), portrait_freq) # performs the same operation as get_inaugural_data, but user uses own file def get_own_file_data(filename): data = nltk.corpus.PlaintextCorpusReader('.', [filename]) portrait_words = data.words(filename) portrait_freq = nltk.FreqDist(portrait_words) return (len(portrait_words), portrait_freq) # get avg sent len from a file in inaugural corpus def get_avg_sentence_len(filename): # put into list of sentences sents = (nltk.corpus.inaugural.sents(filename)) total_words = 0 for words in sents: total_words += len(words) return (total_words / len(sents)) def get_own_file_avg_sent_len(filename): f = open(filename) raw = f.read() total_words = 0 sents = nltk.sent_tokenize(raw) for words in sents: total_words += len(words.split()) #print (total_words) return (total_words / len(sents)) def main(): wash_result = get_inaugural_data('1789-Washington.txt') wash_avg_len = get_avg_sentence_len('1789-Washington.txt') print ('1789-Washington.txt: ' + str(wash_result[0]) + ' words') wash_result[1].tabulate(12) print ("Average sentence length: " + str(wash_avg_len)) print ('') obama_result = get_inaugural_data('2009-Obama.txt') obama_avg_len = get_avg_sentence_len('2009-Obama.txt') print ('2009-Obama.txt: ' + str(obama_result[0]) + ' words') obama_result[1].tabulate(12) print("Average sentence length: " + str(obama_avg_len)) print ('') trump_result = get_own_file_data('2017-Trump.txt') trump_avg_len = get_own_file_avg_sent_len('2017-Trump.txt') print ('2017-Trump.txt: ' + str(trump_result[0]) + ' words') trump_result[1].tabulate(13) print ("Average sentence length: " + str(trump_avg_len)) print ('') # if hw1.py is top-level program if __name__ == '__main__': main()
198ef03af9578a1eb1e1b8df281cb7b9321f16e3
theshuv/python-Basics
/shubham vohra/q1.py
146
3.984375
4
dic={} def func(n): for i in range(1,n+1): dic[i]=(i*i) print(dic) n=int(input("ENTER THE NUMBER : ")) func(n)
49127c565d177515cbdbaff5428538d82374329e
vsdrun/lc_public
/backtracking/401_Binary_Watch_slow.py
2,132
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. For example, the above binary watch reads "3:25". Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. Example: Input: n = 1 Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] Note: The order of output does not matter. The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02". """ class Solution(object): def readBinaryWatch(self, num): """ :type num: int :rtype: List[str] """ """ 4 for hour (0-11) 6 for min (0-59) total: 10 x x x x x x x x x x """ delimit = ":" result = ["0"] * 10 sol = [] def count(si, num, result): if not num: hour = int("".join(result[0:4]), 2) minute = int("".join(result[4:]), 2) if hour > 11: return if minute > 59: return solstr = str(hour) + delimit if minute < 10: solstr += "0" + str(minute) else: solstr += str(minute) sol.append(solstr) return for i in xrange(si, 10): result[i] = "1" num -= 1 count(i + 1, num, result) num += 1 result[i] = "0" count(0, num, result) return sol def build_input(): return 1 if __name__ == "__main__": b = build_input() s = Solution() result = s.readBinaryWatch(b) # Return ["eat","oath"]. print(result)
fdcd5b8f618b3c33fd56585aaf184b85b29f7654
lbassett/Leet-Code-Challenges
/GroupAnagrams.py
680
3.96875
4
#Challenge: Group Anagrams # Given a list of strings, return a list of lists where all the strings that are # anagrams are grouped together def groupAnagrams(strs): """ :type strs: List[str] :rtype: List[List[str]] """ tupdict = {} for word in strs: charcount = [0]*26 for letter in word: val = ord(letter) - 97 charcount[val] += 1 charcount = tuple(charcount) if charcount in tupdict: tupdict[charcount] += [word] else: tupdict[charcount] = [word] retlist = [] for x in tupdict: retlist += [tupdict[x]] return(retlist)
e84dfa7c42443b836f817c91a05c74b84c5cc189
jrperlic/data-structure-tutorial
/code/2-example-solution.py
345
3.703125
4
from collections import deque def mystery1(ll): for i in reversed(ll): print(i, end=" ") print("") def mystery2(ll): for i in range(0, len(ll), 2): print(ll[i], end=" ") for i in range(1, len(ll), 2): print(ll[i], end=" ") ll = deque([1, 2, 3, 4, 5]) mystery1(ll) # 5 4 3 2 1 mystery2(ll) # 1 3 5 2 4
3b8cfde0be63249d01ee55d6baebe3ef7d5b7495
arpiagar/HackerEarth
/implement-trie-prefix-tree/solution.py
2,654
4.09375
4
#https://leetcode.com/problems/implement-trie-prefix-tree/ class Node: def __init__(self,val,endNode=False, childMap=None ): self.val = val if childMap: self.childMap = childMap else: self.childMap = {} self.endNode = endNode class Trie(object): def __init__(self): """ Initialize your data structure here. """ self.trie_map = {} def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: None """ self.insertWithMap(word, self.trie_map) # apple def insertWithMap(self, word, node_map): # if not word: # {} return endNode = False if len(word) == 1: endNode = True firstElem = word[0] # a if firstElem not in node_map: obj = Node(firstElem,endNode) # {a: Node(a)} node_map[firstElem] = obj self.insertWithMap(word[1:], obj.childMap) # a -> {p -> {p} -> {l} -> {e}} else: next_node_map = node_map[firstElem].childMap if endNode: node_map[firstElem].endNode = True self.insertWithMap(word[1:], next_node_map) return def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ if not word: # return False firstElem = word[0] # a if firstElem not in self.trie_map: return False startNode = self.trie_map[firstElem] #a for i in range(1, len(word)): # pple elem = word[i] # p if elem not in startNode.childMap: # return False startNode = startNode.childMap[elem] if startNode.endNode: return True return False def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ word = prefix if not word: return True firstElem = word[0] if firstElem not in self.trie_map: return False startNode = self.trie_map[firstElem] for i in range(1, len(word)): elem = word[i] if elem not in startNode.childMap: return False startNode = startNode.childMap[elem] return True # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
87580e955d8a1b483b52465055bbe749bb135ec8
nikita-chudnovskiy/ProjectPyton
/00 Базовый курс/034 Кортежи (tuple)/03 Кортеж явл не изм Объектом.py
1,157
3.90625
4
a = (99,2,3,5,False,[100,200,300],'hi',5,99) print(a.index(99)) # есть ли в списке 5 да под индексом 1 встречающийся элемент print(a.count(5)) # Сколько раз # a[1]=100 не подд изм print(a[4]) a[5].append(400) print(a) # Но в самом кортеже есть список его можно изменить внутри # А зачем нам кортежи print() # Наглядно как изменится элемент в а если мы меняем в b a =[99,2,3,5,False,[100,200,300],'hi',5,99] print(a) b = a # будет 2 однинаковых а если сделать b=a.copy то будет 2 разных объекта print(b) # Если бы мы хранили информацию в кортеже такой бы ситуации не произошло print() b[0]=100 print(a) print(b) # КОРТЕЖИ ЗАНИМАЮТ МЕНЬШЕ МЕСТА В ПАМЯТИ Скорость обработки БЫТРЕЕ a = [99,2,3,5,False,[100,200,300],'hi',5,99] b = tuple([99,2,3,5,False,[100,200,300],'hi',5,99]) print(a.__sizeof__()) print(b.__sizeof__())
7b097bfc96f883685a60f7d8137fb3b267aaa3fd
ZandbergenM/Week_3_Zandbergen
/Chapter_ 5_Week_3_Zandbergen.py
1,641
4.25
4
#Week 3 Module_Zandbergen #5.1 import time epoch = time.time() #Need to convert to the time of day in hours, minutes, and seconds #Need to determine days since epoch #epoch is in SECONDS def current_time(x): total_hours = x // 60 // 60 #takes dividing by 60 twice to get minutes then hours to get TOTAL number of hours current_hour = total_hours - (total_hours // 24) * 24 #converts total hours to the hour of the day rounded down total_minutes = x // 60 #diving by 60 to get total minutes current_minutes = total_minutes - (total_minutes // 60) * 60 #converts total minutes to current minute rounded down total_seconds = x // 1 #this will take the seconds divided by itself and rounded down current_seconds = total_seconds - (total_seconds // 60) * 60 #converts total seconds to current second rounded down return current_hour, current_minutes, current_seconds #returns the three values needed print(current_time(epoch)) def days_since_epoch(x): total_hours = x // 60 // 60 #takes epoch, divides by 60 twice to get total hours days = total_hours// 24 #total hours divided by hours in a day return days print(days_since_epoch(epoch)) #5.2 def check_fermat(a, b, c, n): if n > 2 and a**n + b**n == c**n: print ('Holy smokes, Fermat was wrong!') else: print ("No, that doesn't work") def user_prompt(): a = input('Type the value of A and press enter ') b = input('Type the value of B and press enter ') c = input('Type the value of C and press enter ') n = input('Type the value of N and press enter ') check_fermat(int (a), int (b), int (c), int (n)) user_prompt()
47cf8e30bafd8e37d20025765ec29732b3e4db46
luckyparakh/dsa
/pythonds/ch5/coin_change_dp.py
1,918
4.5625
5
# -*- coding: utf-8 -*- ''' With DP A classic example of an optimization problem involves making change using the fewest coins. Suppose you are a programmer for a vending machine manufacturer. Your company wants to streamline effort by giving out the fewest possible coins in change for each transaction. Suppose a customer puts in a dollar bill and purchases an item for 37 cents. What is the smallest number of coins you can use to make change? The answer is six coins: two quarters, one dime, and three pennies. How did we arrive at the answer of six coins? We start with the largest coin in our arsenal (a quarter) and use as many of those as possible, then we go to the next lowest coin value and use as many of those as possible. This first approach is called a greedy method because we try to solve as big a piece of the problem as possible right away. The greedy method works fine when we are using U.S. coins, but suppose that your company decides to deploy its vending machines in Lower Elbonia where, in addition to the usual 1, 5, 10, and 25 cent coins they also have a 21 cent coin. In this instance our greedy method fails to find the optimal solution for 63 cents in change. With the addition of the 21 cent coin the greedy method would still find the solution to be six coins. However, the optimal answer is three 21 cent pieces. ''' def recMC(coinValueList,change): minCoins=change/min(coinValueList) if change in coinValueList: return 1 else: if change in coinChange.keys(): return coinChange[change] else: for i in coinValueList: if i <= change: numCoins=1+recMC(coinValueList,change-i) if numCoins<minCoins: minCoins=numCoins coinChange[change]=minCoins return coinChange[change] coinChange={} print(recMC([1,5,10,21,25],63))
b4268f6e410c1de4866db65f0a0ee319644d6733
codeAligned/interview_challenges
/factorial/factorial.py
201
3.921875
4
def factorial(n): if n >= 1: numbers = list(range(1,n+1)) answer = 1 for number in numbers: answer *= number return answer else: return None
4885eafe85d9447007dead4ac92d7df28035e4e0
yhhaohao555/AlgorithmCHUNZHAO
/Week_06/翻转字符串中的单词3.py
458
3.609375
4
class Solution(object): def reverseWords(self, s): def reverse(word): letters = list(word) i, j = 0, len(letters) - 1 while i < j: letters[i], letters[j] = letters[j], letters[i] i += 1 j -= 1 return "".join(letters) words = s.split() for i in range(len(words)): words[i] = reverse(words[i]) return " ".join(words)
955851e7943d507b85b87a4c3a92b54e89e988f1
bas20001/b21
/8-7.py
717
3.75
4
def make_album(singer,album_name,album_amount = ''): describe_album = {'musician':singer,'album':album_name} if album_amount : describe_album['album_amount'] = album_amount else : describe_album = {'musician':singer,'album':album_name} return describe_album while True: print("make your own album on it") print("If you want to quit please input q") o_singer = raw_input('Input your singer name: \n') if o_singer == 'q': break o_album_name = raw_input('Input your album name: \n') if o_album_name == 'q': break o_album_amount = raw_input('Input your album_amount: \n') if o_album_amount == 'q': break album = make_album(o_singer,o_album_name,o_album_amount) print(album)
2f615971956b1471e6a8b1d00f32c7cb862eb9f5
Krish695/C-100
/car.py
575
3.578125
4
class Car(object): def __init__(self,model,color,company,speed_limit): self.color=color self.company = company self.speed_limit= speed_limit self.model=model def start(self): print("started") def stop(self): print("stoped") def accelerate(self): print("accelerate functionalty here") def change_gear(self): print("gear_changed") audi=Car("A6","blue","audi",100) print(audi.start()) print(audi.stop()) print(audi.change_gear()) print(audi.accelerate())
ea107ac66e9a3868db9a3dce9245549f56aa5032
BennyAharoni/python_digital
/Lesson1/targil2.py
360
3.984375
4
num = 5 print("Your number is: " + str(num)) print(type(num)) num = num + 2 print(num) num2 = num * 10 print("Your number is: " + str(num)) num = int(input("Enter number: ")) print("Alafim = " + str(num // 1000)) print("Meot = " + str((num % 1000) // 100)) print("Asarot = " + str((num % 100) // 10)) print("Ahadot = " + str((num % 10) // 1)) num = num % 1000
1e85887334cb3d5913e1b11338a50bdca4a14d7b
CarlosCruz10/Mi-proyecto
/Mi-proyecto/time.py
2,035
3.984375
4
from time import sleep import datetime NIGHT_STARTS = 19 DAY_STARTS = 7 HOUR_DURATION = 1 def write_file_and_screen(text, file_name): with open(file_name, "a") as hours_file: hours_file.write("{}{}".format(text, "\n")) print(text) def main(): current_time = datetime.datetime.now() is_night = False alarm = input("¿Quieres programar una alarma[S/N]: ").upper() if alarm == "S": hora = int(input("¿A qué hora quieres que suene?: ")) day = input("¿Qué días quieres que suene?: ").upper() print("¡Genial!, la alarma sonará a las {} el día {}".format(hora, day)) if day == "LUNES": day = 0 elif day == "MARTES": day = 1 elif day == "MIERCOLES": day = 2 elif day == "JUEVES": day = 3 elif day == "VIERNES": day = 4 elif day == "SABADO": day = 5 elif day == "DOMINGO": day = 6 else: pass while True: sleep(HOUR_DURATION) current_time += datetime.timedelta(hours=1) light_changed = False if (current_time.hour >= NIGHT_STARTS or current_time.hour <= DAY_STARTS) and not is_night: is_night = True light_changed = True elif (current_time.hour > DAY_STARTS and current_time.hour < NIGHT_STARTS) and is_night: is_night = False light_changed = True if light_changed: if is_night: write_file_and_screen("Se ha hecho de noche", "horas.txt") else: write_file_and_screen("Se ha hecho de día", "horas.txt") if alarm == "S" and current_time.hour == hora and current_time.weekday() == day: print("Suena la alarma") weekday = current_time.weekday() write_file_and_screen("La hora actual es {}".format(current_time), "horas.txt") if __name__ == "__main__": main()
4362c37ac7d6bd55441de398f7b108e612101aee
keepforever/udemy-python-tutorial
/old/blockchain-S4L64.py
3,251
3.96875
4
# Keyword argument example allows us to declair vars in any order # or ommit and revert to devalut vals. def keyword_args_example(name, age): print("hello " + name + "aged " + age) # keyword_args_example(age="33", name="Brian") # Define blockchain variable as an empty list blockchain = [] # Function to get last blockchain value def get_last_blockchain_value(): """ BC: Returns last value in the blockchain """ #check if blockchain is empty if len(blockchain) < 1: return None return blockchain[-1] def add_transaction(transaction_amount, last_transaction=[1]): """ Appends new value to the list of existing values in the blockchain Arguments tranaction_amount: the amount that should be added. last_transaction: the previous blockchain transaction. (default: [1]) """ if last_transaction == None: last_transaction = [1] blockchain.append([last_transaction, transaction_amount]) def get_transaction_value(): """ Returns the input of the user (a new transaction_amount) """ return float(input('Your transaction amount please: ')) def get_user_choice(): """ Returns decision of user to add another transaction or print the blockchain values. """ return input("Enter Your Choice: ") def print_blockchain_elements(): # bring for loop inside while loop for block in blockchain: print(block) def verify_chain(): """ checks to make sure the first element of the current block is equal to the previous block. """ #helper vars block_index = 0 is_valid = True for block_index in range(len(blockchain)): if block_index == 0: continue elif blockchain[block_index][0] == blockchain[block_index - 1]: is_valid = True else: is_valid = False break return is_valid #Using waiting_for_input to control the while loop as alt to 'break' waiting_for_input = True while waiting_for_input: print("Please choose: ") print(" 1: Add a transactio value") print(" 2: Output the blockchain blocks") print(" h: Manipulate blockchain") print(" q: Quit") user_choice = get_user_choice() if user_choice == '1': tx_amount = get_transaction_value() add_transaction(tx_amount, get_last_blockchain_value()) elif user_choice == '2': print_blockchain_elements() elif user_choice == 'h': if len(blockchain) >= 1: blockchain[0] = [2] elif user_choice == 'q': waiting_for_input = False else: print("Invalid choice!") if not verify_chain(): print("Gasp! \nThe blockchain is invalid!") break else: print("User left.") print("Done!") ############### OLD CODE ################# # # for block in blockchain: # if block_index == 0: # block_index += 1 # continue # #continue skips to next iteration in for loop # elif block[0] == blockchain[block_index - 1]: # is_valid = True # else: # is_valid = False # break # #increment block_index to check each block # block_index += 1
caae49de4c389a404f93ab8fa566628e0940cb4d
raghuprasadks/pythontutoriallatest
/gui/registrationformwithdb.py
2,666
3.609375
4
import sqlite3 conn = sqlite3.connect('registrationnew.db') print("Opened database successfully") conn.execute('''CREATE TABLE REGISTRATIONS (NAME TEXT NOT NULL, EMAIL TEXT NOT NULL, MOBILE INT NOT NULL, PWD TEXT NOT NULL)''') from tkinter import * class Registration(): def __init__(self): window = Tk() window.geometry('400x300') window.title("Registration form") Label(window, text = "Name").grid(row = 1,column = 1, sticky = W) Label(window, text = "Email address").grid(row = 2,column = 1, sticky = W) Label(window, text = "Mobile number").grid(row = 3,column = 1, sticky = W) Label(window, text = "Password").grid(row = 4,column = 1, sticky = W) Label(window, text = "Confirm Password").grid(row = 5,column = 1, sticky = W) self.nameVar = StringVar() Entry(window, textvariable = self.nameVar,justify = LEFT).grid(row = 1, column = 2) self.emailVar = StringVar() Entry(window, textvariable = self.emailVar,justify = LEFT).grid(row = 2, column = 2) self.mobileVar=StringVar() Entry(window, textvariable = self.mobileVar,justify = LEFT).grid(row = 3, column = 2) self.passwordVar=StringVar() Entry(window, textvariable = self.passwordVar,justify = LEFT).grid(row = 4, column = 2) self.conpasswordVar=StringVar() Entry(window, textvariable = self.conpasswordVar,justify = LEFT).grid(row = 5, column = 2) btSubmit = Button(window, text = "Submit",command = self.Save).grid(row = 6, column = 2, sticky = E) window.mainloop() def Save(self): try: conn = sqlite3.connect('registrationnew.db') name=self.nameVar.get() email=self.emailVar.get() mobile =self.mobileVar.get() password = self.passwordVar.get() param = (name,email,mobile,password) #conn.execute("INSERT INTO REGISTRATIONS VALUES (?,?,?,?),(name,email,mobile,password)") sql = ''' INSERT INTO REGISTRATIONS VALUES (?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, param) conn.commit() self.nameVar.set('') self.emailVar.set('') self.mobileVar.set('') self.passwordVar.set('') self.conpasswordVar.set('') conn.close() except Exception as e: print("Exception ::",e) print('Saved to db') reg=Registration()
48134a6835cb0309d7ed55db1f7ca340f24ff74d
matheusquei/array
/listas3.py
445
3.921875
4
usuarios = [input("Digite o primeiro usuario: "), input("Digite o segundo usuario: "), input("Digite o terceiro usuario: ")] for user in usuarios: if user.lower()=="admin": print("Olá administrador, temos relátorios à observar") elif user.lower()=="user": print("Olá usuario seja bem vindo") elif user.lower()=="estagiario": print("Por favor, não mexa em nada!") else: print("Ola visitante")
067f87f012f6b4e26ea2bcb51f23ab8107e6c555
UWPCE-PythonCert-ClassRepos/Wi2018-Classroom
/students/luke/s08/circle.py
1,260
3.734375
4
import math import functools @functools.total_ordering class Circle: def __init__(self, radius=0): self._radius = radius @classmethod def from_diameter(myclass, diameter=0): return myclass(diameter / 2) @property def radius(self): return self._radius @property def circumference(self): return self._radius * 2 * math.pi @property def area(self): return (self._radius ** 2) * math.pi @property def diameter(self): return self._radius * 2 @radius.setter def radius(self, newradius): self._radius = newradius @diameter.setter def diameter(self, newdiameter): self._radius = newdiameter / 2 def __str__(self): return f"Circle with radius: {self._radius:.6f}" def __repr__(self): return f"Circle({self._radius})" def __add__(self, other): return Circle(self._radius + other.radius) def __mul__(self, other): return Circle(self._radius * other) def __rmul__(self, other): return Circle(self._radius * other) def __eq__(self, other): return self._radius == other.radius def __lt__(self, other): return self._radius < other.radius
39b877f7b60c0337d0afd32e765f59d5e9d41bbd
edenuis/Python
/Code Challenges/countInversions.py
1,152
3.96875
4
#Challenge: Count inversions in an array # Inversion Count for an array indicates – how far (or close) the # array is from being sorted. If array is already sorted then # inversion count is 0. If array is sorted in reverse order that # inversion count is the maximum. # Formally speaking, two elements a[i] and a[j] form an inversion if # a[i] > a[j] and i < j import math def countInversions(numbers): size = math.ceil(len(numbers)/2) count = 0 while size > 0: i = 0 while i + size < len(numbers): if numbers[i] > numbers[i + size]: count += 1 i += 1 if size/2 < 1: break size = math.ceil(size/2) return count if __name__ == '__main__': assert countInversions([2,4,1,3,5]) == 3 assert countInversions([]) == 0 assert countInversions([1,2,3,4,5]) == 0 assert countInversions([3,2,1]) == 3 assert countInversions([2,2,1,4,1]) == 4 assert countInversions([1,20,6,4,5]) == 5 assert countInversions([1]) == 0 assert countInversions([1,2,3,4,2,3,4,5]) == 3
55335314e3d4e1ee2b9fe1ccbb2e7bb4c43aec36
Alexandr-94/overone_ez
/third_lesson/task_6.py
167
3.828125
4
s = str(input('введите больше 2 символов' )) print(s[::3]) print(s[1]+s[-1]) print(s.upper()) print(s[::-1]) print(s.isdigit()) print(s.isalpha())
19c6ce9821366d560f4c60d80ab5394eb42b5d06
poi0905/Scientific-Computing
/hw2/dss02.py
351
3.5625
4
# Use DSS to optimize function of two variables from scipy import optimize def f1(x): return x[0]**2-2*x[0]+x[1]**2-4*x[1] f2 = lambda x: x[0]**2-2*x[0]+x[1]**2-4*x[1] def banana1(x): return 100*(x[1]-x[0]**2)**2+(1-x[0])**2 banana2 = lambda x: 100*(x[1]-x[0]**2)**2+(1-x[0])**2 x0 = [0, 0] xopt = optimize.fmin(banana1, x0) print(xopt)
d3c43f259dd2b6d5f4539e7d4516e86ffa415ca9
parkersell/HackPsu2021
/YouTube.py
1,465
3.765625
4
# Retrieves relevant data from the YouTube search history or watch history .html files of the Google Takeout .zip file. import urllib.parse import html # Returns a list of string data points from the search-history.html file of a user's YouTube data. def searchHistory(filePath): # Getting the important data from the bottom of the html file. with open(filePath, encoding="utf8") as file: raw = file.readline() while raw[:8] != "</style>": raw = file.readline() file.close() # Splitting the html file to get the search data, raw looks like: '...query=search+text+here"...' queries = raw.split("query=") matchable = [] for query in queries: query = query[:query.index('"')] query = " ".join(query.split("+")) matchable.append(urllib.parse.unquote(query)) return matchable[1:] # Returns a list of string data points from the watch-history.html file of a user's YouTube data. def watchHistory(filePath): with open(filePath, encoding="utf8") as file: raw = file.readline() while raw[:8] != "</style>": raw = file.readline() file.close() # Splitting the html file to get the video title, raw looks like: '...">video title here</a>...' queries = raw.split("</a>") matchable = [] for query in queries: query = query[query.rindex('">') + 2:] matchable.append(html.unescape(query)) return matchable[:-1]
2ec0063350d63117236e344afc8b66dc83e95108
pulavartivinay/CSES_problemSet_solutions
/Counting_Rooms.py
1,993
3.5625
4
def DFS(start): queue = [] queue.append(start) visited_list[start] = "True" while queue: s = queue.pop(0) row = int(s/m) column = int(s%m) for action in adjacent_list[s]: if action == "up": if row-1 >=0 and building[row-1][column] == ".": if visited_list[(row-1)*m+column] == "False": queue.append((row-1)*m+column) visited_list[(row-1)*m+column] = "True" elif action == "down": if row+1 < n and building[row+1][column] == ".": if visited_list[(row+1)*m+column] == "False": queue.append((row+1)*m+column) visited_list[(row+1)*m+column] = "True" elif action == "left": if column-1 >=0 and building[row][column-1] == ".": if visited_list[(row)*m+column-1] == "False": queue.append((row)*m+column-1) visited_list[(row)*m+column-1] = "True" elif action == "right": if column+1 < m and building[row][column+1] == ".": if visited_list[(row)*m+column+1] == "False": queue.append((row)*m+column+1) visited_list[(row)*m+column+1] = "True" n,m = input().split() n = int(n) m = int(m) building = [] for i in range(0,n): temp = input() building.append(temp) adjacent_list = {} visited_list = {} for i in range(0,n): for j in range(0,m): if building[i][j] == ".": adjacent_list[i*m + j] = ["up","down","left","right"] visited_list[i*m + j] = "False" ans = 0 for i in range(0,n): for j in range(0,m): if building[i][j] == "." and visited_list[i*m+j] == "False": ans = ans + 1 DFS(i*m+j) print(ans)
a91136d3ae4f411caa813dd508250f3690c97840
HaochenGou/Database
/mini_project1/291 miniproject01-03.py
9,331
3.703125
4
import sys import sqlite3 import datetime from random import randint def __register_birth(self): valid_inputs = False while not valid_inputs: try: # Gather mother's info m_f_name = input("Mother's first name: ") m_l_name = input("Mother's last name: ") self.__cursor.execute('SELECT * FROM persons WHERE fname like :mfname and lname like :mlname', {'mfname': m_f_name, 'mlname': m_l_name}) mother_info = self.__cursor.fetchall() if len(mother_info) > 0: assert len(mother_info) == 1 print("Found mother's info in system.") address = mother_info[0][4] phone = mother_info[0][5] else: # registering mother's info into persons table print("Must add mother's info into system: ") mbdate_str = input("Mother's birthdate (MMDDYYYY): ") if mbdate_str == '': mbdate = None else: mbdate = datetime.strptime(mbdate_str, '%m%d%Y') mbplace = input("Mother's birth city: ") if mbplace == '': mbplace = None maddress = input("Mother's Address: ") if maddress == '': maddress = None address = maddress mphone = input("Mother's Phone Number: ") if mphone == '': mphone = None phone = mphone m_person_reg = (m_f_name, m_l_name, mbdate, mbplace, maddress, mphone) self.__cursor.execute('INSERT INTO persons values (?,?,?,?,?,?)', m_person_reg) self.__conn.commit() print("Successfully added mother's info into system.") print("Continuing to gather info to register birth.") # Gather father's info f_f_name = input("Father's first name: ") f_l_name = input("Father's last name: ") self.__cursor.execute('SELECT * FROM persons WHERE fname like :ffname and lname like :flname', {'ffname': f_f_name, 'flname': f_l_name}) father_info = self.__cursor.fetchall() if len(father_info) > 0: assert len(father_info) == 1 print("Found fathers's info in system.") else: # Registering father's info into persons table print("Must add fathers's info into system: ") fbdate_str = input("Fathers's birthdate (MMDDYYYY): ") if fbdate_str == '': fbdate= None else: fbdate = datetime.strptime(fbdate_str, '%m%d%Y') fbplace = input("Fathers's birth city: ") if fbplace == '': fbplace = None faddress = input("Fathers's Address: ") if faddress == '': faddress = None fphone = input("Fathers's Phone Number: ") if fphone == '': fphone = None f_person_reg = (f_f_name, f_l_name, fbdate, fbplace, faddress, fphone) self.__cursor.execute('INSERT INTO persons values (?,?,?,?,?,?)', f_person_reg) self.__conn.commit() print("Successfully added fathers's info into system.") print("Continuing to gather info to register birth.") # Gather birth information f_name = input('First Name: ') assert len(f_name) > 0 l_name = input('Last Name: ') assert len(l_name) > 0 gender = input('Gender (m/f): ') assert len(gender) == 1 assert gender.upper() == 'M' or gender.upper() == "F" # NEED TO CONFIRM DATE INPUT CONVERSION TO SQLITE DATE OBJECT birthdate_str = input('Birthdate (MMDDYYYY): ') birthdate = datetime.strptime(birthdate_str, '%m%d%Y') birthplace = input('Birth Place: ') reg_location = self.__user_info[5] reg_date = date.today() self.__cursor.execute('SELECT max(regno) FROM births') new_regno = self.__cursor.fetchall()[0][0] + 1 birth = (new_regno, f_name, l_name, reg_date, reg_location, gender, f_f_name, f_l_name, m_f_name, m_l_name) person = (f_name, l_name, birthdate, birthplace, address, phone) self.__cursor.execute( 'insert into persons values (?,?,?,?,?,?)', person) self.__cursor.execute( 'insert into births values (?,?,?,?,?,?,?,?,?,?)', birth) self.__conn.commit() except: print('Invalid Entry.') next_step = input("Type 'C' to cancel, or any other key to retry: ") if next_step.upper() = 'C': print('Returning to user menu.') break else: print('Retry inputs.') else: print('Successfully registered birth/person.') print('Returning to user menu.') valid_inputs = True return None def __register_marriage(self): print("Registering a marriage...") p1_fname, p1_lname = "", "" p2_fname, p2_lname = "", "" for lname, fname, partner in ([p1_lname, p1_fname, "first"], [p2_lname, p2_fname, "second"]): print("Enter the %s partner's information" % (partner)) lname = input("\tLast Name: ") fname = input("\tFirst Name: ") fname, lname = self.__enter_valid_name() # check if the person exists in the database. self.__cursor.execute('''SELECT * FROM persons WHERE lname=? AND fname=?;''', (lname, fname)) if self.__cursor.fetchone() == 0: # person not in database; enter the info required. # currently creates a new row in the persons table. **Should it?** print("Person not found! Create a new entry...") bdate = input("Birthdate (MMDDYYYY): ") bplace = input("Birth Place: ") address = input("Address: ") phone = input("Phone Number: ") persons_insert = (lname, fname, bdate, bplace, address, phone) self.__cursor.execute(''' INSERT INTO persons VALUES (?,?,?,?,?,?); ''', persons_insert) # Create a marriage entry for the two partners. self.__cursor.execute('SELECT max(regno) FROM marriages') regno = self.__cursor.fetchone() + 1 # inserted valus: (regno, regdate, regplace, p1_fname, p1_lname, p2_fname, p2_lname) marriages_insert = (regno, date.today(), self.__user_info[5], p1_fname, p1_lname, p2_fname, p2_lname) self.__cursor.execute(''' INSERT INTO marriages VALUES (?,?,?,?,?,?); ''', marriages_insert) self.__conn.commit() print("Marriage successfully registered!") def __renew_registration(self): valid_inputs = False while not valid_inputs: try: print('Renewing Registration...') regno = int(input('Registration number: ')) self.__cursor.execute('SELECT * FROM registrations where regno= :regno', {'regno':regno}) current_reg = self.__cursor.fetchone() current_expiry = current_reg[2] print('Current expiration date: ', current_expiry) if current_expiry <= date.today(): new_expiry = date.today() new_expiry = new_expiry.replace(new_expiry.year + 1) elif current_expiry > date.today(): new_expiry = current_expiry.replace(current_expiry.year + 1) self.__cursor.execute('UPDATE registrations SET expiry=:new_exp WHERE regno=:reg', {'new_exp':new_expiry, 'reg':regno}) self.__conn.commit() except: print('Invalid registration number. Registration not renewed.') retry_entry = input("Type 'C' to cancel task. Enter any other key to retry: ") if retry_entry.upper() = 'C': print('Returning to user menu.') break else: print('Retry input.') else: print('Successfully renewed registration.') print('Returning to user menu.') valid_inputs = True