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
f7a815b3d22e89e076dbd469b1771959a5421d6a
Kushagrakmr/learning_python
/debugging/try_and_except.py
285
3.71875
4
# try: # foobar # except : # print("Error") # print("After Error handling") d = {"name" :"Kush"} # d["Kush"] def get(d, key): try: print(d[key]) except KeyError: print("The given value is not found in the dictionary.") get(d, "hello") get(d, "name")
0284e766d60cb1927876feb62af601c38977e9e9
motyzk/setsEx
/3.py
718
4.34375
4
# An element is in the result set if it is in the left set and not in the right set # >>> set([3, 4]) - set ([4, 5]) # set([3]) # when the sorted() function is executed on a set - it returns a sorted list, # consists of the elements of the set # >>> sorted(set([99,4,8])) # [4, 8, 99] import school # The principle will lecture to pupils who take no extra classes (literature, technology) # about the importance of expanding your horizons. # ----- ENTER SOME CODE HERE -------- take_no_extra_classes = ['I should be a sorted list of the names of the pupils who take no extra classes. FIX ME'] # ----------------------------------- print(take_no_extra_classes) assert take_no_extra_classes == ['Carl Hale', 'Ronald Tucker']
7df73af531338f699ce4e413f87007ffccdc1ce2
eroicaleo/LearningPython
/ch19/lambda.py
1,174
3.609375
4
#!/usr/local/bin/python3.3 f = lambda a, b, c: a+b+c print(f(2, 3, 4)) x = lambda a='fee', b='fie', c='foe': a+b+c print(x('wee')) def knights(): title = 'Sir' action = lambda x: title + ' ' + x return action act = knights() msg = act('Robin') print(msg) L = [lambda x: x ** 2, lambda x: x ** 3, lambda x: x ** 4, ] for f in L: print(f(2)) print(L[0](3)) # multiple branch switch D = { 'already': lambda: 2 + x, 'got' : lambda: 2 * 4, 'one' : lambda: 2 ** 6 } print(D['one']()) lower = (lambda x, y: x if x < y else y) print(lower('aa', 'bb')) print(lower('bb', 'aa')) import sys showall = lambda x: list(map(sys.stdout.write, x)) print(showall(["spam\n", "eggs\n", "ham\n"])) showall = lambda x: map(sys.stdout.write, x) print(list(showall(["spam\n", "eggs\n", "ham\n"]))) showall = lambda x: [print(line, end='') for line in x] showall(["spam\n", "eggs\n", "ham\n"]) showall = lambda x: print(*x, end='', sep='') showall(["spam\n", "eggs\n", "ham\n"]) def action(x): return lambda y: x+y act = action(99) print(act(2)) action = lambda x: lambda y: x+y act = action(101) print(act(3))
5dcb617ad6dc90480aa8b62fef55fab245a09c03
paldheeraj25/scrap
/scrape-shoe.py
3,667
3.5625
4
# module to fetch the url import urllib3 # module to query the page from bs4 import BeautifulSoup # cssutils import cssutils # url to be scraped shoe_url = "https://www.flipkart.com/mens-footwear/sports-shoes/pr?sid=osp%2Ccil%2C1cu&p%5B%5D=facets.brand%255B%255D%3DPuma&otracker=categorytree&page=" flipkart = 'https://www.flipkart.com' # query the url and return the object in the variable page http = urllib3.PoolManager() """ 40 urls in total, looping on each url to create soup object every url """ # initialize lists for data frame shoe_name = [] shoe_name_url = [] pic_url_0 = [] pic_url_1 = [] pic_url_2 = [] pic_url_3 = [] pic_url_4 = [] pic_url_5 = [] pic_url_6 = [] pic_url_7 = [] pic_url_8 = [] pic_url_9 = [] # function: append url in the list def append_list(list_name, elem_url): image_url = '' if elem_url is not None: # from image element extract url using cssutils style = cssutils.parseStyle(elem_url.get('style')) image_url = style['background-image'] # cleaning the url IMPORTANT: This is getting url with 128 by 128 change it to 400 by 400 image_url = image_url.replace('url(', '').replace(')', '') # append in corresponding list if list_name == 0: pic_url_0.append(image_url) if list_name == 1: pic_url_1.append(image_url) if list_name == 2: pic_url_2.append(image_url) if list_name == 3: pic_url_3.append(image_url) if list_name == 4: pic_url_4.append(image_url) if list_name == 5: pic_url_5.append(image_url) if list_name == 6: pic_url_6.append(image_url) if list_name == 7: pic_url_7.append(image_url) if list_name == 8: pic_url_8.append(image_url) if list_name == 9: pic_url_9.append(image_url) total_shoe_count = 1 # loop for pagination and iterate every page in the pagination, for page in range(1, 40): shoe_page_url = shoe_url + str(page) # print(shoe_page_url) # Get the dome for soup from url shoe_list_response = http.request('GET', shoe_page_url) # create soup object from the fetched dome soup = BeautifulSoup(shoe_list_response.data, 'html.parser') # get shoe names, contain in the element with class _2cLu-l names = soup.find_all('a', class_='_2cLu-l') # print(len(names)) # shoe on given page counter page_shoe_count = 1 # iterate on every shoe in the given page from the single pagination page for name in names: # get shoe name shoe_name.append(name.get('title')) # get url for particular shoe store shoe_spec_url = flipkart+name.get('href') # get shoe url shoe_name_url.append(shoe_spec_url) # get the dome object for shoe store shoe_store_response = http.request('GET', shoe_spec_url) # create soup object for shoe store shoe_store_soup = BeautifulSoup( shoe_store_response.data, 'html.parser') # from shoe store get all images from the link shoe_store_images = shoe_store_soup.find_all('div', class_='_2_AcLJ') # storing different urls in lists for shoe_pic in range(0, 10): if shoe_pic in range(0, len(shoe_store_images)): append_list(shoe_pic, shoe_store_images[shoe_pic]) else: append_list(shoe_pic, None) # break outer loop, To help with the pagination page debug # break print('iterating shoe {} on {} page of pagination, total shoe collected: {}'.format( page_shoe_count, page, total_shoe_count)) page_shoe_count += 1 total_shoe_count += 1
28ec64accb84b0853d461c1497ba3afc5d7fa691
HyPerSix/PythonCoding
/Coding/job.py
472
3.890625
4
def get_input(): name=input("Enter ur name : ") age=int(input("Enter ur age : ")) job=input("Enter ur jobs : ") return name,age,job name,age,job=get_input() point = 0 if name[0] == 'O': point += 1000 if age <= 24: point = point-300 if job == "Student" or job == "Programmer" : point -= 300 print(point) if point > 500 : print("You've got money !!!") else: print("You're not passed ,sorry.")
4658ccce9a43808f4e8ef1af1817f9ebf2b54120
cifpfbmoll/practica-7-python-JLCardona
/E11.py
498
3.765625
4
from os import system system("cls") def pal(frase): for i in range (len (frase)): if frase[i] == " ": fraseA = frase.replace(frase[i],"") A = 0 B = 0 for i in reversed (range (len (fraseA))): if fraseA[i].lower() == fraseA[B].lower(): A += 1 B += 1 if len (fraseA) == A: return "Tu frase es un palíndromo :)" else: return "Tu frase no es un palíndromo :(" frase = input ("Escribeme una frase : ") print (pal (frase))
cc9f0088aa89a572b31bcc57fa9f859f91285e0a
aadarshraj4321/Python-Small-Programs-And-Algorithms
/Data Structure Problems/Tree/balanced_tree.py
931
3.78125
4
class Node: def __init__(self, value): self.data = value self.left = None self.right = None # Binary Tree Class class BinaryTree: def isBalanced(self, root): pass def takeInput(self): data = int(input()) if(data == -1): return root = Node(data) left = self.takeInput() right = self.takeInput() root.left = left root.right = right return root def printTree(self, root): if(root == None): return None print(root.data, end = ":") if(root.left != None): print(" L ", root.left.data, end = " , ") if(root.right != None): print(" R ", root.right.data) print() self.printTree(root.left) self.printTree(root.right) bt = BinaryTree() root = bt.takeInput() bt.printTree(root)
7f04c7cf3f7e736f197ca5374a4a9ae3d9930ab5
AbdelrahmanShehab/Hangman_In_Python
/main.py
965
4
4
import random from hangman_art import logo, stages import hangman_words game_over = False chosen_word = random.choice(hangman_words.word_list) word_length = len(chosen_word) lives = 6 print(logo) print(f'Pssst, the solution is {chosen_word}.') display = [] for _ in range(word_length): display += '_' while not game_over: guess = input("Guess a letter: ").lower() if guess in display: print(f"You've already guessed {guess}") for position in range(word_length): letter = chosen_word[position] if letter == guess: display[position] = letter if guess not in chosen_word: print(f"You guessed {guess}, thats not in the word. You lose a life") lives -= 1 if lives == 0: game_over = True print("You Lose") print(f"{' '.join(display)}") if '_' not in display and lives > 0: game_over = True print("You Win") print(stages[lives])
fe1247af0516f46c40c82524942b7f12b4ffb336
cxzzzz/algorithms
/leetcode/546.移除盒子.py
1,127
3.546875
4
# # @lc app=leetcode.cn id=546 lang=python3 # # [546] 移除盒子 # # https://leetcode-cn.com/problems/remove-boxes/description/ # # algorithms # Hard (42.96%) # Total Accepted: 235 # Total Submissions: 547 # Testcase Example: '[1,3,2,2,2,3,4,3,1]' # # 给出一些不同颜色的盒子,盒子的颜色由数字表示,即不同的数字表示不同的颜色。 # 你将经过若干轮操作去去掉盒子,直到所有的盒子都去掉为止。每一轮你可以移除具有相同颜色的连续 k 个盒子(k >= 1),这样一轮之后你将得到 k*k # 个积分。 # 当你将所有盒子都去掉之后,求你能获得的最大积分和。 # # 示例 1: # 输入: # # # [1, 3, 2, 2, 2, 3, 4, 3, 1] # # # 输出: # # # 23 # # # 解释: # # # [1, 3, 2, 2, 2, 3, 4, 3, 1] # ----> [1, 3, 3, 4, 3, 1] (3*3=9 分) # ----> [1, 3, 3, 3, 1] (1*1=1 分) # ----> [1, 1] (3*3=9 分) # ----> [] (2*2=4 分) # # # # # 提示:盒子的总数 n 不会超过 100。 # # class Solution: def removeBoxes(self, boxes: List[int]) -> int:
620874a50984321b4617d2bf5b3c0b4496640c2a
Erica9Wang/PythonClass
/investigate texts and calls/ZH/Task2.py
2,048
3.75
4
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务2: 哪个电话号码的通话总时间最长? 不要忘记,用于接听电话的时间也是通话时间的一部分 (计算主叫时间同时加上其他电话打进来的被叫时间)。 输出信息: "<telephone number> spent the longest time, <total time> seconds, on the phone during September 2016.". 提示: 建立一个字典,并以电话号码为键,通话总时长为值。 这有利于你编写一个以键值对为输入,并修改字典的函数。 如果键已经存在于字典内,为键所对应的值加上对应数值; 如果键不存在于字典内,将此键加入字典,并将它的值设为给定值。 """ telephone_time_dic = {} #dictionary: key: telephone number / value: total time for call in calls: if call[0] in telephone_time_dic: telephone_time_dic[call[0]] += int(call[3]) if call[1] in telephone_time_dic: telephone_time_dic[call[1]] += int(call[3]) else: telephone_time_dic[call[1]] = int(call[3]) else: telephone_time_dic[call[0]] = int(call[3]) if call[1] in telephone_time_dic: telephone_time_dic[call[1]] += int(call[3]) else: telephone_time_dic[call[1]] = int(call[3]) telephone_time=[] for telephone_number in telephone_time_dic: telephone_time.append(telephone_time_dic[telephone_number ]) longest_time = max(telephone_time) longest_time_number = '' for telephone_number in telephone_time_dic: if telephone_time_dic[telephone_number] == longest_time: longest_time_number = telephone_number print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(longest_time_number, longest_time))
d399fb72c9031d41c96f5e7b41430a556fbbd78a
mohamedmolu1/magic-Numbers-in-Python
/main.py
2,187
4.4375
4
# understand lists ,[]<<< this containts the list numbers = [0,1,2,3,4,5,6,7,8,9] print(numbers) # a list also contain lengths so if we use the len() method we get amount of numbers aboive which is 10 print(len(numbers)) # Now we inorder to get the last number "9" we use type. The first element in coding for example the above sequence will show that 1 = 0, 2= 1 and so on. print(numbers[1]) # now in order to get the number 9 we can use the len method however below will show print([len(numbers)-1]) # in order to list all the numbers we are going to use the "for loop" method it will assign the numbers to number varibale for number in numbers: print(number) # I am now going to multiply the list to the power of 2 for number in numbers: print(number**2) # we are going to use boolean - it decides whether something is True or False. We are figuring out if 5 is greater than 3. print(numbers) greater_than_three = 5 > 3 print(greater_than_three) equal_to_five = 5 == 5 print (equal_to_five) # here I used the boolean method to check if all the numbers in the list were greater than 5 print(numbers) # we are using the "if" statement to get another form of responses. for number in numbers: print(number > 5) if 5 > 3: print("Five is greater than three") if 3 < 5 : print("this should not happen") # now to get the numbers printed that are greater than 5 with the boolean expression within in for number in numbers: if number > 5 : print(number) # we are going to look at "in" keyword print(10 in numbers) # we are going to create out magic numbers app magic_numbers = [3,9] user_number = 4 if user_number in [3,9]: print("okay") else: print("try again ") # we imported a package called random which enables the user type any number and still get it wrong basically. import random # used the random method to pick out what would be the smallest number in value against 100 or against the list of random values. minimum = 100 for index in range(10): random_number = random.randint(0,100) print("the number is {}". format(random_number)) if random_number <= minimum: minimum = random_number print(minimum)
f55a34a8d4b4fb2e6811749841914c2f903c7089
ashutoshkrris/Data-Structures-and-Algorithms-in-Python
/Recursion/stringify_numbers.py
429
3.515625
4
def stringify_numbers(obj): new_obj = obj for key in new_obj: if type(new_obj[key]) is int: new_obj[key] = str(new_obj[key]) if type(new_obj[key]) is dict: new_obj[key] = stringify_numbers(new_obj[key]) return new_obj obj1 = { "num": 1, "list": [], "data": { "val": 4, "isRight": True, "random": 66 } } print(stringify_numbers(obj1))
2c4ef694d9016ecb3a4ea6e02aa448dbec398a7a
CrackedCode7/Udemy-Learning
/printandinput/printFun.py
858
4.5625
5
print() print('Hello'*3) # basic multiplication of a string '''You can add \n to add a newline to a string so part of the output spans multiple lines''' print("All the power \n is within you") a,b=10,20 print(a,b,sep=',') # separator SEP used to define what separates print values print(a,b,sep='\n') print(a,b,sep='+++') name="John" marks=94.5678 print("Name is",name,"marks are",marks) # one way to print strings together with varibales print("Name is %s marks are %.2f"%(name,marks)) # %s is a string placeholder, %i integer, %f float '''Above .2f is used to only display 2 numbers after the decimal''' # braces with format can also be used as a string placeholder print("Name is {} marks are {}".format(name,marks)) # You can also use indices in the braces that correspond to order in format print("Name is {0} marks are {1}".format(name,marks))
4099b3fbfa1a933b85a51fcd10598cebae27c2b2
GerogeLiu/pyDemos
/01 getMoocMedia/download.py
2,712
3.53125
4
import os import requests from urllib import error # 下载路径选择 def select_direction(courseName): currentDir = os.getcwd() currentDir = currentDir.replace("\\", "/") # 美化显示 path = input(f'>>> 请输入保存路径:(默认在当前路径{currentDir}下创建"{courseName}"文件夹)\n>>> ') # 获得当前文件夹 if not path: path = currentDir + "/" + courseName if not os.path.isdir(path): # 检测是否是文件夹 os.mkdir(path) # 在当前目录下创建文件夹,path = 相对路径 return path # 下载文件 def download(url, direction, fileName, fileType, mode="bigfile"): # 文件的绝对路径,如 D:\Program Files\Python36\python.exe abs_fileName = '{}/{}.{}'.format(direction, fileName, fileType) renameCount = 0 while True: # 检查是否重名 if os.path.exists(abs_fileName): renameCount += 1 abs_fileName = '{}/{}-{}.{}'.format(direction, fileName, renameCount, fileType) else: break # 小文件模式:直接下载 if mode is not 'bigfile': try: r = requests.get(url) r.raise_for_status() with open(abs_fileName, 'wb') as file: file.write(r.content) except requests.HTTPError as ex: print('[-]ERROR: %s' % ex) except KeyboardInterrupt: os.remove(abs_fileName) raise return # 大文件模式:分块下载 try: r = requests.get(url, stream=True) r.raise_for_status() if 'Content-Length' not in r.headers: raise requests.HTTPError('No Content Length') file_size = int(r.headers['Content-Length']) # 文件大小:B if file_size < 10 * 1024 * 1024: chunk_size = 1024 * 1024 # 分块大小 B else: chunk_size = 3 * 1024 * 1024 download_size = 0 # 已下载大小:B with open(abs_fileName, 'wb') as file: for chunk in r.iter_content(chunk_size=chunk_size): progress = download_size / file_size * 100 # 下载进度 prompt_bar = '[{:50}] {:.1f}%\tSize: {:.2f}MB'.format( '=' * int(progress / 2), progress, download_size / 1024 / 1024) print(prompt_bar, end='\r') # \r 代表打印头归位,回到某一行的开头 file.write(chunk) download_size += chunk_size print('[{:50}] 100% Done!\tSize: {:.2f}MB'.format('=' * 50, file_size / 1024 / 1024)) except error.HTTPError as ex: print('[-]ERROR: %s' % ex) except KeyboardInterrupt: os.remove(path) raise
1dcda649ec6a6240d65724dffcd73bf5667c4a76
panumas300/project1
/september 22/Listoperator.py
229
3.875
4
even_numbers = [2,4,6,8,10] heroes = ['Ironman','Thor','Hulk','Spiderman'] numbers = [1,2,3,4,5,6,7,8,9,10] print(numbers[-5:]) numbers[8] = 99 print(numbers) pluslist = heroes + even_numbers print(pluslist) print(len(numbers))
f8324917de4e91879bfb0963856961e4eda00867
EvanEPrice/Euler-Python
/problems/Problem9.py
263
3.96875
4
#There exists exactly one Pythagorean triplet for which a + b + c = 1000. #Find the product abc. import math for a in range(1, 1000): for b in range(1, 1000): c = math.sqrt(a*a + b*b) if a + b + c == 1000: print(a*b*c)
6595ff127bc8a4c823f4b028eb2a14af34843b10
candyer/leetcode
/validMountainArray.py
1,271
4
4
# https://leetcode.com/problems/valid-mountain-array/description/ # 941. Valid Mountain Array # Given an array A of integers, return true if and only if it is a valid mountain array. # Recall that A is a mountain array if and only if: # A.length >= 3 # There exists some i with 0 < i < A.length - 1 such that: # A[0] < A[1] < ... A[i-1] < A[i] # A[i] > A[i+1] > ... > A[B.length - 1] # Example 1: # Input: [2,1] # Output: false # Example 2: # Input: [3,5,5] # Output: false # Example 3: # Input: [0,3,2,1] # Output: true # Note: # 0 <= A.length <= 10000 # 0 <= A[i] <= 10000 def validMountainArray(A): """ :type A: List[int] :rtype: bool """ n = len(A) if n < 3: return False i = 0 while i < n - 1: if A[i] < A[i + 1]: i += 1 elif A[i] == A[i + 1]: return False else: break if i in [0, n - 1]: return False while i < n - 1: if A[i] <= A[i + 1]: return False else: i += 1 return True assert validMountainArray([3,3,3]) == False assert validMountainArray([2,1]) == False assert validMountainArray([3,5,5]) == False assert validMountainArray([0,3,2,1]) == True assert validMountainArray([0,3,4,5]) == False assert validMountainArray([5,4,3,2]) == False assert validMountainArray([5,4,3,2,2]) == False
70f0a50bc216cc7588c74c98dbfa3aae6ef781ef
cljacoby/leetcode
/src/climbing-stairs/climbing-stairs.py
845
3.921875
4
# https://leetcode.com/problems/climbing-stairs class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ self.cache = dict() self.cache[1] = 1 self.cache[2] = 2 return self._step(n) def _step(self, n): if n in self.cache: return self.cache[n] a = self._step(n - 1) b = self._step(n - 2) c = a + b self.cache[n] = c return c if __name__ == "__main__": sol = Solution() tests = [ (2, 2), (3, 3), ] for (n, solution) in tests: result = sol.climbStairs(n) print(f"n={n}, solution={solution}, result={result}") assert result == solution, \ f"result={result} != solution={solution}" print("✅ All tests passed")
fbbde862c025550cd630dc75bca596c2bfe87ae9
fgoingtob/python
/add.py
87
3.578125
4
x = input( "enter first:" ) y = input( "enter second:" ) z = int(x) + int(y) print z
50203df4ea1f8d860feea604cd11039116ce9acb
xuefly09/Python
/ps3pr2.py
668
3.609375
4
def abs_list_lc(values): return [abs(x) for x in values] def abs_list_rec(values): if len(values) == 0: return print('values is empty!') if len(values) == 1: return [abs(values[0])] else: res_list = abs_list_lc(values[1:]) return [abs(values[0])] + list(res_list) def num_factors(x): if x == 0: print('Zero doesn\'t have factors!' ) else: abs_x = abs(x) factors_list = [i for i in range(1, abs_x + 1) if abs_x%i == 0] return len(factors_list) def most_factors(values): number_list = [[num_factors(x), x] for x in values] return max(number_list)[1]
7039d77ba65e7395557585b0deb0453c9d55cd80
chiamtw95/MastermindGame
/mastermind.py.py
5,223
4.21875
4
#This program is a game called "Mastermind" import random global puzzleLength puzzleLength = 4 #main function def main(): #Initiate Variables colourList = [ 'red' , 'blue' , 'green'] #List of colours answerList = [] #List of answers from user guesses = 0 #Counter for guesses solved = False #Default state of the game answerList = generateRandomColours(colourList) #Generate the answers #Sequences of functions for the game setup() #Give instructions to teach users how to play while solved == False: userAnswer =getAnswer() #Function that gets user input guesses = countGuess(guesses) #Function that keeps track the amount of guesses correctPosition = checkColours(answerList,userAnswer) #Function to analyse user input solved = isitSolved(correctPosition) #Function to check whether the puzzle is solved print(f"Congratulations! You have solved the puzzle in {guesses} steps.") ### ###Function definitions here ### #Print instructions to teach users how to play def setup(): print("Welcome to Mastermind!") print(f"To win, guess the random generated sequence of {puzzleLength} colours in correct order.") print("Give your answer comma-seperated, like the following:") print("red,green,blue,red") #Function to generate random colours and store into rColourList def generateRandomColours(colourList): rColourList= [] # Empty list of random colours for _i in range(puzzleLength): rColour = random.choice(colourList) rColourList.append(rColour) return rColourList #Function to get answer/input from user def getAnswer(): while True: answerList= [] #Empty list to store answers validAnswerList=[] #Empty list to store answer that are str only answer = input("Answer:") #Gets user input answer = answer.lower() #Convert user input to lowercase answerList = answer.split(sep=',') #Convert user input from string to list #Answer checks/filtering if answer.count(',')< puzzleLength: #checks for extra ',' given from user #Input validation and converting answer from str -> list for i in answerList: if i.isdigit() == False and i=='red' or i=='green' or i=='blue': validAnswerList.append(i) else: print("Input incorrect. Please check spelling and try again.") break #Validation checks to answerList if len(validAnswerList) == puzzleLength: #Sufficient valid inputs break elif len(validAnswerList) > puzzleLength: #Too many arguments case print("Too many arguments. Please try again") elif len(validAnswerList) < puzzleLength and len(answerList)!= puzzleLength: #Too little arguments case print("Too little arguments. Please try again") else: print("Too many arguments or extra comma found. Please try again") return validAnswerList #Function to keep track the number of guesses def countGuess(guesses): guesses +=1 return guesses #Function to check how many colours the user got correct def checkColours(answerList,userAnswer): correctColours = 0 # correct answers with N + colour Nred = answerList.count('red') Nblue = answerList.count('blue') Ngreen = answerList.count('green') # user input with small n + colour nred = userAnswer.count('red') nblue = userAnswer.count('blue') ngreen = userAnswer.count('green') #The case where the user has more Reds than the actual answer if nred >= Nred: cred = Nred else: cred = nred #The case where the user has more Blue than the actual answer if nblue > Nblue: cblue = Nblue else: cblue = nblue #The case where the user has more Green than the actual answer if ngreen > Ngreen: cgreen = Ngreen else: cgreen = ngreen #Now we have amount of colours the user guessed correctly correctColours = cred + cgreen + cblue # Now we analyse the number of correctly guessed positions of colours correctPositions = 0 for i in range(len(answerList)): if answerList[i] == userAnswer[i]: correctPositions += 1 if correctPositions == 4: pass else: print(f"Correct colour in the correct place: {correctPositions}") print(f"Correct colour but in the wrong place: {correctColours - correctPositions}") return correctPositions #function to check whether the user managed to guess the answer correctly def isitSolved(correctPositions): if correctPositions == puzzleLength: return True else: return False if __name__ == "__main__": main()
f8d47c2d3c80d3886c9357a44cd0d97349bde9c2
huangke19/LeetCode
/485/485.py
1,014
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 1. 检查先决条件 2. 定义子程序要解决的问题 3. 为子程序命名 4. 决定如何测试子程序 5. 在标准库中搜寻可用的功能 6. 考虑错误处理 7. 考虑效率问题 8. 研究算法和数据类型 9. 编写伪代码 1. 首先简要地用一句话来写下该子程序的目的, 2. 编写很高层次的伪代码 3. 考虑数据 4. 检查伪代码 10. 在伪代码中试验一些想法,留下最好的想法 ''' class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ max_ = 0 count = 0 for i in nums: if i == 1: max_ += 1 if count < max_: count = max_ else: max_ = 0 return count if __name__ == '__main__': solution = Solution() print(solution.findMaxConsecutiveOnes([1, 0, 1, 1, 1, 0, 1]))
7157c2cf1d2006a5dd01b3e893315c46bf5c7cf6
kackburt/restaurantmenuPy
/restaurantmenu.py
773
3.953125
4
print("Welcome to your restaurant menu - add dishes to your daily menu list.") # Taskmanager yes = ['yes', 'y'] save = ['save', 's', 'exit', 'e', 'x'] menu = {} currency = raw_input("Enter a currency for your menu: ") while True: dish = raw_input("Enter a dish for the menu: ") price = float(raw_input("Enter a price for '%s' " % dish)) menu[dish] = price newdish = raw_input("Do you want to add another dish (y)es or (s)ave and (e)xit. ") if newdish.lower() in yes: continue elif newdish.lower() in save: with open("menu.txt", "w+") as menu_file: for dish in menu: menu_file.write("%s, %s, %s\n" % (dish, menu[dish], currency)) break print("Your menu includes now: ") + str(menu)
d1fbd75924fc92f2c9eb623d2bb1182e6b406bc0
braucci/developing
/plot_funzione_drawnstyle.py
421
3.625
4
# # How To Make Hand-Drawn Style Plots In Python # import numpy as np import matplotlib.pyplot as plt # Python gives us the option to make xkcd style # plots using the matplotlib library. #f(x) = sin(x) f = lambda x:np.sin(x) xi=0 xf= 2*np.pi n=100 x=np.linspace(xi,xf,n) y = f(x) with plt.xkcd(): plt.figure(1) plt.title('f(x)') plt.plot(x,y) plt.xlabel('x') plt.ylabel('y') plt.grid(True) plt.show()
13bffc852c220d6fa209ffb45bcc7177df19cf8e
hysapphire/leetcode-python
/src/100.相同的树.py
703
3.6875
4
# # @lc app=leetcode.cn id=100 lang=python3 # # [100] 相同的树 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: return self.is_equal(p, q) def is_equal(self, left, right): if not left and not right: return True elif not left or not right: return False return left.val == right.val and self.is_equal(left.left, right.left) and self.is_equal(left.right, right.right) # @lc code=end
9b200f83cd804f2391a8b01167d0629538ec50d5
bhavinidata/DataStructuresAndAlgorithms
/TreesAndGraphs/isValidBST.py
3,402
4.34375
4
# Given a binary tree, determine if it is a valid binary search tree (BST). # Assume a BST is defined as follows: # The left subtree of a node contains only nodes with keys less than the node's key. # The right subtree of a node contains only nodes with keys greater than the node's key. # Both the left and right subtrees must also be binary search trees. # Example 1: # 2 # / \ # 1 3 # Input: [2,1,3] # Output: true # Example 2: # 5 # / \ # 1 4 # / \ # 3 6 # Input: [5,1,4,null,null,3,6] # Output: false # Explanation: The root node's value is 5 but its right child's value is 4. # ============================================================================ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isValidBST(self, root: TreeNode) -> bool: """ :type root: TreeNode :rtype: bool """ stack, prev = [], float('-inf') while stack or root: while root: stack.append(root) root = root.left root = stack.pop() # If next element in inorder traversal # is smaller than the previous one # that's not BST. if root.val <= prev: return False prev = root.val root = root.right return True if __name__ == '__main__': solution = Solution() root = TreeNode(2) root.left = TreeNode(1) root.right = TreeNode(3) # root = TreeNode(5) # root.left = TreeNode(3) # root.right = TreeNode(7) # root.left.left = TreeNode(1) # root.left.right = TreeNode(4) # root.right.left = TreeNode(6) # root.right.right = TreeNode(9) if (solution.isValidBST(root) == True): print("Is valid BST") else: print("Not a BST") # ============================================================== # NEED TO REVISIT THIS PORTION AND UNDERSTAND THE RECURSIVE FUNCTION. # class Solution: # # sortArray = [] # def isValidBST(self, root: TreeNode) -> bool: # print(f"first root value: {root.val}") # global sortArray # sortArray = [] # if root.left: # print(f"left going: {root.val}") # self.isValidBST(root.left) # print(f"ROOT: {root.val}") # sortArray.append(root.val) # # print(f"sorted after left: {sortArray}") # if root.right: # print(f"right going: {root.val}") # self.isValidBST(root.right) # # if root.left == None and root.right == None: # # print(f"sorted at last: {sortArray}") # return sortArray # if __name__ == '__main__': # solution = Solution() # # root = TreeNode(2) # # root.left = TreeNode(1) # # root.right = TreeNode(3) # root = TreeNode(5) # root.left = TreeNode(3) # root.right = TreeNode(7) # root.left.left = TreeNode(1) # root.left.right = TreeNode(4) # root.right.left = TreeNode(6) # root.right.right = TreeNode(9) # resArray = solution.isValidBST(root) # print(f"REsult Array: {resArray}") # sArray = resArray.sort() # if sArray == resArray: # print("Is valid BST") # else: # print("Not a BST")
ab046eaf6055e1ec20094d038cec92465613e5b9
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_135/2082.py
1,309
3.515625
4
def solve(answer_a, answer_b, board_a, board_b): row_a = board_a[answer_a-1] row_b = board_b[answer_b-1] intersection = set(row_a).intersection(row_b) if not intersection: return 'Volunteer cheated!' if len(intersection) > 1: return 'Bad magician!' else: return intersection.pop() def main(fin, fout): """steps: 1) read data from fin 2) operate on data 3) write answers to fout Note: fin is read-only and fout allows writing""" ## methods for reading from and writing to file objects: ## http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects T = int(fin.readline().strip()) for t in xrange(T): answer_a = int(fin.readline().strip()) board_a = [map(int, fin.readline().strip().split()) for _ in xrange(4)] answer_b = int(fin.readline().strip()) board_b = [map(int, fin.readline().strip().split()) for _ in xrange(4)] solution = solve(answer_a, answer_b, board_a, board_b) fout.write('Case #{}: {}'.format(t+1, solution) + '\n') # print 'Case #{}: {}'.format(t+1, solution) if __name__ == '__main__': with open('A-small-attempt0.in', 'r') as fin: with open('A-small.out', 'w') as fout: main(fin, fout) print 'done!'
7ad23ca35f1ad43993dd9e46dc74f6ee4c6d1d80
sotsoguk/elementsOfPI
/ch11/11_7_minmax.py
1,311
3.5625
4
import random def minmax(a): # find the min and max simultanously if not a: return (-1,-1) if len(a) == 1: return a[0],a[0] a_min = min(a[0],a[1]) a_max = max(a[0],a[1]) if len(a) == 2: return a_min,a_max upper_range_bound = len(a)-1 # if len(a) %2 : # upper_range_bound = upper_range_bound//2 * 2 for i in range(2,upper_range_bound,2): local_min, local_max = 0,0 if a[i] < a[i+1]: local_min = a[i] local_max = a[i+1] else: local_min = a[i+1] local_max = a[i] a_min = min(a_min,local_min) a_max = max(a_max,local_max) # a_min = min(a[i],a_min) # a_max = max(a[i+1],a_max) # elif a[i] > a[i+1]: # a_min = min(a[i+1],a_min) # a_max = max(a[i],a_max) # else: # a_min = min(a_min,a[i]) # a_max = min(a_max,a[i]) if len(a) % 2: a_min = min(a_min,a[len(a)-1]) a_max = max(a_max,a[len(a)-1]) return a_min, a_max if __name__ == "__main__": num_ints = 10 range_ints = [0,20] a = [0] * num_ints for i in range(num_ints): a[i] = random.randint(range_ints[0],range_ints[1]) a = [1,2,3,4] print(a) print(minmax(a))
aaae559eab134526a88aa5cd4e04728f5d76c9ef
ShubhangiDabral13/Pythonic_Lava_Coding_Question
/GeeksForGeeks/gfg-Amazon/Pairwise Swap Element/Swap_Pairwise_Element.py
1,311
4.25
4
class Node: def __init__(self,data): self.data = data self.next = None class Linked_List: def __init__(self): self.head = None def insert(self,data): new_node = Node(data) if self.head == None: self.head = new_node else: new_node.next = self.head self.head = new_node def swap_pairs(self): temp = self.head if temp == None: print("Link list is empty") return elif temp.next == None: print("Only one element in linkedlist") while(temp != None and temp.next != None): temp.data,temp.next.data = temp.next.data,temp.data temp = temp.next.next def display(self): temp = self.head while temp != None: print(temp.data,end = " ") temp = temp.next # Driver program llist = Linked_List() llist.insert(5) llist.insert(4) llist.insert(3) llist.insert(2) llist.insert(1) print("Linked list before calling swap_pairs() ") llist.display() llist.swap_pairs() print ("\nLinked list after calling swap_pairs()") llist.display()
a36a76bc5ee9d6af5d4f25ea92643a291b7e02c2
yellankisanthan/Competitive-Programming
/Competitive-Programming/Week-3/Day-1/single_riffle_shuffle.py
1,086
3.78125
4
def is_single_riffle(half1, half2, shuffled_deck): len_half1 = len(half1) len_half2 = len(half2) len_full = len(shuffled_deck) half1_i = 0 half2_i = 0 if len_half1 + len_half2 != len_full: return False for i in shuffled_deck: if half1_i<len_half1 and i==half1[half1_i]: half1_i += 1 elif half2_i<len_half2 and i==half2[half2_i]: half2_i += 1 elif i!=half1[half1_i] or i!=half2[half2_i]: return False return True # Tests result = is_single_riffle([1, 4, 5], [2, 3, 6], [1, 2, 3, 4, 5, 6]) expected = True print(result == expected) result = is_single_riffle([1, 5], [2, 3, 6], [1, 2, 6, 3, 5]) expected = False print(result == expected) result = is_single_riffle([], [2, 3, 6], [2, 3, 6]) expected = True print(result == expected) result = is_single_riffle([1, 5], [2, 3, 6], [1, 6, 3, 5]) expected = False print(result == expected) result = is_single_riffle([1, 5], [2, 3, 6], [1, 2, 3, 5, 6, 8]) expected = False print(result == expected)
434dd6803df303fbc328938f3777ec8420c36cac
midgithub/Learning
/Python/input_print.py
776
3.953125
4
# print #可以有分号 也可以没有 写在同一行的语句要用分号隔开 否则以换行隔开就行了 print("hello world");print("other hello") #print可以有任意个输出,每个输出参数之间以","隔开,输出时会被替换为空格 print("hello","world") #print还可以输出整数,布尔型或等式都可以 print('hello world',666,3+2,True,3>2) #input #输入函数,输入得到的变量为字符串 sublime编译执行不了输入操作,要验证得在命令行下验证 print("inputed ",input()); a=input(); print("input val a ",a); #input 还可以传入一个字符串参数,作为输出提示语 input输入得到都是字符串类型,要得到其他类型的需要转换 num=input("please Input a Number "); print(int(num))
d44b5570d78e304c344b8f8a0c2cd11d12cfcf17
alexle512/9-21
/names.py
446
4.34375
4
names = ["Alex", "John","Mary","Steve","John","Steve"] #Assignment: Write a program which will remove duplicates from the array. finalnames = [] for item in names: if item not in finalnames: finalnames.append(item) print(finalnames) #Assignment: Write a program which finds the largest element in the array print(max(names, key=len)) #Assigmment: Write a program which finds the smallest element in the array print(min(names, key=len))
813f11f4b4232b82d5244ed6c961c2ba461d9038
darshanjoshi16/GTU-Python-PDS
/lab5_9.py
1,685
4.1875
4
from abc import ABC,abstractmethod class interface(): @abstractmethod def enroll_from_course(): pass def remove_from_course(): pass class student(interface): def __init__(self,firstname,lastname,age): self.firstname = firstname self.lastname = lastname self.age = age def enroll_to_course(self,course) : self.temp="enrolled to" self.course=course def remove_from_course(self,course): self.temp="removed from" self.course=course def display(self) : print("\"{} {} is {} the course:{}\"".format(self.firstname,self.lastname,self.temp,self.course)) print("------------------------------------------------------------------------") firstname = input(" Enter Your First Name:") lastname=input(" Enter Your Last Name: ") age=input(" Enter Your Age:") print("------------------------------------------------------------------------") s1=student(firstname,lastname,age) choice=int(input(" Enter a 1 for enroll into course \n Enter 2 for removal from course\n Choose Your Option: ")) if choice==1: print("------------------------------------------------------------------------") course=input("Enter the name of the course you want to enroll: ") s1.enroll_to_course(course) elif choice==2: print("------------------------------------------------------------------------") course=input("Enter the name of the course you want to remove from your learning list: ") s1.remove_from_course(course) s1.display() print("------------------------------------------------------------------------")
4e5034331a9e2e1fa1b2f8084d0c77c3131238f1
antoinemadec/test
/python/foobar/rm_duplicated_nb_in_list/rm_duplicated_nb_in_list.py
705
4.03125
4
#!/usr/bin/env python3 """ Write a function called answer(data, n) that takes in a list of less than 100 integers and a number n, and returns that same list but with all of the numbers that occur more than n times removed entirely. The returned list should retain the same ordering as the original list - you don't want to mix up those carefully-planned shift rotations! For instance, if data was [5, 10, 15, 10, 7] and n was 1, answer(data, n) would return the list [5, 15, 7] because 10 occurs twice, and thus was removed from the list entirely. """ def answer(data,n): d = dict((x,data.count(x)) for x in set(data)) return [x for x in data if d[x] <= n] print(answer([5, 10, 15, 10, 7], 1))
e387c803185872cda602f4a6d19cc3efa3d97f0b
DyadushkaArchi/python_hw
/python_hw_1-6.py
2,052
3.828125
4
import math #======================================================================================== #task one a = 5 b = 7 c = 12 equation = a + b * (c / 2) result = "1)Выражение a + b * (c / 2) при а = %d, b = %d и с = %d, равно %d;" % (a, b, c, equation) print(result) #========================================================================================== #task two a = 8 b = 3 equation = (a**2 + b**2) % 2 result = "2)Остаток от деления двучлена (a**2 + b**2) на 2, при а = %d и b = %d, равен %d;" % (a, b, equation) print(result) #========================================================================================= #task three a = 88 b = 77 c = 66 equation = (a + b) / 12 * c % 4 + b result = "3)Сумма числа b и остатока от деления выражения (a + b) / 12 * c на 4," \ "при а = %d, b = %d, с = %d, равна %.1f;" % \ (a, b, c, equation) print(result) #========================================================================================== #task four a = 9 b = 17 c = 4 equation = (a - b * c) / (a + b) % c result = "4)Остаток от деления выражения (a - b * c) / (a + b) на число с," \ "при а = %d, b = %d и с = %d, равен %f;" % \ (a, b, c, equation) print(result) #=========================================================================================== #task five a = 1 b = -4 c = 34 equation = abs(a - b) / (a + b)**3 - math.cos(c) result = "5)Выржение | a - b | /(a + b)3 - cos( c )," \ "при а = %d, b = %d и с = %d, равнo %f;" % \ (a, b, c, equation) print(result) #=========================================================================================== #task six a = 90 b = 54.8 c = 0 equation = (math.log(1+c) / -b)**4+ abs(a) result = "6)Выражение (ln(1 + c) / -b)4+ | a |," \ "при а = %d, b = %d и с = %d, равно %d." % \ (a, b, c, equation) print(result)
58665c93ade0ae59a20751ada33f8171043fb48a
iontsev/GeekBrains--Algorithms_and_data_structures_in_Python
/lesson_5/lesson_5__task_1.py
2,179
3.90625
4
""" Пользователь вводит данные о количестве предприятий, их наименования и прибыль за четыре квартала для каждого предприятия. Программа должна определить среднюю прибыль (за год для всех предприятий) и отдельно вывести наименования предприятий, чья прибыль выше среднего и ниже среднего. """ from collections import namedtuple Enterprise = namedtuple('Enterprise', 'name quarter_1 quarter_2 quarter_3 quarter_4 year') enterprise_count = int(input('Введите количество предприятий для анализа: ')) enterprises = [0 for _ in range(enterprise_count)] profit_sum = 0 for i in range(enterprise_count): name = input(f'Введите название {i+1}-го предприятия: ') quarters = [float(input(f'Введите прибыль в {i}-ом квартале: ')) for i in range(4)] year = 0 for quarter in quarters: year += quarter profit_sum += year enterprises[i] = Enterprise(name, *quarters, year) if enterprise_count == 1: print(f'Для анализа передано только одно предприятие: {enterprises[0].name}. Eго годовая прибыль: {enterprises[0].year}') else: profit_average = profit_sum / enterprise_count less = [] more = [] for i in range(enterprise_count): if enterprises[i].year < profit_average: less.append(enterprises[i]) elif enterprises[i].year > profit_average: more.append(enterprises[i]) print(f'\nСредняя годовая прибыль по предприятиям: {profit_average: .2f}') print(f'\nПредприятия, чья прибыль выше средней:') for item in more: print(f'{item.name} ({item.year: .2f})') print(f'\nПредприятия, чья прибыль ниже средней:') for item in less: print(f'{item.name} ({item.year: .2f})')
0fac52cfd6db45784aabbf4594e0bd22b20c990e
patricia-faustino/cursoPython01
/pythonTeste/desafio011.py
213
3.875
4
largura = float(input('Digite a largura ')) altura = float(input('Digite a altura ')) area = largura * altura tinta = area / 2 print('A área é {}m2 e a quantidade necessária de tinta é {}l'.format(area,tinta))
9c83e1efd41eec5ff7211f4677df050eebe6c9ab
jaford/thissrocks
/Python_Class/py3intro3day 2/EXAMPLES/function_basics.py
368
3.703125
4
#!/usr/bin/env python def say_hello(): # <1> print("Hello, world") print() # <2> say_hello() # <3> def get_hello(): return "Hello, world" # <4> h = get_hello() # <5> print(h) print() def sqrt(num): # <6> return num ** .5 m = sqrt(1234) # <7> n = sqrt(2) print("m is {:.3f} n is {:.3f}".format(m, n))
99184759b5a94ba8431b741ef4f769be73ba8ef4
eulaapp/Exercicios
/ex005.py
186
4.125
4
numero = int(input('Digite um número: ')) antecessor = numero - 1 sucessor = numero + 1 print(f'O antecessor do numero {numero} é {antecessor} e o seu sucessor é {sucessor}')
d777192ebf308b3ff674d0c435d622c32a2969cc
lokeshraogujja/practice
/even.py
123
4.15625
4
# code for even and odd i = int(input("Enter a Number: ")) if i % 2 ==0 : print("even") else: print("Odd")
1ee96fb00d77cafb5a88cc06cd991acf2d268d21
zhoushaodong666/python-study
/14-面向对象/class_test2.py
4,553
3.953125
4
class Student(): # 类的属性 age = 0 name = '' # 类的方法 def printHello(self): print("hello") def printTest(self): print(self) print(self.__class__) # 3.类的方法 # 类中定义的函数称为方法 # 类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是【self】,也可以是其他名称. # self指向调用类的方法的实例对象 # 格式: """ def methodName(self): pass """ # 【self】输出类的实例对象的当前内存地址 # 【self.class】 指向类 s = Student() s.printTest() # 输出结果 # <__main__.Student object at 0x0000029312E58188> # <class '__main__.Student'> # 构造方法 # 类有一个名为 __init__() 的特殊方法(构造方法),该方法在类实例化时会自动调用 # 常用与类的初始化操作 # 每次实例化类对象都会调用__init__()方法 class Person: # 类的属性/类的变量 des = "这是一个Person类" name = 'jason' def __init__(self, name, age): # 使用self.xx的方式 将形参的值保存到实例对象的实例变量中 self.name = name self.age = age self.test = "test" print("我是__init__方法") print("name:" + name) print("age:" + str(age)) # return "person" def printPerson(self): self.ha = "df" pass # print("类变量name:"+name) def printObjectMethod(self): print("实例方法") # 类方法 @classmethod def classMethodName(cls): print("classMethodName 类的方法执行") print("类的属性 des:", cls.des) @staticmethod def staticMethodName(): # 访问类变量 print(Person.des) print("staticMethodName 静态方法执行") # 实例化类对象 会自动调用一次__init__()方法 p = Person("小丽", 16) # 我是__init__方法 # name:小丽 # age:16 print("=====================") # 4.类变量,定义在类中且在方法之外,Person类的变量des就是类变量,通过【类名.变量名】来访问变量 print(Person.des) # 这是一个Person类 Person.des2 = "这是一个Person类2" print(Person.des2) # 这是一个Person类2 print("=====================") # 5.实例变量,定义在方法内部,变量是保存在实例对象中的,通过【self(实例).变量名】来访问实例变量 p2 = Person("小白", 18) p3 = Person("小红", 20) print(p2.name) # 小白 print(p2.age) # 18 print(p3.name) # 小红 print(p3.age) # 20 # 内置变量__dict__可以查看pyhton类实例的全部实例变量 print("p2的全部实例变量", p2.__dict__) # p2的全部实例变量 {'name': '小白', 'age': 18, 'test': 'test'} print("p3的全部实例变量", p3.__dict__) # p3的全部实例变量 {'name': '小红', 'age': 20, 'test': 'test'} print("=====================") # 6.类变量和实例变量的访问顺序 # 使用实例对象访问变量 优先从实例变量中找 没有再向上找类变量 print(p3.des) # 这是一个Person类 print(p3.name) # 小红 print(Student.age) # 0 print(Student.name) # '' print("=====================") # 7.构造方法也可以自己显式的调用 p.__init__("小白", 18) # 我是__init__方法 # name:小白 # age:18 # 构造方法的返回值只能是None,不能是其他的。None一般不写,函数会自动返回。 # print(p) # TypeError: __init__() should return None, not 'str' # 8.类的方法 使用classmethod的修饰符定义,classmethod修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等 # 格式: """ @classmethod def classMethodName(cls): pass """ # 类名调用类的方法 Person.classMethodName() # classMethodName 类的方法执行 # 类的属性 des: 这是一个Person类 # 实例对象调用类的方法 p.classMethodName() # classMethodName 类的方法执行 # 类的属性 des: 这是一个Person类 # 9.静态方法 # 使用@staiticmethod来修饰一个方法,该方法不强制传递参数 # 格式: """ @staticmethod def staticMethodName(): pass """ print("=============") # 使用类名调用静态方法 Person.staticMethodName() # 这是一个Person类 # staticMethodName 静态方法执行 # 使用实例对象调用静态方法 p.staticMethodName() # 这是一个Person类 # staticMethodName 静态方法执行
87c307086b93ec8895f1da6bed9d0a0e7064aad1
varsha0201/automate_the_borningstuff_with_python
/yourname.py
343
4.03125
4
# ---------------------while - break name = '' while True: print('Please eneter your name.') name = input() if name == 'your name': break print('Thank you') #------------------------while -continue --------------- spam = 0 while spam < 5: spam = spam+1 if spam ==3: continue print('spam is'+ str(spam))
1c857c7eba977f78d70bafd05efb2b293af1f3d4
IRS-PM/IRS-PM-2020-01-18-IS02PT-GRP18-Smart_Travel_Recommender
/SystemCode/database/unit_test.py
1,597
3.765625
4
from city_selector import city_selector from random import randint PERMITTED_ITEMS = [ 'Museums', 'Outdoor Activities', 'Nature & Parks', 'Shopping', 'Spas & Wellness', 'Food & Drink', 'Nightlife', 'Sights & Landmarks' ] total_test = 30 for iter in range(total_test): print(f"======================================= Run {iter + 1}===========================================") ranked_preference = {} unranked_preference = [] rand1 = randint(0,7) ranked_preference[PERMITTED_ITEMS[rand1]] = '1' unranked_preference.append(PERMITTED_ITEMS[rand1]) rand2 = randint(0, 7) while rand2 == rand1: rand2 = randint(0,7) ranked_preference[PERMITTED_ITEMS[rand2]] = '2' unranked_preference.append(PERMITTED_ITEMS[rand2]) rand3 = randint(0, 7) while (rand3 == rand2) or (rand3 == rand1): rand3 = randint(0,7) ranked_preference[PERMITTED_ITEMS[rand3]] = '3' unranked_preference.append(PERMITTED_ITEMS[rand3]) ranked_selector = city_selector() unranked_selector = city_selector() print(f"Ranked preference is: {ranked_preference}") print(f"Unranked preference is: {unranked_preference}") ranked_matching = ranked_selector.find_matching_city(ranked_preference) print("Matching city based on ranked preference: ") print(ranked_matching['matching_city']) print("\n") unranked_matching = unranked_selector.find_matching_city(unranked_preference) print("Matching result based on unranked preference: ") print(unranked_matching['matching_city']) print("\n")
a4b031efaa4c10a415f3c5320a1bc7e8097b41fb
gistable/gistable
/all-gists/2140276/snippet.py
2,039
3.625
4
"""Python implementation of Conway's Game of Life Somewhat inspired by Jack Diederich's talk `Stop Writing Classes` http://pyvideo.org/video/880/stop-writing-classes Ironically, as I extended the functionality of this module it seems obvious that the next step would be to refactor board into a class with advance and constrain as methods and print_board as __str__. """ import sys import time GLIDER = { (2, 2), (1, 2), (0, 2), (2, 1), (1, 0), } def neighbors(cell, distance=1): """Return the neighbors of cell.""" x, y = cell r = xrange(0 - distance, 1 + distance) return ((x + i, y + j) # new cell offset from center for i in r for j in r # iterate over range in 2d if not i == j == 0) # exclude the center cell def advance(board): """Advance the board one step and return it.""" new_board = set() for cell in board: cell_neighbors = set(neighbors(cell)) # test if live cell dies if len(board & cell_neighbors) in [2, 3]: new_board.add(cell) # test dead neighbors to see if alive for n in cell_neighbors: if len(board & set(neighbors(n))) is 3: new_board.add(n) return new_board def print_board(board, size=None): sizex = sizey = size or 0 for x, y in board: sizex = x if x > sizex else sizex sizey = y if y > sizey else sizey for i in xrange(sizex + 1): for j in xrange(sizey + 1): sys.stdout.write(' x ' if (i, j) in board else ' . ') print def constrain(board, size): return set(cell for cell in board if cell[0] <= size and cell[1] <= size) def main(board, steps=75, size=20): for i in xrange(1, steps + 1): sys.stdout.write('\033[H') # move to the top sys.stdout.write('\033[J') # clear the screen print 'step:', i, '/', steps print_board(board, size) time.sleep(0.1) board = constrain(advance(board), size) if __name__ == '__main__': main(GLIDER)
791cdd0a2c672a93a770b096dec987f49421ef86
dzieber/python-crash-course
/ch4/numbers.py
578
4.125
4
for value in range(1,5): print(value) for value in range(1,6): print(value) print(range(1,5)) numbers = list(range(1,5)) for number in numbers: print(number) numbers = list(range(2,11,2)) for number in numbers: print(number) squares = [] for number in range(1,11): squares.append(number**2) print(squares) digits = list(range(1,10)) digits.append(0) print(digits) print(min(digits)) print(max(digits)) print(sum(digits)) digits.append(11) print(min(digits)) print(max(digits)) print(sum(digits)) squares = [values**2 for values in range(1,11)] print squares
ad83ace8e357b2c52bd9bccf70645efb34bc83b7
JavidSalmanov/hackerrank
/time-Conversion.py
592
3.875
4
#!/bin/python3 import os import sys def timeConversion(s): last_chars = s[-2:] first_chars = s[:2] if last_chars == 'AM' and first_chars == '12': return "00" + s[2:-2] elif s[-2:] == "AM": return s[:-2] elif last_chars == 'PM' and first_chars == '12': return s[:-2] else: return str(int(s[:2]) + 12)+s[2:-2] if __name__ == '__main__': f = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = timeConversion(s) f.write(result + '\n') f.close() s = input() result = timeConversion(s) print(result)
e6cfdec9baa0bfa72c27fe4915eb9a77e4575249
pemburukoding/belajar_python
/part003.py
2,770
4.1875
4
# num = -1 # if num > 0: # print("Positive number") # elif num == 0: # print("Zero") # else: # print("Negative number") # if False: # print("I am inside the body of if.") # print("I am also inside the body of if.") # print("I am outside the body of if.") # n = 100 # sum = 0 # i = 1 # while i <= n: # sum = sum + i # i = i+1 # print("The sum is ", sum) # numbers = [6, 5, 3, 8, 4, 2] # sum = 0 # for val in numbers: # sum = sum + val # print("The sum is ", sum) # for val in "string": # if val == "r": # break # print(val) # print("The End") # for val in "string": # if val == "r": # continue # print(val) # print("The End") #Pas Sequence # sequence = {'p', 'a', 's', 's'} # for val in sequence: # pass # Function and method # def print_lines(): # print("I am line1.") # print("I am line2.") # print_lines() # def add_numbers(a, b): # sum = a + b # return sum # result = add_numbers(4, 5) # print(result) # def calc_factorial(x): # if x == 1: # return 1 # else: # return (x * calc_factorial(x - 1)) # num = 4 # print("The factorial of ", num, "is ",calc_factorial(num)) # square = lambda x:x ** 2 # print(square(100)) # import example # output = example.add(4, 5.5) # print(output) # import math # result = math.log2(5) # print(result) # from math import pi # print("The value of pi is ", pi) # with open("test.txt", "w", encoding = 'utf-8') as f: # f.write("my first file\n") # f.write("This file\n\n") # f.write("contains three lines\n") # import sys # randomList = ['a', 0, 2] # for entry in randomList: # try: # print("The entry is ", entry) # r = 1 / int(entry) # break # except: # print("Oops!", sys.exc_info()[0], "occured.") # print("Next extry.") # print() # print("The reciprocal of", entry, "is", r) # Class and object # class MyClass: # "This is my class" # a = 10 # def func(self): # print('hello') # print(MyClass.a) # print(MyClass.func) # print(MyClass.__doc__) # obj1 = MyClass() # print(obj1.a) # obj2 = MyClass() # print(obj1.a + 5) # class ComplexNumber: # def __init__(self, r = 0, i = 0): # self.real = r # self.imag = i # def getData(self): # print("{0}+{1}j".format(self.real, self.imag)) # c1 = ComplexNumber(2, 3) # c1.getData() # c2 = ComplexNumber() # c2.getData() # class Mamal: # def displayMamalFeatures(self): # print("Mamal is a warm-blooded animal.") # class Dog(Mamal): # def displayDogFeatures(self): # print("Dog has 4 legs") # d = Dog() # d.displayMamalFeatures() # d.displayDogFeatures() # my_list = [4, 7, 0, 3] # my_iter = iter(my_list) # print(next(my_iter)) # print(next(my_iter)) def print_msg(msg): def printer(): print(msg) return printer another = print_msg("Hello") another()
6de7dfdae489771e8d51dab845f31a5b490c6bc6
KartikKannapur/Algorithms
/00_Code/01_LeetCode/657_JudgeRouteCircle.py
1,509
4.25
4
""" Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle. Example 1: Input: "UD" Output: true Example 2: Input: "LL" Output: false Your runtime beats 77.72 % of python submissions. """ class Solution: def judgeCircle(self, moves): """ :type moves: str :rtype: bool """ """ Method 1: * The robot moves back to its initial position IF count of left moves == count of right moves IF count of up moves == count of down moves * We could assign a cost to each of these operations say +1/-1 scheme and compute the cost of traversal map_path = {"U" : 1, "D": -1, "R": 1, "L": -1,} Your runtime beats 73.96 % of python3 submissions. """ # map_path = {"U" : 1, "D": -1, "R": 1, "L": -1,} # return sum([map_path[var_move] for var_move in moves]) == 0 """ Method 2: * Cost computation is done via a count operation in a single line Your runtime beats 82.29 % of python3 submissions. """ return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')
66fee6038f093138b70735be0d2b030cc882cb4d
DanishShaikh-787/Python_Problems
/PowerOfTwo.py
891
4
4
""" * Author - danish * Date - 16/11/20 * Time - 1:31 AM * Title - Find Power Of 2 between 0 to 31 """ class Power: # Definning constructor method def __init__(self,number): self.number = number # Method to check number is valid or not def checkValidNumber(self): if 0 <= self.number < 31: print(f"Power Of Two Is: {Power.powerOf2(self.number)}") else: print("Not a valid power.") # Method to calculate power of 2 def powerOf2(number): if number == 0: return 1 else: return Power.powerOf2(number-1)*2 if __name__ == "__main__": number = int(input("Enter a Number: ")) powerObject = Power(number) powerObject.checkValidNumber()
88168d14cb8868186b23a4318c48226cdd4da85f
MittalMakwana/ProjectEuler
/fact_tool.py
566
3.953125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 17 13:36:14 2017 @author: mmakwana """ import math def factorial(n):return reduce(lambda x,y:x*y,[1]+range(1,n+1)) def fact_trailling_zero(n): ''' parm: n natural number to get trailing zero in a factorail of large number Formula explained in https://brilliant.org/wiki/trailing-number-of-zeros/ ''' if n < 1: raise ValueError('Negative number less than 1 not aceppted') return sum((n/5**i for i in range(1,int(math.log(n,5))+1))) def fact_number_digits(n):
1aef40d15dd0bf6c6708f66861accb250e0f8bcc
rebeccasmile1/algorithm
/sort/BubbleSort.py
470
3.796875
4
''' j从后面开始 每次把最小的冒泡到i位置 ''' def BubbleSort(a): for i in range(len(a)): for j in range(len(a)-1): if a[j]>a[j+1]: a[j],a[j+1]=a[j+1],a[j] def BubbleSort2(a): for i in range(len(a)): j=len(a)-1 while j>i: if a[j]<a[j-1]: a[j],a[j-1]=a[j-1],a[j] j-=1 if __name__ == '__main__': a=[38,49,65,97,76,13,27,49] BubbleSort2(a) print(a)
9cbe999231395382068f2cbfb0adfd4cf720cad7
srankur/ProgPrep
/Leet/Easy/String/String_Integer_atoi.py
2,871
4.28125
4
""" String to Integer (atoi) Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. Note: Only the space character ' ' is considered as whitespace character. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2**31, 2**31 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned. Example 1: Input: "42" Output: 42 Example 2: Input: " -42" Output: -42 Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42. Example 3: Input: "4193 with words" Output: 4193 Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. Example 4: Input: "words and 987" Output: 0 Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed. Example 5: Input: "-91283472332" Output: -2147483648 Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned. """ # -42 def atoi(arr): negative_flag = False base = 10 num = 0 for i in range(len(arr)): if arr[i] == " ": i += 1 continue # Negative sign check if arr[i] == "-": negative_flag = True i += 1 continue # Postive sign check elif arr[i] == "+": i += 1 continue # range check if ord("0") <= ord(arr[i]) <= ord("9"): num = (num * base) + (ord(arr[i] ) - ord('0')) #base = base*10 if num > 2**31: return 2**31 -1 elif num < 2**31 and negative_flag == True: return -2**31 elif ord(arr[i]) < 0 or ord(arr[i]) > 9: break return -num if (negative_flag == True) else num # Driver Code if __name__ == "__main__": num = " -4267707870" print(atoi(num))
ca821789cdaef2e39ac87e2566cd3ec584c0ea18
Sarbodaya/PythonGeeks
/Operator/AnyAllInPython.py
1,277
4.15625
4
# Any # Returns true if any of the items is True. # It returns False if empty or all are false. # Any can be thought of as a sequence of OR operations on the provided iterables. # It short circuit the execution i.e. stop the execution as soon as the result is known print("ANY Function : ") # Since all are False so False is returned print(any([False, False, False, False, False, False])) print(any([])) # Here the Second Method will short - circuit at the # second item( True) and will return True print(any([False, True, False, False, False])) print(any([True, False, False, False, False])) # ALL print("ALL Function : ") # Returns true if all of the items are True (or if the iterable is empty). # All can be thought of as a sequence of AND operations on # the provided iterables. It also short circuit the execution # i.e. stop the execution as soon as the result is known. print(all([True, True, True, True])) print(all([False, False, True])) print(all([False, False, False])) print("Practical Example") # This code explains how can we # use 'any' function on list list1 = [] list2 = [] for i in range(1, 11): list1.append(4*i) for i in range(0, 10): list2.append(list1[i] % 5 == 0) print(any(list2)) print(all(list2))
c8adad8c3001c00085a25e045686f8d419ad848d
MAPLE-Robot-Subgoaling/IPT
/data/HW4/hw4_137.py
661
4.3125
4
def main(): height = 0 STOP_HEIGHT = 1 numberType = "" ONE = 1 TWO = 2 THREE = 3 height = int(input("What height is the hailstone at: ")) while height != 1: print("THe hailstone is currently at height:", height) if height % TWO == 0: numberType = "even" else: numberType = "odd" if numberType == "even": height = height // TWO else: height = (height * THREE) + ONE print("The hailstone has stopped at height", height ) main()
20fcd5a8a19770e974b627125f9a0f932128783e
brady-wang/spider_python
/ai/3.py
570
3.65625
4
# *_*coding:utf-8 *_* def binaery_search(list,item): low=0 high=len(list)-1 while low <= high: mid=int((low+high)/2) guess=list[mid] if guess == item: return mid if guess >item: high=mid-1 else: low=mid+1 return None my_list=[1,3,5,7,9,11] print(binaery_search(my_list,1)) print(binaery_search(my_list,3)) print(binaery_search(my_list,5)) print(binaery_search(my_list,7)) print(binaery_search(my_list,9)) print(binaery_search(my_list,11)) print(binaery_search(my_list,-1))
8708704feb740479f358775b73f9173271eff9ac
skelkelian/crash_course_python
/week_one.py
488
3.8125
4
friends = ['Serop', 'Alex', 'Aramis', 'Katherine'] for friend in friends: print("hi " + friend) print('Hello, world!') name = "Brook" print("hello ", name) color = "Green" thing = "Hope" print(color + " is the color of " + thing) print(4+5) print(9*7) print(-1/4) print(1/3) print(((2050/5-32)/9)) print(4**5) print((((1+2)*3)/4)**5) ratio = ((1+5**(1/2))/2) print(ratio) disk_size = 16*1024*1024*1024 sector_size = 512 sector_amount = disk_size/sector_size print(sector_amount)
eaf741ad59b1eabbfac1bc399788226857fc990b
ekremcivan/GoPY-Board-Game-on-Python
/GoPy game.py
2,642
3.609375
4
import sys game = [] a = int(input("What Size Game GoPy ")) def board_game(): for i in range(0, a * a, a): row = [] for j in range(a): row.append(i + j) global b b = game.append(row) def board(): for x in range(len(game)): for y in range(len(game[x])): if str(game[x][y]).isalpha() == True: print("", game[x][y], end=" ") elif game[x][y] <= 9: print("", game[x][y], end=" ") elif game[x][y] > 9: print(game[x][y], "", end=" ") print() board() while True: q = int(input("Player 1 turn --> ")) if q not in range(a * a): print("Please enter a valid number") else: for i in range(a): for j in range(a): if game[i][j] == q: game[i][j:j + 1] = "X" board() def winner(): for i in range(a): for j in range(a): if game[i].count("X") == len(game[i]): print("Winner: X") quit() elif game[i].count("O") == len(game[i]): print("Winner: O") quit() for i in range(len(game[0])): j = [] for k in game: j.append(k[i]) if j.count(j[0]) == len(j): print(f"Winner: {j[0]}") quit() diags = [] for idx, reverse_idx in enumerate(reversed(range(len(game)))): diags.append(game[idx][reverse_idx]) if diags.count(diags[0]) == len(diags): print(f"Winner: {diags[0]}") quit() diags = [] for i in range(len(game)): diags.append(game[i][i]) if diags.count(diags[0]) == len(diags): print(f"Winner: {diags[0]}") quit() winner() w = int(input("Player 2 turn --> ")) if w not in range(a * a): print("Please enter a valid number") if w == q: print("The other player select this cell before ") else: for i in range(a): for j in range(a): if game[i][j] == w: game[i][j:j + 1] = "O" board() winner() board_game()
5a6e8078861c7578790b5a29c92c1231fbd68200
sangbarta/pytho
/fileext.py
85
3.5625
4
f= input("enter filename:") s=f.split(".") print ("Extention of the file is:",s[-1])
d8e9d647891c6737e9803d176affec70c6f7794f
prasun2106/image_classifier_using_convolutional_network
/convolutional_neural_network.py
5,699
4.09375
4
#!/usr/bin/env python # coding: utf-8 # # Introduction # # In this motebook, we will build a simple image classification model using convolutional neural network to predict whether an image is cat or dog. I will be using Keras framework to solve the problem. The training dataset cointains labelelled images of dogs and cats. In machine learning learning concepts is equally important as applying them in Python. To bridge this gap, I will also add mathematical aspects as well as the reason behind doing any of the steps of convolutional neural network so that you can have a better understanding of the concept. # In[1]: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split # In[2]: # import libraries import tensorflow as tf from keras.preprocessing.image import ImageDataGenerator, load_img import os import shutil # In[3]: #creating a data folder get_ipython().system('mkdir data') # In[4]: get_ipython().system('cp ../input/dogs-vs-cats/* data') # In[5]: get_ipython().system('ls') # # Part 1 - Prepare Data # In[6]: #unzipping train set import zipfile with zipfile.ZipFile ('data/train.zip', 'r') as zip_ref: zip_ref.extractall('data/train/') # In[7]: filenames = os.listdir('data/train/train/') categories = [] for filename in filenames: category = filename.split(".")[0] if category == 'dog': categories.append(1) if category == 'cat': categories.append(0) df = pd.DataFrame({'filename':filenames, 'category':categories}) # In[8]: df.head() # In[9]: sns.countplot(df.category) # In[10]: # A Random Image random_number = np.random.randint(1, 25000, 1) plt.imshow(load_img('data/train/train/' + df['filename'][int(random_number)])) # In[11]: df['category'] = df['category'].replace({1:'dog', 0:'cat'}) # In[12]: train_df, validate_df = train_test_split(df, test_size = 0.2, random_state = 42) train_df.reset_index(drop = True, inplace = True) validate_df.reset_index(drop = True, inplace = True) # In[13]: total_train = train_df.shape[0] total_validate = validate_df.shape[0] batch_size = 15 # In[15]: # training generator train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.1, zoom_range = 0.2, rotation_range = 15, horizontal_flip = True, width_shift_range = 0.1 ,height_shift_range = 0.1) train_generator = train_datagen.flow_from_dataframe(train_df, 'data/train/train/', x_col = 'filename', y_col = 'category', target_size = (64,64), class_mode = 'categorical', batch_size = 15) # In[16]: # Validation generator validate_datagen = ImageDataGenerator(rescale = 1./225) validate_generator = validate_datagen.flow_from_dataframe(validate_df, directory = 'data/train/train/', x_col = 'filename', y_col = 'category' ,target_size = (64,64), batch_size = 15, class_mode = 'categorical') # Checking the results of our generator # In[47]: sample_df = df.sample(n=1) example_datagen = ImageDataGenerator(rescale = 1./255, horizontal_flip = True, shear_range = 0.2, zoom_range = 0.2,rotation_range = 0.1) example_data = example_datagen.flow_from_dataframe(sample_df, 'data/train/train/', x_col = 'filename' , y_col = 'category', target_size = (64,64), class_mode = 'categorical') # In[48]: i = 0 print('original_images') for image in sample_df['filename']: # i = i+1 # plt.subplot(2,2,i) plt.imshow(load_img('data/train/train/'+image)) # In[49]: plt.figure(figsize = (15,12)) for i in range(0, 50): plt.subplot(10, 5, i+1) for X_batch, Y_batch in example_data: image = X_batch[0] plt.imshow(image) break # plt.tight_layout() plt.show() # # Part 2 - Build Model # In[50]: # Import Libraries import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D,Dropout, Flatten, Dense, Activation, BatchNormalization # In[51]: # building the model model = Sequential() # convolution - number of filters are chosen arbitrarily for now model.add(Conv2D(filters = 32, kernel_size = 3, activation = 'relu', input_shape = [64, 64, 3])) # pooling - arbitrary choice model.add(MaxPooling2D(pool_size = 2, strides = 2)) # second convolutional layer model.add(Conv2D(filters = 32, kernel_size = 3, activation = 'relu')) # max pooling for second layer model.add(MaxPooling2D(pool_size = 2, strides = 2)) # flattening model.add(Flatten()) # Full Connection model.add(Dense(units = 128, activation = 'relu')) # Output layer model.add(Dense(units = 1, activation = 'sigmoid')) # # Part 3 - Train the model # In[53]: # Compile model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Training the CNN on training set and evaluating it on validation set model.fit(x = train_generator, validation_data=validate_generator, epochs=2) # # Part 4 - Making Prediction # In[ ]:
286d689351a17327fd626ae90b25d0ba53be35ba
hiepxanh/C4E4
/Tung/session 3 - Assignment/1.2.py
111
3.515625
4
color_list = ['Blue', 'Red', 'Black', 'Pink', 'Brown', 'Yellow'] print('color_list index 3 :',color_list[3])
c4ae4b5e59670cb24c73a6f613fab45eb1eb36c2
jieunyu0623/3522_A00998343
/Assignments/Assignment1/angel.py
1,328
3.625
4
from Labs.Lab4.userType import UserType from Assignments.Assignment1.users import Users class Angel(UserType): """ Angel class using the abstract class UserType. A user type Angel. """ def __init__(self): """ constructs an user type by using the super class constructor. """ super().__init__() def lock_account(self, user: Users): """ no need to lock account for the user type Angel. :param user: Users :return: None """ pass def warning_message(self, user: Users): """ gives the user warning message if the user exceeds 90% of the amount assigned to the budget. :param user: Users :return: None """ for budget in user.get_budgets(): if budget.get_budget() > budget.get_amount_spent() > (0.90 * budget.get_budget()): print("\nYou have spent more than 90 % of your budget!\n") def notification(self, user: Users): """ gives the user notification if the user exceeds the budget amount. :param user: Users :return: None """ for budget in user.get_budgets(): if budget.get_amount_spent() > budget.get_budget(): print("\nYou have exceeded the budget.\n")
d34f344881ba8c4df51369e6b4f476ea5529493a
HemanthSana/INF200-2019-Exercises
/src/hemanth_sana_ex/ex_02/file_stats.py
806
3.890625
4
import io def char_counts(input_file_name): """ Returns a list with the frequency of each- letter with utf-8 encoding """ utf_list = [0] * 256 with io.open(input_file_name, 'r', encoding='utf8') as file: file_content = file.read().rstrip("\n") for char in file_content: utf_code = ord(char) utf_list[utf_code] += 1 return utf_list if __name__ == '__main__': filename = 'file_stats.py' frequencies = char_counts(filename) for code in range(256): if frequencies[code] > 0: character = '' if code >= 32: character = chr(code) print( '{:3}{:>4}{:6}'.format( code, character, frequencies[code] ) )
00de2d4825b9f0df58e7c641c39786a2de6c7342
Sujitha03/python-programming
/vowels.py
156
3.859375
4
ch=input() ch=ch.lower() c=["a","e","i","o","u"] if(ch>='a' and ch<='z'): if ch in c: print("Vowel") else: print("Consonant") else: print("Invalid")
6ceb7032b0ca3b97dcd6d8c0d7deeafb9e981e97
tibetsam/learning
/cc150/_3_6.py
927
3.765625
4
class Stack(): def __init__(self, *values): if not values: values=None self.list=[] self.mins=None self.cur_min=float('inf') if values is not None: for v in values: self.push(v) return def push(self,value): #if value == (min(self.cur_min, value)): # self.mins=self.cur_min=value self.list.append(value) return self.list def sort(self): temp=Stack() temp.list=[] while self.list: data=self.list.pop() while (temp.list != [] and temp.list[-1]>data): self.push(temp.list.pop()) temp.push(data) return temp def min(self): return self.mins def pop(self): return self.list.pop() def __str__(self): return str(self.list) a=[5,2,1,3,4] b=Stack(*a) c=b.sort() print c
8081c83ac4e85d5e898a96a71d5ca682b4e7e07c
Aasthaengg/IBMdataset
/Python_codes/p02405/s151136464.py
590
3.5
4
import sys while True: height, width = map(int, raw_input().split()) if height == 0 and width == 0: break for i in range(height): for j in range(width): if j % 2 == 0 and i % 2 == 0: #even n, even n sys.stdout.write("#") elif j % 2 != 0 and i % 2 == 0: #even n, odd n sys.stdout.write(".") elif j % 2 == 0 and i % 2 != 0: #odd n, even n sys.stdout.write(".") elif j % 2 != 0 and i % 2 != 0: #odd n, odd n sys.stdout.write("#") print print
35e167c5484be65d46202d0dd30c1f702e075cab
yasheymateen/holbertonschool-machine_learning
/math/0x00-linear_algebra/5-across_the_planes.py
481
3.96875
4
#!/usr/bin/env python3 """ Implemnt function that adds two matrices element-wise""" def add_matrices2D(mat1, mat2): """ add matrices mat1, mat2 returns matrix_sum """ if len(mat1) != len(mat2) or len(mat1[0]) != len(mat2[0]): return None matrix_sum = [] for row_first, row_second in zip(mat1, mat2): matrix_sum.append([]) for i, j in zip(row_first, row_second): matrix_sum[-1].append(i + j) return matrix_sum
1cfaf1fac73de2aa20a5b2578041dc47e3815956
naveen1pantham/code-20211003
/bmi_assessment.py
1,417
3.921875
4
from data_file import bmi_list, bmi_category, health_risk def get_bmi(record): '''Calculating BMI by using given formula and adding new columns''' bmi = round(record['WeightKg']/(record['HeightCm']*0.01)**2, 2) record['BMI'] = bmi if bmi <= 18.4: record['health_risk'] = health_risk[0] record['bmi_category'] = bmi_category[0] elif bmi >= 18.5 and bmi <= 24.9: record['health_risk'] = health_risk[1] record['bmi_category'] = bmi_category[1] elif bmi >= 25 and bmi <= 29.9: record['health_risk'] = health_risk[2] record['bmi_category'] = bmi_category[2] elif bmi >= 30 and bmi <= 34.9: record['health_risk'] = health_risk[3] record['bmi_category'] = bmi_category[3] elif bmi >= 35 and bmi <= 39.9: record['health_risk'] = health_risk[4] record['bmi_category'] = bmi_category[4] elif bmi >= 40: record['health_risk'] = health_risk[5] record['bmi_category'] = bmi_category[5] return record if __name__ == '__main__': #Task 1 result = list(map(get_bmi, bmi_list)) print("List of dictionaries with new columns") print("*"*20) print("*"*20) print(result) print("*"*20) print("*"*20) #Task 2 count_list = filter(lambda record: record['bmi_category']=='Overweight', result) print("Count of Overweight persons",len(count_list))
61dd561111f5055f8dfb42c37c7dfb6bb61e0499
wesenu/Python-3
/04.Simple Loops/leftOrRight.py
284
3.625
4
n = int(input()) leftSum = 0 rightSum = 0 for i in range(n): leftSum = leftSum + int(input()) for i in range(n): rightSum = rightSum + int(input()) if leftSum == rightSum: print('Yes, sum = ' + str(leftSum)) else: print('No, diff = ' + str(abs(rightSum - leftSum)))
632a86c3b1b4158f7eadd6ac3ca7f24f4005ce97
pritamshrestha/DSC_550-data_mining-
/week_2(python_file)/Hypersphere_radius.py
1,317
3.734375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Name:Pritam Shrestha # FileName:Hypersphere_Radius # Date:6/05/2020 # Course: DSC550-Data Mining # Professor/Instructor:Brant Abeln # Description:Hypersphere radius with d-dimentions # Due Date:06/20/20 # Assignment No:2.1 # Reference:http://www.dataminingbook.info/uploads/videos/lecture7/ # In[6]: import numpy as np import math import matplotlib.pyplot as plt from scipy.special import gamma from math import pi # function to calculate radious of hyperSphere # given volume is 1 list_radius=[] # dimensions list d=[x for x in range(1,100)] def radius(d): for i in d: v=1 r=gamma((i/2+1)**1/i)/pi**0.5*v**1/i list_radius.append(r) def plot(d,list_radius): plt.plot(d,list_radius) plt.xlabel("d") plt.ylabel("radius") plt.show() if __name__=='__main__': #calling function inside the try block to catch the errors try: radius(d) plot(d,list_radius) except Exception as exception: print('exception') traceback.print_exc() print('An exception of type {0} occurred. Arguments:\n{1!r}'.format(type(exception).__name__, exception.args)); finally: print("Finally block is executed whether exception is handled or not!!") # In[ ]: # Thanks!!!
ff46572a9835fde3b24d43e73517a397318e005e
benLbishop/chess
/tests/test_pawn.py
10,024
3.875
4
"""Module for testing the Pawn class.""" import unittest from unittest.mock import patch from chess_game.square import Square from chess_game.pieces.pawn import Pawn from chess_game.pieces.piece import Piece from chess_game.enums import ChessColor from chess_game.board import Board from chess_game import constants from chess_game.custom_exceptions import InvalidMoveException class PawnTest(unittest.TestCase): """class for testing the Pawn class.""" @classmethod def setUpClass(cls): cls.white_pawn = Pawn(ChessColor.WHITE) cls.black_pawn = Pawn(ChessColor.BLACK) cls.board = Board(constants.STD_BOARD_CONFIG) def tearDown(self): self.board.clear() self.white_pawn.move_count = 0 self.black_pawn.move_count = 0 def test_init(self): """Tests for the class constructor.""" white_pawn = self.white_pawn self.assertEqual(white_pawn.char, constants.PIECE_CHARS['Pawn']) self.assertEqual(white_pawn._value, constants.PIECE_VALUES['Pawn']) self.assertEqual(white_pawn._offsets, []) @patch.object(Piece, 'has_valid_move_in_list') def test_has_valid_move(self, valid_move_mock): """Tests the overwritten has_valid_move method.""" white_pawn = Pawn(ChessColor.WHITE) black_pawn = Pawn(ChessColor.BLACK) cur_square = self.board.squares[0][0] # should call has_valid_move_in_list with the proper coordinates white_pawn.has_valid_move(cur_square, self.board) valid_move_mock.assert_called_with((0, 0), constants.WHITE_PAWN_OFFSETS, self.board) valid_move_mock.reset_mock() black_pawn.has_valid_move(cur_square, self.board) valid_move_mock.assert_called_with((0, 0), constants.BLACK_PAWN_OFFSETS, self.board) valid_move_mock.reset_mock() # should return what has_valid_move_in_list returns valid_move_mock.return_value = False res = white_pawn.has_valid_move(cur_square, self.board) self.assertFalse(res) res = black_pawn.has_valid_move(cur_square, self.board) self.assertFalse(res) valid_move_mock.return_value = True res = white_pawn.has_valid_move(cur_square, self.board) self.assertTrue(res) res = black_pawn.has_valid_move(cur_square, self.board) self.assertTrue(res) def test_can_reach_square(self): """Tests the overwritten can_reach_square method.""" start_row = 3 start_col = 3 start = Square(start_row, start_col) # test white pawns valid_white_dests = [ Square(start_row + 1, start_col), Square(start_row + 1, start_col + 1), Square(start_row + 1, start_col - 1), Square(start_row + 2, start_col), ] valid_black_dests = [ Square(start_row - 1, start_col), Square(start_row - 1, start_col + 1), Square(start_row - 1, start_col - 1), Square(start_row - 2, start_col), ] # test valid cases for dest in valid_white_dests: self.assertTrue(self.white_pawn.can_reach_square(start, dest)) for dest in valid_black_dests: self.assertTrue(self.black_pawn.can_reach_square(start, dest)) # test invalid cases # wrong color test for dest in valid_white_dests: self.assertFalse(self.black_pawn.can_reach_square(start, dest)) for dest in valid_black_dests: self.assertFalse(self.white_pawn.can_reach_square(start, dest)) # bad distance tests invalid_dests = [ Square(start_row, start_col + 1), Square(start_row + 2, start_col + 1), Square(start_row - 2, start_col + 1), Square(start_row + 4, start_col + 4) ] for dest in invalid_dests: self.assertFalse(self.white_pawn.can_reach_square(start, dest)) self.assertFalse(self.black_pawn.can_reach_square(start, dest)) def test_can_capture_en_passant(self): """Tests for the can_capture_en_passant method.""" b = self.board wp = self.white_pawn bp = self.black_pawn # should not work if piece not in correct location white_start = b.squares[4][4] black_start = b.squares[3][4] self.assertFalse(wp.can_capture_en_passant(b.squares[4][4], b.squares[5][5], b)) # Should raise InvalidMoveException if board has no move_history # TODO @patch.object(Pawn, 'can_capture_en_passant') def test_get_one_move_path(self, passant_mock): """Tests for the get_one_move_path method.""" passant_mock.return_value = None squares = self.board.squares row, col = 1, 1 start = squares[row][col] straight1 = squares[row + 1][col] right_diag = squares[row + 1][col + 1] left_diag = squares[row + 1][col - 1] white_piece = Piece(ChessColor.WHITE) black_piece = Piece(ChessColor.BLACK) # should raise if straight move attempted and ANY piece in way straight1.piece = white_piece with self.assertRaises(InvalidMoveException): self.white_pawn.get_one_move_path(start, straight1, self.board) straight1.piece = None straight1.piece = black_piece with self.assertRaises(InvalidMoveException): self.white_pawn.get_one_move_path(start, straight1, self.board) straight1.piece = None # should raise if diagonal move attempted and no piece on end with self.assertRaises(InvalidMoveException): self.white_pawn.get_one_move_path(start, right_diag, self.board) with self.assertRaises(InvalidMoveException): self.white_pawn.get_one_move_path(start, left_diag, self.board) # should raise if diagonal move attempted and player piece on end right_diag.piece = white_piece with self.assertRaises(InvalidMoveException): self.white_pawn.get_one_move_path(start, right_diag, self.board) right_diag.piece = None left_diag.piece = white_piece with self.assertRaises(InvalidMoveException): self.white_pawn.get_one_move_path(start, left_diag, self.board) left_diag.piece = None # should not raise if en passant is possible passant_return = 'dummy passant' passant_mock.return_value = passant_return res = self.white_pawn.get_one_move_path(start, left_diag, self.board) self.assertEqual(res, [start, left_diag]) # should work otherwise TODO def test_get_two_move_path(self): """Tests for the get_two_move_path method.""" squares = self.board.squares row, col = 1, 1 start = squares[row][col] mid = squares[row + 1][col] end = squares[row + 2][col] black_piece = Piece(ChessColor.BLACK) # should raise if moving 2 squares and pawn has moved self.white_pawn.move_count = 1 with self.assertRaises(InvalidMoveException): self.white_pawn.get_two_move_path(start, end, self.board) self.white_pawn.move_count = 0 # should raise if moving 2 is squares is valid, but blocking piece mid.piece = black_piece with self.assertRaises(InvalidMoveException): self.white_pawn.get_two_move_path(start, end, self.board) mid.piece = None end.piece = black_piece with self.assertRaises(InvalidMoveException): self.white_pawn.get_two_move_path(start, end, self.board) end.piece = None # should get the proper path for 2 otherwise res = self.white_pawn.get_two_move_path(start, end, self.board) self.assertEqual(res, [start, mid, end]) @patch.object(Pawn, 'get_two_move_path') @patch.object(Pawn, 'get_one_move_path') @patch.object(Pawn, 'can_reach_square') def test_get_path_to_square(self, valid_move_mock, one_move_mock, two_move_mock): """Tests the overwritten get_path_to_square method.""" one_move_return = 'one move return' two_move_return = 'two move return' valid_move_mock.return_value = True one_move_mock.return_value = one_move_return two_move_mock.return_value = two_move_return squares = self.board.squares row, col = 1, 1 start = squares[row][col] straight1 = squares[row + 1][col] straight2 = squares[row + 2][col] right_diag = squares[row + 1][col + 1] left_diag = squares[row + 1][col - 1] valid_move_mock.return_value = False # should raise if piece cannot reach end square with self.assertRaises(InvalidMoveException): self.white_pawn.get_path_to_square(start, straight1, self.board) valid_move_mock.return_value = True # should properly call two move and one move functions one_ends = [straight1, left_diag, right_diag] for end in one_ends: res = self.white_pawn.get_path_to_square(start, end, self.board) self.assertEqual(res, one_move_return) two_res = self.white_pawn.get_path_to_square(start, straight2, self.board) self.assertEqual(two_res, two_move_return) # should raise if moving one square fails one_move_mock.side_effect = InvalidMoveException('dummy exception') with self.assertRaises(InvalidMoveException): self.white_pawn.get_path_to_square(start, straight1, self.board) one_move_mock.side_effect = None # should raise if moving two squares fails two_move_mock.side_effect = InvalidMoveException('dummy exception') with self.assertRaises(InvalidMoveException): self.white_pawn.get_path_to_square(start, straight2, self.board) two_move_mock.side_effect = None def test_get_move_params(self): """Tests the overwritten get_move_params method.""" # TODO
94526edfc56b166ed27d7dd2bf1819b76f580cd6
MRYoung25/Python_InsertionSort
/Python_InsertionSort.py
394
4
4
data = [1, 3, 4, 6, 8, 7, 2, 5, 10, 11, 9, 13, 12] def InsertionSort(L): length = len(L) if length == 0 or length == 1: return L for i in range(len(L)-1, 0 , -1): current = i j = i - 1 for j in range(j, 0, -1): if L[j] > L[current]: (L[current],L[j]) = (L[j], L[current]) return L pass print InsertionSort(data)
c50d693eb19ed10fdeb31076d7b3c8a0cc7f678e
Gauravlamba1109/CS50-AI-2021
/tictactoe/tictactoe.py
4,172
3.96875
4
""" Tic Tac Toe Player """ import math import copy X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Returns player who has the next turn on a board. """ if board==initial_state() : return X if(terminal(board)) : return X noOfX = board[0].count(X)+board[1].count(X)+board[2].count(X) noOfO = board[0].count(O)+board[1].count(O)+board[2].count(O) if noOfX > noOfO : return O else : return X def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ myset=set() #find the empty points in the board for i in range(3): for j in range(3): if( board[i][j]==EMPTY): myset.add((i,j)) return myset def result(board, action): """ Returns the board that results from making move (i, j) on the board. """ #action will have i,j values so if action[0] not in range(0,3) or action[1] not in range(0,3) or board[action[0]][action[1]] is not EMPTY: raise Exception("Not Valid") boardnew= copy.deepcopy(board) boardnew[action[0]][action[1]]= player(board) return boardnew def winner(board): """ Returns the winner of the game, if there is one. """ if(board[0][0]==X and board[0][1]==X and board[0][2] ==X)or(board[1][0]==X and board[1][1]==X and board[1][2] ==X)or(board[2][0]==X and board[2][1]==X and board[2][2] ==X)or(board[0][0]==X and board[1][0]==X and board[2][0] ==X)or(board[0][1]==X and board[1][1]==X and board[2][1] ==X)or(board[0][2]==X and board[1][2]==X and board[2][2] ==X)or(board[0][0]==X and board[1][1]==X and board[2][2] ==X)or(board[2][0]==X and board[1][1]==X and board[0][2] ==X): return X if(board[0][0]==O and board[0][1]==O and board[0][2] ==O)or(board[1][0]==O and board[1][1]==O and board[1][2] ==O)or(board[2][0]==O and board[2][1]==O and board[2][2] ==O)or (board[0][0]==O and board[1][0]==O and board[2][0] ==O)or (board[0][1]==O and board[1][1]==O and board[2][1] ==O)or (board[0][2]==O and board[1][2]==O and board[2][2] ==O)or (board[0][0]==O and board[1][1]==O and board[2][2] ==O)or (board[2][0]==O and board[1][1]==O and board[0][2] ==O): return O return None def terminal(board): """ Returns True if game is over, False otherwise. """ if winner(board) is not None: return True #if no cell on the board is empty cnt=0 for i in range(3) : for j in range(3) : if board[i][j]==EMPTY : cnt=1 if cnt==0 : return True return False def utility(board): """ Returns 1 if X has won the game, -1 if O has won, 0 otherwise. """ if winner(board) == X : return 1 if winner(board) == O : return -1 return 0 def minimax(board): """ Returns the optimal action for the current player on the board. """ if terminal(board) : return None if player(board) == X : bests = -math.inf # making all moves to see beforehand what bring the best result for move in actions(board) : maxs = min_value(result(board,move)) if maxs > bests : bests = maxs best_move = move elif player(board) == O : bests = math.inf for move in actions(board) : mins = max_value(result(board,move)) if mins < bests : bests = mins best_move = move return best_move #defining max_value and min_value functions def min_value(board) : if terminal(board) : return utility(board) s = math.inf for move in actions(board) : s = min(s,max_value(result(board,move))) return s def max_value(board) : if terminal(board) : return utility(board) s = -math.inf for move in actions(board) : s = max(s,min_value(result(board,move))) return s
e6fd0dc5f4ab5d95a1d9305609ee0416aada0088
baatchman/MansaMusa
/Interface/code/setupaccounts.py
974
3.609375
4
import sys def main(): print("It seems as though you don't have your accounts set up, I'll get to doing that right now, I just need to ask you some questions :-)") keyamount = int(input("How many accounts do you have sir? > ")) s_key = "" p_key = "" #name = "" dirnname = input("Please input the name and directory of the new file e.g ~/accounts.txt > ") f = open(dirnname, "w+") for i in range(keyamount): s_key = input("What is the Private Key for the account, sir? > ") p_key = input("What is the Public key for the account, sir? > ") #name = raw_input("What would you like to call this account, sir? > ") f.write(str(s_key) + "\n" + str(p_key) + "\n") f.close() print("Your accounts are all setup now sir, you can now run the program like this for example:") print("./main.py -a " + dirnname + "-t buy -o market -q 100 -c BTCUSDT") print("Have a good day sir :-)") sys.exit()
120cd6cb30a51deaa5face2df7b5024ec22ba663
StephenCoady/AWS_management
/run_newwebserver.py
14,734
3.515625
4
#!/usr/bin/python3 # A program to manage a user's AWS. Uses the boto API to interact with AWS. # Functions include creating, stopping and terminating a new instance # managing your list of instances (obtained using your key as a search) # installing nginx, python, and managing nginx # # Stephen Coady # 20064122 import boto import boto.ec2 import time import logger import ssh import menu import subprocess import os import webbrowser private_key_name = None conn = boto.ec2.connect_to_region('eu-west-1') # this variable is the current instance being worked on. can never be None. # once a new instance is called this is update or once one is selected from the list instance = None my_instances = None # Method to create a new instance. # uses the user-defined key name to create an instance def new_instance(): global instance print("Please enter the name you would like to call the instance,") print("leave blank for the default.") instance_name = input(">>> ") if instance_name == "": instance_name = 'GA_StephenCoady' print('Starting instance. This may take a moment.') try: # creates a temporary reservation to create an instance from reservation = conn.run_instances('ami-69b9941e', key_name = private_key_name, \ instance_type = 't2.micro', security_groups = ['witsshrdp']) instance = reservation.instances[0] instance.add_tag('Name', instance_name) instance.update() while instance.state != 'running' : time.sleep(2) instance.update() print("\nRunning!") except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("new_server method failed. Error: " + error) # terminates the current instance. def terminate_instance(): global instance try : if instance.state == 'terminated' : print('Instance already terminated!') logger.status_log("User tried to stop an instance already terminated") else : decision = input("Are you sure you wish to terminate this instance? (y/n) ") if decision == 'y': instance.terminate(); print("Instance terminated!") else : print("Termination aborted! Instance is safe...for now.") except Exception as e: error = str(e) print("Cannot terminate instance, something went wrong. Please try again.") logger.status_log("Error terminating instance. Error: " + error) # starts the current instance def start_instance(): global instance try : if instance.state == 'terminated': print("Sorry, this instance is terminated. RIP.") else : if instance.state == 'running' : print('Instance already running!') logger.status_log("User tried to start an instance already running") else : instance.start(); print("Instance started!") except Exception as e: error = str(e) print("Cannot start instance, something went wrong. Please try again.") logger.status_log("Error starting instance. Error: " + error) # stops the current instance def stop_instance(): global instance if running_check() : try : if instance.state == 'terminated': print("Sorry, this instance is terminated. RIP.") else : if instance.state == 'stopped' : print('Instance already stopped!') logger.status_log("User tried to stop an instance already stopped") else : instance.stop(); print("Instance stopped!") except Exception as e: error = str(e) print("Cannot stop instance, something went wrong. Please try again.") logger.status_log("Error stopping instance. Error: " + error) # installs nginx on the current instance. def install_nginx(): global instance if running_check() : try : print("Installing nginx...") dns = instance.public_dns_name (status, output) = ssh.connect(dns, private_key_name, "sudo yum -y install nginx") if status > 0: print("Something went wrong. Check error log for information.") logger.status_log("Can't install nginx using SSH. Error message: ") logger.status_log(output) else : print("Nginx successfully installed on instance.") except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("install_nginx method failed. Error: " + error) # creates a list of all instances associated with the key the user entered. def view_all_instances(): global my_instances try : # loops through all reservations associated with this connection # and forms a list of instances reservations = conn.get_all_instances() instances = [] for r in reservations: instances.extend(r.instances) # within these instances if the key name matches the user entered # key it adds it to my_instances[] my_instances = [] for x in instances: if x.key_name == private_key_name : my_instances.append(x) if len(my_instances) == 0: print("No instances associated with this key. Please ensure it is the") print("correct key and that you have created some instances first.") else : print() print("No Name Status Time Started") print("---------------------------------------") for i in range (0, len(my_instances)) : print(str(i) + ": " + my_instances[i].tags["Name"] + " " + my_instances[i].state + " " + my_instances[i].launch_time) print("\n") instance_choice = input("Please enter the number of the instance you wish to manage (x to cancel) >>> ") return instance_choice except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("view_all_instances method failed. Error: " + error) # copies a python script from the current directory to the instance. def copy_web_script(): global instance if running_check() : try : print("Copying script...") dns = instance.public_dns_name (status, output) = ssh.copy(dns, private_key_name, "check_webserver.py", "") if status > 0: logger.status_log("Can't connect using ssh. Error message: ") logger.status_log(output) print("Something isn't quite right. Please try again.") return else : (status, output) = ssh.connect(dns, private_key_name, "ls") print("Current directory: ") print(output) (status, output) = ssh.connect(dns, private_key_name, "chmod 700 check_webserver.py") except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("copy_web_script method failed. Error: " + error) # runs the script copied and asks the user if they would like to start nginx # if the script returns that it is not already running. def run_nginx_check(): global instance if running_check() : try : dns = instance.public_dns_name (status, output) = ssh.connect(dns, private_key_name, "sudo python3 check_webserver.py") if "command not found" in output: print("It doesn't look like you've installed python, please try that first.") elif "No such file" in output: print("It doesn't look like you've copied the file to the instance, please try that first.") else : print(output) if status > 0 : choice = input("Would you like to start nginx? (y/n) ") if choice == 'y' : (stat, out) = ssh.connect(dns, private_key_name, "sudo service nginx start") if "unrecognized service" in out: print("It doesn't look like you've installed nginx, please try that first.") run_nginx_check() else : print("Nginx not started.") except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("run_nginx_check method failed. Error: " + error) # installs python3.4 on the instance. needed to run the check_webserver script def install_python(): global instance if running_check() : try : dns = instance.public_dns_name (status, output) = ssh.connect(dns, private_key_name, "sudo yum -y install python34") if status == 0: print("Python installed successfully!") else : logger.status_log("Python not installed correctly.") try_again = input("Oops, something wen't wrong installing python. Try again? (y/n) ") if try_again == 'y': install_python() except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("install_python method failed. Error: " + error) # allows the user to run their own commands on the instance. # os.system is used her as opposed to subprocess which is generally used elsewhere # because of its friendliness with certain commands such as nano etc. def run_user_command(): global instance if running_check(): try : dns = instance.public_dns_name command = None print("\nPlease use x to exit the python terminal. ") print("Please enter the command you wish to run, don't forget to") print("include -y to accept changes if necessary.") sudo = input("Would you like to emulate the terminal? (y/n) >>> ") while command != 'x': command = input(">>> ") if command !='x': if sudo == 'y': cmd = "ssh -t -o StrictHostKeyChecking=no -i " + private_key_name +".pem ec2-user@" + dns + " " + command print(os.system(cmd)) else : cmd = "ssh -o StrictHostKeyChecking=no -i " + private_key_name +".pem ec2-user@" + dns + " " + command print(os.system(cmd)) except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("run_user_command method failed. Error: " + error) # opens the index.html page of the nginx server in a new browser tab def visit_website(): global instance if running_check(): try : dns = instance.public_dns_name webbrowser.open("http://" + dns, new=0, autoraise=True) except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("visit_website method failed. Error: " + error) # allows the user to view the access log of the server to make sure they are connecting # and also what ip addresses are connecting. def view_access_log(): global instance if running_check(): try : dns = instance.public_dns_name ssh.connect(dns, private_key_name, "sudo chmod 777 /var/log/nginx") cmd = "nano /var/log/nginx/access.log" command = "ssh -t -o StrictHostKeyChecking=no -i " + private_key_name + ".pem ec2-user@" + dns + " " + cmd print(os.system(command)) except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("view_access_log method failed. Error: " + error) # allows the user to see what is going wrong if they cannot connect to their # web server def view_error_log(): global instance if running_check(): try : dns = instance.public_dns_name ssh.connect(dns, private_key_name, "sudo chmod 777 /var/log/nginx") cmd = "nano /var/log/nginx/error.log" command = "ssh -t -o StrictHostKeyChecking=no -i " + private_key_name +".pem ec2-user@" + dns + " " + cmd print(os.system(command)) except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("view_error_log method failed. Error: " + error) # a helper method which simply checks whether or not their is an instance # and if their is then whether or not it is running def running_check(): global instance if instance == None: print("No instance selected!") logger.status_log("No instance selected.") try: instance.update() if instance.state == 'running': return True else : print("Instance not running yet, please make sure it is running and then try again.") logger.status_log("User tried to access non-running instance.") return False except Exception as e: error = str(e) logger.status_log("running_check method failed. Error: " + error) # The main method is the method which controls the menu and flow of the program. # All menus are called from the menu.py module in this directory. def main(): menu.start_menu() global private_key_name print("Please enter key name, or leave blank for the default (stephencoady)") private_key_name = input(" >>> ") if private_key_name == "" : private_key_name = "stephencoady" decision = None # this while loop controls the "Main Menu" while decision != '0': menu.main_menu() decision = input("Please enter your choice >>> ") if decision == '1': new_instance() if decision == '2': print("Gathering information about your instances, please wait.") instance_choice = view_all_instances() global my_instances global instance if instance_choice != 'x' : submenu = None try: instance = my_instances[int(instance_choice)] except Exception as e: error = str(e) print("Please choose an instance from the list!") logger.status_log(error) submenu = '0' # this while loop controls the "Instance Manager" menu while submenu != '0': menu.instance_manager() submenu = input("Please enter your choice >>> ") if submenu == '1': start_instance() if submenu == '2': stop_instance() if submenu == '3': terminate_instance() if submenu == '4': install_python() if submenu == '6': run_user_command() if submenu == '5': # This while loop cntrols the "Nginx Manager" menu nginx_choice = None while nginx_choice != '0': menu.nginx_manager() nginx_choice = input("Please enter your choice >>> ") if nginx_choice =='1': install_nginx() if nginx_choice == '2': copy_web_script() if nginx_choice == '3': run_nginx_check() if nginx_choice == '4': visit_website() if nginx_choice == '5': view_access_log() if nginx_choice == '6': view_error_log() print("\nExiting! Goodbye!") if __name__ == '__main__': main()
cf512c1f4158e1c4258b225aa13e877ed36c5f4d
garrettsc/quadcopter
/analysis.py
325
3.578125
4
import matplotlib.pyplot as plt import numpy as np def power(T,rho, r): A = 2*np.pi*r return np.sqrt(T**3 / (2*rho*A)) thrust = np.arange(0,2000) rho=1.225 r = np.linspace(.1,1,thrust.shape[0]) p = power(thrust,rho,r) plt.scatter(p,thrust) plt.ylabel('Thrust [newtons]') plt.xlabel('Power [watts]') plt.show()
a4ec38841641f57356cf9121a716f39e313d2d43
DincerDogan/Data-Science-Learning-Path
/Data Scientist Career Path/7. Summary Statistics/8. Associations between Variables/2. Two Quantitative/2. scatter.py
308
3.6875
4
import pandas as pd import matplotlib.pyplot as plt import codecademylib3 housing = pd.read_csv('housing_sample.csv') print(housing.head()) #create your scatter plot here: plt.scatter(x = housing.beds, y = housing.sqfeet) plt.xlabel('Number of beds') plt.ylabel('Number of sqfeet') plt.show() plt.show()
aff958833090c9fef6a7e99d8a70728a28e43c0c
Yashasvini18/EDUYEAR-PYTHON-20
/age_calculator.py
130
3.984375
4
currentYear= 2021 birthYear=int(input("Enter ypu birth year ")) age=currentYear- birthYear print("Your age is ",age," years")
bb36b785bcdc3f0da89ca78804a9ac2d044f24b5
HeberCooke/Python-Programming
/Chapter4/exercise6.py
1,266
4.25
4
""" Heber Cooke 10/17/2019 Chapter 4 Exercise 6 This program takes in a message converts the characters to ascii, adds 1, and left shifts the bit and places it on the other side. It converts the bits back to ascii to print the code """ message = input("Enter a message: ") word = message.split() # splits the mesage into words list print("The CODE: ",end=" ") for i in message: # each word word = i for j in word: # each letter charValue = ord(j) + 1 # adding 1 to the ascii value # convert decimal to binary binaryString = '' while charValue > 0: remander = charValue % 2 charValue = charValue // 2 binaryString = str(remander) + binaryString # bit wrap one place to the left #print(binaryString) num = binaryString shiftAmount = 1 for i in range(0,shiftAmount):# shift Left temp = num[0] num = num[1:len(num)] + temp # print(num) # create the code from shifted bit string decimal = 0 exponent = len(binaryString) - 1 for digit in binaryString: decimal = decimal + int(digit) * 2 ** exponent exponent = exponent -1 print(chr(decimal), end="") print()
9340e2359e2133938ff6edec26d767dfdf60f6e3
Iyutwindayana22/Python-UAS
/tiga.py
1,036
3.5625
4
def fc(): print"Modul List Append" i=0 nama=[] nim=[] tugas=[] uts=[] uas=[] total=[] while True: s_nama=raw_input('Nama :') nama.append(s_nama) s_nim=raw_input('NIM :') nim.append(s_nim) i_tugas=input('Nilai Tugas :') tugas.append(i_tugas) i_uts=input('Nilai UTS : ') uts.append(i_uts) i_uas=input('masukan nilai uas :') uas.append(i_uas) rata=(i_tugas+i_uts+i_uas)/3 total.append(rata) lagi=' ' while lagi!='y' and lagi!='t': lagi=raw_input('Tambah Data [y/t] : ') i+=1 if lagi=='t': break print' DAFTAR MAHASISWA' print'=======================================================================' print'|No. | Nama | NIM | TUGAS | UTS | UAS | AKHIR |' print'=======================================================================' for n in range(i): print ' ',n+1, '|\t',nama[n],' |',nim[n],' |',tugas[n],' | ',uts[n],' | ',total[n],' |'
7f2376f128cffc506acd27c97f56573f263996eb
maratb3k/lab2
/Lab1/8/a.py
209
4
4
import math def distance(x1, y1, x2, y2): return math.sqrt((x1-x2)**2+(y1-y2)**2) x1 = float(input()) y1 = float(input()) x2 = float(input()) y2 = float(input()) print(distance(x1, y1, x2, y2))
f573f1dbbbccf484aa59f3d75dd0b53f2c73c10f
Garcluca/Homework-4-unit-testing
/avg.py
137
3.5
4
def calculate(arr): if len(arr) == 0: return 0 total = 0 for i in arr: total+= i return total/ len(arr)
c9110b5afcfbc81d940582fe56eda4c487adef40
daniel-reich/turbo-robot
/KYGpco9NFmJRyMQqj_7.py
982
4.28125
4
""" Create a function that returns the **smallest number of letter removals** so that two strings are **anagrams** of each other. ### Examples min_removals("abcde", "cab") ➞ 2 # Remove "d", "e" to make "abc" and "cab". min_removals("deafk", "kfeap") ➞ 2 # Remove "d" and "p" from the first and second word, respectively. min_removals("acb", "ghi") ➞ 6 # Remove all letters from both words to get "" and "". ### Notes * An anagram is any string that can be formed by shuffling the characters of the original string. For example: `baedc` is an anagram of `abcde`. * An empty string can be considered an anagram of itself. * Characters won't be used more than once per string. """ def min_removals(txt1, txt2): count = 0 for ch in txt1: if ch not in txt2: count+=1 for ch in txt2: if ch not in txt1: count+=1 return(count)
c69360e1c6d5de727bbab840240e68c6a3431bad
itsolutionscorp/AutoStyle-Clustering
/assignments/python/anagram/src/274.py
396
3.921875
4
from collections import Counter def detect_anagrams(original_word, possible_anagrams): original_word_count = Counter(original_word.lower()) list_of_anagrams = [] for word in possible_anagrams: if original_word_count == Counter(word.lower()) \ and not word.lower() == original_word.lower(): list_of_anagrams.append(word) return list_of_anagrams
412e1b1f397488beb70f6d1796bf24c15b68ccc6
lihararora/snippets
/python/crypto/cryptopals/s1_c8.py
1,157
3.828125
4
#!/usr/bin/python3 ''' @cryptopals: s1_c8 @description: detect_aes_ecb @author: Rahil Arora ''' import binascii ciphers = [line[:-1] if line[-1] == '\n' else line for line in open('challenge8.txt')] ''' Returns the numner of times common characters appear in the string ''' def stupid_score(sentence): score = 0 score = score + sentence.count(' ') + sentence.count('e') + sentence.count('t') + sentence.count('a') + sentence.count('o') + sentence.count('i') + sentence.count('E') + sentence.count('T') + sentence.count('A') + sentence.count('O') + sentence.count('I') return score if __name__ == "__main__": cipher_bytes = [binascii.unhexlify(c) for c in ciphers] encrypted = None for cb in cipher_bytes: i = 0 count = 0 for c in cb: ''' Count number of repeating 16 byte ciphertext blocks in a given ciphertext ''' if i < (len(cb) - 16): count = cb.count(cb[i:i+16]) i = i + 1 if(count > 1): encrypted = cb if encrypted != None: print("AES ECB encrypted text: ", binascii.hexlify(encrypted))
83bfe839e55036c93f802ff418fd9b70ea7c7cf2
JaiminSagar/HakerRankPyhtonPrograms
/NestedLists.py
496
3.53125
4
ps = [] # no = [] # naam = [] flag = 0 ans = [] for _ in range(int(input())): name = input() score = float(input()) ps.append([name, score]) # no.append(score) # naam.append(name) def sortSecond(val): return val[1] ps.sort(key=sortSecond) print(ps) for i in range(1, len(ps)): if ps[0][1] < ps[i][1] and flag == 0: ans.append(ps[i]) flag = 1 elif len(ans) != 0 and ans[0][1] == ps[i][1]: ans.append(ps[i]) for j in ans: print(j[0])
e56c4405eaf4386527dd21de69a197450a88b175
DouglasEDBR1/Python_Codes
/Repetition_Structure(Exercises)/Repetition_Structure_(Exercise1).py
191
3.859375
4
#1. Ler 5 notas e informar a média # Com o 'for' soma = 0 for nota in range (1, 6): nota = float(input(f'Digite a {nota}ª nota:')) soma = nota + soma media = soma / 5 print(media)
854dcb300a6bcff606ebf05d2d7f91a545a4f5b1
AdamZhouSE/pythonHomework
/Code/CodeRecords/2833/60768/235489.py
338
3.6875
4
cup = int(input()) remain = input().split(' ') remain = [int(x) for x in remain] capacity = input().split(' ') capacity = [int(x) for x in capacity] amount = 0 for i in remain: amount = amount + i capacity.sort() two_capacity = capacity[cup - 1] + capacity[cup - 2] if amount > two_capacity: print('NO') else: print('YES')
e3704481c48e11603b5fe3ef142fcec3cb665deb
Karvenko/MADE-Projects
/Algorithms/16 Geom/task_a.py
993
3.671875
4
"""Task A Solution""" class Point: def __init__(self, x, y): self.x = x self.y = y class Vector: def __init__(self, a, b): self.x = b.x - a.x self.y = b.y - a.y def scalar_product(self, other): return self.x * other.x + self.y * other.y def vector_product(self, other): return self.x * other.y - self.y * other.x class Segment: def __init__(self, a, b): self.a = a self.b = b def contains(self, c): v1 = Vector(self.a, c) v2 = Vector(self.b, c) scalar_product = v1.scalar_product(v2) vector_product = v1.vector_product(v2) if scalar_product <= 0 and vector_product == 0: return True else: return False if __name__ == '__main__': c_x, c_y, a_x, a_y, b_x, b_y = map(int, input().split()) s = Segment(Point(a_x, a_y), Point(b_x, b_y)) if s.contains(Point(c_x, c_y)): print('YES') else: print('NO')
743432d00a02b358e2c1edd6607a8c9b279b454c
wilwil186/python_intermedio
/debugging.py
561
3.859375
4
def divisors(num): divisors = [] for i in range(1, num + 1): if num % i == 1: divisors.append(i) return divisors def run(): divisors = lambda num: [x for x in range(1, num + 1) if num % x == 0] try: num = int(input('Ingresa un numero: ')) if num < 0: raise ValueError('Solo ingresa numeros positivos') print(divisors(num)) print("Termino") except ValueError: print('Solo Ingrese Numeros Positivos :|') if __name__ == '__main__': run()
f640c143e1b37da456ddcbcb239368fc4012b040
casaldev/curso-fundamentos-python
/aulas/continue.py
1,074
3.578125
4
# from datetime import date, timedelta # today = date.today() # tomorrow = today + timedelta(days=1) # products = [ # {'sku': '1', 'expiration_date': today, 'price': 100.00}, # {'sku': '2', 'expiration_date': tomorrow, 'price': 50.00}, # {'sku': '3', 'expiration_date': today, 'price': 20.00}, # ] # for product in products: # if product['expiration_date'] != today: # continue # product['price'] *= 0.8 # print(f"O preço por sku {product['sku']} agora é {product['price']}") # items = [0, None, 0.0, True, 0, 7] # found = False # for item in items: # print('Item de escaneamento', item) # if item: # found = True # break # if found: # print('Pelo menos um item avaliado como True') # else: # print('Todos os itens avaliados como False') class DriverException(Exception): pass people = [('Helena', 17), ('André', 13), ('Débora', 13), ('Julio', 16)] for person, age in people: if age >= 18: driver = (person, age) break else: raise DriverException('Motorista não encontrado')
50d7a4dae17acae4c8d0a85902b830af36cb80a0
teja1729/DataStructures-and-Algorithms-450-Questions-
/Arrays/_21SubarrayWithSum0.py
946
3.84375
4
''' Question:Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum. example Input : [4 2 -3 1 6] Input: [4 2 0 1 6] output: Yes Output:Yes Algorithm: Time complexity = O(n) Step 1 : Take a set and sum =0 Step 2 : as we traverse array we do add arr[i] to sum and check if it is 0 or if sum already exists,then we return True Step 3: if sum not is in set we add to set Step 4 : return false if we didn't got any answer ''' def solution(arr): set1 = set() sum1 = 0 for i in range(len(arr)):#O(n) sum1+=arr[i] if sum1==0 or sum1 in set1:#if sum1 = 0 subarray is exists with sum =0,sum1 is already exist means return True #for that sum to now the subarray sum is 0 set1.add(sum1) return False if __name__ =='__main__': arr = [4,2,-3,1,6] print(solution(arr))#Output: True arr1=[4,2,0,1,6] print(solution(arr1))#Output: True
b5636571f001396eaead5be873b1f4af51ace030
thisisyoojin/Linear-models-from-scratch
/linear_model/LinearRegression.py
4,165
3.671875
4
from model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt from linear_model import Batchifier, LinearModel class LinearRegression(LinearModel): def __init__(self, learning_rate=0.01, batch_size=16): """ Initialise linear regression model """ super().__init__(learning_rate=learning_rate, batch_size=batch_size) def fit(self, X_train, y_train, normalise=False, epochs=30, learning_rate=None, batch_size=None, draw=False, debug=True): """ Fit the model according to the given training data """ # Creates a validation dataset for training if normalise: X_train, X_val, y_train, y_val = self.normalise_train_data(X_train, y_train) else: X_train, X_val, y_train, y_val = train_test_split(X_train, y_train) # Set up the hyperparameters for a model if learning_rate is None: learning_rate = self.learning_rate if batch_size is None: batch_size = self.batch_size # Initialise the parameters for model self.w = np.random.randn(X_train.shape[1]) self.b = np.random.randn() # List for losses and early stopping loss train_losses = [] val_losses = [] # Create an instance for batchifier batchifier = Batchifier(batch_size=batch_size) # epochs: the number of running the whole dataset for epoch in range(epochs): losses_per_epoch = [] # Creates a shuffled batch batchifier.batch(X_train, y_train) # Train with batch for X_batch, y_batch in batchifier: y_pred = self.predict(X_batch) # Calculates the gradient and update params grad_w, grad_b = self.calculate_gradient(X_batch, y_batch, y_pred) self.w -= learning_rate * grad_w self.b -= learning_rate * grad_b # Calculates the loss loss_per_batch = self.calculate_loss(y_batch, y_pred) losses_per_epoch.append(loss_per_batch) train_losses.append(np.mean(losses_per_epoch)) if debug: print(f"Loss of epoch {epoch+1}: {np.mean(losses_per_epoch)}") # Validation loss y_val_pred = self.predict(X_val) val_loss = self.calculate_loss(y_val, y_val_pred) val_losses.append(val_loss) if draw: plt.plot(train_losses) plt.plot(val_losses) plt.show() return train_losses, val_losses def calculate_gradient(self, X, y, y_pred): """ Calculate gradient for the current parameters """ # calculate the gradient for weights(coefficient) # grad_individuals = [] # for idx in range(len(X)): # grad = 2 * (y_pred[idx] - y[idx]) * X[idx] # grad_individuals.append(grad) # grad_w = np.mean(grad_individuals, axis=0) # calculate the gradient for bias grad_w = 2 * (y_pred - y) @ X / len(X) grad_b = 2 * np.mean(y_pred - y, axis=0) return grad_w, grad_b def calculate_loss(self, y, y_pred): """ MSE(Mean Squared Error) """ return np.mean((y_pred - y)**2) def predict(self, X): """ Predict the values """ if self.w is None: raise Exception("You should fit a model first.") return np.matmul(X, self.w) + self.b def score(self, X_test, y_test, noramlise=True): """ Return the coefficient of determination R squared of the prediction """ if noramlise: X_test = (X_test - self.X_train_mean) / self.X_train_std y_pred = self.predict(X_test) # u is the residual sum of squres u = ((y_test - y_pred)**2).sum() # v is the total sum of squares v = ((y_test - y_test.mean()) ** 2).sum() return round(1 - u/v, 5)
f15cdb5c5bc491a4971c51592a5b37783ad90711
ashwani1310/Detect-Tables-In-PDFs
/src/detectRect.py
806
3.5
4
import cv2 import numpy as np def detect_rect(img): """ it detects the rectangles in the images if finds the rectangles which encloses minimum area :param img: np.array :return: list """ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1] image, cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) rect_coordinates = [] for cnt in cnts: rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) # box = np.int(box) rect_coordinates.append(box) # box # <- statement seems to have no effect # cv2.drawContours(again, [box], 0, (0, 255, 0), 2) return rect_coordinates
2c7b46dec79706d5dc6bb13cc2a63a55298e23b3
Miguelflj/Prog1
/CodesURI/exfibo.py
363
3.546875
4
def main(): fibo = []; fibo.append(0) fibo.append(1) fibo.append(1) qtd = int(input()) i = 0 j = 2 x = 0 while(x < qtd): pos = int(input()) if( pos > j): while(j < pos): j = j+1 fibo.append(fibo[j-1] + fibo[j-2]) print "Fib("+ str(pos) +") =",fibo[pos] else: print "Fib("+ str(pos) + ") =",fibo[pos] x = x +1 main()
d0a234807aabdb92fb6611c9fc6aea08c253a0df
axllow91/python-tut
/files.py
1,030
4.34375
4
# Python has functions for creating, reading, updating, and deleting files. # Open File # We can open a file that does not exist; it will be created automatically myFile = open('myfile.txt', 'w') # w for writting # Get info print('Name: ', myFile.name) print('Is Closed? ', myFile.closed) print('Opening Mode: ', myFile.mode) # Write something to file myFile.write('I love Python!') myFile.write('\nAnd I love Java') myFile.write('\nAnd I love Javascript') myFile.write('\nAnd I love C++') # Close file after we finished writting on it myFile.close() # To delete a file we need to import OS module # and then we can remove the file # import os # os.remove('myfile.txt') # Append to file myFile = open('myfile.txt', 'a') # a is for append something into file myFile.write(' I also like Typescript') myFile.close() # Read from file myFile = open('myfile.txt', 'r+') # r+ for reding from the file n_chars = 100 # max chars to read from the file text = myFile.read(n_chars) # reading the first 10 char print(text)
3caeb6939dcd68c07aeda81a692b35b20fc7f1f3
dj5353/Projects
/Tic_Tac_Toe.py
3,167
4.09375
4
#creating board board = ["-","-","-", "-","-","-", "-","-","-"] game_still_going = True winner = None player = "X" #displaying board def display_board(): print(board[0]+" |",board[1]+" |",board[2]) print(board[3]+" |",board[4]+" |",board[5]) print(board[6]+" |",board[7]+" |",board[8]) #handling players turn def handle_turn(player): print(player + "turn") position = input("choose a position from 1-9") while position not in ["1","2","3","4","5","6","7","8","9"]: position = input("Invalid Input! choose a position from 1-9") else: position = int(position)-1 while board[position] != '-': print('you cannot overwitre choose again') position = input("Invalid Input! choose a position from 1-9") position = int(position)-1 board[position] = player display_board() #this function calls other functions def play_game(): display_board() while game_still_going: handle_turn(player) check_if_game_over() flip_player() if winner == "X" or winner == "O": print(winner + "'s Won.") elif winner == None: print("it's a tie") def check_if_game_over(): check_if_win() check_if_tie() #if any rows or cols are matched def check_if_win(): global winner row_winner = check_row() col_winner = check_col() diaoganl_winner = check_diagonal() if row_winner: winner = row_winner elif col_winner: winner = col_winner elif diaoganl_winner: winner = diaoganl_winner else: winner = None #if any rows matches def check_row(): global game_still_going row_1 = board[0] == board[1] == board[2] != "-" row_2 = board[3] == board[4] == board[5] != "-" row_3 = board[6] == board[7] == board[8] != "-" if row_1 or row_2 or row_3: game_still_going = False if row_1: return board[0] elif row_2: return board[3] elif row_3: return board[6] #if any cols matches def check_col(): global game_still_going col_1 = board[0] == board[3] == board[6] != "-" col_2 = board[1] == board[4] == board[7] != "-" col_3 = board[2] == board[5] == board[8] != "-" if col_1 or col_2 or col_3: game_still_going = False if col_1: return board[0] elif col_2: return board[1] elif col_3: return board[2] #if diaoganlly matches def check_diagonal(): global game_still_going diag_1 = board[0] == board[4] == board[8] != "-" diag_2 = board[2] == board[4] == board[6] != "-" if diag_1 or diag_2: game_still_going = False if diag_1: return board[0] elif diag_2: return board[2] #if no one wins def check_if_tie(): global game_still_going if "-" not in board: game_still_going = False return #change(flip) turn of the player def flip_player(): global player if player == "X": player = "O" elif player == "O": player = "X" return play_game()
1900035fea24672551527d46a2314fa0e234f915
tokado/Algo1
/sort_algorithm/insertion_sort.py
667
3.890625
4
from help_instrument import counters def insertionSort(zoos): for i in range(1, len(zoos)): key_atribute = zoos[i].number_of_passengers key = zoos[i] j = i - 1 while j >= 0 and compare_element_from_insertsort(key_atribute, zoos[j].number_of_passengers): zoos[j + 1] = zoos[j] j -= 1 counters.swap_counter_insert += 1 zoos[j + 1] = key counters.swap_counter_insert += 1 def compare_element_from_insertsort(first_element, second_element): counters.compare_counter_insert += 1 if first_element < second_element: return True else: return False
7a169600df92760118462e94afbe152b87793970
falcon-ram/PythonTest
/test32_classvariables.py
1,020
3.875
4
class Employee: raise_amount = 1.04 # Class variable num_of_emps = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.num_of_emps += 1 def fullname(self): return f'{self.first} {self.last}' def apply_raise(self): #self.pay = int(self.pay * raise_amount) # raise amount is not defined #self.pay = int(self.pay * Employee.raise_amount) # this works # or self.pay = int(self.pay * self.raise_amount) emp_1 = Employee('me', 'maw', 20000) emp_2 = Employee('test2', 'noway', 30000) print(emp_1.pay) emp_1.apply_raise() print(emp_1.pay) Employee.raise_amount = 1.05 print(Employee.raise_amount) print(emp_1.raise_amount) print(emp_2.raise_amount) #print(Employee.__dict__) emp_1.raise_amount = 1.06 print(Employee.raise_amount) print(emp_1.raise_amount) print(emp_2.raise_amount) print() print(Employee.num_of_emps)
8f2855c7af78bc5efd29691d9cfa5856a0794889
OIrabor24/beginner-projects
/rock_paper_scissors.py
698
3.953125
4
import random def play(): user = input("Choose 'r' for rock, 'p' for paper, or 's' for scissors: ") computer = random.choice(['r', 'p', 's']) if not is_win(user, computer): return F"{user} not allowed!" if user == computer: return f"You tied! your opponent selected {computer}!" if is_win(user, computer): return f"You won {user} beats {computer}!" if is_win(user, computer) != True: return f"You lost! {computer} wins!" def is_win(player, opponent): # r > s s > p p > r if (player == 'r' and opponent == 's') or (player == 's' and opponent == 'p') or (player == 'p' and opponent == 'r'): return True print(play())
9ff288f5bbc01771b6c301065246541dd6d7673c
Loisa-Kitakaya/resources
/resource/madlibs.py
1,521
4.5625
5
""" Madlibs.py This program prompts the user for words, then prints a story with the words. Author: Loisa """ print ("Madlibs is starting...") user_name = input("Enter a name: ") adjective1 = input("Enter an adjective: ") adjective2 = input("Enter an adjective: ") adjective3 = input("Enter an adjective: ") verb = input("Enter a verb: ") noun1 = input("Enter a noun: ") noun2 = input("Enter a noun: ") animal = input("Enter an animal: ") food = input("Enter a food: ") fruit = input("Entera fruit: ") superhero = input("Enter a superhero: ") country = input("Enter a country: ") dessert = input("Enter a dessert: ") year = input("Enter a year: ") # The template for the story print ("This morning %s " % (user_name.upper()) + "woke up feeling %s. " % (adjective1.upper()) + "It was going to be a %s day! " % (adjective2.upper()) + "Outside, a bunch of %ss were protesting " % (animal.upper()) + "to keep %s in stores. " % (food.upper()) + "They began to %s " % (verb.upper()) + "to the rhythm of the %ss, " % (noun1.upper()) + "which made all the %ss " % (fruit.upper()) + "very %s. " % (adjective3.upper()) + "Concerned, %s " % (user_name.upper()) + "texted %s, " % (superhero.upper()) + "who flew %s " % (user_name.upper()) + "to %s and dropped " % (country.upper()) + "%s in a puddle of frozen " % (user_name.upper()) + "%s. " % (dessert.upper()) + "%s woke up " % (user_name.upper()) + "in the year %s, " % (year) + "in a world where %ss ruled the world." % (noun2.upper()))