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
bf0c9587e2b002eeaf268c0772500bbf0462f5e0
adamsdenniskariuki/andelabootcamp
/test_loan.py
854
3.8125
4
import unittest from loan_calculator import loan_calculator #class to hold the test cases for the loan calculator class LoanCalculator(unittest.TestCase): #test to determine if the loan calculator works def test_it_works(self): self.assertEquals(loan_calculator(100000, 12, 12), 112000) #test to ensure the user inputs are integers or decimals is validated def test_inputs(self): self.assertEquals(loan_calculator("12000", "12", "45"), 'invalid input') #test to ensure the amount is validated def test_amount(self): self.assertEquals(loan_calculator(0, 12, 10), 'invalid amount') #test to ensure time is validated def test_time(self): self.assertEquals(loan_calculator(100000, 12, -10), 'invalid time') #test to ensure rate is validated def test_rate(self): self.assertEquals(loan_calculator(100000, -18, 10), 'invalid rate')
43f8b364c5f5d43067ac60d98c5169579039ec8b
999010alex/python-and-algorithms
/december22cw.py
1,110
3.90625
4
''' 1 ''' balance=100 intrest=1.1 print(balance*intrest**7) ''' 2 ''' savings=100 factor=1.10 print(savings*factor**7) result=194.8717 ''' 3 ''' string="compound interest" boolean=True ''' 4 ''' ''' 5 ''' print('I started with $100, and now I have $194.87, great!') ''' 1 ''' print("Hello","World","!") ''' 2 ''' #You get a syntax error because "World! is not closed off. ''' 3 ''' #print("Helu","word","?") #print(hello world!) #print("HELLO WORLD!" ''' 4 ''' ''' 5 ''' print("Guten tag!") ''' 6 ''' print(1+2+3+4+5+6+7+8+9+10) ''' 7 ''' print(1*2*3*4*5*6*7*8*9*10) ''' 8 ''' balance=1000 intrest=1.05 print(balance*intrest) print(balance*intrest**2) print(balance*intrest**3) ''' 9 ''' print(' ______\n| Alex |\n ------' ) ''' 10 ''' print(' ** * ***** * *') print(' * * * * * * ') print(' ****** * ***** * ') print('* * * * * * ') print('* * **** ***** * *') ''' 11 ''' print(' \\\// ') print(' +"""""+ ') print('(|o o|)') print(' | > | ') print(' | (-) | ') print(' | | ') print(' +-----+ ')
f7e15b4811b82823983cd7a3b3a4b03aa12a17ae
cIvanrc/problems
/ruby_and_python/2_condition_and_loop/guess_game.py
525
4.09375
4
# Generate a random number between 1 and 9 (including 1 and 9). # Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. from random import randint def guess_game(): i = randint(1,9) print(check_response(i)) def check_response(i): number = int(input("Digit a number: ")) output = '' if i < number: output = "too low" elif i > number: output = "too high" else: output = "exactly right" return output guess_game()
cd1d4e74b81f887a3823fde206322acadf985a62
nanli-7/algorithms
/994-rotting-oranges.py
2,629
3.9375
4
""" 994. Rotting Oranges - Easy ## breadth-first search In a given grid, each cell can have one of three values: the value 0 representing an empty cell; the value 1 representing a fresh orange; the value 2 representing a rotten orange. Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead. Example 1: Input: [[2,1,1],[1,1,0],[0,1,1]] Output: 4 Example 2: Input: [[2,1,1],[0,1,1],[1,0,1]] Output: -1 Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. Example 3: Input: [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0. Note: 1 <= grid.length <= 10 1 <= grid[0].length <= 10 grid[i][j] is only 0, 1, or 2. """ # Intuition # Every turn, the rotting spreads from each rotting orange to other adjacent # oranges. Initially, the rotten oranges have 'depth' 0 [as in the spanning tree # of a graph], and every time they rot a neighbor, the neighbors have 1 more depth. # We want to know the largest possible depth. # Algorithm # We can use a breadth-first search to model this process. Because we always # explore nodes (oranges) with the smallest depth first, we're guaranteed that # each orange that becomes rotten does so with the lowest possible depth number. # We should also check that at the end, there are no fresh oranges left. import collections class Solution(object): def orangesRotting(self, grid): """ :type grid: List[List[int]] :rtype: int """ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] count = 0 q = collections.deque() for r, row in enumerate(grid): for c, val in enumerate(row): if val == 2: q.append((r, c, 0)) elif val == 1: count += 1 result = 0 while q: r, c, result = q.popleft() for d in directions: nr, nc = r + d[0], c + d[1] if not (0 <= nr < len(grid) and 0 <= nc < len(grid[r])): continue if grid[nr][nc] == 1: count -= 1 grid[nr][nc] = 2 q.append((nr, nc, result + 1)) return result if count == 0 else -1 if __name__ == "__main__": grid = [[2, 1, 1], [1, 1, 0], [0, 1, 1]] res = Solution().orangesRotting(grid) print(res)
fbc641fbfe051f99816a68d61f84cd3f2d05d219
avengerryan/daily_practice_codes
/four_sept/programiz/three.py
219
4.3125
4
# Finding the square root # Pre filled number #num=9 # Taking input from the user num=float(input('enter a number: ')) num_sqrt=num**0.5 print('the square root of %0.3f is %0.3f'%(num, num_sqrt))
7fc21455fe1e9c298171688034df46be7fa00613
AnixDrone/QuestionGenerator
/question_generator.py
1,254
3.546875
4
import os while True: try: import docx break except: os.system("pip install docx") def newDoc(filename): doc = docx.Document() doc.save(filename) return doc def loadDoc(filename): return docx.Document(filename) def newQuestion(file, fileName): question = input("Enter question: ") num = stats(file) paragraph = file.add_paragraph(str(num+1) + ". " + question + '\n') for i in range(4): answer = input("Enter answers: "); paragraph.add_run('\t' + str(i+1) + '. ' + answer + '\n'); file.save(fileName) def stats(file): return len(file.paragraphs) def main(): fileName = input("Enter filename: ") badChars = ['<','>','?','\'','/','\\','*','|',':'] for c in badChars: fileName = fileName.replace(c,'') if not fileName.endswith(".docx"): fileName += ".docx" file = loadDoc(fileName) if os.path.exists(fileName) else newDoc(fileName) #print(stats(file)) while True: try: print(stats(file)+1) newQuestion(file, fileName) os.system("cls") except KeyboardInterrupt: break if __name__ == "__main__": main() else: exit()
d64a6cdf95b62df3960dc1de508ab0c8c9b552c1
sachasi/W3Schools-Python-Exercises
/src/05_Numbers/01_float_method.py
271
4.625
5
# Instructions: Insert the correct syntax to convert x into a floating point number. x = 5 # Solution: float() x = float(x) print(x) ''' The float() method can be used to transform an int to float. Read more here: https://www.w3schools.com/python/python_numbers.asp '''
048694c1b0fb6cac9751edcc4748a023f70eb7e3
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/ovdjon001/question4.py
751
3.5
4
"""question 4 20 April 2014 by Jonathan Ovadia""" def main(): marks = input("Enter a space-separated list of marks:\n").split(" ") print(histogram(marks)) def histogram(l): fail = "F |" third = "3 |" lower_second = "2-|" upper_second = "2+|" first = "1 |" for i in range(len(l)): if eval(l[i]) < 50 : fail+="X" elif eval(l[i]) > 49 and eval(l[i]) < 60: third +="X" elif eval(l[i]) > 59 and eval(l[i]) < 70: lower_second +="X" elif eval(l[i]) > 69 and eval(l[i]) < 75: upper_second +="X" else: first+="X" return first + "\n" + upper_second + "\n" + lower_second + "\n" +third + "\n" + fail main()
bef10f95ceccfa83d6a6203c070a1a340e587fc2
aumaro-nyc/leetcode
/trees/199.py
1,160
3.78125
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 rightSideView(self, root: TreeNode) -> List[int]: # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution: def rightSideView(self, root: TreeNode) -> List[int]: if not root: return [] result = [] level = deque() waiting = deque() level.append(root) while level: added = False while level: temp = level.popleft() if not added: result.append(temp.val) added = True waiting.append(temp) while waiting: temp = waiting.popleft() if temp.right is not None: level.append(temp.right) if temp.left is not None: level.append(temp.left) return result
bc1268e26aa7b4de94718725a09272f5a7c008b8
Gaurav-dawadi/Python-Assignment-II
/question16.py
1,722
4.1875
4
"""Imagine you are creating a Super Mario game. You need to define a class to represent Mario. What would it look like? If you aren't familiar with SuperMario, use your own favorite video or board game to model a player.""" class fifaPlayer(): def __init__(self, name, age, position, nationality, overallRating): self.name = name self.age = age self.position = position self.nationality = nationality self.overallRating = overallRating def playerInfo(self): print("-------PLAYER INFO-------") print('\n') print("Name of Player: ", self.name) print("Age of Player: ", self.age) print("Position of Player: ", self.position) print("Nationality of Player: ", self.nationality) print("OverallRatings of Player: ", self.overallRating) print("-------------------------------------") print('\n') def awardsWon(self): print('\n') print("Bundesliga Young Player of the Hinrunde: 2010") print("Korean Footballer of the Year: 2013, 2014, 2017, 2019") print("Tottenham Hotspur Player of the Season: 2018–19") print("Tottenham Hotspur Goal of the Season: 2017–18, 2018–19") print("Premier League Goal of the Month: November 2018, December 2019") print("AIPS ASIA Best Asian Male Athlete: 2018") print("FIFA FIFPro World11 nominee: 2019") print("London Player of the Year: 2018–19 Premier League") playerOne = fifaPlayer('Son Heung Min', 27, 'Left Wing', 'South Korea', 90) playerOne.playerInfo() print("--------Individuals Award One--------") playerOne.awardsWon() print("------------------------------------------")
c358d14d4aba8db12aaddee3f837a2d5383bc811
tiavlovskiegor24/Algorithms
/assignment2.py
1,464
4.1875
4
from random import randint def median(points): for point1 in points: for point2 in points: for point3 in points: if points[point1] < points[point2] and points[point2] < points[point3]: return point2 def swap(array,i1,i2): swap = array[i1] array[i1] = array[i2] array[i2] = swap def partition(array,l,r): q = l+1 for j in range(l+1,r): if array[j] < array[l]: swap(array,q,j) q += 1 swap(array,l,q-1) return q def quick_sort(array,l = 0,r = None): global comparisons if r == None: r = len(array) if r-l <= 1: return #p = l # case 1 #p = r-1 # case 2 #case 3 median of three points '''if r-l >= 3: p = median({l:array[l],(r-1)-(r-l)/2:array[(r-1)-(r-l)/2],r-1:array[r-1]}) else: p = l''' p = randint(l,r-1) # partition the array and return the index of pivot element swap(array,p,l) q = partition(array,l,r) comparisons += r-l-1 quick_sort(array,l,q-1) quick_sort(array,q,r) with open("assignment2.txt","r") as f: array = [] for line in f: array.append(int(line)) f.closed comparisons = 0 comp_array = [] for i in range(20): copy = [element for element in array] quick_sort(copy) comp_array.append(comparisons) comparisons = 0 print sum(comp_array)/len(comp_array)
a9ef46e598905edfd8d2f3f0454a47d74ab987e5
Uzbec/mini_paint
/main.py
834
3.609375
4
from sys import argv import os import ft_len from pathlib import Path BASE_DIR = Path(__file__).resolve().parent if len(argv) == 2: a = argv[1] elif len(argv) > 2: print("Error: a lot of arguments") a = None print() else: a = input() if " " in a: print("Error: a lot of arguments") a = None print() if a: #if str(BASE_DIR) not in a: #a = f"{BASE_DIR}/{a}" print(a) if "operation" in a and "operation.it" not in a: a = None print("Error:Operation file has not correct extension") print() if a: try: file = open(a) except FileNotFoundError as e: a = None print("Error:name file\n") except IOError as e: a = None print("Error:Operation file corrupted")
61399623115b8bc74758aac67036ef7a8fec97e6
thegreatcodini/mac_address_app
/mac_address.py
938
4.03125
4
#!/usr/bin/env python3 import sys import requests import re def check_mac(mac): """use this function to check if a string supplied is a mac address""" return re.match('[0-9a-f]{2}([-:.]?)[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$', mac.lower()) def getCompany(): """use this function to query the macaddress.io API with the api key and mac address""" try: API_AUTH_KEY=sys.argv[1] MAC=sys.argv[2] except IndexError: sys.exit("error: please the following format 'mac_address.py <api key> <mac address>'") url='https://api.macaddress.io/v1?apiKey='+API_AUTH_KEY+'&output=vendor&search='+MAC.lower() if not check_mac(MAC): sys.exit("please enter a valid mac address") try: resp = requests.get(url) except Exception: sys.exit("error: Issue with api request. Please check parameters.") else: print(resp.text) if __name__ == "__main__": getCompany()
8540f0543c8f96ab79f7b7bb8241517b4268998d
bp2070/vr_software_renderer
/Geometry.py
5,247
3.984375
4
""" Bryan Petzinger Vector & Matrix based on: http://www.math.okstate.edu/~ullrich/PyPlug/ """ import math from numbers import Real from operator import add, sub, mul class Vector(object): def __init__(self, data): self.data = data def Len(self): return math.sqrt(reduce(add, map(lambda x: math.pow(x, 2), self))) def Normalize(self): length = self.Len() return Vector(map(lambda x: x/length, self)) def Dot(self, other): if not isinstance(other, Vector): raise Exception if len(self) != len(other): raise Exception return reduce(add, map(mul, self, other)) def Cross(self, other): """only valid for 3-dimensional vectors""" if len(self) != 3 or len(other) != 3: raise Exception x = (self[1] * other[2]) - (self[2] * other[1]) y = (self[2] * other[0]) - (self[0] * other[2]) z = (self[0] * other[1]) - (self[1] * other[0]) return Vector([x, y, z]) def __add__(self, other): if len(self) != len(other): raise Exception return Vector(map(add, self, other)) def __sub__(self, other): if len(self) != len(other): raise Exception return Vector(map(sub, self, other)) def __mul__(self, other): """multiplication against a scalar or matrix""" if isinstance(other, Real): return Vector(map(lambda x: x * other, self)) elif isinstance(other, Vector): return Vector(map(other.Dot, self)) else: raise Exception def __str__(self): result = ', '.join(map(str, self)) return '{' + result + '}' def __getitem__(self, index): return self.data[index] def __len__(self): return len(self.data) class Matrix(Vector): """default to identity matrix""" def __init__(self, data = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]): self.data = map(Vector, data) def Transpose(self): return Matrix(zip(*self.data)) def RotateX(self, theta): return Matrix([[1, 0, 0, 0], [0, math.cos(theta), -math.sin(theta), 0], [0, math.sin(theta), math.cos(theta), 0], [0, 0, 0, 1]]) def RotateY(self, theta): return Matrix([[math.cos(theta), 0, math.sin(theta), 0], [0, 1, 0, 0], [-math.sin(theta), 0, math.cos(theta), 0], [0, 0, 0, 1]]) def RotateZ(self, theta): return Matrix([[math.cos(theta), -math.sin(theta), 0, 0], [math.sin(theta), math.cos(theta), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) def Scale(self, x = 1, y = 1, z = 1): return Matrix([[x, 0, 0, 0], [0, y, 0, 0], [0, 0, z, 0], [0, 0, 0, 1]]) def Translate(self, x = 0, y = 0, z = 0): return Matrix([[1, 0, 0, x], [0, 1, 0, y], [0, 0, 1, z], [0, 0, 0, 1]]) class Vertex(Vector): def __init__(self, x, y, z, w = 1): super(Vertex, self).__init__([x,y,z,w]) class Polygon: def __init__(self, verticies = [], color = (255, 255, 255)): self.verticies = verticies self.color = color def AddVertex(self, vertex): self.verticies.append(vertex) def GetVertex(self, index): return self.verticies[index] def GetVerticies(self): return self.verticies def SetColor(self, color): self.color = color def GetColor(self): return self.color def __str__(self): result = ', '.join(map(str, self)) return '{' + result + '}' def __getitem__(self, index): return self.verticies[index] def __len__(self): return len(self.verticies) class Mesh: def __init__(self, polygons = []): self.polygons = polygons def AddPolygon(self, polygon): self.polygons.append(polygon) def GetPolygon(self, index): return self.polygons[index] def GetPolygons(self): return self.polygons def __str__(self): result = ', '.join(map(str, self)) return '{' + result + '}' def __getitem__(self, index): return self.polygons[index] def __len__(self): return len(self.polygons) class Object(object): def __init__(self, mesh = None): self.mesh = mesh self.world_rotate = Matrix() self.world_scale = Matrix().Scale() self.world_translate = Matrix().Translate() self.parent = None self.color = None def SetColor(self, color): self.color = color def GetColor(self): return self.color def ReferenceMesh(self, mesh): self.mesh = mesh def SetParent(self, parent): self.parent = parent def GetParent(self): return self.parent def SetPos(self, (x, y, z)): self.world_translate = Matrix().Translate(x, y, z) def Rotate(self, rot_matrix): self.world_rotate *= rot_matrix def Translate(self, trans_matrix): self.world_translate *= trans_matrix def Scale(self, scale_matrix): self.world_scale *= scale_matrix def GetMesh(self): return self.mesh def GetTranslateMatrix(self): return self.world_translate def GetConMatrix(self): return Matrix(self.world_scale * self.world_rotate * self.world_translate) class Camera: def __init__(self): self.view_rotate = Matrix() self.view_scale = Matrix().Scale() self.view_translate = Matrix().Translate() def GetViewMatrix(self): return Matrix(self.view_scale * self.view_rotate * self.view_translate) def Translate(self, trans_matrix): self.view_translate *= trans_matrix def Rotate(self, rot_matrix): self.view_rotate *= rot_matrix
ea01738e54dd60d15c3f3e9ca51d5ddc311b2773
karacanil/BasicProjects
/sudokusolver.py
2,436
3.59375
4
import time # Starting the timer start_time = time.time() # Inserting the sudokus in a 9x9 form #Example1 inp = [[0,0,0,2,0,0,0,0,9], [0,0,0,0,9,0,0,3,6], [0,0,0,0,0,5,1,4,0], [0,3,0,0,4,6,8,7,0], [1,0,0,0,2,0,0,0,3], [0,7,2,3,5,0,0,1,0], [0,2,5,8,0,0,0,0,0], [9,4,0,0,1,0,0,0,0], [6,0,0,0,0,4,0,0,0]] #Example2 inp2 = [[8,0,0,0,0,0,0,0,0], [0,0,3,6,0,0,0,0,0], [0,7,0,0,9,0,2,0,0], [0,5,0,0,0,7,0,0,0], [0,0,0,0,4,5,7,0,0], [0,0,0,1,0,0,0,3,0], [0,0,1,0,0,0,0,6,8], [0,0,8,5,0,0,0,1,0], [0,9,0,0,0,0,4,0,0]] def solver(grid, r=0, c=0): r,c = nextCell(grid, r ,c) # r stands for row, c stands for column if r == -1 or c == -1: # Checking if program run out of unprocessed cells # Terminating the process return True for num in range(1,10): if iscorrect(grid, r, c, num): grid[r][c] = num # Assigning the correct value to the certain cell if solver(grid, r, c): # Checking if all the values are valid and proper by calling the function again ''' for i in grid: print(i) print('\n\n\n') ''' return True grid[r][c] = 0 return False def nextCell(grid, r, c): # Determining a cell to process for i in range(9): for k in range(9): if grid[i][k] == 0: return i,k # Returning -1,-1 for the if statement on the 33th line to terminate the program return -1,-1 def iscorrect(grid, r, c, num): topleftr = 3*(r//3) #Determining the r of the top left element topleftc = 3*(c//3) #Determining the c of the top left element if all([num != grid[r][i] for i in range(9)]): #Checking the row if all([num != grid[k][c] for k in range(9)]): #Checking the column #Checking the 3x3 grid for i in range(topleftr,topleftr+3): for k in range(topleftc,topleftc+3): if grid[i][k] == num: return False return True return False ''' for i in inp: print(i) solver(inp) print(3*('\n')) for i in inp: print(i) ''' for i in inp2: print(i) solver(inp2) print(2*('\n')) for i in inp2: print(i) print('\n\nIt took %s seconds to solve that sudoku'%(time.time() - start_time))
8a88ed616fea1b4806c741092040ec3f28ffddaa
g-hurst/Python-For-Teenagers-Learn-to-Program-Like-a-Superhero-codes
/super hero quiz.py
866
3.625
4
wonderBoyScore = 82 #intro text print("aCongrats on finnishing your Super-Hero Intelligence and Reasoniong Test.") print("or, S Q U I R T for short.") print("lets see if you passed.") print("A passing score means you are liscenced to be a sidekick.") #checks to see if Wonder Boy passed or not if wonderBoyScore > 60: print("Here are your results:") if wonderBoyScore > 60 and wonderBoyScore < 70: print("Well, you passed by the skin of your teeth.") elif wonderBoyScore >= 70 and wonderBoyScore < 80: print("You passed... average isnt so bad. Im sure youll make up for it with heart.") elif wonderBoyScore >= 80 and wonderBoyScore < 90: print("Wow, not bad at all! Youre a regular B+ player!") elif wonderBoyScore >= 90: print("Great job! A+") else: print("Sorry buddy, you failed.")
7447000604ba079441bfd82b99a03bd2e8de26fb
douradodev/Uri
/Uri/1096_v2.py
203
3.53125
4
def imprime_seq(I, J, num=3): if num: print('I={}'.format(I), 'J={}'.format(J)) imprime_seq(I, J-1, num-1) def seq_IJ02(I=1, J=7): if I <= 9: imprime_seq(I,J) seq_IJ02(I+2, J=7) seq_IJ02()
a61b1c58115a09357bd9008373a0f2567e7e4a12
dylanawhite92/Python-Graphics
/Simple Code Blocks/graphics/turtle/ClickSpiral.py
518
4.125
4
import random import turtle t = turtle.Pen() t.speed(0) turtle.bgcolor("black") # List of colors available colors = [ "red", "yellow", "blue", "green", "orange", "purple", "white", "gray" ] # Define function for drawing spirals of random colors and sizes on click def spiral(x,y): t.pencolor(random.choice(colors)) size = random.randint(10,40) t.penup() t.setpos(x,y) t.pendown() for m in range(size): t.forward(m*2) t.left(91) turtle.onscreenclick(spiral)
305cfb82d3e69a53a9ccc2d72940e1af30ce6879
midhunmdrs/Python-Projects
/loops/while_loops.py
212
4.03125
4
i = 6 while(i >= 1): print("Rocky Bai" , end = " ") #end is used to print in same line i = i - 1 j = 4 while(j >= 1): print("rocks" , end = " ") j = j - 1 print()
954e6f9ab4770826ad54bc799a054515b8ea85e2
HashtagPradeep/python_practice
/control_flow_assignment/Assignment- Control Flow_Pradeep.py
886
4.46875
4
#!/usr/bin/env python # coding: utf-8 # --- # --- # # <center><h1>📍 📍 Assignment: Control Flow 📍 📍</h1></center> # # --- # # ***Take 3 inputs from the user*** # # - **What is your Age?** (Answer will be an Intger value) # - **Do you eat Pizza?** (Yes/No) # - **Do you do exercise?** (Yes/No) # # #### `Write the if else condition for the given flow chart.` # # ![](image/control-flow.png) # In[17]: # What is your Age? Age=int(input('What\'s your age?')) # In[11]: # Do you eat Pizza? pizza=input('Do you eat pizza?') # In[5]: # Do you do exercise? exercise=input('Do you exercise? ') # In[18]: if Age<30: if (pizza=='yes'): print('1.unfit') else: print('1.fit') else: if (exercise=='yes'): print('2.fit') else: print('2.unfit') # In[ ]: # In[ ]: # In[ ]:
b9e0ca60ac96ea375d02b3effe7f9e86076f62c1
Ruotongw/The-Truth-of-Asian-Restaurants
/scraping.py
4,888
3.546875
4
#Eric Mok, Siddhant Singh, Ruotong Wang #COMP 123 Lian Duan # In this program we do web-scraping from Yelp.com to build a database # of Chinese Restaurants in the Twin Cities #Requires BeautifulSoup to work. from bs4 import BeautifulSoup import urllib.request import urllib.error import json import csv yelpRestList=[] def restCompile(): """Here we compile a list of Chinese restaurants in the Twin Cities, the details of which we want to scrape and put into our database. We read the urls through python's urllib module""" yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/little-szechuan-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/rainbow-chinese-restaurant-and-bar-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/hong-kong-noodle-minneapolis-2")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/jun-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/red-dragon-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/tasty-pot-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/lepot-chinese-hotpot-minneapolis-2")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/mandarin-kitchen-minneapolis-2")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/pagoda-minneapolis-5")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/cheng-heng-restaurant-saint-paul")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/yangtze-st-louis-park")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/keefer-court-bakery-and-caf%C3%A9-minneapolis-2")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/lao-sze-chuan-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/grand-szechuan-bloomington-3")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/mandarin-kitchen-minneapolis-2")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/new-beijing-eden-prairie-2")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/caf%C3%A9-99-saint-paul-3")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/peking-garden-saint-paul")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/grand-shanghai-restaurant-saint-paul")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/shuang-cheng-restaurant-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/cathay-chow-mein-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/sidewalk-kitchen-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/xin-wong-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/kowloon-restaurant-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/tea-house-chinese-restaurant-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/szechuan-spice-minneapolis")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/hong-kong-noodle-minneapolis-2")) yelpRestList.append(urllib.request.urlopen("https://www.yelp.com/biz/mei-inn-chinese-foods-minneapolis")) listDict=[] def scraping(): """This function takes in no parameters. When it is called, it scrapes the urls found in the yelpRestList, which is a global variable. When it comes across the part of the URL which contains the data we want(in the url, the data is contained in a dictionary in json), it saves the data in a csv file where each key of the dictionary becomes a column title and each new row entry is a new restaurant.""" for i in range(len(yelpRestList)): yelpHtml = yelpRestList[i].read() yelpRestList[i].close() soup = BeautifulSoup(yelpHtml, "lxml") yelpRest = soup.find_all("script", type="application/ld+json") for links in yelpRest: listDict.append(json.loads(links.contents[0])) with open('names.csv', 'w', newline='',encoding='utf-8') as csvfile: fieldnames = ['review', 'servesCuisine','@type','aggregateRating','image','address','name','@context','telephone','priceRange'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(listDict) if __name__ == '__main__': restCompile() scraping() #to test the scraping function, we manually open the csv file we have created and go through it to ensure scraping happened properly.
0316d5567dbc85f94ea4a655a2872014b813b7de
BogomilaKatsarska/Python-Advanced-SoftUni
/Lists as Stacks and Queues - E1Q1.py
140
3.515625
4
input = list(input().split()) stack = [] while input: last_el = input.pop() stack.append(last_el) print(f"{' '.join(stack)}")
59e653746c5d1c8cd033d6612d0d4f0c466c4112
chrisglencross/advent-of-code
/aoc2021/day17/day17.py
1,044
3.703125
4
#!/usr/bin/python3 # Advent of code 2021 day 17 # See https://adventofcode.com/2021/day/17 import re with open("input.txt") as f: bounds = [int(value) for value in re.match("^target area: x=([-0-9]+)..([-0-9]+), y=([-0-9]+)..([-0-9]+)$", f.readline().strip()).groups()] def hit_target(fire_dx, fire_dy, bounds): x, y = 0, 0 dx, dy = fire_dx, fire_dy max_height = y while x <= bounds[1] and y >= bounds[2]: if dx == 0 and x < bounds[0]: break # Not enough x velocity to reach the target max_height = max(max_height, y) if bounds[0] <= x <= bounds[1] and bounds[2] <= y <= bounds[3]: return max_height x += dx y += dy dx = max(0, dx - 1) dy -= 1 return None max_height = 0 count = 0 for fire_dx in range(0, bounds[1]+1): for fire_dy in range(bounds[2], 1000): h = hit_target(fire_dx, fire_dy, bounds) if h is not None: max_height = max(max_height, h) count += 1 print(max_height) print(count)
dd10e1071576866fb2dc22692db6e1e96a998f36
setooc/python-programacion-uade
/Progra I - PYTHON/TP1/ej_7_modif.py
360
4.09375
4
def concatenar_numero (num1, num2): aux = num2 count = 0 while (aux > 1): aux = aux /10 count = count + 1 num1 = num1 * (10**count) num = num1 + num2 return num num1 = int(input("ingrese un numero: ")) num2 = int(input("Ingrese otro numero: ")) num3 = concatenar_numero(num1, num2) print(num1) print(num2) print(num3)
bd2871786201e5d6667ff10b449a3ec536bba23a
JONGSKY/Gachon_CS50_Python_KMOOC
/code/11/finally_exception.py
209
3.875
4
for i in range(0, 10): try: result = 10 // i print(i, "------", result) except ZeroDivisionError: print("Not divided by 0") finally: print("종료되었습니다.")
233802acbf9e19028a53521b75d6e780d616e814
Vance23/Homework_Ivan_Lihuta
/hw_17.py
550
3.734375
4
import math # квадратное уравнение (ax**2 + bx + c = 0) # d - дискриминант a = 10 b = 2 c = 0 def solve_quadratic_equation(a, b, c): d = b ** 2 - 4 * a * c print(d) if d > 0: x1 = (-b + math.sqrt(d)) / (2 * a) x2 = (-b - math.sqrt(d)) / (2 * a) return(x1, x2) elif d == 0: x1 = -b / (2 / a) x2 = None return (x1, x2) else: x1 = None x2 = None return(x1, x2) print(solve_quadratic_equation(a, b, c))
dee2235dc4dc85be61fd707782906e0dcf70e8c5
Zhuhh0311/leetcode
/stack/backspaceCompare.py
2,185
3.796875
4
#844. 比较含退格的字符串 #给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。 #注意:如果对空文本输入退格字符,文本继续为空。 ''' 示例 1: 输入:S = "ab#c", T = "ad#c" 输出:true 解释:S 和 T 都会变成 “ac”。 ''' #自己的想法,将两个字符串都重构,然后比较是否相等,使用栈存储重构后的结果 #思路没问题,但是代码冗余 class Solution: def backspaceCompare(self, S: str, T: str) -> bool: stack_s, stack_t = [], [] for i in S: if stack_s: if i == '#': stack_s.pop() else: stack_s.append(i) else: if i != '#': stack_s.append(i) for i in T: if stack_t: if i == '#': stack_t.pop() else: stack_t.append(i) else: if i != '#': stack_t.append(i) return stack_s == stack_t #同样的思路,看人家官方题解多简洁明了。。。 #时间复杂度O(M+N),空间复杂度也是O(M+N) class Solution: def backspaceCompare(self, S: str, T: str) -> bool: def build(S): ans = [] for s in S: if s != '#': ans.append(s) elif ans: ans.pop() #return ans 这一步直接比较ans不join也可以,join的话与题目示例的输出相同,均为str return ''.join(ans) return build(S) == build(T) #官方题解给出的另一种方法,反向遍历 #yield 是个知识点 class Solution(object): def backspaceCompare(self, S, T): def F(S): skip = 0 for x in reversed(S): if x == '#': skip += 1 elif skip: skip -= 1 else: yield x return all(x == y for x, y in itertools.izip_longest(F(S), F(T)))
5a15d172a0595061722c6b7e079cb9ce9e918c0a
AkankshaRakeshJain/CodeChef
/FLOW006_SumOfDigits.py
153
3.859375
4
user = int(input()) for value in range(user): number = input() sum = 0 for values in number: sum += int(values) print(sum)
17a61aa20200a17de4bf1998ab524a96d24762c5
rohanprateek/pythonprograms
/printingmatrixdiagonally.py
594
3.765625
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 25 19:36:10 2021 @author: Rohan Prateek """ class Solution: # @param A : list of list of integers # @return a list of list of integers def diagonal(self, A): n = int(2 * len(A) - 1) res = [list() for i in range(n)] print(res) for i in range(len(A)): for j in range(len(A)): print(i + j) res[i + j].append(A[i][j]) return res s = Solution() print(s.diagonal([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
2e36b810b128d7d5bef232a6dd9efcfadc86642c
ankit96/rejigthesystem
/src/clean.py~
983
3.75
4
''' 1)cleaning every word from tweet 2)input=list of words,op: list of cleaned words ''' __author__ = 'ankit' from classes import stopwords def clean(parliament): redundant=[':',",",")",".","(",";","/","|","-",'?','=','+'] i=0 flag=0 newobj=[] m=0 #print parliament for a in parliament: #print str(i)+' '+str(a) a=a.lower() if "http" in a or "\xe2\x80\xa6" in a: continue while a[-1] in redundant: if len(a)>1: a=a[:-1] else: a="n" while a[0] in redundant: if len(a)>1: a=a[1:] else: a="n" if ',' in a: b=a.split(',') flag=1 if a =='n' or a in stopwords : m=1 else: if flag==1: for m in b: if m not in newobj: newobj.append(m) flag=0 else: if a not in newobj: newobj.append(a) #print str(a) i=i+1 return newobj #clean(['#transformingindia.', 'in', 'defence', 'india', 'is', 'most', 'powerful', 'than', 'ever', 'before.', 'proud', 'of', 'pm.'])
ae2e919c0d420daf88f16a0356ab438c22403417
antonyaraujo/ClassPyExercises
/Lista02/Questao13.py
689
3.96875
4
# Escreva um programa para calcular o salário semanal de uma pessoa, determinado pelas # seguintes condições. Se o número de horas trabalhadas for menor ou igual a 40, a pessoa # recebe 8 reais por hora trabalhada, se não a pessoa recebe 320 reais fixos e mais 12 reais # para cada hora trabalhada que excede 40 horas. (Exemplo: uma pessoa que trabalha 42 # horas deve receber 344 reais). Seu programa deve ler o número de horas trabalhadas e # deve imprimir na tela o salário semanal. horas = int(input("Informe o número de horas trabalhadas: \n")) if (horas <= 40): salario = 8 * horas else: salario = 320 + 12*(horas-40) print("Seu salário semanal é de R$", salario)
a617695c04656236b944a2106b764fa02e2cedeb
chenxu0602/LeetCode
/1352.product-of-the-last-k-numbers.py
2,683
3.59375
4
# # @lc app=leetcode id=1352 lang=python3 # # [1352] Product of the Last K Numbers # # https://leetcode.com/problems/product-of-the-last-k-numbers/description/ # # algorithms # Medium (42.54%) # Likes: 397 # Dislikes: 23 # Total Accepted: 21.4K # Total Submissions: 50.3K # Testcase Example: '["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]\n' + '[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]' # # Implement the class ProductOfNumbers that supports two methods: # # 1. add(int num) # # # Adds the number num to the back of the current list of numbers. # # # 2. getProduct(int k) # # # Returns the product of the last k numbers in the current list. # You can assume that always the current list has at least k numbers. # # # At any time, the product of any contiguous sequence of numbers will fit into # a single 32-bit integer without overflowing. # # # Example: # # # Input # # ["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"] # [[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]] # # Output # [null,null,null,null,null,null,20,40,0,null,32] # # Explanation # ProductOfNumbers productOfNumbers = new ProductOfNumbers(); # productOfNumbers.add(3); // [3] # productOfNumbers.add(0); // [3,0] # productOfNumbers.add(2); // [3,0,2] # productOfNumbers.add(5); // [3,0,2,5] # productOfNumbers.add(4); // [3,0,2,5,4] # productOfNumbers.getProduct(2); // return 20. The product of the last 2 # numbers is 5 * 4 = 20 # productOfNumbers.getProduct(3); // return 40. The product of the last 3 # numbers is 2 * 5 * 4 = 40 # productOfNumbers.getProduct(4); // return 0. The product of the last 4 # numbers is 0 * 2 * 5 * 4 = 0 # productOfNumbers.add(8); // [3,0,2,5,4,8] # productOfNumbers.getProduct(2); // return 32. The product of the last 2 # numbers is 4 * 8 = 32 # # # # Constraints: # # # There will be at most 40000 operations considering both add and # getProduct. # 0 <= num <= 100 # 1 <= k <= 40000 # # # # @lc code=start class ProductOfNumbers: def __init__(self): self.nums = [1] def add(self, num: int) -> None: if num == 0: self.nums = [1] else: self.nums.append(self.nums[-1] * num) def getProduct(self, k: int) -> int: if k >= len(self.nums): return 0 return self.nums[-1] // self.nums[-k - 1] # Your ProductOfNumbers object will be instantiated and called as such: # obj = ProductOfNumbers() # obj.add(num) # param_2 = obj.getProduct(k) # @lc code=end
1a5b0b2a690cf5030d12a6cbd091c6f18aabaffa
brennon/eimutilities
/eim/tools/analysis.py
25,466
3.65625
4
import numpy as np import scipy.interpolate def bioemo_readings_to_volts(readings): """ Convert readings from the BioEmo sensor range to voltages. Parameters ---------- readings : array_like The readings to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted reading(s) as voltage(s) Raises ------ TypeError If ``readings`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> midrange = bioemo_readings_to_volts(512) >>> np.abs(midrange - 2.5024437927663734) < 0.001 True """ return (np.asarray(readings) / 1023.) * 5. def bioemo_volts_to_ohms(volts): """ Convert voltages from the BioEmo sensor to resistances in ohms. This mapping was empirically verified and is governed by the relationship: .. math:: \\begin{eqnarray} \\ln{V} &=& -1.17 \\times 10^{-3} R + 0.861 \\\\ \\ln{V} - 0.861 &=& -0.00117R \\\\ R &=& \\frac{\ln{V} - 0.861}{-0.00117} \\\\ R &=& \\frac{0.861 - \ln{V}}{0.00117} \\\\ R &=& \\frac{0.861}{0.00117} - \\frac{\\ln{V}}{0.00117} \\end{eqnarray} Parameters ---------- volts : array_like The voltages to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted voltage(s) as resistance(s) Raises ------ TypeError If ``volts`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> two_volts = bioemo_volts_to_ohms(2) >>> np.abs(two_volts - 143463.94823936306) < 0.001 True """ volts = np.asarray(volts) # left = 0.861 / 0.00117 # right = 1. / 0.00117 # right = right * np.log(volts) # return (left - right) * 1000 num = 1000 * np.log(volts) - 861 denom = -0.00117 return num / denom def bioemo_volts_to_siemens(volts): """ Convert voltages from the BioEmo sensor to conductances in siemens. Parameters ---------- volts : array_like The voltages to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted voltage(s) as conductance(s) Raises ------ TypeError If ``volts`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> two_volts = bioemo_volts_to_siemens(2) >>> np.abs(two_volts - 6.9703922990572208e-06) < 0.001 True """ ohms = bioemo_volts_to_ohms(volts) siemens = ohms_to_siemens(ohms) return siemens def bioemo_readings_to_siemens(readings): """ Convert readings from the BioEmo sensor to conductances in siemens. Parameters ---------- readings : array_like The voltages to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted reading(s) as conductance(s) Raises ------ TypeError If ``readings`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> midrange = bioemo_readings_to_siemens(512) >>> np.abs(midrange - -2.0793430561630236e-05) < 0.001 True """ readings = np.asarray(readings) volts = bioemo_readings_to_volts(readings) return bioemo_volts_to_siemens(volts) def ohms_to_siemens(ohms): """ Convert resistances in ohms to conductances in siemens. Parameters ---------- ohms : array_like The resistances to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted resistance(s) as conductance(s) Raises ------ TypeError If ``ohms`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> ohms_to_siemens(512) == 1. / 512 True """ return 1. / np.asarray(ohms) def siemens_to_ohms(siemens): """ Convert conductances in siemens to resistances in ohms. Parameters ---------- siemens : array_like The conductances to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted conductance(s) as resistance(s) Raises ------ TypeError If ``siemens`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> siemens_to_ohms(512) == 1. / 512 True """ return ohms_to_siemens(siemens) def unit_to_kilounit(measure): """ Convert measures in whole units to thousands of units. Parameters ---------- measure : array_like The measure(s) to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted measure(s) Raises ------ TypeError If ``measure`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> unit_to_kilounit(1) == 1. / 1000 True """ return measure / 1000. def unit_to_megaunit(measure): """ Convert measures in whole units to millions of units. Parameters ---------- measure : array_like The measure(s) to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted measure(s) Raises ------ TypeError If ``measure`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> unit_to_megaunit(1) == 1. / 1000000 True """ return measure / 1000000. def unit_to_gigaunit(measure): """ Convert measures in whole units to billions of units. Parameters ---------- measure : array_like The measure(s) to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted measure(s) Raises ------ TypeError If ``measure`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> unit_to_gigaunit(1) == 1. / 1000000000 True """ return measure / 1000000000. def unit_to_milliunit(measure): """ Convert measures in whole units to thousandths of units. Parameters ---------- measure : array_like The measure(s) to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted measure(s) Raises ------ TypeError If ``measure`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> unit_to_milliunit(1) == 1. * 1000 True """ return measure * 1000. def unit_to_microunit(measure): """ Convert measures in whole units to millionths of units. Parameters ---------- measure : array_like The measure(s) to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted measure(s) Raises ------ TypeError If ``measure`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> unit_to_microunit(1) == 1. * 1000000 True """ return measure * 1000000. def unit_to_nanounit(measure): """ Convert measures in whole units to billionths of units. Parameters ---------- measure : array_like The measure(s) to be converted Returns ------- out : float or :py:class:`numpy.ndarray` The converted measure(s) Raises ------ TypeError If ``measure`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> unit_to_nanounit(1) == 1. * 1000000000 True """ return measure * 1000000000. def contiguous_subsequences(sequence): """ Extract a list of the contiguous subsequences in ``sequence``. Parameters ---------- sequence : list of int A list of montotonically increasing integers Returns ------- list of list of int A list of lists of contiguous subsequences in ``sequence`` Examples -------- >>> contiguous_subsequences([]) [] >>> contiguous_subsequences([1]) [[1]] >>> contiguous_subsequences([1,2,3]) [[1, 2, 3]] >>> contiguous_subsequences([-4,2,3,4,5,10,11,12,13,14]) [[-4], [2, 3, 4, 5], [10, 11, 12, 13, 14]] """ subsequences = [] if len(sequence) == 0: return [] current_subsequence = [sequence[0]] for i in range(1, len(sequence)): if sequence[i] == current_subsequence[-1] + 1: current_subsequence.append(sequence[i]) else: subsequences.append(current_subsequence) current_subsequence = [sequence[i]] subsequences.append(current_subsequence) return subsequences def detect_artifacts(data, fs, up=0.2, down=0.1, signal_min=0., signal_max=1., window_size=0., mode='interpolate'): """ Using the method described in [1], detect and remove artifacts in an electrodermal activity signal. In summary, this method considers any increase in EDA greater than ``up`` or any decrease in EDA greater than ``down`` within a second to be an artifact. Artifacts can either be replaced with :py:class:`numpy.nan`, or the values in ``data`` before and after the artifact can be used to interpolate across the artifact. A window size can be set that will exclude data before and after each artifact. Parameters ---------- data : array_like The original data fs : int or float The sample rate of the original data up : float, optional The maximum absolute rise in amplitude that is allowable in one second expressed as a fraction of the entire signal range (the default is ``0.2``) down : float, optional The maximum absolute fall in amplitude that is allowable in one second expressed as a fraction of the entire signal range (the default is ``0.1``) signal_min : int, optional The minimum allowable value in ``data`` (the default is ``0.``) Values below ``signal_min`` will be set to ``signal_min``. signal_max : float, optional The maximum allowable value in ``data`` (the default is ``1.``) Values above ``signal_max`` will be set to ``signal_max``. window_size : float, optional If a window size is set (default is ``0.``), this value is taken as a window of ``window_size`` seconds that is centered over each detected artifact. All samples within this window are also considered artifacts. mode : str, optional If ``'interpolate'`` (the default), ``data`` will be interpolated across artifacts. If ``'nan'``, artifacts will be replaced with :py:class:`numpy.nan` Returns ------- clean_data : :py:class:`numpy.ndarray` The data with artifacts removed quality : float The percentage of the original signal that did not contain artifacts Raises ------ TypeError If ``arr`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> data = [0.1, 0.1, 0.1, 0.3, 0.1, 0.1] >>> clean, q = detect_artifacts(data, 2, signal_min=0, signal_max=0.3) >>> clean array([ 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) >>> np.testing.assert_almost_equal(q, 2./3.) >>> data = [0.1, 0.1, 0.1, 0.101, 0.1, 0.1] >>> clean, q = detect_artifacts(data, 2, signal_min=0, signal_max=0.3) >>> clean array([ 0.1 , 0.1 , 0.1 , 0.101, 0.1 , 0.1 ]) >>> q 1.0 >>> data = [0.1, 0.1, 0.1, 0.3, 0.1, 0.1] >>> detect_artifacts(data, 2, signal_min=0, signal_max=0.3, mode='nan')[0] array([ 0.1, 0.1, 0.1, nan, nan, 0.1]) >>> data = [0.5, 0.55, 0.5, 0.55, 0.1, 0.2, 0.55, 0.9] >>> detect_artifacts(data, 3, mode='nan')[0] array([ 0.5 , 0.55, 0.5 , 0.55, nan, nan, nan, nan]) >>> data = [0.5, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0] >>> detect_artifacts(data, 2, signal_min=0., signal_max=1., window_size=1., mode='nan')[0] array([ 0.5, 0.5, 0.5, nan, nan, nan, 1. , 1. , 1. ]) >>> data = [0., 0., 0.5, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0] >>> detect_artifacts(data, 2, signal_min=0., signal_max=1., window_size=1., mode='nan')[0] array([ 0., nan, nan, nan, nan, nan, 1., 1., 1.]) >>> data = [0., 0., 0., 0., 1., 1., 1., 1., 1.] >>> detect_artifacts(data, 2, signal_min=0., signal_max=1., window_size=2., mode='nan')[0] array([ 0., 0., nan, nan, nan, nan, nan, 1., 1.]) >>> data = [0., 0., 0., 0., 1., 1., 1., 1., 1.] >>> detect_artifacts(data, 2, signal_min=0., signal_max=1., window_size=3., mode='nan')[0] array([ 0., nan, nan, nan, nan, nan, nan, nan, 1.]) >>> data = [0., 0., 0., 0., 0., 0., 0., 0., 1.] >>> detect_artifacts(data, 2, signal_min=0., signal_max=1., window_size=3., mode='nan')[0] array([ 0., 0., 0., 0., 0., nan, nan, nan, nan]) >>> data = [0., 0., 1., 1., 1., 1., 1., 1., 1.] >>> detect_artifacts(data, 2, signal_min=0., signal_max=1., window_size=2., mode='nan')[0] array([ 0., nan, nan, nan, nan, 1., 1., 1., 1.]) >>> data = [0.5, 0.5, 0.5, 0.5, 0.4999, 0.5, 0.5, 0.5, 0.5] >>> detect_artifacts(data, 2, signal_min=0.5, signal_max=1., mode='nan')[0] array([ 0.5, 0.5, 0.5, 0.5, nan, 0.5, 0.5, 0.5, 0.5]) >>> data = [0.5, 0.5, 0.5, 0.5, 0.5001, 0.5, 0.5, 0.5, 0.5] >>> detect_artifacts(data, 2, signal_min=0., signal_max=0.5, mode='nan')[0] array([ 0.5, 0.5, 0.5, 0.5, nan, 0.5, 0.5, 0.5, 0.5]) .. [1] R. Kocielnik, N. Sidorova, F. M. Maggi, M. Ouwerkerk, and J. H. D. M. Westerink, “Smart Technologies for Long-Term Stress Monitoring at Work,” in Proceedings of the 2013 IEEE 26th International Symposium on Computer-Based Medical Systems (CBMS 2013), University of Porto, Porto, Portugal, 2013, pp. 53–58. """ data = np.array(data) artifact_count = 0 # Rises and falls should be positive percentages up = np.abs(up) down = np.abs(down) # Clip values outside of [signal_min, signal_max] # TODO: This should have an option to mark clipped values as artifacts min_clip_indices = data < signal_min max_clip_indices = data > signal_max normalized_data = np.clip(data, signal_min, signal_max) # print('data:', data) # print('normalized_data:', normalized_data) # Create a shifted copy of normalized data shifted_normalized_data = np.roll(normalized_data, 1) # print('shifted_normalized_data:', shifted_normalized_data) # shifted_normalized_data = np.roll(normalized_data, fs) # Calculate maximum allowable changes signal_range = np.abs(signal_max - signal_min) max_rise = up * signal_range max_fall = -down * signal_range # Convert max_rise and max_fall to sample-wise allowable rises/falls max_rise = max_rise / fs # print('max_rise:', max_rise) max_fall = max_fall / fs # print('max_fall:', max_fall) # Find differences differences = normalized_data - shifted_normalized_data # print('differences:', differences) # Find indices that are greater than max_rise or max_fall rise_artifact_indices = differences > max_rise # print('rise_artifact_indices:', rise_artifact_indices) fall_artifact_indices = differences < max_fall # print('fall_artifact_indices:', fall_artifact_indices) # Combine artifact index arrays artifact_indices = \ rise_artifact_indices + \ fall_artifact_indices + \ min_clip_indices + \ max_clip_indices # print('combined artifact_indices:', artifact_indices) # TODO: We could compare these to preceding values instead of losing them # Mark first fs indices as not artifacts artifact_indices[0:fs] = False # print('corrected artifact_indices:', artifact_indices) # Convert boolean indices to integer indices artifact_indices = np.nonzero(artifact_indices)[0] # print('integer artifact_indices:', artifact_indices) # window_size in samples window_n = 1 if window_size > 0. and len(artifact_indices) > 0: window_n = np.int(np.ceil(window_size * fs)) # Force odd window length if window_n % 2 == 0: window_n = window_n + 1 # For each artifact index, create a artifact 'window' artifact_window_indices = [] for artifact_index in artifact_indices: half_window_n = window_n // 2 this_window_indices = np.arange( artifact_index - half_window_n, artifact_index + half_window_n + 1 ) artifact_window_indices.append(this_window_indices) from functools import reduce artifact_indices = reduce(np.union1d, artifact_window_indices) # print('integer artifact_indices:', artifact_indices) # Chop spurious indices from beginning and end artifact_indices = artifact_indices[artifact_indices < len(data)] artifact_indices = artifact_indices[artifact_indices > 0] # print('integer artifact_indices:', artifact_indices) # Get contiguous subsequences artifact_indices = contiguous_subsequences(artifact_indices) # TODO: Remove indices greater than length of data # If last subsequence of artifacts is the end of data, extend last good # value in data and remove this subsequence from artifacts if len(artifact_indices) != 0: last_artifact_index = artifact_indices[-1][-1] if last_artifact_index == len(normalized_data) - 1: artifact_start = artifact_indices[-1][0] artifact_end = artifact_indices[-1][-1] + 1 artifact_count = artifact_count + artifact_end - artifact_start if mode == 'interpolate': normalized_data[artifact_start:artifact_end] = \ normalized_data[artifact_indices[-1][0] - 1] else: normalized_data[artifact_start:artifact_end] = np.nan artifact_indices.pop() for r in artifact_indices: artifact_count = artifact_count + len(r) if mode == 'interpolate': # TODO: We should use more than one index preceding and following artifact for interpolation # Add the previous and following indices onto r actual_artifact_indices = r.copy() non_artifact_indices = np.array([], dtype=np.dtype(np.int64)) to_prepend = np.arange(r[0] - 5, r[0]) to_append = np.arange(r[-1] + 1, r[-1] + 6) # r = np.insert(r, 0, r[0] - 1) # r = np.append(r, r[-1] + 1) non_artifact_indices = np.insert(non_artifact_indices, 0, to_prepend) non_artifact_indices = np.append(non_artifact_indices, to_append) too_low = non_artifact_indices < 0 too_high = non_artifact_indices > len(data) - 1 non_artifact_indices = non_artifact_indices[~(too_low + too_high)] interpolated_artifact = scipy.interpolate.pchip_interpolate( non_artifact_indices, data[non_artifact_indices], actual_artifact_indices ) normalized_data[r] = interpolated_artifact else: normalized_data[r] = np.nan quality = 1. - (artifact_count / len(data)) return normalized_data, quality def windows(data, length, stride=None, pad=None, equal_lengths=False): """ Separate an array into windows with an optional stride distance. Parameters ---------- data : array_like The array to be 'windowed' length : int The length of each window stride : int, optional The distance between window start indices. If ``None``, ``length`` is used as ``stride``. pad : int or float, optional If ``pad`` is specified (default is ``None``), ``data`` will be extended with the value of ``pad`` such that all windows are of length ``length``. equal_lengths : bool, optional If ``True`` (default is ``False``), only equal length windows will be returned. In the event that the values for ``length`` and ``stride`` would generate windows of uneven length at the end of data, these shorter windows are not returned. If ``False``, all windows are returned. In the event that the values for ``length`` and ``stride`` would generate windows of uneven length at the end of data, these shorter windows are returned. Returns ------- out : list of :py:class:`numpy.ndarray` A list of each of the windows of ``data`` in order Raises ------ TypeError If ``data`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> windows([0, 1, 2, 3, 4, 5], length=3) [array([0, 1, 2]), array([3, 4, 5])] >>> windows([0, 1, 2, 3, 4, 5], length=3, stride=1) [array([0, 1, 2]), array([1, 2, 3]), array([2, 3, 4]), array([3, 4, 5]), array([4, 5]), array([5])] >>> windows([0, 1, 2, 3, 4, 5], 3, 1, equal_lengths=True) [array([0, 1, 2]), array([1, 2, 3]), array([2, 3, 4]), array([3, 4, 5])] >>> windows([0, 1, 2, 3, 4, 5], 3, 1, pad=-1) [array([0, 1, 2]), array([1, 2, 3]), array([2, 3, 4]), array([3, 4, 5]), array([ 4, 5, -1]), array([ 5, -1, -1])] >>> windows([0, 1, 2, 3, 4, 5], 12, equal_lengths=True) [] >>> windows([0, 1, 2, 3, 4, 5], 12, equal_lengths=False) [array([0, 1, 2, 3, 4, 5])] >>> windows([0, 1, 2], length=1) [array([0]), array([1]), array([2])] >>> windows([0, 1, 2, 3, 4, 5], length=3, stride=4) [array([0, 1, 2]), array([4, 5])] """ # Local copy of data for padding local_data = np.array(data) # Check value of stride if stride is None: stride = length # Generate start indices starts = np.arange(0, len(local_data), stride) # Container for windows out = list() # Iterate over start indices for i in starts: window = local_data[i:i+length] if len(window) < length: if pad is not None: difference = length - len(window) tail = np.repeat(pad, difference) window = np.concatenate([window, tail]) out.append(window) elif equal_lengths is False: out.append(window) else: out.append(window) return out def pad_array(arr, length, pad=0): """ Pad an array to a specific ``length`` with a certain value. If ``length`` is less than the length of ``arr``, ``arr`` is returned unchanged. Parameters ---------- arr : array_like The array to be padded length : int The length of the array after padding pad : int or float, optional The value with which to extend **arr** Returns ------- out : :py:class:`numpy.ndarray` The padded array Raises ------ TypeError If ``arr`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> a = np.array([1,2,3]) >>> padded = pad_array(a, 5) >>> np.testing.assert_equal(padded, np.array([1,2,3,0,0])) >>> padded = pad_array(a, 6, pad=-1) >>> np.testing.assert_equal(padded, np.array([1,2,3,-1,-1,-1])) >>> padded = pad_array(a, 2, pad=-1) >>> np.testing.assert_equal(padded, np.array([1, 2, 3])) >>> np.testing.assert_equal(a, np.array([1,2,3])) """ arr = np.array(arr) tail_length = length - len(arr) if tail_length > 0: tail = np.repeat(pad, tail_length) return np.concatenate([arr, tail]) else: return arr def normalize_array(arr, range_min=0., range_max=1., clip=None): """ Scale the values in an array to the range ``[min, max]``, optionally clipping the values in ``arr``. Parameters ---------- arr : array_like The array to be normalized range_min : float, optional The minimum value in ``out`` (default is ``0.``). The minimum value in ``arr`` will be scaled to this value. range_max : float, optional The maximum value in ``out`` (default is ``1.``). The maximum value in ``arr`` will be scaled to this value. clip : tuple, optional If ``clip`` is specified (default is ``None``), it should be a tuple of length 2: ``(min, max)``. Values in ``arr`` that are less than this ``min`` will be set to ``min`` before normalization. Similarly, values in ``arr`` that are greater than this ``max`` will be set to ``max`` before normalization. Returns ------- out : :py:class:`numpy.ndarray` A normalized copy of ``arr`` Raises ------ TypeError If ``arr`` cannot be converted to a :py:class:`numpy.ndarray` Examples -------- >>> normalize_array([-2, 0, 2]) array([ 0. , 0.5, 1. ]) >>> normalize_array([-2, 0, 2], range_min=0.5, range_max=1.5) array([ 0.5, 1. , 1.5]) >>> normalize_array([1, 2, 3, 4, 5], clip=(2, 4)) array([ 0. , 0. , 0.5, 1. , 1. ]) >>> normalize_array([-2, 0, 2], range_min=1., range_max=0.) array([ 1. , 0.5, 0. ]) """ arr = np.array(arr) if clip is not None: arr = np.clip(arr, clip[0], clip[1]) old_range = np.max(arr) - np.min(arr) new_range = range_max - range_min return (((arr - np.min(arr)) * new_range) / old_range) + range_min
70b9497612178b97d69e5f675cfac26255819ed0
maxmartinezruts/Algorithms-Data-Structures
/largest_palindromic_sequence.py
900
3.96875
4
""" Author: Max Martinez Date: October 2019 Description: Given a string s, determine which is the longest palindrome hidden in s allowing to remove any character but not sorting s Complexity: O(n^2) Proof: Complexity = # guesses * time_guess = n^2 * O(1) = O(n^2) """ memo = {} def L(s): if s in memo: return memo[s] if len(s) == 1: memo[s] = s return s # If initial character i and final character j are equal, return i + L(s[1:-1]) + j if s[0] == s[-1]: sol = s[0] + L(s[1:-1]) + s[-1] memo[s] = sol return sol # If the characters are unequal, guess removing the first or the last character and opt for the max else: l1 = L(s[1:]) l2 = L(s[:-1]) if len(l1)>len(l2): memo[s] = l1 return l1 else: memo[s] = l2 return l2 print(L('turboventilator'))
47bc879c1917a2ce464d3a26087918bcc48fbcd7
JavierEsteban/Basico
/1.- Tipos De Datos/2.- Estructura de Datos.py
1,820
4.3125
4
# Estructura de Datos Python ''' ############################### ######### Listas : ########## ############################### ''' ### Listas : Las listas son esructuras flexibles que puede tener varios tipos de datos... " SON MUTABLES.. " lista_numeros = [1,2,3,4,5] print(lista_numeros) lista_textos = [1,'2',3,4,5] print(lista_textos ) listas_totales = lista_numeros + lista_textos print(listas_totales) ### Metodos : ''' append() -> agrega un elemento al final de la lista. extend() -> agrega otra lista a la lista. count() -> cuenta cuantos elementos se repiten en la lista. index() -> enumera el elemento de la posicion insert() -> inserta el elemnto en la posición. remove() -> elimina el elemnto en la posición. pop() -> devuelve el último valor de la lista. sort() -> ordenar la lista de elementos. ''' listas_frutas = ['Manzanas', 'Peras','Platanos', 'Yucas'] listas_frutas.append('Mandarinas') #append listas_frutas2 = ['Melon', 'Papaya'] listas_frutas.extend(listas_frutas2) #Extend() print(listas_frutas) listas_frutas.append('Manzanas') print(listas_frutas.count('Manzanas')) print(listas_frutas.index('Peras')) listas_frutas.insert(4, 'Manzanas') print(listas_frutas) listas_frutas.remove( 'Yucas') print(listas_frutas) ejemplo_lista1 = list() ejemplo_lista1.append('Melon') ejemplo_lista1.extend(['Melon', 'Papaya']) ejemplo_lista1 'naranjas' in ejemplo_lista1 ############################### ######### Tuplas : ########## ############################### ### Tuplas : Son un tipo de lista que tiene la caracteristica de ser inmutabe #Declaración de la tupla numeros = tuple() print (type(numeros)) numeros_1 = (0,1,2,3) print (type(numeros_1)) dictionario = { '1' : "Javier", '2' : "Roy"} print(dictionario.keys())
a89c0073bf567dc06b4685f08f5497dd5407da69
Aasthaengg/IBMdataset
/Python_codes/p02701/s706011545.py
99
3.53125
4
n = int(input()) dict = {} for i in range(0, n) : s = input() dict[s] = 1 print(len(dict))
1d93668af1b36e741a33e55667fda9919c2c34b3
mtlock/CodingChallenges
/CodingChallenges/Project_Euler/Euler_3.py
537
4.03125
4
#The prime factors of 13195 are 5, 7, 13 and 29. #What is the largest prime factor of the number 600851475143? #Change it to enter a number and find largest prime factor num=raw_input("Enter an odd integer: ") fnum=float(num) i=3 lst=list() while i<=fnum: k=3 a=0 if fnum%i==0: while k<i: if i%k==0: a=1 k=k+2 if a==0: lst.append(i) fnum=fnum/i i=i+1 print "The prime factors are", lst print "The largest prime factor is", lst[len(lst)-1]
747ab5c511d3a364309ea149398ded92eb23d748
Mil0dV/AoC-2018
/day2.py
655
3.96875
4
filename = "input-day2.txt" # filename = "input-day2-test.txt" def calculate_checksum(): file = open(filename, "r") doubles = 0 triples = 0 for line in file: double_letters = set() triple_letters = set() for char in line: if line.count(char) == 2: double_letters.add(char) if line.count(char) == 3: triple_letters.add(char) if len(double_letters) > 0: doubles += 1 if len(triple_letters) > 0: triples += 1 print(doubles) print(triples) return(doubles * triples) print(calculate_checksum())
15df55056f20f311bb6a66a7ebcaf1477f69bc74
ksheetal/MCA_NN
/hello.py
1,471
3.703125
4
#print("Hello! Python") #SHEETAL KUMAR import numpy as np def AND(x1, x2): x = np.array([1, x1, x2]) w = np.array([-1.5, 1, 1]) y = np.sum(w*x) if y <= 0: return 0 else: return 1 def OR(x1, x2): x = np.array([1, x1, x2]) w = np.array([-0.5, 1, 1]) y = np.sum(w*x) if y <= 0: return 0 else: return 1 def NAND(x1, x2): x = np.array([1, x1, x2]) w = np.array([1.5, -1, -1]) y = np.sum(w*x) if y <= 0: return 0 else: return 1 def NOT(x1): x = np.array([1,x1]) w = np.array([0.5,-1]) y = np.sum(w*x) if y <= 0: return 0 else: return 1 '''def NOR(x1,x2): x = np.array([1,x1,x2]) w = np.array([-1, 1, 1]) y = np.sum(w*x) if y <= 0: return 0 else: return 1''' if __name__ == '__main__': input = [(0, 0), (1, 0), (0, 1), (1, 1)] input_not = [0,1] print("\nAND") for x in input: y = AND(x[0], x[1]) print(str(x) + " - " + str(y)) print("\nOR") for x in input: y = OR(x[0], x[1]) print(str(x) + " - " + str(y)) print("\nNAND") for x in input: y = NAND(x[0], x[1]) print(str(x) + " - " + str(y)) print("\nNOT") for x in input_not: y = NOT(x) print(str(x) + " - " + str(y)) '''print("NOR") for x in input: y = NOR(x[0], x[1]) print(str(x) + " -> " + str(y)) '''
defb9f073b167c746a19c632369957d12ecf49c6
bdejene19/tkinterPythonCourse
/OpenFilesandDialogueBoxes.py
396
3.53125
4
from tkinter import * from tkinter import filedialog # is needed to open files anywhere on your computer root = Tk() root.title("Dialogue box") # come back to this lesson --> @2:47:00 #initialdir allows us to get file from anywhere on computer --> note: still trying to figure it out root.filename = filedialog.askopenfilename(initialdir="Bemnet/PycharmProjects/GUIs/images") root.mainloop()
249a6eb0e26f754537a8448f748c9871ad8d2e10
tanyastropheus/holbertonschool-higher_level_programming
/0x0B-python-input_output/0-read_file.alt.py
363
4.125
4
#!/usr/bin/python3 def read_file(filename=""): """print out the entire content of a file to stdout using UTF8 encoding Args: filename (str): file to be printed """ try: with open(filename, encoding='UTF8') as f: print(f.read(), end="") except (TypeError, IOError): print("Please enter a valid file name")
35b3bae86a38a1c1dca0f11082ed454b0a9d1ed6
yeshwanth2812/Python_Week2
/Week2_basic/Group_member.py
378
3.6875
4
# -*- coding: utf-8 -*- # @Author: Yeshwanth # @Date: 2021-01-04 18:58:12 # @Last Modified by: Yeshwanth # @Last Modified time: 2021-01-09 12:30:53 # @Title: Group_member def is_group_member(group_data, n): for value in group_data: if n == value: return True return False print(is_group_member([1, 5, 8, 3], 3)) print(is_group_member([5, 8, 3], -1))
d6f8b49ae0583c3e6456075f995a2ba888c0965d
GhostOsipen/pyRep
/leetcode/LengthOfLastWord.py
563
4.0625
4
# Given a string s consists of some words separated by spaces, # return the length of the last word in the string. # If the last word does not exist, return 0. def lengthOfLastWord(s: str) -> int: count = 0 rs = s[::-1] for i in rs: if i == " ": count += 1 else: break if count != 0: rs = s[-(count + 1)::-1] count = 0 for i in rs: if i != " ": count += 1 else: break return count print(lengthOfLastWord(" "))
b5afe2d8912041d73a8a14aeee6f81954179b05c
mhsimpson24/algorithms
/two_color.py
1,262
3.84375
4
class Graph(): def __init__(self, V): self.V = V self.adj = [[0 * self.V] * self.V] def twoColor(self, start): if self.V == 0: return "Trivially two colorable" color = ["NULL"] * self.V color[start] = "red" queue = [] queue.append(start) while len(queue) > 0: print queue p = queue.pop() if p in (self.adj[p]): return "Not two colorable" for p in range(self.V): for u in self.adj[p]: print queue if color[u] == "NULL": if color[p] == "NULL": color[p] = "red" if color[p] == "red": color[u] = "blue" else: color[u] = "red" queue.append(u) elif p in self.adj[u] and color[p] == color[u]: return "Not two colorable" if self.V == 1: return "Trivially two colorable" return "Two colorable with adjacency lists %s and vertex colors %s" % (self.adj, color)
13712aa9ee6581cdc87c817cb630001117e159b7
apriantoa917/Python-Latihan-DTS-2019
/LOOPS/loops - for examples.py
415
4.15625
4
#3.1.2.5 Loops in Python | for # for range 1 parameter -> jumlah perulangan for i in range(10) : print("perulangan ke",i) print() # for range 2 parameter -> angka awal perulangan, angka akhir perulangan a = 1 for i in range(3,10) : print(i," = perulangan ke",a) a+=1 print() # for range 3 parameter -> angka awal, angka akhir, pertambahan / iterasi for i in range(3,20,4) : print(i) print()
333dc9fd827d05719d19ac77e8611c72c25779e8
jaredchin/Core-Python-Programming
/第十一章/练习/11-3.py
305
3.578125
4
def max2(a,b): if a > b: return a else: return b def my_max(alist): if len(alist) == 0: return 'Can not be None' else: res = alist[0] for i in alist: res = max2(res, i) return res alist = [1,2,3,4,5,6,7] print(my_max(alist))
b8381abeac06851409641218402c718e708cbeaa
richartzCoffee/aulasUdemy
/templates2/dicCompre.py
251
3.796875
4
numero = {'a': 1 ,'b':2} print(numero) [print(f"{a} {b}") for a,b in numero.items()] lisa = [1,2,3,4,5,6] quadrado = {valor:valor**2 for valor in lisa} print(quadrado) res = {nun : ('par' if nun%2 ==0 else 'impar') for nun in lisa} print(res)
f7c2dc0e28916b8aac2c2cdaec206d2373d63c19
dking6902/pythonhardwaybookexercises
/ex18.py
460
3.703125
4
# this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") # ok that *args is pointless, do This def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}") # one argument def print_one(arg1): print(f"arg1: {arg1}") #no arguments def print_none(): print("I got nothing") print_two("Daniel", "King") print_two_again("Daniel", "King") print_one("Daniel") print_none()
bfacb7a3e3ef3ce2412532232268baa275270747
MinecraftDawn/LeetCode
/Medium/230. Kth Smallest Element in a BST.py
580
3.640625
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 kthSmallest(self, root: TreeNode, k: int) -> int: self.k = k self.ans = root self.inorder(root) return self.ans.val def inorder(self, node:TreeNode): if not node: return self.inorder(node.left) self.k -= 1 if self.k == 0: self.ans = node elif self.k > 0: self.inorder(node.right)
e1c6ae3e024b8e094f501ce6c3fceeb878f586bd
AlexsanderDamaceno/x86-assembler
/Tokenizer.py
3,112
3.609375
4
from TokenTypes import TokenType from Token import Token class Tokenizer(): def __init__(self, filestream): self.filestream = filestream self.text_pos = 0 def advance(self): self.text_pos += 1 def lookahead(self): orig = self.text_pos Token = self.nextToken() self.text_pos = orig return Token def look2ahead(self): orig = self.text_pos Token = self.nextToken() Token = self.nextToken() self.text_pos = orig return Token def nextToken(self): if self.text_pos >= len(self.filestream) - 1: print("end of file") return Token(TokenType.EOF , "EOF") while self.filestream[self.text_pos] == ' ': self.advance() if self.text_pos >= len(self.filestream) - 1: return Token(TokenType.EOF , "EOF") if self.filestream[self.text_pos].isalpha(): name = "" while self.filestream[self.text_pos].isalpha(): name += self.filestream[self.text_pos] self.advance() return Token(TokenType.Mnemonic , name) elif self.filestream[self.text_pos] == '%': self.advance() name = "" while self.filestream[self.text_pos].isalpha(): name += self.filestream[self.text_pos] self.advance() return Token(TokenType.Register , name) elif self.filestream[self.text_pos] == ',': self.advance() return Token(TokenType.Comma , ',') elif self.filestream[self.text_pos] == '$': self.advance() number = "" while self.filestream[self.text_pos].isdigit(): number += self.filestream[self.text_pos] self.advance() return Token(TokenType.Number , int(number)) elif self.filestream[self.text_pos] == '(': self.advance() return Token(TokenType.LPAREN , '(') elif self.filestream[self.text_pos] == ')': self.advance() return Token(TokenType.RPAREN , ')') elif self.filestream[self.text_pos] == ':': return Token(TokenType.Colon , ':') elif self.filestream[self.text_pos] == '-' or self.filestream[self.text_pos].isdigit(): val = '' flag = 0 if self.filestream[self.text_pos] == '-': flag = 1 self.advance() while self.filestream[self.text_pos].isdigit(): val += self.filestream[self.text_pos] self.advance() if flag: return Token(TokenType.Disp , -int(val)) else: return Token(TokenType.Disp , int(val)) elif self.filestream[self.text_pos] == '\n': self.advance() return Token(TokenType.NewLine , '\n')
55861d11eb9e3d52f6849c0840547c3035cbc622
Nicholas1771/Blackjack
/Hand.py
1,436
3.546875
4
from Card import Card class Hand: def __init__(self, cards): self.cards = cards self.bust = False def __str__(self): string = '' for card in self.cards: if card.visible: string += card.__str__() + ' ' else: string += 'XX' + ' ' return string def add_card(self, card): self.cards.append(card) def hand_value(self): values = [0] for card in self.cards: if card.visible: if card.rank == 'A': values.extend(values) for i, value in enumerate(values): if i < len(values)/2: values[i] += card.value[0] else: values[i] += card.value[1] else: for i, value in enumerate(values): values[i] += card.value for value in values: if value > 21 and len(values) > 1: values.remove(value) return tuple(set(values)) def check_hand(self): value = self.hand_value()[0] if value > 21: return 'bust' elif value == 21: return 'blackjack' else: return 'good' def get_and_remove_cards(self): cards = self.cards self.cards.clear() return cards
f96fac4ed8aae32de2c69ac415a4f5681147cc75
Rptiril/pythonCPA-
/chapter-3-pracise-set/Qno_4_findNreplace.py
163
3.796875
4
''' Write a program to detect double spaces in a string. ''' str = ''' Pake ped pe paka papita pinku pakde paka papita ''' s = str.replace(" "," ") print(s)
585d2339578ac1bbf8a6b88b70cffcc006257ed4
darrenredmond/programming_for_big_data_SROB
/calculator.py
2,367
3.796875
4
import math class Calculator(object): # addition def add(self, x, y): number_types = (int, long, float, complex) if isinstance(x, number_types) and isinstance(y, number_types): return x + y else: raise ValueError # subtraction def subtract(self, x, y): number_types = (int, long, float, complex) if isinstance(x, number_types) and isinstance(y, number_types): return x - y else: raise ValueError # multiplication def multiply(self, x, y): number_types = (int, long, float, complex) if isinstance(x, number_types) and isinstance(y, number_types): return x * y else: raise ValueError # division def divide(self, x, y): number_types = (int, long, float, complex) if isinstance(x, number_types) and isinstance(y, number_types): return x / y else: raise ValueError # exponent def exponent(self, x, y): number_types = (int, long, float, complex) if isinstance(x, number_types) and isinstance(y, number_types): return x ** y else: raise ValueError # square root def sqrt(self, x): number_types = (int, long, float, complex) if isinstance(x, number_types): return self.exponent(x, 0.5) else: raise ValueError # square def square(self, x): number_types = (int, long, float, complex) if isinstance(x, number_types): return self.exponent(x, 2) else: raise ValueError # cube def cube(self, x): number_types = (int, long, float, complex) if isinstance(x, number_types): return self.exponent(x, 3) else: raise ValueError # sine def sine(self, x): number_types = (int, long, float, complex) if isinstance(x, number_types): return math.sin(math.radians(x)) else: raise ValueError # cosine def cosine(self, x): number_types = (int, long, float, complex) if isinstance(x, number_types): return math.cos(math.radians(x)) else: raise ValueError
27f66f2f6fd727f304d5aa4f9319bb9a0d033e15
Nisar-1234/LeetCode-Hard
/1220-Count Vowels Permutation.py
1,959
3.671875
4
# https://leetcode.com/problems/count-vowels-permutation/ """ Example 1: Input: n = 1 Output: 5 Explanation: All possible strings are: "a", "e", "i" , "o" and "u". Example 2: Input: n = 2 Output: 10 Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua". Example 3: Input: n = 5 Output: 68 """ # n = 1 # n = 2 # n = 3 # 19 n = 5 # DP # Iteratively class Solution: def countVowelPermutation(self, n: int) -> int: MAX = 10**9 + 7 dp = [[0]*5 for _ in range(n)] # dp = [[0 for _ in range(5)] for _ in range(n)] for i in range(5): dp[0][i] = 1 for i in range(1, n): for j in range(5): if j == 0: # ends with the "a" vowel, previous could be "e", "i", "u". dp[i][j] = dp[i-1][1] + dp[i-1][2] + dp[i-1][4] elif j == 1: # ends with the "e" vowel, previous could be "a", "i". dp[i][j] = dp[i-1][0] + dp[i-1][2] elif j == 2: # ends with the "i" vowel, previous could be "e", "o". dp[i][j] = dp[i-1][1] + dp[i-1][3] elif j == 3: # ends with the "o" vowel, previous could be "i". dp[i][j] = dp[i-1][2] elif j == 4: # ends with the "u" vowel, previous could be "i", "o". dp[i][j] = dp[i-1][2] + dp[i-1][3] return sum(dp[n-1])%MAX # Runtime: 480 ms, faster than 36.62% of Python3 online submissions for Count Vowels Permutation. # Memory Usage: 117.5 MB, less than 20.52% of Python3 online submissions for Count Vowels Permutation. # If using: dp = [[0 for _ in range(5)] for _ in range(n)] # Runtime: 532 ms, faster than 33.51% of Python3 online submissions for Count Vowels Permutation. # Memory Usage: 117.7 MB, less than 19.22% of Python3 online submissions for Count Vowels Permutation. solution = Solution() print(solution.countVowelPermutation(n))
2ecc9286547fc1f7166caed9a7373035b3b6c84f
loveAlakazam/Homeworks2019
/ProgramTraining/SW_Expert_Academy/1974/1974.py
808
3.734375
4
# 소요시간: 3시간 넘음.. ㅠㅠ T= int(input()) test= sum(range(1,10))#45 for t in range(1, T+1): sudoku=list( list(map(int, input().split())) for _ in range(9)) #2차원 배열생성 result=1 #초기화(겹치는 숫자가 없다고 가정) # 행 for row in range(9): if( sum(sudoku[row])!=test): result=0 #열 for col in range(9): col_sum=[sudoku[row][col] for row in range(9)] if test!=sum(col_sum ): result=0 #3*3부분행렬 for row in range(0,9,3):#row=0,3,6 for col in range(0,9,3):#col=0,3,6 sub_sum=sum([sum(sudoku[r][col:col+3]) for r in range(row, row+3)]) if sub_sum!=test: result=0 break print('#{} {}'.format(t, result))
5d6d96933094c6c10ab536161a2b79da8e60a10b
selam-weldu/algorithms_data_structures
/leet_code/python/binary_trees/lca_with_parent.py
580
3.59375
4
# O(h) time, O(1) space def lca(node_one, node_two): def get_depth(node): depth = 0 while node: node = node.parent depth -= 1 return depth depth_one, depth_two = get_depth(node_one), get_depth(node_two) if depth_two > depth_one: node_one, node_two = node_two, node_one depth_diff = abs(depth_one - depth_two) while depth_diff: node_one = node_one.parent depth_diff -= 1 while node_one != node_two: node_one, node_two = node_one.parent, node_two.parent return node_one
6c028b45fa4d58940c2ea759163b13bd63e49d97
Nimrod-Galor/selfpy
/911.py
477
3.703125
4
def are_files_equal(file1, file2): """ check if files content is equal :param file1 file path :type string :param file2 file path :type string :return true if files content is the same :rtype bool """ res = False fo1 = open(file1, "r") f1l = fo1.read() fo2 = open(file2, "r") f2l = fo2.read() if f1l == f2l: res = True fo1.close() fo2.close() return res print(are_files_equal("726.py", "726.py"))
830ddf409cccd4910f33f4790c612b5e0fd6f33c
EEEEEEcho/requestDetail
/mutilProcessDemo/test7.py
1,123
4.21875
4
# 递归锁,为了将锁的粒度控制的更小,更精准,需要使用递归锁 # 缺点:很慢 import time import threading class Test: rlock = threading.RLock() def __init__(self): self.number = 0 def add(self): with Test.rlock: # 这里加了一把锁,执行execute方法,执行后释放 self.execute(1) def down(self): with Test.rlock: self.execute(-1) def execute(self,n): # with关键字的使用与打开文件的功能类似,实现自开合效果, # 会自动的加锁和释放 with Test.rlock: # 这里又加了一把锁,等到执行完加法之后释放 self.number += n def add(test): for i in range(10000000): test.add() def down(test): for i in range(10000000): test.down() if __name__ == '__main__': test = Test() # args传递方法执行所需要的参数 t1 = threading.Thread(target=add,args=(test,)) t2 = threading.Thread(target=down,args=(test,)) t1.start() t2.start() t1.join() t2.join() print(test.number)
29aabedf4ac88aaef7d4c63615b72ead4c269a91
havenshi/leetcode
/27. Remove Element.py
911
3.53125
4
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ i = 0 index = 0 while i < len(nums): if nums[i] == val: i += 1 else: # 常规的交换是可以的 nums[i], nums[index] = nums[index], nums[i] index += 1 i += 1 return index class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ j=len(nums)-1 for i in range(len(nums)-1,-1,-1): if nums[i]==val: nums[i],nums[j]=nums[j],nums[i] j-=1 return j+1 if __name__ == "__main__": answer=Solution() print answer.removeElement([3,2,2,2,3],3)
642cad91d850493e612e64589eb89b39f69d222d
TahaKhan8899/Coding-Practice
/LeetCode/MissingNumber.py
712
3.515625
4
# THIS IS STUPID. class Solution: def missingNumber(self, nums): # nums.sort() # print(nums) # if len(nums) == 1 and nums[0] == 0: # return 1 # if len(nums) == 1 and nums[0] == 1: # return 0 # if len(nums) == 1: # return nums[0]+1 # for i in range(0, len(nums)-1): # if nums[i+1]-nums[i] != 1: # return nums[i]+1 # return None s = sum(nums) print("1", s) real_sum = (0+len(nums))*(len(nums)+1)/2 print("2", real_sum) print("3", s - real_sum) return s - real_sum obj = Solution() arr = [0] ans = obj.missingNumber(arr) print(ans)
70392967b8a87b3501e26714b4f98f5166cc38f8
itsafjal/python_stats
/percentile_score.py
302
3.546875
4
#! /usr/bin/python def Percentile_calculater(scores, your_score): cnt = 0 for score in scores: if score<=your_score: cnt += 1 result = (cnt*100)/len(scores) return result scores= [11,22,33,44,55,66,77] your_score = 55 myresult = Percentile_calculater(scores, your_score) print myresult
2fcffcf8343c050e8d5fbc08d528158276b3d8a3
tjatn304905/algorithm
/SWEA/1232_사칙연산/sol1.py
1,474
3.5625
4
import sys sys.stdin = open('input.txt') # 후위 탐색 def traversal(n): if 1 <= n <= N: traversal(left[n]) traversal(right[n]) # 후위 연산식 스택에 쌓아주기 stack.append(values[n]) # 후위 연산 def calculate(): traversal(1) # 숫자를 담아둘 스택 numbers = [] while stack: elem = stack.pop(0) if elem in signs: if elem == '+': numbers[-1] = numbers[-2] + numbers.pop() elif elem == '-': numbers[-1] = numbers[-2] - numbers.pop() elif elem == '*': numbers[-1] = numbers[-2] * numbers.pop() elif elem == '/': numbers[-1] = numbers[-2] / numbers.pop() else: numbers.append(elem) return int(numbers[0]) for tc in range(1, 11): N = int(input()) signs = ['+', '-', '*', '/'] left = [0] * (N+1) right = [0] * (N+1) values = [0] * (N+1) # 트리 만들기 for i in range(N): nodes = list(input().split()) idx = int(nodes[0]) # 사칙연산을 하는 노드라면 if nodes[1] in signs: values[idx] = nodes[1] left[idx] = int(nodes[2]) right[idx] = int(nodes[3]) # 단순 숫자 노드라면 else: values[idx] = int(nodes[1]) # 후위 연산식 스택 stack = [] print('#{} {}'.format(tc, calculate()))
5a773b56dbfb90839a1f23301ac47eab05a59879
bpbethstar/assignment
/H180621T ass1.py
170
3.8125
4
n=10 a=[] for i in range(0,n): elem=int(input("Enter height of student: ")) a.append(elem) avg=sum(a)/n print("Average height of students is:",round(avg,2))
bcd5b7b01a3b05f40f069df0a61345a5830ea6f3
ankitniranjan/HackerrankSolutions
/Python/Lists.py
704
3.90625
4
if __name__ == '__main__': N = int(input()) list = [] for _ in range(N): operation, *attr = input().split() if operation == 'insert': index = int(attr[0]) value = int(attr[1]) list.insert(index, value) elif operation == 'remove': value = int(attr[0]) list.remove(value) elif operation == 'append': value = int(attr[0]) list.append(value) elif operation == 'sort': list.sort() elif operation == 'reverse': list.reverse() elif operation == 'pop': list.pop() elif operation == 'print': print(list)
63f38b13d2461f5f12ee8277daf2a7ce1c304fa7
rad10/NIPScan
/nipscan.py
7,210
3.5625
4
#!/usr/bin/python3 from sys import argv, exit, stdin import socket import re import argparse # make sure library is installed try: import nmap except: print("Error: cannot find nmap library on platform.") print("Please install nmap library from pip") print("Please run either \"pip3 install python-nmap\"") print("or \"sudo apt install python3-nmap\"") print("Exiting now") exit(1) #[InitConfig]# nm = nmap.PortScanner() # the NMap scanning object ip = [] opts = ["-sL"] #[/InitConfig]# #[Help]# parser = argparse.ArgumentParser( prefix_chars="-+/", description="""this is a portscanner that takes in ip addresses and can do multiple things, including displaying the hostnames of each ip address, as well as filtering out dead ip addresses and only displaying currently alive ips.""") parser.add_argument("ips", nargs=argparse.REMAINDER, type=str, metavar="ip_address", help="The IP Addresses to be scanned.") parser.add_argument("-a", "--alive", type=bool, nargs="?", default=False, const=True, help="Filters only alive ips into list") parser.add_argument("-vi", "--visual", type=bool, nargs="?", default=True, const=True, help="Gives the visual desplay of results (defualt)") parser.add_argument("-r", type=bool, default=False, nargs="?", dest="brute", const=True, help="Reads ips and assumes hosts are all alive. for incase some ips block ping.") parser.add_argument("-f", "--file", type=argparse.FileType("r"), metavar="input_file", help="Imports hosts from file, fan only be used once") parser.add_argument("-e", "--extra", nargs="+", metavar="options", help="Adds extra options to nmap scanner") parser.add_argument("-ln", "--local", type=bool, nargs="?", default=False, const=True, help="Adds local network addresses to scanner") parser.add_argument("-t", "--text", type=bool, nargs="?", default=False, const=True, help="Changes the scripts result so that it only displays the ips given. -a and -hn will change these from defualt input") parser.add_argument("-hn", "--hostname", type=bool, nargs="?", default=False, const=True, help="Addition to -t that includes hostname to raw result") #[/Help]# #[Config]# if len(argv) <= 1 and stdin.isatty(): parser.print_help() parse = parser.parse_args() if parse.alive: opts.append("-sn") opts.remove("-sL") if parse.visual: parse.text = False elif parse.text: parse.visual = False if parse.brute: opts.append("-Pn") if (parse.extra != None): opts.extend(parse.extra) if (parse.ips != None): for i in range(len(parse.ips)): if (re.search(r"\d{1,3}.\d{1,3}.\d{1,3}.(\d{1,3}/\d{2}|(\d{1,3}-\d{1,3}|\d{1,3}))", parse.ips[i]) == None): try: socket.gethostbyname(parse.ips[i]) except socket.gaierror: parse.ips.pop(i) ip.extend(parse.ips) # elif(re.search(r"\d{1,3}.\d{1,3}.\d{1,3}.(\d{1,3}/\d{2}|(\d{1,3}-\d{1,3}|\d{1,3}))", i) != None): # ip.append(i) # else: # try: # socket.gethostbyname(i) # except socket.gaierror: # pass # else: # ip.append(i) # [/Config] #[STDIN]# if not stdin.isatty(): addin = str(stdin.read()).split() for term in addin: reg = re.search( r"\d{1,3}.\d{1,3}.\d{1,3}.(\d{1,3}/\d{2}|(\d{1,3}-\d{1,3}|\d{1,3}))", term) if (reg != None): ip.append(str(reg.group())) else: try: socket.gethostbyname(term) except socket.gaierror: pass else: ip.append(term) #[/STDIN]# #[LocalHosts]# if parse.local: # Local Network option # opens a socket on computer to connect to internet s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) # Talks to dns provider from google localip = s.getsockname()[0] # this will get the local ip s.close() # Turns off socket for possible later use sets = localip.split(".") # splits 4 sections for use in next line ip.append(str(sets[0] + "." + sets[1] + "." + sets[2] + ".0-255")) # 192.168.1.0-255 #[/LocalHosts]# #[Files]# if parse.file != None: # this will grab ip addresses from an inputed file doc = parse.file.read().split() for term in doc: reg = re.search( r"\d{1,3}.\d{1,3}.\d{1,3}.(\d{1,3}/\d{2}|(\d{1,3}-\d{1,3}|\d{1,3}))", term) if (reg != None): ip.append(str(reg.group())) else: try: socket.gethostbyname(term) except socket.gaierror: pass else: ip.append(term) # [/Files] #[Generator]# opts.sort() # org to filter non ip addresses for i in range(len(ip)-1, 0, -1): reg = re.search( r"\d{1,3}.\d{1,3}.\d{1,3}.(\d{1,3}-\d{1,3}|\d{1,3})", ip[i]) if (reg != None): ranges = str(reg.group()).split(".") for p in ranges[:2]: if int(p) < 0 or int(p) > 255: print("Pop: %s. Not a real ipv4 address" % ip[i]) ip.pop(i) break else: if "-" in ranges[3]: ipr = ranges[3].split("-") if int(ipr[0]) < 0 or int(ipr[1]) > 255: print("Pop: %s. Not a real ipv4 address" % ip[i]) ip.pop(i) elif int(ranges[3]) < 0 or int(ranges[3]) > 255: print("Pop: %s. Not a real ipv4 address" % ip[i]) ip.pop(i) if len(ip) == 0: print("Error: No valid targets given\n") parser.print_help() exit() count = 0 while count < len(opts) - 1: # This whole section if to remove duplicate options if opts[count] == opts[count + 1]: opts.pop(count) else: count += 1 sopts = opts[0] sips = ip[0] for i in opts[1:]: sopts += (" " + i) # organizes all string options with a space separation for i in ip[1:]: sips += (" " + i) # organizes all ip addresses with a space as separation nm.scan(arguments=sopts, hosts=sips) #[/Generator]# #[Visual]# if parse.visual: print("Hosts:") print("state | hostname (ipaddress)") for host in nm.all_hosts(): if parse.alive and parse.brute: try: if (nm[host] > 0 and nm[host].hostname() != ""): print(nm[host].state() + "\t| " + nm[host].hostname() + " ("+host+")") except: continue elif parse.alive: # prints as [true/false] | hostname (ip address) print(nm[host].state() + "\t| " + nm[host].hostname() + " (" + host + ")") else: if nm[host].hostname() != "": print(nm[host].hostname() + " (" + host + ")") #[/Visual]# #[Text]# if parse.text: for host in nm.all_hosts(): if parse.hostname: # Hostname if nm[host].hostname() != "": print(host + ":" + nm[host].hostname()) else: print(host) #[/Text]#
44d9757efc6221b7c4a9eb66eabadb81af089d5b
etikrusteva/python_acadaemy
/First/main.py
1,390
4.125
4
""" def main(): my_name = input("Name:") print("Az sam", my_name) def display(x): print(x) def test_condition(): var = input("Number:") if (var == "5"): int(var) print("fire") elif (var == "7"): print("ne raboti") else: print("lalal") if __name__ == "__main__": test_condition() def add(a, b): return a+b def main(): a = input("vavedi edno chislo:") b = input("vavedi o6te edno 4islo:") a = int(a) b = int(b) # add(a,b) result = add(a, b) print(result) def izv(x, y): return x-y def umn(x, y): return x*y def main(): x = input("X:") y = input("Y:") x = int(x) y = int(y) result1= izv(x, y) result2= umn(x, y) print(result1, result2) if __name__ == "__main__": main() """ def calc(): a = input("A") b = input("B") a = int(a) b = int(b) op = input("Operation:") result = "" def add(a, b): return a+b def subs(a, b): return a-b def col(a, b): return a*b def di(a, b): return a/b if op == "+": result= add(a,b) elif op == "-": result= subs(a,b) elif op == "*": result= subs(a,b) elif op == "/": result= di(a,b) print(result) if __name__ == "__main__": calc()
63bfc428714fda200a6ef906fe8e45b327aafe58
wupei93/black-jack
/player.py
2,576
3.5
4
import random import string from abc import abstractmethod from poker import Pile, ConsoleCard, Card, ConsoleCardBack class BasePlayer: def __init__(self, name, token=1000): self.name = 'unknown' self._cards = [] self.name = name self.token = token def __str__(self): return self.name def get_card(self, pile: Pile): c = pile.get_card() self._cards.append(c) def show_cards(self): cards = [] c = self._cards[0] # 按照规则,第一张牌不展示 if self.is_bot(): cards.append(ConsoleCardBack()) else: cards.append(self._cards[0]) for i in range(1, len(self._cards)): cards.append(self._cards[i]) self._show_cards(cards) def show_all_cards(self): self._show_cards(self._cards) def drop_cards(self): self._cards = [] def add_token(self, delta_token): self.token += delta_token @abstractmethod def _show_cards(self, cards): pass def is_bot(self): return False def get_point(self): _card = Card() for card in self._cards: _card += card return _card.score @abstractmethod def need_card(self): pass def is_black_jack(self): _card_nums = [] for c in self._cards: _card_nums.append(c.num) return len(self._cards) == 2 \ and ('A' == _card_nums[0] and _card_nums[1] in ['10', 'J', 'Q', 'K']) \ or ('A' == _card_nums[1] and _card_nums[0] in ['10', 'J', 'Q', 'K']) class ConsolePlayer(BasePlayer): def need_card(self): return input('要牌(y)') in ['y', 'Y', ''] def _show_cards(self, cards): s = '' for i in range(6): for c in cards: s += str(c).split('\n')[i] s += '\n' print(s) # 电脑玩家 class BotPlayer(ConsolePlayer): _name_no = 0 def __init__(self): BotPlayer._name_no += 1 super().__init__('Bot_{}'.format(BotPlayer._name_no)) self.risk_appetite = random.random() def is_bot(self): return True def need_card(self): """ 1. 手牌小于15点时要牌 2. 手牌大于18点时不要牌 3. 15点到18点以self.risk_appetite的概率要牌 :return: """ if self.get_point() > 18: return False if self.get_point() < 15: return True return random.random() < self.risk_appetite
6bd5725816b7e009fd4dd9112b9005cadadbfe0c
d1rtyst4r/archivetempLearningPythonGPDVWA
/Chapter07/tasks/vacation.py
441
3.96875
4
# Task 7-10 vacation = {} poll_active = True while poll_active: name = input("Please enter your name: ") vacation[name] = input("Please enter your next place for vacation :") repeat = input("Do you have any person for the poll? (yes/no) ") if repeat == 'no': poll_active = False print("\n--- Poll results ---") for name, answer in vacation.items(): print(name.title() + " would like to go to " + answer + ".")
e710b7a214d123351036d9647299ce61a222154b
MaFerToVel/Tarea-06
/Tarea-6.py
3,550
3.828125
4
#encoding: UTF-8 #Autor: Maria Fernanda Torres Velazquez A01746537 #Descripcion: El siguiente programa, muestra un menu al usuario que le permite escoger 2 opciones, posteriormente #mediante un ciclo while, se ejcutaran cuantas veces el usuario lo desee def registrarColeccion(): #Registra el numero de insectos y muestra cuantos lleva recolectados, cuantos le faltan y cuantos le sobran print ("BIENVENIDO A TU REGISTRO DE INSECTOS") print ("------------------------------------") insectos = 0 dia= 0 while not insectos >=30: recolectados=(int(input("¿Cuantos insectos recolectaste hoy? "))) insectos = insectos + recolectados dia= dia+1 restantes= 30 - insectos excedente= insectos-30 print ("Despues de: %d dias, llevas %d insectos recolectados" %(dia,insectos)) if restantes >0 and restantes<30: print ("Te faltann: %d insectos" %restantes) elif restantes == 0: print ("Muchas felicidades has llegado a la meta, recolectaste 30 insectos") elif excedente > 0: print ("Muchas felicidades has llegado a la meta, recolectaste: %d insectos" %insectos) print ("Recolectaste %d insectos mas de tu meta" %excedente) def encontrarMayor(): #Registra numeros y muestra el mayor print("BIENVENIDO AL PROGRAMA QUE ENCUENTRA EL MAYOR") print("---------------------------------------------") lista = [] numero=(int(input("Introduce un numero [-1 para salir]: "))) if numero==-1: print ("HASTA LUEGO") else: while numero != -1: lista.append(numero) numero = (int(input("Introduce un numero [-1 para salir]: "))) if len(lista) > 0: print("-----------------------------------------") print("EL NUMERO MAYOR ES: ", max(lista)) elif len(lista) == 0: print("LISTA VACIA, NO HAY VALOR MAXIMO") def main(): print ("BIENVENIDO, A CONTINUACION TE MOSTRAMOS EL MENU DE OPCIONES:") print ("------------------------------------------------------------") print (" 1. Recolectar insectos ") print (" 2. Encontrar el mayor ") print (" 3. S A L I R ") opcion=(int(input(" POR FAVOR ELIGE UNA OPCION: "))) print("------------------------------------------------------------") while opcion != 3: if opcion == 1: print("------------------------------------------------------------") registrarColeccion() print("------------------------------------------------------------") elif opcion == 2: print("------------------------------------------------------------") encontrarMayor() print("------------------------------------------------------------") else: print("------------------------------------------------------------") print ("OPCION INVALIDA, SOLO PUEDES INTRODUCIR NUMEROS ENTRE 1 Y 3") print("------------------------------------------------------------") print ("------------------------------------------------------------") print (" 1. Recolectar insectos") print (" 2. Encontrar el mayor") print (" 3. S A L I R ") opcion=(int(input(" POR FAVOR ELIGE UNA OPCION: "))) print("------------------------------------------------------------") main()
d8939b2a452aa02b921d68142bb10a93300d7e08
acc-cosc-1336/cosc-1336-spring-2018-Carol-COSC1336
/tests/assignments/test_assign9.py
1,443
3.609375
4
import unittest from src.assignments.assignment9.invoice import Invoice from src.assignments.assignment9.invoice_item import InvoiceItem #from invoice import Invoice #from invoice_item import InvoiceItem class Test_Assign8(unittest.TestCase): invoice_items = [] #list of Invoice Item instance objects def test_invoice_item_extended_cost_w_qty_10_cost_5(self): ''' Create an Invoice item instance with argument values: 'Widget1', 10, and 5 The extended cost result should be 50; ''' invoice_item = InvoiceItem('Widget1', 10, 5) self.assertEqual(50, invoice_item.get_extended_cost()) #create the assert code def test_invoice__w_3_invoice_items(self): ''' Create an Invoice instance with argument values: 'ABC company', '03282018' Three invoice items as follows argument values: 'Widget1', 10, and 5 'Widget2', 7, and 8 'Widget3', 20, and 10 Get Extended result should be 50 + 56 + 200 = 306 ''' invoice = Invoice('ABC Company', '03282018') invoice.add_invoice_item(InvoiceItem('Widget1', 10, 5)) invoice.add_invoice_item(InvoiceItem('Widget2', 7, 8)) invoice.add_invoice_item(InvoiceItem('Widget3', 20, 10)) self.assertEqual(306, invoice.get_invoice_total()) #create the assert equal code #if __name__ == '__main__': #unittest.main(verbosity=2)
b5cc5f217274309e75b4b35be47d303bed574133
MESragelden/leetCode
/Interval List Intersections.py
516
3.578125
4
def intervalIntersection(A, B): out = [] i=0 j=0 while(i < len(A) and j < len(B)): new = [max(A[i][0],B[j][0]),min(A[i][1],B[j][1])] if (new[0]<=new[1]): out.append(new) if (A[i][1] > B[j][1]): j += 1 elif(A[i][1] < B[j][1]): i += 1 else : i+=1 j+=1 return out A = [[0,2],[5,10],[13,23],[24,25]] B = [[1,5],[8,12],[15,24],[25,26]] print(intervalIntersection(A,B))
c3b95c2f73607105b6d35999ba3882bf9ad22ec3
MarianaDrozd/Python-Martian-Manhunter-adv-
/homeworks/HW3_OOP_Practice/houses.py
822
3.8125
4
from abc import ABC, abstractmethod class Home(ABC): @abstractmethod def apply_a_purchase_discount(self, discount): raise NotImplementedError class House(Home): def __init__(self, address, area, cost): self.address = address self.area = area self.cost = cost def apply_a_purchase_discount(self, discount): if discount > 0: print(f"You're lucky! A discount for house {self.address} is {discount}!" f"Now it costs {self.cost - round(self.cost * discount)}") self.cost -= round(self.cost * discount) else: print(f"Sorry, but there is no discount for house {self.address}.") class SmallTypicalHouse(House): def __init__(self, address, cost, area=40): super().__init__(address, area, cost)
9b90679ffe2b4af0babc8cea3bea3edbd704c267
nontapanr/data-structures-and-algorithms
/Python5.Linked List/InsertSinglyLinkedList.py
1,964
4
4
class Node: def __init__(self, data): self.data = data self.next = None def __str__(self): return str(self.data) class LinkedList: def __init__(self): self.head = None self.tail = None self.size_ = 0 def __str__(self): if not self.isEmpty(): current = self.head string = "link list : " + str(self.head.data) while current.next != None: string += "->" + str(current.next.data) current = current.next return string else: return "List is empty" def append(self, item): newNode = Node(item) if self.head == None: self.head = self.tail = newNode else: self.tail.next = newNode self.tail = newNode self.size_ += 1 def insert(self, index, data): current = self.head if 0 <= index <= self.size_: newNode = Node(data) print(f"index = {index} and data = {data}") if index == 0: newNode.next = current self.head = newNode self.size_ += 1 return else: for x in range(index-1): current = current.next newNode.next = current.next current.next = newNode self.size_ += 1 else: print("Data cannot be added") def isEmpty(self): return self.size_ == 0 if __name__ == "__main__": input_ = input("Enter Input : ").split(",") ll = LinkedList() if input_[0] != "": for value in input_[0].split(): ll.append(value) print(ll) else: print("List is empty") for insertValue in input_[1:]: insertValue = insertValue.split(":") ll.insert(int(insertValue[0]), insertValue[1]) print(ll)
0322aa69cef5a1b2ae773f3ffab56f0fab58a639
shobhit-nigam/strivers
/day4/adv_funcs/15.py
205
3.765625
4
lista = ['w', 'o', 'r', 'l', 'd', ' ', 'p', 'e', 'a', 'c', 'e'] def only_vowels(ch): vowels = ['a', 'e', 'i', 'o', 'u'] return ch in vowels listx = list(filter(only_vowels, lista)) print(listx)
cbab7ac982cdb7e6ff8b67f1338b21a95d5190c1
rishikesh12/MachineLearningBasics
/PolynomialRegression/polynomial_regression.py
1,227
3.53125
4
# Bluffing Detector using Polynomial Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:,1:2].values y = dataset.iloc[:,2].values #Fitting linear regression to the dataset from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(X,y) # Fitting polynomial regression to the dataset from sklearn.preprocessing import PolynomialFeatures poly_reg = PolynomialFeatures(degree = 4) X_poly = poly_reg.fit_transform(X) lin_reg2 = LinearRegression() lin_reg2.fit(X_poly,y) # visualizing linear regression results plt.scatter(X,y,color='red') plt.plot(X, lin_reg.predict(X), color='blue') plt.title('Level vs Salary') plt.xlabel('Level') plt.ylabel('Salary') plt.show() #Visualizing polynomial regression results X_grid = np.arange(min(X),max(X),0.1) #stepwise incrementer for a proper plot X_grid = X_grid.reshape(len(X_grid),1) plt.scatter(X,y,color='red') plt.plot(X_grid, lin_reg2.predict(poly_reg.fit_transform(X_grid)), color='blue') plt.title('Level vs Salary(Polynomial Regression)') plt.xlabel('Level') plt.ylabel('Salary') plt.show()
d84424cdf28d31f5896784c6eefe49c3159ac5d7
Persist-GY/algorithm008-class02
/Week_02/levelorder.py
800
3.546875
4
# https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/ class Solution: def levelOrder(self, root: 'Node'): def helper(root, level): if len(res) == level: res.append([]) res[level].append(root.val) for r in root.children: helper(r, level+1) res = [] if root != None: helper(root, 0) return res # 队列 广度优先搜索 def levelOrder2(self, root): if root == None: return [] deq = [root, ] res = [] while deq: current = [] res.append([]) for r in deq: res[-1].append(r.val) current.extend(r.children) deq = current return res
4c64b289ba9cadb571ef46bea53be3aded7e0a9c
veerabhadrareddy143/python
/tkinter1.py
748
4.1875
4
from tkinter import * window=Tk(); #creating new blank window window.title("welcome"); #title presentation txt=Entry(window,width=40) txt.grid(column=20,row=13) window.geometry('1000x1000') #mentioning size of window lbl=Label(window,text="hello") #name to a window lbl.grid(row=100,column=100) #size of label def clicked(): #when button was clicked this executes lbl.configure(text="button was clicked sir") b=Button(window,text="veera",command=clicked) #crating button b.grid(column=1,row=2) #size of button window.mainloop()
b1a2d291122ceab7ac964d693570c9ce81ef2b75
fabiomeendes/nanocourses-python
/Cap5_Files/Functions.py
651
3.796875
4
def ask(): return input("What do you want?\n" + "<I> - To insert a user\n" + "<S> - To search a user\n" + "<D> - To delete a user\n" + "<L> - To list a user: ").upper() def insert(dictionary): dictionary[input("Type a login: ").upper()] = [ input("Type a name: ").upper(), input("Type the last access date: "), input("Which was the last station accessed: ").upper() ] save(dictionary) def save(dictionary): with open("bd.txt", "a") as file: for key, value in dictionary.items(): file.write(key + ": " + str(value))
3b936f01bfc2d51ed82210144b4174c0a47f78c1
ebanner/cs381v_project
/img_info.py
4,921
3.640625
4
# Handles processing image path files (which define where the data is stored) # and their associated labels. class ImageInfo(object): """Loads image file paths from input files.""" _DEFAULT_IMG_DIMENSIONS = (256, 256, 1) def __init__(self, num_classes, explicit_labels=False): """Sets up the initial data variables and data set sizes. Args: num_classes: the number of data classes in the data set. explicit_labels: set to True if the provided data has soft labels or otherwise explicity defined values for each class for the data. """ # Set the data values. self.num_classes = num_classes self.explicit_labels = explicit_labels # Initialize the data lists. self.img_dimensions = self._DEFAULT_IMG_DIMENSIONS self.classnames = [] self.train_img_files = {} self.test_img_files = {} for i in range(self.num_classes): self.train_img_files[i] = [] self.test_img_files[i] = [] self.num_train_images = 0 self.num_test_images = 0 @property def img_width(self): """Returns the width of the input images. Returns: The input image width. """ return self.img_dimensions[0] @property def img_height(self): """Returns the height of the input images. Returns: The input image height. """ return self.img_dimensions[1] @property def num_channels(self): """Returns the number of image channels the data is using. Returns: The number of image channels for the input data. """ return self.img_dimensions[2] def set_image_dimensions(self, dimensions): """Set the training and testing image dimensions. All images fed into the neural network, for training and testing, will be formatted to match these dimensions. Args: dimensions: a tuple containing the following three values: width - a positive integer indicating the width of the images. height - a positive integer indicating the height of the images. num_channels - the number of channels to use. This number should be 1 for grayscale training images or 3 to train on full RGB data. """ width, height, num_channels = dimensions # Make sure all the data is valid. if width <= 0: width = self._DEFAULT_IMG_DIMENSIONS[0] if height <= 0: height = self._DEFAULT_IMG_DIMENSIONS[1] if num_channels not in [1, 3]: num_channels = self._DEFAULT_IMG_DIMENSIONS[2] # Set the dimensions. self.img_dimensions = (width, height, num_channels) def load_image_classnames(self, fname): """Reads the classnames for the image data from the given file. Each class name should be on a separate line. Args: fname: the name of the file containing the list of class names. """ classnames_file = open(fname, 'r') for line in classnames_file: line = line.strip() if len(line) == 0 or line.startswith('#'): continue self.classnames.append(line) classnames_file.close() def load_train_image_paths(self, fname): """Reads the image paths for the training data from the given file. Each file name (full directory path) should be on a separate line. The file paths must be ordered by their class label. Args: fname: the name of the file containing the training image paths. """ self.num_train_images = self._read_file_data(fname, self.train_img_files) def load_test_image_paths(self, fname): """Reads the image paths for the test data from the given file. Each file name (full directory path) should be on a separate line. The file paths must be ordered by their class label. Args: fname: the name of the file containing the test image paths. """ self.num_test_images = self._read_file_data(fname, self.test_img_files) def _read_file_data(self, fname, destination): """Reads the data of the given file into the destination list. The file will be read line by line, and each line that doesn't start with a "#" or is not empty will be stored in the given list. Args: fname: the name of the file to read. destination: a dictionary into which the file's data will be put line by line. Returns: The number of image paths that were provided for this data batch. """ paths_file = open(fname, 'r') num_images = 0 for line in paths_file: line = line.strip() if len(line) == 0 or line.startswith('#'): continue imdata = line.split() impath, classnum = imdata[0], imdata[1] classnum = int(classnum) label_vals = [] if self.explicit_labels: for i in range(self.num_classes): label_vals.append(float(imdata[i+2])) destination[classnum].append((impath, label_vals)) num_images += 1 paths_file.close() return num_images
a1674fca2f4784b15f3380bb9160094ebdbd1b8d
CodeTools/hello-world
/python/Calulator.py
1,336
4.1875
4
# Ok this is inspired from some web site # but atleast the coding is mine # Menu Functions def menu(): print("This is python calculator v1.0"); print(""); print("your options are"); print(""); print("1. Add"); print("2. Substract"); print("3. Multiply"); print(""); print("4. Divide"); print("5. Exit"); return input("Enter your options:"); # Add function def add(x, y): print(""); print(x, " + ", y , " = " , (x + y)); # Substract function def substract(x, y): print(""); print(y, " - ", x , " = " , (y - x)); # Multiply function def multiply(x, y): print(""); print(x, " * ", y , " = " , (x * y)); # Divide function def divide(x, y): print(""); print(x, " / ", y , " = " , (x / y)); # Main program starts loop = 1; choice = 0; while (loop == 1) : choice = int(menu()); if ( choice == 1 ): add(int(input("add this:")), int(input("to this:"))); elif ( choice == 2 ) : substract(int(input("Substract this:")), int(input("from this:"))); elif ( choice == 3 ) : multiply(int(input("Multiply this:")), int(input("with this:"))); elif ( choice == 4 ) : divide(int(input("Divide this:")), int(input("with this:"))); elif ( choice == 5 ) : loop = 0; else : loop = 1;
03c8c69556065fb99ab3927bee5c7821c94becac
RomaTk/The-basic-knowledge-of-programming
/laboratory work 3/solutions/code/1.py
237
3.984375
4
print("Введите три стороны: "); a=float(input()); b=float(input()); c=float(input()); if ((a==b)or(a==c)or(b==c)): print("равнобедренный") else: print("Не равнобедренный"); input();
d47d832d44b2da72776029bf738c86aa224cb0e9
PacktPublishing/Python-Data-Analytics-and-Visualization
/Module 1/4/better.py
278
3.53125
4
#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 3, 6) y = np.power(x, 2) plt.axis([0, 6, 0, 10]) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('Data Visualization using Pyplot from Matplotlib') plt.savefig('better.png')
abe17ee6550bfa68bf780aa51b4ed31f91dbaeeb
sudhirkk/ML_Projects
/EmailSpamClassifiers/PerceptronClassifier/ImplementPerceptron.py
1,988
4.1875
4
def perceptron(xs,ys): """ function w=perceptron(xs,ys); Implementation of a Perceptron classifier Input: xs : n input vectors of d dimensions (nxd) ys : n labels (-1 or +1) Output: w : weight vector (1xd) b : bias term """ n, d = xs.shape # so we have n input vectors, of d dimensions each w = np.zeros(d) b = 0.0 # YOUR CODE HERE Iter = 100 i = 0 while (i < Iter): misclass = 0 # Randomize the order in the training data for i in np.random.permutation(n): if ys[i]*(np.dot(w, xs[i]) + b) <= 0: perceptron_update(xs[i], ys[i], w) b += ys[i] misclass += 1 if (misclass == 0): break i += 1 return (w, b) # These self tests will check that your perceptron function successfully classifies points in two different linearly separable dataset def test_Perceptron1(): N = 100; d = 10; x = np.random.rand(N,d) w = np.random.rand(1,d) y = np.sign(w.dot(x.T))[0] w, b = perceptron(x,y) preds = classify_linear_grader(x,w,b) return np.array_equal(preds.reshape(-1,),y.reshape(-1,)) def test_Perceptron2(): x = np.array([ [-0.70072, -1.15826], [-2.23769, -1.42917], [-1.28357, -3.52909], [-3.27927, -1.47949], [-1.98508, -0.65195], [-1.40251, -1.27096], [-3.35145,-0.50274], [-1.37491,-3.74950], [-3.44509,-2.82399], [-0.99489,-1.90591], [0.63155,1.83584], [2.41051,1.13768], [-0.19401,0.62158], [2.08617,4.41117], [2.20720,1.24066], [0.32384,3.39487], [1.44111,1.48273], [0.59591,0.87830], [2.96363,3.00412], [1.70080,1.80916]]) y = np.array([1]*10 + [-1]*10) w, b =perceptron(x,y) preds = classify_linear_grader(x,w,b) return np.array_equal(preds.reshape(-1,),y.reshape(-1,)) runtest(test_Perceptron1, 'test_Perceptron1') runtest(test_Perceptron2, 'test_Perceptron2')
873805d8f5c277b4a977b4a3f58a0cc3ae58e6f6
stuartwray/bric-a-brac
/correlations.py
2,501
3.828125
4
#!/usr/bin/python3 from math import * import random import time # demonstration that when we sum four independent random variables, the # correlation between the sum and any one of them is r = 0.5 def correl2(xs, ys): # Simple-minded code from mathematical definition # # r = N * sum(x * y) - sum(x) * sum(y) # ----------------------------------------------------------------- # sqrt((N * sum(x**2) -(sum(x))**2) * (N * sum(y**2) -(sum(y))**2)) N = len(xs) sum_xy = sum(x * y for x, y in zip(xs, ys)) sum_x = sum(xs) sum_y = sum(ys) sum_x2 = sum(x * x for x in xs) sum_y2 = sum(y * y for y in ys) A = N * sum_xy - sum_x * sum_y B = N * sum_x2 - sum_x**2 C = N * sum_y2 - sum_y**2 return float(A) / sqrt(B * C) def correlW(xs, ys): assert len(xs) == len(ys) # Slightly bizzare code: this is cribbed from Wikipedia article on # "correlation", but that assumes that arrays run from 1 to N ... # Seems most reliable to pad-out with a dummy element zero. N = len(xs) x = [None] + xs y = [None] + ys sum_sq_x = 0 sum_sq_y = 0 sum_coproduct = 0 mean_x = float(x[1]) mean_y = float(y[1]) for i in range(2, N + 1): # ie last i is N, as desired sweep = (i - 1.0) / i delta_x = x[i] - mean_x delta_y = y[i] - mean_y sum_sq_x += delta_x * delta_x * sweep sum_sq_y += delta_y * delta_y * sweep sum_coproduct += delta_x * delta_y * sweep mean_x += delta_x / i mean_y += delta_y / i pop_sd_x = sqrt( sum_sq_x / N ) pop_sd_y = sqrt( sum_sq_y / N ) cov_x_y = sum_coproduct / N correlation = cov_x_y / (pop_sd_x * pop_sd_y) return correlation def quite_close(a, b): ratio = a / b return abs(ratio - 1) < 1e-9 def correl(*args): answer1 = correl2(*args) answer2 = correlW(*args) if not quite_close(answer1, answer2): print("+++ Problem:", answer1, answer2) assert False return answer1 def one_trial(size): dataA = [random.random() for x in range(size)] dataB = [random.random() for x in range(size)] dataC = [random.random() for x in range(size)] dataD = [random.random() for x in range(size)] combined = [a + b + c + d for a, b, c, d in zip(dataA, dataB, dataC, dataD)] return correl(combined, dataA) # take an average repeats = 1000 r_sum = 0.0 for i in range(repeats): r_sum += one_trial(1000) print("r =", r_sum/repeats)
8b94a2c51024b20bcd7bbd327a3b5271dc695d4b
kzth4/Tugas-PROKSI-Kuhhh
/Operasi_Temperatur_Suhu_Kuhhh.py
1,982
4.03125
4
# Nama : Kukuh Cokro Wibowo # NIM : 210441100102 print("Operasi Temperature by Kuhhh\n") print("---------------------------------") print("\nSilahkan isi Nama kakak terlebih dahulu\n") its_you = input("Nama Panggilan Kakak : ") print("\nSelamat datang kak",its_you,"\n", "----------------------------------") # Panduan # Isi Suhu dengan angka (int), jangan ada tambahan apapun (str) # Celcius C = float(input("Masukkan Suhu Celcius Anda :")) print("\nSuhu Celcius Kak",its_you,"saat ini adalah",C,"C") # Pada Suhu Lain R = (4/5)*C print("Hasil ke Reamur =",R,"R") F = ((9/5)*C)+32 print("Hasil ke Fahrenheit =",F,"F") K = C+273 print("Hasil ke Kelvin =",K,"K") # Konversi Reamur print("\nSilahkan kak",its_you,"\n", "------------------------------") R = float(input("Masukkan Suhu Reamur Anda :")) print("\nSuhu Reamur kak",its_you,"saat ini adalah",R,"R") # Pada Suhu Lain C = (5/4)*R print("Hasil ke Celcius =",C,"C") F = ((9/4)*R)+32 print("Hasil ke Fahrenheit =",F,"F") K = ((5/4)*R)+273 print("Hasil ke Kelvin =",K,"K") # Konversi Fahrenheit print("\nLagi kak",its_you,"\n", "---------------------------") F = float(input("Masukkan Suhu Fahrenheit Anda :")) print("\nSuhu Fahrenheit kak",its_you,"saat ini adalah",F,"F") # Pada Suhu Lain C = (5/9)*(F-32) print("Hasil ke Celcius =",C,"C") R = (4/9)*(F-32) print("Hasil ke Reamur =",R,"R") K = (5/9)*(F-32)+273 print("Hasil ke Kelvin =",K,"K") # Konversi Kelvin print("\nTerakhir kak",its_you,"\n", "------------------------------") K = float(input("Masukkan Suhu Kelvin Anda :")) print("\nSuhu Kelvin kak",its_you,"saat ini adalah",K,"K") # Pada Suhu Lain C = K-273 print("Hasil ke Celcius =",C,"C") R = (4/5)*(K-273) print("Hasil ke Reamur =",R,"R") F = (9/5)*(K-273)+32 print("Hasil ke Fahrenheit =",F,"F") print("\nTerimakasih telah mencoba kak",its_you,":)") # GitHub : kzth4(Boo)
a9621406b5800e2fe102d55c36210044b33ffe60
biao111/learn_python
/set/sample3.py
465
3.59375
4
#集合间的关系操作 s1 = {1,2,3,4,5,6} s2 = {6,5,4,3,2,1} #==判断两个元素是否相等 print(s1 == s2) s3 = {4,5,6,7} s4 = {1,2,3,4,5,6,7,8} #issubset()判断是否为子集 print(s3.issubset(s4)) #issuperset()判断是否为父集 print(s4.issuperset(s3)) s5 = {5} s6 = {1,3,5,7,9} #isdisjoint()函数判断两个集合是否存在重复元素 #True代表不存在重复元素,Fals代表存在重复元素 print(s5.isdisjoint(s6))
bac5f443074118776ee6ec8ff0ff9fa79e2ef8a0
JavierSada/MathPython
/Support/Mid Term P4.py
559
3.6875
4
print ("\nProblem 4 Mid Term") import matplotlib.pyplot from matplotlib.pyplot import * import numpy from numpy import * figure() x= arange(0,400.1,0.1) y= arange(0,400.1,0.1) y1 = 220 - 0.66*x y2 = 372 - 2*x y3 = [0]*len(x) grid(True) xlim(0,400) ylim(0,400) xlabel('X') ylabel('Y') plot(x, y1, 'crimson') plot(x, y2, 'navy') legend(['0.5x +0.75y <= 165', '0.5x + 0.25y <= 93']) fill_between(x,y2,where=(y2<=y1),color='SpringGreen') fill_between(x,y1,where=(y1<=y2),color='SpringGreen') title ('Solution Problem 4 Mid Term') show()
84cb0f4c01814ee40341dc56e809c80a9cc53c60
dandocmando/Python-Answers-by-dandocmando
/PT15_15.1.py
593
3.59375
4
import time import random def l(): print("This program will ask you for a list of animals and then tell where the animal is in the list") time.sleep(0.5) print("Please type a list of animals with a space inbetween each") arr = input() print() lst = list(map(str,arr.split( ))) time.sleep(0.5) le = len(lst) time.sleep(0.5) print("You have {0} items in your animal list.".format(le)) print() time.sleep(0.5) for counter in range(le): time.sleep(0.5) print("Animal {0} is {1}".format((counter+1),lst[counter]))
0f671c0a066a05a44d9694b618c8257532473ed5
nicolepits/Security
/2-it21762/my-port-scanner.py
1,683
3.640625
4
import sys import socket from datetime import datetime # In this program we basically use Python's socket library to connect to a socket, and try to connect # to each port with the socket's connect() function. There is a for getting all port ranging from 1 to # 100. This program is in reality slow at reading all ports , one way of making this program faster is # to use multithreading techniques. # The banner is retrieved once the port is open using the recv function. #Main program starts now print("PORT SCANNER") f = open("addresses.txt", "r") for line in f.readlines(): #get ip from line ip = line.split("\n") #remove \n from the string try: target = socket.gethostbyname(ip[0]) # translate hostname to IPv4 except: print("Could not be reached IP : ", ip[0]) break # Add Banner print("*" * 50) print("Scanning Target: " + target) print("Scanning started at:" + str(datetime.now())) print("*" * 50) for port in range(1,100): print("Knock on port: ", port) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: con = s.connect((target, port)) print("Port is open!") banner = s.recv(2048) print(banner) except KeyboardInterrupt: print("\n Goodbye!") sys.exit() except socket.gaierror: print("\n Hostname could not be resolved.") sys.exit() except Exception as e: print(e) except 10060: pass f.close()
01f91f14ee71b2895c1ea0ef2be2175fae777024
howardcameron2/PHY494
/03_python/heaviside.py
506
3.625
4
# Heaviside step function def heaviside(x): theta = None if x < 0: theta = 0. elif x == 0: theta = 0.5 else: theta = 1. return theta xvalues = [] thetavalues = [] for i in range(-16,17): x=i/4 xvalues.append(x) theta = heaviside(x) thetavalues.append(theta) print("Theta(" + str(x) + ") = " + str(theta)) print(xvalues,thetavalues) import matplotlib.pyplot as plt plt.plot(xvalues, thetavalues, '-o', color="red", linewidth=2) plt.show()
9805977d2a55806dcffd9f6cfd534bf574d673dd
TreySchneider95/geocoding-project
/geocoding.py
1,728
3.75
4
'''Geocoding Flask project This program is a flask project that allows a user to input an address and return to the user the latitude and longitude of that address. The script requires that requests be installed as well as flask within the python enviroment you are running the program in. ''' import requests from flask import Flask, render_template, request app = Flask(__name__) # Base Url for geocoding URL = "https://us1.locationiq.com/v1/search.php" # Token for api call PRIVATE_TOKEN = "pk.727f7e39de9a6cafee73b56668557864" #test def get_geo(address): ''' Function that holds all of the functionality to find latitude and longitude ''' data = { 'key': PRIVATE_TOKEN, 'q': address, 'format': 'json' } response = requests.get(URL, params=data) latitude = response.json()[0]['lat'] longitude = response.json()[0]['lon'] geo_lst = [latitude, longitude] return geo_lst @app.route('/') def welcome(): ''' Start page with form on it ''' return render_template('home.html') @app.route('/locate', methods = ['GET', 'POST']) def show_location(): ''' Page that returns the latitude and longitude of the address entered in ''' lst = get_geo(request.form['address']) return render_template('show.html', latitude = lst[0], longitude = lst[1]) @app.route('/curl-test/<address>') def show_curl_location(address): ''' Dummy route used only for curl testing with bash file ''' address = address.replace(' ', '-') lst = get_geo(request.form['address']) return render_template('curlshow.html', latitude = lst[0], longitude = lst[1]) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
a6146ec0ee02faa4b34f03bdf7ef6f7d27c31169
macnaer/python-apps
/Lessons/03. OOP Intro/lib/Person.py
758
4
4
if __name__ == "__main__": Person class Person: def __init__(self, name: str, surname: str, age: int): self.__name = name self.__surname = surname self.__age = age print("Constructor works") def show_person_info(self): print("Name: ", self.__name, "\nSurname: ", self.__surname, "\nAge: ", self.__age) @property def age(self): return self.__age @age.setter def age(self, new_age): if self.__age == new_age: print("The same age") elif self.__age > new_age: print("Error bad idea") elif new_age >= 120: print(self.__name, " can't live ", new_age, " years") else: self.__age = new_age
3b88d00fabdf7fbf63dc02a491a247d5d17cbe4d
shelcia/InterviewQuestionPython
/MasaiChallenge/minimumRouterRange.py
1,086
3.78125
4
# Minimum Router Range # Problem # Submissions # Leaderboard # Discussions # There are N houses in a straight line i.e, on X-axis and K routers whose signal has to reach the entire road of houses All routers have some strength , which denotes the range of signal that it can cover in both the directions. # The router's strength should not be wasted unnecessarily ,so we have to keep its range minimum. # Find the minimum range of strength of all , utilising all the given routers such that all houses can receive it. # Input Format # The first line contains two integers, N and K - denoting the number of houses and number of routers. The next line contains N integers denoting the position of the houses in the straight line. # Constraints # 1 <= N <= 10^5 # 1 <= K < N # 1 <= Positioni <= 10^7 # Output Format # Print the minimum range in a new line. # Sample Input 0 # 3 2 # 1 5 20 # Sample Output 0 # 2 # Explanation 0 # The optimal answer is 2. # A router positioned at 3, can serve houses at 1 and 5. # The other router can be placed at 18, to serve house at 20.
11bec3515f21feb0091e265291f1e840bbab4ea7
yangyali1015/webservice
/class_20190106/class_循环练习.py
2,062
3.796875
4
# # a=('请输入您想要的配料:') # active=True # while active: # message =input(a) # if message =='quit': # active=False # else: # print('我们会在披萨中添加此配料') # a='请问你多大了?' # age =() # while True: # age=int(input(a)) # if age <= 3: # print('免费') # elif 3< age<12: # print('请支付10美元') # else: # print('请支付15美元') # sandwich_orders=['汉堡包','肯德基','麦当劳','pastrami','pastrami','pastrami'] # finished_sandwiches=[] # for name in sandwich_orders: # print('I made your' +name+'sandwich') # finished_sandwiches.append(name) # print(finished_sandwiches) # print('牛肉卖完了') # while 'pastrami' in sandwich_orders: # sandwich_orders.remove('pastrami') # print(sandwich_orders) dreams={} active = True while active: name = input ('您好,请问您怎么称呼?') dream = input ('请问你有什么梦想吗') dreams[name]=dream repeat = input('还要继续调查吗') if repeat == 'no': active =False print('调查结果') print(dreams) for name,dream in dreams.items(): print(name +'的梦想是:'+dream) # c[0] = {'手撕包菜': '10元', '香干肉丝': '10元', '土豆丝': '10元', '胡萝卜炒肉': '10元'} # c[1] = {'凉拌黄瓜': '10元', '凉拌皮蛋': '10元'} # c[2] = {'大盆花菜': '16元', '红烧鱼块': '18元'} # if order ==c[0]: # for d in c : # print(d) # # for e in d.keys(): # f =input(('请输入菜名')) # if f in e: # print(f +d[e]) # 第二种方法 # orders ={'手撕包菜':'10元','香干肉丝':'10元'} # a= input('输入菜名') # for b in orders .keys(): # c=[b] # if a ==b: # print(a+orders[b]) # elif a!=b: # print('您要的菜我们店没有') # d=input('请选择您要的菜名') # if d== caiming: # print(d+pingjia_orders[caiming])
4b6408e9411c2ce638e8cee21a063e2c32bed2f5
chengcheng8632/lovely-nuts
/114 Flatten Binary Tree to Linked List.py
1,412
3.84375
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 flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if root == None: return None def getlist(root, res=[]): res.append(root.val) if root.left: getlist(root.left, res) if root.right: getlist(root.right, res) def build(res): root.val = res[0] a = root for i in range(len(res) - 1): p = TreeNode(res[i + 1]) a.right = p a = a.right return root res = [] getlist(root, res) print(res) root.val = res[0] if root.left: root.left = None i = 1 while i <= len(res) - 1: if root.left: root.left = None if root.right: root.right.val = res[i] # i = i + 1 print('1', i) root = root.right else: temp = TreeNode(res[i]) root.right = temp i = i + 1 root = root.right print('2', i)
478c34ea5f652fcbd880b55ae7afd8652237dc18
CharlyWelch/code-katas
/objects.py
283
3.65625
4
""" Kata: Creating a string for an array of objects from a set of words #1 Best practices solution by **** and others: """ def words_to_object(s): objects = s.split() print(words_to_object("1 red 2 white 3 violet 4 green")) # { _key : _value(_key) for _key in _container }
e43068be614cf828b301419c16f703080c74d6a4
bitterengsci/algorithm
/九章算法/基础班LintCode/3.1534. Convert Binary Search Tree to Sorted Doubly Linked List.py
2,336
4.21875
4
#-*-coding:utf-8-*- ''' Description Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list. We want to transform this BST into a circular doubly linked list. Each node in a doubly linked list has a predecessor and successor. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element. The figure below shows the circular doubly linked list for the BST above. The "head" symbol means the node it points to is the smallest element of the linked list. Specifically, we want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. We should return the pointer to the first element of the linked list. The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship. ''' # Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param root: root of a tree @return: head node of a doubly linked list """ def treeToDoublyList(self, root): if not root: return root first, last, prev = None, None, None # iterate the tree like a list for v in self.inorder(root): if first is None: first = v last = v if prev is not None: prev.right = v v.left = prev prev = v first.left = last last.right = first return first def inorder(self, node): if not node: return for n in self.inorder(node.left): yield n yield node for n in self.inorder(node.right): yield n ''' if node.left is leaf: node.left.right = node if node.right is leaf: node.right.right = node.ascentor node.ascentor.left = node.right node.right.left = node TODO 不知道如何实现 '''
f2a5d812e3c43e78e3fafddd72beb7af8bb9a925
sbhackerspace/sbhx-ai
/connect4/human_player.py
520
3.53125
4
from board import * class Human: def __init__(self): pass def SetPlayerNumber(self, player): self.player = player def GetMove(self, board): board.Display() available_moves = board.GetAvailableMoves() while True: print("Player ", self.player, " (", board.player_chars[self.player], "), please enter a move:", sep='') move = input() try: move = int(move) except: pass for m in available_moves: if move == m: return move print("Invalid Move!") return -1
2684274ababfeedba7a3e9a1b5fe0d00386346b0
HieuDoan188/QAI_module1
/code-lab-6.py
329
3.5
4
# 42 s = input() print(s.upper()) # 43 s = input() l = len(s) if s != "a": print(s[0:2]+s[l-2:l]) else: print("") # 44 s1 = input() s2 = input() s3 = s1[0:2] + s2[2:] s1 = s2[0:2] + s1[2:] s2 = s3 print(s1 + " " + s2) #45 s = "The quick brown fox jumps over the lazy dog" t = s.split() m = " " print(m.join(t[::-1]))
1d8d65a71f215e296d09c32157283cbee8d30a60
vega2k/python_basic
/exercise/5char_count_dict.py
251
3.75
4
message = \ 'It was a bright cold day in April, and the clocks were striking thirteen.' print(message, type(message)) msg_dict = dict() for msg in message: print(msg, message.count(msg)) msg_dict[msg] = message.count(msg) print(msg_dict)