blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
96c1eab5dbd571a58c12b346966d802a90274e08
sahussawud/CV
/week2/draw101.py
1,054
3.5625
4
import numpy as np import cv2 # Create a black image img = np.zeros((512,512,3), np.uint8) # Draw a diagonal blue line with thickness of 5 px img = cv2.line(img,(0,0),(511,511),(255,0,0),5) # Draw a green rectangle at the top-right corner of image img = cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) # Draw a circle inside the rectangle drawn above. img = cv2.circle(img,(447,63), 63, (0,0,255), -1) # Draws a half ellipse at the center of the image. #img = cv2.ellipse(img,(256,256),(100,50),0, 0,180, 255, -1) img = cv2.ellipse(img,(256,256),(100,50),0, 0,180, (255,0,0), -1) # Draw a small polygon of with four vertices in yellow color pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32) pts = pts.reshape((-1,1,2)) img = cv2.polylines(img,[pts],True,(0,255,255)) #img = cv2.polylines(img,[pts],False,(0,255,255)) # Write 'OpenCV' on the image in white color font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img,'OpenCV',(10,500), font, 4, (255,255,255),2,cv2.LINE_AA) cv2.imshow('Drawing on an image',img) cv2.waitKey(0) cv2.destroyAllWindows()
526f22a637e16c2d571122064a79ca009e0a3505
afarica/Task2.3
/p23.py
533
4.25
4
# Write a program that reads an integer number and prints its previous and # next numbers. See the examples below for the exact format your answers # should take. There shouldn't be a space before the period. # Remember that you can convert the numbers to strings using the function str. # (На английском языке что бы Вы научились понимать The next number for the number 179 is 180. The previous number for the # number 179 is 178.) a=int(input("Enter your number:")) b=a-1 c=a+1 print(b,c)
5daea9573ee2764a78cd8cf6074fc4428ac64621
zTaverna/Logica-de-Programacao
/Unidade 01/Aula 04 ex 04.py
439
4.15625
4
print("Digite os lados de um triângulo:") a=float(input("Lado 1: ")) b=float(input("Lado 2: ")) c=float(input("Lado 3: ")) if a<(b+c) and b<(a+c) and c<(a+b): if a==b and b==c: print("O triângulo é equilátero!") else: if a==b or a==c or b==c: print("O triângulo é isósceles!") else: print("O triângulo é escaleno!") else: print("Não é um triângulo!")
970130036674baae56cec508d290d1fc9d0c1ff4
anermika/PythonForEverybody
/Python Data Structures/Week 5 - Dictionaries/Assignement9_1.py
405
3.546875
4
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) counts=dict() bigcount= None bigword= None for line in handle: if not line.startswith('From '): continue words=line.split() mail=words[1] counts[mail]=counts.get(mail, 0) +1 for mail,count in counts.items(): if bigcount is None or count > bigcount: bigword=mail bigcount=count print(bigword,bigcount)
b7432c45158de1dfaca5a3e1b0b32479aa898814
sashank-kasinadhuni/CodeEvalSolutions
/Easy_Split_the_number.py
664
3.671875
4
import argparse def Split_the_Number(): parser = argparse.ArgumentParser() parser.add_argument("filename") args = parser.parse_args() with open(args.filename) as f: for line in f: line = line.rstrip('\n') line = line.split() operator = "" left = 0 for i in line[1]: if(i == '+' or i == '-'): operator = i break else: left+=1 a = int(line[0][0:left]) b = int(line[0][left:]) result = a-b if operator == "-" else a+b print(result) Split_the_Number()
93010b9686dafd491c83495cb3f059c2b1774ebe
handee/ARCfacegame
/week4/facegame.py
3,255
3.59375
4
import cv2 import video import common import sys import numpy as np from random import randint cv2.namedWindow('facedetect') score=0 level=0 player_lives=3 b=150 g=150 r=150 colour=(b,g,r) balldiameter=10 bx=100 by=balldiameter/2 ballcolour=(255,100,100) bx_direction=2 by_direction=3 #The face detector can have minimum and maximum sizes. mn=30 # minimum face width mx=500 # maximum face width #these two lines set up the face detector and the video input cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") cam = video.create_capture(0) fimg=cv2.imread("smily.png") while True: ret, img = cam.read() height, width= img.shape[:2] #print(height,width) #n make a blank background instead of the input image # output_image=np.zeros((height,width,3),np.uint8) # output_image[:]=(0,0,255) output_image=img bx=bx+bx_direction by=by+by_direction if (bx>width or bx<0): bx_direction=-bx_direction if (by<0): by_direction=-by_direction if (by>height): by=balldiameter/2 #n this is going off the bottom of the screen. do you want to do something # when it's dropped? if so this is where you'll want to put the code. player_lives=player_lives-1 print("you have {} lives left".format(player_lives)) # read an image from the video camera # convert the image to greyscale (black and white) storing it in the # variable "grey" grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.circle(output_image, (bx,by), balldiameter, ballcolour, -1) # run the face detector on the grey image and store the output in # the variable "rects" rects = cascade.detectMultiScale(grey, scaleFactor=1.3, minNeighbors=3, minSize=(mn, mn), maxSize=(mx,mx)) # loop through and draw the detected faces on the image for x, y, w, h in rects: if ((bx > x) and (bx < x+w) and (by < y) and (by > y-balldiameter )): by_direction=-by_direction by=y colour=(0,0,255) # make the face flash red #n Increase the score by one score=score+1 print("your score is {}".format(score)) print("your level is {}".format(level)) if (score>15): level=4 by_direction=12 elif (score>10): level=3 by_direction=9 elif (score>5): level=2 by_direction=6 else: level=1 #else: #n do something if you miss..? #n draw a face instead of a rectangle? f2=cv2.resize(fimg,(w,h),interpolation=cv2.INTER_CUBIC) output_image[y:y+h,x:x+w]=f2 # cv2.rectangle(img, (x, y), (x+w, y+h), colour, -1) colour=(b,g,r) #n flip the image - make sure to do this before writing but after drawing output=cv2.flip(output_image,1) #n Put the score on the screen font=cv2.FONT_HERSHEY_SIMPLEX score_print ="Score: {}".format(score) cv2.putText(output,score_print,(10,40), font, 1,(255,255,255),4,cv2.LINE_AA) lives_print ="Lives: {}".format(player_lives) cv2.putText(output,lives_print,(10,80), font, 1,(255,255,255),2,cv2.LINE_AA) cv2.imshow('facedetect', output) if 0xFF & cv2.waitKey(5) == 27: break if (player_lives<0): print("You lose!") break
657f9b9bc971871779b0bd2f0951348a179fc10d
valborgs/pythonStudy
/0722/함수/평균반환함수.py
699
3.65625
4
# 사용자로부터 국어, 영어, 수학 점수를 입력받는다 # 평균을 구해 출력한다. # 단, 평균을 구하는 작업은 함수 get_average() # 함수의 매개변수, 인수, 반환값 등의 처리는 조건에 맞춰서 임의로 설정 # 조건1. 함수는 평균만 구해야 함 # 조건2. 점수의 입력과 평균의 춣력은 main코드 부분에서 처리 # 함수 부분 def get_average(kor,eng,math): avg = (kor+eng+math)/3 return avg # main코드 부분 k = int(input("국어 점수: ")) e = int(input("영어 점수: ")) m = int(input("수학 점수: ")) avg = get_average(k,e,m) print("평균:",avg,"점") # print("평균:",get_average(k,e,m),"점")
e727d20b7e0e13161717ab263e1a1694e6079bc0
Hipo/university-domains-list
/tests/test_domains.py
3,841
3.53125
4
import json import unittest import validators class DomainsTests(unittest.TestCase): def setUp(self): """Load the JSON file into a variable""" with open("world_universities_and_domains.json", encoding="utf-8") as json_file: self.valid_json = json.load(json_file) def test_university_json_structure(self): """Test the structure of each university entry in the JSON file""" for university in self.valid_json: # Name self.assertIn("name", university, msg="University Name is missing") self.assertIsInstance( university["name"], (str, type(None)), msg="University Name must be a string or null", ) # Domains self.assertIn("domains", university, msg="University Domains are missing") self.assertIsInstance( university["domains"], (list, type(None)), msg="University Domains must be a list or null", ) if university["domains"] is not None: for domain in university["domains"]: self.assertIsInstance( domain, (str, type(None)), msg="University Domain must be a string or null", ) if domain is not None: self.assertTrue( validators.domain(domain), msg=f"Invalid domain: {domain}" ) # Web Pages self.assertIn( "web_pages", university, msg="University Web Pages are missing" ) self.assertIsInstance( university["web_pages"], (list, type(None)), msg="University Web Pages must be a list or null", ) if university["web_pages"] is not None: for web_page in university["web_pages"]: self.assertIsInstance( web_page, (str, type(None)), msg="University Web Page must be a string or null", ) if web_page is not None: self.assertTrue( validators.url(web_page), msg=f"Invalid web page: {web_page}", ) # Alpha Two Code self.assertIn( "alpha_two_code", university, msg="Country Alpha Two Code is missing" ) self.assertIsInstance( university["alpha_two_code"], (str, type(None)), msg="Country Alpha Two Code must be a string or null", ) if university["alpha_two_code"] is not None: self.assertEqual( len(university["alpha_two_code"]), 2, msg=f"Country Alpha Two Code must be 2 characters long: {university['alpha_two_code']}", ) # State/Province self.assertIn( "state-province", university, msg="University State/Province is missing" ) self.assertIsInstance( university["state-province"], (str, type(None)), msg="University State/Province must be a string or null", ) # Country self.assertIn("country", university, msg="University Country is missing") self.assertIsInstance( university["country"], (str, type(None)), msg="University Country must be a string or null", ) # Run tests locally # if __name__ == "__main__": # unittest.main()
ecde195282166ec438830febcd009bee48c1039e
tripathyas/Online-Hackathon
/GeeksForGeeks/14_top_view_of_tree.py
1,026
3.9375
4
class Node(): def __init__(self, value): self.value = value self.left = None self.right = None # 25 # 15 35 # 10 20 30 45 # 5 12 17 21 28 33 40 50 root = Node(25) root.left = Node(15) root.right = Node(35) root.left.left = Node(10) root.left.right = Node(20) root.left.left.left = Node(5) root.left.left.right = Node(12) root.left.right.left = Node(17) root.left.right.right = Node(21) root.right.left = Node(30) root.right.right = Node(45) root.right.left.left = Node(28) root.right.left.right = Node(33) root.right.right.left = Node(40) root.right.right.right = Node(50) def get_top_view(node): stack = [node] while node.left: stack.append(node.left) node = node.left while len(stack) != 1: print(stack.pop(-1).value) node = stack.pop(-1) print(node.value) while node.right: print(node.right.value) node = node.right get_top_view(root)
44428c9d58076a000c4c7217f0db779c966e8538
AparnaDR/LearnPython
/tuples.py
724
4.46875
4
# tuples are similar to list, unlike list we cannot add, remove items form tuple. they ate immutable,cannot change them # no append,remove, clear,insert,pop # only count and index methods are available # we can only get information of a tuple but not change it numbers =(1,2,3) print(numbers.count(1)) # numbers[0] = 10 # error print(numbers[0]) # unpackaging coordinates=(1,2,3) """ x = coordinates[0] y = coordinates[1] z = coordinates[2] """ # above 3 lines of code can also be written like below # shorthand # we are unpacking tuple in to a variable # takes first item in the tuple and assign it to a variable # coordinate 1 will be assigned to x x,y,z = coordinates print(x) # unpacking is applicable to list also
5487321ae7ebd80decc3dfa487e0f1976e88de0a
emekambachu/modern_python3_bootcamp
/break.py
179
3.734375
4
# while True: # command = input("Type 'exit' to exit: ") # if (command == "exit"): # break for x in range(1, 101): print(x) if x == 20: break
d0fc4569658a5fc5cb12610948bdbace2cd564f5
rutvikpadhiyar000/python-math-calculator
/code/version1-0.py
999
4.25
4
try: # Take Input Command cmd = int(input(""" Enter 1 for Area of Square Enter 2 for Perimeter of Square Enter 3 for Area of Rectangle Enter 4 for Perimeter of Rectangle >>> """)) except ValueError: print("You have entered an invalid input. Please try again.") else: # Just giving a newline print() # For square if cmd in [1, 2]: length = float(input("Enter length of sides of Square: ")) # For area of square. if cmd == 1: print(length * length) # For perimeter of square. else: print(4 * length) elif cmd in [3, 4]: length = float(input("Enter length of Rectangle: ")) breath = float(input("Enter width of Rectangle: ")) # For area of Rectangle if cmd == 3: print(length * breath) # For perimeter of Rectangle else: print(2 * (length + breath)) else: print("You have entered in an invalid input. Please try again.")
cd36141486e675fb9e0bef6a0cd0916ef612f1cd
dvncan/python_fun
/controlstatements/assignmnet3.py
138
3.8125
4
x = int(input("Please enter a number: ")) for i in range(1,x+1): if(i%10==0):continue print(i) if(i>100):break i+=1
8f6877c4a35cca36e89d720b5aa8d46571e36ecc
MonCalFF/football_data
/profootballReferenceScrape.py
5,002
3.53125
4
## Ben Kite import pandas import requests, bs4 import re ## Provides a list of the html tables that can be found at the url ## provided. The order in the list returned should reflect the order ## that the tables appear. On pro-football-reference.com, these names ## usually indicate what information they contain. def findTables(url): res = requests.get(url) comm = re.compile("<!--|-->") soup = bs4.BeautifulSoup(comm.sub("", res.text), 'lxml') divs = soup.findAll('div', id = "content") divs = divs[0].findAll("div", id=re.compile("^all")) ids = [] for div in divs: searchme = str(div.findAll("table")) x = searchme[searchme.find("id=") + 3: searchme.find(">")] x = x.replace("\"", "") if len(x) > 0: ids.append(x) return(ids) ## For example: ## findTables("http://www.pro-football-reference.com/boxscores/201702050atl.htm") ## Pulls a table (indicated by tableID, which can be identified with ## "findTables") from the specified url. The header option determines ## if the function should try to determine the column names and put ## them in the returned data frame. The default for header is True. ## If you get an index error for data_header, try specifying header = ## False. I will include a generated error message for that soon. def pullTable(url, tableID, header = True): res = requests.get(url) ## Work around comments comm = re.compile("<!--|-->") soup = bs4.BeautifulSoup(comm.sub("", res.text), 'lxml') tables = soup.findAll('table', id = tableID) data_rows = tables[0].findAll('tr') game_data = [[td.getText() for td in data_rows[i].findAll(['th','td'])] for i in range(len(data_rows)) ] data = pandas.DataFrame(game_data) if header == True: data_header = tables[0].findAll('thead') data_header = data_header[0].findAll("tr") data_header = data_header[0].findAll("th") header = [] for i in range(len(data.columns)): header.append(data_header[i].getText()) data.columns = header data = data.loc[data[header[0]] != header[0]] data = data.reset_index(drop = True) return(data) ## For example: ## url = "http://www.pro-football-reference.com/boxscores/201702050atl.htm" ## pullTable(url, "team_stats") ## Finds offensive player data for a given season. ## This one was written with fantasy football GMs in mind. ## stat indicates what statistic is desired. ## the user must specify "passing", "rushing", or "receiving" ## the year indicates the year in which the season of interest started def seasonFinder (stat, year): url = "http://www.pro-football-reference.com/years/" + str(year) + "/" + stat + ".htm" if stat == "rushing": stat = "rushing_and_receiving" dat = pullTable(url, stat, header = False) dat = dat.reset_index(drop = True) names = dat.columns for c in range(0, len(names)): replacement = [] if type (dat.loc[0][c]) == str: k = names[c] for i in range(0, len(dat[k])): p = dat.loc[i][c] xx = re.sub("[#@*&^%$!+]", "", p) xx = xx.replace("\xa0", "_") xx = xx.replace(" ", "_") replacement.append(xx) dat[k] = replacement return(dat) ## seasonFinder("passing", 2016) ## For example: ## tables = ["passing", "rushing", "receiving"] ## years = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, ## 2009, 2010, 2011, 2012, 2013, 2014, 2015] ## for y in years: ## for t in tables: ## SeasonFinder(t, y) ## Finds the play by play table a game with the date and homeTeam provided. ## The date has to be yyyymmdd with a 0 on the end. ## The reference sites use the trailing 0 incase there are multiple games on the same day (it happens in baseball). ## For the 2017 Superbowl the date of February 5th, 2017 would be 201702050. ## The team is the three letter abbrieviation for the home team in lower case. def playByPlay (date, homeTeam): url = "http://www.pro-football-reference.com/boxscores/" + str(date) + homeTeam + ".htm" dat = pullTable(url, "pbp") dat = dat.reset_index(drop = True) dat = dat.loc[dat["Detail"] != "None"] return(dat) ## For example: ## This provides the play by play for the 2017 Superbowl. ## playByPlay("201702050", "atl") ## This function provides an easy way to access NFL scouting combine data. ## The year indicates the year the combine was held. ## The pos argument can be used to specify a position to pull data for. ## If pos is not specified all data will be pulled. def pullCombine(year, pos = None): url = "http://www.pro-football-reference.com/draft/" + str(year) + "-combine.htm" dat = pullTable(url, "combine") dat["year"] = year if pos is not None: dat = dat.loc[dat["Pos"] == pos] return(dat) ## For example: ## This pulls all data for Quarterbacks in 2016 ## pullCombine(2016, "QB")
dfe96824de1a7eeb530e57cbe36cd68868796e9b
pepeArenas/PythonGettingStarted
/FunctionsUseExample.py
1,404
4.3125
4
students = ["jesus", "miguel", "elena", "guadalupe"] # We can have functions that not receive parameters and not return anything def printStudents(): for student in students: print(student) print("---------") # The we call the function printStudents() # The function can have arguments def addStudent(name): students.append(name) # Then we call the function addStudent("Mario") printStudents() # The function can return something def sum(a, b): return a + b # We can use vars like in java but instead of use ... we use * and this will result in a list def printNames(*names): print(names) print(sum(1, 4)) printNames("Jesus", "Pepe", "Elena", "Lupita") # Also we can have a kvars and this will result in a dictionary rather than a list as vars do def printValues(**kvars): print(kvars["nombre"]) # We call the funtion kvargs defining the properties that the map will have printValues(nombre="jesus", edad=34) # Also we can have default values inside our function, this will make optional the arg with default value def functionWithDefaultValue(name, age=18): print("Name: {} Age: {}".format(name, age)) # We can call without the default parameter and will print age default value functionWithDefaultValue("Jesus") # Also we can call the function with the second parameter and will override the default value functionWithDefaultValue("Jesus", 34)
75445b5be3cb9808eeb000b16a4a10490438e370
yashydv/leetcode
/Medium/#222.py
1,485
3.625
4
class Solution: def countNodes(self, root: TreeNode) -> int: def pathExists(root: TreeNode, pathNumber: int, treeHeight: int) -> bool: current = root for level in range(0, treeHeight - 1): current = current.left if (pathNumber & (1 << (treeHeight - 2 - level))) == 0 else current.right if not current: return False return True if not root: return 0 count = 0; # Node count without last level hcurrent = root.left levelCount = 1 height = 1 while hcurrent: height += 1 count += levelCount levelCount *= 2 hcurrent = hcurrent.left # Find node count in the last level using binary search # encode last level node number: # going from the root to node and adding bits: 0bit - on going left, 1bit - on going right, # so first node bits is 0...0 (left) and last node bits is 1...1 (right) left = 0 right = levelCount - 1 if pathExists(root, right, height): return count + right + 1 while True: mid = (left + right) // 2 if pathExists(root, mid, height): left = mid else: right = mid if right - left <= 1: break return count + left + 1
6e50415e888fe36e6e164a403d8190e1460d1238
Prasan92/mywork
/strings/str_odd_even.py
320
4.03125
4
#print the characters present at even index and odd index separately for the given string s = input('enter the string: ') print('print char in even index') i=0 while i<len(s): print(s[i]) i=i+2 print('enter char in odd index') i=1 while i<len(s): print(s[i]) i=i+2 print('char in odd index')
81e9673147892fddbf18c18a15cbc2aca6bd8650
TurtlesAndBacon/ga306
/Python_Scripts/magic8ball_test.py
1,136
3.78125
4
import random randomNum = [0, 1, 2, 3, 4, 5, 6, 7, 8] print('What is your name?') name = input() def get_fortune(name): if randomNum == 1: print(name + ', you have been cursed with male-pattern baldness.') if randomNum == 2: print(name + ', you have been cursed to always think there is one more stair.') if randomNum == 3: print(name + ', you have been cursed to always step in water after putting on fresh socks.') if randomNum == 4: print(name + ', you have been cursed to always get the squeaky shopping cart.') if randomNum == 5: print(name + ', you have been cursed to always sit at wobbly tables.') if randomNum == 6: print(name + ', you have been cursed to always sit in the front row at the movies.') if randomNum == 7: print(name + ', you have been cursed to always be behind a slow driver.') if randomNum == 8: print(name + ', you have been cursed to always lose a book just before finishing it.') if randomNum == 9: print(name + ', you have been cursed to only have access to dial-up internet.') get_fortune(name)
96c957a24b26abe3d12977e8d06ebb18ac895820
kadhirash/leetcode
/problems/search_insert_position/solution.py
820
3.984375
4
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: # for counter, value in enumerate(nums): # #print(counter,value) # if value == target: # return counter # else: low = 0 high = len(nums) - 1 mid = 0 while low <= high: mid = (low + high) // 2 # Check if x is present at mid if nums[mid] < target: low = mid + 1 # If x is greater, ignore left half elif nums[mid] > target: high = mid - 1 # If x is smaller, ignore right half else: return mid # If we reach here, then the element was not present return low
7acfcc3c23320b749fae6f90b66e09631e7d9f1f
mdhvkothari/Python-Program
/hackerrank/co.py
570
3.71875
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 18 17:19:49 2018 @author: Madhav """ for _ in range (input()): c=input() main=0 maxnum=1 for x in range (1,c+1): temp=0 T=x while True : if x%2 ==0 : x=x/2 else : x=3*x+1 temp=temp+1 if x==1: if temp == main and T>maxnum : maxnum=T elif temp>main : main=temp maxnum=T break print (maxnum)
9ca759d946822672a6bf7724727b3625f550c72e
w940853815/my_leetcode
/utils/tree_node.py
1,822
3.859375
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def gatherAttrs(self): return ", ".join( "{}: {}".format(k, getattr(self, k)) for k in self.__dict__.keys() ) def __str__(self): return self.__class__.__name__ + " {" + "{}".format(self.gatherAttrs()) + "}" class List2Tree(object): def __init__(self, nums: list): self.nums = nums self.queue = [] if len(nums) == 1: self.root = TreeNode(self.nums.pop(0)) else: a = self.nums.pop(0) b = self.nums.pop(0) c = self.nums.pop(0) self.root = TreeNode(a) if b is not None: self.root.left = TreeNode(b) else: self.root.left = b if c is not None: self.root.right = TreeNode(c) else: self.root.right = c self.queue.append(self.root.left) self.queue.append(self.root.right) def main(self): while len(self.nums) > 0 and len(self.queue) > 0: node = self.queue.pop(0) if node is not None: num = self.nums.pop(0) if num is not None: node.left = TreeNode(num) else: node.left = num num = self.nums.pop(0) if num is not None: node.right = TreeNode(num) else: node.right = num self.queue.append(node.left) self.queue.append(node.right) return self.root if __name__ == "__main__": root = List2Tree([10, 5, 15, 3, 7, None, 18]).main() print(root)
18e3aa395bce97fb8a77e8bb5156273c70a20589
sakamot/nlp100
/chapter1/04.py
332
3.5
4
str = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can." dict = {} for i, s in enumerate(str.split()): if i + 1 in [1, 5, 6, 7, 8, 9, 15, 16, 19]: dict[i] = s[0] # 1文字目 else: dict[i] = s[0:2] # 0文字目から2文字 print(dict)
62fc0b851f4fb46af98e95022be609083ec9de6f
8BitJustin/2020-Python-Crash-Course
/Chapter 8 - Functions/8-8 User_Albums.py
589
4.0625
4
def make_album(artist_name, album_title, tracks=''): album = {'artist': artist_name.title(), 'title': album_title.title()} return album while True: print('Lemme know your favorite artist and their best album:') print('(press \'q\' to quit)') name = input('Artist name? ') if name == 'q': break album = input('Album name? ') if album == 'q': break full = 'Your artist is ' + name.title() + ' and your favorite album of ' \ 'their\'s is ' + album.title()\ + '.' print(full)
9f59b288441bd88c2450d9c878a54cc73893cf82
narhirep/Python-Deep-Learning
/ICP3/sourcecode/ICP3_1.py
1,866
4.125
4
# Function for average salary def avg_salary(): print("Total salary of all employees = ", Employee.total_salary) print("Total number of employees = ", Employee.no_of_employees) return Employee.total_salary / Employee.no_of_employees # Employee class 'Parent Class' class Employee: no_of_employees = 0 # data member to count the number of Employees total_salary = 0 # data member to save the total salary # constructor to initialize name, family, salary, department def __init__(self, name, family, salary, department): self.name = name self.family = family self.salary = salary self.department = department Employee.no_of_employees += 1 Employee.total_salary += self.salary # Function to print employee details def get_employee_details(self): print("Name = ", self.name) print("Family =", self.family) print("Salary =", self.salary) print("Department =", self.department) # Adding 3 employees a = Employee("Edward", 7, 8000, "Management") b = Employee("Bella", 3, 4000, "Audit") c = Employee("Alice", 3, 12000, "Research") print("Average salary = ", avg_salary()) #Inheriting parent class Employee to child class FullTimeEmployee class FullTimeEmployee(Employee): def __init__(self, name, family, salary, department): Employee.__init__(self, name, family, salary, department) def get_fulltimeemployee_details(self): print("Name = ", self.name) print("Family =", self.family) print("Salary = ", self.salary) print("Department =", self.department) d = FullTimeEmployee("Jacob", 9, 6000, "Sales") #Adding 4th employee print("\nAccess from full time employee function") d.get_fulltimeemployee_details() print("\nAccessing from parent class Employee function ") d.get_employee_details()
3156b6b7b9f9cafbef8de4aec935f56423547beb
JanHamara/Python_MiniScripts_LearningRepo
/json-import.py
711
3.96875
4
#! /usr/bin/env python """ json-import.py, by Jan Hamara, 2018-01-10 This script uses json module to execute conversion between string and object data structure """ import json def add_employee(salaries_json, name, salary): file_json = json.loads(salaries_json) try: file_json[str(name)] = int(salary) except ValueError: print("Make sure your input values are correct") salaries_json = json.dumps(file_json) return salaries_json # test code salaries = '{"Alfred" : 300, "Jane" : 400 }' new_salaries = add_employee(salaries, "Me", "sup") decoded_salaries = json.loads(new_salaries) print(decoded_salaries["Alfred"]) print(decoded_salaries["Jane"]) print(decoded_salaries["Me"])
3f5c80e85b70edfa55663dddea412756c6b17ac1
mohits1005/DSAlgo
/two-pointers/another-count-rectangles.py
1,288
3.734375
4
''' Another Count Rectangles Problem Description Given a sorted array of distinct integers A and an integer B, find and return how many rectangles with distinct configurations can be created using elements of this array as length and breadth whose area is lesser than B. (Note that a rectangle of 2 x 3 is different from 3 x 2 if we take configuration into view) Problem Constraints 1 <= |A| <= 100000 1 <= A[i] <= 109 1 <= B <= 109 Input Format The first argument given is the integer array A. The second argument given is integer B. Output Format Return the number of rectangles with distinct configurations with area less than B modulo (109 + 7). Example Input Input 1: A = [1, 2] B = 5 Input 2: A = [1, 2] B = 1 Example Output Output 1: 4 Output 2: 0 Example Explanation Explanation 1: All 1X1, 2X2, 1X2 and 2X1 have area less than 5. Explanation 2: No Rectangle is valid. ''' class Solution: # @param A : list of integers # @param B : integer # @return an integer def solve(self, A, B): i = 0 n = len(A) j = n-1 ans = 0 while i < n and j >= 0: if A[i]*A[j] >= B: j-=1 else: ans += j+1 i+=1 return ans%((10**9)+7)
26bf05425f148a441b1670d51fc5b8dc97f59846
pjt1988/Python-programming-exercises
/q_2/solution.py
443
3.8125
4
import sys import time def array_loop(x): numbers = [] for i in range(0,x+1): numbers.append(i*i) return numbers def dict_loop(x): numbers = {} for i in range(1,x+1): numbers[i] = i*i return numbers num = int(sys.argv[1]) t0 = time.time() print dict_loop(num) print "Dictionary loop needed %.2f s" % (time.time() - t0) print array_loop(num) print "Array loop needed %.2f s" % (time.time() - t0)
c49ef76394792097b55d2aff563c68bb9227a868
jeffminsungkim/ocean
/challenges/hackerrank/datastructure/stacks/game-of-two-stacks.py
1,772
3.59375
4
""" Sample Input 0 1 5 4 10 4 2 4 6 1 2 1 8 5 Sample Output 0 4 Explanation Detail: https://www.hackerrank.com/challenges/game-of-two-stacks/problem """ def is_exceed_limit(num): if num > limit: return True else: return False def sum_list(stk, limit): if is_exceed_limit(stk[0]): return [] for i in range(1, len(stk)): stk[i] = stk[i - 1] + stk[i] if is_exceed_limit(stk[i]): return stk[:i] return stk def find_max_number(stack_a, stack_b, limit): """ The two stacks initially look like this: stack_a: 4 2 4 6 1 stack_b: 2 1 8 5 Add each number in the stack until the sum of number exceeds the limit. If the number exceeds the limit, then remove the rest of numbers in the stack including the number on the current index. If sum of the last value from stack A and the value of stack B exceed the limit, then pop the value from the stack A. If the sum of the last value of stack A and the value in stack B exceed the limit, then pop the number from the stack A. """ s_a = sum_list(stack_a, limit) # [4, 6, 10] s_b = sum_list(stack_b, limit) # [2, 3] max_num = len(s_a) # max_num: 3 i = 0 while (i < len(s_b)): if len(s_a) and is_exceed_limit(s_a[-1] + s_b[i]): s_a.pop() else: max_num = max(max_num, len(s_a) + i + 1) i += 1 return max_num g = int(input().strip()) for _ in range(g): stack_a, stack_b, limit = input().strip().split(' ') stack_a, stack_b, limit = [int(stack_a), int(stack_b), int(limit)] stack_a = list(map(int, input().strip().split(' '))) stack_b = list(map(int, input().strip().split(' '))) print(find_max_number(stack_a, stack_b, limit))
07067f712446a3c3f863b6714e186cbcae4a21ac
JasonLeeSJTU/LeetCode
/166.py
1,266
3.703125
4
#!/usr/bin/env python # encoding: utf-8 ''' @author: Jason Lee @license: (C) Copyright @ Jason Lee @contact: jiansenll@163.com @file: 166.py @time: 2019/6/1 15:33 @desc: ''' class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: if numerator == 0: return '0' pos = (numerator < 0) == (denominator < 0) numerator = abs(numerator) denominator = abs(denominator) quotient = str(numerator // denominator) if pos: res = quotient else: res = '-' + quotient remainder = numerator % denominator if not remainder: #整除,没有小数点以及后面的数 return res else: res += '.' map = {} remainder *= 10 while remainder: if remainder not in map.keys(): map[remainder] = len(res) else: i = map[remainder] res = res[:i] + '(' + res[i:] + ')' return res res += str(remainder // denominator) remainder = remainder % denominator remainder *= 10 return res if __name__ == '__main__': res = Solution() print(res.fractionToDecimal(20, 7))
fc6b7bcfc0fad2a8bb5454082029b77160bf382b
Dakontai/-.
/cs/2/17.py
236
3.875
4
a = int(input("введите a :")) b = int(input("введите b :")) if a==0: if b ==0: print("x любое") else: print("нет решений") else: c = b/a if a>0: print("x>c") else: print("x<c")
2f579e407b1818f182379f9f6f73c3a3c83dc938
maomao905/algo
/all-tasks-scheduling-orders.py
1,692
3.703125
4
from collections import defaultdict, deque, Counter def sort_orders(tasks, prerequisites): # sources: [a, b, c] # N! combinations # pop a -> b -> c or a -> c -> b or b -> a -> c or b -> c -> a or c -> a -> b or c -> b -> a def backtrack(sources, sorted_order): for source in sources: sorted_order.append(source) # O(N) sources_copy = deque(sources) # only remove the current source # O(N) sources_copy.remove(source) for child in graph[source]: in_degrees[child] -= 1 if in_degrees[child] == 0: sources_copy.append(child) backtrack(sources_copy, sorted_order) # backtrack # O(N) sorted_order.remove(source) for child in graph[source]: in_degrees[child] += 1 # define the goal if len(sorted_order) == tasks: result.append(list(sorted_order)) graph = defaultdict(list) in_degrees = Counter() for parent, child in prerequisites: graph[parent].append(child) in_degrees[child] += 1 sources = deque([parent for parent in graph.keys() if parent not in in_degrees]) result = [] backtrack(sources, []) return result def main(): print("Task Orders: ") print(sort_orders(3, [[0, 1], [1, 2]])) print("Task Orders: ") print(sort_orders(4, [[3, 2], [3, 0], [2, 0], [2, 1]])) print("Task Orders: ") print(sort_orders(6, [[2, 5], [0, 5], [0, 4], [1, 4], [3, 2], [1, 3]])) main()
9135cf1728d938d57e7258dcf0caebca0a8726b8
y2ksayed/test2
/projects/student-submissions/movie_project_01132020_lindsey.py
5,754
3.65625
4
#1/22 project due import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline movies = pd.read_csv(r'C:\Users\linds\.spyder-py3\imdb_1000.csv') movies.head() """Check the number of rows and columns.""" movies.shape #979 rows and 6 columns """"Check the data type of each column.""" movies.dtypes movies.columns.values.tolist() """Calculate the average movie duration.""" np.mean(movies.duration) movies.duration.mean() """Sort the DataFrame by duration to find the shortest and longest movies""" duration = movies.sort_values('duration') duration.columns.values.tolist() duration['title'].tail(1) duration['title'].head(1) """Create a histogram of duration, choosing an "appropriate" number of bins.""" duration.duration.plot(kind='hist', bins=10); """Use a box plot to display that same data.""" duration.duration.plot(kind='box'); """Intermediate level""" """Count how many movies have each of the content ratings.""" duration.groupby(['content_rating'])['title'].count() content_rating = duration.groupby(['content_rating'])['title'].nunique() content_rating = pd.DataFrame(content_rating) content_rating['content_rating'] = content_rating.index content_rating.reset_index(drop=True, inplace=True) content_rating.columns = [ 'movie_count','content_rating'] """Use a visualization to display that same data, including a title and x and y labels.""" x=content_rating.content_rating x_pose = np.arange(len(x)) y=content_rating.movie_count plt.figure(figsize=(15,8)) plt.bar(x_pose,y) plt.ylabel('Movie Count') plt.xticks(x_pose,x) plt.title('Movie Count by Content Rating') plt.show() """Convert the following content ratings to "UNRATED": NOT RATED, APPROVED, PASSED, GP.""" movies= movies.replace(["NOT RATED", "APPROVED", "PASSED", "GP"], ["UNRATED","UNRATED","UNRATED","UNRATED"]) """Convert the following content ratings to "NC-17": X, TV-MA.""" movies= movies.replace(["X", "TV-MA"], ["NC-17","NC-17"]) """Count the number of missing values in each column.""" movies.isna().sum() movies.isnull().sum() """If there are missing values: examine them, then fill them in with "reasonable" values""" movies["content_rating"] = movies.content_rating.fillna("reasonable") """Calculate the average star rating for movies 2 hours or longer, and compare that with the average star rating for movies shorter than 2 hours.""" avg_star_high = movies[movies["duration"] >= 120] avg_star_low = movies[movies["duration"] < 120] avg_star_high["star_rating"].mean() avg_star_low["star_rating"].mean() """Use a visualization to detect whether there is a relationship between duration and star rating""" dur_star = movies[["star_rating","duration"]].copy() dur_star.corr() #1 import seaborn as sns sns.pairplot(dur_star) #2 import matplotlib.pyplot as plt plt.matshow(dur_star.corr()) plt.show() #heatmap dur_star_correlations = dur_star.corr(); sns.heatmap(dur_star_correlations); """Calculate the average duration for each genre""" movies.dtypes genre_avg = movies.groupby(['genre'])['duration'].mean() """Advanced level""" """Visualize the relationship between content rating and duration.""" con_rate_dur = movies[["content_rating","duration"]].copy() con_rate_dur['content_rating'].unique() #con_rate_dur = pd.get_dummies(con_rate_dur['content_rating']) con_rate_dur = pd.concat([con_rate_dur, pd.get_dummies(con_rate_dur['content_rating'])],axis=1) con_rate_dur.drop('content_rating', axis=1, inplace=True) con_rate_dur.corr() #1 import seaborn as sns sns.pairplot(con_rate_dur) #2 import matplotlib.pyplot as plt plt.matshow(con_rate_dur.corr()) plt.show() #heatmap con_rate_dur_correlations = con_rate_dur.corr(); sns.heatmap(con_rate_dur_correlations); """Determine the top rated movie (by star rating) for each genre""" movies.dtypes top_rated=movies[["title","genre","star_rating"]].copy() top_rated = movies.sort_values('star_rating') top_rated.columns.values.tolist() top_rated['genre'].head() top_rated #get the first row each group top_rated.groupby('genre').first() top_rated = top_rated.groupby(['genre'])['star_rating'].max() content_rating = duration.groupby(['content_rating'])['title'].nunique() content_rating = pd.DataFrame(content_rating) content_rating['content_rating'] = content_rating.index content_rating.reset_index(drop=True, inplace=True) """Check if there are multiple movies with the same title, and if so, determine if they are actually duplicates.""" movies[movies.duplicated()] any(movies['title'].duplicated()) duplicates = movies[movies.duplicated('title', keep=False) == True] """Calculate the average star rating for each genre, but only include genres with at least 10 movies""" top_rated = top_rated.sort_values("star_rating",ascending = False) top_ten = top_rated.groupby('genre').head(10).reset_index(drop=True) top_ten = top_ten.sort_values('genre') top_ten = top_rated.sort_values("star_rating",ascending = False) top_ten = top_rated.sort_values(["genre","star_rating"],ascending = [True,False]) #more than 10 movies per genre genre_counts = movies.genre.value_counts() top_genres = genre_counts[genre_counts >= 10].index movies[movies.genre.isin(top_genres)].groupby('genre').star_rating.mean() # option 3: colculate the average star rating for all genres, then filter using a boolean Series movies.groupby('genre').star_rating.mean()[movies.genre.value_counts() >= 10] # option 4: aggregate by count and mean, then filter using the count genre_ratings = movies.groupby('genre').star_rating.agg(['count', 'mean']) genre_ratings[genre_ratings['count'] >= 10]
b988749d4634b63abdd8053f2611e5d26166d064
nfarnan/cs001X_examples
/oo/MW/blackjack/hand.py
1,027
3.71875
4
from card import Card class Hand: def __init__(self): self.cards = [] def add(self, new_card): self.cards.append(new_card) def countAces(self): count = 0 for card in self.cards: if card.getValue() == "A": count += 1 return count def getValue(self): total = 0 points = {} for i in range(2, 11): points[i] = i for i in ["J", "Q", "K"]: points[i] = 10 points["A"] = 11 for card in self.cards: total += points[card.getValue()] aces = self.countAces() while total > 21 and aces > 0: total -= 10 aces -= 1 return total def __str__(self): rv = "Hand: (" + str(self.getValue()) + ")[" for card in self.cards: rv += str(card) rv += ", " rv = rv.strip(", ") rv += "]" return rv def __repr__(self): return self.__str__() def main(): print("Initialinzing Hand object...") h = Hand() print(h) print("DONE") print("Adding cards to Hand...") h.add(Card(4, "H")) h.add(Card("Q", "S")) print(h) print("DONE") if __name__ == "__main__": main()
df21252701fde5dfaa324bef106ab6a90719b2fa
martakunszt/Python-guess-the-number
/test.py
916
4.125
4
# print ("trzynascie".upper()) # print (len("thiscountsletters in a sentence")) # Guess the number import random print("Number guessing game") # Generating random numbers btween X and Y number = random.randint(1,50) # number of chances/inputs given chances = 0 print("Guess a number between 1 and 50:") #loop to count the number of chances while chances < 5: # input guess =int(input()) # comparing the numbers if guess == number: # if number entered is the same as random generated print("Congratulation You won!") break # if guess is too low elif guess < number: print("Your guess was too low") # if too high else: print("Your guess was too high") # increase the value of chance by 1 chances += 1 # check whether the user guessed the correct number if not chances < 5: print("You lose. The number is:", number)
9ca1814e0124a0f473ec7e0329c24777683a1ccc
leanndropx/px-python-logica-de-programacao
/85 - Funções - Calcule a area.py
674
4.25
4
# - DESCREVENDO O DESAFIO print('85 - Faça um programa que tenha uma função chamada área(), que receba dimensões',end='') print('de um terreno retangular (largura e comprimento) e mostre a área do terreno') print() #INICIALIZANDO O PROGRAMA # IMPORTA BIBLIOTECAS # CRIA FUNCOES def area(larg,comp): a=larg*comp print(f'A área do terreno de {larg:.0f}x{comp:.0f} é de {a} metros quadrados') # 1 - RECEBE DADOS l=float(input('largura do terreno: ')) c=float(input('comprimento do terreno: ')) # 2 - USA FUNCOES - MANIPULA DADOS, RETORNA DADOS area(l,c)
432a452f0caf248b6504de56b7223a6998e40543
SHaO-CHuN/Python-Practice
/第 2 章,作業 3 - Python的語法練習作業.py
1,105
3.953125
4
# 練習一: # 今天你有三個水果,分別為蘋果,葡萄,香蕉 # 1.請用程式碼加入一個新的水果 # 2.列出現在有幾個水果 # 3.每個水果分別列出:「我手上拿的是XX,好吃!」 # 從以下程式碼開始 # fruit = ["蘋果","葡萄","香蕉"] # 在終端機中顯示===> # 現在水果有4個,分別拿起來吃:) # 我手上拿的是蘋果,好吃! # 我手上拿的是葡萄,好吃! # 我手上拿的是香蕉,好吃! # 我手上拿的是草莓,好吃! fruit = ["蘋果","葡萄","香蕉"] fruit.append('草莓') print('現在水果有',len(fruit),'個,分別拿起來吃:)') for i in fruit: print('我手上拿的是',i,',好吃!') # # 練習二:開獎練習 # # 1.利用random隨機產生一組數字 # # 2.利用if else來判斷<0.1就顯示中獎,其餘顯示沒中獎(中獎機率10%)。 # # 3.利用for迴圈連續開三次。 import random for i in range(0,3,1): num = random.random() if num <0.1: print('中獎') else: print('沒中獎')
afcd2edec3cd0def9add65d1b87590a656758441
bluedawn123/Study
/keras/python/python08_hamsu.py
2,109
3.84375
4
#함수 def sum(z, x): #함수정의. sum이라는 함수에 a,b를 받아들인다. return z+x #그것의 리턴값은 a+b이다. a = input("a를 입력하시오 > ") a = int(a) b = input("b를 입력하시오 > ") b = int(b) c = a + b print("a + b의 값은 ", c) print("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ곱셈ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ") def multiply(z, x): #함수정의. sum이라는 함수에 a,b를 받아들인다. return z * x #그것의 리턴값은 a+b이다. a = input("a를 입력하시오 > ") a = int(a) b = input("b를 입력하시오 > ") b = int(b) c = a * b print("a 와 b의 곲은 ", c) print("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ나눗셈ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ") def divide(z, x): #함수정의. sum이라는 함수에 a,b를 받아들인다. return z / x #그것의 리턴값은 a+b이다. a = input("a를 입력하시오 > ") a = int(a) b = input("b를 입력하시오 > ") b = int(b) c = a / b print("a 와 b의 나눗셈 값 ", c) print("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ뺄셈ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ") def subtract(z, x): #함수정의. sum이라는 함수에 a,b를 받아들인다. return z - x #그것의 리턴값은 a+b이다. a = input("a를 입력하시오 > ") a = int(a) b = input("b를 입력하시오 > ") b = int(b) c = a - b print("a 와 b의 뺄셈은 ", c) print("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ기타ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ") def sayYeh(): return 'hi' aaa = sayYeh() print(aaa)
e81ed307a4963ff620264a3b0cf18932fca2557b
offero/algs
/dcp624_removeparen.py
726
4.25
4
''' Given a string of parentheses, write a function to compute the minimum number of parentheses to be removed to make the string valid (i.e. each open parenthesis is eventually closed). For example, given the string "()())()", you should return 1. Given the string ")(", you should return 2, since we must remove all of them. ''' def minparen(s): invalid = 0 count = 0 for char in s: if char == ')': if count == 0: invalid += 1 else: count -= 1 else: # '(' count += 1 return invalid + count if __name__ == "__main__": print(minparen('()())()') == 1) print(minparen(')(') == 2) print(minparen('))(()(()') == 4)
66647440e44c2955d76c972c5f4eaef12e7f52f1
MysteriousSonOfGod/Python-2
/Lyceum/lyc2/pg_rombiki.py
588
3.53125
4
import pygame, math k = int(input()) pygame.init() size = (155, 155) screen = pygame.display.set_mode(size) screen.fill(pygame.Color('yellow')) color = pygame.Color('orange') katet = int(math.sqrt(k ** 2) / 2) for i in range(0, size[1] - katet * 2, katet * 2): for j in range(0, size[0] - katet * 2, katet * 2): pygame.draw.polygon(screen, color, [[j + katet, i], [j + 2 * katet, i + katet], [j + katet, i + 2 * katet], [j, i + katet]]) pygame.display.update() while 1: for i in pygame.event.get(): if i.type == pygame.QUIT: exit()
cba40590b5b765c2791ab787e75c089721170762
sergiogbrox/guppe
/Seção 4/exercicio35.py
644
4.15625
4
""" 35- Sejam 'a' e 'b' os catetos de um triângulo, onde a hipotenusa é obtida pela equação: hipotenusa= raiz_quadrada de a²+b². Faça um programa que receba os valores de 'a' e 'b' e calcule o valor da hipotenusa através da equação. Imprima o resultado dessa operação. """ print(f'\nCalculadora de Hipotenusa.') a = input('Digite o valor do primeiro cateto: ') b = input('Digite o valor do segundo cateto: ') try: a = float(a) b = float(b) print(f'\nO valor da hipotenusa é {(a**2+b**2)**0.5}.') except ValueError: print('Somente números são aceitos. Feche o programa e tente novamente.')
9219ba57640b689290c31b4843abf37f3e6c0c4e
humenda/simple-orca-plugin-system
/SOPS/examples/parameter_test__-__parameters_ arg1 arg2 arg3__+__key_y__+__startnotify__+__stopnotify.py
277
3.59375
4
#!/bin/python # -*- coding: utf-8 -*- #could used to print parameters passed by "parameters arg1 arg2 arg3" import sys import getopt opts, extraparams = getopt.getopt(sys.argv[1:],"p:") print ("parameters") for o,p in opts: print(o + " ") print(p) print(extraparams)
78ea3b07e91ecef63deb2097a26f76c29a8310df
creeperdeking/Sea-battle
/game/scripts/gameHandler.py
1,842
3.734375
4
""" information: le point(0,0) de la carte est le point en haut a droite la coordonnée x est la coordonée de largeur la coordonnée y est la coordonée de longueur donnée manquente: """ import pdb import scripts.utils as utils import scripts.unit as unit class Game: """A class designed to handle the behavior of the game, independently from events or graphical interface""" def __init__(self, fileName,nbJoueur): print("Initialising game") self.map = [[]] self.loadMapFromFile(fileName) self.tour = 1 self.listeJoueur = [Player for i in range(nbJoueur)] self.joueurActuel = 0 def loadMapFromFile(self, filePath): f = open(filePath, 'r') content = f.readlines() mapSizeStr = content[0].strip().split(',') size = utils.Position([int(mapSizeStr[0]), int(mapSizeStr[1])]) self.map = [["sea" for i in range(size.x)] for j in range(size.y)] # #Synthaxe du fichier: #1,2 land for i in content[1:-1]: parties = i.strip().split(" ") coordinates = parties[0].strip().split(',') #pdb.set_trace() self.map[int(coordinates[0])][int(coordinates[1])] = [parties[1]] def updateTerrain(): print() def generate_map(largueur_carte,longueur_carte): """renvoie une carte pleine d'eau (a finir)""" carte=[["sea" for i in range(largueur_carte)] for j in range(longueur_carte)] return(carte) def tourSuivant(self): self.tour += 1 class Player: def __init__(self): self.nom = "random" self.point = 0 self.unite = [] #variable qui contient la liste des bateaux du joueur def calculPoint(self): self.point = 0 for bateau in self.unite: self.point += bateau.point_vie
19be173c4897948bebb40d3fbf9e0d35f7b64fbd
pranaysathu/pythonTraining
/class.py
927
3.609375
4
class MGM: def walk3(self): print("walk-MGM") class MGF: def Talk(self): print("Talk -MGF") class PGM: def walk(self): print("walk-PGM") class PGF: def Talk(self): print("Talk -PGF") print(dir(self)) class Mom(MGM,MGF): '''def __del__(self): print("Destructor for the class",id(self)) def __init__(self): print("object constructed successfully")''' def walk2(self): print("walk elegentlu", id(self)) class Dad(PGM,PGF): def Talk(self): print("Talk -Dad") class Infant(Mom,Dad): 'First class Python () are optional' '''def __del__(self): print("Destructor Infant for the class",id(self)) def __init__(self): print("object Infant constructed successfully",id(self))''' def walk1(self): print("walk -infant") #Mother = Mom() #Mother.walk() #del(Mother) Baby = Infant() Baby.Talk() Baby.walk() PGF.Talk(Baby) #print("Mother id,id(Mother)") #help(Baby) #print(dir(Baby))
cc1f18ad7b4eb3a9b0b0571aa185784f8a12657d
mattwfranchi/3600
/SampleCode/BufferedTCPEchoClient.py
2,655
3.5
4
from socket import * from struct import pack, unpack # Define variables that hold the desired server name, port, and buffer size SERVER_NAME = 'localhost' SERVER_PORT = 3604 BUFFER_SIZE = 32 class BufferedTCPEchoClient(object): def __init__(self, server_name, server_port): # We are creating a *TCP* socket here. We know this is a TCP socket because of # the use of SOCK_STREAM self.sock = socket(AF_INET, SOCK_STREAM) # Connect to a server at the specified port using this socket self.sock.connect((server_name, server_port)) def start(self): while True: # Read in an input statement from the user message = input('Input: ') # Send the message to the server self.send_message(message) # Wait for a response from the server response = self.receive_message() if response: print(response) else: print("Server disconnected...") break print("Closing socket...") self.sock.close() def send_message(self, message): message_length = len(message) data = pack("!B" + str(message_length) + "s", message_length, message.encode()) self.sock.send(data) def receive_message(self): # Get the first part of the message, this includes the header and the start of the string first_part = self.sock.recv(BUFFER_SIZE) if first_part: # First, strip out the header message_length = unpack("!B", first_part[:1])[0] print("..New message size: " + str(message_length)) print("..Received '" + first_part[1:].decode() + "'") message = first_part[1:] # Next, continue recv until the full message has been received while (len(message) < message_length): # Receive the next part of the message next_part = self.sock.recv(BUFFER_SIZE) # If there is a next part, append it to the current message if next_part: print("..Received '" + next_part.decode() + "'") message += next_part # Else, the client has disconnected, so return false else: print("Client disconnected!") return False return message.decode() else: return False if __name__ == "__main__": BufferedTCPEchoClient(SERVER_NAME, SERVER_PORT).start()
65579eed87265de53512b25a731cedfa5f9475b2
hillelweintraub/deepLearn
/code/util/logger.py
858
4.03125
4
# A Logger class for logging experiment runs class Logger: """ A simple class for logging stuff """ def __init__(self,logfile): """ Constructor. Opens a file object for writing """ self.myLog = open(logfile,'w') def log(self, log_string, print_stdout=True): """ write log_string to the log. If print_stdout, also print log_string to stdout """ self.myLog.write(log_string+'\n') self.flush() if print_stdout: print log_string def flush(self): """ Flush the IO buffer, to force a write to disc """ self.myLog.flush() def add_newline(self,print_stdout=True): """ Add a blank line to the log, and also to stdout if print_stdout is True """ self.log("",print_stdout) def close(self): """ Close the file object """ self.myLog.close()
027316e0461cc732c43f92f4424ef09155754961
shivamanhar/dynamic-programming
/23-countHowSum.py
468
3.671875
4
def countHowSum(targetSum, numbers): if targetSum == 0: return [] if targetSum < 0: return None remainderCombination = [] for num in numbers: remainder = targetSum-num remainderResult= countHowSum(remainder, numbers) if remainderResult != None: remainderCombination= remainderResult+[num] return remainderCombination return None result = countHowSum(7, [1,3, 4]) print(result)
ceddeb951d01fb0aaa74314138ba61aa1ba05a23
zzq5271137/learn_python
/14-基础知识点补充/02-ternary_operator.py
365
4.03125
4
""" Python的三目运算符 """ """ 在其他编程语言中, 存在三目运算符, 主要是用作简化条件判断语句的, 其语法为: 条件 ? 满足条件的结果 : 不满足条件的结果; 而在Python中, 其实不存在三目运算符, 但可以通过if...else...模拟这种行为; """ a = 5 b = 2 c = 'a大于b' if a > b else "a小于b" print(c)
2f1a4561a1afab769d9f793db6cbecd2d5292006
ospluscode/osPlayground
/fibonacci.py
238
4.28125
4
# a recursive function to find fibonacci sequence of n def fibonacci(n): assert n >= 0 and int(n) == n, 'Make sure n is a positive integer' if n in [0, 1]: return n else: return fibonacci(n-1) + fibonacci(n-2)
f73f64abef970bf689c12d35793b1cebef7a33c9
Vidoux/N_Reines-Algo_Avanc-
/min_conflicts.py
6,118
3.5
4
import random from Coordonnées import Coordonnées from Damier import Damier def solve_n_queen_big(taille, damier): """[summary] Résoudre le problème des n dames pour n'importe quelle valeure de n [description] Arguments: taille {Integer} -- taille du damier à résoudre damier {Damier} -- damier à résoudre Returns: {Damier} -- Damier contenant une solution {Boolean} -- True si le problème a été résolu """ lignes = [] # Stocke le placement de la dame sur chaque ligne du damier candidats = [] # Stocke les condidats possibles pour # un déplacement de dame # placement initial des dames initialisation_damier(taille, lignes, candidats) damier = dames_to_damier(lignes, damier.get_taille()) # résoudre le damier nbr_mvt = placer_dames(lignes, damier, candidats) print(nbr_mvt) damier = dames_to_damier(lignes, damier.get_taille()) # print(damier.toString()) # print(lignes) return damier, True def initialisation_damier(taille, lignes, candidats): """[summary] Placement initial des dames [description] Arguments: taille {Integer} -- Taille du damier lignes {Array} -- emplacement des dames pour chaque ligne candidats {Array} -- condidats possibles pour un déplacement de dame """ # Placement d'une dame par colonne for col in range(taille): # conflit minimum repéré, 8 par défaut min_conflit = 8 # réinitialisation des candidats candidats = [] # recherche des meilleurs cases pour placer la dame lignes.append(0) for row in range(len(lignes)): nbr_conflits = check_conflits(lignes[row], col, lignes) if nbr_conflits == min_conflit: candidats.append(row) elif nbr_conflits < min_conflit: candidats = [row] min_conflit = nbr_conflits # Sélection d'un candidat aléatoire pour placer la dame lignes[col] = random.choice(candidats) def check_conflits(row, col, lignes): """[summary] Evalue et retourne le nombre de conflicts sur une case donnée [description] Arguments: row {Integer} -- ligne concernée col {Integer} -- colonne concernée lignes {Array} -- emplacement des dames pour chaque ligne Returns: {Integer} -- nombre de conflicts """ conflit_count = 0 for val in range(len(lignes)): # La case courante n'est pas vérifiée if val != col: ligne_suivante = lignes[val] # si il y a une menace alors on incrémente le nombre de menaces if ligne_suivante == row or\ abs(ligne_suivante - row) == abs(val - col): conflit_count += 1 return conflit_count def dames_to_damier(lignes, damier_taille): """[summary] Transfère les emplacement des dames sur chaque lignes vers le damier complet [description] Arguments: lignes {Array} -- emplacement des dames pour chaque ligne damier_taille {Integer} -- taille du damier Returns: [Damier] --Damier rempli avec les dames """ # Supressions des anciens placements damier_new = Damier(damier_taille) # Placement des dames sur le damier vide for i in range(len(lignes)): case = Coordonnées(i, lignes[i]) damier_new.set_case_dame(case) return damier_new def placer_dames(lignes, damier, candidats): """[summary] Cherche à placer toutes les dames de sorte à arriver à une solution au problème des n dames. [description] Arguments: lignes {Array} -- emplacement des dames pour chaque ligne damier {Damier} -- damier à modifier candidats {Array} -- tableau de stockage des candidats possible pour chaque déplacement Returns: {Integer} -- Nombre de mouvements effectués avant de trouver une solution """ nbr_mouvements = 0 while True: nbr_conflits = 0 candidats = [] # Vérification du nombre de conflicts sur le damier # Si il n'y a pas de conflicts alors la solution est trouvée, # Sinon on modifie le placement des dames for val in range(len(lignes)): nbr_conflits += check_conflits(lignes[val], val, lignes) if nbr_conflits == 0: return nbr_mouvements # On déplace une dame au hasard sur un meilleur # emplacement (si possible) random_queen = random.randint(0, len(lignes) - 1) deplacer_reine(random_queen, lignes, candidats) nbr_mouvements += 1 damier = dames_to_damier(lignes, damier.get_taille()) def deplacer_reine(queen_col, lignes, candidats): """[summary] Recherche le meilleur placement possible d'une dame sur sa ligne et déplace la dame sur ce meilleur emplacement (ne déplace pas la dame si aucun meilleurs placement n'est possible) [description] Arguments: queen_col {Integer} -- colonne concernée par le déplacement lignes {Array} -- emplacement des dames pour chaque ligne candidats {Array} -- stocke les meilleurs emplacement pour la dame """ candidats = [] # conflit minimu constaté sur la ligne (8 par défaut) min_conflit = 8 # cherche la ligne pour laquelle le conflit est minimum for val in range(len(lignes)): val_conflit = check_conflits(val, queen_col, lignes) if val_conflit == min_conflit: candidats.append(val) else: if val_conflit < min_conflit: candidats = [] min_conflit = val_conflit candidats.append(val) # Si il existe un (ou plusieurs) meilleur emplacement pour la dame # alors on déplace celle ci sur l'un de ces emplacements if candidats: lignes[queen_col] = random.choice(candidats) # -----Tests------ damier = Damier(8) board, solved = solve_n_queen_big(8, damier) print(board.toString())
305d2e35ed9caee4fb023535536b0791d4868b36
lkkk1/python-text
/ex4.py
833
3.78125
4
#coding=utf-8 cars = 100 #车的数量 space_in_a_car = 4.0 #下划线字符通常被当做字符串中的假想空格用来分隔字符。 drivers = 30 #司机数量 passengers = 90 #乘客数量 cars_not_driven = cars - drivers #未用车的数量 cars_driven = drivers #用车的数量 carpool_capacity = cars_driven * space_in_a_car #可用车的容纳人数总和 (包含司机在内) #carpool 拼车 average_passengers_per_car = passengers / cars_driven #平均每辆车的乘客数 print('There are',cars,'cars available.') print('There are only',drivers,'drivers available') print('There will be',cars_not_driven,'empty cars today') print('We can transport',carpool_capacity,'people today') print('We have',passengers,'to carpool today') print('We need to put about',average_passengers_per_car,'in each car')
ccece1f47c8c22b518d28adcbe5a8047738d07d7
statco19/doit_pyalgo
/ch1/sum_verbose2.py
308
3.71875
4
print("a부터 b까지 정수의 합을 구합니다.") a = int(input("정수 a를 입력하세요.: ")) b = int(input("정수 b를 입력하세요.: ")) if a > b: a,b = b,a sum = 0 for i in range(a,b+1): if i < b: print(f"{i} +", end=' ') sum += i print(f"{b} =", end=' ') print(sum)
75b15daa8554b4db98901d1422dfe7196fa8a97b
ShoyiRen/cs839-project
/Stage4/DATA & CODE/merge.py
305
3.78125
4
import csv # write to a redirected output with open('Matched.csv', 'r') as csvfile: line = csv.reader(csvfile, delimiter=',') for row in line: if row[-1] == '1': # if it is a match print(','.join(row[3:8])) # keep columns 3-8, which only keeps A
6f3b3fdeae812e45f88e0c05dd78f995d618c368
njcssa/njcssa-python-practice-probs
/class05answers.py
2,804
4.40625
4
####################################################################################### # 5.1 # Make an infinite loop. while True: print("infinite") ####################################################################################### # 5.2 # Make a while loop which prints out the numbers 0 through 10. Here you will need to # create a counter variable. counter = 1 while counter <= 10: print(counter) counter += 1 ####################################################################################### # 5.3 # Make a while loop which counts up by 2s to 100. Print out the current count each loop. counter = 0 while counter <= 100: print(counter) counter += 2 ####################################################################################### # 5.4 # Make a while loop which counts down by 3s while the count is greater than 0. Print out # the count each loop. Start the countdown at 100. counter = 100 while counter > 0: print(counter) counter -= 3 ####################################################################################### # 5.5 # Use the input function to continually ask the user for a number and add that number # to the total. Each loop you should print out the current total. If the user enters # -1 the loop stops. total = 0 inp = int(input()) while not inp == -1: print("{} + {} = {}".format(total, inp, total+inp)) total = total + inp inp = int(input()) ####################################################################################### # 5.6 # Make a while loop with a counter variable. If the counter variable equals 100 break # out of the loop. Use the break statement for this. counter = 0 while counter < 1000: if counter == 100: print("exited") break print(counter) counter += 1 ####################################################################################### # 5.7 # Make a while loop which has 3 variables and changes each one at a different rate. Stop # the while loop when a variable gets to 100. a = 0 b = 0 c = 0 while a < 100 and b < 100 and c < 100: print("a: {} b: {} c: {}".format(a, b, c)) a += 1 b += 2 c += 3 ####################################################################################### # 5.8 # Make a while loop within a while loop. In the outer while loop count up to 10 from 1 # and in the inner loop count up to 3 from 1. counter1 = 1 counter2 = 1 while counter1 <= 10: while counter2 <= 3: print("counter1: {} counter2: {}".format(counter1, counter2)) counter2 += 1 counter2 = 1 counter1 += 1 ####################################################################################### # 5.9 string = "this is a cool string" length = len(string) i = 0 while i < length: print(string[i:i+1]) i += 1
7e9985290440b60053fe3ae8d4e78bf048756f69
RachanaDontula/beginner-learning
/practice9.py
559
4.15625
4
# Decorators: we can change the behaviour of the exixting function at the compile time itself # eg: without touching the function changing the function operation or condition of function # python is a functional programming language def div(a,b): print(a/b) def smart_duv(func): # passing parameter/augument a function # this is extra, so this is called decorator def inner(a,b): # function inside a function if a<b: a,b =b,a return func(a,b) return inner div = smart_duv(div) div(2, 4)
f74d2d9d22fbd83e8871ab9fde8c96915437fd98
dario-castano/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
372
4.5
4
#!/usr/bin/python3 def say_my_name(first_name, last_name=""): """Prints: My name is <first name> <last name>""" if not type(first_name) is str: raise TypeError("first_name must be a string") elif not type(last_name) is str: raise TypeError("last_name must be a string") else: print("My name is {} {}".format(first_name, last_name))
b3f6a94531694179360267a2e6d45ed97aa23911
loveplay1983/python_study
/21_oop/class_and_creation/basic/demo.py
1,818
4.34375
4
x = [4, 5, 9] y = "Hello" print(type(x), type(y)) print(type(type(x)), type(type(y))) """ type(classname, superclasses, attributes_dict) """ class A: pass x = A() print(type(x)) """ When we call "type", the call method of type is called. The call method runs two other methods: new and init __new__ accepts a type as the first argument, and (usually) returns a new instance of that type. Thus it is suitable for use with both mutable and immutable types. __init__ accepts an instance as the first argument and modifies the attributes of that instance. This is inappropriate for an immutable type, as it would allow them to be modified after creation by calling obj.__init__(*args). type.__new__(typeclass, classname, superclasses, attributedict) type.__init__(cls, classname, superclasses, attributedict) The new method creates and returns the new class object, and after this the init method initializes the newly created object. """ class Robot: counter = 0 def __init__(self, name): self.name = name def say_hello(self): return 'Hi, this is ' + self.name # Define new robot class with type class. # It is same to "class Robot2: pass" def rob_init(self, name): self.name = name Robot2 = type('Robot2', # class name (), # superclass { 'counter': 0, # attributes '__init__': rob_init, 'say_hello': lambda self: "Hi, this is " + self.name}) # x = Robot2('Robot2') x = Robot2('Robot2') print('class defined with type manually - ', x.name) print(x.say_hello()) print('----------------------------------------') y = Robot('Marvin') print('class defined with class directly - ', y.name) print(y.say_hello()) print(x.__dict__, '\n', y.__dict__)
82a3d1954a5bacbc1a54a99e8ed34514ae210249
BillNguyen1999/Escape-From-Alcatrazz
/escapefrompuzzeltraz/src/TicTacToe.py
8,065
3.5625
4
import pygame import random from button import Button import time from pygame.locals import * from pygame.sprite import Sprite, Group pygame.init() clock = pygame.time.Clock() screen_width = 600 screen_height = 500 screen = pygame.display.set_mode((screen_width, screen_height)) back_button = Button(screen,"BACK") replay_button = Button(screen,"Play Again") pygame.display.set_caption('TicTacToe') font = pygame.font.SysFont(None, 40) markers = [] for x in range(3): row = [0] * 3 markers.append(row) rand_pos = [[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]] clicked = False pos = [] winner = 0 game_over = False #define colors green = (0, 255, 0) red = (255, 0, 0) blue = (0, 0, 255) def draw_grid(): bg = (255, 255, 200) grid = (50, 50, 50) screen.fill(bg) pygame.draw.line(screen, grid, (150, 150), (450, 150), 6) pygame.draw.line(screen, grid, (150, 250), (450, 250), 6) pygame.draw.line(screen, grid, (250, 50), (250, 350), 6) pygame.draw.line(screen, grid, (350, 50), (350, 350), 6) def draw_markers(): y_pos = 0 for y in markers: x_pos = 0 for x in y: if x == 1: pygame.draw.line(screen, green, ((x_pos * 100) + 150 + 15, y_pos * 100 + 50 + 15), (x_pos * 100 + 150 + 85, y_pos * 100 + 50 + 85), 6) pygame.draw.line(screen, green, ((x_pos * 100) + 150 + 15, y_pos * 100 + 50 + 85), (x_pos * 100 + 150 + 85, y_pos * 100 + 50 + 15), 6) if x == -1: pygame.draw.circle(screen, red, (x_pos * 100 + 150 + 50, y_pos * 100 + 50 + 50), 38, 6) x_pos += 1 y_pos += 1 def check_winner(): global winner global game_over x_pos = 0 for y in markers: #check columns if sum(y) == 3: winner = 1 game_over = True if sum(y) == -3: winner = -1 game_over = True #check rows if markers[0][x_pos] + markers[1][x_pos] + markers[2][x_pos] == 3: winner = 1 game_over = True if markers[0][x_pos] + markers[1][x_pos] + markers[2][x_pos] == -3: winner = -1 game_over = True x_pos += 1 #check cross if markers[0][0] + markers[1][1] + markers[2][2] == 3 or markers[2][0] + markers[1][1] + markers[0][2] == 3 : winner = 1 game_over = True elif markers[0][0] + markers[1][1] + markers[2][2] == -3 or markers[2][0] + markers[1][1] + markers[0][2] == -3: winner = -1 game_over = True def tictactoe(code, time_amount): from gameScreen import countdown global winner global game_over global clicked global markers global rand_pos global y global x y = None x = None player = 1 ## timer clock_time = pygame.time.Clock() timer_font = pygame.font.Font(None, 38) rect = screen.get_rect() position = rect.centerx, 20 timer = countdown.DisplayCountDown(time_amount, timer_font, pygame.Color("Black"), position, "midtop") timer_group = Group(timer.text) run = True while run: draw_grid() draw_markers() back_button.draw_button() replay_button.draw_button() ticks = pygame.time.get_ticks() timer.update(ticks) timer_group.draw(screen) #add event handler for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN and clicked == False: clicked = True if event.type == pygame.MOUSEBUTTONUP and clicked == True: clicked = False pos = pygame.mouse.get_pos() cell_x = pos[0] cell_y = pos[1] back = back_button.rect.collidepoint(cell_x, cell_y) if back: run = False again = replay_button.rect.collidepoint(cell_x, cell_y) if game_over == False: if (150 <= cell_x and cell_x < 250) and (50 <= cell_y and cell_y < 150): x = 0; y = 0 elif (250 <= cell_x and cell_x < 350) and (50 <= cell_y and cell_y < 150): x = 0; y = 1 elif (350 <= cell_x and cell_x < 450) and (50 <= cell_y and cell_y < 150): x = 0; y = 2 elif (150 <= cell_x and cell_x < 250) and (150 <= cell_y and cell_y < 250): x = 1; y = 0 elif (250 <= cell_x and cell_x < 350) and (150 <= cell_y and cell_y < 250): x = 1; y = 1 elif (350 <= cell_x and cell_x < 450) and (150 <= cell_y and cell_y < 250): x = 1; y = 2 elif (150 <= cell_x and cell_x < 250) and (250 <= cell_y and cell_y < 350): x = 2; y = 0 elif (250 <= cell_x and cell_x < 350) and (250 <= cell_y and cell_y < 350): x = 2; y = 1 elif (350 <= cell_x and cell_x < 450) and (250 <= cell_y and cell_y < 350): x = 2; y = 2 if y != None and x != None: if markers[x][y] == 0: markers[x][y] = player player *= -1 check_winner() if (len(rand_pos) == 1 and winner == 0 and player == -1): game_over = True winner = -1 ### Computer if (player == -1 and winner == 0): rand_index = random.randint(0,len(rand_pos) - 1) rand_x = rand_pos[rand_index][0] rand_y = rand_pos[rand_index][1] while(markers[rand_x][rand_y] != 0): if (len(rand_pos) == 1): game_over = True winner = -1 else: rand_pos.remove([rand_x,rand_y]) rand_index = random.randint(0,len(rand_pos) - 1) rand_x = rand_pos[rand_index][0] rand_y = rand_pos[rand_index][1] if (len(rand_pos) == 1): game_over = True winner = -1 else: rand_pos.remove([rand_x,rand_y]) rand_index = random.randint(0,len(rand_pos) - 1) markers[rand_x][rand_y] = -1 player *= -1 check_winner() if again: player = 1 winner = 0 markers = [] game_over = False for x in range(3): row = [0] * 3 markers.append(row) rand_pos = [[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]] if game_over == True and winner == 1: win_text = "You WON! Your Code is: " + code win_img = font.render(win_text, True, blue) screen.blit(win_img, (150, 400)) elif (game_over == True and winner == -1) or time_amount <= 0: win_text = "You LOST! Try again quick" win_img = font.render(win_text, True, red) screen.blit(win_img, (150, 400)) pygame.display.update()
330fb53582c47ec674eaf32bb2771c940bd542ab
rokastr/Introduction-to-Object-oriented-Programming
/oblig1/beslutninger.py
248
3.859375
4
#Et program ber brukeren om å svare "ja" eller "nei". brus=input("Ønsker du å drikke brus?") if brus== "ja": print ("Her har du en brus!") elif brus== "nei": print ("Den er grei") else: print ("Det forstod jeg ikke helt")
c383aef2b190e559a04001ddf22591f086fc82a8
alexandraback/datacollection
/solutions_2751486_0/Python/ozan/consonants.py
1,185
3.6875
4
# import necessary modules # global variables n = 0 string = '' vowels = ['a', 'e', 'i', 'o', 'u'] # helper functions def isconsecutive(string): for i in range(n - 1): if string [i] in vowels: return False return True def isnsubstring(string): for i in range(len(string) - n + 1): if string [i] not in vowels: if isconsecutive(string [i + 1:]): return True return False def calculateleft(string): global result if len(string) < n: return if isnsubstring(string): result += 1 calculateleft(string[:-1]) def calculateright(string): global result if len(string) < n: return if isnsubstring(string): result += 1 calculateleft(string[:-1]) calculateright(string[1:]) # read function def read(): global string, n, result result = 0 temp = raw_input() loc = temp.find(' ') string = temp[:loc] n = int(temp[loc + 1:]) # main logic def solve(i): read() calculateright(string) print 'Case #' + str(i) + ': ' + str(result) def main(): T = int(raw_input()) for i in range(T): solve(i + 1) main()
d3a197dd7c4eeb3a6cf18d3e9d097636b5f6d7ab
lohitbadiger/python-basics-all
/19.0.py
648
4.15625
4
# data type set # removes the dublicate /repeated value set_of_number={1,2,3,3,4,5,6,7,7,8,9,2,4} print(set_of_number) set={8,8,8,8,8,8,8,8} print(set) sets={'a','b','c','d','e'} sets.add('f') print('adding the letter:',sets) # removing the item from the sets sets.remove('f') print(sets) ####### # #Intersection in python(common items) # #intersection can be used in set sets1={1,2,3,4,6,5,5,5,6,88} sets2={2,44,6,54,5,43,6,3,4,88} print(sets1.intersection(sets2)) print('------------------') sets3={2,4,4,5,67,8,9,2,4,88} set4=sets1.intersection(sets2,sets3) print('new set4 will be',set4) print('---------------------')
ef4efb98ef563f033097e98e5f6c6c1d7246df93
cedouiri/holbertonschool-web_back_end
/0x01-python_async_function/2-measure_runtime.py
635
3.515625
4
#!/usr/bin/env python3 ''' an async routine called wait_n that takes in 2 int arguments (in this order): n and max_delay. You will spawn wait_random n times with the specified max_delay ''' import time import asyncio wait_n = __import__('1-concurrent_coroutines').wait_n def measure_time(n: int, max_delay: int) -> float: ''' return the list of all the delays (float values). The list of the delays should be in ascending order without using sort() because of concurrency ''' start = time.perf_counter() asyncio.run(wait_n(n, max_delay)) elapsed = time.perf_counter() - start return elapsed / n
6b981d1d7a38a84f323103540315cb4bea1a5a67
justkrismanohar/bootcamp2017
/Mary_Had_A_Robo_Lamb/mary.py
526
3.5
4
from gopigo import * import time from __future__ import print_function from six.moves import input DISTANCE_TO_STOP = 20 print("Press ENTER to strart") input() # accepts keyboard input # Infinite Loop # Keep running until we break out of loop while True: dist = us_dist(15) # get distance from sensor print(dist) if dist < DISTANCE_TO_STOP: print("Stopping") stop() # Estimate distance travelled # If "run out of road" turn around else: fwd() time.sleep(.5)
0fd62c16c5e731f780a2be7e8fb5bac99c9ece44
bitomann/classes
/main.py
1,399
4.1875
4
from building import Building from city import City # Create a new city instance and add your building instances to it. # Once all buildings are in the city, iterate the city's building # collection and output the information about each building in the city. eight_hundred_eighth = Building("800 8th Street", 12) seven_hundred_seventh = Building("700 7th Street", 44) six_hundred_sixth = Building("600 6th Street", 13) five_hundred_fifth = Building("500 5th Street", 99) four_hundred_forth = Building("400 4th Street", 88) eight_hundred_eighth.purchase("Kid Frost") seven_hundred_seventh.purchase("MC Eight") six_hundred_sixth.purchase("Dr. Dre") five_hundred_fifth.purchase("B. Real") four_hundred_forth.purchase("Mr. Cartoon") eight_hundred_eighth.construct() seven_hundred_seventh.construct() six_hundred_sixth.construct() five_hundred_fifth.construct() four_hundred_forth.construct() megalopolis = City() megalopolis.add_building(eight_hundred_eighth) megalopolis.add_building(seven_hundred_seventh) megalopolis.add_building(six_hundred_sixth) megalopolis.add_building(five_hundred_fifth) megalopolis.add_building(four_hundred_forth) for building in megalopolis.buildings: print(f"------------------- \n{building.address.upper()}:\n Owner: {building.owner} \ \n Stories: {building.stories}\n Built: {building.date_constructed} \ \n Builder: {building.designer} ")
68ef4c72fb9d8c4bc3cb0a8786a8b9d8dd40ed3c
petrapes/pyladies
/03/hanka.py
552
3.953125
4
from turtle import * from random import randrange shape('turtle') color("Yellow") bgcolor("MidnightBlue") # star.color("yellow") for stars in range(1): begin_fill() for star in range(5): forward(20) left(144) forward(20) right(72) end_fill() penup() x = randrange(-200,200) y = randrange(-200,200) goto(y,x) pendown() for stars in range(1): begin_fill() for star in range(5): forward(20) left(144) forward(20) right(72) end_fill() hideturtle() exitonclick()
b082adc914f7f5b5b089dabe4b93b353940c1329
AstridTrj/noteStorage
/temp_project/dan1_8/homework1.py
1,061
3.515625
4
import matplotlib.pyplot as plt import pandas as pd import numpy as np # 为了显示中文,需要更换字体 plt.rcParams['font.family'] = ['sans-serif'] plt.rcParams['font.sans-serif'] = ['SimHei'] # 绘制图像 def hand_data(data: pd.DataFrame): # 利用matplotlib绘制散点图 (Revise列与Anxiety列) s为点的大小 plt.scatter(data['Revise'], data['Anxiety'], color='red', s=10) # 设置坐标标签,标签位置以及图表标题 plt.xlabel("Revise") plt.ylabel("Anxiety") plt.show() # 利用pandas的boxplot绘制箱型图 # 指定分析列为Revise列,用于分组的列为Gender列,即可得到不同性别的箱线图 data.boxplot(column='Revise', by='Gender') plt.show() def main(): # 文件路径,注意根据自己所存路径修改 path = "ExamAnxiety.csv" # 利用pandas读取数据 data = pd.read_csv(path) # 简单查看数据基本信息 print(data.describe()) # 调用函数绘制图像 hand_data(data) if __name__ == "__main__": main()
2ffd481182062b04cae90a91c939d5e35b8bce32
Jzgao04/Year9DesignCS-PythonPM
/AmeriCanadian.py
302
4.46875
4
#1. Obtain last two characters of string #2. Find out if the last two characters are "or" #3. Create a new string by adding "u" in between the o and r. #4. Return the new string word = input("Write the word here: ") part1 = word[:-1] if word[-2:] == 'or': print(part1 + "ur") else: print(word)
b1c9e2c8a00a4629e172218fe03d8b85f7f02283
LexGalante/Python.Lang
/funcoes/definicao.py
2,501
3.53125
4
def minha_funcao_sem_parametro(): """Documentação Docsstring, utilize print(help(minha_funcao_sem_parametro))""" return "Teste testando testamento...." def minha_funcao_com_parametro(texto): return texto.upper() def soma(numeros): if type(numeros) is not list: return 0 return sum(numeros) def quadrado(numero): if type(numero) is not int: return 0 return numero * numero def exponencial(numero, potencia=2): return numero ** potencia def funcao_com_parametro_callback(text, func=lambda text: text.title()): text += " testando..." return func(text) def usuario(login, password, active): """ Cria um usuário :login do usuário :password do usuário :active usuário está ativo """ return { "login": login, "password": password, "active": active } def nome_programa(nome="Python.Lang"): return nome teste = 42 def funcao_usando_parametro_global(): global teste return teste def funcoes_aninhadas(): numero = 42 def funcao_interna(): nonlocal numero return numero return funcao_interna() # utilizar *args como o ultimo parametro antes dos opicionais # transforma o *args em uma tupla def funcao_com_varios_parametros(*args): return print(sum(args)) # utilizar o **kwargs como ultimo parametro de uma funcao # tranforma o **kwargs em uma tupla def funcao_com_varios_parametros_2(**kwargs): if 'nome' in kwargs: print(f'achei o nome: {kwargs["nome"]}') print(kwargs) print(help(print)) print(help(minha_funcao_sem_parametro())) print(minha_funcao_sem_parametro()) print(minha_funcao_com_parametro(minha_funcao_sem_parametro())) print(soma([5, 5, 5, 6])) print(quadrado(5)) print("parametros nomeados") print(usuario(active=False, password="teste", login="teste")) print("parametros com valores default") print(nome_programa()) print(exponencial(5)) print(funcao_com_parametro_callback("Teste")) print(funcao_usando_parametro_global()) print(funcoes_aninhadas()) funcao_com_varios_parametros(1) funcao_com_varios_parametros(1, 2) funcao_com_varios_parametros(1, 2, 3) funcao_com_varios_parametros(1, 2, 3, 4) funcao_com_varios_parametros(1, 2, 3, 4, 5) numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9] # usando o * pedimos ao python que realize o desempactamento da variavel antes de usar funcao_com_varios_parametros(*numeros) funcao_com_varios_parametros_2(nome='Alex', sobrenome='Galante', idade=18)
3b4e4befa95a024a5f192b7b782ecc4869f7deb1
santoshganti/MITx
/MITx-6.00.1x/problemset1/Test.py
274
3.5
4
''' Created on 14-Jan-2015 @author: santoshganti ''' str1 = 'exterminate!' str2 = 'nUMBER ONE - THE LARCH' print str2.swapcase() print str1.index('!') print str1.find('!') print str1.count('e') str1 = str1.replace('e', '*') print str1 print str2.replace('one', 'seven')
ce462e0f5bd48c9e8e77dd53f117770b1de4d8c5
koytze/learn_python
/files.py
1,252
4.4375
4
#!/usr/bin/python #Basic file i/o exercises #You have to fill in the code for each function. #1. Display top N lines of a file #Your function receive as parameters: path of input file and n, the number of lines #Write the rest of the code to display the top n lines from the input_file #Append in front of each line, the line number. def PrintLinesFromFile(input_file,n): #fill in your code here return #2. Find longest word in the file #Your function receives as parameter path of input file and should display the #longest word found in the file. If multiple words have the same, maximum, length, #display all of them. def LongestWord(input_file): #fill in your code here return #3. Copy content #Your function receives as parameters path of input file and output file. #Write the code as to copy the text from the input file and to write it to output file. def CopyContent(input_file,output_file): #fill in your code here return def main(): #call your functions from here PrintLinesFromFile('ceo.txt',10) LongestWord('ceo.txt') CopyContent('ceo.txt','ceo_copy.txt') # Standard boilerplate to call the main() function. if __name__ == '__main__': main()
577a69eeec6e4d1cf2df5d8e4fd7136600129885
flyupwards/python3_source_code
/ch06a/ex0616.py
160
3.578125
4
# program0516.py def fib(i): if i == 0: return 0 elif i == 1: return 1 else: return fib(i - 1) + fib(i - 2) print(fib(8))
47ca10e91573f0a244c4d25f6513ca7f90f36e91
joshambush/reverse_shell_tcp
/reverse_shell_tcp/server.py
1,145
3.703125
4
# python2 # Make sure to run server before client """ |****************************| |Author:Josh Ambush |https://github.com/joshambush/ | joshambush5435@gmail.com |by-: joshambush |______________________________| """ import socket def main(): port = 5000 # could be any port host = '0.0.0.0' # all IP addresses on the local machine server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((host, port)) server_socket.listen(1) print("[!] Waiting for connection to be established...") conn, addr = server_socket.accept() print("[$] Connected to " + str(addr) + " on port "+str(port)+ " | [*]Successful") while True: try: request = raw_input(str(addr) + ">") if(len(request.split()) != 0): conn.send(request) else: continue except(EOFError): print("command is invalid") continue if(request == "stop()"): break data = conn.recv(1024) print(data + '\n') conn.close() if __name__ == "__main__": main()
9d03ef4de2541d31f024ccfef162059bc3ab406b
peitur/demo_python
/demo/hello_binary.py
2,495
3.625
4
#!/usr/bin/env python3 import os, re, sys import binascii import string from pprint import pprint def hexStr( data_str ): """ Lets convert our string to hex based integers """ return int( binascii.hexlify( data_str.encode() ), 16 ) def enc( msg, k ): """ Simple encoding by exoring stuff with a key k """ return int( binascii.hexlify( msg.encode() ), 16 ) ^ k def dec( msg, k ): """ Lets decode xor with a key k ... """ b = format( msg ^ k, 'x' ) return binascii.unhexlify( ( '0' * (len( b ) % 2 )) + b ) def printable( line, plist ): """ checking if a list of bytes are printable as charachters """ ret = b'' for s in line: if s in (b'\n', b'\r',b'\t',b'\x0b', b'\x0c', b' '): ret += b'.' elif s in bytes( plist, 'ascii'): ret += s.to_bytes(2, byteorder='little') else: ret += b'.' return ret def file_n_bytes( filename, n ): """ dump any file as a common hexdumper would do """ try: line = b"" plist = string.ascii_letters + string.digits + string.punctuation print() with open( filename, "rb" ) as fd: m = 0 i = 0 byte = fd.read(1) while byte != b'': # print( "%s " % ( hex( ord( byte ) ) ), end="" ) print( "%s " % ( binascii.hexlify( byte ).decode('utf-8') ), end="" ) i += 1 m += 1 byte = fd.read(1) line += byte if i % n == 0: # print() print("\t%s" % ( printable( line, plist ).decode('utf-8') ) ) line = b"" # print("\t%s" % ( printable( line ) ) ) last_ind = (1 + len(line)) * 3 totl_ind = n * 3 print("%s\t%s" % ( " "*(totl_ind - last_ind), printable( line, plist ).decode('utf-8') ) ) return m except Exception as e: raise if __name__ == "__main__": x = xorStr( "tets1tets1tets1tets1tets1tets1tets1tets1" ) e = enc( "Hello World, this a first xor test", x ) d = dec( e, x ) pprint( x ) pprint( e ) pprint( d ) fname = sys.argv[0] if len( sys.argv ) > 1: fname = sys.argv[1] print("#====================== %s ===================" % ( fname ) ) nbytes = file_n_bytes( fname, 32) print("#====================== %s bytes ===================" % ( nbytes ) )
f107e7687fce4c3031d193534d13818624023fbe
j-freimuth/CodingChallenge
/Word.py
1,975
3.703125
4
import copy allowedCharacters = "abcdefghijklmnopqrstuvwxyz" class Word: def __init__(self, word, targetWord = None): self.word = str.lower(word) self.createCharacterMap() if targetWord is not None: self.isValid = self.compare(targetWord) >= 0 # create a charmap counting all relevant chars def createCharacterMap(self): charMap = {} for character in self.word: if character not in allowedCharacters: continue if character in charMap: charMap[character] += 1 else: charMap[character] = 1 self.characterMap = charMap # compares two word objects def compare(self, targetWord): myWordChars = self.characterMap.keys() myWordCharsLength = len(myWordChars) targetWordChars = targetWord.characterMap.keys() targetWordCharsLength = len(targetWordChars) isPerfectMatch = True if myWordCharsLength > targetWordCharsLength: return -1 for char in myWordChars: if char not in targetWordChars: return -1 if self.characterMap[char] > targetWord.characterMap[char]: return -1 if self.characterMap[char] < targetWord.characterMap[char]: isPerfectMatch = False if myWordCharsLength < targetWordCharsLength: isPerfectMatch = False return 0 if isPerfectMatch else 1 # Merges two words together to a new word def mergeWords(self, otherWord): thisWord = copy.deepcopy(self) thisWord.word += " " + otherWord.word thisWord.characterMap = self.mergeMaps(thisWord.characterMap, otherWord.characterMap) return thisWord # Merges two maps together def mergeMaps(self, charMap1, charMap2): for key in charMap2.keys(): if key in charMap1: charMap1[key] += charMap2[key] else: charMap1[key] = charMap2[key] return charMap1
5d2de2c5a546e232c8836caa62fd6a305d272e52
GongFuXiong/leetcode
/topic13_tree/T110_isBalanced/interview.py
1,509
3.765625
4
''' 110. 平衡二叉树 给定一个二叉树,判断它是否是高度平衡的二叉树。 本题中,一棵高度平衡二叉树定义为: 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。 示例 1: 给定二叉树 [3,9,20,null,null,15,7] 3 / \ 9 20 / \ 15 7 返回 true 。 示例 2: 给定二叉树 [1,2,2,3,3,null,null,4,4] 1 / \ 2 2 / \ 3 3 / \ 4 4 返回 false 。 ''' import sys sys.path.append("..") # 这句是为了导入_config from T_tree.Tree import Tree import math class Solution: def get_height(self,root): if not root: return -1 return 1+max(self.get_height(root.left),self.get_height(root.right)) def isBalanced(self, root): if not root: return True if abs(self.get_height(root.left)-self.get_height(root.right))<2 and self.isBalanced(root.left) and self.isBalanced(root.right): return True if __name__ == "__main__": tree = Tree() solution = Solution() while 1: str1 = input() if str1 != "": node_list = str1.split(",") for node in node_list: tree.add(node) print(f"层次遍历:{tree.traverse(tree.root)}") res = solution.isBalanced(tree.root) print(res) else: break
287a55e3591c3bef384cd96ff2f2db3565adad0c
showsean/Myproject
/function_varargs.py
336
3.6875
4
def total(initial=5,*numbers,**keywords): count = initial for number in numbers: count += number print 'count is count+numbers',count for key in keywords: count += keywords[key] print 'count is count + numbers + keywords',count return count print total(10,1,2,3,vagetables=50,fruits=100)
f639b888b7e69c8ca19f2c19dd647c63bf26f01c
fiestas/python
/ej10.py
169
3.671875
4
import turtle turtle.pencolor("red") for i in range(500): # this "for" loop will repeat these functions 500 times turtle.forward(i) turtle.left(91) turtle.done()
3383facd64d89447eeeac38967bc077802081f0a
brandenchan/all_of_the_lights
/animation.py
1,161
3.828125
4
""" This contains the Animation class which generates a pygame animation of the lights """ import pygame import numpy as np import sys DIMENSIONS = (1000, 50) BLACK = (0, 0, 0) BORDER = 20 class Animation: def __init__(self): pygame.init() self.screen = pygame.display.set_mode(DIMENSIONS) self.screen.fill(BLACK) def draw_circles(self, values): coords, diameter = spacing(len(values), DIMENSIONS[0], DIMENSIONS[1], BORDER) radius = int(diameter / 2) for i, coord in enumerate(coords): pygame.draw.circle(self.screen, values[i], coord, radius) def update(self, values): self.draw_circles(values) pygame.display.update() for evt in pygame.event.get(): if evt.type == pygame.QUIT: pygame.quit() sys.exit() def spacing(n, width, height, border): xs = np.linspace(border, width - border, n).astype(int) y = [height - border] * n coords = zip(xs, y) diameter = xs[1] - xs[0] return coords, diameter
43c24c8c6bb449c87bca5e3ff5752f0b154013ab
kononovk/HomeTasks
/hw2/t02_perfnum.py
805
3.734375
4
from unittest import TestCase, main def is_perfect_number(inp_num): if type(inp_num) != int or inp_num < 1: raise ValueError("Input number must be natural") sum_of_dividers = 0 for i in range(1, inp_num): if inp_num % i == 0: sum_of_dividers += i if sum_of_dividers == inp_num: return True return False class Validator(TestCase): def test_false(self): self.assertFalse(is_perfect_number(1)) def test_true_1(self): self.assertTrue(is_perfect_number(6)) def test_true_2(self): self.assertTrue(is_perfect_number(28)) def test_list(self): self.assertRaises(ValueError, is_perfect_number, [6]) def test_negative_num(self): self.assertRaises(ValueError, is_perfect_number, -28) main()
22ea2a00550df94a8d0950a05a54e43381945143
Shulamith/csci127-assignments
/lab_04/lady.py
1,298
3.796875
4
#python allows you to hold integers and strings in list but most don't usually only dictionary/hashmaps/keyvalue pairs/map/hashtable def happyLadybugs(b): for character in b: if character!= "_" and b.count(character) == 1: return "No" if b.count("_")==0: i = 0 while i < (len(b)-1): #alternatively fo i in inrange(0, len(b)-1) if b[i] != b[i+1]: return "No" else: i+=1 ## if b[len(b)-1] != b[(len(b))-2]: ## return false ## else: return "yes" else: #I really should try to make the thing here #I wonder f I could see minimum amount of spaces rel to list needed to ensure possibility or to ensure that it is not solvable" return "yes" print("B,C",happyLadybugs(["B","C"])) print("B,B",happyLadybugs(["B","B"])) print("B,C,B",happyLadybugs(["B","C","B"])) print('B,C,B,C,_',happyLadybugs(["B","C","B","C","_"])) print("B","_","C","A","B","C","A",happyLadybugs(["B","_","C","A","B","C","A"])) print(happyLadybugs("AABBCCEE")) #Making a dictionary by adding a value each time #for bug in s: #counts.setdefault(bug,0) equivalent of if bug in counts.keys(): counts[bug} = counts[bug]+1 else: counts{bug}=1 #counts[bug]=counts[bug]+1
f33b42cb36dce900a5faa64cae5980d52da580c4
SteinarEinarsson/Verkefni01
/car_rental.py
1,412
3.84375
4
print('Welcome to car rentals!') contine_str = 'y' while contine_str == 'y': contine_str = input('Would you like to continue (y/n)? ') if contine_str == 'n': break customer_code = input('Customer code (b or d): ') number_days = input('Number of days: ') Odo_start = input('Odometer reading at the start: ') Odo_end = input('Odometer reading at the end: ') miles_total = int(Odo_end) - int(Odo_start) if customer_code == 'b': budget_cost = 40 base_cost = int(budget_cost) * int(number_days) miles_cost = float(miles_total)*0.25 amount_due = round((float(base_cost) + float(miles_cost)),1) print('Miles driven:', miles_total,'\nAmount due:',amount_due) elif customer_code == 'd': daily_cost = 60 base_cost = int(daily_cost) * int(number_days) av_miles = float(miles_total) / float(number_days) if float(av_miles) <= 100: extra_miles = 0 amount_due = float(base_cost) + float(miles_cost) print('Miles driven:', miles_total,'\nAmount due:',amount_due) else: extra_miles = (float(miles_total) / float(number_days)) - 100 miles_cost = float(extra_miles) * float(number_days) * 0.25 amount_due = float(base_cost) + float(miles_cost) print('Miles driven:', miles_total,'\nAmount due:',amount_due)
73172bb03e5ff93c76b67fe5aceee8e3369085e6
byron-hai/PythonOn
/algorithms/recursion/fabnacci.py
187
3.890625
4
#!/usr/bin/env python3 def fab(num): if num <= 0: raise ValueError("input must be greater than 0") else: return 1 if num < 3 else fab(num - 1) + fab(num - 2)
46334df89d8e5fdfc52a6c9599c1e57995a33de0
dvnesterov/PY101-october
/Tasks/dijkstra.py
1,170
3.75
4
import networkx as nx def dijkstra_algo(G, starting_node) -> dict: """ Count shortest paths from starting node to all nodes of graph G :param G: Graph from NetworkX :param starting_node: starting node from G :return: dict like {'node1': 0, 'node2': 10, '3': 33, ...}, where nodes are nodes from G """ visited = [] nodes = dict(G.nodes) for v in nodes: nodes[v] = float("inf") def getmincostnode(): nodewtmin = None wtmin = float("inf") for x in nodes.items(): if (x[1] < wtmin) and (x[0] not in visited): wtmin = x[1] nodewtmin = x[0] return nodewtmin node = starting_node endnode = None nodes[node] = 0 while node != endnode: visited.append(node) for nbr in G.neighbors(node): wt = G[node][nbr]['weight'] newcost = nodes[node] + wt if nodes[nbr] > newcost: nodes[nbr] = newcost node = getmincostnode() else: if node != None: visited.append(node) # print("visited", visited) # print("nodes", nodes) return nodes
9acecb45aa8ee187d5de969ea0fe6cfbb9bc32b9
arunvijay211/pypro
/multiples.py
125
3.96875
4
num=raw_input() print("Input:") print(num) sum=0 print("Output:") for i in range(1,6): sum=sum+int(num) print(sum)
71059d79e645d808b91c75d44832dba9bfab872c
mtmmy/Leetcode
/Python/0315_CountOfSmallerNumbersAfterSelf/countSmaller.py
2,139
3.5
4
import bisect class TreeNode: def __init__(self, val): self.val = val self.count = 1 self.left = None self.right = None class Solution: def add(self, node, val): curCount = 0 while 1: if val <= node.val: node.count += 1 if not node.left: node.left = TreeNode(val) break else: node = node.left else: curCount += node.count if not node.right: node.right = TreeNode(val) break else: node = node.right return curCount def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ if not nums: return [] root = TreeNode(nums.pop()) result = [0] for val in reversed(nums): result.append(self.add(root, val)) return result[::-1] def countSmallerBisect(self, nums: 'List[int]') -> 'List[int]': if not nums: return [] result, rank = [], [] for num in nums[::-1]: i = bisect.bisect_left(rank, num) result.append(i) rank[i:i] = num, return result[::-1] def countSmallerMergeSort(self, nums: 'List[int]') -> 'List[int]': result = [0] * len(nums) def sort(enum): half = len(enum) // 2 if half: left, right = sort(enum[:half]), sort(enum[half:]) for i in range(len(enum))[::-1]: if not right or left and left[-1][1] > right[-1][1]: result[left[-1][0]] += len(right) enum[i] = left.pop() else: enum[i] = right.pop() return enum sort(list(enumerate(nums))) return result # target = Solution() # target.countSmallerBisect([5,2,6,1])
e3f23ac8057cb0afcbc317de5e3450c85ac0187e
jodiezhu/leetcode_algo
/leetcode_57.py
1,323
3.703125
4
class Solution(object): def merge_intervals(self,intervals): if not intervals: return None sort_by_low=sorted(intervals,key=lambda x:x[0]) merge=[] for item in sort_by_low: if not merge: merge.append(item) else: if item[0]<=merge[-1][1]: upper_bound=max(merge[-1][1],item[1]) merge[-1]=[merge[-1][0],upper_bound] else: merge.append(item) return merge s=Solution() print(s.merge_intervals ([[1,3],[7,8],[2,5]])) ##way2:using Interval class: # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def insert(self, intervals, newInterval): s, e = newInterval.start, newInterval.end left, right = [], [] for i in intervals: if i.end < s: left += i, elif i.start > e: right += i, else: s = min(s, i.start) e = max(e, i.end) return left + [Interval(s, e)] + right s=Solution() ans=s.insert([Interval(1,3),Interval(6,9)],Interval(0,8)) print(ans[0].end)
da23ee15447a30cae5ee7d5d852e77bddc6070a9
EthanAwa/Movie_Fundraiser
/regex_test.py
391
4.03125
4
import regex strings = [ "Popcorn", "2 pc", "1.5OJ", "4OJ" ] for item in strings: number_regex = "^[1-9]" if regex.match(number_regex, item): amount = int(item[0]) snack = item[1:] else: amount = 1 snack = item snack = snack.strip() print("Amount:", amount) print("Snack:", snack) print("Length:", len(snack))
9448ea298b3cf2948713987344c528ff050eb114
VictorRiosM/RSA-authentication
/rsa_authentication/cgi-bin/modularExp.py~
269
3.671875
4
#!/usr/bin/python2 def modularExp(base, exponent, modulo): res = 1 pot = base % modulo while exponent > 0: if exponent % 2 == 1: res = (res * pot) % modulo pot = (pot * pot) % modulo exponent >>= 1 print res
6b1f83fd5e893516d551911083593da06318f1e5
nanodotpy/TurtleProjects
/Spirale de Fibonacci.py
927
3.6875
4
import turtle loadwindow = turtle.Screen() loadwindow.screensize(1920,1080) pen = turtle.Pen() pen.penup() pen.goto((-1920//5,1080//5)) pen.speed(3) pen.width(1) pen.pendown() def fibonacci(a = 1,b = 1) : fibo = [a,b] while fibo[-1]<800 : fibo.append(fibo[-1]+fibo[-2]) return fibo fibo = fibonacci(a=4,b=4) def quartercircle(radius): pen.circle(radius,90) def square(c): pen.pencolor("black") pen.forward(c) pen.left(90) pen.forward(c) pen.left(90) pen.forward(c) pen.left(90) pen.forward(c) def spiral_of_fibonacci(a) : initial = pen.pos() square(a) pen.pencolor("red") pen.speed("fastest") pen.goto(initial) pen.speed(3) pen.left(90) quartercircle(a) for a in fibo : spiral_of_fibonacci(a) pen.exitonclick()
b79bf293d2ebfd4f1df4d020679a49d2a05641ea
orhaneng/PythonUCSC
/venv/Classnotes/hw3_solution.py
2,156
4
4
''' # Question 1: 5 points Quadratic equations ''' class Quadratic: def __init__(self,a,b,c): self.a = a self.b = b self.c = c def __str__(self): return '%d x^2 + %d x + %d' %(self.a,self.b,self.c) def __add__(self,other): return Quadratic(self.a + other.a, self.b + other.b, self.c + other.c) def __sub__(self,other): return Quadratic(self.a - other.a, self.b - other.b, self.c - other.c) def __eq__(self,other): if(self.a == other.a and self.b == other.b and self.c == other.c): print("The two quadratic expressions are equal") return True else: print("The two quadratic expressions are not equal") return False q1 = Quadratic(3, 8, -5) q2 = Quadratic(2, 3, 7) print("The sum of the given quadratic expressions is ", q1 + q2) print("The difference of the given quadratic expressions is ", q1 - q2) print(q1 == q2) ''' # Question 2: 5 points Word counter ''' import string, csv class WordCounter: def __init__(self,filename): self.filename = filename self.contentlist = [] self.cleanlist = [] self.countdict = {} fo = open(self.filename,'r') for lines in fo.readlines(): lineitems = lines.strip().split() self.contentlist.extend(lineitems) def removepunctuation(self): for items in self.contentlist: cleanstring = items for c in string.punctuation: cleanstring = cleanstring.replace(c,"") if cleanstring != '': self.cleanlist.append(cleanstring) def findcount(self): uniqlist = list(set(self.cleanlist)) print uniqlist for items in uniqlist: self.countdict[items] = self.cleanlist.count(items) def writecountfile(self,csvfilename): writer = csv.writer(open(csvfilename, 'wb')) for key, value in self.countdict.items(): writer.writerow([key, value]) wc = WordCounter('red-headed-league.txt') wc.removepunctuation() wc.findcount() print(wc.countdict) wc.writecountfile('my4.csv')
caa5b426d7275d965231086c7451751c9cbecae0
Abdulrahimch/problemSet
/easy/is_anagram.py
235
4.125
4
def is_anagram(s: str, t: str) -> bool: for i in t: if i not in s: return False return True s, t = "anagram", "nagaram" str1, str2 = 'apple', 'apitte' print(is_anagram(s, t)) print(is_anagram(str1, str2))
5610568286da74f670303318414c1952b772482c
tyronedamasceno/Daily-Coding-Problem
/src/problem_33/solution.py
979
4.09375
4
""" Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element. Recall that the median of an even-numbered list is the average of the two middle numbers. For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out: 2 1.5 2 3.5 2 2 2 """ import unittest import bisect def solve(stream): ans = [] helper = [] for x in stream: bisect.insort(helper, x) h_sz = len(helper) if h_sz % 2 != 0: val = helper[h_sz//2] ans.append(val) else: val = helper[h_sz//2] + helper[(h_sz//2) - 1] ans.append(val/2) return ans class Tests(unittest.TestCase): def test_example1(self): stream = [2, 1, 5, 7, 2, 0, 5] expected = [2, 1.5, 2, 3.5, 2, 2, 2] ans = solve(stream) for i, x in enumerate(ans): self.assertEqual(expected[i], x)
53e6001abe725c52019a73421d70676d7e7e8341
joseangel-sc/CodeFights
/Arcade/AtTheCrossroads/KnapsackLight.py
1,468
3.84375
4
'''You found two items in a treasure chest! The first item weights weight1 and is worth value1, and the second item weights weight2 and is worth value2. What is the total maximum value of the items you can take with you, assuming that your max weight capacity is maxW and you can't come back for the items later? Example For value1 = 10, weight1 = 5, value2 = 6, weight2 = 4 and maxW = 8, the output should be knapsackLight(value1, weight1, value2, weight2, maxW) = 10. You can only carry the first item. For value1 = 10, weight1 = 5, value2 = 6, weight2 = 4 and maxW = 9, the output should be knapsackLight(value1, weight1, value2, weight2, maxW) = 16. You're strong enough to take both of the items with you. Input/Output [time limit] 4000ms (py) [input] integer value1 Constraints: 2 ≤ value1 ≤ 20. [input] integer weight1 Constraints: 2 ≤ weight1 ≤ 5. [input] integer value2 Constraints: 2 ≤ value2 ≤ 20. [input] integer weight2 Constraints: 2 ≤ weight2 ≤ 5. [input] integer maxW Constraints: 1 ≤ maxW ≤ 20. [output] integer''' def knapsackLight(value1, weight1, value2, weight2, maxW): temp = 0 if value1>value2: if weight1<maxW: temp += value1 maxW -= weight1 if weight2<maxW: temp += value2 else: if weight2<maxW: temp += value2 maxW -= weight2 if weight1<=maxW: temp += value1 return temp
db94c1e65f72374611bba09a84cc86bf555436a8
yajacob/algorithms
/std_algorithm/btree/binary_tree.py
3,334
3.84375
4
class BTree(): def __init__(self, data): self.data = data self.left = None self.right = None def add(tree, data): # if no data if tree == None: tree = BTree(data) return # add to the left if data < tree.data: if tree.left == None: tree.left = BTree(data) else: add(tree.left, data) # add to the right else: if tree.right == None: tree.right = BTree(data) else: add(tree.right, data) def largest(tree): # 1. no child = root is largest if tree.right == None: largest(tree.left) cur = tree while cur.right != None: cur = cur.right return cur.data def largest_2nd(tree): # 1. no child = root is largest if tree.right == None: largest(tree.left) cur = tree cur_pa = tree # get largest(cur) while cur.right != None: cur_pa = cur cur = cur.right # if largest has a left child if cur.left != None: largest(cur.left) else: return cur_pa.data # it doesn't work yet def remove(root, data): if root == None: return False if data == root.data: # 1. no child if root.left == None and root.right == None: root = None # 2-1. one child on left elif root.left != None and root.right == None: root = root.left # 2-2. one child on right elif root.left == None and root.right != None: root = root.right # 3. two child else: # 3.0 explore left side cur = root.right cur_pa = root.right while cur.left != None: cur_pa = cur cur = cur.left # 3.1 replace data from cur to root root.data = cur.data #3.2 root.right has no child if cur == cur_pa: root.right = None #3.3 if right has a child elif cur.right != None: cur_pa.left = cur.right else: cur_pa.left = None cur = None return elif data < root.data: remove(root.left, data) else: remove(root.right, data) def findHeight(root): if root == None: return -1 left_height = findHeight(root.left) right_height = findHeight(root.right) return max(left_height, right_height) + 1 def display(tree): if tree is None: return display(tree.left) print(tree.data, end=' ') display(tree.right) """ bt = BTree(25) add(bt, 10) add(bt, 13) add(bt, 23) add(bt, 14) add(bt, 4) add(bt, 42) display(bt) print("\nlargest:" + str(largest(bt))) print("\nlargest 2nd:" + str(largest_2nd(bt))) remove(bt, 23) display(bt) print("\nheight:" + str(findHeight(bt))) """ #********************************** def bstDistance(values, n, node1, node2): bt = BTree(values[0]) for i in range(len(values)): if i == 0: continue print(values[i]) add(bt, values[i]) values = [5,6,3,1,2,4] bstDistance(values, 6, 2, 4)
db1693913563322696d7f736b826a81640f246fb
Molocher/algorithm_python
/chapter4_快速排序/sum.py
530
3.671875
4
#!/usr/bin/env python # _*_ coding=utf-8 _*_ ''' @author:moloqu @file:sum.py @time:2020/5/30 15:02 ''' def sum(arr): if len(arr) == 0: return 0 else: head = arr[0] arr.pop(0) result = head + sum(arr) return result def count(arr): if len(arr) == 0: return 0 else: arr.pop(0) return (1 + count(arr)) if __name__ == '__main__': print(sum([1,2,3,4])) print(count([1,2,3,4,5])) # arr = [1,2,3,4] # print(arr.pop(0)) # print(arr)
5009c8b3c9e80fe0572aa78770cf7026bee13379
oliveira-julio/coding-challenge
/URI/Python/Beginner/2633/uri2633.py
880
3.765625
4
''' Product is (Name, Price) Price is a Int Name is a String ''' def parse_input(string): """ String -> Product """ name, price = string.split() return name, int(price) def sort_products(products): """ List Product-> List Product """ return sorted(products, key=lambda x: x[1]) def products_names(products): """ List Product -> List Name """ return list(map(lambda product: product[0], products)) def output(names): """ List Name -> String """ return ' '.join(names) if __name__ == "__main__": while True: try: times = int(input()) products = [] while times: products.append(parse_input(input())) times -= 1 print(output(products_names(sort_products(products)))) except EOFError: break
f28ace551df0286e9cb9ace58cd11e4699805f79
hyuraku/Python_Learning_Diary
/section2/func_in_func.py
156
3.984375
4
def outer(a,b): def plus(c,d): return c+d print(plus(a,b)+plus(b,a)) outer(2,2) #> 8 #plus(2,3) #この関数は外では使えない。
7d20427ce0ffd52dc05c6e659e787c972cd1ac90
msarch/pyramid
/pyramid.py
370
3.75
4
from vector import Vector, Spherical import math v1 = Vector([1,0,0]) v2 = Vector([0,1,0]) v3 = Spherical([1,90,90]) # GENERAL FUNCTIONS #-------------------------------------- def main(): print v1 print v2 print v3 w = Vector.dot(v1,v2) x = Vector.cross(v1,v2) print w print x if __name__ == '__main__': main()
344e2b17dfab7c0370bdda33372ef48f810fcf71
epfl-si/jahia2wp
/src/parser/box_sorted_group.py
1,372
3.59375
4
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2018""" from collections import OrderedDict class BoxSortedGroup: """ To group boxes that have to be sort using on of their property field """ def __init__(self, uuid, sort_field, sort_way): """ Class constructor :param uuid: uuid of sort handler :param sort_field: field used to sort :param sort_way: sort way ('asc', 'desc') """ self.uuid = uuid self.sort_field = sort_field self.sort_way = sort_way.lower() self.boxes = OrderedDict() def add_box_to_sort(self, box, sort_field_value): """ Add a box to the sort group. :param box: Instance of Box class or shortcode representing a Box :param sort_field_value: value to use to sort the group :return: """ self.boxes[sort_field_value] = box def get_sorted_boxes(self): """ Returns a list with sorted boxes Sort and returns this way is the only working way I found. Maybe it's possible to do better with less code lines :return: """ ordered_keys = sorted(self.boxes, reverse=(self.sort_way == 'desc')) box_list = [] for key in ordered_keys: box_list.append(self.boxes[key]) return box_list
40cd96eec15637a03f84eef45d76748634b072f3
KenyC/Shajara
/src/tree/__init__.py
7,429
3.703125
4
class Tree: """ Trees are stored in a flat representation Attributes: - children (list[list[int]): index i, self.children[i] is the set of indices that are children to i - labels (list[str]) : label of nodes IMPORTANT Always make sure that children always come after fathers """ def __init__(self, label = "", children = None): self.labels = [label] if children is None: self.children = [[]] else: self.children = children def merge_trees(children, label = ""): sums = [1] for child in children[:-1]: sums.append(sums[-1] + child.n) nodes = [[subnode + increment for subnode in node] for increment, child in zip(sums, children) for node in child.children] labels = sum([child.labels for child in children], [label]) t = Tree() t.children = [sums] + nodes t.labels = labels return t def sprout(self, idx, labelL = "", labelR = ""): """ Add two children to a leaf or adds a parent to an internal node, labels optional """ if not self.children[idx]: self.labels += [labelL, labelR] self.children[idx] += [self.n , self.n + 1] self.children += [[],[]] else: iFather = self.father(idx) self.insert_child(idx, labelR, [idx]) if iFather is not None: self.children[iFather] = [idx if x == idx + 1 else x for x in self.children[iFather]] self.labels.append(labelL) self.children.append([]) self.children[idx] = [self.n - 1] + self.children[idx] def father(self, idx): return (next( (j for j, child in enumerate(self.children) if idx in child), None)) def insert_child(self, idx, label = "", children = None): lookUpFun = lambda i: i if i < idx else (i + 1) if children is None: ch = [] else: ch = list(map(lookUpFun, children)) self.children = [list(map(lookUpFun, child)) for child in self.children] self.children.insert(idx, ch) self.labels.insert(idx, label) def make_reverse_polish(self, node = 0): for child in self.children[node]: for element in self.make_reverse_polish(child): yield element yield node def next_reverse_polish(self, node): """ Returns the node to the right of "node" when tree is linearized in reverse Polish notation """ polish_sequence = list(self.make_reverse_polish()) position = polish_sequence.index(node) return polish_sequence[(position + 1) % self.n] def previous_reverse_polish(self, node): """ Returns the node to the right of "node" when tree is linearized in reverse Polish notation """ polish_sequence = list(self.make_reverse_polish()) position = polish_sequence.index(node) return polish_sequence[(position - 1) % self.n] @property def n(self): return len(self.children) def delete(self, idx): """ Delete all children of node idx """ self.children[idx] = [] # Some nodes may no longer be connected to the root ; delete them self.trim() def accessible(self, idx = 0): """ Returns the list of descendants of node "idx" ("idx" included) """ l = [idx] for j in self.children[idx]: l.extend(self.accessible(j)) return l def leaves(self, node = 0): if self.children[node]: for child in self.children: for leaf in self.leaves(child): yield leaf else: yield node def trim(self): """ Remove nodes that are inaccessible from the root """ acc = self.accessible() # Stores the new position of nodes as function of the old position invAcc = {idx:i for i,idx in enumerate(acc)} # Creates new labels and children list from only the set of accessible nodes newLabels = [self.labels[idx] for idx in acc] newChildren = [self.children[idx] for idx in acc] # The position of nodes in the list has changed # Use the look-up table "invAcc" to replace old position of children with the new ones for i, cdren in enumerate(newChildren): newChildren[i] = [invAcc[c] for c in cdren] # Finally, update the tree with new values self.labels = newLabels self.children = newChildren def show(self, idx = 0, space = 0): """ Prints simple representation of tree in string format (for debugging purposes)""" print(space*" "+ (str(idx) if self.labels[idx] == "" else self.labels[idx])) for c in self.children[idx]: self.show(c, space + 1) def compute_display_positions(self, pos, **params): """ Computes position of nodes if root is at coordinate "pos" Display rules: - A leaf has a fixed width specified in "defaults". - The width of a subtree is the sum of width of his children. - A node's X coordinate is the average of its children's X coordinate (symmetry) - A node is always above its children by a height specified in "defaults". - Between adjacent sister nodes n1 and n2, there must be a gap of at least the width of n1 and the width of n2 (prenvents overlap) """ defaults = {"node_width": 60., "height_branch": 100., "node_widths": None, "height_branches": None} defaults.update(params) same_node_width = defaults["node_widths"] is None same_node_height = defaults["height_branches"] is None ### FIRST PASS # Computes the width of all subtrees # Computes the position of node with respect to left of the subtree it spans (mean position of children) # Looping from end to beginning makes sure we get to children before their mothers self.lgths = [0. for _ in self.labels] self.loc_in_segment = [0. for _ in self.labels] for i in range(self.n - 1, -1, -1): if not self.children[i]: if same_node_width: self.lgths[i] = defaults["node_width"] self.loc_in_segment[i] = defaults["node_width"] / 2 else: self.lgths[i] = defaults["node_widths"][i] self.loc_in_segment[i] = defaults["node_widths"][i] / 2 else: running_sum_length = 0. running_sum_child_pos = 0. for c in self.children[i]: running_sum_child_pos += running_sum_length + self.loc_in_segment[c] running_sum_length += self.lgths[c] n_children = len(self.children[i]) self.lgths[i] = running_sum_length self.loc_in_segment[i] = running_sum_child_pos / n_children ### SECOND PASS # Computes node position # Initialization to the position of root self.positions = [pos for i in range(self.n)] for i in range(self.n): if self.children[i]: # Current node position x_father, y_father = self.positions[i] # x_position of left edge left_edge = x_father - self.loc_in_segment[i] if same_node_height: height = defaults["height_branch"] else: height = defaults["height_branches"][i] + defaults["height_branch"] # Compute position of nodes for c in self.children[i]: self.positions[c] = (left_edge + self.loc_in_segment[c], y_father + height) left_edge += self.lgths[c] def copy(self): return Tree(self.labels[:],[child[:] for child in self.children]) def set(self, tree): self.children = tree.children self.labels = tree.labels if __name__ == "__main__": t1 = Tree(label = "t1.0") t1.sprout(0, labelL = "t1.1", labelR = "t1.2") t1.sprout(1, labelL = "t1.3", labelR = "t1.4") t2 = Tree(label = "t2.0") t2.sprout(0, labelL = "t2.1", labelR = "t2.2") t2.sprout(2, labelL = "t2.3", labelR = "t2.4")
9b544b37341018a68ee7efb40a489c94072f852c
genghaiyang626/w
/PycharmProjects/untitled/one.py
673
3.765625
4
# x=eval(input('输入第一个数字:')) # y=eval(input('输入第二个数字:')) # z=eval(input('输入第三个数字:')) # if x > y: # t=x # x=y # y=t # if x > z: # t = x # x = z # z = t # if y > z: # t = y # y = z # z = t # print('按有小到大的顺序排列') # print(x,y,z) # print('按有大到小的顺序排列') # print(z,y,x) # for i in range(1,101): # if i%3==0: # print(i) for i in range(1,5): for j in range(1,i+1): print('#',end="") print() for i in range(1,5): for k in range(1,i): print(' ',end="") for j in range(1,10-i*2): print('*',end="") print()