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
0fac9b063f054fbd85c04825690db77f865fcd27
NayanJain09/TASK-2
/class.py
2,686
3.734375
4
class Player(object): def __init__(self, name, symbol, initial_score=0): self.name= name self.symbol= symbol self.score= initial_score def won_match(self): self.score+= 100 def lost_match(self): self.score-= 50 def show_score(self): print('Player {}: {} points'.format(self.name, self.score)) class PlayingField(object): def __init__(self): self.field= [ [None, None, None], [None, None, None], [None, None, None] ] def show_field(self): for row in self.field: for player in row: print('_' if player is None else player.symbol,end=' ') print() def set_player(self, x, y, player): if self.field[y][x] is not None: return False self.field[y][x]= player return True def full_board(self): for row in self.field: for col in self.field: if col is '_': return False else: return True def check_won(self, x, y, player): if self.field[0][x] == player.symbol and self.field[1][x] == player.symbol and self.field[2][x] == player.symbol: return True elif self.field[y][0] == player.symbol and self.field[y][1] == player.symbol and self.field[y][2] == player.symbol: return True elif self.field[0][0] == player.symbol and self.field[1][1] == player.symbol and self.field[2][2] == player.symbol: return True elif self.field[0][2] == player.symbol and self.field[1][1] == player.symbol and self.field[2][0] == player.symbol: return True else: return False name_1= input('Name of Player 1: ') name_2= input('Name of Player 2: ') players= [ Player(name_1, 'X'), Player(name_2, 'O') ] field= PlayingField() while True: for player in players: print(player.symbol) y= int(input('Player {} choose your row: '.format(player.name))) - 1 x= int(input('Player {} choose your column: '.format(player.name))) - 1 if not field.set_player(x, y, player): print('That field is already occupied.') else : field.show_field() for player in players: print('{}: {}'.format(player.name, player.score)) if field.check_won(x,y,player): print('Player {} won the game.'.format(player.name)) exit(0)
823815fa2fcabe0bae5f0c341935f3d5d0a84c4f
DigantaBiswas/python-codes
/working_with_lists.py
277
3.953125
4
cat_names = [] while True: print('Enter the name of cat '+str(len(cat_names)+1)+'or enter nothing to stop') name = input() if name =='': break cat_names= cat_names+[name] print('the cat names are:') for name in cat_names: print(''+name)
84bc960c4519feff5a5f96d991f563f12d57f8a0
GopiReddy590/python_code
/task1.py
128
3.625
4
n='abbabbaabab' for i in range(1,len(n)): for j in range(0,i): a=n[i:j] if a==a[::-1]: print(a)
6317d6a640f443b471f457f053cc1a7daf58e468
RadSebastian/AdventOfCode2018
/day02/part_1.py
822
3.8125
4
def result(string): count_twos = 0 count_threes = 0 dict = {} for word in string: dict[word] = 0 for key in dict: for _word in string: if key == _word: dict[key] += 1 for _key in dict: if dict[_key] == 2: count_twos = 1 elif dict[_key] == 3: count_threes = 1 return count_twos, count_threes, dict if __name__ == "__main__": INPUT = 'input.txt' strings = [str(line.rstrip('\n')) for line in open(INPUT)] count_twos_ = 0 count_threes_ = 0 for string in strings: count_twos, count_threes, dict = result(string) count_twos_ += count_twos count_threes_ += count_threes print(count_twos_, count_threes_) print("Checksum:", count_twos_ * count_threes_)
c57bf5de10396fb91422064e3a68639c048ee4da
dreamson80/Python_learning
/loop_function.py
149
3.890625
4
def hi(): print('hi') def loop(f, n): # f repeats n times if n <= 0: return else: f() loop(f, n-1) loop(hi , 5)
ea9628aae7659d2c942568ad4f6bfca3c32a8cf9
Harrywekesa/Classes
/classstudents.py
747
4.03125
4
class Student: #defining class 'Common base class for all students' student_count = 0 #class variable accessible to all instances of the class def __init__(self, name, id): # class constructor self.name = name self.id = id Student.student_count =+ 1 def printStudentData(self): #Other class methods declared as normal functions print('Name : ', self.name, 'Id : ', self.id) s = Student("Harrison wekesa", 2034) d = Student('Nathan Lomin', 2042) e = Student("Brian Kimutai", 2220) s.printStudentData() #Accessing class attributes using the dot operator d.printStudentData() #Accessing class attributes using the dot operator e.printStudentData() print("Total students : ", Student.student_count)
f600c5a54d0e24daac47a3c576c10e54c97a75e3
PaulLiang1/CC150
/binary_search/searchinsert/search_insert_2.py
647
3.953125
4
class Solution: """ @param A : a list of integers @param target : an integer to be inserted @return : an integer """ def searchInsert(self, A, target): # boundary case if A is None or target is None: return None if len(A) == 0: return 0 low = 0 high = len(A) - 1 while low <= high: # prevent overflow mid = low + (high - low) / 2 if A[mid] == target: return mid elif A[mid] > target: high = mid - 1 else: low = mid + 1 return low
d01bc0fe676657ad68c0b3fdd3c3f5d13a7e8a36
PaulLiang1/CC150
/linklist/partition_list.py
1,275
3.953125
4
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of linked list. @param x: an integer @return: a ListNode """ def partition(self, head, x): if head is None or head.next is None: return head before = after = None before_ptr = after_ptr = None ptr = head while ptr is not None: if ptr.val < x: if before is None: before_ptr = ptr before = ptr else: before_ptr.next = ptr before_ptr = ptr else: if after is None: after_ptr = ptr after = ptr else: after_ptr.next = ptr after_ptr = ptr ptr = ptr.next if before is None: after_ptr.next = None return after elif after is None: before_ptr.next = None return before else: before_ptr.next = after after_ptr.next = None return before
0832f4bc298fe913b4cd09bfb1f976173e74f751
PaulLiang1/CC150
/linklist/remoev_nth_node_from_list.py
925
3.765625
4
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of linked list. @param n: An integer. @return: The head of linked list. """ def removeNthFromEnd(self, head, n): prev_ptr = ptr = n_ptr = head for i in xrange(n): n_ptr = n_ptr.next while n_ptr is not None: n_ptr = n_ptr.next prev_ptr = ptr ptr = ptr.next # remove head: if head == ptr: if ptr.next is None: return None else: head = ptr.next return head # remove last nd elif ptr.next is None: prev_ptr.next = None # remove nd in middle else: prev_ptr.next = ptr.next return head
3a6afb8dd2b80a53e0b1375c0d9212d486bcc62a
PaulLiang1/CC150
/linklist/sort_link_list_merge_sort.py
1,353
3.953125
4
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of the linked list. @return: You should return the head of the sorted linked list, using constant space complexity. """ def sortList(self, head): if head is None or head.next is None: return head mid = self.findmid(head) right = self.sortList(mid.next) mid.next = None left = self.sortList(head) return self.merge(left, right) def findmid(self, node): slow_ptr = fast_ptr = node while fast_ptr.next is not None and fast_ptr.next.next is not None: fast_ptr = fast_ptr.next.next slow_ptr = slow_ptr.next return slow_ptr def merge(self, list1, list2): dummy = ListNode(0) ptr = dummy while list1 and list2: if list1.val < list2.val: ptr.next = list1 ptr = list1 list1 = list1.next else: ptr.next = list2 ptr = list2 list2 = list2.next if list1: ptr.next = list1 if list2: ptr.next = list2 return dummy.next
7eb9f91582d5d33fd2d8d4a9cc604075b63bd44f
PaulLiang1/CC150
/binary_tree/complete_binary_tree_iter.py
1,085
3.78125
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): this.val = val this.left, this.right = None, None """ from collections import deque class Solution: """ @param root, the root of binary tree. @return true if it is a complete binary tree, or false. """ def isComplete(self, root): if root is None: return True queue = deque() queue.append(root) result = list() # Do BFS while len(queue) > 0: node = queue.popleft() if node is None: result.append('#') continue result.append(node.val) queue.append(node.left) queue.append(node.right) if '#' not in result: return True non_hash_bang_found = False for i in xrange(len(result) - 1, -1, -1): if '#' == result[i] and non_hash_bang_found is True: return False if '#' != result[i]: non_hash_bang_found = True return True
6533ce18f884504f827c1bd6e96d9658d7a6d795
PaulLiang1/CC150
/binary_tree/binary_tree_level_order_traversal.py
890
3.703125
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ from collections import deque class Solution: """ @param root: The root of binary tree. @return: Level order in a list of lists of integers """ def levelOrder(self, root): result = list() if root is None: return result queue = deque() queue.append(root) while len(queue) > 0: sub_result = list() for i in xrange(len(queue)): node = queue.popleft() sub_result.append(node.val) if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) result.append(sub_result) return result
39e68074ff349b3c0b678957c5858ab9a7987833
PaulLiang1/CC150
/array/sort_colors.py
632
3.71875
4
class Solution: """ @param nums: A list of integer which is 0, 1 or 2 @return: nothing """ def sortColors(self, nums): if nums is None or len(nums) == 0: return nums zero_idx = 0 two_idx = len(nums) - 1 i = 0 while i <= two_idx: if nums[i] == 0: nums[zero_idx], nums[i] = nums[i], nums[zero_idx] zero_idx += 1 i += 1 elif nums[i] == 1: i += 1 elif nums[i] == 2: nums[two_idx], nums[i] = nums[i], nums[two_idx] two_idx -= 1
36d89924222e0e22a0c1b77dd71a77102a64c7d9
kiwanter/Python-Workspace
/work5/5-2.py
375
3.5
4
f=open('log.txt','w') f.close() def outer(func): def inner(*args): f=open('log.txt','a') f.write('start %s(%s)'%(func.__name__,args)) f.write('\n') f.close() return func(*args) return inner @outer def fun1(i): print(i+1) return i @outer def fun2(n,s): for i in range(n): print(s) fun1(5) fun2(3,'hello')
198d10d5bfedd6d8de05492324b991c7d5172f0a
kiwanter/Python-Workspace
/work1/1-1.py
430
3.84375
4
odd=[] even=[] prime=[] user1=[] for i in range(0,50): if(i%2==0): even.append(i) if(i%3)==0: user1.append(i) if(i%2!=0): odd.append(i) isprime=1 for j in range(2,i): if(i%j==0): isprime=0 if(i>=2 and isprime==1): prime.append(i) print("偶数:",even) print("奇数:",odd) print("质数:",prime) print("同时被二三整除:",user1)
033707f7e7982db2fc97a110263d385005f6223e
kiwanter/Python-Workspace
/work6/6-1.py
1,057
4.09375
4
#一、定义一个狗类,里面有一个 列表成员变量(列表的元素是字典), 分别记录了 3种颜色的狗的颜色, 数量,和价格;实现狗的买卖交易方法; 打印输出经过2-3次买卖方法后,剩下的各类狗的数量; class dog(): __data=[] def __init__(self,r:int,g:int,b:int): self.__data.append({'color':'red','number':r,'price':30}) self.__data.append({'color':'green','number':g,'price':20}) self.__data.append({'color':'blue','number':b,'price':40}) def p(self): for t in self.__data: print('%s dog price %d now has %d' %(t['color'],t['price'],t['number'])) def buy(self,c:str,n:int): for t in self.__data: if t['color']==c: t['number']+=n print('buy %s dog %d' %(c,n)) def sell(self,c:str,n:int): for t in self.__data: if t['color']==c: t['number']-=n print('sell %s dog %d' %(c,n)) a=dog(2,3,4) a.p() a.buy('red',3) a.p() a.sell('blue',2) a.p()
fd9dad0af1812ba52f121ceb27cdac565a1441df
zilinwujian/sgFoodImg
/fileHandle.py
1,119
3.734375
4
# #coding:utf-8 import os # def fileRead(filePath): # fileList = list() # with open(filePath,"r") as f: # # # for line in f.readline(): # # line = line.strip() # 去掉每行头尾空白 # # print line # # if not len(line) or line.startswith('#'): # 判断是否是空行或注释行 # # continue # 是的话,跳过不处理 # # fileList.append(line) # 保存 # return fileList # 读取文件 def fileRead(filePath): f = open(filePath, 'r') # 以读方式打开文件 result = list() for line in f.readlines(): # 依次读取每行 line = line.strip() # 去掉每行头尾空白 result.append(line) # 保存 f.close() return result # 写入文件 def fileWrite(filePath,contents): f =open(filePath,'a+') f.write(contents) f.close() return # 创建目录 def makeDir(fileDir): if not os.path.exists(fileDir): # print(fileDir, " not exist") os.makedirs(fileDir) # print("make directory successfully") else: print(fileDir, "exist")
fb62ce8b5b142244e6ad9e8ac4a0ea62bec28689
OleKabigon/test1
/Nested loop.py
124
4.09375
4
for x in range(4): # This is the outer loop for y in range(3): # This is the inner loop print(f"{x}, {y}")
43e3cb0d6e43924b778e04ac8e6aa2234bba0a7b
kishoreganth-Accenture/Training
/python assessment 3/rationalMultiplication2.py
249
4.03125
4
import math t = int(input("enter the number of rrational numbers needed to multiply :")) product = 1 num = 1 den = 1 for i in range(t): a = int(input()) b = int(input()) product= product * a/b print(product.as_integer_ratio())
7676428ccc068cb340ac724f2a4a7df6c288b250
kishoreganth-Accenture/Training
/python assessment 3/cartesianProduct7.py
115
3.5
4
A = [1, 2] B = [3, 4] for i in set(A): for j in set(B): print("(",i,",",j,")",end = "")
37aa1112ee4933613e016e886a874f31b3c76685
PrasTAMU/SmartStats
/weatherUtil.py
1,472
3.84375
4
import requests import config #Uses the OpenWeatherMap API to get weather information at the location provided by the car WEATHER_KEY=config.openweathermapCONST['apikey']#'741365596cedfc98045a26775a2f947d' #gets generic weather information of the area def get_weather(lat=30.6123149, lon=-96.3434963): url = "https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid={}".format(str(lat), str(lon), WEATHER_KEY) r = requests.get(url) return r.json() #isolates the temperature from the list and returns it to the main file def weather(lat=30.6123149, lon=-96.3434963): weather = get_weather(lat, lon) temperature = weather['main']['temp'] temperature = temperature - 273.15 return str(temperature) #creative descriptions of how the weather feels def temperature_description(temperature="25"): temp = float(temperature) if temp < -30: return ", perfect weather for penguins." elif temp < -15: return ", you might want stay inside." elif temp < 0: return ", you should wear a few layers." elif temp < 10: return ", sure is chilly." elif temp < 20: return ", sweater weather!" elif temp < 30: return ", the weather looks great!" elif temp < 40: return ", ice cream weather!" elif temp < 45: return " stay inside and stay hydrated." else: return ", the A/C bill is going to be high."
4f0ed2eb6105138360c8b2c165cfe5550c797fcb
NielsRoe/ProgHw
/Huiswerk/28.09 Control Structures/1. If statements.py
213
3.765625
4
score = float(input("Geef je score: ")) if score > 15 or score == 15: print("Gefeliciteerd!") print("Met een score van %d ben je geslaagd!" % (score)) else: print("Helaas, je score is te laag.")
4eb84d42d875ac7d4d69ca9fb3682b799b71ea50
YuvalLevy1/ImageProcessing
/src/slider.py
2,576
3.515625
4
import math import pygame SLIDER_HEIGHT = 5 VALUE_SPACE = 50 class Circle: def __init__(self, x, y, radius, color): self.x = x self.y = y self.radius = radius self.color = color class Slider: def __init__(self, coordinates, min_value, max_value, length, text): self.held = False self.__x = coordinates[0] self.__y = coordinates[1] self.__max_x = self.__x + length self.min = min_value self.max = max_value self.__length = length self.rectangle = pygame.Rect(self.__x, self.__y, length, SLIDER_HEIGHT) self.__circle = Circle(self.__x + int(length / 2), self.__y + 2, SLIDER_HEIGHT, (127, 127, 127)) font = pygame.font.SysFont('Corbel', 20) self.text = text self.rendered_text = font.render(text, True, (0, 0, 0)) """ moves the circle according to borders """ def move_circle(self, x): if not self.held: return if self.between_borders(x): self.__circle.x = x return self.__circle.x = self.__closest_to(x) """ returns the closest point to x from border """ def __closest_to(self, x): if math.fabs(x - self.__x) > math.fabs(x - self.__max_x): return self.__max_x return self.__x """ returns true if param x is between the boarders of the slider. """ def between_borders(self, x): return self.__max_x >= x >= self.__x def get_value(self): if self.__circle.x == self.__x: return self.min if self.__circle.x == self.__max_x: return self.max return int((self.__circle.x - self.__x) * (self.max / self.__length)) def get_circle_x_by_value(self, value): return (value * self.__length + self.__x * self.max) / self.max def is_mouse_on_circle(self, mouse_pos): return math.dist(mouse_pos, self.get_circle_coordinates()) <= self.__circle.radius def get_circle_coordinates(self): return self.__circle.x, self.__circle.y def get_size(self): return self.rectangle.width + self.rendered_text.get_rect().width + ( self.__x - self.get_value_coordinates()[0]) + VALUE_SPACE def get_circle_r(self): return self.__circle.radius def get_circle_color(self): return self.__circle.color def get_text_coordinates(self): return self.__max_x + 3, self.__y - 8 def get_value_coordinates(self): return self.__x - VALUE_SPACE, self.__y - 8
f003dd889cdce228f66dbad8f66955c9c32563c0
csgray/IPND_lesson_3
/media.py
1,388
4.625
5
# Lesson 3.4: Make Classes # Mini-Project: Movies Website # In this file, you will define the class Movie. You could do this # directly in entertainment_center.py but many developers keep their # class definitions separate from the rest of their code. This also # gives you practice importing Python files. # https://www.udacity.com/course/viewer#!/c-nd000/l-4185678656/m-1013629057 # class: a blueprint for objects that can include data and methods # instance: multiple objects based on a class # constructor: the __init__ inside the class to create the object # self: Python common practice for referring back to the object # instance methods: functions within a class that refers to itself import webbrowser class Movie(): """This class provides a way to store movie related information.""" def __init__(self, movie_title, rating, duration, release_date, movie_storyline, poster_image, trailer_youtube): # Initializes instance of class Movie self.title = movie_title self.rating = rating self.duration = duration self.release_date = release_date self.storyline = movie_storyline self.poster_image_url = poster_image self.trailer_youtube_url = trailer_youtube def show_trailer(self): # Opens a browser window with the movie trailer from YouTube webbrowser.open(self.trailer_youtube_url)
967a8757c9139a9b7614956677620f3697443938
HenkT28/GMIT
/my-first-program-new.py
339
3.984375
4
# Henk Tjalsma, 03-02-2019 # Calculate the factorial of a number. # start wil be the start number, so we need to keep track of that. # ans is what the answer will eventually become. It started as 1. # i stands for iterate, something repetively. start = 10 ans = 1 i = 1 while i <= start: ans = ans * i i = i + 1 print(ans)
d2ea6ef4b341d5071a0adb05dd72d4f9995b677e
ncmarian/prediction
/archive/formatter.py
4,918
3.578125
4
#Owen Chapman #first stab at text parsing import string #Premiership #Championship #opening files. def getFiles (read, write): """ read: string of filename to be read from. write: string name of file to be written to. returns: tuple of files (read,write) """ r=open(read) w=open(write,'w') return (r,w) def getPremierTeams(r,leaguename): """ finds the team names of all of the teams participating in the premier league of a given year. r: file object to be read from return: list of strings. all of the teams' names. """ start=0 teams=[] for line in r: line=line.strip() if start==0: if line==leaguename: start=1 elif start==1: if line=="Round 1": start=2 else: if line=="Round 2": break elif line=='' or line[0]=='[' or line[-1]==']': continue else: wordlist=line.split(' ') firstname="" scoreindex=0 for i in range(len(wordlist)): word=wordlist[i] if word=='': continue elif word[0] in string.digits: scoreindex=i break else: firstname+=(word+' ') firstname=firstname.strip() #print firstname teams.append(firstname) secondname="" for i in range(scoreindex+1,len(wordlist)): word=wordlist[i] if word=='': continue else: secondname+=(word+ ' ') secondname=secondname.strip() #print secondname teams.append(secondname) return teams #09-10. for testing purposes. globalteams=['Chelsea','Manchester U','Arsenal','Tottenham','Manchester C','Aston Villa', 'Liverpool','Everton','Birmingham','Blackburn','Stoke','Fulham','Sunderland', 'Bolton','Wolverhampton','Wigan','West Ham','Burnley','Hull','Portsmouth'] def parse (r,w,pteams,cteams): """ r: file object to be read from w: file object to be written to returns void """ count = 0 regseas=0 for line in r: d=parseline(line,pteams+cteams) if d!=None: (t1,s,t2)=d tag='c' if t1 in pteams and t2 in pteams: regseas+=1 tag='p' #print t1+'_'+s+'_'+t2+'_'+tag w.write(t1+'_'+s+'_'+t2+'_'+tag+'\n') count +=1 print regseas, count def parseline(line,teamlist): """ line: string line to be parsed teamlist: list of strings: valid team names. Should be created prior to calling this function. All teams in a given league. return: void if not a valid score (string team, string score, string team) if valid score. """ line=line.strip() wordlist=line.split(" ") firstname="" scoreindex=0 for i in range(len(wordlist)): word=wordlist[i] if word=='': continue elif word[0] in string.digits: scoreindex=i break else: firstname+=(word+' ') firstname=firstname.strip() #print firstname score=(wordlist[scoreindex]).strip() if (len(score)<3) or (score[0] not in string.digits) or (score[-1] not in string.digits) or (score[1] != '-'): return None if firstname not in teamlist: return None secondname="" for i in range(scoreindex+1,len(wordlist)): word=wordlist[i] if word=='': continue elif word[0]=='[': break else: secondname+=(word+ ' ') secondname=secondname.strip() #print secondname if secondname not in teamlist: return None return (firstname,wordlist[scoreindex],secondname) def getFilePrefix(yr1): if yr1<10: tdy='0' else: tdy='' tdy+=str(yr1) if yr1<9: tdyp1='0' else: tdyp1='' tdyp1+=str(yr1+1) return (tdy+'-'+tdyp1) def writeTeams(year): prefix=getFilePrefix(year) r=open(prefix+" scores.txt") w=open(prefix+" teams.txt",'w') teams=getPremierTeams(r,'Premiership') for team in teams: print team w.write(team+'\n') r.close() w.close() return teams def run(year): pteams=writeTeams(year) prefix=getFilePrefix(year) fname1=prefix+' scores.txt' fname2=prefix+' scores formatted.txt' r=open(fname1) cteams=getPremierTeams(r,'Championship') print cteams r.close() (r,w)=getFiles(fname1,fname2) parse(r,w,pteams,cteams) r.close() w.close()
16415d6886a2bc38110cdb9df667adb99a78b638
Mounik007/Map-Reduce
/mounik_muralidhara_squared_two_1.py
1,823
3.53125
4
import MapReduce import sys import re """ Matrix 5*5 Multiplication Example in the Simple Python MapReduce Framework using two phase """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line class MapValueObject(object): """__init__() functions as class constructor""" def __init__(self, mapSet=None, mapRowOrColumn = None, mapCellValue = None): self.mapSet = mapSet self.mapRowOrColumn = mapRowOrColumn self.mapCellValue = mapCellValue def mapper(record): elements = record mapValueObjA = MapValueObject() mapValueObjA.mapSet = "A" mapValueObjA.mapRowOrColumn = elements[0] mapValueObjA.mapCellValue = elements[2] mr.emit_intermediate(elements[1], mapValueObjA) mapValueObjB = MapValueObject() mapValueObjB.mapSet = "B" mapValueObjB.mapRowOrColumn = elements[1] mapValueObjB.mapCellValue = elements[2] mr.emit_intermediate(elements[0], mapValueObjB) def reducer(key, list_of_values): listA = [] listB = [] for index in range(len(list_of_values)): if(list_of_values[index].mapSet == "A"): listA.append(list_of_values[index]) else: listB.append(list_of_values[index]) for indexA in range(len(listA)): for indexB in range(len(listB)): keyValueLst = [] keyValueLst.append(listA[indexA].mapRowOrColumn) keyValueLst.append(listB[indexB].mapRowOrColumn) keyValueLst.append((listA[indexA].mapCellValue) * (listB[indexB].mapCellValue)) mr.emit(keyValueLst) # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
140675932ae15b2421f6ca7a1f7cbf6babab74f6
Ludwig-Graef/webserver
/webserver_v3/WebServer.py
1,154
3.671875
4
import sys import argparse import www if __name__ == "__main__": if sys.version_info[0] is not 3: print("ERROR: Please use Python version 3 !! (Your version: %s)" % (sys.version)) exit(1) def type_port(x): x = int(x) if x < 1 or x > 65535: raise argparse.ArgumentTypeError( "Port number has to be greater than 1 and less than 65535.") return x description = ("Serves a local directory on your computer via the HTTP protocol." "Use the www/serve.py file to implement your changes.") parser = argparse.ArgumentParser(description=description) parser.add_argument("-a", "--address", help="The address to listen on. (Default: '127.0.0.1')", default="127.0.0.1") parser.add_argument("-p", "--port", help="The port to listen on. (Default: 8080)", type=type_port, default=8080) args = parser.parse_args() www.serve(address=args.address, port=args.port)
f3a0ae3922cf341c118cb36ca0fdd6ca2d9ea521
lucasgameiroborges/Python-lista-1---CES22
/item10.py
133
3.59375
4
def sum(A, B): (x, y) = A (z, w) = B return (x + z, y + w) X = (1, 2) Y = (3, 4) print("{0}".format(sum(X, Y)))
d3abb379287051f91e29c3bc69fc07df400b5573
MathAdventurer/Python-Algorithms-and-Data-Structures
/Codes/chapter_1/chapter_1_solution.py
2,116
3.890625
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: Wang,Xudong 220041020 SDS time:2020/11/25 class Fraction: def gcd(m: int, n: int): if n != 0 and m != 0: while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n else: return None def __init__(self,top,bottom): common = Fraction.gcd(top, bottom) self.num = top//common self.den = bottom//common def show(self): print(self.num,"/",self.den) print(self.num,"/",self.den) def __str__(self): return str(self.num) + "/" + str(self.den) # 定义加法 \为续行符 # def __add__(self, otherfraction): # newnum = self.num * otherfraction.den + \ # self.den * otherfraction.num # newden = self.den * otherfraction.den # return Fraction(newnum,newden) # 化简分数的方法 greatest common divisor,GCD # 欧几里得算法 化简分数 不用loop用判断写不出来 def __add__(self,otherfraction): newnum = self.num * otherfraction.den + \ self.den * otherfraction.num newden = self.den * otherfraction.den common = Fraction.gcd(newnum,newden) #如果函数定义在class内部,调用的时候需要用class.method,定义在外部可以直接调用gcd return Fraction(newnum//common,newden//common) #只取了余数 # 浅相等与真相等 # 浅相等:同一个对象的引用(根据引用来判断)才为真,在当前实现中,分子和分母相同的两个不同的对象是不相等的。 # 深相等:根据值来判断相等,而不是根据引用 def __eq__(self, other): firstnum = self.num * other.den secondnum = self.den * other.num return firstnum == secondnum def __le__(self, other): firstnum = self.num * other.den secondnum = self.den * other.num return firstnum <= secondnum if __name__ == "__main__": f1 = Fraction(6,8) f1.show() print(f1)
4af35eb512097893fbb7cd211b0bb5cbdc60d5fb
camiladlsa/Recursividad
/FactorialTR.py
445
3.984375
4
n = int(input("\nIngrese un entero positivo para tomar el factorial: ")) def factorial(n): if not isinstance(n, int): print("Error: el valor debe ser un entero\n") elif n < 0: print("\nError: el factorial no existe para n < 0.\n") else: return factorial_process(n, 1); def factorial_process(n, accm): if n == 0: return accm else: return factorial_process(n - 1, n * accm) print("\nFactorial:",factorial(n),"\n")
8dd4b348fd8210b3ca0c49a097bb52b97fefab2c
williamabreu/esp8266-micropython
/thermistor.py
999
3.53125
4
import machine, math def get_temp(_pin): # Inputs ADC Value from Thermistor and outputs temperature in Celsius raw_ADC = machine.ADC(_pin).read() # Assuming a 10k Thermistor. Calculation is actually: resistance = (1024/ADC) resistance=((10240000/raw_ADC) - 10000) # ***************************************************************** # * Utilizes the Steinhart-Hart Thermistor Equation: * # * temperature in Kelvin = 1 / {A + B[ln(R)] + C[ln(R)]^3} * # * where A = 0.001129148, B = 0.000234125 and C = 8.76741E-08 * # ***************************************************************** temp = math.log(resistance) temp = 1 / (0.001129148 + (0.000234125 * temp) + (0.0000000876741 * temp * temp * temp)) temp = temp - 273.15; # Convert Kelvin to Celsius # Uncomment this line for the function to return Fahrenheit instead. # temp = (temp * 9.0)/ 5.0 + 32.0 # Convert to Fahrenheit return temp # Return the temperature
faab5b174ee26be0d7355a29476d7d4af0d96418
rmmo14/pyforloopbasic2
/for_loop_basic_2.py
3,023
3.890625
4
# 1. Big size # def biggie(mylist): # empty = [] # for x in range (0,len(mylist)): # if mylist[x] > 0: # empty.append('big') # else: # empty.append(mylist[x]) # print(empty) # return empty # holder = biggie([-1, 2, 3, -5]) # 2. count positives # def counting(my_list): # count = 0 # empty = [] # for x in range (0,len(my_list)): # if my_list[x] > 0: # count += 1 # my_list[len(my_list) - 1] = count # print (my_list) # return my_list # holder = counting([-1, 2, -3, 9, -3, -4]) # 3. sum total # def sumtotal(mylist): # sum = 0 # for x in range (0, len(mylist)): # sum += mylist[x] # print (sum) # return sum # hold = sumtotal([1,2,5,6]) # 4. average # def average(my_list): # sum = 0 # for x in range (0,len(my_list)): # sum += my_list[x] # avg = sum / len(my_list) # print(avg) # return avg # holder = average([2,3,5,6,4]) # 5. length # def length(mylist): # holder = len(mylist) # print(holder) # return holder # hold = length([2,3,4,5,6,7]) # 6. minimum # def min(my_list): # if my_list == []: # print("False") # return False # else: # min = my_list[0] # for x in range (0,len(my_list)): # if my_list[x] < min: # min = my_list[x] # print(min) # return min # holder = min([1,2,3,-1]) # 7. maximum # def max(mylist): # if mylist == []: # print("False") # return False # else: # max = mylist[0] # for x in range (0, len(mylist)): # if mylist[x] > max: # max = mylist[x] # print(max) # return max # hold = max([]) # 8. ulti analysis # def ult(my_list): # if my_list == []: # print("False") # return False # else: # dicto = {} # min = my_list[0] # max = my_list[0] # sum = 0 # for x in range (0,len(my_list)): # sum += my_list[x] # if my_list[x] > max: # max = my_list[x] # elif my_list[x] < min: # min = my_list[x] # avg = sum / len(my_list) # dicto['min'] = min # dicto['max'] = max # dicto['avg'] = avg # dicto['length'] = len(my_list) # print(dicto) # return dicto # holder = ult([2,3,4,5,6,4]) # potato = ult([-1,-1,-2,-1,0]) # 9. reverse list def revlist(mylist): length = len(mylist) - 1 for x in range (int(len(mylist)/2)): temp = mylist[length - x] mylist[length - x] = mylist[x] mylist[x] = temp print(mylist) return mylist # def reverse_list(nums_list): # list_len = len(nums_list) # for idx in range(int(list_len/2)): # temp = nums_list[list_len-1-idx] # nums_list[list_len-1-idx] = nums_list[idx] # nums_list[idx] = temp # print(nums_list) # return nums_list print(revlist([3, 1, 8, 10, -5, 6]))
9f3dd5176c949bf0cf35fd32d81900aca0665e64
mglowacz/algorithms
/ch4/quickSort.py
422
3.953125
4
from random import randint def quickSort(arr) : if (len(arr) < 2) : return arr pivot = randint(0, len(arr)) less = [val for idx, val in enumerate(arr) if val <= arr[pivot] and idx != pivot] greater = [val for idx, val in enumerate(arr) if val > arr[pivot] and idx != pivot] return quickSort(less) + [arr[pivot]] + quickSort(greater) arr = [56, 21, 45, 2, 14, 86, 33, 12, 8] print(arr) print(quickSort(arr))
2d451bac8c45fbacd81c9074a9261463d67fbf52
mglowacz/algorithms
/ch4/binarySearch.py
741
3.84375
4
def binarySearch(arr, item) : if arr == [] : return -1 if len(arr) == 1 : return 0 if item == arr[0] else -1 mid = len(arr) // 2 if arr[mid] == item : return mid sublist = arr[:mid] if arr[mid] > item else arr[mid + 1:] subindex = 0 if arr[mid] > item else mid + 1 bs = binarySearch(sublist, item) return -1 if bs == -1 else subindex + bs arr = [1, 3, 4, 6, 7, 9, 12, 13, 18] print(arr) print("Found (1) at {}".format(binarySearch(arr, 1))) print("Found (3) at {}".format(binarySearch(arr, 3))) print("Found (7) at {}".format(binarySearch(arr, 7))) print("Found (12) at {}".format(binarySearch(arr, 12))) print("Found (18) at {}".format(binarySearch(arr, 18))) print("Found (11) at {}".format(binarySearch(arr, 11)))
8e52b22c8ed94bac68be42c51785e6333690d415
SirBman/Prac5
/listWarmUp.py
305
3.90625
4
"""List Warm Up""" numbers = [3, 1, 4, 1, 5, 9, 2] print (numbers[0], numbers[-7], numbers[3], numbers[:-1], numbers[3:4], 5 in numbers, 7 in numbers, "3" in numbers, numbers + [6, 5, 3]) numbers [0] = "ten" print(numbers[0]) numbers[-1] = 1 print(numbers[-1]) print(numbers[2:]) print(9 in numbers)
bcab1361c0719abacf15a91b0ae627330749501e
rottenFetus/Algorithms-4-everyone
/Data Structures/Binary Search Tree/Python/BinarySearchTree.py
4,827
4.28125
4
from TreeNode import * class BinarySearchTree: def __init__(self, root): """ This constructor checks if the root is a TreeNode and if it is not it creates a new one with the data being the given root. """ if not isinstance(root, TreeNode): root = TreeNode(root) self.root = root def insertNewNode(self, node, root=None): def _insertNewNode(root, node): """ 'node' is the node that is to be inserted in the tree. This function takes a node and a tree node and inserts it in that tree. it checks if the current node (the root) is None and if so it just returns 'node', if not it repeats the process but this time for the left subtree if node.data < root.data else it repeats it for the right subtree """ if (root == None): return node elif (node.data < root.data): root.leftChild = _insertNewNode(root.leftChild, node) return root else: root.rightChild = _insertNewNode(root.rightChild, node) return root # If the root is None this means that the tree has no nodes (no root) if (root == None): root = self.root # If the input is not a TreeNode, Make it a TreeNode :) if not isinstance(node, TreeNode): node = TreeNode(node) # Call the helper method self.root = _insertNewNode(root, node) def preOrderTraversal(self, root=None): """ This function traverses the tree in a way such it prints the root of the current tree first, repeats the process for the left subtree then the right one """ def _preOrderTraversal(root): if (root == None): return print(root.data) _preOrderTraversal(root.leftChild) _preOrderTraversal(root.rightChild) # Initialize the root to pass it the helper method if (root == None): root = self.root # Call the helper method _preOrderTraversal(root) def inOrderTraversal(self, root=None): """ Traverse the tree in a way such that it does not print a node unless it had printed every other node that was to the left of it. After printing that node it goes ot the right subtree and does the same """ def _inOrderTraversal(root): if (root == None): return _inOrderTraversal(root.leftChild) print(root.data) _inOrderTraversal(root.rightChild) if (root == None): root = self.root _inOrderTraversal(root) def postOrderTraversal(self, root=None): """ Traverses the tree in a way such that it does not print a node unless it had printed every other node to its right and to its left """ def _postOrderTraversal(root): if (root == None): return _postOrderTraversal(root.leftChild) _postOrderTraversal(root.rightChild) print(root.data) if (root == None): root = self.root _postOrderTraversal(root) def getHeight(self, root=None): """ Gets the height of the tree where the tree that consists of only one node (the root of the tree) has a height of zero. we mean by the height of the tree the longest branch (subtree) it has. The idea is simple, the height of any tree = the maximum between the height of the left and right subtree + 1. If a None value is reached then it has a length of -1, this means that the leaf that is before it has a height of zero """ def _getHeight(root): if (root == None): return -1 leftHeight = _getHeight(root.leftChild) rightHeight = _getHeight(root.rightChild) return 1 + max(leftHeight, rightHeight) if (root == None): root = self.root return _getHeight(root) root = 5 bst = BinarySearchTree(root) bst.insertNewNode(TreeNode(4)) bst.insertNewNode(TreeNode(8)) bst.insertNewNode(TreeNode(10)) bst.insertNewNode(TreeNode(1)) bst.insertNewNode(TreeNode('e')) bst.insertNewNode(TreeNode(11)) bst.insertNewNode(TreeNode(9)) bst.insertNewNode(TreeNode('A')) bst.insertNewNode(TreeNode('x')) print("The height of the tree: " + str(bst.getHeight())) print("-----------------------------") print("In order traversal") bst.inOrderTraversal() print("------------------") print("pre order traversal") bst.preOrderTraversal() print("------------------") print("post order traversal") bst.postOrderTraversal()
4a86095a7680c8066a0ef6e8c6cb54b0e121b08c
rottenFetus/Algorithms-4-everyone
/Algorithms/Searching Algorithms/Binary Search/Python/BinarySearch.py
620
3.75
4
class BinarySearch(): def search(self, haystack, needle): middle = 0 lower_bound = 0 higher_bound = len(haystack) while (lower_bound <= higher_bound): middle = lower_bound + (higher_bound - lower_bound) / 2 if (haystack[middle] == needle): return middle elif (haystack[middle] < needle): lower_bound = middle + 1 elif (haystack[middle] > needle): higher_bound = middle - 1 return -1 bs = BinarySearch() haystack = [2, 3, 5, 7, 11, 13, 17, 19] print( bs.search(haystack, 1) )
a6abf1f12cc09aeb393630d5c59219e9ae0c479b
chill133/BMI-calculator-
/BMI.py
310
4.25
4
height = input("What is your height?") weight = input("What is your weight?") BMI = 703 * (int(weight))/(int(height)**2) print("Your BMI " + str(BMI)) if (BMI <= 18): print("You are underweight") elif (BMI >= 18) and (BMI <= 26): print("You are normal weight") else: print("You are overweight")
bb17f8db4c2707099517d4cf4c748135b5fe5a31
MarvelICY/LeetCode
/Solutions/multiply_strings.py
1,247
3.921875
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Solution of [Multiply Strings] in LeetCode. Created on: Nov 27, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# class Solution: # @param num1, a string # @param num2, a string # @return a string # @ICY: big number multiply def multiply(self, num1, num2): num1 = num1[::-1] num2 = num2[::-1] tmp = [0 for i in range(len(num1)+len(num2))] result = [] for i in range(len(num1)): for j in range(len(num2)): tmp[i+j] += int(num1[i]) * int(num2[j]) for i in range(len(tmp)): digit = tmp[i] % 10 carry = tmp[i] / 10 if i < len(tmp) - 1: tmp[i+1] += carry result.append(str(digit)) result = result[::-1] while result[0] == '0' and len(result) > 1: del result[0] result = ''.join(result) return result #----------------------------SELF TEST----------------------------# def main(): num1 = '188' num2 = '24' solution = Solution() print solution.multiply(num1,num2) pass if __name__ == '__main__': main()
9f62f466d3d580c12d4c2c93dc9cfd3d8ac93924
MarvelICY/LeetCode
/Solutions/validate_binary_search_tree.py
1,007
3.84375
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Solution of [Validate Binary Search Tree] in LeetCode. Created on: Nov 12, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a boolean def isValidBST(self, root): return self.ValidBST(root, -2147483648, 2147483647) def ValidBST(self, root, min, max): #update the value of min and max recursively if root == None: return True if root.val <= min or root.val >= max: return False return self.ValidBST(root.left, min, root.val) and self.ValidBST(root.right, root.val, max) #----------------------------SELF TEST----------------------------# def main(): pass if __name__ == '__main__': main()
c21f43947cb50c668b37bb9eee7624154a6e0653
MarvelICY/LeetCode
/Solutions/unique_path.py
1,515
3.734375
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Solution of [Unique Paths II] in LeetCode. Created on: Nov 18, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# class Solution: # @param obstacleGrid, a list of lists of integers # @return an integer def uniquePathsWithObstacles(self, obstacleGrid): if obstacleGrid == [] or obstacleGrid[0][0] == 1: return 0 dp = obstacleGrid[:] dp[0][0] = 1 row_max = len(obstacleGrid) col_max = len(obstacleGrid[0]) for i in range(1, row_max): if obstacleGrid[i][0] == 1: dp[i][0] = 0 else: dp[i][0] = dp[i-1][0] for i in range(1, col_max): if obstacleGrid[0][i] == 1: dp[0][i] = 0 else: dp[0][i] = dp[0][i-1] for row in range(1, row_max): for col in range(1, col_max): if obstacleGrid[row][col] == 1: dp[row][col] = 0 else: dp[row][col] = dp[row-1][col] + dp[row][col-1] return dp[row_max-1][col_max-1] #----------------------------SELF TEST----------------------------# def main(): grid = [ [0,0,0], [0,1,0], [0,0,0] ] solution = Solution() print solution.uniquePathsWithObstacles(grid) pass if __name__ == '__main__': main()
399f740052feeccdebd601c1bda14a24e04f64ed
MarvelICY/LeetCode
/Solutions/next_permutation.py
1,261
3.609375
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Solution of [Next Permutation] in LeetCode. Created on: Nov 20, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# class Solution: # @param num, a list of integer # @return a list of integer # @ICY: reprint def nextPermutation(self, num): if len(num) <= 1: return num partition = -1 for i in range(len(num)-2, -1, -1): if num[i] < num[i+1]: partition = i break if partition == -1: num.reverse() return num else: for i in range(len(num)-1, partition, -1): if num[i] > num[partition]: num[i],num[partition] = num[partition],num[i] break left = partition+1; right = len(num)-1 while left < right: num[left],num[right] = num[right],num[left] left+=1; right-=1 return num #----------------------------SELF TEST----------------------------# def main(): num = [1,2,4,3] num = [2,1,4,3] solution = Solution() print solution.nextPermutation(num) pass if __name__ == '__main__': main()
e5b13a2f77a66c8d33fea1c19bccc02d04e972a4
MarvelICY/LeetCode
/Solutions/longest_valid_parentheses.py
1,142
3.78125
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Solution of [Longest Valid Parentheses] in LeetCode. Created on: Nov 27, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# class Solution: # @param s, a string # @return an integer # @ICY: reprint,stack,O(n) def longestValidParentheses(self, s): result = 0 start_index = -1 stack = [] for i in range(len(s)): if s[i] == '(': stack.append(i) elif stack == []: start_index = i #denote the beginning position else: stack.pop() if stack == []: result = max(result, i - start_index) else: result = max(result, i - stack[len(stack)-1]) return result #----------------------------SELF TEST----------------------------# def main(): test_string = '()()))())()))(' test_string = ')()' solution = Solution() print solution.longestValidParentheses(test_string) pass if __name__ == '__main__': main()
2419795a51efcdbe1d5ce3a3a2045f807dc00f5c
MarvelICY/LeetCode
/Solutions/sum_root_to_leaf_numbers.py
978
3.734375
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Solution of [Sum Root to Leaf Numbers] in LeetCode. Created on: Nov 12, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return an integer def sumNumbers(self, root): return add_path(root, 0) def add_path(self, root, path_sum): if root == None: return 0 path_sum = path_sum * 10 + root.val if root.left == None and root.right == None: return path_sum return self.add_path(root.left, path_sum) + self.add_path(root.right, path_sum) #----------------------------SELF TEST----------------------------# def main(): pass if __name__ == '__main__': main()
6ed224ce0268e3ccfb8a2ea8e361b4435e28cbb5
MarvelICY/LeetCode
/Solutions/edit_distance.py
1,138
3.703125
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Solution of [Edit Distance] in LeetCode. Created on: Nov 20, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# class Solution: # @return an integer # @ICY: dp def minDistance(self, word1, word2): row_max = len(word1) + 1 col_max = len(word2) + 1 dp = [[0 for i in range(col_max)] for j in range(row_max)] for row in range(row_max): dp[row][0] = row for col in range(col_max): dp[0][col] = col #print dp for row in range(1,row_max): for col in range(1,col_max): dp[row][col] = min(min(dp[row-1][col]+1, dp[row][col-1]+1), dp[row-1][col-1] + (0 if word1[row-1] == word2[col-1] else 1)) return dp[row_max-1][col_max-1] #----------------------------SELF TEST----------------------------# def main(): word1 = 'abcd' word2 = 'cba' solution = Solution() print solution.minDistance(word1,word2) pass if __name__ == '__main__': main()
5570392d12ebeada71dc57c0d7dc812012579dba
MarvelICY/LeetCode
/Solutions/length_of_last_word.py
900
3.8125
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Solution of [Length of Last Word] in LeetCode. Created on: Nov 13, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# class Solution: # @param s, a string # @return an integer def lengthOfLastWord(self, s): #remove space in the tail of the string for i in range(len(s)-1,-1,-1): if s[i] != ' ': s = s[:i+1] break list = s.split(' ') print list return len(list[len(list)-1]) #----------------------------SELF TEST----------------------------# def main(): test_string = 'leed code' test_string = 'le asd wefsda' test_string = 'a ' solution = Solution() print solution.lengthOfLastWord(test_string) pass if __name__ == '__main__': main()
8904731c0bd6c47eebe2dd98d3c0296f6bdd3d99
MarvelICY/LeetCode
/Solutions/binary_tree_level_order_traversal.py
1,332
3.859375
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Solution of [Binary Tree Level Order Traversal] in LeetCode. Created on: Nov 13, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers # dsf def levelOrder(self, root): if root == None: return [] self.result = [] self.traversal(root,0) return self.result def traversal(self,root,level): if root: if level >= len(self.result): self.result.append([]) self.result[level].append(root.val) self.traversal(root.left, level+1) self.traversal(root.right, level+1) #----------------------------SELF TEST----------------------------# def main(): root = TreeNode(1) a = TreeNode(2) b = TreeNode(3) c = TreeNode(4) d = TreeNode(5) e = TreeNode(6) root.left = a root.right = b a.left = c c.left = e a.right = d solution = Solution() print solution.levelOrder(root) pass if __name__ == '__main__': main()
79acb839e91a261e3bf2974608c3fa527efe1387
MarvelICY/LeetCode
/Solutions/spiral_matrix_2.py
1,641
3.890625
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Solution of [Spiral Matrix II] in LeetCode. Created on: Nov 18, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# class Solution: # @return a list of lists of integer def generateMatrix(self, n): if n == 0: return [] result = [[0 for i in range(n)] for j in range(n)] num = 1 #four boundaries up = 0 bottom = len(result) - 1 left = 0 right = len(result[0]) - 1 # right:0, down:1, left:2, up:3 direct = 0 while up <= bottom and left <= right: if direct == 0: for i in range(left, right+1): result[up][i] = num num += 1 up += 1 if direct == 1: for i in range(up, bottom+1): result[i][right] = num num += 1 right -= 1 if direct == 2: for i in range(right, left-1, -1): result[bottom][i] = num num += 1 bottom -= 1 if direct == 3: for i in range(bottom, up-1, -1): result[i][left] = num num += 1 left += 1 direct = (direct + 1) % 4 #loop return result #----------------------------SELF TEST----------------------------# def main(): n = 3 solution = Solution() print solution.generateMatrix(n) pass if __name__ == '__main__': main()
e75ff35b0086a8ef4a610ed3a737d756e3efc6c5
MarvelICY/LeetCode
/Solutions/string_to_integer.py
2,079
3.84375
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Solution of [Srting to Integer] in LeetCode. Created on: Nov 10, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# class Solution: # @return an integer # hints: space sign and overflow # take care when : no-digit appears, space appears, multi signs appear def atoi(self, str): if str == '': return 0 INT_MAX = 2147483647 #2^31 INT_MIN = -2147483648 sum = 0 sign = 1 sign_num = 0 #bug of leetcode exist = 0 for letter in str: if letter == ' ' and exist == 0: continue if letter == '-': if sign_num > 0: return 0 else: sign = -1 sign_num = 1 exist = 1 elif letter == '+': if sign_num > 0: return 0 else: sign = 1 sign_num = 1 exist = 1 elif letter in '0123456789': digit = int(letter) if sum <= INT_MAX / 10: sum = sum * 10 else: if sign == 1: return INT_MAX else: return INT_MIN if sum <= INT_MAX - digit: sum = sum + digit else: if sign == 1: return INT_MAX else: return INT_MIN exist = 1 else: return sign * sum return sign * sum #----------------------------SELF TEST----------------------------# def main(): test_string = ' -65769863' test_string = ' -0012a42' solution = Solution() print solution.atoi(test_string) pass if __name__ == '__main__': main()
1103ddc9f5b00fad29a428a1c962a7f1fc52b53e
rbpdqdat/osmProject
/phones.py
1,181
3.6875
4
import re import phonenumbers #convert alphabet phone characters to actual phone numbers # missphone = '+19999999999' def phone_letter_tonum(alphaphone): char_numbers = [('abc',2), ('def',3), ('ghi',4), ('jkl',5), ('mno',6), ('pqrs',7), ('tuv',8), ('wxyz',9)] char_num_map = {c:v for k,v in char_numbers for c in k} return("".join(str(char_num_map.get(v,v)) for v in alphaphone.lower())) def is_phone(elem): return (elem.attrib['k'] == "phone") def audit_phone_number(phone): #found some columns had 2 phone numbers phone = phone.split(";")[0] phone = re.sub("^\++0+1?","+1",phone) #some phone numbers were purposely words # such as '1-888-AMC-4FUN' for business #the phone number needed to be converted to properly work if re.search("[A-Za-z]",phone): phone = phone_letter_tonum(phone) if (re.search('^[\+1]',phone) == None): phone = missphone #additional substitution to make sure the #country code was in the phone number phone = re.sub("^1+","+1",phone) z = phonenumbers.parse(phone, "US") phone = phonenumbers.format_number(z, phonenumbers.PhoneNumberFormat.NATIONAL) return phone
2e0b65f9be804d132dd15c781ce5bca69d3c7ff4
niketanmoon/Data-Science
/Data Preprocessing/Day6-Final Data Preprocessing Template/final.py
1,678
3.96875
4
#No need to do missing data, categorical data, Feature Scaling #Feature Scaling is implemented by some of the algorithms, but in some cases you need to do feature scaling #This is the final template of the data preprocessing that you will be needed to do each and every time #Step 1 importing the libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #Step2 Reading the dataset from the file dataset = pd.read_csv('Data.csv') #Give the path to the exact folder #Step3 Listing the dataset as X and Y X = dataset.iloc[:,:-1].values Y = dataset.iloc[:,3].values #Transformation of the missing data #First importing the library # from sklearn.preprocessing import Imputer # #Creating the object # imputer = Imputer(missing_values='NaN', strategy = 'mean', axis= 0) # imputer = imputer.fit(X[:,1:3]) # X[:,1:3] = imputer.transform(X[:,1:3]) #Categorical data encoding #First importing the library # from sklearn.preprocessing import LabelEncoder,OneHotEncoder # #Encoding of X dataset # labelencoder_X = LabelEncoder() # X[:,0] = labelencoder_X.fit_transform(X[:,0]) # #Now doing the dummy encoding # onehotencoder = OneHotEncoder(catgorical_features = [0]) # X = onehotencoder.fit_transform(X).toarray() # #Encoding of the Y dataset # labelencoder_Y = LabelEncoder() # Y = labelencoder_Y.fit_transform(Y) #Splitting the dataset from sklearn.cross_validation import train_test_split X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size = 0.2, random_state = 0) #Feature Scaling # from sklearn.preprocessing import StandardScaler # sc_X = StandardScaler() # X_train = sc_X.fit_transform(X_train) # X_test = sc_X.transform(X_test)
02092a3692fc1dca4d02a0aededb730650683d54
cindykhris/temperature_convertor
/tem_conv.py
1,593
3.90625
4
# -*- coding: utf-8 -*- """ Authors: Cindy Pino Date: 3/26/2020 Description: Kelvin, Celsius, Farenheight Temperature Convertor""" import sys def tempConvertor(): while True: inp1 = (input("Temperature one? (c = celsius, f = fahrenheit, k = kelvin) ")) if inp1 == "c" or inp1 == "f" or inp1 == "k": break while True: inp2 = input("Temperature two? (c = celsius, f = fahrenheit, k = kelvin) ") if inp1 != inp2 and inp2 == "c" or inp1 != inp2 and inp2 == "f" or inp1 != inp2 and inp2 == "k": break while True: inp3 = int(input(("What's your temperature " ))) if (inp3) <= 1000: break if inp1 == "c" and inp2 == "f": c1 = float(inp3) * 9/5 + 32 print(c1) elif inp1 == "c" and inp2 == "k": c2 = float(inp3) + 273.15 print(c2) elif inp1 == "f" and inp2 == "c": f1 = (float(inp3) - 32 ) * 5/9 print(f1) elif inp1 == "f" and inp2 == "k": f2 = (((float(inp3) - 32) * 5/9 ) + 273.15 ) print(f2) elif inp1 == "k" and inp2 == "c": k1 = (float(inp3) - 273.15) print(k1) else: k2 = (((float(inp3) - 273.15) * 9/5 )+ 32) print(k2) def again(): while True: inp4 = (str(input(" Do you want to try again? yes/no. "))).lower() if inp4 == "yes": tempConvertor() if inp4 == "no": sys.exit() while True: if inp4 != "yes" or inp4 != "no": break (str(tempConvertor())) (again())
73367dc10875863ceac9026f5292a5e4dccb6a21
paulan94/Intermediate-Python-Tutorials
/listcomp_generators.py
887
3.828125
4
##xyz = [i for i in range(5000000)] #list takes longer because its stored into memory ##print 'done' ##xyz = (i for i in range(5000000)) #generator doesnt store as list or into memory ##print 'done' #this is almost instant after list is created input_list = [5,6,2,10,15,20,5,2,1,3] def div_by_five(num): return num % 5 == 0 xyz = (i for i in input_list if div_by_five(i)) #return #s that are div by 5 for i in xyz: print i ##[print(i) for i in xyz] python 3 only xyz = [i for i in input_list if div_by_five(i)] #cool ##print xyz #these were never in memory, would run out of memory with lists #lists take a lot of memory, generators might run out of time ##xyz = ( ( (i,ii) for ii in range(50000000))for i in range(5)) ##for i in xyz: ## for ii in i: ## print ii #python 3 this would work ##xyz = (print(i) for i in range(5)) ##for i in xyz: ## i
55ef5cc09c7bdabe692af9783837faf6f5cfbc31
paulan94/Intermediate-Python-Tutorials
/argparse_cli.py
900
3.765625
4
import argparse import sys def main(): parser = argparse.ArgumentParser() parser.add_argument('--x', type=float,default=1.0, help='What is the first number?') parser.add_argument('--y', type=float,default=1.0, help='What is the second number?') parser.add_argument('--operation', type=str,default='add', help='What operation? (add,sub,mul,div)') args = parser.parse_args() sys.stdout.write(str(calc(args))) #print works sometimes but stdout better def calc(args): if args.operation == 'add': return args.x+args.y elif args.operation == 'sub': return args.x-args.y elif args.operation == 'mul': return args.x*args.y elif args.operation == 'div': return args.x/args.y ##operation = calc(7,3,'div') ##print operation if __name__ == '__main__': main()
839de1b8a63762d56ab6c3d9f17a825bce6f410a
mucel/python-1
/eksperiment.py
749
3.625
4
saraksts = ['a'] vardnica = {'black': 'melns', 'white': 'balts'} vardnica['blue'] = 'zils' print(vardnica['black']) personaA = { 'vards' : 'Mara', 'dzimums':'s', 'gads': 2002 } personaB = { 'vards': 'Linda', 'dzimums': 's', 'gads': 1999 } cilveki = [personaA, personaB] while True: task = input("Please enter TODO task: ") status = input("Was the task complited yet? (yes/no)") print("Your task is: " + task) if status == "yes" todo_dict[task] = True else: todo_dict[task] = False new = input("Would you like to enter new task? (yes/no)") if new == "no" break print("All tasks: %s" % todo_dict) print("Emd") with open('piemers.html', '+w')as file print ()
8ce4fb9950dc61d3b59664aee815d5b0cb8dca3f
bkwong1990/PygamePrimerFishBomb
/score_helper.py
1,990
3.734375
4
import json ENEMY_SCORES = { "missile": 1000, "tank": 10000, "laser": 100000 } SCORE_PER_LIVING_TANK = 10 SCORE_COUNT = 5 NAME_CHAR_LIMIT = 10 score_file_name = "scores.json" # Defaults to an empty list scores = [] ''' Loads scores from a JSON file ''' def load_scores(): global scores try: with open(score_file_name, "r") as json_file: scores = json.load(json_file) print("Successfully read from " + score_file_name) except: print("Couldn't read " + score_file_name) ''' Saves scores to a JSON file ''' def save_scores(): try: with open(score_file_name, "w") as json_file: # use optional args to prettify the JSON text json.dump(scores, json_file, indent=2, separators=(", ", " : ")) print("Successfully wrote to " + score_file_name) except: print("Couldn't save " + score_file_name) ''' Checks if the given score is high enough to be added. Will be added anyways if there aren't enough scores. Parameters: new_score: the score to be tested ''' def is_score_high_enough(new_score): if len(scores) < SCORE_COUNT: return True else: lowest_score = min( [ entry["score"] for entry in scores ] ) if new_score > lowest_score: return True return False ''' Adds a new score and removes old scores if necessary Parameters: name: the name of the scorer score: the score ''' def add_score(name, new_score): global scores # Prevent overly long names from being used if len(name) > NAME_CHAR_LIMIT: name = name[:NAME_CHAR_LIMIT] scores.append({ "name": name, "score": new_score }) def sort_fun(entry): return entry["score"] #It'd be more efficient to insert, but there aren't many scores to work with. scores.sort(key = sort_fun,reverse = True) #If necessary, cut out the lowest score if len(scores) > SCORE_COUNT: scores = scores[0:SCORE_COUNT]
e2bed78a5631d38dfdbbffe383bb5f09cac17e9e
bkwong1990/PygamePrimerFishBomb
/my_events.py
1,090
3.5
4
import pygame ADDMISSILE = pygame.USEREVENT + 1 ADDCLOUD = pygame.USEREVENT + 2 ADDTANK = pygame.USEREVENT + 3 ADDLASER = pygame.USEREVENT + 4 MAKESOUND = pygame.USEREVENT + 5 ADDEXPLOSION = pygame.USEREVENT + 6 RELOADBOMB = pygame.USEREVENT + 7 SCOREBONUS = pygame.USEREVENT + 8 TANKDEATH = pygame.USEREVENT + 9 NEXTSESSION = pygame.USEREVENT + 10 ''' A function to simplify the process of posting an explosion event Parameters: rect: the rectangle needed to determine the explosion's size and position ''' def post_explosion(rect): explosion_event = pygame.event.Event(ADDEXPLOSION, rect = rect) pygame.event.post(explosion_event) ''' A function to simplify the process of posting a score bonus event Parameters: enemy_name: the name of the destroyed enemy, which is used to look up their score value center: the center of the text showing the score bonus ''' def post_score_bonus(enemy_name, center): score_bonus_event = pygame.event.Event(SCOREBONUS, enemy_name = enemy_name, center = center) pygame.event.post(score_bonus_event)
6070edc3bdc5fd7757edb7632903a78a56c12d06
flaviojussie/Exercicios_Python-Inciante-
/EstruturaDeDecisao - PythonBrasil/exec14.py
542
3.609375
4
def conceito(med): if med >= 9: idx = 0 elif med >= 7.5 and med < 9: idx = 1 elif med >= 6 and med < 7.5: idx = 2 elif med >= 4 and med < 6: idx = 3 else: idx = 4 con = ['A', 'B', 'C', 'D', 'E'] return con[idx] n1, n2 = int(input('Insira a nota 1: ')), int(input('Insira a nota 2: ')) media = (n1+n2)/2 conc = conceito(media) print('A media geral é: ', media) print('O conceito é ', conc) if conceito(media) in 'ABC': print('Aprovado') else: print('Reprovado')
b5a78563e656e4617132516dd50a6ca328f29c25
flaviojussie/Exercicios_Python-Inciante-
/EstruturaDeDecisao - PythonBrasil/exec16.py
709
3.796875
4
import math def calculaDelta(a, b, c): delt = math.pow(b, 2) - 4*a*c if delt >= 0: print('O valor de delta é:', delt) print(' X`:', calculaValorX1(delt, a, b)) print(' X``:', calculaValorX2(delt, a, b)) else: print('Não há raizes para a equação.') def calculaValorX1(delt, a, b): x1 = ((-1*b) + math.sqrt(delt))/(2*a) return x1 def calculaValorX2(delt, a, b): x2 = ((-1*b) - math.sqrt(delt))/(2*a) return x2 a = int(input('Indique um valor para a: ')) b = int(input('Indique um valor para b: ')) c = int(input('Indique um valor para c: ')) if a != 0: calculaDelta(a, b, c) else: print('Não é uma equação de segundo grau.')
525d2a568cba6cfa8a127e781f53e09b56cff1bb
flaviojussie/Exercicios_Python-Inciante-
/EstruturaDeRepeticao - PythonBrasil/exec36.py
206
3.9375
4
num = int(input('Digite um numero: ')) inicio = int(input('Digite o inicio: ')) fim = int(input('Digite o final: ')) for i in range(inicio,(fim+1)): res = num * i print('%d X %d = %d'%(num, i, res))
90a33d10723fa9f4cac04339dca95e9ebde4d0bb
flaviojussie/Exercicios_Python-Inciante-
/EstruturaDeRepeticao - PythonBrasil/exec41.py
512
3.71875
4
cont = 0 valorParcela = 0 parcela = 1 valorDivida = float(input('Insira o valor da divida: ')) print('\nValor da Dívida | Valor dos Juros | Quantidade de Parcelas | Valor da Parcela') for i in [0,10,15,20,25]: dividaTotal = valorDivida valorJuros = valorDivida*(i/100) dividaTotal += valorJuros valorParcela = dividaTotal/parcela print('R$ %5.2f %d %d R$ %5.2f'%(dividaTotal,valorJuros,cont, valorParcela)) cont += 3 parcela = cont
e742c028b56006a536127f23b6697000620b2923
flaviojussie/Exercicios_Python-Inciante-
/EstruturaDeRepeticao - PythonBrasil/exec22.py
325
3.984375
4
num = int(input('Digite um numero: ')) cont = 1 divisor = [] primo = 0 while cont <= num: if num % cont == 0: primo += 1 divisor.append(cont) cont += 1 if primo == 1: print(num, 'é primo, pois é divisivel apenas por', divisor) else: print(num, 'não é primo pois é divisivel por', divisor)
c1d8a5f4962f68ac43d139ab714655917c5c4068
flaviojussie/Exercicios_Python-Inciante-
/ExerciciosListas - PythonBrasil/exer05.py
361
3.734375
4
vetor = [] impares = [] pares = [] for i in range(20): vetor.append(int(input('Digite o %d número: '%(i+1)))) for i in vetor: if i % 2 == 0: pares.append(i) else: impares.append(i) print('O vetor é formado pelos numeros:',vetor) print('Os numeros pares do vetor são: ', pares) print('Os numeros impares do vetor são: ', impares)
588f92fcd4309b777bf0f75be9a4bd6e9b99f8c4
flaviojussie/Exercicios_Python-Inciante-
/EstruturaDeDecisao - PythonBrasil/exec05.py
272
3.828125
4
n1, n2 = int(input('Nota 1: ')), int(input('Nota 2: ')) media = (n1 + n2)/2 if media >= 7: print('Aluno nota,', media, 'Aprovado') elif media == 10: print('Aluno nota,', media ,'Aprovado com distinção') elif media < 7: print('Aluno Repovado, nota:', media)
2a3f669de150632c4a096455723c8a44d32dc43c
flaviojussie/Exercicios_Python-Inciante-
/EstruturaDeRepeticao - PythonBrasil/exec44.py
1,062
3.84375
4
sair = 's' print('''Complete seu voto. 1 - para votar em Fulano 2 - para votar em Cicrano 3 - para votar em Beltrano 4 - para votar em Zezinho 5 - para nulo 6 - para branco''') fulano = 0 cicrano = 0 beltrano = 0 zezinho = 0 nulo = 0 branco = 0 totalEleitores = 0 while sair == 's': voto = int(input('Digite seu voto: ')) sair = input('Deseja continuar votando (S/N): ') if voto == 1: fulano += 1 elif voto == 2: cicrano += 1 elif voto == 3: beltrano += 1 elif voto == 4: zezinho += 1 elif voto == 5: nulo += 1 elif voto == 6: branco += 1 totalEleitores += 1 perNulos = (nulo*100)/totalEleitores perBranco = (branco*100)/totalEleitores print('Fulano %d votos.'%fulano) print('Cicrano %d votos.'%cicrano) print('Beltrano %d votos'%beltrano) print('Zezinho %d votos'%zezinho) print('A soma dos votos nulos %d'%nulo) print('A soma dos votos em branco %d\n'%branco) print('O percentual de votos nulos é %5.1f'%perNulos) print('O percentual de votos brancos é %5.1f'%perBranco)
93a61b2e40b4d8f0662b8e856d50d4648ac20ee6
flaviojussie/Exercicios_Python-Inciante-
/EstruturaDeRepeticao - PythonBrasil/exec42.py
605
3.796875
4
numVezes = int(input('Quantos numeros você que inserir: ')) intervalo1 = 0 intervalo2 = 0 intervalo3 = 0 intervalo4 = 0 for i in range(numVezes): num = int(input('Digite o %d numero: '%(i+1))) if num >= 0 and num <= 25: intervalo1 += 1 elif num >=26 and num <= 50: intervalo2 += 1 elif num >= 51 and num <= 75: intervalo3 += 1 elif num >= 76 and num <= 100: intervalo4 += 1 print('\n%d no intervalo [0-25]'%intervalo1) print('%d no intervalo [26-50]'%intervalo2) print('%d no intervalo [51-75]'%intervalo3) print('%d no intervalo [76-100]'%intervalo4)
209f266a0c58dac79b4ad6cd2d585a798c4ce3f7
flaviojussie/Exercicios_Python-Inciante-
/EstruturaDeDecisao - PythonBrasil/exec19.py
850
3.515625
4
def grafiaExtensso(num, quant): c = 'centena' d = 'dezena' u = 'unidade' compl = '' if num == 0: return compl elif num == 1: if quant == 100: compl = ',' return str(num)+' '+ c + compl elif quant == 10: compl = ' e' return str(num)+' '+ d + compl else: return str(num)+' '+ u elif num >= 2: if quant == 100: compl = ',' return str(num)+' '+ c +'s' + compl elif quant == 10: compl = ' e' return str(num)+' '+ d +'s' + compl else: return str(num)+' '+ u +'s' num = int(input('Insira um numero menor que 1000: ')) cent = num//100 deze = (num%100)//10 unid = num%10 print(grafiaExtensso(cent,100), grafiaExtensso(deze,10), grafiaExtensso(unid,1))
2cc8395ee00da81c09d43db8800ecd08f1045542
flaviojussie/Exercicios_Python-Inciante-
/EstruturaDeRepeticao - PythonBrasil/exec26.py
706
3.78125
4
eleitores = int(input('Insira o numero de eleitores: ')) print('''\nPara votar em fulano - 1 Para votar em cicrano - 2 Para votar em beltrano - 3 Para votar em branco - 4\n''') cont = 0 fulano = 0 cicrano = 0 beltrano = 0 branco = 0 nulos = 0 candidatos = ['Fulano','Cicrano','Beltrano'] while cont < eleitores: voto = int(input('Digite seu voto: ')) if voto == 1: fulano += 1 elif voto == 2: cicrano += 1 elif voto == 3: beltrano += 1 elif voto == 4: branco += 1 else: nulos += 1 cont += 1 print('''\n\nRelação dos votos: FULANO - %d CICRANO - %d BELTRANO - %d BRANCO - %d NULOS - %d'''%(fulano, cicrano, beltrano, branco, nulos))
09ebe4d259f873fbc9a53fe8710e30081ec29d2e
SachinMCReddy/810homework
/HW02(SSW-810).py
3,147
3.71875
4
''' python program that includes class fractions , plus , minus, times, divide ,equal to perform tasks on calculator''' class Fraction: def __init__(self, numerator, denominator): self.numerator = numerator self.denominator = denominator if self.denominator <=0 : raise ValueError("This is not possible to divide by zero ") def __str__(self): # display fraction return str(self.numerator) + "/" + str(self.denominator) def plus(self, a): # For addition num = (self.numerator * a.denominator) + (self.denominator * a.numerator) den = (self.denominator * a.denominator) return Fraction(float(num), float(den)) def minus(self, a): # For subtraction num = (self.numerator * a.denominator) - (self.denominator * a.numerator) den = (self.denominator * a.denominator) return Fraction(float(num), float(den)) def times(self, a): # For multiplication num = (self.numerator * a.denominator) den = (self.denominator * a.denominator) return Fraction(float(num), float(den)) def divide(self, a): # For division num = (self.numerator * a.denominator) den = (self.denominator * a.denominator) return Fraction(float(num), float(den)) def equal(self, a): # For equal if (self.numerator * a.denominator) == (self.denominator * a.numerator): return True else: return False def get_number(prompt): #input passed while True: inpt = input(prompt) try: return float(inpt) except ValueError: print("Error: Please try again") def test(): #test function to demonstrate few functions f12 = Fraction(1, 2) f44 = Fraction(4, 4) f34 = Fraction(3, 4) f33 = Fraction(3, 3) print(f12, '+', f12, '=', f12.plus(f12), '[4/4]') print(f44, '-', f12, '=', f44.minus(f12), '[4/8]') print(f12, '*', f34, '=', f12.times(f34), '[4/8]') print(f34, '/', f12, '=', f34.divide(f12), '[6/8]') print(f33, '=', f33, f33.equal(f33), '[TRUE]') def main(): print("welcome to the fraction calculator") nm1 = get_number("Fraction one numerator") dn1 = get_number("Fraction one denominator") operation = ["+", "-", "*", "/", "="] opp = input("operation (+, -, *, /, =)") if opp not in operation: print("invalid operator") return nm2 = get_number("Fraction two numerator") dn2 = get_number("Fraction two denominator") f1 = Fraction(nm1, dn1) f2 = Fraction(nm2, dn2) #checking if the user input is the same as functions in the list printed[+, -, *, /] if opp == "+": print(f1, "+", f2, "=", f1.plus(f2)) elif opp == "-": print(f1, "-", f2, "=", f1.minus(f2)) elif opp == "*": print(f1, "*", f2, "=", f1.times(f2)) elif opp == "/": print(f1, "/", f2, "=", f1.divide(f2)) elif opp == "=": print(f1, "=", f2, f1.equal(f2)) if __name__ == "__main__": test() main()
e8e71c47bd34a628562c9dfcd351bcd336a99d70
endar-firmansyah/belajar_python
/oddevennumber.py
334
4.375
4
# Python program to check if the input number is odd or even. # A number is even if division by given 2 gives a remainder of 0. # If the remainder is 1, it is an odd number # div = 79 div = int(input("Input a number: ")) if (div % 2) == 0: print("{0} is even Number".format(div)) else: print("{0} is Odd Number".format(div))
b928d3b1b8bfac3efa68e1bccaa9347c16482bd8
JianHui1208/Code_File
/Python/Lists.py
291
4.15625
4
thislist = ["a", "b","c"] print(thislist) thislist = ["a", "b", "c"] print(thislist[1]) # same the array start for 0 thislist = ["a", "b", "c"] print(thislist[-1]) # -1 is same like the last itme # -2 is second last itme thislist = ["a", "b", "c", "d", "e", "f", "g"] print(thislist[2:5])
48de21f792a50fa63d62e5656c123a20a551acd1
acado1986/cs50
/pset6_2016/crack.py
2,617
3.96875
4
import crypt import argparse import itertools import time def main(): # running time mesurements start_time = time.time() # path to default dictionary in Ubuntu distros default_dictionary = '/usr/share/dict/american-english' # ensure correct usage of the program parser= argparse.ArgumentParser() parser.add_argument("dictionary", default=default_dictionary, nargs="?", help="path to different dictionary, else default") parser.add_argument("chiphertext",help="encrypted text to decipher") args = parser.parse_args() # store supplied dictionary or default dictionary = args.dictionary # store encrypted text encrypted_text= args.chiphertext # decrypt using a dictionary def decryptDictionary(encrypted_text, dictionary): ''' The function reads dictionary in a text format, arranged one word by line, encrypts the word and compares it to the encrypted text''' salt = encrypted_text[:2] with open(dictionary, 'r') as dictionary: for word in dictionary: # pset6 specificacion only password only 4 letters long if len(word) < 5: if encrypted_text == crypt.crypt(word.rstrip('\n'), salt): return word.rstrip('\n') else: return None # decrypt using brute force def decryptBruteForce(encrypted_text, wordLength): ''' The function generates a permutation of letters to form words, of wordLength length, encrypts the word and compares it to the encrypted text''' salt = encrypted_text[:2] chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' for word in (itertools.product(chars, repeat=wordLength)): if encrypted_text == crypt.crypt(''.join(word), salt): return ''.join(word) else: return None # find the password first in dictionary, if unsuccesfull use brute force dict_passwd = decryptDictionary(encrypted_text, dictionary) if dict_passwd == None: # password max lenght only 4 letters for i in range(5): brute_passwd = decryptBruteForce(encrypted_text, i) if brute_passwd is not None: break print('{}'.format(dict_passwd if dict_passwd is not None else brute_passwd)) # print running time end_time = time.time() print("--- %s seconds ---" % (end_time - start_time)) if __name__ == '__main__': main()
0ce3f5ef67b779ef85eade0c4457a38a50dc9c44
wecchi/univesp_com110
/Sem2-Strings.py
404
3.921875
4
# Videoaula 7 - Strings nome = input('Digite o seu nome completo: ') nome2 = input('Qual o nome da sua mãe? ') nome = nome.strip() nome2 = nome2.strip() print('é Marcelo? ', 'Marcelo' in nome) print('Seu nome e de sua mãe são diferentes? ', nome != nome2) print('Seu nome vem depois da sua mãe? ', nome > nome2) print('Quantidade de letras do seu nome: ', len(nome)) print(nome.upper())
5d175c14c2438c669efe9fd451e0c88ace14ce7b
wecchi/univesp_com110
/contar_letras.py
288
3.890625
4
def countLetter(textAsCount, l): x = textAsCount.count(l) return x frase = input('digite uma frase qualquer ') letra = input('que letra deseja contar? ') print('\n','''Encontramos %d letras "%s"s no seu texto "%s"'''%(countLetter(frase, letra), letra, frase[:8] + '...'))
7a539c585cf9adca8dc788fea5295f99a65b5e92
wecchi/univesp_com110
/Sem2-Texto22.py
1,217
4.15625
4
''' Texto de apoio - Python3 – Conceitos e aplicações – uma abordagem didática (Ler: seções 2.3, 2.4 e 4.1) | Sérgio Luiz Banin Problema Prático 2.2 Traduza os comandos a seguir para expressões Booleanas em Python e avalie-as: (a)A soma de 2 e 2 é menor que 4. (b)O valor de 7 // 3 é igual a 1 + 1. (c)A soma de 3 ao quadrado e 4 ao quadrado é igual a 25. (d)A soma de 2, 4 e 6 é maior que 12. (e)1387 é divisível por 19. (f)31 é par. (Dica: o que o resto lhe diz quando você divide por 2?) (g)O preço mais baixo dentre R$ 34,99, R$ 29,95 e R$ 31,50 é menor que R$ 30,00.* ''' a = (2 + 2) < 4 b = (7 // 3) == (1 + 1) c = (3 ** 2 + 4 ** 2) == 25 d = (2 + 4 + 6 ) > 12 e = 1387 % 19 == 0 f = 31 % 2 == 0 g = min(34.99, 29.95, 31,50) < 30 print('(a)A soma de 2 e 2 é menor que 4.', a) print('(b)O valor de 7 // 3 é igual a 1 + 1.', b) print('(c)A soma de 3 ao quadrado e 4 ao quadrado é igual a 25.', c) print('(d)A soma de 2, 4 e 6 é maior que 12.', d) print('(e)1387 é divisível por 19.', e) print('(f)31 é par. (Dica: o que o resto lhe diz quando você divide por 2?)', f) print('(g)O preço mais baixo dentre R$ 34,99, R$ 29,95 e R$ 31,50 é menor que R$ 30,00.', g)
2681542783b3751bd885d3f5d829d6bf2ccde4be
code-wiki/Data-Structure
/Array/(Manacher's Algoritm)Longest Palindromic Substring.py
1,046
4.125
4
# Hi, here's your problem today. This problem was asked by Twitter: # A palindrome is a sequence of characters that reads the same backwards and forwards. # Given a string, s, find the longest palindromic substring in s. # Example: # Input: "banana" # Output: "anana" # Input: "million" # Output: "illi" # class Solution: # def longestPalindrome(self, s): # # Fill this in. # # Test program # s = "tracecars" # print(str(Solution().longestPalindrome(s))) # # racecar class Solution: def checkPalindrome(str): # reversing a string in python to get the reversed string # This is extended slice syntax. # It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, # it reverses a string. reversedString = str[::-1] if (str == reversedString): return true else: return false def longestPalindrome(str): while (index > str.length): while (): pass
e466c0aab2dbbe4e0a661609f0f7421ab23dc967
xpessoles/Cycle_01_DecouverteSII
/Chaine_Fonctionnelle/02_Fonction_Traiter/TP_Traiter_Pyhon_Arduino/Librairie py2duino v4/py2duino.py
22,737
3.53125
4
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: py2duino # Purpose: Programming arduino from python commands # # Author: David Violeau, Alain Caignot # # Created: 01/01/2014 # Modified : 01/03/2016 D. Violeau # Copyright: (c) Demosciences UPSTI # Licence: GPL #------------------------------------------------------------------------------- import serial import sys import time import struct import traceback class Servo(): """ Classe Servo pour piloter un ou deux servomoteurs Les servomoteurs doivent etre definis sur les broches 9 et 10 obligatoirement. Il suffit ensuite de definir les numeros des servomoteurs 1 ou 2 servo=Servo(monarduino,1) # avec monarduino la carte definie Pour demander au servomoteur de tourner de x degre (de 0 à 180), taper servo.write(x) """ def __init__(self,parent,number): self.number=number self.parent=parent if number!=1 and number!=2: print("Les servomoteurs doivent etre branches sur les pin digitaux 9 ou 10, taper Servo(monarduino,1 ou 2)") self.parent.close() else: self.attach() print("attach ok") def attach(self): mess="Sa"+str(self.number) self.parent.ser.write(bytes(mess,"ascii")) def dettach(self): mess="Sd"+str(self.number) self.parent.ser.write(bytes(mess,"ascii")) print("detach ok") def write(self,value): if value<0 : value=0 elif value>180: value=180 mess="Sw"+str(self.number)+chr(value) self.parent.ser.write(bytes(mess,"ISO-8859-1")) class PulseIn(): """ Classe PulseIn pour connaitre le temps écoulé entre l'émission et la réception d'un signal de durée donnée Vous devez spécifier la carte arduino et le pin digital du trigger (émetteur) puis du pin digital récepteur (echo) pulse=DigitalOutput(macarte,6,5) (pin trigger 6, pin echo 5) Pour lancer une lecture, taper puilse.read(duree) où duree est la durée en milliseconde entre le passage à l'état haut puis bas du trigger. La grandeur renvoyée est en microsecondes. Si aucune duree n'est renseignée, une valeur de 20 ms est adoptée par défaut. La durée maximale est de 255 ms. """ def __init__(self,parent,pin_trigger,pin_echo): self.trigger=pin_trigger self.echo=pin_echo self.parent=parent self.init() self.duree=20 def init(self): self.parent.pinMode(self.trigger,"OUTPUT") self.parent.pinMode(self.echo,"INPUT") def read(self,duree=20): if duree>255: duree=20 if duree <=0: duree=20 self.duree=duree val=self.parent.pulseIn(self.duree,self.trigger,self.echo) return val class DigitalOutput(): """ Classe DigitalOutput pour mettre à l'état haut ou bas une sortie digitale Vous devez spécifier la carte arduino et le pin digital de sortie souhaité led=DigitalOutput(macarte,9) Pour mettre à l'état haut taper : led.high(), pour l'état bas : led.low() """ def __init__(self,parent,pin): self.pin=pin self.parent=parent self.init() def init(self): self.parent.pinMode(self.pin,"OUTPUT") def high(self): self.parent.digitalWrite(self.pin,1) def low(self): self.parent.digitalWrite(self.pin,0) class DigitalInput(): """ Classe DigitalInput pour lire la donnée binaire d'un pin digital Vous devez spécifier la carte arduino et le pin digital d'entré souhaité push=DigitalInput(macarte,9) Pour lire la valeur, tapez : push.read(). La valeur obtenue est 0 ou 1 (état haut) La fonction push.upfront() (ou downfront) permet de renvoyer 1 ou 0 sur front montant ou descendant de l'entrée La fonction push.pulse() renvoie la durée (en microsecondes) écoulée entre deux passages au niveau haut de l'entrée """ def __init__(self,parent,pin): self.pin=pin self.parent=parent self.previous_value=0 self.value=0 self.duree=0 self.init() def init(self): self.parent.pinMode(self.pin,"INPUT") self.value=self.parent.digitalRead(self.pin) self.previous_value=self.value def read(self): return self.parent.digitalRead(self.pin) def upfront(self): self.value=self.parent.digitalRead(self.pin) val=0 if ((self.value!=self.previous_value) & (self.value==1)): val=1 else : val=0 self.previous_value=self.value return val def downfront(self): self.value=self.parent.digitalRead(self.pin) val=0 if ((self.value!=self.previous_value) & (self.value==0)): val=1 else : val=0 self.previous_value=self.value return val def pulse(self): print("pulse In ") self.duree=self.parent.pulseIn(self.pin) return self.duree class AnalogInput(): """ Classe AnalogInput pour lire les données issues d'une voie analogique Vous devez spécifier la carte arduino et le pin analogique d'entrée souhaitée analog=AnalogInput(macarte,0) Pour lire la valeur analogique : analog.read(). La valeur renvoyée est comprise entre 0 et 1023 """ def __init__(self,parent,pin): self.pin=pin self.parent=parent self.value=0 def read(self): self.value=self.parent.analogRead(self.pin) return self.value class AnalogOutput(): """ Classe AnalogOutput pour envoyer une grandeur analogique variant de 0 à 5 V ce qui correspond de 0 à 255 \n Vous devez spécifier la carte arduino et le pin Analogique (pwm ~) de sortie souhaité led=AnalogOutput(macarte,9) Utiliser la commande led.write(200) """ def __init__(self,parent,pin): self.pin=pin self.parent=parent self.value=0 def write(self,val): if val>255 : val=255 elif val<0: val=0 self.parent.analogWrite(self.pin,val) class DCmotor(): """ Classe DCmotor pour le pilotage des moteurs a courant continu Les parametres de definition d'une instance de la classe sont :\n - la carte arduino selectionnee\n - le numero du moteur de 1 a 4\n - le pin du PWM1\n - le pin de sens ou de PWM2\n - le type de pilotage : 0 (type L293 avce 2 PWM) ou 1 (type L298 avec un PWM et une direction)\n Ex : monmoteur=DCmotor(arduino1,1,3,5,0) (moteur 1 pilotage de type L293 avec les PWM des pins 3 et 5\n Pour faire tourner le moteur a une vitesse donne, taper : monmoteur.write(x) avec x compris entre -255 et 255) """ def __init__(self,parent,number,pin_pwm,pin_dir,mode): self.pin1=pin_pwm self.pin2=pin_dir self.mode=mode self.number=number self.parent=parent if mode!=0 and mode!=1: print("Choisir un mode egal a 0 pour un pilotage par 2 PWM ou 1 pour un pilotage par un PWM et un pin de sens") elif number!=1 and number!=2 and number!=3 and number!=4: print("Choisir un numero de moteur de 1 a 4") else : try: mess="C"+str(self.number)+chr(48+self.pin1)+chr(48+self.pin2)+str(self.mode) self.parent.ser.write(bytes(mess,"ISO-8859-1")) tic=time.time() toread=self.parent.ser.inWaiting() value="" while(toread < 2 and time.time()-tic < 1): # attente retour Arduino toread=self.parent.ser.inWaiting(); value=self.parent.ser.read(toread); if value==b"OK": print("Moteur "+str(self.number)+" correctement connecté") else: print("Problème de déclaration et connection au moteur") self.parent.close() return except: print("Problème de déclaration et connection au moteur") self.parent.close() def write(self,value): value=int(value) if value<-255: value=-255 elif value>255: value=255 if value<0: direction=0 else: direction=1 mess="M"+str(self.number)+chr(48+direction)+chr(abs(round(value))) self.parent.ser.write(bytes(mess,"ISO-8859-1")) class Stepper(): """ Classe Stepper pour le pilotage d'un moteur pas à pas accouplé à un driver nécessitant la donnée d'une direction et d'un signal pulsé Les parametres de definition d'une instance de la classe sont :\n - la carte arduino selectionnee\n - un numero de 1 à 4 pour activer de 1 à 4 moteurs pas à pas\n - le numéro du pin donnant le signal pulsé (STEP)\n - le numéro du pin donnant la direction (DIR)\n Ex : monstepper=Stepper(arduino1,1,10,11) (moteur 1 sur les pins STEP 10, DIR 11 Pour faire tourner le moteur d'un nombre de pas donné, taper : monmoteur.move(nb_steps, dt) avec nb_steps le nombre de pas ou demi-pas (ou autre en fonction du mode) qui peut etre positif ou négatif (ce qui définit le sens de déplacement), dt le temps laissé entre chaque pas en millisecondes (de 0.05 à 15). Attention, le choix du pas de temps est fonction de la dynamique souhaitée et donc du réglage de l'intensité de consigne sur le driver du moteur. Il est peut etre nécessaire de définir des sorties digitales ENABLE, pour autoriser ou non le moteur pas à pas à bouger et des sorties digitales MS1, MS2, MS3 pour définir le mode de pas à pas (pas complet, demi-pas, ou autre...) """ def __init__(self,parent,number,pin_pwm,pin_dir): self.pin_pwm=pin_pwm self.pin_dir=pin_dir self.parent=parent self.number=number self.nb_steps=0 self.dt=0 self.launched=0 self.tic=0 try: mess="Pa"+chr(48+self.number)+chr(48+self.pin_pwm)+chr(48+self.pin_dir) print(mess) self.parent.ser.write(bytes(mess,"ISO-8859-1")) tic=time.time() toread=self.parent.ser.inWaiting() value="" while(toread < 2 and time.time()-tic < 1): # attente retour Arduino toread=self.parent.ser.inWaiting(); value=self.parent.ser.read(toread); if value==b"OK": print("Moteur pas a pas correctement connecté") else: print("Problème de déclaration et connection au moteur pas a pas") self.parent.close() return except: print("Problème de déclaration et connection au moteur pas a pas") self.parent.close() def move(self,nb_steps,dt): self.dt=dt dt=dt/2 self.nb_steps=nb_steps if dt>15: dt=15 if dt<0.05: dt=0.05 dt=int(dt*1000) value=int(nb_steps) if value >=0: direction=1 else: direction=0 value=abs(value) if value>=2**32: value=2**32-1 messb=bytes("Pm"+chr(48+self.number)+chr(48+direction),"ISO-8859-1")+struct.pack('L',value)+struct.pack('i',dt) self.parent.ser.write(messb) tic=time.time() toread=self.parent.ser.inWaiting() value="" while(toread < 2 and time.time()-tic < 1): # attente retour Arduino toread=self.parent.ser.inWaiting() value=self.parent.ser.read(toread) if value!=b'OK': self.stop() self.launched=1 self.tic=time.time() def stop(self): mess="Ps"+chr(48+self.number) self.parent.ser.write(bytes(mess,"ISO-8859-1")) self.launched=0 def isMoving(self): mess="Pi"+chr(48+self.number) self.parent.ser.write(bytes(mess,"ISO-8859-1")) tic=time.time() toread=self.parent.ser.inWaiting() value="" while(toread < 1 and time.time()-tic < 1): # attente retour Arduino toread=self.parent.ser.inWaiting() value=self.parent.ser.read(toread) if value!=b'1' and value!=b'0': return 0 else: return int(value) def isMoving2(self): #print(time.time()-self.tic) if time.time()-self.tic>abs(self.nb_steps*self.dt/1000)+0.01: self.launched=0 return self.launched class Encoder(): """ Classe Encoder pour la lecture d'interruption sur des encodeurs 2 voies Les parametres de definition d'une instance de la classe sont :\n - la carte arduino selectionnee\n - le pin de l'entrée digitale de la voie A (avec interruption)\n - le pin de l'entrée digitale de la voie B (avec ou sans interruption)\n - le type de lecture : 1 pour front montant de la voie A (et sens donné par la voie B), 2 pour fronts montants et descendants de la voie A seule, 4 pour fronts montants et descendants des deux voies codeur=Encoder(macarte,2,3,1) pour lire le nombre de tops, taper codeur.read(). La valeur obtenue peut etre positive ou négative (codée sur 4 octets) Pour remettre à 0 la valeur lue, codeur.reset() """ def __init__(self,parent,pinA,pinB,mode): self.parent=parent self.pinA=pinA self.pinB=pinB self.mode=mode self.corresp=[-1,-1,0,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,4,3,2] try: if self.corresp[self.pinA]==-1 or self.corresp[self.pinB]==-1: print("Les pins utilisés pour l'encodeur doivent accepter les interruptions. Choisir les pins 2,3 (UNO, MEGA) ou 18 à 21 (MEGA)") self.parent.close() except: print("Les pins utilisés pour l'encodeur doivent accepter les interruptions. Choisir les pins 2,3 (UNO, MEGA) ou 18 à 21 (MEGA)") self.parent.close() if mode!=1 and mode!=2 and mode !=4: print(["Choisir un mode pour le codeur egal a : ", "1 : front montant de la voie A, ", "2 : front montant et descendants de la voie A,", "4 : fronts montants et descendants des voies A et B"]) self.parent.close() else : if mode==4: mess="Ea"+chr(self.corresp[self.pinA])+chr(self.corresp[self.pinB])+str(mode) else: mess="Ea"+chr(self.corresp[self.pinA])+chr(self.pinB)+str(mode) self.parent.ser.write(bytes(mess,"ISO-8859-1")) def reset(self): mess="Ez"+chr(self.corresp[self.pinA]) self.parent.ser.write(bytes(mess,"ISO-8859-1")) def read(self): mess="Ep"+chr(self.corresp[self.pinA]) self.parent.ser.write(bytes(mess,"ISO-8859-1")) toread=self.parent.ser.inWaiting() tic=time.time() while(toread < 4 and time.time()-tic < 1): # attente retour Arduino toread=self.parent.ser.inWaiting(); value=self.parent.ser.read(toread); value=struct.unpack('l',value) return value[0] class Arduino(): """ Classe Arduino pour definition d'une carte arduino. Ne fonctionne qu'en python 3.X Il faut charger le programme toolbox_arduino_vX.ino dans la carte Arduino pour pouvoir utiliser cette classe. Les parametres de definition d'une instance de la classe sont :\n - le port de communication (numero sous Windows, chemin sous linux /dev/xxx )\n Le taux de transfert peut être passé en argument mais il faut modifier celui du fichier ino pour qu'il corresponde. Par défaut il est à 115200 La connection à la carte est faite automatiquement à la déclaration\n Taper macarte=Arduino(8) pour se connecter automatiquement à la carte sur le port 8\n Taper macarte.close() pour fermer la connexion\n Il faudra alors toujours passer en argument l'objet macarte pour toute déclaration de pins arduino (DigitalOutput, DigitalInput, DCmotor, Stepper, Servo, AnalogInput, AnalogOutput, Encoder) """ def __init__(self,com,baudrate=115200): self.ser = serial.Serial() self.com=com #define com port self.baudrate=baudrate #define com debit self.digitalPins=[] #list of defined digital pins self.analogPins=[] #list of defined analog pins self.interrupts=[] #list of defined interrupt self.steppers=[] #list of defined pins for stepper self.connect() def ask(self): mess="B" self.ser.write(bytes(mess,"ISO-8859-1")) toread=self.ser.inWaiting(); #tic=time.time() #while(toread < 2 and time.time()-tic < 2): # attente retour Arduino # toread=self.ser.inWaiting(); value=0 if toread!=0: value=self.ser.read(toread) print(value) def connect(self): self.ser.baudrate=self.baudrate #definition du debit import os if os.name == "posix": self.ser.port=self.com else: if int(serial.VERSION.split('.')[0])>=3: self.ser.port="COM"+str(self.com) else: self.ser.port=self.com-1 connect = 0 try: self.ser.open(); #open port4 time.sleep(2); #wait for stabilisation self.ser.write(b"R3"); #send R3 to ask for arduino program tic = time.time(); toread=self.ser.inWaiting(); while(toread < 2 and time.time()-tic < 2): # attente retour Arduino toread=self.ser.inWaiting(); value=self.ser.read(toread) if value == b"v4": print("Connexion ok avec l'arduino") connect=1 finally: if connect==0: print("Connexion impossible avec l'arduino. Verifier que le com est le bon et que le programme toolbox_arduino_v4.ino est bien chargé dans l'arduino") return 0 else: return 1 def close(self): self.ser.close() def pinMode(self,pin,type): mode='x' if type=='OUTPUT': mode='1' elif type=='INPUT': mode='0' else: print("Attention le type OUTPUT ou INPUT du pin n'est pas bien renseigne") if mode != 'x': mess="Da"+chr(pin+48)+mode #self.ser.write(bytes(mess,"ascii")) self.ser.write(bytes(mess,"ISO-8859-1")) self.digitalPins.append(pin) def digitalwrite(self,pin,value): self.digitalWrite(self,pin,value) def digitalWrite(self,pin,value): try: self.digitalPins.index(pin) data='x' if value=="HIGH": data='1' elif value=="LOW": data='0' elif value==1 or value==0: data=str(value) else: print("Valeur incorrecte pour un pin digital") if data !='x': mess="Dw"+chr(pin+48)+data #self.ser.write(bytes(mess,"ascii")) self.ser.write(bytes(mess,"ISO-8859-1")) except: print("Erreur de transmission ou bien le pin digital n'a pas ete bien assigne au prealable avec arduino.pinMode") self.close() traceback.print_exc(file=sys.stdout) def analogwrite(self,pin,value): self.analogWrite(self,pin,value) def analogWrite(self,pin,value): try: if abs(value)>255: code_sent="W"+chr(pin+48)+chr(255); else: code_sent="W"+chr(pin+48)+chr(abs(round(value))) self.ser.write(bytes(code_sent,"ISO-8859-1")) except: print("Erreur de transmission") self.close() #traceback.print_exc(file=sys.stdout) def digitalread(self,pin): return self.digitalRead(self,pin) def digitalRead(self,pin): try: self.digitalPins.index(pin) mess="Dr"+chr(pin+48) #self.ser.write(bytes(mess,"ascii")) self.ser.write(bytes(mess,"ISO-8859-1")) tic=time.time() toread=self.ser.inWaiting(); while(toread < 1 and time.time()-tic < 1): # attente retour Arduino toread=self.ser.inWaiting(); value=self.ser.read(toread) return int(value) except: print("Erreur de transmission ou bien le pin digital n'a pas ete bien assigne au prealable avec arduino.pinMode") self.close() #traceback.print_exc(file=sys.stdout) def pulseIn(self,duree,trigger,echo): try: self.digitalPins.index(trigger) self.digitalPins.index(echo) mess="Dp"+chr(trigger+48)+chr(echo+48)+chr(abs(round(duree))) #self.ser.write(bytes(mess,"ascii")) self.ser.write(bytes(mess,"ISO-8859-1")) toread=self.ser.inWaiting() tic=time.time() while(toread < 4 and time.time()-tic < 1): # attente retour Arduino toread=self.ser.inWaiting() value=self.ser.read(toread) value=struct.unpack('l',value) return value[0] except: print("Erreur de transmission") self.close() #traceback.print_exc(file=sys.stdout) def analogread(self,pin): return self.analogRead(self,pin) def analogRead(self,pin): try: mess="A"+chr(pin+48) #self.ser.write(bytes(mess,"ascii")) self.ser.write(bytes(mess,"ISO-8859-1")) toread=self.ser.inWaiting() tic=time.time() while(toread < 2 and time.time()-tic < 1): # attente retour Arduino toread=self.ser.inWaiting(); value=self.ser.read(toread); value=struct.unpack('h',value) return value[0] except: print("Erreur de transmission") self.close() #traceback.print_exc(file=sys.stdout) def Servo(self,pin): return Servo(self,pin)
09c24a1dce6f40409993005a582dafc018ce3d3e
adykumar/Leeter
/python/206_reverse-linked-list.py
1,281
3.890625
4
""" Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL """ class Node(object): def __init__(self, x): self.val= x self.next= None class Solution(object): def createLL(self, lis): if len(lis)<1: return None head= Node(lis[0]) p= head for each in lis[1:]: temp= Node(each) p.next= temp p= p.next return head def printLL(self, head): while head!= None: print head.val, head= head.next print def reverseLL(self, head): if head==None or head.next==None: return head left= head right= head.next while right.next!= None: temp= right right= right.next temp.next= left left= temp right.next= left head.next= None return right if __name__=="__main__": testcases= [ [1,2,3,4], [1], [], [2,1,34,7] ] obj= Solution() for test in testcases: print "-----------\n",test print "Orig LL => ", orig= obj.createLL(test) obj.printLL(orig) print "Reversed => ", rev= obj.reverseLL(orig) obj.printLL(rev)
f503e91072d0dd6c7402e8ae662b6139feed05e0
adykumar/Leeter
/python/104_maximum-depth-of-binary-tree.py
1,449
4.125
4
""" WORKING.... Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3. """ import Queue as queue class TreeNode(object): def __init__(self,x): self.val= x self.left= None self.right= None class Solution(object): def createTree(self, treelist): root= TreeNode(treelist[0]) q= queue.Queue(maxsize= len(treelist)) q.put(root) i = 1 while True: if i>= len(treelist): break node= q.get() if treelist[i] != "null": node.left= TreeNode(treelist[i]) q.put(node.left) i+=1 if i>= len(treelist): break if treelist[i] != "null": node.right= TreeNode(treelist[i]) q.put(node.right) i+=1 return root def maxDepth(self, root): if root==None: return 0 return max( self.maxDepth(root.left)+1, self.maxDepth(root.right)+1 ) if __name__=="__main__": testcases= [[3,9,20,"null","null",15,7, 1, 1, 3], [1], [1,"null", 3]] obj= Solution() for test in testcases: root= obj.createTree(test) print test, " -> ", obj.maxDepth(root)
c5765011e3f9b07eae3a52995d20b45d0f462229
adykumar/Leeter
/python/429_n-ary-tree-level-order-traversal.py
1,083
4.1875
4
""" Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example, given a 3-ary tree: 1 / | \ 3 2 4 / \ 5 6 We should return its level order traversal: [ [1], [3,2,4], [5,6] ] Note: The depth of the tree is at most 1000. The total number of nodes is at most 5000. """ class Node(object): def __init__(self, val, children): self.val = val self.children = children #list of nodes class Solution(object): def helper(self, root, res, level): if root==None: return if len(res)<= level+1 and len(root.children)>0: res.append([]) for eachNode in root.children: res[level+1].append(eachNode.val) self.helper(eachNode, res, level+1) def levelOrder(self, root): """ :type root: Node :rtype: List[List[int]] """ if root==None: return [] res= [[root.val]] self.helper(root, res, 0) return res
abccc32f0d420aa7189c76bbdf0a67c63435a58a
adykumar/Leeter
/python/564_LC_find-the-closest-palindrome_bruteforce.py
1,260
4.03125
4
""" Given an integer n, find the closest integer (not including itself), which is a palindrome. The 'closest' is defined as absolute difference minimized between two integers. Example 1: Input: "123" Output: "121" Note: The input n is a positive integer represented by string, whose length will not exceed 18. If there is a tie, return the smaller one as answer. """ """ Solution time complexity: conversion and palin check O(l)...l is length of n range of checks - O(10^(l/2)) So overall- O(10^l/2) """ class Solution(object): def isPalin(self,num): """ :type num: int :rtype: bool """ n= str(num) l= len(n) for i in range(l/2): if n[i]!=n[l-1-i]: return False return True def nearestPalindromic(self, n): """ :type n: str :rtype: str """ num= int(n) i = 1 while True: if self.isPalin(num-i): return str(num-i) if self.isPalin(num+i): return str(num+i) i=i+1 if __name__=="__main__": obj= Solution() samples= ["123","123678", "123456789", "4110099"] for sample in samples: print sample, "->", obj.nearestPalindromic(sample)
165690d692300da3fc40600251f7812b70db5c15
adykumar/Leeter
/python/136_single-number.py
743
4
4
""" Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4 """ class Solution(object): def findSingle(self, nums): """ params- list(int) return- int """ if len(nums)< 3: return res= nums[0] for i in range(1, len(nums)): res^= nums[i] return res if __name__=="__main__": testcases= [[2,2,1], [4,1,2,1,2], [4,4,1,2,1,2,-4]] obj= Solution() for test in testcases: print test, " -> ", obj.findSingle(test)
d4836b75dadfb3625e1dd8f47297f4ef06997442
DingJunyao/my-first-algorithm-book-py
/0/full_sort.py
990
3.5625
4
""" 全排列算法(0-1,P4) 随机生成不重复的数列,当数列内数字排序正确再输出。 一个非常低效的算法。 """ from random import randint from time import time def gen_arr(n): arr = [] for _ in range(n): while True: random_int = randint(1, 1000000) if random_int not in arr: break arr.append(random_int) return arr def check_arr(arr): for i in range(len(arr)-1): if arr[i] <= arr[i+1]: continue else: return False return True def full_sort(n): arr_list = [] while True: arr = gen_arr(n) if arr not in arr_list: arr_list.append(arr.copy) else: continue if check_arr(arr): return arr n = int(input('Please input the length of the array: ')) start_time = time() arr = full_sort(n) end_time = time() print(arr) print('Elapse time: %s s' % (end_time - start_time))
f278ab03d685a821f876189a3034524ce4685d99
Leszeg/MES
/MES/Node.py
806
3.875
4
class Node: """ Class represents the node in the global coordinate system: Attributes: ---------- x : float x coordinate. y : float y coordinate t0 : float Node temperature bc : float Flag needed to check if there is a boundary condition """ def __init__(self, X: float, Y: float, T0: float, BC: int): """ Constructs all the necessary attributes for the Node object Parameters ---------- X : float x coordinate Y : float y coordinate T0 : float Node temperature BC : bool Flag needed to check if there is a boundary condition """ self.x = X self.y = Y self.t0 = T0 self.bc = BC
b0d28d98ea61e10c4ec318aa8184d0dab66c5978
StevenAston/project-euler-python
/euler-006.py
451
3.71875
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 9 03:41:36 2017 @author: Steven """ import timeit start = timeit.default_timer() def sum_of_squares(n): sum = 0 for i in range(1, n+1): sum += i**2 return sum def square_of_sum(n): sum = 0 for i in range(1, n+1): sum += i return sum**2 def difference(n): return (square_of_sum(n) - sum_of_squares(n)) print (difference(100)) stop = timeit.default_timer() print (stop - start,"seconds")
3b790c60659d28ef6b1c29d24400266ff2266a49
Chimer2017/nba_stats_scraper_db_storage
/nba_ss_db/db/store.py
6,153
3.5
4
""" Handles the creation of tables and storage into tables. """ from typing import List from .. import db, CONFIG from ..scrape.utils import is_proper_date_format, format_date PROTECTED_COL_NAMES = {'TO'} DATE_QUERY_PARAMS = {'GAME_DATE', 'DATE_TO'} def store_nba_response(data_name: str, nba_response, primary_keys=(), ignore_keys=set()): """ Stores a single nba_response, creating a table if necessary with the given data_name and primary keys. """ store_nba_responses(data_name, [nba_response], primary_keys, ignore_keys) def store_nba_responses(data_name: str, l_nba_response: List, primary_keys=(), ignore_keys=set()): """ Stores a given list of nba responses, creating a table if necessary with the given data_name and primary keys. """ if len(l_nba_response) == 0: raise ValueError('List of nba responses was empty.') response_columns = l_nba_response[0].headers desired_column_headers = filter_column_headers(response_columns, ignore_keys) extracted_rows = extract_used_columns(l_nba_response, desired_column_headers) format_date_columns(desired_column_headers, extracted_rows) renamed_column_headers = map_protected_col_names(desired_column_headers) if db.retrieve.exists_table(data_name): add_rows_to_table(data_name, renamed_column_headers, extracted_rows) else: create_table_with_data(data_name, renamed_column_headers, extracted_rows, primary_keys) def filter_column_headers(column_names, ignore_keys): combined_ignore_keys = ignore_keys | set(CONFIG['GLOBAL_IGNORE_KEYS']) desired_column_headers = [ header for header in column_names if header not in combined_ignore_keys ] return desired_column_headers def extract_used_columns(nba_responses, desired_column_headers): filtered_rows = [] for nba_response in nba_responses: filtered_rows.extend(extract_used_columns_from_nba_response( nba_response, desired_column_headers)) return filtered_rows def extract_used_columns_from_nba_response(nba_response, desired_column_headers): """ Keeps all columns specified in desired_column_headers and returns the processed list of rows. """ try: desired_column_indicies = [nba_response.headers.index( header) for header in desired_column_headers] except ValueError: raise ValueError('nba response headers are inconsistent: {} \n\n {}'.format( nba_response.headers, desired_column_headers )) rows = nba_response.rows filtered_rows = [] for row in rows: filtered_rows.append([row[i] for i in desired_column_indicies]) return filtered_rows def format_date_columns(desired_column_headers, rows): for header_i, header in enumerate(desired_column_headers): if header in DATE_QUERY_PARAMS: example_date = rows[0][header_i] if not is_proper_date_format(example_date): format_date_column(rows, header_i) def format_date_column(rows, header_i): for row_i, row in enumerate(rows): rows[row_i][header_i] = format_date(row[header_i]) def map_protected_col_names(column_names: List[str]): """ Returns a new list with renamed columns. Renamed columns have a NBA_ prepended. """ return [col_name if col_name not in PROTECTED_COL_NAMES else 'NBA_{}'.format(col_name) for col_name in column_names] def create_table_with_data(table_name: str, headers: List[str], rows: List[List], primary_keys=()): """ Creates a table with column names and rows corresponding to the provided json responses. """ if len(headers) != len(rows[0]): raise ValueError('Length of the headers and rows are not the same.') initialize_table_if_not_exists(table_name, headers, rows, primary_keys) add_rows_to_table(table_name, headers, rows) def initialize_table_if_not_exists(table_name, headers, rows, primary_keys): column_sql_str = format_sql_table_column_declaration_str(headers, primary_keys, rows) db.utils.execute_sql("""CREATE TABLE IF NOT EXISTS {} ({});""".format( table_name, column_sql_str)) def format_sql_table_column_declaration_str(headers, primary_keys, rows): """ Returns the string representing the declaration of columns in a sqlite3 table declaration which includes. - column name - column type (sqlite3) - primary key Ex. 'PLAYER_ID INT, PLAYER_NAME TEXT, PRIMARY KEY (PLAYER_ID, PLAYER_NAME)' """ column_types = get_column_types(headers, rows) column_name_type_pairs = ['{} {}'.format(headers[i], column_types[i]) for i in range(len(headers))] column_def = ', '.join(column_name_type_pairs) if len(primary_keys) != 0: column_def += ', PRIMARY KEY ({})'.format(', '.join(primary_keys)) return column_def def get_column_types(headers, rows: List[List]): """ Returns a list of sqlite3 types defined by the data in the json response rows. """ TYPE_MAPPING = { str: 'TEXT', int: 'INT', float: 'FLOAT', bool: 'INT' } unknown_type_indicies = set(range(len(headers))) column_types = [None for _ in range(len(headers))] r = 0 while len(unknown_type_indicies) > 0: discovered_type_indicies = [] for i in unknown_type_indicies: if rows[r][i] is not None: column_types[i] = TYPE_MAPPING[type(rows[r][i])] discovered_type_indicies.append(i) for i in discovered_type_indicies: unknown_type_indicies.remove(i) r += 1 return column_types def add_rows_to_table(table_name: str, headers: List[str], rows: List[List]): """ Adds the rows to the table. """ insert_values_sql_str = '({})'.format(', '.join(['?'] * len(headers))) if CONFIG['IGNORE_DUPLICATES']: sql_statement = """INSERT OR IGNORE INTO {} VALUES {};""" else: sql_statement = """INSERT OR REPLACE INTO {} VALUES {};""" db.utils.execute_many_sql(sql_statement.format(table_name, insert_values_sql_str), rows)
ce4dbe12399397596aa9eebfaf09b62bc11b29f5
mosabry/Python-Stepik-Challenge
/1.04 Combining strings.py
142
4.3125
4
# use the variable names to print out the string *with a space between the words* word1 = "hello" word2 = "world" print(word1 + " " + word2)
2b65c4cf9a9372262d2cc927904e36f69cec9cd4
mosabry/Python-Stepik-Challenge
/1.06 Compute the area of a rectangle.py
323
4.15625
4
width_string = input("Please enter width: ") # you need to convert width_string to a NUMBER. If you don't know how to do that, look at step 1 again. width_number = int(width_string) height_string = input("Please enter height: ") height_number = int(height_string) print("The area is:") print(width_number * height_number)
b7b296552886fe0ca8d13d543770e0575361837c
joanamdsantos/world_happiness
/functions.py
1,018
4.125
4
import numpy as np import pandas as pd import seaborn as sns import matplotlib as mpl import matplotlib.pyplot as plt def plot_countrybarplot(df, var, top_num): ''' INPUT: df - pandas dataframe with the data var- variable to plot, not categorical top_num - number of top countries to plot OUTPUT: plot with the top number of countries with the var scores ''' # Initialize the matplotlib figure f, ax = plt.subplots(figsize=(6, 15)) # Choose only the top 50 countries with higher score y=df.sort_values(var, ascending=False) y_top = y['Country or region'][:top_num] # Plot the GDP per capita per country sns.set_color_codes("pastel") g=sns.barplot(x=var, y=y_top, data=df, label=var, color="y") # Add a legend and informative axis label ax.legend(ncol=3, loc="lower right", frameon=True) ax.set(xlim=(0, 10), ylabel="", xlabel=var) sns.despine(left=True, bottom=True) return g
d9a77d8f9ee22aae949c604daa9b428f23aea5ac
reqhiem/EDA_Laboratorio
/Python/Insertionsort.py
635
3.5625
4
import random from timeit import default_timer def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] j = i-1 while j >= 0 and key < arr[j] : arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def evaluateinsertion(ndatos): A = [] tiempo = 0.0 for i in range(5): for j in range(multiplicadordatos*ndatos): a = random.randint(1,10000) A.append(a) inicio = default_timer() insertionSort(A) fin = default_timer() tiempo = tiempo + (fin-inicio) A.clear() return tiempo/5.0
360ad5223ecaf2dd4d197282e964b1565d258a10
hefeholuwah/myfirstproject
/project.py
306
3.5
4
# we make a list of values c_t = [10,-20,-289,100,987] def temp(c): faren = c * 9 / 5 + 32 if c < -273: return("that temperature doesnt make sense") else: return(faren) with open("dat.txt","w") as file: for b in c_t: cont = file.write(str(temp(b))+"\n") print(cont)
1dd6bcec60728bf71fc84d3a759712d5032dfd59
shakib609/grokking-algorithm
/Chapter02/selection-sort.py
563
4.03125
4
import random def find_largest(arr): largest = arr[0] largest_index = 0 for i in range(1, len(arr)): if arr[i] > largest: largest = arr[i] largest_index = i return largest_index def selection_sort(arr): new_arr = [] for i in range(len(arr)): largest_index = find_largest(arr) new_arr.append(arr.pop(largest_index)) return new_arr def main(): arr = [random.randint(0, 15) for _ in range(10)] print(arr) print(selection_sort(arr)) if __name__ == '__main__': main()
d4818ff0e9e58b79e1855bc4476fa881a47763da
andrzmil/Excercise_Numbers
/liczby.py
1,729
3.984375
4
import itertools from operator import itemgetter import operator import functools import math numbers = [] for i in range(5): print("Enter number no " + str(i+1)) given_number = int(input()) numbers.append(given_number) print("Chosen numbers:") print(numbers) index_list = list(itertools.combinations([0,1,2,3,4], 3)) first_list = [] second_list = [] #locate elements that are not in index, prepare two list consist accordingly of 3 and 2 elements for ix in index_list: not_in_ix = list(set([0,1,2,3,4]) - set(ix)) first_list.append(itemgetter(*ix)(numbers)) second_list.append(itemgetter(*not_in_ix)(numbers)) def sum(a, b): return a+b diff_list = [] #check if sum is positive for i in range(10): curr_sum = functools.reduce(sum, first_list[i]) - functools.reduce(sum,second_list[i]) print("Difference of sum [" + ' '.join(str(e) for e in first_list[i]) + "] and sum [" + ' '.join(str(e) for e in second_list[i]) + "] equals " + str(curr_sum)) if curr_sum <= 0: print("Difference is negative or equals 0.") exit() else: diff_list.append(curr_sum) print("Differences are correct!") #check multiplication of differences vs square of given numbers final_check_diff = functools.reduce(operator.mul, diff_list) final_check_numbers = int(math.pow(functools.reduce(operator.mul, numbers), 2)) if final_check_diff <= final_check_numbers: print("Multiplied differences give " + str(final_check_diff) + ". Squared and multiplied numbers give " + str(final_check_numbers) + ". Multiplication of all differences is equal or smaller than squared and multiplicated given numbers.") else: print("Chosen numbers don't satisfy excercise conditions")
54f0e746f3067e9c8f182de031b0711fd4033569
shinozaki1595/hacktoberfest2021-3
/Python/Algorithms/Sorting/heap_sort.py
884
4.34375
4
# Converting array to heap def arr_heap(arr, s, i): # To find the largest element among a root and children largest = i l = 2 * i + 1 r = 2 * i + 2 if l < s and arr[i] < arr[l]: largest = l if r < s and arr[largest] < arr[r]: largest = r # Replace the root if it is not the largest, then continue with the heap algorithm if largest != i: arr[i], arr[largest] = arr[largest], arr[i] arr_heap(arr, s, largest) # Heap sort algorithm def heapsort(arr): s = len(arr) # Making the Max heap for i in range(s//2, -1, -1): arr_heap(arr, s, i) for i in range(s-1, 0, -1): # replace arr[i], arr[0] = arr[0], arr[i] # Transform root element into Heap arr_heap(arr, i, 0) arr = [1, 12, 9, 5, 6, 10] heapsort(arr) n = len(arr) print("Array after Heap Sort is:") print(arr)
8ffb50229c5c290cefa3a895c0853414f7da0b49
Byteme8bit/FileSearch
/program.py
1,758
3.859375
4
import os __author__ = "byteme8bit" # Program's main function def main(): print_header() # Prints app header folder = get_folder_from_user() # Grabs input from user if not folder: # Test for no input from user print("Try again") return text = get_search_text_from_user() # Grabs input from user if not text: # Test for no input from user print("Try again") return search_folders(folder, text) # Prints program's header in terminal def print_header(): print('=====================================') print(' File Search ') print('=====================================') print() # Function defines grabbing input from user to be used as location to be searched. Absolute path required! def get_folder_from_user(): folder = input("What folder do you want to search? ") # Grabs input from user (Absolute path to location) if not folder or not folder.strip(): # This test will trigger the main test for empty input from user return None if not os.path.isdir(folder): # Tests for file or directory return None return os.path.abspath(folder) # Function defines grabbing input from user to be used as search terms def get_search_text_from_user(): text = input("What are you searching for [single phrases only]") # Grabs input from user return text # Defines the algorithm to recursively search through directories def search_folders(folder, text): print("Would search {} for {}".format(folder, text)) # Defines the algorithm to recursively search files for the text def search_file(): pass # Allows file to be imported without running in host environment if __name__ == '__main__': main()
13c8da2ded9c2e01f814ec2eb9a422d92a798ba9
rkalz/CS355
/hw9.py
662
3.53125
4
# Rofael Aleezada # CS355, Homework 9 # March 27 2018 # Implementation of the Rejection Algorithm from math import ceil import numpy as np import matplotlib.pyplot as plt def rejection_method(): a = 0 b = 3 c = ceil((b - 1) ** 2 / 3) x = np.random.uniform(a, b) y = np.random.uniform(0, c) f_x = (x - 1) ** 2 / 3 while y > f_x: x = np.random.uniform(a, b) y = np.random.uniform(0, c) f_x = (x - 1) ** 2 / 3 return x def simulate(count): results = [] for _ in range(count): results.append(rejection_method()) plt.hist(results, bins=np.arange(0, 3, 0.1)) plt.show() simulate(10000)
0a5b3eadda2c696fa97a0169a8fa161fc6e51786
dunnbrit/Introduction-to-Computer-Networks
/chatserve.py
1,718
3.6875
4
# Name: Brittany Dunn # Program Name: chatserve.py # Program Description: A simple chat system for two users. This user is a chat server # Course: CS 372 - 400 # Last Modified: April 30, 2019 # Library to use sockets import socket # Library to get command line argument import sys # Referenced Lecture 15 and geeksforgeeks.org/socket-programming-python # Create a socket object try: serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) except: print "Socket Creation FAILED" exit() # Get the port number from command line try: serverPort = int(sys.argv[1]) except: print "Port Number NOT saved" exit() # Bind the socket to the port and host # Host is an empty string so it accepts requests from other network computers try: serverSocket.bind(('',serverPort)) except: print "Bind FAILED" exit() # Start the server to listen for incoming TCP requests try: # Only open 1 connection on the server serverSocket.listen(1) print "Server listening for requests" except: print "Server NOT listening" # Loop until interrupted while 1: # Connect to client sending request by creating a new socket object clientConnectSocket,addr = serverSocket.accept() print 'Connected to' , addr while 1: # Receive Message recievedMsg = clientConnectSocket.recv(512) # If client ended connection if recievedMsg == "": print "Client has left chat" break # Print Message print recievedMsg # Get message to send from user sendMsg = raw_input('Server> ') # if the message is quit if "\quit" in sendMsg: # close the connection clientConnectSocket.close() # break nested loop (skip next statement) break # send the message clientConnectSocket.send(sendMsg)
34d8b5c3ddcac697d76c5d8f91309086475100dd
Priyankkoul/cd-1
/1-Token_and_Symbol_Table/inp.py
127
3.734375
4
#comment a=10 a++ b=20 if(a>b): b-- else: a++ x=30 while x>0: x-=1 # #a=0 #b=b+10 #while(a>=0): # a = a + 10 # #c = c +10
70d87e6fe32ad1b0d647e85cf8a64c8f59c9398a
marcin-skurczynski/IPB2017
/Daria-ATM.py
568
4.125
4
balance = 542.31 pin = "1423" inputPin = input("Please input your pin: ") while pin != inputPin: print ("Wrong password. Please try again.") inputPin = input("Please input your pin: ") withdrawSum = float(input("How much money do you need? ")) while withdrawSum > balance: print ("The sum you are trying to withdraw exceeds your balance. Try again.") withdrawSum = float(input("How much money do you need? ")) print ("You have successfully withdrawn " + str(withdrawSum) + "PLN. Your current balance is " + str(round((balance-withdrawSum), 2)) + "PLN.")