blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
0e63b36d3102607cbc9735009e6bb07796d67e20
forest-data/luffy_py_algorithm
/算法入门/quick_sort.py
2,049
3.71875
4
# # 快速排序 def partition(li,left,right): tmp = li[left] while left < right: while left < right and li[right] >= tmp: # 找比左边tmp小的数,从右边找 right -= 1 # 往左走一步 li[left] = li[right] # 把右边的值写到左边空位上 while left < right and li[left] <= tmp: left += 1 li[right] = li[left] #把左边的值写到右边空位上 li[left] = tmp # 把tmp归位 return left def quick_sort(data, left, right): if left < right: mid = partition(data, left, right) quick_sort(data, left, mid-1) quick_sort(data, mid+1, right) # li = [5,7,4,6,3,1,2,9,8] # print(li) # partition(li, 0, len(li)-1) # quick_sort(li, 0, len(li)-1) ''' # 快排 # first 第一索引位置, last 最后位置索引 # 时间复杂度 最坏O(n^2) 最优O(nlogn) def quick_sort(li, first, last): # 递归终止条件 if first >= last: return # 设置第一个元素为中间值 mid_value = li[first] # low指向first low = first # high指向last high = last # 只要low < high 就一直走 while low < high: # high 大于中间值, 则进入循环 while low < high and li[high] >= mid_value: # high往左走 high -= 1 # 出循环后,说明high < mid_value, low指向该值 li[low] = li[high] # high走完了,让low走 # low小于中间值,则进入循环 while low < high and li[low] < mid_value: low += 1 # 出循环后,说明low > mid_value, high 指向该值 li[high] = li[low] # 退出整个循环后, low和high相等 li[low] = mid_value # 递归 # 先对左侧快排 quick_sort(li, first, low-1) # 对右侧快排 quick_sort(li, low+1, last) ''' if __name__ == '__main__': li = [54, 26, 93, 17, 77, 31, 44, 55, 20] print(li) quick_sort(li, 0, len(li)-1) print(li)
0a953197aa82f1ee8ddfb16a4d8a12bb3977f9a0
forest-data/luffy_py_algorithm
/算法入门/查找算法/search.py
958
3.53125
4
import random # 查找: 目的都是从列表中找出一个值 # 顺序查找 > O(n) 顺序进行搜索元素 from 算法入门.cal_time import cal_time @cal_time def linear_search(li, val): for ind, v in enumerate(li): if v == val: return ind else: return None # 二分查找 > O(logn) 应用于已经排序的数据结构上 @cal_time def binary_search(li, val): left = 0 # 坐下标 right = len(li) - 1 #右下标 while left <= right: # 候选区有值 mid = (left + right)//2 # 对2进行整除,向下取整 if li[mid] == val: return mid elif li[mid] > val: right = mid - 1 else: left = mid + 1 else: return None # 测试 # li = [i for i in range(10)] # random.shuffle(li) # print(li) # # print(binary_search(li, 3)) # 性能比较 li = list(range(10000000)) linear_search(li, 3890) binary_search(li, 3890)
e737daceec599900b8e22c001f9288b5fb70ac25
karakorakura/Data-Structures-Practice
/btree.py
3,787
3.5
4
# Shivam Arora # 101403169 # Assignment 4 # Avl tree # COE7 #GlObal #degree t=2; class Node: def __init__(self,data=None,parent = None,pointers = None,leaf = True): self.keys = [] self.pointers=[] self.keysLength = 0 self.parent=parent self.leaf = leaf if data!=None : for d in data: self.keys.append(d) self.keysLength+=1 if pointers!=None : for p in pointers: self.pointers.append(p) def search(self,data): i = 0 while i < self.keysLength and data > self.keys[i]: i += 1 if self.keys[i] == data: return self if self.leaf: return None return self.pointers[i].search(data) def insert(self,data,node1=None,node2=None): i = 0 while i < self.keysLength and data > self.keys[i]: i += 1 self.keys.insert(i,data) self.keysLength+=1 if i < len(self.pointers) : self.pointers[i]=node1 else: self.pointers.append(node1) self.pointers.insert(i+1,node2) class Btree: def __init__(self,root=None): global t self.degree=t self.maxKeyLength = self.degree*2 - 1 self.minKeyLength = self.degree - 1 # self.root=Node(root) self.root=None def printTree(self,node=None): if node==None: node= self.root if node.leaf: for key in node.keys: print key, else : i=0 for key in node.keys: self.printTree(node.pointers[i]) print key, i+=1 self.printTree(node.pointers[i]) def preorder(self,node=None): if node==None: node= self.root if node.leaf: for key in node.keys: print key, else : i=0 for key in node.keys: print key, # printTree(pointers[i+1]) i+=1 pass def split(self,node=None): parent = node.parent #mid element keys[t-1] node1 = Node(data = node.keys[:t-1], pointers = node.pointers[:t] ) node2 = Node(data = node.keys[t:], pointers = node.pointers[t+1:] ) if parent==None: self.root = Node([node.keys[t-1]],pointers=[node1,node2],leaf=False) parent = self.root parent.leaf = False else : parent.insert(node.keys[t-1],node1,node2) node1.parent=parent node2.parent=parent #Insertion at node def insertAtNode(self,data,node): i = 0 while i < node.keysLength and data > node.keys[i]: i += 1 if node.leaf: node.insert(data) if node.keysLength>=2*t-1: self.split(node) else: self.insertAtNode(data,node.pointers[i]) # Insertion start def insert(self,data=None): if self.root==None: self.root=Node([data]) else: self.insertAtNode(data,self.root) # Search element # Deletion start unfinished def delete(self,data): pass ############################################## main code test code below b = Btree() # b.insert(1) # b.insert(2) # b.insert(3) # b.insert(4) # b.insert(5) # b.insert(6) x=0 x=int(raw_input('enter value to insert -1 to exit')) while x!=-1: b.insert(x) x=int(raw_input('enter value to insert -1 to exit')) b.printTree(); # b.preorder();
5d003bd13085125d781ca29eb8060b3db3bfe3a3
kesicigida/python_example
/find_student_number.py
1,973
3.59375
4
def printLine(x): for i in range(0, x): print "=", print(" ") def isEven(x): if x%2 == 0: return True else: return False ''' x[len(x)] overflows array x[len(x) - 1] equals newline <ENTER> x[len(x) - 2] is what is desired ''' def isLastUnknown(x): if x[len(x)-2] == "n": return True else: return False ''' x[len(x)] overflows array x[len(x) - 1] equals newline <ENTER> x[len(x) - 2] equals last digit We check all digits except the last digit ''' def isOneDigitUnknown(x): number_of_ns = 0 for i in range (0, len(x)-2): if x[i] == "n": number_of_ns = number_of_ns + 1 if number_of_ns == 0: print("no unknown") return False elif number_of_ns > 1: print("more than 1 unknown") return False else: return True def getDigit(x): printLine(len(x)) print(x) pos_of_n = 0 for i in range (0, len(x)-2): if x[i] == "n": pos_of_n = i for j in range (0, 10): xList = list(x) xList[pos_of_n] = str(j) x = "".join(xList) tSum = 1 for i in range (0, len(x)-2): if isEven(i): tSum = tSum + int(x[i]) else: tSum = tSum + 2*int(x[i]) if tSum%10 == 10 - int(x[len(x)-2]): print "n =", j return True ''' len(x) includes newline <ENTER> len(x) - 1 includes "n" len(x) - 2 is what is desired ''' def getLast(x): printLine(len(x)) print(x) tSum = 1 for i in range (0, len(x)-2): if isEven(i): tSum = tSum + int(x[i]) else: tSum = tSum + 2*int(x[i]) lastn = 10 - tSum%10 if lastn == 10: lastn = 0 print "n =", lastn return True mFile = open("student_number_samples.txt", "r") for line in mFile: a = line if isLastUnknown(a): getLast(a) elif isOneDigitUnknown(a): getDigit(a)
14d98d23d3617c08a2aefd1b4ced2d80c5a9378c
168959/Datacamp_pycham_exercises2
/Creat a list.py
2,149
4.40625
4
# Create the areas list areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Print out second element from areas" print(areas[1]) "# Print out last element from areas" print(areas[9]) "# Print out the area of the living room" print(areas[5]) "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Sum of kitchen and bedroom area: eat_sleep_area" eat_sleep_area = areas[3] + areas[-3] "# Print the variable eat_sleep_area" print(eat_sleep_area) "#Subset and calculate" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Sum of kitchen and bedroom area: eat_sleep_area" eat_sleep_area = areas[3] + areas[-3] "# Print the variable eat_sleep_area" print(eat_sleep_area) "#Slicing and dicing" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Use slicing to create downstairs" downstairs = areas[0:6] "# Use slicing to create upstairs" upstairs = areas[6:10] "# Print out downstairs and upstairs" print(downstairs) print(upstairs) "# Alternative slicing to create downstairs" downstairs = areas[:6] "# Alternative slicing to create upstairs" upstairs = areas[-4:] "#Replace list elements" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Correct the bathroom area" areas[-1] = 10.50 # Change "living room" to "chill zone" areas[4] = "chill zone" "#Extend a list" areas = ["hallway", 11.25, "kitchen", 18.0, "chill zone", 20.0, "bedroom", 10.75, "bathroom", 10.50] "# Add poolhouse data to areas, new list is areas_1" areas_1 = areas + ["poolhouse", 24.5] "# Add garage data to areas_1, new list is areas_2" areas_2 = areas_1 + ["garage", 15.45] "#Inner workings of lists" "# Create list areas" areas = [11.25, 18.0, 20.0, 10.75, 9.50] "# Create areas_copy" areas_copy = list(areas) "# Change areas_copy" areas_copy[0] = 5.0 "# Print areas" print(areas)
cdae0b35f271a30def8b69d9cb1f93731a10e99b
shane-kerr/pythonmeetup-bmazing
/players/astarplayer.py
9,728
4.4375
4
""" This player keeps a map of the maze as much as known. Using this, it can find areas that are left to explore, and try to find the nearest one. Areas left to explore are called "Path" in this game. We don't know where on the map we start, and we don't know how big the map is. We could be lazy and simply make a very large 2-dimensional array to hold the map; this will probably work fine since we know that the map is loaded from a text file. However, we will go ahead and do it all sweet and sexy-like and make a map that resizes itself to allow for any arbitrary position. This player will use the A* algorithm to find the number of steps to get to any path that we have not yet explored. """ import heapq import pprint import sys from game import moves from game.mazefield_attributes import Path, Finish, Wall, Start from players.player import Player DEBUG = False def dist(x0, y0, x1, y1): """distance between two positions using only cardinal movement""" return abs(x1-x0) + abs(y1-y0) class Map: """ Implements a rectangular 2-dimensional map of unknown size. """ def __init__(self): self.pos_x = 0 self.pos_y = 0 self.map_x0 = self.map_x1 = 0 self.map_y0 = self.map_y1 = 0 self.map = [[Path]] # we must have started on a Path def move_left(self): self.pos_x -= 1 def move_right(self): self.pos_x += 1 def move_up(self): self.pos_y += 1 def move_down(self): self.pos_y -= 1 def _map_height(self): return self.map_y1 - self.map_y0 + 1 def _map_width(self): return self.map_x1 - self.map_x0 + 1 def _grow_map_left(self): """ To grow the map to the left, we have to add a new column. """ new_column = [None] * self._map_height() self.map = [new_column] + self.map self.map_x0 -= 1 def _grow_map_right(self): """ To grow the map to the right, we have to add a new column. """ new_column = [None] * self._map_height() self.map.append(new_column) self.map_x1 += 1 def _grow_map_up(self): """ To grow the map up, we add an unknown value to each column. """ for column in self.map: column.append(None) self.map_y1 += 1 def _grow_map_down(self): """ To grow the map down, we have to add a new unknown value to the bottom of every column. There is no simple way to add an item to the start of a list, so we create a new map using new columns and then replace our map with this one. """ new_map = [] for column in self.map: column = [None] + column new_map.append(column) self.map = new_map self.map_y0 -= 1 def remember_surroundings(self, surroundings): if DEBUG: print("---- before ---") pprint.pprint(vars(self)) if self.pos_x == self.map_x0: self._grow_map_left() if self.pos_x == self.map_x1: self._grow_map_right() if self.pos_y == self.map_y0: self._grow_map_down() if self.pos_y == self.map_y1: self._grow_map_up() x = self.pos_x - self.map_x0 y = self.pos_y - self.map_y0 self.map[x-1][y] = surroundings.left self.map[x+1][y] = surroundings.right self.map[x][y-1] = surroundings.down self.map[x][y+1] = surroundings.up if DEBUG: print("---- after ---") pprint.pprint(vars(self)) def dump(self): if DEBUG: pprint.pprint(vars(self)) chars = {None: " ", Path: ".", Wall: "#", Finish: ">", Start: "<", } for y in range(self._map_height()-1, -1, -1): for x in range(self._map_width()): if (((y + self.map_y0) == self.pos_y) and ((x + self.map_x0) == self.pos_x)): sys.stdout.write("@") else: sys.stdout.write(chars[self.map[x][y]]) sys.stdout.write("\n") def is_interesting(self, x, y): x_idx = x - self.map_x0 y_idx = y - self.map_y0 # if we do not know if the place is a path, then it is not interesting if self.map[x_idx][y_idx] != Path: return False # if it is on the edge then it is interesting if x in (self.map_x0, self.map_x1): return True if y in (self.map_y0, self.map_y1): return True # if it has an unknown square next to it then it is interesting if self.map[x_idx-1][y_idx] is None: return True if self.map[x_idx+1][y_idx] is None: return True if self.map[x_idx][y_idx-1] is None: return True if self.map[x_idx][y_idx+1] is None: return True # everything else is uninteresting return False def all_interesting(self): interesting = [] for x in range(self.map_x0, self.map_x1+1): for y in range(self.map_y0, self.map_y1+1): if self.is_interesting(x, y): interesting.append((x, y)) return interesting def _moves(self, x, y): result = [] x_idx = x - self.map_x0 y_idx = y - self.map_y0 if (x > self.map_x0) and (self.map[x_idx-1][y_idx] in (Path, Start)): result.append((x-1, y)) if (x < self.map_x1) and (self.map[x_idx+1][y_idx] in (Path, Start)): result.append((x+1, y)) if (y > self.map_y0) and (self.map[x_idx][y_idx-1] in (Path, Start)): result.append((x, y-1)) if (y < self.map_y1) and (self.map[x_idx][y_idx+1] in (Path, Start)): result.append((x, y+1)) return result @staticmethod def _cur_priority(p, pos): """ This is a very inefficient way to see if we are in the priority queue already. However, for this program it is good enough. """ for n, node in enumerate(p): if node[1] == pos: return n return -1 def find_path_to(self, x, y): """ We can use Djikstra's algorithm to find the shortest path. This won't be especially efficient, but it should work. The algorithm is described here: http://www.roguebasin.com/index.php?title=Pathfinding """ v = {} # previously visited nodes p = [] # priority queue node = (0, (self.pos_x, self.pos_y)) p.append(node) while p: cost, pos = heapq.heappop(p) # if we've reached our target, build our path and return it node_x, node_y = pos if (node_x == x) and (node_y == y): path = [] path_pos = pos while path_pos != (self.pos_x, self.pos_y): path.append(path_pos) path_pos = v[path_pos][1] path.reverse() return path # otherwise check our possible moves from here cost_nxt = cost + 1 for (x_nxt, y_nxt) in self._moves(node_x, node_y): enqueue = False est_nxt = cost_nxt + dist(x_nxt, y_nxt, x, y) if not (x_nxt, y_nxt) in v: enqueue = True else: cost_last = v[(x_nxt, y_nxt)][0] if cost_last > est_nxt: enqueue = True else: priority_idx = self._cur_priority(p, (x_nxt, y_nxt)) if priority_idx != -1: if p[priority_idx][0] > est_nxt: del p[priority_idx] enqueue = True if enqueue: p.append((est_nxt, (x_nxt, y_nxt))) heapq.heapify(p) v[(x_nxt, y_nxt)] = (est_nxt, (node_x, node_y)) return None class AStarPlayer(Player): name = "A* Player" def __init__(self): self.map = Map() def turn(self, surroundings): # TODO: save the path between turns # hack to handle victory condition if surroundings.left == Finish: return moves.LEFT if surroundings.right == Finish: return moves.RIGHT if surroundings.up == Finish: return moves.UP if surroundings.down == Finish: return moves.DOWN self.map.remember_surroundings(surroundings) if DEBUG: self.map.dump() shortest_path = None for candidate in self.map.all_interesting(): path = self.map.find_path_to(candidate[0], candidate[1]) if path is None: # this should never happen, but... continue if (shortest_path is None) or (len(path) < len(shortest_path)): shortest_path = path if DEBUG: print(shortest_path) next_pos = shortest_path[0] if DEBUG: input() if self.map.pos_x+1 == next_pos[0]: self.map.move_right() return moves.RIGHT if self.map.pos_x-1 == next_pos[0]: self.map.move_left() return moves.LEFT if self.map.pos_y+1 == next_pos[1]: self.map.move_up() return moves.UP if self.map.pos_y-1 == next_pos[1]: self.map.move_down() return moves.DOWN return "pass"
1aa7609aca58c9f7546ab422239493c0d3a3b0a4
mmsolovev/python-basics
/Solovev_Mikhail_dz_3.3.py
271
3.625
4
def thesaurus(*args): people = {} for name in args: people.setdefault(name[0], []) people[name[0]].append(name) return people print(thesaurus("Иван", "Мария", "Петр", "Илья", "Михаил", "Алексей", "Павел"))
57dbfca3f3ddf3eaf18353b599fad9670b081ad2
longsube/longsube.github.io
/HVN_gitlab/exercises/07_module_class/LONGLQ_7.1.py
1,411
3.59375
4
class Trading: def __init__(self, **goods): #goods{name:(price, quantity, size)} self.goods = goods def buyer(self,money, bags): return (money,bags) def buy(self, buyer, **goods_quantity): #goods_quantity{name:quantity} amount_money = 0 amount_size = 0 for k,v in goods_quantity.iteritems(): if v > self.goods[k][1]: return "Not enough %s"%(k) break else: amount_money += (self.goods[k][0]*v) amount_size += (self.goods[k][2]*v) if amount_money > buyer[0]: return "Not enough money to buy" # break elif amount_size > buyer[1]: return "Not enough bags for carrying" # break else: #for i in return "Buying success" if __name__ == '__main__': trading = Trading(apple=(10000, 4, 3), milks=(40000, 3, 4), beef=(100000, 3, 5)) bm = int(raw_input("Buyer money: >")) bb = int(raw_input("Buyer bags: >")) buyer = trading.buyer(bm, bb) a = int(raw_input("apple_amount: >")) m = int(raw_input("milks_amount: >")) b = int(raw_input("beef_amount: >")) print trading.buy(buyer, apple=a, milks=m, beef=b) # Buyer money: >1000000 # Buyer bags: >100 # apple_amount: >2 # milks_amount: >2 # beef_amount: >2 # Buying success
15f3f55bed1b55968cb3000d1abfe46952757031
jimohafeezco/nlp_ws
/bots/src/prayer_time.py
1,540
3.609375
4
# import required modules import requests, json from datetime import datetime # Enter your API key here def get_prayer(user_message): api_key = "0c42f7f6b53b244c78a418f4f181282a" # base_url variable to store url base_url = "http://api.aladhan.com/v1/calendarByCity?" city = "Innopolis" country = "Russia" # Give city name # city_name = input("Enter city name : ") complete_url = "http://api.aladhan.com/v1/calendarByCity?city=Innopolis&country=Russia&method=1" # get method of requests module # return response object response = requests.get(complete_url) current_date =datetime.date(datetime.now()) x = response.json() if x["code"] != "404": y = x["data"][1]["timings"] l=['Fajr', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'] prayer_time= {key: y[key] for key in l} # for prayer in prayer_time.keys(): # prayers = Fajr if user_message.capitalize() in l : # print(prayer_time) prayer= user_message.capitalize() return "The time for {} on {} is {}".format(prayer, current_date, prayer_time[prayer]) elif user_message.lower() =="magrib": prayer ="Maghrib" return "The time for {} is {}".format(prayer, current_date, prayer_time[prayer]) else: return "the time for prayers today : {}, are {}".format(current_date, prayer_time) # return prayer_time else: # print(" City Not Found ") return "City not found" # print(get_prayer())
f6e5c5eaa503f06c40806736159dd6b238943c35
sohanmithinti/p-1071
/correlation.py
679
3.5
4
import numpy as np import pandas as pd import plotly.express as px import csv def getdatasource(): icecream = [] temperature = [] with open("icecreamsales.csv") as f: reader = csv.DictReader(f) print(reader) for row in reader: icecream.append(float(row["IcecreamSales"])) temperature.append(float(row["Temperature"])) print(icecream) print(temperature) return {"x":icecream, "y":temperature} def findcorrelation(datasource): correlation = np.corrcoef(datasource["x"], datasource["y"]) print(correlation[0, 1]) data = getdatasource() findcorrelation(data)
a65aa34ef32d7fced8a91153dae77e48f5cc1176
2019-fall-csc-226/a02-loopy-turtles-loopy-languages-henryjcamacho
/Camachoh- A02.py
1,133
4.15625
4
###################################################################### # Author: Henry Camacho TODO: Change this to your name, if modifying # Username: HenryJCamacho TODO: Change this to your username, if modifying # # Assignment: A02 # Purpose: To draw something we lie with loop ###################################################################### # Acknowledgements: # # original from # # licensed under a Creative Commons # Attribution-Noncommercial-Share Alike 3.0 United States License. ###################################################################### import turtle wn = turtle.Screen() circle = turtle.Turtle() circle.speed(10) circle.fillcolor("yellow") circle.begin_fill() for face in range(75): circle.forward(10) circle.right(5) circle.end_fill() eyes = turtle.Turtle() eyes.speed(10) eyes.penup() eyes.setpos(50, -50) eyes.shape("triangle") eyes.stamp() eyes.setpos (-50, -50) mouth = turtle.Turtle() mouth.speed(10) mouth.penup() mouth.setpos(-50, -100) mouth.pendown() mouth.right(90) for smile in range(30): mouth.forward(5) mouth.left(5) wn.exitonclick()
9aaf6c575136295abbec00c59b5ce50fd0a02b7d
harishkumarhm/Python-Learning
/firstScript.py
146
3.515625
4
first_number = 1+1 print(first_number) second_number = 100 +1 print(second_number) total = first_number + second_number print(total) x = 3
c1facc994bca79947e20fe4adf7890d15ee16f41
zqhappyday/myleetcode
/hard/42接雨水.py
849
3.5
4
''' 经典题目,当初是通过这个题目学会了双指针 这题只要想到到了双指针就一点也不难 这题同样可以使用二分法来做,速度会快很多 ''' class Solution: def trap(self, height: List[int]) -> int: n = len(height) left = 0 right = n - 1 res = 0 leftmax = 0 rightmax = 0 while right > left + 1 : if height[left] <= height[right]: leftmax = max(height[left],leftmax) if height[left + 1] <= leftmax: res = leftmax - height[left+1] + res left += 1 else: rightmax = max(height[right],rightmax) if height[right-1] <= rightmax: res += rightmax - height[right-1] right -= 1 return res
fbf1f445e45e174cc971321ab3f92adaa3de702b
DevRyu/Daliy_Code
/DataStructure/graph(DFS).py
1,896
3.765625
4
# 23-18 깊이우선 탐색 # BFS(Breadth First Search) : 노드들과 같은 레벨에 있은 노드들 큐방식으로 # DFS(Depth First Search) : 노드들의 자식들을 먼저 탐색하는 스택방식으로 # 스택 방식으로 visited, need_visited 방식으로 사용한다. # 방법 : visited 노드를 체우는 작업 # 1) 처음에 visited에 비어있으니 시작 노드의 키를 넣고 # 2) 시작 노드의 값에 하나의 값(처음또는마지막 인접노드들)을 need_visit에 넣는다, # 2-1) 인접노드가 2개 이상이면 둘 중 원하는 방향애 따라서 순서대로 데이터를 넣으면 된다. # 3) need_visit의 추가한 노드 키를 visited에 넣고 해당 값들을 need_visited에 넣는다. # 4) visited에 있으면 패스한다. # 5) need_visited는 스택임으로 마지막의 값을 pop해서 key값은 visited need_visited에 value를 넣음 # 6) 반복 # 예시) graph = dict() graph['A'] = ['B', 'C'] graph['B'] = ['A', 'D'] graph['C'] = ['A', 'G', 'H', 'I'] graph['D'] = ['B', 'E', 'F'] graph['E'] = ['D'] graph['F'] = ['D'] graph['G'] = ['C'] graph['H'] = ['C'] graph['I'] = ['C', 'J'] graph['J'] = ['I'] def dfs(graph,start): visited = list() need_visit = list() # 시작값 need_visit.append(start) count = 0 # need_visit == 0 이될때까지 while need_visit: count += 1 # need_visit에 마지막 값을 pop(삭제)후 node에 넣어주고 (temp역할) node = need_visit.pop() # 방문한 값에 ㅇ벗다면 if node not in visited: #방문 값에 넣어주고 visited.append(node) # node의 값을 need_visit 에 추가 need_visit.extend(graph[node]) return visited dfs(graph,'A') # 시간 복잡도 # BFS 시간복잡도 # Vertex(노드) 수 : V # Edge(간선) 수 : E # 시간 복잡도 O(v+E)
4f11d9065d690ab960835e56cb56788487d6aa3b
DevRyu/Daliy_Code
/Python/baekjoon_2920.py
1,293
3.65625
4
# 문제 # 다장조는 c d e f g a b C, 총 8개 음으로 이루어져있다. 이 문제에서 8개 음은 다음과 같이 숫자로 바꾸어 표현한다. c는 1로, d는 2로, ..., C를 8로 바꾼다. # 1부터 8까지 차례대로 연주한다면 ascending, 8부터 1까지 차례대로 연주한다면 descending, 둘 다 아니라면 mixed 이다. # 연주한 순서가 주어졌을 때, 이것이 ascending인지, descending인지, 아니면 mixed인지 판별하는 프로그램을 작성하시오. # 입력 # 첫째 줄에 8개 숫자가 주어진다. 이 숫자는 문제 설명에서 설명한 음이며, 1부터 8까지 숫자가 한 번씩 등장한다. # 출력 # 첫째 줄에 ascending, descending, mixed 중 하나를 출력한다. # 정답 def solution(data): type_ = ["ascending", "descending", "mixed"] asc = True desc = True for i in range(len(data)-1): if data[i] < data[i+1]: asc = False elif data[i] > data[i+1]: desc = False if asc: return type_[0] elif desc: return type_[1] else: return type_[2] print(solution([1, 2, 3, 4, 5, 6, 7, 8])) print(solution([8, 7, 6, 5, 4, 3, 2, 1])) print(solution([8, 1, 7, 2, 6, 3, 5, 4])) # 총 풀이 시간 및 설정 7분
b30bbbdaad7f749a52eab049027fed4ccbb881d3
DevRyu/Daliy_Code
/Python/bubble_sort.py
441
3.5625
4
def bubble(data): for i in range(len(data) -1): result = False for j in range(len(data) -i-1): if data[j] > data[j+1]: data[j], data[j+1] = data[j+1], data[j] result = True if result == False: break return data import random random_list = random.sample(range(100), 50) print(bubble(random_list)) # [0, 1, 3, 4, 6, 10, 12, 13, 14, 15, 18 ...]
aee0c755f6cc99568b1d0d258b800f91afa9c5c8
JenySadadia/Assignments-of-Python
/calc.py
685
3.984375
4
while True: op=int(input('''Enter the operation which you would like to b performed :- 1.Addition 2.Subtraction 3.Multiplication 4.Division''')) if op==1: x=int(input("enter x")) y=int(input("enter y")) print(x+y) elif op==2: x=int(input("enter x")) y=int(input("enter y")) print(x-y) elif op==3: x=int(input("enter x")) y=int(input("enter y")) print(x*y) elif op==4: x=int(input("enter x")) y=int(input("enter y")) print(x/y) else: print("invalid choice")
0e49ff158c9aacce1854660e39d4ef8c28266cc5
thewchan/python_crash_course
/python_basic/pizza1.py
477
4.09375
4
def make_pizza(*toppings): """Print the list of toppings that have been requested.""" print(toppings) make_pizza('pepperoni') make_pizza('mushrooms', 'green peppers', 'extra cheese') def make_pizza1(*toppings): """Summarize the pizza we are about to make""" print("\nMaking a pizza with the following toppings:") for topping in toppings: print(f"- {topping}") make_pizza1('pepperoni') make_pizza1('mushrooms', 'green peppers', 'extra cheese')
790c7add244f5bed8e7b70a400cfc61f6e82f1ad
thewchan/python_crash_course
/python_basic/admin.py
673
4.03125
4
usernames = ['admin', 'jaden', 'will', 'willow', 'jade'] if usernames: for username in usernames: if username == 'admin': print(f"Hello {username.title()}, would you like to see a status "+ "report?") else: print(f"Hello {username.title()}, thank you for logging in again.") else: print("We need to find some users!\n") current_users = usernames[:] new_users = ['jaden', 'john', 'hank', 'Will', 'cody'] for new_user in new_users: if new_user.lower() in current_users: print(f"{new_user}, you will need a differnt username.") else: print(f"{new_user}, this username is available.")
b8ac3fd6403e0903d4cee84188d0066548a26593
thewchan/python_crash_course
/python_basic/counting_lists.py
551
3.90625
4
#list exercises numbers = range(1, 21) #for number in numbers: # print(number) numbers = range(1, 1_000_001) #for number in numbers: # print(number) million_list = list(range(1, 1_000_001)) print(min(million_list)) print(max(million_list)) print(sum(million_list)) odd_numbers = range(1, 21, 2) for number in odd_numbers: print(number) threes = range(3, 31, 3) for three in threes: print(three) numbers = range(1,11) for number in numbers: print(number ** 3) cubes = [number ** 3 for number in range(1,11)] print(cubes)
91ea218914b1e1e678308f8f2dce8f2422e8af38
thewchan/python_crash_course
/python_basic/movie_tickets.py
341
4.09375
4
age = "" while age != 'quit': age = input("What is your age?\n(Enter 'quit' to exit program) ") if age == 'quit': continue elif int(age) < 3: print("Your ticket is free!") elif int(age) < 12: print("Your ticket price is $10.") elif int(age) >= 12: print("Your ticket price is $15.")
084d8fa68428b070de38472353b3517f5d0cdfa0
Shobhit05/Linux-and-Python-short-scripts
/csvfilereader.py
503
3.75
4
import csv with open('something.csv') as csvfile: readcsv=csv.reader(csvfile,delimiter=',') dates=[] colors=[] for row in readcsv: print row color=row[3] date=row[1] colors.append(color) dates.append(date) print dates print colors try: #some of ur code if it gives the error now except Exception,e: print(e) print('sahdias') print(''' so this is a perfect exapmple of printing the code in another line ''')
5c703ed90acda4eaba3364b6f510d28622ddc4a0
ndenisj/web-dev-with-python-bootcamp
/Intro/pythonrefresher.py
1,603
4.34375
4
# Variables and Concatenate # greet = "Welcome To Python" # name = "Denison" # age = 6 # coldWeather = False # print("My name is {} am {} years old".format(name, age)) # Concatenate # Comment: codes that are not executed, like a note for the programmer """ Multi line comment in python """ # commentAsString = """ # This is more like # us and you can not do that with me # or i will be mad # """ # print(commentAsString) # If statement # if age > 18: # print("You can VOTE") # elif age < 10: # print("You are a baby") # else: # print("You are too young") # FUNCTIONS # def hello(msg, msg2=""): #print("This is a function - " + msg) # hello("Hey") # hello("Hey 2") # LIST - Order set of things like array # names = ["Dj", "Mike", "Paul"] # names.insert(1, "Jay") # # print(names[3]) # # del(names[3]) # # print(len(names)) # length # names[1] = "Peter" # print(names) # LOOPS # names = ["Dj", "Mike", "Paul"] # for name in names: # #print(name) # for x in range(len(names)): # print(names[x]) # for x in range(0, 5): # print(x) # age = 2 # while age < 3: # print(age) # age += 1 # DICTIONARY # allnames = {'Paul': 23, 'Patrick': 32, 'Sally': 12} # print(allnames) # print(allnames['Sally']) # CLASSES # class Dog: # dogInfo = 'Dogs are cool' # # Constructor of the class # def __init__(self, name, age): # self.name = name # self.age = age # def bark(self): # print('Bark - ' + self.dogInfo) # myDog = Dog("Denis", 33) # create an instance or object of the Dog Class # myDog.bark() # print(myDog.age)
590ea704b57b48282c9b8af409c5c5076244a434
ndenisj/web-dev-with-python-bootcamp
/Intro/listDict.py
436
3.90625
4
# LIST names = ['Patrick', 'Paul', 'Maryann', 'Daniel'] # # print(names) # # print(names[1]) # # print(len(names)) # del (names[3]) # names.append("Dan") # print(names) # names[2] = 'Mary' # print(names) for x in range(len(names)): print(names[x]) # DICTIONARY # programmingDict = { # "Name": "Tega", # "Problem": "Thumb Issue", # "Solution": "Go home and rest" # } # print("NAME {}".format(programmingDict['Name'],))
6a34f3d820de100c471e0a8e82cb5372e2eced85
regi18/offset-chiper
/offset-chiper.py
1,914
4.03125
4
""" Decode and Encode text by changing each char by the given offset Created by: regi18 Version: 1.0.4 Github: https://github.com/regi18/offset-chiper """ import os from time import sleep print(""" ____ __ __ _ _____ _ _ / __ \ / _|/ _| | | / ____| | (_) | | | | |_| |_ ___ ___| |_ ______ | | | |__ _ _ __ ___ _ __ | | | | _| _/ __|/ _ \ __| |______| | | | '_ \| | '_ \ / _ \ '__| | |__| | | | | \__ \ __/ |_ | |____| | | | | |_) | __/ | \____/|_| |_| |___/\___|\__| \_____|_| |_|_| .__/ \___|_| | | |_| Created by regi18 """) while True: # reset variables plaintext = "" answer = input("\nDecode(d), Encode(e) or Quit(q)? ").upper() print("\n") # Change every char into his decimal value, add (or subtract) the offset and than save it in plain text. try: if answer == "D": offset = int(input("Enter the offset: ")) text = input("Enter the text to decode: ") for i in text: plaintext += chr((ord(i) - offset)) elif answer == "E": offset = int(input("Enter the offset: ")) text = input("Enter the text to encode: ") for i in text: plaintext += chr((ord(i) + offset)) elif answer == "Q": break else: raise ValueError except ValueError: # handle errors print("\nError, the entered value is not correct\n") sleep(1.2) os.system('cls') continue print("The text is: {}".format(plaintext)) print("") os.system("pause") os.system('cls')
23bdbbe3a731836ff6897d7d15a9feebd191dea2
yongjoons/test1
/019.py
149
3.765625
4
try : num=int(input('enter : ')) print(10/num) except ZeroDivisionError : print('zero') except ValueError: print('num is not int')
d0ee097dd1a70c65be165d7911acfbc09659f199
dokurin/dokushokai
/season2-DDD/cargo-system/sample/customer.py
346
3.5
4
from typing import NewType ID = NewType("CustomerID", str) class Customer(object): """顧客Entity Args: id (ID): 顧客ID name (str): 氏名 Attrubutes: id (ID): 顧客ID name (str): 氏名 """ def __init__(self, id: str, name: ID) -> None: self.id = id self.name = name
313575eca38588d312890f248e02831afcdc65bb
yeming0923/12
/zh_即时标记/002_PYthon callable()函数.py
882
4.03125
4
''' 描述 callable() 函数用于检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败;但如果返回 False,调用对象 object 绝对不会成功。 对于函数、方法、lambda 函式、 类以及实现了 __call__ 方法的类实例, 它都返回 True。 语法 callable()方法语法: callable(object) >> > callable(0) False >> > callable("runoob") False >> > def add(a, b): ... return a + b ... >> > callable(add) # 函数返回 True True >> > class A: # 类 ... def method(self): ... return 0 ... >> > callable(A) # 类返回 True True >> > a = A() >> > callable(a) # 没有实现 __call__, 返回 False False >> > class B: ... def __call__(self): ... return 0 ''' ... >> > callable(B) True >> > b = B() >> > callable(b) # 实现 __call__, 返回 True True
4dedc11bbcb4cf48033088f8cb65e49f59faa0ed
budidino/AoC-python
/2020-d9.py
930
3.515625
4
INPUT = "2020-d9.txt" numbers = [int(line.rstrip('\n')) for line in open(INPUT)] from itertools import combinations def isValid(numbers, number): for num1, num2 in combinations(numbers, 2): if num1 + num2 == number: return True return False def findSuspect(numbers, preamble): for index, number in enumerate(numbers[preamble:], preamble): num = numbers[index-preamble:index] if not isValid(num, number): return number return 0 def findWeakness(numbers, suspect): low, high = 0, 1 setSum = numbers[low] + numbers[high] while setSum != suspect: if setSum < suspect: high += 1 setSum += numbers[high] else: setSum -= numbers[low] low += 1 return min(numbers[low:high+1]) + max(numbers[low:high+1]) suspect = findSuspect(numbers, 25) print(f"part 1: {suspect}") # 257342611 weakness = findWeakness(numbers, suspect) print(f"part 2: {weakness}") # 35602097
019b895273e8298815a4547eb0dde193fd71b8a3
budidino/AoC-python
/2019-d3.py
1,152
3.640625
4
INPUT = "2019-d3.txt" wires = [string.rstrip('\n') for string in open(INPUT)] wire1 = wires[0].split(',') wire2 = wires[1].split(',') from collections import defaultdict path = defaultdict() crossingDistances = set() # part 1 crossingSteps = set() # part 2 def walkTheWire(wire, isFirstWire): x, y, steps = 0, 0, 0 for step in wire: direction = step[0] distance = int(step[1:]) while distance > 0: steps += 1 distance -= 1 if direction == "L": x -= 1 elif direction == "R": x += 1 elif direction == "U": y += 1 else: y -= 1 key = (x, y) if isFirstWire and not key in path: path[key] = steps elif not isFirstWire and key in path: crossingDistances.add(abs(x) + abs(y)) crossingSteps.add(path[key] + steps) walkTheWire(wire1, True) walkTheWire(wire2, False) print(f"part 1: {min(crossingDistances)}") print(f"part 2: {min(crossingSteps)}")
e9812329ff0bf1398fe67004e49a79a1d0075b6c
budidino/AoC-python
/2020-d2.py
443
3.5625
4
INPUT = "2020-d2.txt" strings = [string.strip('\n') for string in open(INPUT)] part1, part2 = 0, 0 for string in strings: policy, password = string.split(': ') numbers, letter = policy.split(' ') minVal, maxVal = map(int, numbers.split('-')) part1 += minVal <= password.count(letter) <= maxVal part2 += (password[minVal-1] == letter) != (password[maxVal-1] == letter) print(f"part 1: {part1}\npart 2: {part2}") # 548 # 502
53c640630c6f2bdfc7199cbe241af57b58e77652
budgiena/domaci_projekty_ZuzkaV
/ukol4_13.py
854
3.765625
4
# --- domaci projekty 4 - ukol 13 --- pocet_radku = int(input("Zadej pocet radku (a zaroven sloupcu): ")) """ # puvodni varianta ##for cislo_radku in range(pocet_radku): ## if cislo_radku in (0,pocet_radku-1): ## for prvni_posledni in range(pocet_radku): ## print ("X", end = " ") ## print ("") ## else: ## for cislo_sloupce in range (pocet_radku): ## if cislo_sloupce in (0,pocet_radku-1): ## print ("X", end = " ") ## else: ## print (" ", end = " ") ## print ("") ## """ for cislo_radku in range(pocet_radku): for cislo_sloupce in range(pocet_radku): if (cislo_radku in (0, pocet_radku-1)) or (cislo_sloupce in (0, pocet_radku-1)): print ("X", end = " ") else: print (" ", end = " ") print ("")
847cf25b568b9ced3123114bafa3e4088c5fb8ef
limiteddays/Programming-tips
/node.py
1,618
3.8125
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: temp1 = "" temp2 = "" current_node_1 = l1 current_node_2 = l2 while True: if current_node_1.next == None: temp1 = str(current_node_1.val) + temp1 break else: temp1 = str(current_node_1.val) + temp1 current_node_1 = current_node_1.next while True: if current_node_2.next == None: temp2 = str(current_node_2.val) + temp2 break else: temp2 = str(current_node_2.val) + temp2 current_node_2 = current_node_2.next # ans_list = (list(val1 + val2)).reverse() temp3 = int(temp1) + int(temp2) temp3 = str(temp3)[::-1] i = 0 for x in temp3: if i == 0: ans_node = ListNode(int(x),None) current_node = ans_node else: new_node = ListNode(int(x),None) current_node.next = new_node current_node = new_node i += 1 return ans_node if __name__ == '__main__': c = ListNode(1,None) b = ListNode(2,c) a = ListNode(3,b) sol = Solution() print(sol.addTwoNumbers(a,a))
461af0dc439dfcf33b2dd0bfcf6d4a684949171d
limiteddays/Programming-tips
/forge_rever.py
473
3.796875
4
class Tree(object): x = 0 l = None r = None def traverse(sub_tree, height): left_height = 0 right_height = 0 if sub_tree.l: left_height = traverse(sub_tree.l, height + 1) if sub_tree.r: right_height = traverse(sub_tree.r, height + 1) if sub_tree.l or sub_tree.r: return max(left_height, right_height) else: return height def solution(T): # write your code in Python 3.6 return traverse(T, 0)
6929627ac4b226a8364a5708b8243b2f9eddf454
jaydeu/Python-Programs
/Aug_12_2015.py
2,815
3.65625
4
######################################################## ### Daily Programmer 226 Intermediate - Connect Four ### ######################################################## # Source: r/dailyprogrammer ''' This program tracks the progress of a game of connect-four, checks for a winner, then outputs the number of moves and position of four winning pieces. ''' import pandas as pd from pandas import DataFrame from math import floor import sys ### Read in the list of moves from a text file f = open('inputs\226_int_2.txt', 'r') ### Create a game board board = DataFrame(index=range(1,7), columns=list('ABCDEFG')) board = board.fillna('.') ### Initialize next free space and move count dictionaries next_free_space = {'A':6, 'B':6, 'C':6, 'D':6, 'E':6, 'F':6, 'G':6} move_count = {'X':0, 'O':0} ### Function that adds a move to the board def add_move(col, player): global board, next_free_space, move_count board[col][next_free_space[col]] = player next_free_space[col] -= 1 move_count[player] += 1 ### Create our sequences to check for winners sequences = [] # rows for i in range(0,6): sequences.append(range(7*i, 7+7*i)) # columns for i in range(0,7): sequences.append([7*j + i for j in range(0,6)]) # diagonals diag_length = [4,5,6,6,5,4] # diagonals right diags_right = [14,7,0,1,2,3] for i in range(0,len(diags_right)): sequences.append([8*j + diags_right[i] for j in range(0, diag_length[i])]) # diagonals left diags_left= [3,4,5,6,13,20] for i in range(0,len(diags_left)): sequences.append([6*j + diags_left[i] for j in range(0, diag_length[i])]) ### Function that changes an index number to coordinates def num_to_coord(n): row = int(floor(n/7))+1 col = list('ABCDEFG')[n%7] return str(col)+str(row) ### Function to be run when a winner is found. Prints number of moves, winning positions and the final board. def winner_found(player,code, vector, line): print "%s is a winner in %d moves!" % (player, move_count[player]) start = line.find(code) for i in range(0,4): print num_to_coord(vector[start+i]) print board f.close() sys.exit() ### Function that checks for winners def check_winners(): boardList = board.values.flatten() for s in sequences: check_line = "".join([boardList[i] for i in s]) if "XXXX" in check_line: winner_found('X','XXXX', s, check_line) if "OOOO" in check_line: winner_found('O','OOOO', s, check_line) ########################################## for line in f: next = line.split(" ") move_X = next[0] move_O = next[1].upper().rstrip() #Add an X add_move(move_X, 'X') check_winners() #Add an O add_move(move_O, 'O') check_winners() f.close() print "Nobody won!"
1c32272ef45f6e6958cee58d95088c5b475269b1
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Tuplas.py
808
4.28125
4
# La tupla luego de ser inicializada no se puede modificar frutas = ("Naranja", "Platano", "Guayaba") print(frutas) print(len(frutas)) print(frutas[0]) # Acceder a un elemento print(frutas[-1]) # Navegación inversa #Tambien funcionan los rangos igual que en las listas print(frutas[0:2]) # Una Lista se puede inicializar con una tubpla frutasLista = list(frutas) frutasLista[1] = "Platanito" # Una tupla se puede modificar, metiendo una lista que sustituye su valor frutas = tuple(frutasLista) # Iterar sobre la tupla, esto se realiza de igual manera que con las listas for fruta in frutas: print(fruta, end=" ") #El end=" " indica como queremos que finalize el imprimir fruta #Tarea tupla = (13, 1, 8, 3, 2, 5, 8) lista = [] for t in tupla: if t < 5: lista.append(t) print(lista)
236756b3ed86fc33bb38ab279c03792e6aa312a6
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Clases.py
2,012
3.953125
4
class Persona: #Contructor def __init__(self, nombre, edad): self.nombre = nombre self.edad = edad class Aritmetica: #Constructor def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def suma(self): return self.num1 + self.num2 class Retangulo: #Constructor def __init__(self, base, altura): self.base = base self.altura = altura def calcularArea(self): return self.base * self.altura class Caja: #Contructor def __init__(self, largo, ancho, alto): self.largo = largo self.ancho = ancho self.alto = alto def Volumen(self): return self.largo * self.ancho * self.alto #El parametro self se puede cambiar por cualquier otro palabra siempre y # cuando se utilice de la misma manera, asi mismo se puede colocar otros # nombres a los parametros y lo que quedaran como nombres de los atributos # son los que esten con self class Carro: #Constructor def __init__(this, n, e, *v, **d): #El "*" significa que el parametro es una tupla y es opcional this.marca = n # el "**" significa que el parametro es un diccionario y es opcional this.modelo = e this.valores = v this.diccionario = d def desplegar(this): print("Marca:", this.marca) print("Modelo:", this.modelo) print("Valores (Tupla):", this.valores) print("Dicionario:", this.diccionario) carro = Carro("Toyota", "Yaris", 2,4,5) print(carro.desplegar()) carro2 = Carro("Volvo", "S40", 4,9,5, m="Manzana", p="Pera", j="Jicama") print(carro2.desplegar()) #Instanciar una clase persona = Persona("Sergio", 22) print(persona.nombre, persona.edad) aritmetica = Aritmetica(2, 4) print("Resultado suma:", aritmetica.suma()) base = int(input("Ingrese base del Retangulo: ")) altura = int(input("Ingrese altura del retangulo: ")) retangulo = Retangulo(base, altura) print(retangulo.calcularArea())
3c004f1b944ab083ef565a4e48106303ee124904
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Metodos Privados.py
500
3.53125
4
class Persona: def __init__(self, nombre, apellido, apodo): self.nombre = nombre #Atributo public self._apellido = apellido #Atributo protected "_" self.__apodo = apodo #Atributo privado "__" def metodoPublico(self): self.__metodoPrivado() def __metodoPrivado(self): print(self.nombre) print(self._apellido) print(self.__apodo) p1 = Persona("Sergio", "Lara", "Chejo") print(p1.nombre) print(p1._apellido)
5ad72e3d56246bc745fb208eb7e8a74860c66a3d
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Manejo de Archivos.py
1,214
3.78125
4
#Abre un archivo # open() tiene dos parametros, el primero el archivo y el segundo lo que se desea hacer # r - Read the default value. Da error si no existe el archivo # a - Agrega info al archivo. Si no existe lo crea # w - Escribir en un archivo. Si no existe lo crea. Sobreescribe el archivo # x - Crea un archivo. Retorna error si el archivo ya existe try: archivo = open("File_Manejo_Archivos.txt", "w") archivo.write("Agregando información al archivo \n") archivo.write("Agregando linea 2") archivo = open("File_Manejo_Archivos.txt", "r") ''' Formas de leer un archivo print(archivo.read()) # Leer archivo completo print(archivo.read(5)) # Numero de caracteres a leer print(archivo.readline()) # Leer una linea print(archivo.readlines()) # Lee todas las linea, agrega todo a una lista print(archivo.readlines()[1]) # Lee solo la linea con indice 1 for linea in archivo: print(linea) ''' # Copiando un archivo a otro archivo2 = open("File_Copia.txt", "w") archivo2.write(archivo.read()) except Exception as e: print(e) finally: archivo.close() # No es obligatorio archivo2.close()
409574344dcb3ca84b2da297f0dfa35d721fd7b2
gitter-badger/cayenne
/cayenne/results.py
7,558
3.625
4
""" Module that defines the `Results` class """ from collections.abc import Collection from typing import List, Tuple, Iterator from warnings import warn import numpy as np class Results(Collection): """ A class that stores simulation results and provides methods to access them Parameters ---------- species_names : List[str] List of species names rxn_names : List[str] List of reaction names t_list: List[float] List of time points for each repetition x_list: List[np.ndarray] List of system states for each repetition status_list: List[int] List of return status for each repetition algorithm: str Algorithm used to run the simulation sim_seeds: List[int] List of seeds used for the simulation Notes ----- The status indicates the status of the simulation at exit. Each repetition will have a status associated with it, and these are accessible through the ``status_list``. 1: Succesful completion, terminated when ``max_iter`` iterations reached. 2: Succesful completion, terminated when ``max_t`` crossed. 3: Succesful completion, terminated when all species went extinct. -1: Failure, order greater than 3 detected. -2: Failure, propensity zero without extinction. """ def __init__( self, species_names: List[str], rxn_names: List[str], t_list: List[np.ndarray], x_list: List[np.ndarray], status_list: List[int], algorithm: str, sim_seeds: List[int], ) -> None: self.species_names = species_names self.rxn_names = rxn_names self.x_list = x_list self.t_list = t_list self.status_list = status_list self.algorithm = algorithm self.sim_seeds = sim_seeds if not self._check_consistency(): raise ValueError("Inconsistent results passed") def _check_consistency(self) -> bool: """ Check consistency of results Returns ------- bool True if results are consistent False otherwise """ if ( len(self.x_list) == len(self.t_list) == len(self.status_list) == len(self.sim_seeds) ): pass else: return False for x, t, status in self: if x.shape[0] != t.shape[0]: return False if x.shape[1] != len(self.species_names): return False if not isinstance(status, int): return False return True def __repr__(self) -> str: """ Return summary of simulation. Returns ------- summary: str Summary of the simulation with length of simulation, algorithm and seeds used. """ summary = f"<Results species={self.species_names} n_rep={len(self)} " summary = summary + f"algorithm={self.algorithm} sim_seeds={self.sim_seeds}>" return summary def __str__(self) -> str: """ Return self.__repr__() """ return self.__repr__() def __iter__(self) -> Iterator[Tuple[np.ndarray, np.ndarray, int]]: """ Iterate over each repetition """ return zip(self.x_list, self.t_list, self.status_list) def __len__(self) -> int: """ Return number of repetitions in simulation Returns ------- n_rep: int Number of repetitions in simulation """ n_rep = len(self.x_list) return n_rep def __contains__(self, ind: int): """ Returns True if ind is one of the repetition numbers """ if ind < len(self): return True else: return False def __getitem__(self, ind: int) -> Tuple[np.ndarray, np.ndarray, int]: """ Return sim. state, time points and status of repetition no. `ind` Parameters ---------- ind: int Index of the repetition in the simulation Returns ------- x_ind: np.ndarray Simulation status of repetition no. `ind` t_ind: np.ndarray Time points of repetition no. `ind` status_ind Simulation end status of repetition no. `ind` """ if ind in self: x_ind = self.x_list[ind] t_ind = self.t_list[ind] status_ind = self.status_list[ind] else: raise IndexError(f"{ind} out of bounds") return x_ind, t_ind, status_ind @property def final(self) -> Tuple[np.ndarray, np.ndarray]: """ Returns the final times and states of the system in the simulations Returns ------- Tuple[np.ndarray, np.ndarray] The final times and states of the sytem """ final_times = np.array([v[1][-1] for v in self]) final_states = np.array([v[0][-1, :] for v in self]) return final_times, final_states def get_state(self, t: float) -> List[np.ndarray]: """ Returns the states of the system at time point t. Parameters ---------- t: float Time point at which states are wanted. Returns ------- List[np.ndarray] The states of the system at `t` for all repetitions. Raises ------ UserWarning If simulation ends before `t` but system does not reach extinction. """ states: List[np.ndarray] = [] e = np.finfo(float).eps * t t = t + e for x_array, t_array, s in self: ind = np.searchsorted(t_array, t) ind = ind - 1 if ind > 0 else ind if ind == len(t_array) - 1: states.append(x_array[-1, :]) if s != 3: warn(f"Simulation ended before {t}, returning last state.") else: x_interp = np.zeros(x_array.shape[1]) if self.algorithm != "direct": for ind2 in range(x_array.shape[1]): x_interp[ind2] = np.interp( t, [t_array[ind], t_array[ind + 1]], [x_array[ind, ind2], x_array[ind + 1, ind2]], ) states.append(x_interp) else: states.append(x_array[ind, :]) return states def get_species(self, species_names: List[str]) -> List[np.ndarray]: """ Returns the species concentrations only for the species in species_names Parameters --------- species_names : List[str] The names of the species as a list Returns ------ List[np.ndarray] Simulation output of the selected species. """ x_list_curated = [] species_inds = [self.species_names.index(s) for s in species_names] for rep_ind in range(len(self)): x_list_curated.append(self[rep_ind][0][:, species_inds]) return x_list_curated
10194946199773e708b6a020c01dd7f01af2efee
FlyingSparkie/Raspberry-Pi-stuff
/gpioLed.py
1,582
3.75
4
import RPi.GPIO as GPIO #import the gpio library from time import sleep #import time library redLed=22 #what pin greenLed=23 blinkTimes=[0,1,2,3,4] button=17 inputButton=False range(5) GPIO.setmode(GPIO.BCM) #set gpio mode BCM, not BOARD GPIO.setup(greenLed, GPIO.OUT) #make it an output GPIO.setup(redLed, GPIO.OUT) #make it an output GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #GPIO.output(yellowLed, False) #turn on(True) off(False) #GPIO.cleanup() #reset the pins #GPIO.setmode(GPIO.BCM) #while True: # GPIO.output(yellowLed, True) # sleep(1) # GPIO.output(yellowLed, False) # sleep(1) #iterate list to blink variable #for i in blinkTimes: # GPIO.output(yellowLed, True) # sleep(1) # GPIO.output(yellowLed, False) # sleep(1) try: while True: # inputButton=GPIO.input(button) #if inputButton==True: # print("Buttun pressed") sleep(3) #range example for i in range(5): GPIO.output(greenLed, True) sleep(1) GPIO.output(greenLed, False) sleep(1) for i in range(5): GPIO.output(greenLed, True) sleep(.25) GPIO.output(greenLed, False) sleep(.25) for i in range(3): GPIO.output(redLed, True) sleep(4) GPIO.output(redLed, False) sleep(.25) except KeyboardInterrupt: print("Finished") GPIO.cleanup()
fefc1ce3e2a8afcb32c09d05242089acfba1d567
ZahedAli97/Py-DataStructures
/circularlinkedlist.py
1,829
3.75
4
class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None def taverse(self): temp = self.head if self.head is not None: while True: print(temp.data, end="") print("->", end="") temp = temp.next if temp == self.head: break print("") def addNode(self, data): new = Node(data) temp = self.head new.next = temp if self.head: while temp.next != self.head: temp = temp.next temp.next = new else: new.next = new self.head = new def deleteNode(self, data): temp = self.head prev = self.head while temp.next.data != data: prev = temp.next temp = temp.next temp = temp.next prev.next = temp.next def reverseList(self): prev = None current = self.head # post = current.next # current.next = prev # current = post back = current while current.next != self.head: post = current.next current.next = prev prev = current current = post current.next = prev self.head = current back.next = self.head if __name__ == "__main__": cll = CircularLinkedList() cll.addNode(1) cll.addNode(2) cll.addNode(3) cll.taverse() cll.deleteNode(2) cll.taverse() cll.addNode(7) cll.addNode(10) cll.addNode(29) cll.addNode(32) cll.taverse() cll.deleteNode(10) cll.taverse() cll.reverseList() cll.taverse() cll.reverseList() cll.taverse()
ba2ac685e5bb3fa8a3632b8ddf46fb804113c8ca
Elmuti/tools
/downloader/downloader.py
346
3.5625
4
# File downloader - downloads files from a list # Usage: # python downloader.py links.txt /downloaddir/ import urllib, sys links = sys.argv[1] dldir = sys.argv[2] for line in open(links, "r"): filename = line.split("/")[-1].rstrip('\n') filepath = dldir+filename print "Downloading: ",filename urllib.urlretrieve(line, filepath)
d343dd2b8da73751e837c98ec58ec0fb7b734080
AYSEOTKUN/my-projects
/python/hands-on/flask-04-handling-forms-POST-GET-Methods/Flask_GET_POST_Methods_1/app.py
1,011
3.5625
4
# Import Flask modules from flask import Flask,render_template,request # Create an object named app app = Flask(__name__) # Create a function named `index` which uses template file named `index.html` # send three numbers as template variable to the app.py and assign route of no path ('/') @app.route('/') def index(): return render_template('index.html') # calculate sum of them using inline function in app.py, then sent the result to the # "number.hmtl" file and assign route of path ('/total'). # When the user comes directly "/total" path, "Since this is GET # request, Total hasn't been calculated" string returns to them with "number.html" file @app.route('/',methods=["GET","POST"]) def total(): if request.method =="POST": value1 = request.form.get("value1") value2 = request.form.get("value2") value3 = request.form.get("value3") return render_template("number.html") if __name__ == '__main__': #app.run(debug=True) app.run(host='0.0.0.0', port=80)
f02b8bd1b982abd5bfa37caba9922ae191d9f551
tejashrikelhe/Collatz-conjecture
/collatez conjecture.py
1,214
3.8125
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 17 22:46:10 2020 @author: TEJASHRI """ import matplotlib.pyplot as plt y=[] x=[] a=1 while(a==1): i=0 n=int(input("enter a no=")) x.append(n) while(n!=1): if(n%2==0): n=n/2 print(n) else: n=(3*n)+1 print(n) i=i+1 y.append(i) print("Number of itteration for given ip=") print(i) a=int(input("do you want to continue? If yes enter 1, else enter 0=")) #plot for number of iterations needed for a given input plt.plot(x,y) # naming the x axis plt.xlabel('input value') # naming the y axis plt.ylabel('number of itterations') plt.title('number of iterations needed for a given input') plt.show() #Histogram # setting the ranges and no. of intervals range = (0,100) bins = 10 # plotting a histogram #plt.hist(x, bins, range, color = 'blue', histtype = 'bar', rwidth = 0.8) plt.hist(x,bins,range) # x-axis label plt.xlabel('Input Number') # frequency label plt.ylabel('No. of itterations') plt.title('histogram of Number and itterations') plt.show()
4776ee86a215e14e367a14b74073c1c712233dc6
suyash248/ds_algo
/Array/flipZeroesMaximizeOnes.py
2,484
3.703125
4
# Time complexity: O(n) # Using sliding window strategy. from typing import List def flip_m_zeroes_largest_subarray_with_max_ones(arr, m): """ Algorithm - - While `zeroes_count` is no more than `m` : expand the window to the right (w_right++) and increment the zeroes_count. - While `zeroes_count` exceeds `m`, shrink the window from left (w_left++), decrement `zeroes_count`. - Update the widest window(`best_w_left`, `best_w_size`) along the way. The positions of output 0's are inside the best window. :param arr: Input array. :param m: Maximum number of 0's that can be flipped in `arr` in order to get largest window/sub-array of 1's. :return: """ w_left = w_right = best_w_left = best_w_size = zeroes_count = 0 while w_right < len(arr): if zeroes_count <= m: if arr[w_right] == 0: zeroes_count += 1 w_right += 1 if zeroes_count > m: if arr[w_left] == 0: zeroes_count -= 1 w_left += 1 curr_w_size = w_right - w_left if curr_w_size > best_w_size: best_w_left = w_left best_w_size = curr_w_size best_w_right = best_w_left + best_w_size - 1 best_w = (best_w_left, best_w_right) flip_zero_at_indices = [] for i in range(best_w_left, best_w_right+1): # for i=0; i < best_w_size; i++ if arr[i] == 0: flip_zero_at_indices.append(i) return { "largestWindow": best_w, "largestWindowSize": best_w_size, "flipZeroAtIndices": flip_zero_at_indices } if __name__ == '__main__': ################### TC - 1 ################### nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0] threshold = 2 window_details = flip_m_zeroes_largest_subarray_with_max_ones(nums, threshold) print("Flip 0's at indices {flipZeroAtIndices} to get the maximum window/sub-array of size {largestWindowSize} " \ "where window start & end indices are {largestWindow}".format(**window_details)) ################### TC - 2 ################### nums = [0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1] threshold = 3 window_details = flip_m_zeroes_largest_subarray_with_max_ones(nums, threshold) print("Flip 0's at indices {flipZeroAtIndices} to get the maximum window/sub-array of size {largestWindowSize} " \ "where window start & end indices are {largestWindow}".format(**window_details))
8212efa038c42c118856cb6a50b0d7e9ce1844d2
suyash248/ds_algo
/Tree/traversals.py
2,036
3.921875
4
from Tree.commons import insert, print_tree, is_leaf def preorder(root): if root: print(root.key, end=',') preorder(root.left) preorder(root.right) def inorder(root): if root: inorder(root.left) print(root.key, end=',') inorder(root.right) def postorder(root): if root: postorder(root.left) postorder(root.right) print(root.key, end=',') def level_order(root): from queue import Queue q = Queue() q.put(root) while not q.empty(): popped_elt = q.get() print(popped_elt.key, end=',') if popped_elt.left: q.put(popped_elt.left) if popped_elt.right: q.put(popped_elt.right) def spiral(root): stack1 = [root] stack2 = [] while len(stack1) or len(stack2): while len(stack1): popped_node = stack1.pop() print(popped_node.key, end=',') # left first then right if popped_node.left is not None: stack2.append(popped_node.left) if popped_node.right is not None: stack2.append(popped_node.right) while len(stack2): popped_node = stack2.pop() print(popped_node.key, end=',') # right first then left if popped_node.right is not None: stack1.append(popped_node.right) if popped_node.left is not None: stack1.append(popped_node.left) # Driver program to test above function if __name__ == "__main__": """ Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 """ root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) print("In-Order is - ") inorder(root) print("\nPre-Order is - ") preorder(root) print("\nPost-Order is - ") postorder(root) print("\nLevel-Order is - ") level_order(root) print("\nSprial(zig-zag)-Order is - ") spiral(root)
57bade1fd06c0bf6e9814bea60b5e4e6a8d35163
suyash248/ds_algo
/Queues/queueUsingStack.py
1,364
4.15625
4
class QueueUsingStack(object): __st1__ = list() __st2__ = list() def enqueue(self, elt): self.__st1__.append(elt) def dequeue(self): if self.empty(): raise RuntimeError("Queue is empty") if len(self.__st2__) == 0: while len(self.__st1__) > 0: self.__st2__.append(self.__st1__.pop()) return self.__st2__.pop() def size(self): return len(self.__st1__) + len(self.__st2__) def empty(self): return len(self.__st1__) == 0 and len(self.__st2__) == 0 if __name__ == '__main__': q = QueueUsingStack() choices = "1. Enqueue\n2. Dequeue\n3. Size\n4. Is Empty?\n5. Exit" while True: print choices choice = input("Enter your choice - ") if choice == 1: elt = raw_input("Enter element to be enqueued - ") q.enqueue(elt) elif choice == 2: try: elt = q.dequeue() print "Dequeued:", elt except Exception as e: print "Error occurred, queue is empty?", q.empty() elif choice == 3: print "Size of queue is", q.size() elif choice == 4: print "Queue is", "empty" if q.empty() else "not empty." elif choice == 5: break else: print "Invalid choice"
589fe67c8ae98e36a621432ab7abb275156172cd
suyash248/ds_algo
/Misc/sliding_window/count_good_strings.py
2,108
3.875
4
''' A string is good if there are no repeated characters. Given a string s and integer k, return the number of good substrings of length k in s​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A substring is a contiguous sequence of characters in a string. Example 1: Input: s = "xyzzaz", k = 3 Output: 1 Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". The only good substring of length 3 is "xyz". Example 2: Input: s = "aababcabc", k = 3 Output: 4 Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc". The good substrings are "abc", "bca", "cab", and "abc". Constraints: 1 <= s.length <= 100 s​​​​​​ consists of lowercase English letters. ''' from typing import List def count_good_strings(chars: List[str], k: int) -> int: l, gc, r = 0, 0, k substr = dict() for i in range(min(k, len(chars))): substr[chars[i]] = substr.get(chars[i], 0) + 1 if len(substr) == k: gc += 1 while r < len(chars): substr[chars[r]] = substr.get(chars[r], 0) + 1 if substr[chars[l]] > 1: substr[chars[l]] -= 1 else: substr.pop(chars[l]) if len(substr) == k: gc += 1 r += 1 l += 1 return gc def brute_force(chars: List[str], k: int) -> int: gc = 0 for i in range(len(chars)): sub_str = chars[i: i + k] if len(set(sub_str)) == 3: gc += 1 return gc if __name__ == '__main__': k = 3 chars = ['a', 'a', 'b', 'a', 'b', 'c', 'a', 'b', 'c'] # ['a', 'b', 'c', 't'] gc = count_good_strings(chars, k) print(chars, gc) gc = brute_force(chars, k) print(chars, gc) chars = ['o', 'w', 'u', 'x', 'o', 'e', 'l', 's', 'z', 'b'] gc = count_good_strings(chars, k) print(chars, gc) gc = brute_force(chars, k) print(chars, gc) chars = ['x'] gc = count_good_strings(chars, k) print(chars, gc) gc = brute_force(chars, k) print(chars, gc)
61e6633eeadf4384a18603640e30e0fa0a6998c8
suyash248/ds_algo
/Array/stockSpanProblem.py
959
4.28125
4
from Array import empty_1d_array # References - https://www.geeksforgeeks.org/the-stock-span-problem/ def stock_span(prices): # Stores index of closest greater element/price. stack = [0] spans = empty_1d_array(len(prices)) # Stores the span values, first value(left-most) is 1 as there is no previous greater element(price) available. spans[0] = 1 # When we go from day i-1 to i, we pop the days when the price of the stock was less than or equal to price[i] and # then push the value of day i back into the stack. for i in range(1, len(prices)): cur_price = prices[i] while len(stack) != 0 and prices[stack[-1]] <= cur_price: stack.pop() spans[i] = (i+1) if len(stack) == 0 else (i-stack[-1]) stack.append(i) return spans if __name__ == '__main__': prices = [10, 4, 5, 90, 120, 80] spans = stock_span(prices) print("Prices:", prices) print("Spans:", spans)
6e8ee71a88eb45d5849993481a375a0d6a625afa
suyash248/ds_algo
/DynamicProgramming/minJumpsToReachEndOfArray.py
960
3.65625
4
from Array import empty_1d_array, MAX # Time complexity: O(n^2) # https://www.youtube.com/watch?v=jH_5ypQggWg def min_jumps(arr): n = len(arr) path = set() jumps = empty_1d_array(n, MAX) jumps[0] = 0 for i in xrange(1, n): for j in xrange(0, i): if i <= j + arr[j]: # Checking if `i` can be reached from `j` if jumps[j] + 1 < jumps[i]: jumps[i] = jumps[j] + 1 # jumps[i] = min(jumps[i], jumps[j] + 1) path.add(j) path.add(arr[-1]) # adding last element(destination) to path #print jumps, path return path if __name__ == '__main__': arr = [2, 3, 1, 1, 2, 4, 2, 0, 1, 1] path = min_jumps(arr) minimum_jumps = len(path) - 1 path = " -> ".join(map(lambda x: str(x), path)) print "To reach at the end, at least {} jump(s) are required and path(indices): {}".format(minimum_jumps, path)
2439116226bb241f4f6d138e4725607724c6e343
suyash248/ds_algo
/Tree/segment_tree/base_segment_tree.py
599
3.6875
4
from Array import empty_1d_array from math import pow, log, ceil """ Height of segment tree is log(n) #base 2, and it will be full binary tree. Full binary tree with height h has at most 2^(h+1) - 1 nodes. Segment tree will have exactly n leaves. """ class SegmentTree(object): def __init__(self, input_arr): self.input_arr = input_arr self.n = len(input_arr) self.height = ceil(log(self.n, 2)) # 2^(h+1) - 1, where h = log(n) // base 2 self.seg_tree_size = int(pow(2, self.height + 1) - 1) self.seg_tree_arr = empty_1d_array(self.seg_tree_size)
dad7df39a66de05b8743e5b6a8e52de20b24531f
suyash248/ds_algo
/Array/nextGreater.py
1,602
3.90625
4
""" Algorithm - 1) Push the first element to stack. 2) for i=1 to len(arr): a) Mark the current element as `cur_elt`. b) If stack is not empty, then pop an element from stack and compare it with `cur_elt`. c) If `cur_elt` is greater than the popped element, then `cur_elt` is the next greater element for the popped element. d) Keep popping from the stack while the popped element is smaller than `cur_elt`. `cur_elt` becomes the next greater element for all such popped elements. g) If `cur_elt` is smaller than the popped element, then push the popped element back to stack. 3) After the loop in step 2 is over, pop all the elements from stack and print -1 as next greater element for them. """ # Time Complexity: O(n) def next_greater(arr): stack = list() stack.append(arr[0]) for cur_elt in arr[1:]: if len(stack) > 0: popped_elt = stack.pop() if popped_elt < cur_elt: while popped_elt < cur_elt: print "{} -> {}".format(popped_elt, cur_elt) # Keep popping element until either stack becomes empty or popped_elt >= cur_elt if len(stack) == 0: break popped_elt = stack.pop() else: # If popped_elt >= cur_elt, push it back to stack and continue stack.append(popped_elt) # Push cur_elt to stack stack.append(cur_elt) while len(stack) > 0: print "{} -> {}".format(stack.pop(), -1) if __name__ == '__main__': arr = [4, 5, 2, 25] next_greater(arr)
c26340df6acd4f7cbe5fa2060212013b618b7f43
suyash248/ds_algo
/Tree/distanceBetweenNodes.py
1,301
3.984375
4
from Tree.commons import insert def distance_between_nodes(root, key1, key2): """ Dist(key1, key2) = Dist(root, key1) + Dist(root, key2) - 2*Dist(root, lca) Where lca is lowest common ancestor of key1 & key2 :param root: :param key1: :param key2: :return: """ from Tree.distanceFromRoot import distance_from_root_v1 from Tree.lowestCommonAncestor import lca_v2 d1 = distance_from_root_v1(root, key1) d2 = distance_from_root_v1(root, key1) lca = lca_v2(root, key1, key2) if lca is None: return 0 # When either of key1 or key2 is not found, distance is 0 d_lca = distance_from_root_v1(root, lca.key) return (d1 + d2 - 2*d_lca) # Driver program to test above function if __name__ == "__main__": """ Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 / \ 15 25 """ root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 15) insert(root, 25) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) key1= 60; key2 = 30 d = distance_between_nodes(root, key1, key2) print("Distance between {key1} & {key2} is {d}".format(key1=key1, key2=key2, d=d))
a8e3dc574a5a78960baaf96994c73f8ea5df4269
suyash248/ds_algo
/Tree/treeSerialization.py
1,906
3.53125
4
from commons.commons import insert, Node, print_tree class BinaryTreeSerialization(object): def __init__(self, delimiter=None): self.delimiter = delimiter self.index = 0 def __preorder__(self, root, serialized_tree=[]): if root is None: serialized_tree.append(self.delimiter) return None serialized_tree.append(root.key) self.__preorder__(root.left, serialized_tree) self.__preorder__(root.right, serialized_tree) def serialize(self, root): serialized_tree = [] self.__preorder__(root, serialized_tree) return serialized_tree def deserialize(self, serialized_tree): self.index = 0 root = self.__deserialize__(serialized_tree) return root def __deserialize__(self, serialized_tree): if self.index >= len(serialized_tree) or serialized_tree[self.index] == self.delimiter: self.index += 1 return None root = Node(serialized_tree[self.index]) self.index += 1 root.left = self.__deserialize__(serialized_tree) root.right = self.__deserialize__(serialized_tree) return root if __name__ == '__main__': root = Node(7, left=Node(2, left=Node(1) ), right=Node(5, left=Node(3), right=Node(8) ) ) print "\nInput Tree - \n" print_tree(root) print "\n************* SERIALIZATION *************\n" obj = BinaryTreeSerialization() serialized_tree = obj.serialize(root) print "Serialized Tree (Preorder) -", serialized_tree print "\n************* DE-SERIALIZATION *************\n" deserialized_tree_root = obj.deserialize(serialized_tree) print "\nOutput Tree - \n" print_tree(deserialized_tree_root)
576f7c47da643057c2643ba703b65e917a6597d4
suyash248/ds_algo
/Array/factorial.py
238
3.765625
4
def fact_rec(n): if n <= 1: return 1 return n * fact_rec(n-1) def fact_itr(n): fact = 1 for i in range(2, n+1): fact *= i return fact if __name__ == '__main__': print (fact_rec(5)) print (fact_itr(5))
d21394227d4390b898fc1588593e43616ed7e502
suyash248/ds_algo
/Misc/sliding_window/substrings_with_distinct_elt.py
2,324
4.125
4
''' Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c. Example 1: Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). Example 2: Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". Example 3: Input: s = "abc" Output: 1 Constraints: 3 <= s.length <= 5 x 10^4 s only consists of a, b or c characters. ''' def __num_substrings_brute_force__(s: str) -> int: k = 3 res = 0 substr = dict() for i in range(min(k, len(s))): substr[s[i]] = substr.get(s[i], 0) + 1 if len(substr) == k: res += 1 for i in range(0, len(s) - k): left_elt = s[i] right_elt = s[i + k] substr[right_elt] = substr.get(right_elt, 0) + 1 if substr.get(left_elt) > 0: substr[left_elt] -= 1 else: substr.pop(left_elt) if len(substr) == k: res += 1 return res def num_substrings_brute_force(s: str) -> int: res = 0 for i in range(len(s)): res += __num_substrings_brute_force__(s[i:]) return res ############################################################################### def num_substrings_sliding_window(s: str) -> int: left = 0 right = 0 end = len(s) - 1 hm = dict() count = 0 while right != len(s): hm[s[right]] = hm.get(s[right], 0) + 1 while hm.get('a', 0) > 0 and hm.get('b', 0) > 0 and hm.get('c', 0) > 0: count += 1 + (end - right) hm[s[left]] -= 1 left += 1 right += 1 return count if __name__ == '__main__': s = "abcabc" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res) s = "aaacb" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res) s = "abc" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res)
447b5ce60dbe48b380de406540702ef28d034e84
suyash248/ds_algo
/Backtracking/allCombinations.py
2,187
3.53125
4
from Array import empty_1d_array # Time Complexity: O(2^n) def all_combinations(input_seq, combinations): for elt in input_seq: comb_len = len(combinations) for si in range(0, comb_len): combinations.append(combinations[si] + elt) """ {} a {} ab a b {} abc ab ac a bc b c {} """ # Time Complexity: O(2^n) def all_combinations_v2(input_seq, res, level): if level == len(input_seq): all_combinations_v2.combinations.add(res) return all_combinations_v2(input_seq, res, level + 1) all_combinations_v2(input_seq, res+input_seq[level], level + 1) # This solution takes care of duplicates as well. # https://www.youtube.com/watch?v=xTNFs5KRV_g # Time Complexity: O(2^n) def all_combinations_v3(input_seq, count, pos, combinations, level): # print till pos print_till_pos(combinations, level) for i in range(pos, len(input_seq)): if count[i] == 0: continue combinations[level] = input_seq[i] count[i] -= 1 all_combinations_v3(input_seq, count, i, combinations, level+1) count[i] += 1 def print_till_pos(arr, pos): res = "" for elt in arr[:pos]: res += elt print res, if __name__ == '__main__': input_seq = "aabc" print "\n------------------- Using V1 -------------------\n" combinations = [""] # empty list all_combinations(input_seq, combinations) print "All the combinations of {} are -\n".format(input_seq), ' '.join(combinations) print "\n------------------- Using V2 -------------------\n" all_combinations_v2.combinations = set() all_combinations_v2(input_seq, "", 0) print "All the combinations of {} are - ".format(input_seq) for c in all_combinations_v2.combinations: print c, print "" print "\n------------------- Using V3 -------------------\n" ch_counts = {ch: input_seq.count(ch) for ch in input_seq} print "All the combinations of {} are - ".format(input_seq) all_combinations_v3(ch_counts.keys(), ch_counts.values(), 0, empty_1d_array(len(input_seq)), 0)
bb174384697c54d507e314d4df23a66f32f10d0a
suyash248/ds_algo
/DynamicProgramming/stiver/climbingStairs.py
503
3.59375
4
def climbStairs(n: int) -> int: # dp = [-1 for i in range(n+1)] # def f(i, dp): # if i <= 1: # return 1 # if dp[i] != -1: # return dp[i] # dp[i] = f(i-1, dp) + f(i-2, dp) # return dp[i] # return f(n, dp) dp = [0 for i in range(n + 1)] for i in range(n + 1): if i <= 1: dp[i] = 1 else: dp[i] = dp[i - 1] + dp[i - 2] return dp[n] if __name__ == '__main__': print(climbStairs(2))
8df5ea6094331a9249b66ab3f1dd129d9f84957f
suyash248/ds_algo
/Tree/sumOfNodes.py
907
3.828125
4
from Tree.commons import insert, print_tree, is_leaf # fs(50) - 50, fs(30) # fs(30) - 80, fs(20) # fs(20) - 100 def find_sum_v1(root): if root is None: return 0 return root.key + find_sum_v1(root.left) + find_sum_v1(root.right) son = 0 def find_sum_v2(root): global son if root is None: return son son += root.key find_sum_v2(root.left) find_sum_v2(root.right) return son # Driver program to test above function if __name__ == "__main__": """ Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 """ root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) print("Sum of all nodes is", find_sum_v1(root)) print("Sum of all nodes is", find_sum_v2(root))
a23e6eb9e35e685b36de1e108a1734c750dfc093
suyash248/ds_algo
/Queues/PriorityQueue/pq.py
4,722
3.859375
4
from Heap.BinaryHeap.maxHeap import MaxHeap from copy import deepcopy class PriorityQueue(object): def __init__(self, pq_capacity=10): self._pq_capacity_ = pq_capacity self._pq_size_ = 0 self._pq_heap_ = MaxHeap(pq_capacity) # Time Complexity : O(log(n)) def insert(self, item, priority): res = False if self.is_full(): print("Priority queue is full, please delete older items in order to insert newer ones.") return res e = Entry(item, priority) res = self._pq_heap_.insert(e) if res: self._pq_size_ += 1 return res # Time Complexity : O(log(n)) def delete_item_with_highest_priority(self): res = False if self.is_empty(): print("Priority queue is empty") return res res = self._pq_heap_.delete_max() if isinstance(res, bool) and res == False: pass else: self._pq_size_ -= 1 return res # Time Complexity : O(1) def get_item_with_highest_priority(self): if self.is_empty(): print("Priority queue is empty") return False return self._pq_heap_.get_max() def is_full(self): return self._pq_size_ >= self._pq_capacity_ def is_empty(self): return self._pq_size_ <= 0 def pq_print(self): return deepcopy(self._pq_heap_.heap_arr()[0:self.pq_size()]) def pq_size(self): return self._pq_size_ def pq_capacity(self): return self._pq_capacity_ class Entry(object): """ Represents an entry(combination of item & priority) of priority queue. """ def __init__(self, item, priority): self.item = item self.priority = priority def __str__(self): return "({}:{})".format(self.item, self.priority) def __repr__(self): return "({}:{})".format(self.item, self.priority) def __le__(self, other): return self.priority <= other.priority def __lt__(self, other): return self.priority < other.priority def __ge__(self, other): return self.priority >= other.priority def __gt__(self, other): return self.priority > other.priority def __eq__(self, other): return self.priority == other.priority def __ne__(self, other): return self.priority != other.priority def test(): pq_arr_test = ["5 2", "6 1", "2 7", "4 3", "7 0", "8 5", "9 6"] pq_capacity = len(pq_arr_test) pq = PriorityQueue(pq_capacity) mh_test = MaxHeap(pq_capacity) for item_priority in pq_arr_test: item_priority = item_priority.split(" ") item = int(item_priority[0].strip()) priority = int(item_priority[1].strip()) mh_test.insert(priority) pq.insert(item, priority) print(pq.pq_arr()) print(mh_test.heap_arr()) print("Element with highest priority: ", pq.get_item_with_highest_priority()) if __name__ == '__main__': pq_capacity = input("Please enter the size/capacity of priority queue - ") pq = PriorityQueue(pq_capacity) menu = """ Menu: 1. Insert. 2. Print priority queue. 3. Get item with maximum priority. 4. Delete item with maximum priority. 5. Get the size and capacity of priority queue. 6. Stop. """ print(menu) while True: try: choice = input("Please enter your choice - ") except: print("Incorrect choice, please select from menu.") continue try: if choice == 1: item_priority = input("Enter item & priority separated by a white-space - ") item_priority = item_priority.split(" ") item = item_priority[0].strip() priority = item_priority[1].strip() res = pq.insert(item, priority) print(res) continue if choice == 2: print(pq.pq_print()) continue if choice == 3: res = pq.get_item_with_highest_priority() print(res) continue if choice == 4: res = pq.delete_item_with_highest_priority() print(res) continue if choice == 5: print("Size : {} | Capacity: {}".format(pq.pq_size(), pq.pq_capacity())) continue if choice == 6: break except Exception as ex: print("Error occurred while performing last operation(choice: {}):".format(choice)) print(ex.message, ex.args) print(menu)
23f3e33d6028d9aaad652432996ff2570df7490c
DineshDDi/full-python
/hash.py
582
3.71875
4
''' my_dict = dict(dini='001',divi='002') print(my_dict) ''' ''' emp_details = {'employees':{'divi':{'ID':'001','salary':'1000','designation':'team leader'},'dini':{'ID':'002', 'salary':'2000','designation':'associate'}}} print(emp_details) ''' import pandas as pd emp_details = {'employees':{'divi':{'ID':'001','salary':'1000','designation':'team leader'},'dini':{'ID':'002', 'salary':'2000','designation':'associate'}}} df = pd.DataFrame(emp_details['employees']) print(df)
700a4945fee532f3f8e9c9ea6be562cb597a8d69
DineshDDi/full-python
/ATM.py
2,187
3.859375
4
print("Welcome to ICICI Bank ATM") Restart = 'Q' Chance = 3 Balance = 1560.45 while Chance >= 0: pin = int(input("Please enter your PIN: ")) if pin == (1004): while Restart not in ('NO:1', 'NO:2', 'NO:3', 'NO:4'): print('Press 1 for your Bank Balance \n') print('Press 2 to make withdrawl \n') print('Press 3 to Deposit in \n') print('Press 4 to Return Card \n') Option = int(input('What Would like to choose : ')) if Option == 1: print('Your Account Balance is $', Balance, '\n') Restart = input('Go Back : ') if Restart in ('NO:1', 'NO:2', 'NO:3', 'NO:4'): print('Thank You') break elif Option == 2: Option2 = ('Q') withdrawl = float(input('How much you like to withdrawl? \n$100/$200/$500$2000')) if withdrawl in [100, 200, 500, 2000]: Balance = Balance - withdrawl print('\n Your Account Balance is now: ', Balance) Restart = input('Go Back : ') if Restart in ('NO:1', 'NO:2', 'NO:3', 'NO:4'): print('Thank You') break elif withdrawl != [100, 200, 500, 2000]: print('Invaild Amount, Please re-try \n') Restart = ('Q') elif Option == 3: Deposit_in = float(input('Please! enter the Deposit Amount: ')) Balance = Balance + Deposit_in print('\n Your Balance is now $: ', Balance) Restart = input('Go Back : ') if Restart in ('NO:1', 'NO:2', 'NO:3', 'NO:4'): print('Thank You') break elif Option == 4: print('Please wait your card as been return \n') print('Thank You') break elif pin != ('1004'): print('Incorect Password') Chance = Chance-1 if Chance == 0: print('\n NO more Chances, Please collect your Card') break
4d1f4252ebf1d0956f72f99824b1939e7741164c
DineshDDi/full-python
/mat.py
254
3.609375
4
import numpy as np #import pandas as pd import matplotlib.pyplot as plt time = np.arange(100) delta = np.random.uniform(10,10,size=100) y = 3*time - 7+delta plt.plot(time,y) plt.title("matplotlib") plt.xlabel("time") plt.ylabel("function") plt.show()
179bccd8b2796ea4c23ab39ccb490b7f59fb3689
DineshDDi/full-python
/Py_Tkinder/Dx_T1_S0028a(Tkinder_Horizontal Scale widget).py
575
3.65625
4
# Python program to demonstrate # scale widget from tkinter import * root = Tk() root.geometry("400x300") v1 = DoubleVar() def show1(): sel = "Horizontal Scale Value = " + str(v1.get()) l1.config(text=sel, font=("Courier", 14)) s1 = Scale(root, variable=v1, from_=0, to=100, orient=HORIZONTAL) l3 = Label(root, text="Horizontal Scaler") b1 = Button(root, text="Display Horizontal", command=show1, bg="yellow") l1 = Label(root) s1.pack(anchor=CENTER) l3.pack() b1.pack(anchor=CENTER) l1.pack() root.mainloop()
a7475e64d4c78ab644791db9a969b0ad9e4025b7
ninkle/cracking-the-coding-interview
/fibonnaci.py
182
4.03125
4
#prints the fibonnaci sequence for length n def fib(n): seq = [1, 1] while len(seq) < n+1: next = seq[-1] + seq[-2] seq.append(next) print(seq) fib(8)
d9313b97da54f2393f533ab9ba382be423f1b486
gauriindalkar/nested-if-else
/exercise weather.py
373
4.09375
4
exercise=input("enter set alarm") if exercise=="6": print("wake up morning") weather=input("enter the weather") if weather=="cold": print("put on sokes,jarking,handglose") elif weather=="summer": print("don't put on sokes,jarking,handglose") else: print("i will not go down for exercise") else: print("i will go to exercise")
555d0e87fbb1e5116ecb0427737d9177bf13508a
freespace/arduino-ADS7825
/ads7825.py
9,627
3.703125
4
#!/usr/bin/env python """ Simple interface to an arduino interface to the ADS7825. For more details see: https://github.com/freespace/arduino-ADS7825 Note that in my testing, the ADS7825 is very accurate up to 10V, to the point where there is little point, in my opinion, to write calibration code. The codes produce voltages that are within 0.01V of the value set using a HP lab PSU. TODO: - Implement self test using don/doff commands. Use read function to determine if don/doff is working - Use either PWM driver or another chip to generate a clock signal and determine the maximum sampling rate of the system - It will be limited by how fast we can service interrupts, which in turn will be limited by how fast the firmware is capable of reading from the ADC """ from __future__ import division import serial import time def c2v(c, signed=True): """ If signed is True, returns a voltage between -10..10 by interpreting c as a signed 16 bit integer. This is the default behaviour. If signed is False, returns a voltage between 0..20 by interpreting c as an UNSIGNED 16 bit integer. """ if signed: return 10.0 * float(c)/(0x7FFF) else: return 20.0 * float(int(c)&0xFFFF)/(0xFFFF) def find_arduino_port(): from serial.tools import list_ports comports = list_ports.comports() for path, name, vidpid in comports: if 'FT232' in name: return path if len(comports): return comports[0][0] else: return None class ADS7825(object): # this indicates whether we interpret the integers from the arduino # as signed or unsigned values. If this is True, then voltages will be # returned in the range -10..10. Otherwise voltages will be returned # in the range 0..10. # # This is useful when doing multiple exposures with unipolar signals which # would otherwise overflow into negative values when signed. signed=True def __init__(self, port=None, verbose=False): super(ADS7825, self).__init__() self._verbose = verbose if port is None: port = find_arduino_port() self._ser = serial.Serial(port, baudrate=250000) # Let the bootloader run time.sleep(2) # do a dummy read to flush the serial pipline. This is required because # the arduino reboots up on being connected, and emits a 'Ready' string while self._ser.inWaiting(): c = self._ser.read() if verbose: print 'ads7825>>',c def _c2v(self, c): return c2v(c, signed=self.signed) def _write(self, x, expectOK=False): self._ser.write(x) self._ser.flush() if self._verbose: print '>',x if expectOK: l = self._readline() assert l == 'OK', 'Expected OK got: '+l def _readline(self): return self._ser.readline().strip() def _read16i(self, count=1): b = self._ser.read(2*count) import struct fmtstr = '<'+ 'h' * count ints = struct.unpack(fmtstr, b) if count == 1: return ints[0] else: return ints def set_exposures(self, exposures): """ Sets the exposure value, which is the number of readings per read request. This affects read and scan, and defaults to 1. """ exposures = int(exposures) aschar = chr(ord('0')+exposures) self._write('x'+aschar, expectOK=True) def read(self, raw=False): """ Returns a 4-tuple of floats, containing voltage measurements, in volts from channels 0-3 respectively. Voltage range is +/-10V """ self._write('r') line = self._readline() codes = map(float,map(str.strip,line.split(','))) if raw: return codes else: volts = map(self._c2v, codes) return volts def scan(self, nchannels=4): """ Asks the firmware to beginning scanning the 4 channels on external trigger. Note that scans do NOT block serial communication, so read_scans will return the number of scans currently available. """ self._write('s'+str(nchannels), expectOK=True) @property def buffer_writepos(self): """ Returns the write position in the buffer, which is an indirect measure of the number of scans, with the write position incremeneting by nchannels for every scan triggered. """ self._write('c') return self._read16i() def output_on(self, output): """ Turns the specified output """ assert output >= 0 and output < 10, 'Output out of range' self._write('o'+str(output), expectOK=True) def output_off(self, output): """ Turns off the specified output """ assert output >= 0 and output < 10, 'Output out of range' self._write('f'+str(output), expectOK=True) def set_trigger_divider(self, n): """ Divides the incoming trigger signal by n, triggering every nth trigger. Valid range is 1..9 currently. """ assert n > 0 and n < 10 self._write('t'+str(n), expectOK=True) def read_scans(self, nscans, binary=True, nchannels=4): """ Gets from the firmware the scans it buffered from scan(). You must supply the number of scans (nscans) to retrieve. Each scan consists of nchannels number of 16 bit ints. nchannels: the number of channels scanned per scan If binary is set to True, then 'b' is used to retrieve the buffer instead of 'p'. Defaults to True. Returns a list of voltage measurements. , e.g. [v0_0, v1_0, v2_0, v3_0, v0_1, v1_1, v2_1, v3_1 ... v0_n-1, v1_n-1, v2_n-1, v3_-1] If called before nscans have been required, you will get an exception. Just wait a bit longer, and check also that nscans does not exceed the buffer allocated in the firmware. e.g. if buffer can only hold 10 scans, and you want 20, then this method will ALWAYS throw an exception. You should NOT call this during data acquisition because if the processor is forced to handle communication then it will miss triggers because to preserve data integrity interrupts are disabled when processing commands. """ nscans = int(nscans) nchannels = int(nchannels) self._ser.flushInput() if binary: wantints = nscans * nchannels assert wantints < 63*64+63 # ask for binary print out of the required number # int samples self._write('B') ascii0 = ord('0') # we encode using our ad hoc b64 scheme self._write(chr(wantints%64 + ascii0)) self._write(chr(wantints//64 + ascii0)) # get the number of ints available nints = self._read16i() print 'Wanted %d ints, %d available'%(wantints, nints) # read them all in codes = self._read16i(count=nints) if nints < nscans*nchannels: raise Exception("Premature end of buffer. ADC probably couldn't keep up. Codes available: %d need %d"%(nints, nscans*nchannels)) return map(self._c2v, codes)[:nscans*nchannels] else: self._write('p') volts = list() done = False while not done: line = self._readline() if line == 'END': raise Exception("Premature end of buffer. ADC probably couldn't keep up. Lines read: %d"%(len(volts)//4)) ints = map(int,line.split(' ')) index = ints[0] codes = ints[1:] assert(len(codes) == 4) volts += map(self._c2v, codes) if index == nscans-1: done = True # read to the end of the buffer while self._readline() != 'END': pass return volts def close(self): self._ser.close() self._ser = None class Test(): @classmethod def setup_all(self): ardport = find_arduino_port() import readline userport = raw_input('Serial port [%s]: '%(ardport)) if len(userport) == 0: userport = ardport self.adc = ADS7825(ardport, verbose=False) def _banner(self, text): l = len(text) print print text print '-'*l def test_read(self): volts = self.adc.read() print 'Volts: ', volts assert len(volts) == 4 def test_exposures(self): self.adc.set_exposures(1) volts1 = self.adc.read() print 'Volts: ', volts1 self.adc.set_exposures(2) volts2 = self.adc.read() print 'Volts: ', volts2 for v1, v2 in zip(volts1, volts2): assert abs(v2) > abs(v1) def test_outputs(self): self._banner('Digital Output Test') for pin in xrange(8): for ch in xrange(4): e = raw_input('Connect D%d to channel %d, Enter E to end. '%((49-pin), ch+1)) if e == 'E': return self.adc.output_off(pin) voltsoff = self.adc.read() self.adc.output_on(pin) voltson = self.adc.read() print 'on=',voltson[ch], 'off=',voltsoff[ch] assert voltson[ch] > voltsoff[ch] def test_trigger(self): self._banner('Trigger Test') period_ms = 2 halfperiod_s = period_ms*0.5/1000 e = raw_input('Connect D49 to D38, enter E to end.') if e == 'E': return ntriggers = 200 for nchannels in (1,2,3,4): for trigger_div in (1,2,3,5): self.adc.set_trigger_divider(trigger_div) self.adc.scan(nchannels) assert self.adc.buffer_writepos == 0 for x in xrange(ntriggers): self.adc.output_on(0) time.sleep(halfperiod_s) self.adc.output_off(0) time.sleep(halfperiod_s) #print self.adc.buffer_writepos, x+1 writepos = self.adc.buffer_writepos print 'write pos at %d after %d scans of %d channels'%(writepos, ntriggers/trigger_div, nchannels) assert writepos == ntriggers//trigger_div * nchannels if __name__ == '__main__': import nose nose.main()
68516328653c342ca1f8fc10bd452fa86833787d
shangkh/github_python_interview_question
/54.保留两位小数.py
163
3.765625
4
a = "%.2f" % 1.3335 print(a, type(a)) """ round(数值, 保留的数位) """ b = round(float(a), 1) print(b, type(b)) b = round(float(a), 2) print(b, type(b))
b09dd9b4ee31c95569dbed4125448b6894d26b80
shangkh/github_python_interview_question
/17.pyhton中断言方法举例.py
212
3.765625
4
""" assert():断言成功,则程序继续执行,断言失败,则程序报错 """ a = 3 assert (a > 1) print("断言成功,程序继续执行") b = 4 assert (b > 7) print("断言失败,程序报错")
80ebbfd1da7c991ac5810797b90fe493ec22b654
shangkh/github_python_interview_question
/11.简述面向对象中__new__和__init__区别.py
1,384
4.21875
4
""" __init__ 是初始化方法,创建对象后,就立刻被默认调用了,可以接收参数 """ """ __new__ 1.__new__ 至少要有一个参数 cls,代表当前类,此参数在实例化时由python解释器自动识别 2.__new__ 必须要有返回值,返回实例化出来的实例,这点在自己实现__new__时要特别注意, 可以return父类(通过super(当前类名, cls))__new__出来的实例, 或者直接是object的__new__出来的实例 3.__int__有一个参数self,就是这个__new__返回的实例, __init__在__new__的基础上可以完成一些其他的初始化动作, __init__不需要返回值 4.如果__new__创建的是当前类的实例,会自动调用__init__函数, 通过return语句里面调用的__new__函数的 第一个参数是cls来保证是当前类实例,如果是其他类的类名; 那么实际创建返回的就是其他类的实例, 其实就不会调用当前类的__init__函数,也不会调用其他类的__init__函数 """ class A(object): def __int__(self): print("这是__init__方法", self) def __new__(cls, *args, **kwargs): print("这是cls的ID:", id(cls)) print("这是__new__方法", object.__new__(cls)) return object.__new__(cls) if __name__ == '__main__': A() print("这是类A的ID:", id(A))
3ea7c9fc3f2670d89546b76d94c81782face9a2f
shangkh/github_python_interview_question
/80.根据字符串的长度排序.py
111
3.53125
4
s = ["ab", "abc", "a", "asda"] b = sorted(s, key=lambda x: len(x)) print(s) print(b) s.sort(key=len) print(s)
8aebc47e8ae2b71081771c8c069292f1795bc6f2
shangkh/github_python_interview_question
/89.用两种方法去空格.py
118
3.6875
4
str = "Hello World ha ha" res = str.replace(" ", "") print(res) list = str.split(" ") res = "".join(list) print(res)
eddce67f5ecab1fef1b56b2df5c1a707b390b0da
shangkh/github_python_interview_question
/6.python实现列表去重的方法.py
138
3.65625
4
my_list = [11, 12, 13, 12, 15, 16, 13] list_to_set = set(my_list) print(list_to_set) new_list = [x for x in list_to_set] print(new_list)
eda27ec0aba10380bb4f1625ce68bfc49c62142e
shangkh/github_python_interview_question
/76.列表嵌套列表排序,年龄数字相同怎么办.py
236
3.59375
4
my_list = [["wang", 19], ["shang", 34], ["zhang", 23], ["liu", 23], ["xiao", 23]] a = sorted(my_list, key=lambda x: (x[1], x[0])) # 年龄相同添加参数,按字母排序 print(a) a = sorted(my_list, key=lambda x: x[0]) print(a)
8510c5a27d2ed435e47d615d6c9955a388f61424
shangkh/github_python_interview_question
/75.列表嵌套元祖,分别按字母和数字排序.py
223
3.53125
4
my_list = [("wang", 19), ("li", 55), ("xia", 24), ("shang", 11)] a = sorted(my_list, key=lambda x: x[1], reverse=True) # 年龄从大到小 print(a) a = sorted(my_list, key=lambda x: x[0]) # 姓名从小到大 print(a)
abae063d758cc0302f666398f6c169627f66c319
sacremendev/Project-Euler
/Q14.py
363
3.8125
4
#!/usr/bin/python def count(n): k = 0 while n != 1: if (n % 2) == 0: n = n / 2 else: n = n * 3 + 1 k = k + 1 #print n #print k return k result = 0 for i in range(1, 1000000): num = count(i) if num > result: print ("update ", i, " ", num) result = num print (result)
0c927b6c474351d757a631300070d4010d458afa
green-fox-academy/Angela93-Shi
/week-02/day-8/copy_file.py
537
3.6875
4
# Write a function that copies the contents of a file into another # It should take the filenames as parameters # It should return a boolean that shows if the copy was successful import shutil def copy_file(oldfile,newfile): shutil.copyfile(oldfile,newfile) f=open(oldfile,'r') f.seek(0) text1 = f.read() print(text1) f=open(newfile,'r') f.seek(0) text2 = f.read() print(text2) if text1 == text2: return True else: return False print(copy_file("my_file.txt","my-file.txt"))
9d3b7f05c931cceb48d7c2e53fce9dfc35ca1f79
green-fox-academy/Angela93-Shi
/week-05/day-03/change_xy.py
335
3.984375
4
# Given a string, compute recursively (no loops) a new string where all the lowercase 'x' chars # have been changed to 'y' chars. def change_xy(str): if len(str) == 0: return str if str[0] == 'x': return 'y' + change_xy(str[1:]) return str[0] + change_xy(str[1:]) print(change_xy("xxsdsfefenkefnxx"))
f41c3b2d10e43b66cf7ea4ec8c7ad8f527facd28
green-fox-academy/Angela93-Shi
/week-03/day-01/foreat_simulator.py
1,830
3.953125
4
class Tree: def __init__(self,height=0): self.height = height def irrigate(self): pass def getHeight(self): return self.height class WhitebarkPine(Tree): def __init__(self,height=0): Tree.__init__(self , height) self.height = height def irrigate(self): self.height += 2 class FoxtailPine(Tree): def __init__(self,height=0): Tree.__init__(self , height) self.height = height def irrigate(self): self.height += 2 class Lumberjack: def canCut(self,tree): if tree.height > 4: return True else: return False class Forest: def __init__(self): self.trees =[] def add_tree(self,tree): self.trees.append(tree) def rain(self): for tree in self.trees: tree.irrigate() def cutTrees(self,lumberjack): trees_cut=[] for tree in self.trees: if lumberjack.canCut(tree): trees_cut.append(tree) for i in trees_cut: for tree in self.trees: if i == tree: self.trees.remove(tree) def is_empty(self): if len(self.trees) == 0: return True else: return False def get_status(self): for tree in self.trees: # tree.__class__.__name__ get the current name of tree return f'there is a { tree.height } tall {tree.__class__.__name__}in the forest' whitebarkPine = WhitebarkPine(3) # whitebarkPine.irrigate() foxtailPine = FoxtailPine(4) # foxtailPine.irrigate() # lumberjack = Lumberjack() forest = Forest() forest.add_tree(whitebarkPine) forest.add_tree(foxtailPine) # # forest.rain() print(forest.get_status())
d904f6ae14f31c7b284e39329a22a1e0a8ec91bf
green-fox-academy/Angela93-Shi
/week-02/day-7/oop/sharpie.py
806
3.9375
4
# Create Sharpie class # We should know about each sharpie their color (which should be a string), # width (which will be a floating point number), ink_amount (another floating point number) # When creating one, we need to specify the color and the width # Every sharpie is created with a default 100 as ink_amount # We can use() the sharpie objects # which decreases inkAmount class sharpie(): def __init__(self,color,width=0.0,ink_amount=0.0): self.color = color self.width = width self.ink_amount = ink_amount def use(self,inkAmount): self.ink_amount -= inkAmount return self.ink_amount sharpieModal = sharpie('blue',220.0,120.0) print(sharpieModal.color) print(sharpieModal.width) print(sharpieModal.ink_amount) print(sharpieModal.use(100))
0ff0c13459c83929d90c57a453cb8fdf5736af28
green-fox-academy/Angela93-Shi
/week-01/day-3/python/print_even.py
122
3.921875
4
# Create a program that prints all the even numbers between 0 and 500 for i in range(500): if i%2==0: print(i)
12562fa1658d275e15075f71cff3fac681c119ab
green-fox-academy/Angela93-Shi
/week-01/day-4/data_structures/data_structures/product_database.py
715
4.34375
4
map={'Eggs':200,'Milk':200,'Fish':400,'Apples':150,'Bread':50,'Chicken':550} # Create an application which solves the following problems. # How much is the fish? print(map['Fish']) # What is the most expensive product? print(max(map,key=map.get)) # What is the average price? total=0 for key in map: total=total+map[key] average=total/len(map) print(average) # How many products' price is below 300? n=0 for key in map: if map[key] < 300: n+=1 print(n) # Is there anything we can buy for exactly 125? for key,value in map.items(): if map[key] == 125: print("yes") else: print("No") break # What is the cheapest product? print(min(map,key=map.get))
fca1600839df5efa93b7f515b6323c1a32c9e2ce
green-fox-academy/Angela93-Shi
/week-01/day-4/function/summing.py
238
4.03125
4
# Write a function called `sum` that returns the sum of numbers from zero to the given parameter given_num=10 def sum(num): global given_num for i in range(num+1): given_num=i+given_num print(given_num) sum(given_num)
c525397178d3cfa51ee9163724db2d8131c8601f
green-fox-academy/Angela93-Shi
/week-02/day-7/inheritance/student.py
904
3.90625
4
from person import Person class Student(Person): def __init__(self,name='Jane Doe',age=30,gender='female',previous_organization='The School of life',skipped_days=0): Person.__init__(self,name='Jane Doe',age=30,gender='female') self.previous_organization = previous_organization self.skipped_days = skipped_days def get_goal(self): print("Be a junior software develop") def introduce(self): print(f"Hi,I'm{self.name}, a {self.age} year old {self.gender} from {self.previous_organization} who skipped {self.skipped_days} from the course already. ") def skip_days(self,number_of_days): print(f"increase {self.skipped_days} by {number_of_days}") # person = Person('Jane Doe',30,'female') # student = Student(Person,'The School of Life',0) # print(student.get_goal()) # print(student.introduce(person)) # print(student.skip_days(2))
587a7726500b091aea4511e4036f8750c229ecaa
green-fox-academy/Angela93-Shi
/week-05/day-01/all_positive.py
319
4.3125
4
# Given a list with the following items: 1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14 # Determine whether every number is positive or not using all(). original_list=[1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14] def positive_num(nums): return all([num > 0 for num in nums]) print(positive_num(original_list))
7e84399b0ae345beb15e19b1e44663d4bc062138
green-fox-academy/Angela93-Shi
/week-02/day-7/oop/petrol_station.py
718
3.796875
4
# Create Station and Car classes # Station # gas_amount # refill(car) -> decreases the gasAmount by the capacity of the car and increases the cars gas_amount # Car # gas_amount # capacity # create constructor for Car where: # initialize gas_amount -> 0 # initialize capacity -> 100 class Station(): def __init__(self,gas_amount): self.gas_amount = gas_amount def refill(self,Car): self.gas_amount -= Car.gas_amount Car.capacity=Car.gas_amount return self.gas_amount, Car.capacity class Car(): def __init__(self,gas_amount=0,capacity=100): self.gas_amount = gas_amount self.capacity = capacity station=Station(1000) car=Car() print(station.refill(car))
8fcf16851182307c41d9c5dd77e8d42b783628c7
green-fox-academy/Angela93-Shi
/week-01/day-4/function/factorial.py
409
4.375
4
# - Create a function called `factorio` # that returns it's input's factorial num = int(input("Please input one number: ")) def factorial(num): factorial=1 for i in range(1,num + 1): factorial = factorial*i print("%d 's factorial is %d" %(num,factorial)) if num < 0: print("抱歉,负数没有阶乘") elif num == 0: print("0 的阶乘为 1") else: factorial(num)
c5d9cfe8cdda4d4fdc98f77221c15bb23da5e100
green-fox-academy/Angela93-Shi
/week-01/day-4/data_structures/data_structures/telephone_book.py
478
4.1875
4
#Create a map with the following key-value pairs. map={'William A. Lathan':'405-709-1865','John K. Miller':'402-247-8568','Hortensia E. Foster':'606-481-6467','Amanda D. Newland‬':'319-243-5613','Brooke P. Askew':'307-687-2982'} print(map['John K. Miller']) #Whose phone number is 307-687-2982? for key,value in map.items(): if value == '307-687-2982': print(key) #Do we know Chris E. Myers' phone number? for key,value in map.items(): if key == 'Chris E. Myers': print('Yes') else: print('No') break
f0871075ce0fef62569e4ce443389d1c8c592480
sajal203/dice-simulator
/dicesimulator.py
641
3.84375
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 5 20:26:46 2020 @author: sajal """ '''dice simulator''' import random import time user_inp = 'yes' while user_inp == 'yes' or user_inp == 'y': print('dice is rolling...') time.sleep(1) dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) print('dice-1 value is: ',dice1) print('dice-2 value is: ',dice2) time.sleep(1) if dice1 == dice2: print('congo you won!!..') user_inp = input('do you want to play again(y/n):- ').lower() time.sleep(1) print('thank you for playing...')
6f5f64793115b2302e947c9f8ce5be419d5740e1
johnrick10234/hello-world
/Homework-4/Homework_4_12.7.py
484
3.921875
4
#John Rick Santillan #1910045 def get_age(): age=int(input()) if age<18 or age>75: raise ValueError('Invalid age.') return age def fat_burning_heart_rate(age): h_rate=(220-age)*.70 return h_rate if __name__=='__main__': try: age=get_age() print('Fat burning heart rate for a',age,'year-old:',"{:.1f}".format(fat_burning_heart_rate(age)),'bpm') except ValueError as ex: print(ex) print('Could not calculate heart rate info.\n')
cc78b79ef9732173ad7066b7c0474ce639bbe480
Joseane772/exercicios_python
/pratice/B.py
844
3.71875
4
na = int(input('what is the total number of students?')) NV = 0 Lx = 0 Lz = 0 EB = 0 EM = 0 Vb = 0 for n in range(0, na): v = str(input('which list will you vote for(X or Z)')) NE = str(input('what is your level of education (B or S)?')) if v == 'x': Lx = Lx + 1 elif v == 'z': Lz = Lz + 1 else: Vb = Vb + 1 if NE == 'b': EB = EB + 1 else: EM = EM + 1 nv = str(na) lx = str(Lx) lz = str(Lz) eb = str(EB) em = str(EM) vb = str(Vb) print('\nNumber of votes(total):' + nv + '\nNumber of votes(list X):' + lx + '\nNumber of votes(list Z):' + lz + '\nNumber of votes(null):' + vb + '\nNumber of votes(highschoolers):' + em + '\nNumber of votes(preschoolers):' + eb) if Lx > Lz: print('The winner is X') elif Lz < Lx: print('The winner is Z')
b68d019707668a3a3a47b556afa389154e403274
mnusicallity/Py-Pong
/Pong/paddle.py
1,855
3.78125
4
import pygame from pygame.sprite import Sprite class Paddle(Sprite): def __init__(self, screen, ai_settings, player_paddle): super(Paddle, self).__init__() self.ai_settings = ai_settings self.color = ai_settings.paddle_color self.paddle_position = 400 self.paddle_speed = 2 self.screen = screen self.player_paddle = player_paddle self.rect = pygame.Rect(self.player_paddle, self.paddle_position, 10, 40) self.play_against_ai = False self.paddle_moving_up = False self.paddle_moving_down = False def update(self): if self.paddle_moving_up: self.paddle_position_up() elif self.paddle_moving_down: self.paddle_position_down() print(self.ai_settings.paddle_position) def draw_paddle(self): pygame.draw.rect(self.screen, self.color, self.rect) # def update(self, ai_settings):+py setup. # if ai_settings.paddle_moving_up == True and ai_settings.paddle_position >= 0: # elif ai_settings.paddle_moving_down == True and ai_settings.paddle_position <= ai_settings.window_height: def paddle_position_up(self): self.rect = pygame.Rect(self.player_paddle, self.paddle_position, 10, 40) self.paddle_position -= self.paddle_speed def paddle_position_down(self): self.rect = pygame.Rect(self.player_paddle, self.paddle_position, 10, 40) self.paddle_position += self.paddle_speed def against_ai(self, ball): """This function requires a condition to be met by selecting something from the Game Menu""" if ball.starty <= self.paddle_position: self.paddle_position_up() elif ball.starty >= self.paddle_position: self.paddle_position_down()
31c2c7901dd994dea44ce68dea458bf8675926d3
MAWA-Taka/SelfTaughtPgmr
/p156_apple.py
291
3.703125
4
class Apple: def __init__(self, k, s, w, c): self.kind = k self. size = s self.weight = w self.color =c a = Apple("ふじ", "L", 200, "yellow") print("品種:{}、サイズ:{}、重さ:{}、色合い:{}".format(a.kind, a.size, a.weight, a.color))
856e1fe1bffc794ff217365ce83f1bfab6d9e094
misssoft/Fan.PythonExercise
/src/assessment/estimate/binary_search_distribution.py
724
4
4
""" Distribute a depth value into the right bin by binary search """ def binary_search_distribution(boundaries, depth, lower, upper): """ :param boundaries: a list containing the boundary values of different bins in ascending order :param depth: the depth value of a pixel :param lower: position of lower boundaries :param upper: position of upper boundaries :return: the bin number """ if lower + 1 == upper: return upper else: middle = (lower + upper) //2 if depth > boundaries[middle]: return binary_search_distribution(boundaries, depth, middle, upper) else: return binary_search_distribution(boundaries, depth, lower, middle)
5a48b2cc0ad944fafff7215e755a6af233ead39e
KrishnaAgarwal16/May-Leetcode-Challenge-2020
/Week-1/MajorityElement.py
419
3.671875
4
#Problem Link: https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3321/ class Solution: def majorityElement(self, nums: List[int]) -> int: d = set(nums) n = len(nums) for i in d: if nums.count(i)>(n/2): return i def main(): nums = list(map(int(input()))) print(majorityElement(nums))
3f3d0582c711859aae5b2999bf057b6cba2b88fd
LiamBrem/PythonProjects
/PassGen/main.py
577
3.8125
4
import random import pyperclip def generatePassword(chars, charList): password = [] for i in range(chars): nextChar = characterList[random.randint(0, len(charList))] password.append(nextChar) return ''.join(password) def copyToClipBoard(copy): pyperclip.copy(copy) if __name__ == "__main__": characterList = "ABCDEFGHIJKLMOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()_+1234567890" lengthToGenerate = int(input("Length: ")) copyToClipBoard(generatePassword(lengthToGenerate, characterList)) print('Copied To Clipboard!')
6ca4a43e77389bcdec965fc1b9ced177f785c1a8
rajes95/intensive_fundamentals_of_computer_science
/binary_search/binary_search_tree_Tests.py
3,526
4.125
4
# Author: Rajesh Sakhamuru # Version: 3/28/2019 import unittest import binary_search_tree class Binary_Search_Tree_Tests(unittest.TestCase): def testBinarySearchTreeAdd(self): """ # Purpose: This method adds a specified value to the binary tree in the expected location. Lower values are on the left and higher values are on the right. No return value, but the data is stored within the tree. # Signature: add :: (self, Integer) => None # Examples: add :: (self, 8) => None add :: (self, 5) => None """ testTree = binary_search_tree.BinaryTree(8) self.assertEqual(testTree.data, 8) testTree.add(3) testTree.add(10) testTree.add(1) testTree.add(6) testTree.add(4) testTree.add(7) testTree.add(14) testTree.add(13) self.assertEqual(testTree.right.data, 10) # TEST CASES 1-18 self.assertEqual(testTree.right.left, None) self.assertEqual(testTree.left.data, 3) self.assertEqual(testTree.left.left.data, 1) self.assertEqual(testTree.left.left.left, None) self.assertEqual(testTree.left.left.right, None) self.assertEqual(testTree.left.right.data, 6) self.assertEqual(testTree.left.right.left.data, 4) self.assertEqual(testTree.left.right.left.left, None) self.assertEqual(testTree.left.right.left.right, None) self.assertEqual(testTree.left.right.right.data, 7) self.assertEqual(testTree.left.right.right.left, None) self.assertEqual(testTree.left.right.right.right, None) self.assertEqual(testTree.right.right.data, 14) self.assertEqual(testTree.right.right.left.data, 13) self.assertEqual(testTree.right.right.left.right, None) self.assertEqual(testTree.right.right.left.left, None) self.assertEqual(testTree.right.right.right, None) def testBinarySearchTreeGet(self): """ # Purpose: This method searches the binary tree for a specified value (num) and if that value is in the tree, then num is returned and if it is not, then None is returened. # Signature: get :: (self, Integer) => Integer (or none) # Examples: get :: (self, 5) => 5 # if 5 is in the Tree get :: (self, 8) => None # if 8 is not in the Tree """ testTree = binary_search_tree.BinaryTree(8) self.assertEqual(testTree.data, 8) testTree.add(3) testTree.add(10) testTree.add(1) testTree.add(6) getData = testTree.get(3) # TEST CASE 1 self.assertEqual(getData, 3) getData = testTree.get(8) # TEST CASE 2 self.assertEqual(getData, 8) getData = testTree.get(10) # TEST CASE 3 self.assertEqual(getData, 10) getData = testTree.get(1) # TEST CASE 4 self.assertEqual(getData, 1) getData = testTree.get(6) # TEST CASE 5 self.assertEqual(getData, 6) getData = testTree.get(5) # TEST CASE 6 self.assertEqual(getData, None) getData = testTree.get(0) # TEST CASE 7 self.assertEqual(getData, None) getData = testTree.get(-7) # TEST CASE 8 self.assertEqual(getData, None) if __name__ == "__main__": unittest.main(exit=False)
1b42ac0ff1735b7c01b53715a78feb9d6d525700
rajes95/intensive_fundamentals_of_computer_science
/more_shapes_with_loops/moreShapes.py
3,979
4.4375
4
# Author: Rajesh Sakhamuru # Version: 2/10/2019 def printLowerRight(size): """ This function prints a right-aligned triangle with an incrementing number of "*" in each row until it reaches the specified size. A Lower Right triangle of size 6 would look like this: * ** *** **** ***** ****** """ row = 0 count = size col = 0 while row < size: while col < (count - 1): print(" ", end="") col += 1 print("*" * (row + 1), end="") print() count -= 1 col = 0 row += 1 def printUpperRight(size): """ This function prints a right aligned triangle with a decrementing number of "*" in each row until it reaches 1 from the specified size. An Upper Right Triangle of size 8 would look like this: ******** ******* ****** ***** **** *** ** * """ col = size row = size count = size while row > 0: while col < size: print(" ", end="") col += 1 print("*" * row, end="") print() count -= 1 col = count row -= 1 def printRightArrowhead(size): """ This function prints a right-aligned "arrowhead" with an incrementing by 1 number of "*" in each row until it reaches the specified size then decrements by 1 to a single "*". An right-Arrowhead of size 5 would look like this: * ** *** **** ***** **** *** ** * """ row = 0 count = size col = 0 while row < size: while col < (count - 1): print(" ", end="") col += 1 print("*" * (row + 1), end="") print() count -= 1 col = 0 row += 1 col = size - 1 row = size - 1 count = size - 1 while row > 0: while col < size: print(" ", end="") col += 1 print("*" * row, end="") print() count -= 1 col = count row -= 1 def printBoomerang(size): """ This function prints a "boomerang" shape with an incrementing by 1 number of "*" in each row until it reaches the specified size then decrements by 1 to a single "*". An boomerang of size 5 would look like this: * ** *** **** ***** **** *** ** * """ row = 0 count = size col = 0 while row < size: while col < (count - 1): print(" ", end="") col += 1 print("*" * (row + 1), end="") print() count -= 1 col = 0 row += 1 col = size - 1 row = size - 1 count = size - 1 while row > 0: while col < size: print(" ", end="") col += 1 print("*" * row, end="") print() count -= 1 col = count row -= 1 def printDiamond(size): """ This function prints a "diamond" shape with a number of rows indicated by the inputted size value. First row has one "*" and each subsequent row has 2 more "*" in until the number of "*" equals the size value. Then in the next rows the number of "*" decrements by two until there is only 1 in the last row. This function only works with odd values for size. A diamond of size 9 would look like this: * *** ***** ******* ********* ******* ***** *** * """ row = 0 count = int((size - 1) / 2) while row < (((size - 1) / 2) + 1): print(" " * count, end="") print("**" * (row) + "*", end="") print() count -= 1 row += 1 row = int((size - 1) / 2) - 1 count = 0 while row >= 0: print(" " * (count + 1), end="") print("**" * row + "*", end="") print() count += 1 row -= 1
5a094fde4286a2b7776be503ad866871330454bf
rajes95/intensive_fundamentals_of_computer_science
/repeating_shapes/repeatingShapesDriver.py
2,088
4.03125
4
# Author: Maria Jump # Version: 2019-02-15 import repeatingShapes def readInteger(prompt, error="Value must be a positive integer"): """ Read and return a positive integer from keyboard """ value = -1 while(value == -1): entered = input(prompt) try: value = int(entered) if value <= 0: print(error) value = -1 except ValueError: print(error) value = -1 return value def menu(): """ Display the menu and read in user's choice """ print() print("1 - Checkerboard") print("2 - Box Grid") print("3 - Triangle Pattern") print("4 - Diamond Pattern") print("5 - Exit") choice = -1 while(choice == -1): error = "Valid options are between 1 and 5" choice = readInteger("Enter choice: ", error) if choice < 1 or choice > 7: print(error) choice = -1 print() return choice def main(): choice = menu() while choice != 5: if choice == 1: size = readInteger("Enter size: ") width = readInteger("Enter width: ") height = readInteger("Enter height: ") repeatingShapes.printCheckerboard(size, width, height) elif choice == 2: size = readInteger("Enter size: ") width = readInteger("Enter width: ") height = readInteger("Enter height: ") repeatingShapes.printBoxGrid(size, width, height) elif choice == 3: size = readInteger("Enter size: ") width = readInteger("Enter width: ") height = readInteger("Enter height: ") repeatingShapes.printTrianglePattern(size, width, height) elif choice == 4: size = readInteger("Enter size: ") width = readInteger("Enter width: ") height = readInteger("Enter height: ") repeatingShapes.printDiamondPattern(size, width, height) # read another choice choice = menu() if __name__ == "__main__": main()