blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
5d3707ba313e522dde805ab03bc7840a75019834 | Stunion235/TicTacToe | /Final project-TicTacToe with OOP.py | 8,439 | 3.90625 | 4 | #Tic Tac Toe
#Note: I worked alone for this project.
#ADDED USER-FRIENDLY IMPROVEMENTS:
# 1. Defined a getHint() function that is called if the user types 'hint' for a move.
# 2. Implemented a __repr__() for the TicTacToe class if the user wants to print it.
# 3. Created a printInstructions() function to print the instructions
# 4. Changed the getPlayerMove() function to alert the user if a move is invalid.
import random
class TicTacToe():
def __repr__(self):
return('<\nClass Name: ' + self.__class__.__name__ + '\nCurrent Turn: Player ' + str(turn) + '\nBest Move: ' + str(self.getHint()) + '\nTied: ' + str(self.isBoardFull(theBoard)) + '\nGame over: ' + str(not(gameIsPlaying)) + '\n>')
def drawBoard(self, board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
def whoGoesFirst(self):
# Randomly choose the player who goes first.
return(random.randint(1,2))
def playAgain(self):
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
def makeMove(self, board, letter, move):
board[move] = letter
def isWinner(self, bo, le):
# Given a board and a player's letter, this function returns True if that player has won.
# We use bo instead of board and le instead of letter so we don't have to type as much.
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
def getBoardCopy(self, board):
# Make a duplicate of the board list and return the duplicate.
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard
def isSpaceFree(self, board, move):
# Return true if the passed move is free on the passed board.
return board[move] == ' '
def getPlayerMove(self, board):
# Let the player type in his move.
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not self.isSpaceFree(board, int(move)):
print('Player', turn, 'what is your move?', end='\t')
move = input()
#Check if the move is a number, 'hint', or '?'. If not, the user is told so.
if move.upper() not in '1 2 3 4 5 6 7 8 9 HINT ?'.split():
print('Invalid move. Enter a number from 1 to 9 or type hint for a hint.')
move = '0'
#Check if the space is free. If not, the user will be alerted.
elif move.isnumeric() and not(self.isSpaceFree(board, int(move))):
print('That space is occupied.')
move = '0'
#Do the appropriate task if the user typed "hint" or "?".
elif move.lower() == 'hint':
print('Hint:', self.getHint(), '\n')
elif move == '?':
self.printInstructions()
return int(move)
def chooseRandomMoveFromList(self, board, movesList):
# Returns a valid move from the passed list on the passed board.
# Returns None if there is no valid move.
possibleMoves = []
for i in movesList:
if self.isSpaceFree(board, i):
possibleMoves.append(i)
if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None
def getComputerMove(self, board, Letter2):
# Given a board and the computer's letter, determine where to move and return that move.
if Letter2 == 'X':
Letter1 = 'O'
else:
Letter1 = 'X'
# Here is our algorithm for our Tic Tac Toe AI:
# First, check if we can win in the next move
for i in range(1, 10):
copy = self.getBoardCopy(board)
if self.isSpaceFree(copy, i):
self.makeMove(copy, Letter2, i)
if self.isWinner(copy, Letter2):
return i
# Check if the player could win on his next move, and block them.
for i in range(1, 10):
copy = self.getBoardCopy(board)
if self.isSpaceFree(copy, i):
self.makeMove(copy, Letter1, i)
if self.isWinner(copy, Letter1):
return i
# Try to take one of the corners, if they are free.
move = self.chooseRandomMoveFromList(board, [1, 3, 7, 9])
if (move != None):
return move
# Try to take the center, if it is free.
if self.isSpaceFree(board, 5):
return 5
# Move on one of the sides.
return self.chooseRandomMoveFromList(board, [2, 4, 6, 8])
def isBoardFull(self, board):
# Return True if every space on the board has been taken. Otherwise return False.
for i in range(1, 10):
if self.isSpaceFree(board, i):
return False
return True
#Uses the getComputerMove() function to provide the player with a hint.
def getHint(self):
return(game.getComputerMove(theBoard, ['X', 'O'][turn - 1]))
#Print the instructions if user types "?" for a move.
def printInstructions(self):
print('='*23)
print('Instructions:')
print('When you are asked for a move, enter a number from 1-9 and press enter.')
print('They correspond to the spaces in the same way as the keys on a numeric keypad:\n')
print('7 8 9')
print('4 5 6')
print('1 2 3')
print('\nYou can also type "hint" for a hint or "?" to see these instructions.')
print('='*78)
#Define the object game to be of the class TicTacToe.
game = TicTacToe()
print('\nWelcome to Tic Tac Toe!'.upper())
game.printInstructions()
while True:
#Reset the board
theBoard = [' '] * 10
Letter1, Letter2 = ['X', 'O']
turn = game.whoGoesFirst()
print('Player', turn, 'will go first.')
gameIsPlaying = True
while gameIsPlaying:
if turn == 1:
#Player 1's turn.
print('It is Player 1\'s turn.')
game.drawBoard(theBoard)
move = game.getPlayerMove(theBoard)
game.makeMove(theBoard, Letter1, move)
print()
#Check if Player 1 won or for a tie.
if game.isWinner(theBoard, Letter1):
game.drawBoard(theBoard)
print('Player 1 has won the game!')
gameIsPlaying = False
else:
if game.isBoardFull(theBoard):
game.drawBoard(theBoard)
print('The game is a tie!')
break
turn = 2
else:
#Player 2's turn.
print('It is Player 2\'s turn.')
game.drawBoard(theBoard)
move = game.getPlayerMove(theBoard)
game.makeMove(theBoard, Letter2, move)
print()
#Check if Player 2 won or for a tie.
if game.isWinner(theBoard, Letter2):
game.drawBoard(theBoard)
print('Player 2 has won the game!')
gameIsPlaying = False
else:
if game.isBoardFull(theBoard):
game.drawBoard(theBoard)
print('The game is a tie!')
break
turn = 1
if not game.playAgain():
break
|
d3fa8bf44b2ce96fbe50cde8042a4c636c797ee7 | Smithdyl/Ch.04_Conditionals | /4.3_Quiz_Master.py | 2,458 | 3.765625 | 4 | '''
QUIZ MASTER PROJECT
-------------------
The criteria for the project are on the website. Make sure you test this quiz with
two of your student colleagues before you run it by your instructor.
'''
print("Chapter 4 Quiz")
print()
input("Type anything to begin: ")
print()
total_correct=0
total_possible=0
print("Question 1")
total_possible+=1
answer_correct =int(input("What is 9+3? "))
if answer_correct ==12:
print("Correct!")
total_correct+=1
else:
print("Incorrect, the correct answer is 12")
print()
print("Question 2")
total_possible+=1
name_correct =input("Who is the current President? ")
if name_correct.lower() == "donald trump" or name_correct.lower()=="trump":
print("Correct...unfortunately")
total_correct+=1
else:
print("Incorrect, the current President is Donald Trump....unfortunately")
print()
print("Question 3")
total_possible+=1
print()
print("A. Mr. Hermon")
print("B. Mr. Davis")
print("C. Mrs. Jacques")
answer_correct =input("Who is the Best Teacher? ")
if answer_correct.lower()== "a" or answer_correct.lower()=="mr. hermon" or answer_correct.lower()=="mr hermon":
print("Correct!")
total_correct+=1
else:
print("You're entilited to your opinion but it's wrong, the correct answer is A. Mr. Hermon.")
print()
print("Question 4")
total_possible+=1
print()
answer_correct= int(input("What is the square root of 100? "))
print()
if answer_correct== 10:
print("Correct!")
total_correct+=1
else:
print("Incorrect, the answer is 10")
print()
print("Question 5")
total_possible+=1
print()
answer_correct=int(input("What is 9+10? "))
if answer_correct==19:
print("Correct!")
total_correct+=1
elif answer_correct==21:
print("You memelord you, i'll allow it")
total_correct+=1
else:
print("Incorrect, the answer is 19")
print()
print("Question 6")
total_possible+=1
print()
name_correct=input("Who wrote this exam? ")
if name_correct.lower()=="dylan smith" or name_correct.lower()=="dylan":
print("Correct!")
total_correct+=1
else:
print("Incorrect, it was written by Dylan Smith")
print()
print("Question 7")
total_possible+=1
answer_correct=int(input("What is 99+1? "))
if answer_correct==100:
print("Correct!")
total_correct+=1
else:
print("C'mon man the answer was 100")
print()
input("Type anything to see your score ")
print("Your score was", total_correct, "out of", total_possible)
final_grade=(total_correct/total_possible)*100
print("or", final_grade//1,"%") |
9af1710d3635a66317269d22089af4361db1a9a3 | qeedquan/challenges | /codegolf/draw-the-olympic-games-logo.py | 1,646 | 3.78125 | 4 | """
Challenge
Draw the Olympic Games logo...
Olympic Games logo
...as character (e.g. ASCII) art!
Sample Output
* * * * * * * * *
* * * * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * *
* * * *
* * * * * *
Your art doesn't have to look exactly like mine, but it has to represent the Olympic rings well enough that it's recognizable.
Rules
The program must write the art to the console.
Shortest code (in bytes, any language) wins.
A solution that prints rings in their respective colors (or a close representation) will be awarded a minus-twenty-point bonus.
The winner will be chosen on February 23rd at the end of the 2014 Winter Olympics.
"""
olympic = """
* * * * * * * * *
* * * * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * *
* * * *
* * * * * *
"""
print(olympic)
|
7eb8f95401dc62fc9c6e646679c4dfa1bbd0ab67 | Kellyfang/Get-Out | /GET OUT/GET OUT.py | 5,063 | 3.5625 | 4 |
#Almighty Tech
#Get out
from gamelib import*
game=Game(800,600,"GET OUT")
bk=Image("images\\bk.jpg",game)
bk.resizeTo(800,600)
logo=Image("images\\GET OUT!!!.png",game)
comp=Image("images\\ALMIGHTY TECH.png",game)
comp.moveTo(400,400)
bk2=Image("images\\haunted house.png",game)
bk2.resizeTo(800,600)
eman=Animation("images\\kevin.png",21,game,1161/7,810/3)
eman.resizeBy(-40)
eman.moveTo(100,500)
'''g1=Animation("images\\amy.png",21,game,670/7,391/3)
g1.resizeBy(-40)'''
angelica=Animation("images\\angel.png",8,game,863/8,141,6)
angelica.moveTo(200,500)
game.setBackground(bk2)
ghost=Animation("images\\ghost.png",40,game,466/10,192/4)
ghost2=Animation("images\\ghost.png",40,game,466/10,192/4)
ghosts=Animation("images\\ghost.png",40,game,466/10,192/4)
ghosts.resizeBy(-10)
ghost.setSpeed(3,60)
ghost.moveTo(100,450)
ghost2.setSpeed(3,60)
ghost2.moveTo(600,200)
jumping = False
landed = False
factor = 1
ghosts = []#empty list
for index in range(20):#use a loop to add items
ghosts.append(Animation("images\\ghost.png",40,game,466/10,192/4,2))
for index in range(20):#use a loop to set the positions and speed
x = randint(800,4000)
y = randint(400,550)
ghosts[index].moveTo(x,y)
ghosts[index].setSpeed(3,90)
ghostsPassed=0
while not game.over:
game.processInput()
bk.draw()
logo.draw()
comp.draw()
ghost.move(True)
ghost2.move(True)
if keys.Pressed[K_SPACE]:
game.over=True
game.update(60)
game.over=False
ghosts = []#empty list
for index in range(20):#use a loop to add items
ghosts.append(Animation("images\\ghost.png",40,game,466/10,192/4,2))
for index in range(20):#use a loop to set the positions and speed
x = randint(800,4000)
y = randint(400,550)
ghosts[index].moveTo(x,y)
ghosts[index].setSpeed(3,90)
while not game.over:
game.processInput()
game.scrollBackground("left",2)
angelica.draw()
for index in range(20):
ghosts[index].move()
for index in range(20):#the loop will go through the list of asteroids
if ghosts[index].collidedWith(angelica):#each asteroid is checked
angelica.health -= 1
if ghosts[index].isOffScreen("left") and ghosts[index].visible:
ghosts[index].visible=False
ghostsPassed+=1
if angelica.y< 500:
landed = False
else:
landed = True
if keys.Pressed[K_SPACE] or keys.Pressed[K_UP] and landed and not jumping:
jumping = True
if jumping:
angelica.y -=27*factor
factor*=.95
landed = False
if factor < .18:
jumping = False
factor = 1
if not landed:
angelica.y +=8
if keys.Pressed[K_RIGHT]:
angelica.x+=2
if keys.Pressed[K_LEFT]:
angelica.x-=2
if angelica.health<=1:
game.over=True
if ghostsPassed>=20:
game.over=True
game.drawText("ghostsPassed: " + str(ghostsPassed), 600, 100)
game.drawText("health: "+str(angelica.health),angelica.x,angelica.y+50)
game.update(60)
game.over=False
ghosts2 = []#empty list
for index in range(50):#use a loop to add items
ghosts2.append(Animation("images\\ghost.png",40,game,466/10,192/4,2))
for index in range(50):#use a loop to set the positions and speed
x = randint(800,10000)
y = randint(400,550)
ghosts2[index].moveTo(x,y)
ghosts2[index].setSpeed(3,90)
ghostsPassed=0
health=0
while not game.over:
game.processInput()
game.scrollBackground("left",2)
eman.draw()
for index in range(50):
ghosts2[index].move()
for index in range(50):#the loop will go through the list of asteroids
if ghosts2[index].collidedWith(eman):#each asteroid is checked
eman.health -= 1
if ghosts2[index].isOffScreen("left") and ghosts2[index].visible:
ghosts2[index].visible=False
ghostsPassed+=1
if eman.y< 500:
landed = False
else:
landed = True
if keys.Pressed[K_SPACE] or keys.Pressed[K_UP] and landed and not jumping:
jumping = True
if jumping:
eman.y -=27*factor
factor*=.95
landed = False
if factor < .18:
jumping = False
factor = 1
if not landed:
eman.y +=8
if keys.Pressed[K_RIGHT]:
eman.x+=2
if keys.Pressed[K_LEFT]:
eman.x-=2
if eman.health<=1:
game.over=True
if ghostsPassed>=50:
game.over=True
game.drawText("ghostsPassed: " + str(ghostsPassed), 600, 100)
game.drawText("health: "+str(eman.health),eman.x,eman.y+50)
game.update(60)
game.over=False
logo2=Image("images\\gameover.png",game)
while not game.over:
game.processInput()
bk.draw()
logo2.draw()
game.update(60)
|
85783d7a0e5ac551bc8f9dce451984edcfab7735 | malek19-meet/yl1201718 | /lab3.py | 421 | 3.71875 | 4 | class Animal(object):
def __init__(self,sound,name,age,favourite_color):
self.sound = sound
self.name = name
self.age = age
self.favourite_color = favourite_color
def eat(self,food):
print("YUMMY!! " + self.name + "is eating " + food)
def description(self):
print(self.name + "is" + self.age + "years old and loves the color " + self.favourite_color)
m = Animal("miaw","cat ","14","orange")
m.eat("fish")
|
77edf42547803bcc7c2afb2dfb19205e07156a3a | Jeff-Clapper/Coding_Dojo | /Pre-Boot/the_missing_assignment.py | 371 | 4.28125 | 4 | vowels = ['a','e','i','o','u','y']
non_vowel = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
name = input('Write what you will: ')
name = name.lower()
name = str(name)
vowel = 0
cons = 0
for letter in name:
if letter in vowels:
vowel += 1
elif letter in non_vowel:
cons += 1
print(vowel)
print(cons)
|
304280ed754939a66008139fc761e21fe6530867 | khushboo1510/leetcode-solutions | /30-Day LeetCoding Challenge/November/Medium/47. Permutations II.py | 711 | 3.578125 | 4 | # https://leetcode.com/problems/permutations-ii/submissions/
# Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
self.result = []
self.n = len(nums)
nums.sort()
def backtrack(arr, path, m):
if not arr:
self.result.append(path)
for i in range(len(arr)):
if i > 0 and arr[i] == arr[i - 1]:
continue
backtrack(arr[:i] + arr[i+1:], path + [arr[i]], m + 1)
backtrack(nums, [], 0)
return self.result
|
edc886f356ccc6be90228f2a96eae81fb19d045d | NiallS4/CA117 | /lab_9.1/geometry_091.py | 1,333 | 4 | 4 | from math import sqrt
class Shape(object):
def __init__(self, points):
self.points = points
def sides(self):
l = []
for i in range(1, len(self.points)):
l.append(sqrt((self.points[i-1].x - self.points[i].x)**2 +
(self.points[i-1].y - self.points[i].y)**2))
l.append(sqrt((self.points[len(self.points)-1].x - self.points[0].x)**2 +
(self.points[len(self.points)-1].y - self.points[0].y)**2))
return l
def perimeter(self):
return sum(self.sides())
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distance(self, other):
distance = sqrt((other.x - self.x)**2 + (other.y - self.y)**2)
return distance
class Triangle(Shape):
def area(self):
sides = self.sides()
s = (sides[0] + sides[1] + sides[2]) / 2
return sqrt(s*(s - sides[0])*(s - sides[1])*(s - sides[2]))
class Square(Shape):
def area(self):
sides = self.sides()
return sides[0] * sides[1]
def main():
t1 = Triangle([Point(0,0), Point(3,4), Point(6, 0)])
print(t1.sides())
print(t1.perimeter())
print(t1.area())
t2 = Triangle([Point(0,0), Point(4,0), Point(4, 3)])
print(t2.sides())
print(t2.perimeter())
print(t2.area())
s1 = Square([Point(0,0), Point(5,0), Point(5,5), Point(0,5)])
print(s1.sides())
print(s1.perimeter())
print(s1.area())
if __name__ == '__main__':
main() |
30189b7c155fcb74858d29ac4d71974dde347b39 | jerrywardlow/Euler | /4palindromes.py | 581 | 4.21875 | 4 | def is_palindrome(target):
'''Returns a Boolean ofwhether a number is a palindrome or not'''
return str(target) == str(target)[::-1]
def largest_palindrome_product(a, b):
'''Prints the largest palindromic number with factors in the specified
range, 'a' being the low end and 'b' being the high.'''
biggest = 0
for i in range(a, b):
for j in range(a, b):
target = i*j
if is_palindrome(target):
if target > biggest:
biggest = target
print biggest
largest_palindrome_product(100, 999)
|
affc93b2fa24b27e79d01072333c5f47bceef55d | drunckoder/ThesisWork | /sources/NoiseGenerator.py | 550 | 3.5625 | 4 | import numpy as np
def put_pixel(target: np.array, x: int, y: int, color: tuple = (0., 0., 0.)):
for i in range(3):
target[i][y][x] = color[i]
def noise_image(target: np.array, noise_level: float, size: int = 32):
for y in range(size):
for x in range(size):
if np.random.rand() < noise_level:
put_pixel(target=target, x=x, y=y)
def add_noise(target: np.array, noise_level: float, size: int = 32):
for image in target:
noise_image(target=image, noise_level=noise_level, size=size)
|
26594d0a5c1f3ee5eb7d347af05c3fa325d75dcb | Kundan-pseudo/myprofile | /discount.py | 174 | 3.625 | 4 | a=input("Enter the Amount")
if (a<1000):
print a-a/10.0
elif 1000<=a<2000:
print a-(a*20.0)/100.0
elif 2000<=a<3000:
print a-(a*30.0)/100.0
else :
print a-(a*50.0)/100.0
|
417fbfe14d0557bf4037ff2c86397aa6e049b1e2 | MikaMahaputra/Binus | /Assignment/Ascii count.py | 367 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 24 22:52:12 2019
@author: user
"""
def countletter(str_input):
a= []
b= []
for i in str_input:
if i not in a:
a.append(i)
b.append(1)
else:
x=findinlist(i,a)
b[x]+=1
for i in range(len(a)):
print(a[i], "=", b[i])
|
c05e82e0d20d66f2fa2aa40931756a6abcab8491 | davidmurphy5456/eulerprojects | /euler project 26.py | 646 | 3.53125 | 4 | def maxlength():
lim = 1000
maxlength=0
max_d= 1
for i in range(1, lim):
q = []
val = 1
len_recur = 0
while val not in q:
if not val: #if val is 0, empty, false
break
len_recur += 1
q.append(val)
val = (val% i) * 10 #returns val*10 if val < i
if not val:
continue
len_recur -= q.index(val) # subtract leading digits
if len_recur > maxlength :
maxlength = len_recur
max_d = i
print(max_d)
print(q)
print(maxlength)
maxlength()
|
ea1d5e3feafc9763d03bdbef578d7379b5ec193c | perryc85/word_hyphen | /Word_Hy-phen-a-tion.py | 3,609 | 4.125 | 4 | # target word
word = input('Enter word: ').strip()
# each index is a space in the target word.
# Each val is the score of that space.
scores = [0] * len(word)
scores.pop() # minus one
DOT = "."
def stripped_patterns(pattern):
stripped_pattern = ''
for char in pattern:
# strip out all non-alpha chars and store them into temp var
if char.isalpha():
stripped_pattern += char
return stripped_pattern
def find_score_indexs(pattern):
# the index of scores in the pattern
list_vals = []
for i, value in enumerate(pattern):
if value.isdigit():
list_vals.append(i)
return list_vals
def count_scores(pattern):
num_of_scores = 0
for i, value in enumerate(pattern):
if value.isdigit():
# keep track of the number of scores in pattern
num_of_scores += 1
return num_of_scores
def pattern_in_string(pattern):
# index of stripped_pattern in the target word
pattern_match = word.find(stripped_pattern)
list_vals = find_score_indexs(pattern)
num_of_scores = count_scores(pattern)
def score_spaces(pattern, scores, pattern_match, list_vals, dot_in_front):
print(f'Pattern: {pattern}')
# find index of scores in pattern
scores_index = find_score_indexs(pattern)
# the formula to find the correct space score --
# the PM + list_vals - num_of scores
if dot_in_front:
num_of_scores = 2
else:
num_of_scores = 1
for val in scores_index:
# var to hold proper space in scores list
proper_space = pattern_match + val - num_of_scores
if len(scores) - 1 >= proper_space \
and int(pattern[val]) > int(scores[proper_space]):
scores[proper_space] = pattern[val]
num_of_scores += 1
print(f'Scores: {scores}')
return scores
def hyphen_word(pattern, scores, word):
# create string with hyphens
hyphen_word = ''
# the actual hyphen
hyphen = '-'
num_of_hyphens = 1
for i, w in enumerate(word):
if i <= len(scores) - 1 \
and int(scores[i]) % 2 != 0:
hyphen_word += w + hyphen
else:
hyphen_word += w
return hyphen_word
# read file containing patterns -- main part of program
with open('patterns.txt','r') as f:
# iterate over file
for pattern in f:
pattern = pattern.strip()
stripped_pattern = stripped_patterns(pattern)
pattern_match = word.find(stripped_pattern)
list_vals = find_score_indexs(pattern)
# if dot at start, pattern must appear in beg.
if DOT == pattern[0] and pattern_match == 0:
list_vals = find_score_indexs(pattern)
num_of_scores = count_scores(pattern)
scores = score_spaces(pattern, scores, pattern_match, list_vals, True)
# if dot at end, pattern must appear at the end
elif DOT == pattern[-1] and len(stripped_pattern) + pattern_match == len(word):
list_vals = find_score_indexs(pattern)
num_of_scores = count_scores(pattern)
scores = score_spaces(pattern, scores, pattern_match, list_vals, False)
# if pattern appears in string, score it according to the rules.
elif pattern_match >= 0 and DOT != pattern[0] and DOT != pattern[-1]:
pattern_in_string(pattern)
scores = score_spaces(pattern, scores, pattern_match, list_vals, False)
print(hyphen_word(pattern, scores, word)) |
7859f07d78594e9f86faeff05170949e29f459a2 | lawy623/Algorithm_Interview_Prep | /Algo/Leetcode/043MulString.py | 541 | 3.59375 | 4 | class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
return str(self._multiply(num1, num2))
def _multiply(self, num1, num2):
n1 = len(num1)
n2 = len(num2)
if n2 == 0:
return 0
return self._multiply(num1, num2[:-1]) * 10 + nToi(num1) * cToi(num2[-1])
def cToi(c):
return ord(c) - ord('0')
def nToi(s):
res = 0
for n in s:
res = res * 10 + cToi(n)
return res
|
a9fb1b96b8b03c4b44fed9e0c5af89f50b5a78e8 | daehyun1023/Algorithm | /python/programmers/level2/오픈채팅방.py | 577 | 3.53125 | 4 | def solution(records):
answer=[]
id_name = {}
for record in records:
record = record.split(' ')
if record[0] == 'Enter':
id_name[record[1]] = record[2]
answer.append(record[1] + "님이 들어왔습니다.")
elif record[0] == 'Change':
id_name[record[1]] = record[2]
else:
answer.append(record[1] + "님이 나갔습니다.")
for i in range(len(answer)):
idx = answer[i].index('님')
answer[i] = id_name[answer[i][:idx]]+answer[i][idx:]
return answer |
783c5577ef69d6a3231431f8535aa6a7af428939 | ArthurIpolitov/GammaCourses | /012_map_zip/012_itertools.py | 2,580 | 3.890625 | 4 | # ! ---- # ---- # ---- # ---- # ---- # ----
'''
ITERTOOLS
'''
# ! ---- # ---- # ---- # ---- # ---- # ----
# ! ·
# ! ·
# ! ---- # ---- # ---- # ---- # ---- # ----
import itertools
import itertools as itl
# ! ---- # ---- # ---- # ---- # ---- # ----
# ! ·
# ! ·
# ! ---- # ---- # ---- # ---- # ---- # ----
'''EXAMPLE COUNTER'''
# ! ---- # ---- # ---- # ---- # ---- # ----
# counter = itl.count()
# print(counter)
# next(counter)
# print(counter)
# ! ---- # ---- # ---- # ---- # ---- # ----
# itl.count(start=5, step=5)
# ! ---- # ---- # ---- # ---- # ---- # ----
# counter = itl.cycle([1,2,3,4,5])
# ! ---- # ---- # ---- # ---- # ---- # ----
# counter = itl.repeat(2, times=5)
# ! ---- # ---- # ---- # ---- # ---- # ----
# ! ---- # ---- # ---- # ---- # ---- # ----
# def squares(x, y):
# return x ** y
# ! ---- # ---- # ---- # ---- # ---- # ----
# result = map(squares, range(1,11))
# print(list(result))
# result2 = itl.starmap(squares, [(1, 2),(2, 2),(5, 4)])
# print(list(result2))
# ! ---- # ---- # ---- # ---- # ---- # ----
# letters = ['a', 'b', 'c', 'd']
# numbers = [1, 2, 3, 4]
# names = ['Jack', 'John']
# ! ---- # ---- # ---- # ---- # ---- # ----
# result = itl.combinations(letters, 2)
# for x in result:
# print(x)
# ! ---- # ---- # ---- # ---- # ---- # ----
# result2 = itl.permutations(letters,2)
# for x in result2:
# print(x)
# ! ---- # ---- # ---- # ---- # ---- # ----
# result3 = itl.product(letters,repeat=2)
# for x in result3:
# print(x)
# ! ---- # ---- # ---- # ---- # ---- # ----
# result4 = itl.combinations_with_replacement(letters, 2)
# for x in result4:
# print(x)
# ! ---- # ---- # ---- # ---- # ---- # ----
# result5 = itl.chain(letters, numbers)
# print(list(result5))
# for x in result5:
# print(list(x))
# ! ---- # ---- # ---- # ---- # ---- # ----
# with open('logs.txt', 'r', encoding='UTF8') as file:
# log_header = itl.islice(file,3)
#
# for line in log_header:
# print(line, end='')
# ! ---- # ---- # ---- # ---- # ---- # ----
# numbers2 = [4,5,4,3,2,1,0,4]
# selectors = [True, False, False, True]
#
# def more_than_two(x):
# if x > 2:
# return True
# return False
# ! ---- # ---- # ---- # ---- # ---- # ----
# result = itl.compress(letters,selectors)
# for x in result:
# print(x)
# ! ---- # ---- # ---- # ---- # ---- # ----
# result = filter(more_than_two, numbers2)
# for x in result:
# print(x)
# ! ---- # ---- # ---- # ---- # ---- # ----
# result2 = itl.filterfalse(more_than_two,numbers2)
# for x in result2:
# print(x)
# # ! ---- # ---- # ---- # ---- # ---- # ---- |
281f1e0bc4dd6e6fa9dd129f2372aba4d68ec829 | lvang0123/LeastCommonMultiple_TeamPurple | /main.py | 2,308 | 4.09375 | 4 | #Python Team Project - Least Common Multiple
#This program will prompt the user for two number inputs. The program will then try to find the least common multiple for those two numbers.
#May 1, 2018 - Ben, Dan, Kyle, Lisa, and Lia all worked on this program together during class time.
#Welcoming the user
print("Welcome to the Least Common Multiple program!")
print()
#Declaring variables
rerun = "Y"
#Rerunning the program if the user inputs 'Y' at the end of the program
while rerun.lower().upper() != "N":
#Prompting the user to input two numbers
print("Please enter two numbers that you want to find the least common multiple for.")
print()
while True:
try:
num1 = int(input("Number 1: "))
break
except ValueError:
print()
print("*** ERROR: Not an integer ***")
print()
while True:
try:
num2 = int(input("Number 2: "))
break
except ValueError:
print()
print("*** ERROR: Not an integer ***")
print()
print()
#if the second number entered is larger than the first
if(num1 < num2):
#the bigger of the two is logically the second one, and therefore BIGGER is assigned this value
bigger = num2
#the else statement of this if statement
else:
bigger = num1
#while true, loop initialization
while True:
if((bigger % num2 == 0) and (bigger % num1 ==0)):
#if BIGGER is both devisible by both input numbers without a remainder, assign LCM as the value of BIGGER
lcm = bigger
#break out of loop
break
#else add 1 to bigger, and continue the loop
bigger += 1
#when broken out of, print the value of LCM
print("Least Common Multiple: ", lcm)
print()
#Prompting the user to rerun the program or end it
while True:
print("Would you like to rerun the program?")
rerun = input("Enter Y to rerun it or N to end it: ")
if rerun.lower().upper() == "Y":
print()
print('---------------------------------------')
print()
break
elif rerun.lower().upper() == "N":
print()
break
else:
print()
print("*** ERROR: Must enter a Y or N ***")
print()
#Informing the user that the program has ended
print("Thank you for using the Least Common Multiple program!")
|
497b1af3acaeb540c1148d67370e9f70f456e739 | FiyinIsrael/chunk | /chunk.py | 2,050 | 3.90625 | 4 | import os
from pydub import AudioSegment
from pydub.silence import split_on_silence
# a function that splits the audio file into chunks
# and applies speech recognition
def silence_based_conversion(path, seconds_waiting=1):
# open the audio file stored in
# the local system as a wav file.
extension = path.split(".")[-1]
if extension == "mp3":
song = AudioSegment.from_mp3(path)
elif extension == "wav":
song = AudioSegment.from_wav(path)
else:
return "Bye Bye!"
# split track where silence is 0.5 seconds
# or more and get chunks
chunks = split_on_silence(song,
# must be silent for at least 0.5 seconds
# or 500 ms. adjust this value based on user
# requirement. if the speaker stays silent for
# longer, increase this value. else, decrease it.
min_silence_len = seconds_waiting * 1000,
# consider it silent if quieter than -16 dBFS
# adjust this per requirement
silence_thresh = -16
)
# create a directory to store the audio chunks.
try:
os.mkdir('audio_chunks')
except(FileExistsError):
pass
# move into the directory to
# store the audio files.
os.chdir('audio_chunks')
i = 0
# process each chunk
for chunk in chunks:
# Create silence chunk
chunk_silent = AudioSegment.silent(duration = 10)
# add 0.5 sec silence to beginning and
# end of audio chunk. This is done so that
# it doesn't seem abruptly sliced.
audio_chunk = chunk_silent + chunk + chunk_silent
# export audio chunk and save it in
# the current directory.
print("saving chunk{0}.wav".format(i))
# specify the bitrate to be 192 k
audio_chunk.export("./chunk{0}.wav".format(i), bitrate ='192k', format ="wav")
i += 1
os.chdir('..')
if __name__ == '__main__':
silence_based_conversion(input("Enter audio file name: "))
|
30372d850ad2e490892f199ed4ac020cd016b411 | sahilsuri008/python_practice | /01_acloud_guru/age.py | 129 | 4.09375 | 4 | #!/usr/bin/python
name=raw_input("Enter your name: ")
age=input("Enter your age: ")
print ("%s is %s years old." % (name,age))
|
9b097aaba27fdd9dcb23693e5e8f58a67fe16114 | chisoftltd/PythonTuples | /PythonTuples.py | 1,561 | 4.25 | 4 | thistuple = ("ben", "joy", "emma", "joy", "emma")
print(thistuple)
print(len(thistuple))
thistuple2 = ("ben",)
print(type(thistuple2))
thistuple2 = ("ben")
print(type(thistuple2))
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)
tuple4 = ("abd", 34, True, 40, "male")
print(tuple4)
print(type(tuple4))
thistuple1 = tuple(("apple", "banana", "cherry","apple", "banana", "cherry")) # note the double round-brackets
print(thistuple1)
print(thistuple1[1])
print(thistuple1[2])
print(thistuple1[-1])
print(thistuple1[-2])
thistuple2 = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango","ben", "joy", "emma")
print(thistuple2[1:4])
print(thistuple2[2:])
print(thistuple2[:4])
print(thistuple2[-5:-2])
print(thistuple2)
thistuple3 = ("apple", "banana", "cherry")
if "cherry" in thistuple3:
print("Yes, 'apple' is in the fruits tuple")
x = ("apple", "banana", "cherry")
y = list(x)
print(y)
y.append("orange")
y.remove("banana")
print(y)
y[1] = "kiwi"
x = tuple(y)
print(x)
k = x
del x
print(k)
#print(x)
print(y)
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
for t in fruits:
print(t)
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
for i in range(len(fruits)):
print(fruits[i])
print(i)
z = 0
while z < len(fruits):
print(fruits[z])
z = z + 1
xFruits = thistuple3 + fruits
print(xFruits)
xFruits = xFruits * 2
print(xFruits)
print(xFruits.count("apple"))
print(xFruits.index("banana")) |
ddf4ceec417c9c35369d71d20f60ec7c42457c7c | adaltospjr/SI-2-semestre | /Dicionario/exercicio.py | 1,303 | 4.125 | 4 | '''
Exercício 1
A - o maior número da lista
B - o menor número da lista
C - a quantidade de números pares contidos na lista
D - a média dos números contidos na lista
E - todos os números menores do que a média calculada no item anterior
'''
'''
par = 0
lista = []
numero = 0
for a in range(3):
numero = int(input("Digite um número: "))
lista.append(numero)
'''
'''
A
print(max(lista))
'''
'''
B
print(min(lista))
'''
'''
C
for a in lista:
if a % 2 == 0:
par += 1
print(lista)
print(par)
'''
'''
media = sum(lista) / len(lista)
print(media)
'''
# Exercício 2
'''
lista = [1, 2, 3, 4, 5]
lista_par = []
lista_impar = []
for a in lista:
if a % 2 == 0:
lista_par.append(a)
else:
lista_impar.append(a)
print("Lista par: ", lista_par)
print("Lista impar: ", lista_impar)
'''
'''
tupla_1 = (3, 1, 5, 3, 5)
tupla_2 = (5, 5, 7, 3, 1)
tupla_3 = tupla_1 + tupla_2
print(tupla_3)
'''
lista_1 = [1, 2, 3]
lista_2 = [4, 5, 6]
lista_3 = []
'''lista_1.insert(1, lista_2[0])
lista_1.insert(3, lista_2[1])
lista_1.insert(5, lista_2[2])'''
for a in range(1, len(lista_1) + 1):
for b in range(1, len(lista_2) + 1):
lista_3.insert(b, lista_1[b])
print(lista_3) |
378372e1019c8c8c3757601329b04d1043088ed4 | apolonis/PythonExamples | /guesTheNumberGame/app.py | 430 | 3.953125 | 4 | # gues the random number from 0-10, u've got 3 try's
import random
secretNumber = random.randint(0,10)
guessCount = 0
guessLimit = 3
print('Guess the number from 0 - 10')
while guessCount < guessLimit:
guess = int(input('Guess: '))
guessCount += 1
if guess == secretNumber:
print('Congratulations! U won! ')
print(f'Guess times:{guessCount}')
break
else:
print('Failed! Try again') |
6d084b1a4eb9bdfe737e38cefd43e627710d27e7 | nehni/pdsnd_github | /bikeshare_2.py | 9,120 | 4.28125 | 4 | """ This is a script to analyse the data of a bikeshare company
This work was created by nehni as part of the udacity programming for data science nanodegree
"""
import time
import pandas as pd
import numpy as np
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
city = ''
month = ''
day = ''
df = []
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
global city, month, day
print("\nHello! Let\'s explore some US bikeshare data!\n")
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
city = input("Which city would you like to explore?\n").lower()
while city not in ['chicago', 'new york city', 'washington']:
print(
"There is no data available for {}. Please enter another city (chicago, new york city or washington).\n".format(
city))
city = input("Which city would you like to explore?\n")
else:
print("\nGreat, let\'s have a look at {}!\n".format(city.title()))
month = input(
"Which month would you like to look at? If you want to look at all available months, please select all.\n").lower()
while month not in ['all', 'january', 'february', 'march', 'april', 'may', 'june']:
print("There is no data available for {}. Please enter another month (january to june).\n".format(
month))
month = input("Which month would you like to look at? If you want to look at all months, please select all.\n")
else:
if month == 'all':
print('\nGreat, we will look for data in all months.')
else:
print('\nGreat, we will look for data in {}.\n'.format(month.title()))
day = input(
"Which day of the week would you like to look at? If you want to look at all available days, please select all.\n").lower()
while day not in ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']:
print("There is no data available for {}. Please enter another day (monday to sunday).\n".format(
day))
day = input("Which month would you like to look at? If you want to look at all days, please select all.\n")
else:
if day == 'all':
print("\nOkay, we will look for data for all days.")
else:
print("\nOkay, we will look for data from {}s.\n".format(day.title()))
print('-' * 40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
global df
df = pd.read_csv(CITY_DATA[city])
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
df['start_hour'] = df['Start Time'].dt.hour
if month != 'all':
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
df = df[df['month'] == month]
if day != 'all':
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
common_month = df['month'].mode()[0]
months = ['january', 'february', 'march', 'april', 'may', 'june']
common_month = months[common_month - 1]
# display the most common day of week
common_day = df['day_of_week'].mode()[0]
# display the most common start hour
common_hour = df['start_hour'].mode()[0]
print("Within {}, the most frequent time of travel was {}, on {}s at {} o'clock.\n".format(city.title(),
common_month.title(),
common_day.title(),
common_hour))
print("\n\nThis took %s seconds." % (time.time() - start_time))
print('-' * 40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# display most commonly used start station
common_st_station = df['Start Station'].mode()[0]
# display most commonly used end station
common_end_station = df['End Station'].mode()[0]
# display most frequent combination of start station and end station trip
common_station = df.groupby(['Start Station', 'End Station']).size().sort_values(ascending=False)
idx_common_station = common_station.idxmax()
print("Within {}, the most common start station was {} whereas the most common end station was {}.\n".format(
city.title(), common_st_station, common_end_station))
print("The most used combination of start and end station was {}.\n".format(
str(idx_common_station[0] + " with " + idx_common_station[1])))
print("\n\nThis took %s seconds." % (time.time() - start_time))
print('-' * 40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# display total travel time
tt_total = df['Trip Duration'].sum()
tt_total_min = divmod(tt_total, 60)
tt_total_h = divmod(tt_total_min[0], 60)
tt_total_d = divmod(tt_total_h[0], 24)
tt_total_fm = (
"{}d {}h {}min {}sec".format(int(tt_total_d[0]), int(tt_total_d[1]), int(tt_total_h[1]), int(tt_total_min[1])))
# display mean travel time
tt_mean = df['Trip Duration'].mean()
tt_mean_min = divmod(tt_mean, 60)
tt_mean_h = divmod(tt_mean_min[0], 60)
tt_mean_fm = ("{}h {}min {}sec".format(int(tt_mean_h[0]), int(tt_mean_h[1]), int(tt_mean_min[1])))
print("Within {}, the total time that users traveled was {} whereas the mean time of one journey was {}.\n".format(
city.title(), tt_total_fm, tt_mean_fm))
print("\n\nThis took %s seconds." % (time.time() - start_time))
print('-' * 40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
user_types = df['User Type'].value_counts()
print("Users can be grouped into the following types:\n")
print(user_types.to_string())
# Display counts of gender
if 'Gender' in df:
user_gender = df['Gender'].value_counts()
print("\nUsers are grouped into these genders:\n")
print(user_gender.to_string())
else:
print("\nThere is no gender data available for {}.\n".format(city.title()))
# Display earliest, most recent, and most common year of birth
if 'Gender' in df:
earliest_dob = df['Birth Year'].min()
recent_dob = df['Birth Year'].max()
common_dob = df['Birth Year'].value_counts()
common_dob = common_dob.idxmax()
print(
"\nThe earliest date of birth of customers is {}, the most recent date is {} and the most common birth year is {}.\n".format(
int(earliest_dob), int(recent_dob), int(common_dob)))
else:
print("\nThere is no year of birth data available for {}.\n".format(city.title()))
print("\n\nThis took %s seconds." % (time.time() - start_time))
print('-' * 40)
def raw_input(df):
"""Displays 5 lines of raw input upon request."""
pd.set_option('display.max_columns', None)
raw = input('\nWould you like see some raw input data? Enter yes or no.\n')
raw_count = 5
while raw.lower() == 'yes':
print(df[:raw_count])
raw_count += 5
raw = input('\nWould you like see some more raw input data? Enter yes or no.\n')
if raw.lower() != 'yes':
break
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
raw_input(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
f27cd30f9a76a0b6f2496569e399a752af3d8a63 | eric100lin/Learn | /algorithm/Array/242.py | 799 | 3.890625 | 4 | '''
242. Valid Anagram
https://leetcode.com/problems/valid-anagram/
Given two strings s and t,
write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
'''
from typing import *
import collections
# Anagrams have same counters
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
sc = collections.Counter(s)
tc = collections.Counter(t)
return sc == tc
# Anagrams have same sorted chars
class SortSolution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s)==sorted(t)
print(Solution().isAnagram(s = "anagram", t = "nagaram"))
# True
print(Solution().isAnagram(s = "rat", t = "car"))
# False |
11ffbd2aaf6b50aa344d95d9c316829f4dfd03c1 | himani007/pygame_one | /one.py3 | 812 | 3.515625 | 4 |
import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("Hola Gameos")
x = 250
y = 450
width = 40
height = 60
vel = 5
#mainloop:
run = True
while run:
pygame.time.delay(100)#this is miniseconds!
#checking events.....
for event in pygame.event.get():
if event.type ==pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 500-width:
x += vel
if keys[pygame.K_UP] and y > vel:
y -= vel
if keys[pygame.K_DOWN] and y < 500-height:
y += vel
win.fill((0, 255, 0, 128)) #this is colour of whole screen...
#pygame.draw.rect(surface, color, rectangle_tuple, width)
pygame.draw.rect(win, (255, 0, 0),(x, y, width, height))
pygame.display.update()
pygame.quit()
|
628c2fb943e46b912711a8b8dd655b8438324d5a | morteneiby/HelloWorld | /app.py | 720 | 3.875 | 4 | #name = input("Instast dir navn? ")
#if len(name) < 3:
# print("Navn skal have mindst 3 karakterer")
#elif len(name) > 50:
# print("Navn kan max have 50 karakterer")
#else:
# print("Navn er ok")
weight = input("Din vægt? ")
x = input("(P)und eller (K)ilo ")
kilo = int(weight) / 2
pund = int(weight) * 2
if x == "P" or x == "p":
print(f"Vægt i kilo {kilo}")
elif x == "K" or x == "k":
print(f"Vægt i pund {pund}")
else:
print("Du har tastet forkert")
#print("Du vejer " + str(kilo) + " omregnet til kilo")
#age = 47
#is_new = False
#has_credit = False
#price = 1000000
#if has_credit:
# print("Put down 10% = " + str(price * 0.10 ))
#else:
# print("Put down 20% = " + str(price * 0.20))
|
41946ef911ec01f4a22831d83944ae1aff3b04c6 | GeekJamesO/Python_MakeChange | /MakeChange.py | 1,039 | 3.59375 | 4 |
# It is assumed that the MoneyArray is ordered from highest value to the lowest value floats.
def MakeChange(DesiredChange, MoneyArray):
if MoneyArray == None:
raise Exception ("Money array must not be null")
if len(MoneyArray) == 0:
raise Exception ("Money array must be populated")
rtnChange = []
runningValue = int(DesiredChange * 100)
for coin in MoneyArray:
coinValue = int(100 * coin[1])
tokens = runningValue / coinValue
rtnChange.append ( (coin[0], tokens) )
runningValue -= tokens * coinValue
return rtnChange
UsMoney = [ ('Dollar', 1), ('Half-Dollar', 0.5), ('Quarter', 0.25), ('Dime', 0.1), ('Nickel', 0.05), ('Penny', 0.01) ]
print "UsMoney", UsMoney
# MakeChange(7,None)
# MakeChange(7,[])
ExpectedResult = [ ('Dollar', 1), ('Half-Dollar', 0.5), ('Quarter', 0.25), ('Dime', 0.1), ('Nickel', 0.05), ('Penny', 0.01) ]
print "ExpectedResult", ExpectedResult
ActualResult = MakeChange( 3.87, UsMoney )
print "ExpectedResult for 3.87" , ActualResult
|
b3212c3c1b14e3c8b8ed4022148679a290e01417 | catherine7st/SoftUni-Python_Fundamentals | /problems_from_exams/(from-exams)numbers.py | 278 | 3.75 | 4 | list_numbers = list(map(int, input().split()))
average = sum(list_numbers) / len(list_numbers)
new_list = [num for num in list_numbers if num > average]
new_list.sort(reverse=True)
if len(new_list) == 0:
print("No")
else:
new_list = new_list[:5]
print(*new_list)
|
db7da2842425e47c2b40399c595d33d4f8dfe350 | Gendo90/HackerRank | /Strings/alternatingCharacters.py | 402 | 3.96875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the alternatingCharacters function below.
def alternatingCharacters(s):
count = 0
curr = s[0]
for item in s:
#flips the value
if(item==curr):
if(item=="A"):
curr="B"
else:
curr="A"
else:
count+=1
return count
|
7a4a5af4588761d31aa655eab7b24a795c5894a7 | jennarunge/exercises | /chapter-8/ex_8_1.py | 1,122 | 4.40625 | 4 | # Programming Exercise 8-1
#
# Program to extract initials from a person's name.
# This program prompts a user for his or her full name,
# Splits the name into a list of parts and extracts the first character from each,
# and displays the characters in upper case, followed by periods.
# Define the main function
def main():
# Get a full name as user input
name = input("Enter your first and last name: ")
# Split the string on spaces into a list of name parts and assign to a variable
name_s = name.split(" ")
# iterate over each name part in the list
name_s_zero = name_s[0]
name_s_zero = name_s_zero.replace(name_s_zero[0], name_s_zero[0].upper())
name_s_one = name_s[1]
name_s_one = name_s_one.replace(name_s_one[0], name_s_one[0].upper())
print(name_s_zero, name_s_one)
# display the first character ( parts[0] ) of the name part as upper case
# Call the main function.
main()
#SCRATCH/ SCRATCH/ SCRATCH
s = "Hello World"
index= s.index("World")
number = [1,2,3,4]
numbers[0] = 9
#S[6] = "p" NOT LEGAL
c= s[index:11]
|
6a285d785366cb9f33b1a9d8426f50daf99ed295 | siliconchris1973/PyPiBotter | /OuterWorld/MotorController.py | 6,003 | 3.5 | 4 | #!/usr/bin/env python3
#
# drive the motors of the robot
#
# Author: [email protected]
# Version: 0.0.1
# Date: 1st Aug. 2016
#
#
# This class is based on the CamJam EduKit 3 - Robotics / Worksheet 7 – PWM driving
# The original code alongside documentation on the hardware setup can be found on github
#
import RPi.GPIO as GPIO # Import the GPIO Library
import time
import sys
class MotorController:
# Set variables for the GPIO motor pins
PORT_MOTOR_A_FORWARDS = 10
PORT_MOTOR_A_BACKWARDS = 9
PORT_MOTOR_B_FORWARDS = 8
PORT_MOTOR_B_BACKWARDS = 7
# How many times to turn the pin on and off each second
FREQUENCY = 20
# How long the pin stays on each cycle, as a percent
DUTY_CYCLE_A = 30
DUTY_CYCLE_B = 30
# Settng the duty cycle to 0 means the motors will not turn
STOP_VALUE = 0
def MotorController(self, port_motor_a_forwards, port_motor_a_backwards,
port_motor_b_forwards, port_motor_b_backwards,
frequency, duty_cycle_a, duty_cycle_b, stop_value):
self.PORT_MOTOR_A_FORWARDS = port_motor_a_forwards
self.PORT_MOTOR_B_FORWARDS = port_motor_b_forwards
self.PORT_MOTOR_A_BACKWARDS = port_motor_a_backwards
self.PORT_MOTOR_B_BACKWARDS = port_motor_b_backwards
self.FREQUENCY = frequency
self.DUTY_CYCLE_A = duty_cycle_a
self.DUTY_CYCLE_B = duty_cycle_b
self.STOP_VALUE = stop_value
def __init__(self):
# Set the GPIO modes
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Set the GPIO Pin mode to be Output
GPIO.setup(self.PORT_MOTOR_A_FORWARDS, GPIO.OUT)
GPIO.setup(self.PORT_MOTOR_A_BACKWARDS, GPIO.OUT)
GPIO.setup(self.PORT_MOTOR_B_FORWARDS, GPIO.OUT)
GPIO.setup(self.PORT_MOTOR_B_BACKWARDS, GPIO.OUT)
# Set the GPIO to software PWM at 'Frequency' Hertz
self.pwmMotorAForwards = GPIO.PWM(self.PORT_MOTOR_A_FORWARDS, self.FREQUENCY)
self.pwmMotorABackwards = GPIO.PWM(self.PORT_MOTOR_A_BACKWARDS, self.FREQUENCY)
self.pwmMotorBForwards = GPIO.PWM(self.PORT_MOTOR_B_FORWARDS, self.FREQUENCY)
self.pwmMotorBBackwards = GPIO.PWM(self.PORT_MOTOR_B_BACKWARDS, self.FREQUENCY)
# Start the software PWM with a duty cycle of 0 (i.e. not moving)
self.pwmMotorAForwards.start(self.STOP_VALUE)
self.pwmMotorABackwards.start(self.STOP_VALUE)
self.pwmMotorBForwards.start(self.STOP_VALUE)
self.pwmMotorBBackwards.start(self.STOP_VALUE)
def __exit__(self, exc_type, exc_val, exc_tb):
# Reset GPIO settings
GPIO.cleanup()
def setFrequency(self, frequency):
self.FREQUENCY = frequency
def setDutyCycleA(self, dutyCycle):
self.DUTY_CYCLE_A = dutyCycle
def setDutyCycleB(self, dutyCycle):
self.DUTY_CYCLE_B = dutyCycle
# Turn all motors off
def stopMotors(self):
self.pwmMotorAForwards.ChangeDutyCycle(self.STOP_VALUE)
self.pwmMotorABackwards.ChangeDutyCycle(self.STOP_VALUE)
self.pwmMotorBForwards.ChangeDutyCycle(self.STOP_VALUE)
self.pwmMotorBBackwards.ChangeDutyCycle(self.STOP_VALUE)
return 'Stopping (Motors A & B off)'
# Turn motor A off
def stopMotorA(self):
self.pwmMotorAForwards.ChangeDutyCycle(self.STOP_VALUE)
self.pwmMotorABackwards.ChangeDutyCycle(self.STOP_VALUE)
return 'Motor A off'
# Turn motor B off
def stopMotorB(self):
self.pwmMotorBForwards.ChangeDutyCycle(self.STOP_VALUE)
self.pwmMotorBBackwards.ChangeDutyCycle(self.STOP_VALUE)
return 'Motor B off'
# Turn both motors forwards
def driveForwards(self):
self.pwmMotorAForwards.ChangeDutyCycle(self.DUTY_CYCLE_A)
self.pwmMotorABackwards.ChangeDutyCycle(self.STOP_VALUE)
self.pwmMotorBForwards.ChangeDutyCycle(self.DUTY_CYCLE_B)
self.pwmMotorBBackwards.ChangeDutyCycle(self.STOP_VALUE)
return 'Driving forwards (Motors A & B forward)'
# Turn both motors backwards
def driveBackwards(self):
self.pwmMotorAForwards.ChangeDutyCycle(self.STOP_VALUE)
self.pwmMotorABackwards.ChangeDutyCycle(self.DUTY_CYCLE_A)
self.pwmMotorBForwards.ChangeDutyCycle(self.STOP_VALUE)
self.pwmMotorBBackwards.ChangeDutyCycle(self.DUTY_CYCLE_B)
return 'Driving backwards (Motors A & B backward)'
# Turn left
def turnLeft(self):
self.pwmMotorAForwards.ChangeDutyCycle(self.STOP_VALUE)
self.pwmMotorABackwards.ChangeDutyCycle(self.DUTY_CYCLE_A)
self.pwmMotorBForwards.ChangeDutyCycle(self.DUTY_CYCLE_B)
self.pwmMotorBBackwards.ChangeDutyCycle(self.STOP_VALUE)
return 'Turning left (Motor A backward & B forward)'
# Turn Right
def turnRight(self):
self.pwmMotorAForwards.ChangeDutyCycle(self.DUTY_CYCLE_A)
self.pwmMotorABackwards.ChangeDutyCycle(self.STOP_VALUE)
self.pwmMotorBForwards.ChangeDutyCycle(self.STOP_VALUE)
self.pwmMotorBBackwards.ChangeDutyCycle(self.DUTY_CYCLE_B)
return 'Turning right (Motor A forward & B backward)'
def main():
if (len(sys.argv) > 1):
if (sys.argv[1] == '--demo'):
motor = MotorController()
print('Starting Demo Cycle')
status = motor.driveForwards()
print(status)
time.sleep(0.5)
status = motor.turnLeft()
print(status)
time.sleep(0.5)
status = motor.driveBackwards()
print(status)
time.sleep(0.5)
status = motor.turnRight()
print(status)
time.sleep(0.5)
else:
print('If you want to test the motor controller start the script with --demo')
else:
print('Usually this script should not be run standalone. \n'
'If you want to test the motor controller start the script with --demo')
if __name__ == '__main__':
main()
|
a21b7c8f3ec3efcea733d05754f3879b39592d79 | BillJung1024/p2_201611104 | /w5Main4.py | 404 | 4.21875 | 4 | def bmi():
height=input("height: ")
weight=input("weight: ")
print "%.1f"%height, "%.1f" % weight
bmi=weight/(height*height)
print "%.1f" %bmi
if bmi <=18.5:
print 'underweight'
elif bmi>=18.5 and bmi<=23:
print 'normalweight'
elif bmi>=23 and bmi<=25:
print 'overweight'
elif bmi>=25 and bmi<=30:
print 'obesity'
|
f6a09619d980ee0af57cbbe4bc5846141095e71b | LSSTC-DSFP/LSSTC-DSFP-Sessions | /Sessions/Session15/Day1/oop/camping/two_classes/camping.py | 1,637 | 3.59375 | 4 | import operator
class Camper:
max_name_len = 0
template = '{name:>{name_len}} paid ${paid:7.2f}'
def __init__(self, name, paid=0.0):
self.name = name
self.paid = float(paid)
if len(name) > Camper.max_name_len:
Camper.max_name_len = len(name)
def pay(self, amount):
self.paid += float(amount)
def display(self):
return Camper.template.format(
name = self.name,
name_len = self.max_name_len,
paid = self.paid,
)
class Budget:
"""
Class ``camping.Budget`` represents the budget for a camping trip.
"""
def __init__(self, *names):
self._campers = {name: Camper(name) for name in names}
def total(self):
return sum(c.paid for c in self._campers.values())
def people(self):
return sorted(self._campers)
def contribute(self, name, amount):
if name not in self._campers:
raise LookupError("Name not in budget")
self._campers[name].pay(amount)
def individual_share(self):
return self.total() / len(self._campers)
def report(self):
"""report displays names and amounts due or owed"""
share = self.individual_share()
heading_tpl = 'Total: $ {:.2f}; individual share: $ {:.2f}'
print(heading_tpl.format(self.total(), share))
print("-"* 42)
sorted_campers = sorted(self._campers.values(), key=operator.attrgetter('paid'))
for camper in sorted_campers:
balance = f'balance: $ {camper.paid - share:7.2f}'
print(camper.display(), balance, sep=', ')
|
aa0673fb0b69b10be7702378b08be9d3f3fd0f21 | isibord/DecisionTree | /Code/MostCommonModel.py | 449 | 3.609375 | 4 | import collections
class MostCommonModel(object):
"""A model that predicts the most common label from the training data."""
def __init__(self):
pass
def fit(self, x, y):
count = collections.Counter()
for label in y:
count[label] += 1
self.prediction = count.most_common(1)[0][0]
print(self.prediction)
def predict(self, x):
return [self.prediction for example in x]
|
00e05ee9d056ae35e5ef836d79f3413bded0d54f | jgerstein/intro-programming-19-20 | /day10/errorchecking.py | 319 | 4.21875 | 4 | num = ""
# while we haven't chosen a number, repeat
while num == "":
try:
# try to do something
num = int(input("Pick a number >>> "))
except ValueError:
# do something
print("Do you not know what a number is?")
# this print statement represents the rest of the turn
print(num) |
74146cf0a6faee74d08da808b22c420adb046a41 | shakthisachintha/FOSSALGO | /longest_common_subsequence/lcs.py | 954 | 3.8125 | 4 | # Recursive Algorithm For LCS
def recLcs(string1,string2):
stringx=string1+'\0'
stringy=string2+'\0'
return(lcsUtil(stringx,stringy))
def lcsUtil(stringx,stringy,i=0,j=0):
if(stringx[i]=='\0' or stringy[j]=='\0'):
return 0
if(stringx[i]==stringy[j]):
return 1+lcsUtil(stringx,stringy,i+1,j+1)
else:
return max(lcsUtil(stringx,stringy,i,j+1),lcsUtil(stringx,stringy,i+1,j))
print(recLcs("LONGEST","ONE"))
# /Recursive Algorithm For LCS
#Dynamic Programming Algorithm
def dpLcs(string1,string2):
x=len(string1)
y=len(string2)
matrix = [[0 for c in range(y+1)] for v in range(x+1)]
for i in range(1,x+1):
for j in range(1,y+1):
if string1[i-1] == string2[j-1]:
matrix[i][j] = matrix[i-1][j-1]+1
else:
matrix[i][j] = max(matrix[i-1][j] , matrix[i][j-1])
return(matrix[i][j])
print(dpLcs("LONGEST","SON"))
|
cd7510bbe34b4cf2256780ee705734be88f3a437 | sageskr/LeetCodeExercise | /problems/Q3.py | 662 | 3.5625 | 4 | #!/bin/env python
# coding: utf8
# author: Kairong
# create time: 2019-04-10
# 3. Longest Substring Without Repeating Characters
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max=0
lens = len(s)
for _j in xrange(lens):
tmp_result = []
tmp_result.append(s[_j])
for _k in xrange(_j+1,lens):
if s[_k] in tmp_result:
break
else:
tmp_result.append(s[_k])
if max < len(tmp_result):
max = len(tmp_result)
return max |
533cc79c4516259434101ebc84e6341775261c42 | RazvanBerbece/MultiLayerPerceptronFNN | /functions/activation/sigmoid.py | 339 | 3.640625 | 4 | import numpy as np
# Sigmoid function with added derivative functionality through param if true
def sigmoid(x, derivative):
if derivative == True:
"""
Return derivative of function sigmoid(x)
"""
return sigmoid(x, derivative=False) * (1 - sigmoid(x, derivative=False))
return 1 / (1 + np.exp(-x)) |
0510071f44025842a84e0482d4f57e499e217582 | MrDrDAVID/Python-practice-book | /employee.py | 361 | 3.734375 | 4 | class Employee() :
'''Class that represents an employee'''
def __init__(self, f_name, l_name, salary) :
'''Employee instance holds first and last name and salary'''
self.f_name = f_name
self.l_name = l_name
self.salary = salary
def give_raise(self, raise_amount=5000) :
self.salary += raise_amount |
4545f3fa5d837f74009766dff1e81b5f627b5a94 | aadilkhhan/Conditional-Expressions | /09_pr_04.py | 160 | 4 | 4 | a = input("Enter your username : ")
if (len(a) >= 10):
print("not have less 10 character.")
else:
print("It has less than 10 character.")
|
12461edaa2a19105f65275c381dc27b8478056ee | BBackJK/2020tech | /python/200520/13_randomChallenge.py | 1,101 | 3.53125 | 4 | # 교재 p.157 8번 문제
from random import randint
status = True
result = 0
while status:
num = randint(1, 100)
print("첫 값은 %d 입니다." %num)
s = input("산술 연산의 종류를 입력하세요. >> ")
if s != '+' and s != '-' and s != '*' and s !='/':
print("산술연산이 잘못됐습니다.")
status = False
else:
inputNum = int(input("두 번째 피연산자를 입력하세요. >> "))
if s == '+':
result = num + inputNum
print("%d %s %d = %d" %(num, s, inputNum, result))
elif s == '-':
result = num - inputNum
print("%d %s %d = %d" %(num, s, inputNum, result))
elif s == '*':
result = num * inputNum
print("%d %s %d = %d" %(num, s, inputNum, result))
elif s == '/' and inputNum != 0:
result = num / inputNum
print("%d %s %d = %d" %(num, s, inputNum, result))
else:
print("0으로 연산할 수 없습니다.")
status = False
else:
print('종료'.center(20,'*'))
|
b9f7904f3527e6295978a01f6cab8b1cc14811a2 | JairMendoza/Python | /curso 2/ej4.py | 436 | 4 | 4 | print ("Vamos a sacar la suma, resta, multiplicacion y divicion de dos numeros.")
numero1=int(input("Ingrese el primer numero a operar: "))
numero2=int(input("Ingrese el segudo numero a operar: "))
suma= numero1+numero2
resta= numero1-numero2
multiplicacion= numero1*numero2
divicion= numero1/numero2
print(f"La suma es: {suma}\nLa resta es: {resta}\nLa multiplixcacion es: {multiplicacion}\nLa divicion es: {divicion}")
input() |
9fc6d41b019af0a5063c4b0db459093878d4c39a | StepDan23/MADE_algorithms | /hw_11/a.py | 1,265 | 3.546875 | 4 | from collections import deque
def make_step(x, y, n_max):
steps = [(x + 1, y + 2), (x + 2, y + 1),
(x + 2, y - 1), (x + 1, y - 2),
(x - 1, y - 2), (x - 2, y - 1),
(x - 2, y + 1), (x - 1, y + 2)]
correct_steps = [(a, b) for (a, b) in steps
if 0 < a <= n_max and 0 < b <= n_max]
return correct_steps
def bfs(start_vert, n_max):
used = {start_vert: 0}
queue = deque([start_vert])
while queue:
vert_x, vert_y = queue.popleft()
for vert in make_step(vert_x, vert_y, n_max):
if vert not in used:
used[vert] = (vert_x, vert_y)
queue.append(vert)
return used
def recover_route(routes_dict, start, end):
route = [end]
vert = end
while vert != start:
vert = routes_dict[vert]
route.append(vert)
return route
n_max = int(input())
start = tuple(map(int, input().split()))
end = tuple(map(int, input().split()))
routes = bfs(start, n_max)
route = recover_route(routes, start, end)
print(len(route))
for vert in route[::-1]:
print(*vert, sep=' ')
# входные данныеСкопировать
# 5
# 1 1
# 3 2
# выходные данныеСкопировать
# 2
# 1 1
# 3 2
|
9600e263a027c48a61b8463a37630680dd89783c | Dakhi00/Competitve-Programming | /Qwerty keyboard.py | 404 | 4.15625 | 4 | #Qwerty Keyboard
dict1={'W':'Q','E':'W','R':'E','T':'R','Y':'T','U':'Y','I':'U','O':'I','P':'O','[':'P','S':'A','D':'S','F':'D','G':'F','H':'G','J':'H','K':'J','L':'K',';':'L','X':'Z','C':'X','V':'C','B':'V','N':'B','M':'N',',':'M','.':',','/':'.'}
print('Enter string')
string=input()
Final=""
for i in string:
if i==" ":
Final+=" "
else:
Final+=dict1[i]
print(Final)
|
69cb21596e2561712b590c79accce8cfdc9bab0c | VSVDEv/python_starter | /filesandstreams/files.py | 10,045 | 3.796875 | 4 | """Пример открытия файла для чтения"""
def read_file(fname):
"""Функция для чтения файла fname
и вывода его содержимого на экран
"""
# Открытие файла для чтения
file = open(fname, 'r')
# Вывод названия файла
print('File ' + fname + ':')
# Чтение содержимого файла построчно
for line in file:
# Вывод строки s. Перевод строки в файле сохраняется в строке, поэтому
# выводим без дополнительного перевода строки.
print(line, end='')
# Закрытие файла
file.close()
if __name__ == '__main__':
read_file('data/file.txt')
"""Пример использования функции os.path.join
для построения пути к файлу"""
# Модуль, который содержит функции для работы с путями в файловой системе
import os.path
def read_file(fname):
"""Функция для чтения файла fname
и вывода его содержимого на экран
"""
# Открытие файла для чтения
file = open(fname, 'r')
# Вывод названия файла
print('File ' + fname + ':')
# Чтение содержимого файла построчно
for line in file:
# Вывод строки s. Перевод строки в файле сохраняется в строке, поэтому
# выводим без дополнительного перевода строки.
print(line, end='')
# Закрытие файла
file.close()
if __name__ == '__main__':
# Функция os.path.join соединяет части пути в файловой системе требуемым
# для данной платформы разделителем
read_file(os.path.join('data', 'file.txt'))
"""Пример записи данных в текстовый файл"""
import os.path
text = '''Hello!
I am a text file. And I had been written with a Python script
before you opened me, so look up the docs and try to delete
me using Python, too.
'''
def write_text_to_file(filename, text):
"""Функция для записи в файл filename строки text"""
# Открытие файла для записи
f = open(filename, "w")
# Запись строки text в файл
f.write(text)
# Закрытие файла
f.close()
if __name__ == '__main__':
write_text_to_file(os.path.join('data', 'example02.txt'), text)
"""Использование оператора with для автоматического закрытия файла"""
import os.path
# Построение имени файла
filename = os.path.join('data', 'file.txt')
# Оператор with автоматически закроет файл при окончании выполнения операторов
# внутри него или возникновении исключения
with open(filename) as file:
print(file.read())
"""Пример открытия текстового файла для чтения
с указанием кодировки"""
# __file__ - это атрибут модуля, в котором хранится имя его файла
# исходного кода
with open(__file__, 'r', encoding='utf-8-sig') as file:
for number, line in enumerate(file):
print('{0}\t{1}'.format(number + 1, line), end='')
print()
"""Пример открытия файла для чтения и записи"""
import os.path
import statistics
import datetime
def calculate_stats(filename):
with open(filename, 'r+') as file:
numbers = [float(line) for line in file.readlines()
if line != '\n' and not line.lstrip().startswith('#')]
sum_ = sum(numbers)
mean = statistics.mean(numbers)
median = statistics.median(numbers)
cur_time = datetime.datetime.now()
fmt = '\n' \
'# Статистика от {time!s}\n' \
'# Сумма: {sum}\n' \
'# Медиана: {median}\n' \
'# Среднее: {mean}'
print(fmt.format(time=cur_time,
mean=mean,
median=median,
sum=sum_),
file=file)
if __name__ == '__main__':
filename = os.path.join('data', 'example05.txt')
calculate_stats(filename)
"""Пример открытия файла для дозаписи"""
import os.path
import datetime
log_file = os.path.join('data', 'ex06_log.txt')
with open(log_file, 'a') as log:
print(datetime.datetime.now(), file=log)
"""Пример перезаписи файла"""
import os.path
filename = os.path.join('data', 'example07.txt')
# Чтение файла
with open(filename, 'r') as file:
lines = file.readlines()
# Модификация данных
lines.insert(2, 'inserted line\n')
# Перезапись файла
with open(filename, 'w') as file:
file.writelines(lines)
"""Пример использования файлового объекта io.StringIO"""
import io
# Создание потока
stream = io.StringIO() # или io.StringIO('начальное значение')
# Запись данных в поток
stream.write('asdf in memory')
# Получение строки из объекта StringIO
print(stream.getvalue())
# Вывод текущей позиции
print('Current position:', stream.tell())
# Переход в начало потока
stream.seek(0)
# Запись данных в поток
stream.write('data')
# Вывод текущей позиции
print('Current position:', stream.tell())
# Чтение оставшихся данных в потоке
print(stream.read())
# Вывод текущей позиции
print('Current position:', stream.tell())
# Получение строки из объекта StringIO
print(stream.getvalue())
"""Пример использования бинарного файла"""
from array import array
import os.path
prefix = os.path.join('data', 'ex09_')
# Создание списка чисел
numbers = list(range(300, 400))
# Запись в текстовый файл
with open(prefix + 'text.txt', 'w') as txt_file:
print(numbers, file=txt_file)
# Создание массива, поддеживающего buffer protocol, из списка
numbers_array = array('i', numbers)
# Запись в бинарный файл
binary_filename = prefix + 'binary.bin'
with open(binary_filename, 'wb') as bin_file:
bin_file.write(numbers_array)
# Подготовка массива
filesize = os.path.getsize(binary_filename) # размер файла
int_len = array('i').itemsize # размер одного элемента в байтах
read_array = array('i', (0 for _ in range(filesize // int_len)))
# Чтение из бинарного файла
with open(binary_filename, 'rb') as file:
file.readinto(read_array) # чтение в массив
# Вывод массива на экран
print(read_array)
# Проверка, что считанные данные соответствуют изначальным
print(read_array.tolist() == numbers)
"""Пример использования json"""
import json
import os.path
data = [
{
'name': 'John',
'age': 20,
},
{
'name': 'Mary',
'age': 19
}
]
filename = os.path.join('data', 'example10.json')
# Сериализация
with open(filename, 'w') as file:
json.dump(data, file)
# Десериализация
with open(filename, 'r') as file:
read_data = json.load(file)
print(read_data)
"""Пример сериализации при помощи pickle"""
import os.path
import pickle
import reprlib
class Person(object):
"""Класс, описывающий человека"""
def __init__(self, name, age, sibling=None):
"""Конструктор класса.
Параметры:
name -- имя
age -- возраст
sibling -- брат или сестра
"""
self.name = name
self.age = age
self.sibling = sibling
# Декоратор reprlib.recursive_repr(fillvalue='...') отслеживает рекурсивные
# вызовы метода __repr__ и не даёт ему войти в бесконечную рекурсию,
# возвращая fillvalue вместо вызовов данного метода, которые ещё не
# завершены.
@reprlib.recursive_repr()
def __repr__(self):
"""Строковое представление объекта"""
return 'Person({name!r}, {age!r}, {sibling!r})'.format(**self.__dict__)
def write_data(filename):
"""Функция создания и записи данных"""
james = Person('James', 20)
julia = Person('Julia', 21)
james.sibling = julia # создание циклических ссылок
julia.sibling = james
# Сериализация списка объектов
with open(filename, 'wb') as file: # 'wb' -- запись бинарного файла
pickle.dump([james, julia], file)
def read_data(filename):
"""Функция чтения и вывода данных на экран"""
# Десериализация
with open(filename, 'rb') as file:
data = pickle.load(file)
# Вывод в консоль
print(data)
if __name__ == '__main__':
filename = os.path.join('data', 'example11.pkl')
write_data(filename)
read_data(filename)
|
851cc1b8f4b760e5ab78fe622d4fafd95528a847 | danielalvesleandro/520-Python-Fundamentals | /aula_2/exercicio_3.py | 578 | 4.09375 | 4 | # EXERCICIO 3:
# Dar prompt solicitando a idade do usuário
# validando e removendo caracteres inválidos
# da impressão
idade = input('Digite sua idade: ')
string_vazia = ''
caracteres_validos = '0123456789'
for letra in idade:
if letra in caracteres_validos:
string_vazia += letra
print(string_vazia)
exit()
idade = input('Digite sua idade: ')
#idade = int(idade)
caracteres_validos = '0123456789'
for letra in idade:
if letra not in caracteres_validos:
print('Você digitou errado!')
exit()
print('Você digitou corretamente')
|
7c8ec68f97c2c5476ac2c688c4c0266dc2bd0f73 | shamim-ahmed/udemy-python-masterclass | /section-12/examples/listcomp_no_side_effect.py | 518 | 4.1875 | 4 | #!/usr/bin/env python
# declare a list of numbers
numbers = list(range(1, 7))
number = 0
while True:
number = int(input("Please enter a number between 1 and 6: "))
if 1 <= number <= 6:
break
# Note that the variable used in list comprehension has the same name as that of a local variable
# However, this does not change the value of the local variable
squares = [number ** 2 for number in numbers]
idx = numbers.index(number)
result = squares[idx]
print("The square value is: {}".format(result))
|
1b8c6fb3196514f4c194cebe92e683bde899e49f | wadephillips/PrettyPandas | /prettypandas/formatters.py | 2,559 | 3.703125 | 4 | from numbers import Number, Integral
from functools import partial
import locale
import warnings
from babel import Locale, numbers
LOCALE, ENCODING = locale.getlocale()
LOCALE_OBJ = Locale(LOCALE or "en_US")
def format_number(v, number_format, prefix='', suffix=''):
"""Format a number to a string."""
if isinstance(v, Number):
return ("{{}}{{:{}}}{{}}"
.format(number_format)
.format(prefix, v, suffix))
else:
raise TypeError("Numberic type required.")
def as_percent(v, precision=2):
"""Convert number to percentage string.
Parameters:
-----------
:param v: numerical value to be converted
:param precision: int
decimal places to round to
"""
if not isinstance(precision, Integral):
raise TypeError("Precision must be an integer.")
return format_number(v, "0.{}%".format(precision))
def as_unit(v, unit, precision=2, location='suffix'):
"""Convert value to unit.
Parameters:
-----------
:param v: numerical value
:param unit: string of unit
:param precision: int
decimal places to round to
:param location:
'prefix' or 'suffix' representing where the currency symbol falls
relative to the value
"""
if not isinstance(precision, Integral):
raise TypeError("Precision must be an integer.")
if location == 'prefix':
formatter = partial(format_number, prefix=unit)
elif location == 'suffix':
formatter = partial(format_number, suffix=unit)
else:
raise ValueError("location must be either 'prefix' or 'suffix'.")
return formatter(v, "0.{}f".format(precision))
as_percent = partial(numbers.format_percent,
locale=LOCALE_OBJ)
"""Format number as percentage."""
as_currency = partial(numbers.format_currency,
currency='USD',
locale=LOCALE_OBJ)
"""Format number as currency."""
def as_money(v, precision=2, currency='$', location='prefix'):
"""[DEPRECATED] Convert value to currency.
Parameters:
-----------
:param v: numerical value
:param precision: int
decimal places to round to
:param currency: string representing currency
:param location:
'prefix' or 'suffix' representing where the currency symbol falls
relative to the value
"""
warnings.warn("Depricated in favour of `as_currency`.",
DeprecationWarning)
return as_unit(v, currency, precision=precision, location=location)
|
421366445f62c136a632ab6f66bd1da41d09daf2 | DemoshenkovGG/pythonintask | /PMIa/2014/Demoshenkov_G_G/6.py | 710 | 3.734375 | 4 |
import random
a="Ворчун"
b="Чихун"
c="Умник"
d="Соня"
e="Простак"
f="Весельчак"
g="Тихоня"
h="хочу зачёт"
gnom=random.randint(1,8)
print("Программа случайным образом отображает имя одного из семи гномов,друзей Белосжнежки(а иногда и желание автора программы(примерно с шансом 1/8))")
if gnom==1:
print(a)
elif gnom==2:
print(b)
elif gnom==3:
print(c)
elif gnom==4:
print(d)
elif gnom==5:
print(e)
elif gnom==6:
print(f)
elif gnom==7:
print(g)
elif gnom==8:
print(h)
input("Нажмите Enter для выхода")
|
24ed6298823ea0d54fdad337b55bc6b06f4af2cf | arpita-ak/APS-2020 | /Hackerrank solutions/Easy- Beautiful Triplets.py | 594 | 3.734375 | 4 | """
Beautiful Triplets:https://www.hackerrank.com/challenges/beautiful-triplets/problem
"""
import math
import os
import random
import re
import sys
def beautifulTriplets(d, arr):
sarr = set(arr)
return len([c for c in arr if c + d in sarr and c + 2 * d in sarr])
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nd = input().split()
n = int(nd[0])
d = int(nd[1])
arr = list(map(int, input().rstrip().split()))
result = beautifulTriplets(d, arr)
fptr.write(str(result) + '\n')
fptr.close()
|
a227f96b8d9722d4943136bda29f8e78ea76abe0 | muyicui/pylearn | /Py Data Analysis/3.1/3.1.3.py | 597 | 3.890625 | 4 | x = '我是一个字符串'
y = "我也是一个字符串"
z = """我还是一个字符串"""
#字符串str用单引号(' ')或双引号(" ")括起来
#使用反斜杠(\)转义特殊字符。
s = 'Yes,he doesn\'t'
#如果你不想让反斜杠发生转义,
#可以在字符串前面添加一个r,表示原始字符串
print('C:\some\name')
print('C:\\some\\name')
print(r'C:\some\name')
#反斜杠可以作为续行符,表示下一行是上一行的延续。
s = "abcd\
efg"
print(s)
#还可以使用"""..."""或者'''...'''跨越多行
s = """
Hello I am fine!
Thinks.
"""
print(s)
|
6c762444ab047e55101ffd18fd7c92241771dba3 | neiderolivo/metodos-2020 | /neiderolivo/caida_libre.py | 263 | 3.75 | 4 | print('caida libre')
yo=float(input('ingese el valor de la altura inicial:'))
g=float(input('ingrese el valor de la gravedad:'))
t=float(input('ingrese el valor del tiempo:'))
y=yo-0.5*g*t**2
print('el valor de la altura a la cual se encontara el objeto es:',y)
|
ad7f713b1be312995b1d85d507d6f26838498267 | shiyanshirani/w3s-150-questions | /12_calendar_month_year.py | 180 | 3.734375 | 4 | import calendar
month = int(input("Month = "))
year = int(input("Year = "))
print(calendar.month(year, month, l=0,w=0)) # play with l and w for gap
print(calendar.month(1999, 10)) |
f90ea9c65b69e4c6a510c579bce21d707c016c9e | laperss/nmea_navsat_driver | /scripts/positioner.py | 5,662 | 3.546875 | 4 | #! /usr/bin/python
""" Class Positioner for converting between local and global reference frames.
Author: Linnea Persson, [email protected]
This module contains a class used for converting between global (GPS)
coordinates and a user defined local coordinate system. The local
coordinate system is defined by:
1) Origin in global coordinates (latitude, longitude) in degrees
2) Direction of the x-axis, in degrees.
The class 'Positioner' uses the utm package to first convert degrees to UTM,
then convert UTM to the local system.
The module was written as a part of the fg-sim package
(https://github.com/laperss/fg-sim)
Usage:
from positioner import Positioner
ORIGIN = (37.427729, -122.357193)
HEADING = 297.9
pos = Positioner(ORIGIN, HEADING)
LAT, LON = pos.get_global_position(5, 10)
X, Y = pos.get_local_position(37.426855, -122.35790)
"""
from __future__ import print_function
import math
import utm
import numpy as np
class Positioner(object):
""" Deals with convertion between local and global positioning
relative an origin and heading. """
def __init__(self, origin=(37.427729, -122.357193), heading=297.9):
self.ORIGIN = origin
self.RUNWAY_HEADING = heading
(self.EAST_0, self.NORTH_0,
self.ZONE, self.LETTER) = utm.from_latlon(self.ORIGIN[0],
self.ORIGIN[1])
cos = math.cos(math.radians(self.RUNWAY_HEADING))
sin = math.sin(math.radians(self.RUNWAY_HEADING))
self.ROTATION = np.array([[cos, -sin],
[sin, cos]])
self.ROTATION_INV = np.linalg.inv(self.ROTATION)
def get_local_position(self, lat, lon):
"""Get the local position from origin defined at east0, north0"""
if (type(lat) == np.ndarray) or (type(lon) == np.ndarray):
d_east = []
d_north = []
for lt, ln in zip(lat, lon):
east, north, _, _ = utm.from_latlon(lt, ln)
d_east.append(east - self.EAST_0)
d_north.append(north - self.NORTH_0)
elif lat <= -80 or lat >= 84:
print("Latitude not feasible: ", lat)
return
else:
east, north, _, _ = utm.from_latlon(lat, lon)
d_east = east - self.EAST_0
d_north = north - self.NORTH_0
pos = np.array([d_east, d_north])
y, x = np.dot(self.ROTATION, pos)
return x, y
def get_global_position(self, x, y):
"""Get the global position from origin defined at (0,0)"""
pos = np.array([y, x])
d_east, d_north = np.dot(self.ROTATION_INV, pos)
east_1 = d_east + self.EAST_0
north_1 = d_north + self.NORTH_0
latitude, longitude = utm.to_latlon(
east_1, north_1, self.ZONE, self.LETTER)
return latitude, longitude
def get_relative_distance(self, lat1, lon1, lat2, lon2):
""" Calculate position from pos1 to pos2 """
east_1, north_1, _, _ = utm.from_latlon(lat1, lon1)
east_2, north_2, _, _ = utm.from_latlon(lat2, lon2)
d_east = east_2 - east_1
d_north = north_2 - north_1
pos = np.array([d_east, d_north])
deltay, deltax = np.dot(self.ROTATION, pos)
return deltax, deltay
def get_origin(self):
""" Returns origin from which the reference frame is defined. """
return self.ORIGIN
def get_runway_heading(self):
""" Returns heading from which the reference frame is defined. """
return self.RUNWAY_HEADING
def set_origin(self, origin):
""" Set the origin from which the reference frame is defined. """
self.ORIGIN = origin
def set_heading(self, heading):
""" Set the origin from which the reference frame is defined. """
self.RUNWAY_HEADING = heading
def compute_rotation_matrices(self):
""" Recompute the rotation matrices relative to the desired heading """
cos = math.cos(math.radians(self.RUNWAY_HEADING))
sin = math.sin(math.radians(self.RUNWAY_HEADING))
self.ROTATION = np.array([[cos, -sin],
[sin, cos]])
self.ROTATION_INV = np.linalg.inv(self.ROTATION)
def compute_utm_origin(self):
""" Recompute the UTM coordinate, zone and letter. """
(self.EAST_0, self.NORTH_0,
self.ZONE, self.LETTER) = utm.from_latlon(self.ORIGIN[0],
self.ORIGIN[1])
if __name__ == "__main__":
ORIGIN = (42.186702238384, -71.00457277413)
#ORIGIN = (37.427729, -122.357193)
HEADING = 199.67
poser = Positioner(ORIGIN, HEADING)
print("\nExample calculations for positioner module.")
print("- Origin: (%2.5f, %2.5f) deg" % (ORIGIN[0], ORIGIN[1]))
print("- Heading: %2.2f deg\n" % (HEADING))
print("Test cases: \n----------------")
COORD = (42.3768549, -71.0047138267)
COORD = (42.178040, -71.008968) # (1027.47771, 42.22683)
COORD = (42.178200, -71.008896) # (1008.73757, 42.16626)
x, y = poser.get_local_position(COORD[0], COORD[1])
print("Global: (%2.5f, %2.5f) deg \t->\t " % (COORD[0], COORD[1]), end='')
print("Local: (%2.5f, %2.5f) m" % (x, y))
COORD = (-200, 10)
LAT, LON = poser.get_global_position(COORD[0], COORD[1])
print("Local: (%2.5f, %2.5f) m \t->\t " % (COORD[0], COORD[1]), end='')
print("Global: (%2.10f, %2.10f) deg" % (LAT, LON))
xpos, ypos = poser.get_local_position(LAT, LON)
print("Global: (%2.5f, %2.5f) deg \t->\t " % (LAT, LON), end='')
print("Local: (%2.5f, %2.5f) m" % (xpos, ypos))
|
0e6daae2a9372f33d43ca8b30845f1875e1dbc63 | RahulTechTutorials/PythonPrograms | /Recursion/DeepCopyList.py | 1,638 | 4.375 | 4 | import copy
def deepcopy(megalist, result=[]):
if megalist == []:
pass
else:
if type(megalist[0]) != list:
result.append(megalist[0])
else:
result.append([])
deepcopy(megalist[0],result[-1])
deepcopy(megalist[1:], result)
return result
def main():
'''This program is to understand shallowcopy'''
global result
result = []
megalist = [1,2,3,[4,5]]
normalcopylist = copy.copy(megalist)
deepcopylist = copy.deepcopy(megalist)
finallist = deepcopy(megalist)
megalist[0] = 100
megalist[3][0] = 400
print('Original list is: ', megalist, ' and ID is : ',id(megalist), ' and id of Internal list is: ', id(megalist[3]))
print('Normal Copy : ', normalcopylist , ' and the ID is : ', id(normalcopylist), ' and id of Internal list is: ', id(normalcopylist[3]))
print('Deep Copy : ', deepcopylist , ' and the ID is : ', id(deepcopylist), ' and id of Internal list is: ', id(deepcopylist[3]))
print('The copied list is : ', finallist, ' and ID is : ', id(finallist), ' and id of Internal list is: ', id(finallist[3]))
print()
print ('As you can see the reference to all lists are different but the Internal list is same,i updated below values megalist[0] = 100 and megalist[3][0] = 400. While the first value in copied list doesnt get updated, the changes to internal list gets reflected in copied lists. This is shallow copy; However in Deep copy, if you see the below two rows, all references are different. The change to values to all are not visible')
if __name__ == '__main__':
main()
|
cef9e22b1136b08c6917252bf628e6b9f8278d46 | harryd13/Arrays-in-python | /python_arrays/quicksort.py | 503 | 3.78125 | 4 | def partition(arr, l,r):
i = l-1
j = l
while j < r:
if (arr[j] < arr[r-1]):
i += 1
arr[i], arr[j] = arr[j], arr[i]
else:
pass
j+=1
arr[i+1], arr[r-1] = arr[r-1], arr[i+1]
return i+1
arr = [1,3,4,6,7,2]
print(partition(arr,0,6))
def quicksort(arr,l,r):
if(l<r):
piv = partition(arr,l,r)
quicksort(arr,l,piv-1)
quicksort(arr,piv+1,r)
quicksort(arr,0,6)
print(arr) |
fa4e4b254c3fd216e5f86636ad615d59822d84af | devopsvj/PythonAndMe | /oops/constructors.py | 276 | 3.640625 | 4 | class student():
def __init__(self,v1,v2):
self.rollno=v1
self.name=v2
def display(self):
print "Roll No : ",self.rollno
print "Name : ",self.name
obj1=student(100,"Vibaashini")
obj2=student(101,"Sundar")
obj1.display()
obj2.display()
|
2ec9a5f16dd64baef383e7cf5bda25255bdf4c5b | ali-3fr/C.K | /2_1/average_1_N.py | 272 | 4.0625 | 4 | # -*- coding: utf-8 -*-
def average(N):
sum=0
for i in range(0,N+1):
sum+=i
return sum/N
N = input(u'Введите натуральное число N:')
print 'среднее значение целых чисел i=1,2,…,N : '+ str(average(N))
|
ab56827d3c72488066cc20bc422f150b520ae975 | elodeepxj/PythonFirstDemo | /numpyEX/NumpyEx3.py | 836 | 3.765625 | 4 | # -*- coding:utf-8 -*-
#数组的分割
import numpy as np
# x = np.arange(3)
# y = x+3
# z = y+3
# a = np.array([x,y,z])
a = np.arange(9).reshape(3,3)
print a
print "-----------水平分割-----------"
ha = np.hsplit(a,3)#水平分割,对数组a进行水平分割,分割成3份
print ha
sha = np.split(a,3,axis=1) #效果等同水平分割
print sha
print "-----------垂直分割-----------"
va = np.vsplit(a,3)# 垂直分割
print va
sva = np.split(a,3,axis=0) #效果等同垂直分割 axis=0或者不写
print sva
print "-----------深度分割-----------"
b = np.arange(27).reshape(3,3,3)
print b
db = np.dsplit(b,3)
print db
sdb = np.split(b,3,axis=2) #效果等同深度分割 axis=2
print sdb
x = np.arange(0,8).reshape(4,2)
print x
print x.T# 效果等同transpose函数
print x.tolist()# 把数组转换成集合 |
9dcd1a62e23d6982d476d8ca7227a1e82a9e4cce | Jacobb200/ComputerScience3 | /dog.py | 1,422 | 3.890625 | 4 | """Assignment4 04 Jacob B."""
class dog:
# Class Constants
POPULATION = 0
DEFAULT_AGE = -1
def __init__(self, names="No Name", age=-1, breed="No breed"):
"""Initializes instance variables"""
self._name = names
self._age = age
self._breed = breed
dog.POPULATION += 1
# Sanity check for age
try:
self.age = self._age
except ValueError:
self._age = dog.DEFAULT_AGE
@property
def name(self):
"""Returns the value in self._name"""
return self._name
@name.setter
def name(self, dog_name):
"""Sets value in sel._name"""
self._name = dog_name
@property
def age(self):
"""Returns value in self._age"""
return self._age
@age.setter
def age(self, new_age):
"""Checks for age to be greater than 0, if not raise ValueError"""
if new_age <= 0:
raise ValueError
self._age = new_age
@property
def breed(self):
"""Returns Value in self._breed"""
return self._breed
@breed.setter
def breed(self, new_breed):
"""Sets value in self._breed"""
self._breed = new_breed
def print_info(self):
"""Prints all the info about the dog"""
print(f"Dog Name: {self._name}")
print(f"Dog Age: {self._age}")
print(f"Dog Breed: {self._breed}\n")
|
d5c22a994eec6417eb6e9bb72df26bf2642aa8ed | antonmeosh/Learning | /Glava_6_ Slovari.py | 756 | 3.640625 | 4 | alien_0 = {
'color': 'green',
'points': 5,
'x_position': 0,
'y_position': 25,
}
new_points = alien_0['points']
#print(f"You just earned {new_points} points!")
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}. ")
#
alien_0['speed'] = 'medium'
print(f"Original position: {alien_0['x_position']}")
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"New position: {alien_0['x_position']}")
print(alien_0)
del alien_0['points']
print(alien_0)
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)
|
d1752fcf13bbe040f1cc41ffd9a29715d78803b3 | yjiao1213/python-leetcode-offer | /剑指offer66题_pyhton实现/25_MergeSortedLists.py | 1,034 | 3.8125 | 4 | # -*- coding:utf-8 -*-
'''
合并两个排序链表
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def MergeSortedList(self, head1, head2):
if not head1 and not head2:
return None
if not head1:
return head2
if not head2:
return head1
if head1.val <= head2.val:
res = head1
head1 = head1.next
else:
res = head2
head2 = head2.next
pnode = res
while head1 or head2:
if not head1:
pnode.next = head2
break
if not head2:
pnode.next = head1
break
if head1.val <= head2.val:
pnode.next = head1
head1 = head1.next
else:
pnode.next = head2
head2 = head2.next
pnode = pnode.next
return res
|
e190caff29304175cd6d6fefef26263ad3bf7ba6 | erikaklein/algoritmo---programas-em-Python | /4Funções.py | 923 | 4.09375 | 4 | def LerNumero():
a=int(input("Digite um número inteiro: "))
return(a)
def soma (a,b,c):
return (a+b+c)
def media (a,b,c):
return(soma(a,b,c)/3)
def maior (a,b,c):
if a>b and a>c:
M=a
elif b>a and b>c:
M=b
elif c>a and c>b:
M=c
return (M)
def menor (a,b,c):
if a<b and a<c:
M=a
elif b<a and b<c:
M=b
elif c<a and c<b:
M=c
return (M)
opcao=int(input("Selecione uma das opções = Soma digite [1] - Menor [2] - Maior[3] - Media [4]"))
n1=LerNumero()
n2=LerNumero()
n3=LerNumero()
if opcao==1:
x=soma(n1,n2,n3)
print ("A soma dos três números é: ",x)
if opcao==2:
x=media(n1,n2,n3)
print ("A média é: ",x)
if opcao==3:
x=maior(n1,n2,n3)
print ("O maior número é: ",x)
if opcao==4:
x=menor(n1,n2,n3)
print ("O menor número é: ",x)
|
11fab6f03f9716d955b16e22c3f3d46a2f657a76 | ColdSpike/Leetcode | /widest-vertical-area-between-two-points-containing-no-points.py | 974 | 3.828125 | 4 | '''
Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area.
A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.
Note that points on the edge of a vertical area are not considered included in the area.
Example 1:
Input: points = [[8,7],[9,9],[7,4],[9,7]]
Output: 1
Explanation: Both the red and the blue area are optimal.
Example 2:
Input: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]
Output: 3
'''
class Solution:
def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
x_points = list(set([x[0] for x in points]))
x_points.sort()
max_gap = 0
for i in range(len(x_points) - 2):
if x_points[i+1] - x_points[i] > max_gap:
max_gap = x_points[i+1] - x_points[i]
return max_gap
|
8ba0e1e08298feaa7e9ebc6f893be1d0491405c6 | hopaz/LeetCode | /Easy 303. Range Sum Query - Immutable.py | 1,117 | 3.71875 | 4 | from typing import List
class NumArray:
def __init__(self, nums: List[int]):
if len(nums) == 0:
# ["NumArray","sumRange","sumRange","sumRange"]
# [[[]]]
self.nums = None
elif len(nums) == 1:
# ["NumArray","sumRange"]
# [[[-1]],[0,0]]
self.nums = nums
else:
self.cursor = nums[1]
self.nums = nums
for i in range(len(self.nums)):
if i == 0:
self.nums[i] = self.nums[0]
elif i == len(self.nums) - 1:
self.nums[i] += self.nums[i - 1]
else:
self.cursor = self.nums[i + 1]
self.nums[i] += self.nums[i - 1]
def sumRange(self, i: int, j: int) -> int:
if self.nums == None:
return None
if i==0:
return self.nums[j]
else:
return self.nums[j] - self.nums[i-1]
# Your NumArray object will be instantiated and called as such:
nums = [-1]
obj = NumArray(nums)
i = 0
j = 0
param_1 = obj.sumRange(i,j) |
62cd24165dc792b85298787d406e9d26465d532a | kvraiden/GUVI | /camel.py | 149 | 3.546875 | 4 | import camelcase
x = camelcase.CamelCase()
a = "hello there general kenobi, this is a test to check camelcase is working or not."
print(x.hump(a)) |
53aa4d4d2ef8cd323e48f1aab335aaceee9935d9 | captain-yun/algorithm-playground | /programmers/citations.py | 1,176 | 3.5 | 4 | from functools import reduce
# def solution(citations):
# answer = 0
# citations.sort()
# n = len(citations)
# # size
# # 1. 우선 정렬한다
# # 2. 정렬된 원소 중 하나씩 타겟으로 하여 다음을 반복한다.
# # 2-1. target = 1 ~ 10000
#
# # size.sort()
# h = 0
# for h in range(n):
# if len(list(filter(lambda x: x >= h, citations))) >= h and len(list(filter(lambda x: x <= h, citations))) <= h:
# if answer <= h:
# answer = h
# print(answer)
# if citations[0] >= n:
# answer = n
# return answer
#
def solution(citations):
answer = 0
h_indexes = list(set(citations))
h_indexes.sort()
h_indexes.reverse()
for h in h_indexes:
# if len(list(filter(lambda x: x >= h, citations))) >= h and reduce(lambda x, y: x+y, (list(filter(lambda x: x < h, citations)))) <= h:
# Using list comprehension
if len([x for x in citations if x >= h]) >= h and reduce(lambda x, y: x + y,
[x for x in citations if x < h]) <= h:
return h
return answer |
f1723938bd43c84bdc86c3a0185a67bb372a649b | bithu30/myRepo | /Machine Learning A-Z/Part 1 - Data Preprocessing/data_pre_proc.py | 902 | 3.703125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing data
df = pd.read_csv('Data.csv')
X = df.iloc[:,:-1].values
y = df.iloc[:,3].values
#print(X)
#Taking Care of missing data, done using Imputer class
#from sklearn.preprocessing
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values='NaN',strategy="mean",axis=0)
imputer = imputer.fit(X[:,1:3]) #3 because the upper-bound is always excluded in python
X[:,1:3] = imputer.transform(X[:,1:3])
#print(X)
#Taking care of categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelEncoder_X = LabelEncoder()
X[:,0] = labelEncoder_X.fit_transform(X[:,0])
#print(X)
#Creating Dummy variables
oneHotEncoder = OneHotEncoder(categorical_features=[0])
X=oneHotEncoder.fit_transform(X).toarray()
#print(X)
labelEncoder_y = LabelEncoder()
y = labelEncoder_y.fit_transform(y)
print(y) |
c2ed019cd1fc5f0a2d3918018f34f9cc6b6ad882 | ishika161/githubcampus_geekcoders | /Problem Statement 1.py | 1,205 | 3.703125 | 4 | N=int(input())
P=list()
for i in range(N):
name=input()
P.append(name)
noOfEvents=int(input())
M=list()
#User will input integer for particular query evaluation ie 1 for SERVE, 2 for FRIEND X Y, 3 for VIP X
def finalQueue(N,P,M,X):
if(M==1):
print(SERVE(P))
elif(M==2):
print(FriendXY(P))
elif(M==3):
print(VIPX(P))
else:
print("Wrong choice entered")
def SERVE(P):
P=P[1:]
return P
def FriendXY(P):
l=len(P)
y=input()
x=input()
ind=-1
for i in range(l):
if(y==P[i]):
index=i
break
for i in range(l):
if(x==P[i]):
ind=i
break
if(index>=0 and ind<0):
P.append("9")
for i in range(index+1,l):
P[i+1]=P[i]
P[index+1]=x
elif(index<0 and ind>=0):
for i in range(ind,l):
P[i]=P[i+1]
P=P[:l-2]
return P
def VIPX(P):
l=len(P)
x=input()
P.insert(0,x)
return P
for i in range(noOfEvents):
M=int(input("1 to Serve, 2 to Friend, 3 for Vip"))
finalQueue(N,P,M,noOfEvents)
|
cb70acb1cdac54678e6342abba3d3467f87734ee | haveano/codeacademy-python_v1 | /11_Introduction to Classes/02_Classes/09_Inheritance.py | 1,741 | 4.875 | 5 | """
Inheritance
One of the benefits of classes is that we can create more complicated classes that inherit variables or methods from their parent classes. This saves us time and helps us build more complicated objects, since these child classes can also include additional variables or methods.
We define a "child" class that inherits all of the variables and functions from its "parent" class like so:
class ChildClass(ParentClass):
# new variables and functions go here
Normally we use object as the parent class because it is the most basic type of class, but by specifying a different class, we can inherit more complicated functionality.
Instructions
Create a class ElectricCar that inherits from Car. Give your new class an __init__() method of that includes a "battery_type" member variable in addition to the model, color and mpg.
Then, create an electric car named "my_car" with a "molten salt" battery_type. Supply values of your choice for the other three inputs (model, color and mpg).
"""
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %d MPG." % (self.color, self.model, self.mpg)
def drive_car(self):
self.condition="used"
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type=battery_type
my_car = ElectricCar("BMW", "black", 200, "molten salt")
print my_car.condition
print my_car.model
print my_car.color
print my_car.mpg
print my_car.condition
my_car.drive_car()
print my_car.condition
|
7c37487910f4d3b331e99b88c5125c718ae8d2a6 | mingxoxo/Algorithm | /baekjoon/5639.py | 1,309 | 3.6875 | 4 | # 이진 검색 트리
# 22.10.25
# https://www.acmicpc.net/problem/5639
# https://www.acmicpc.net/board/view/81443
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)
def binary_search(preorder):
root = preorder[0]
left, right = 1, len(preorder) - 1
result = 1
while left <= right:
mid = (left + right) // 2
if preorder[mid] < root:
left = mid + 1
else:
result = mid
right = mid - 1
return result
def postorder(preorder):
if not preorder:
return
i = binary_search(preorder)
postorder(preorder[1:i])
postorder(preorder[i:])
print(preorder[0])
preorder = []
try:
while True:
key = int(input())
preorder.append(key)
except:
pass
postorder(preorder)
# 시간초과 코드
# import sys
# input = sys.stdin.readline
# sys.setrecursionlimit(100000)
# def postorder(preorder):
# if not preorder:
# return
# root = preorder[0]
# i = 1
# while i < len(preorder) and preorder[i] < root:
# i += 1
# postorder(preorder[1:i])
# postorder(preorder[i:])
# print(root)
# preorder = []
# try:
# while True:
# key = int(input())
# preorder.append(key)
# except:
# pass
# postorder(preorder)
|
e0bc1e698dcb426382ff8de43df882fb5085a9de | TehWeifu/CoffeeMachine | /Problems/snake_case/task.py | 180 | 4.34375 | 4 | string = input()
result = ""
for char in string:
if char == char.upper():
result += '_'
result += char.lower()
else:
result += char
print(result)
|
b1c97bcb5e5d11fae25bb2d3698d1a53d25cc627 | jeongnara/Programming-Python- | /module, pakage/baseball.py | 340 | 3.71875 | 4 | answer = make_answer()
#무한반복
while True:
# 숫자 묻자
guess = input("뭘까?")
# strike, ball 판정하자
strike, ball = check(guess, answer)
# 출력하자
print(f'{guess}\tstrike: {strike}, ball: {ball}')
# 정답 == 숫자, 끝내자
if answer == guess:
print('정답입니다.')
break |
73222049b0a598259bab10633bb2cf8bdacc4fab | dekapaan/python-add-two-numbers | /main.py | 1,070 | 3.90625 | 4 | from tkinter import *
root = Tk()
root.title("Adding Two Numbers")
lb1 = Label(root, text="Please enter first number")
lb1.grid(column=1, row=1)
entry1 = Entry(root)
entry1.grid(column=2, row=1)
lb2 = Label(root, text="Please enter second number")
lb2.grid(column=1, row=2)
entry2 = Entry(root)
entry2.grid(column=2, row=2)
lb3 = Label(root, text="Your answer")
lb3.grid(column=1, row=3)
result = Entry(root, state="readonly")
result.grid(column=2, row=3)
def add_2_numbers():
total = sum(int(i.get()) for i in (entry1, entry2))
result.config(state="normal")
result.insert(0, total)
result.config(state="readonly")
def delete():
entry1.delete(0, 'end')
entry2.delete(0, 'end')
result.config(state="normal")
result.delete(0, END)
result.config(state="readonly")
add = Button(root, text="Add", width=15, command=add_2_numbers).grid(column=1, row=4)
clear = Button(root, text="Clear", width=15, command=delete).grid(column=2, row=4)
quit = Button(root, text="Exit", width=15, command="exit").grid(column=3, row=4)
root.mainloop()
|
43ffef6e59099c8417a6176a467d8080d750c9c3 | GuileStr/proyectos-py | /Animadoras.py | 467 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 10:08:28 2020
@author: palar
"""
an_letters="aefhilnorsxAEFHILNORSX"
word = input("Te aiuro a echar porras: ")
times = int(input("¿Cuantas veces lo quieres gritar? "))
var=0
while var<len(word):
char= word[var]
if char in an_letters:
print("Give me an: ",char,"!!")
else:
print("Give me a: "+char+"!!")
var+=1
print("¿Y que dice? uwu")
for i in range(times):
print(word+"!!!") |
6b80a53c8b0e01da63c4cc0428e03317929c826a | jocoder22/PythonDataScience | /DataFrameManipulation/AppendSeries.py | 2,145 | 3.640625 | 4 | ############ appending series
import pandas as pd
def print2(*args):
for arg in args:
print(arg, end='\n\n')
sp = {"sep":"\n\n", "end":"\n\n"}
# Load 'sales-jan-2015.csv' into a DataFrame: jan
jan = pd.read_csv('sales-jan-2015.csv', parse_dates=True, index_col='Date')
# Load 'sales-feb-2015.csv' into a DataFrame: feb
feb = pd.read_csv('sales-feb-2015.csv', parse_dates=True, index_col='Date')
# Load 'sales-mar-2015.csv' into a DataFrame: mar
mar = pd.read_csv('sales-mar-2015.csv', parse_dates=True, index_col='Date')
# Extract the 'Units' column from jan: jan_units
jan_units = jan['Units']
# Extract the 'Units' column from feb: feb_units
feb_units = feb['Units']
# Extract the 'Units' column from mar: mar_units
mar_units = mar['Units']
# Append feb_units and then mar_units to jan_units: quarter1
quarter1 = jan_units.append(feb_units).append(mar_units)
# Print the first slice from quarter1
print(quarter1.loc['jan 27, 2015':'feb 2, 2015'], **sp)
# Print the second slice from quarter1
print(quarter1.loc['feb 26, 2015':'mar 7, 2015'], **sp)
# Compute & print total sales in quarter1
print(quarter1.sum(), **sp)
# Initialize empty list: units
units = []
# Build the list of Series
for month in [jan, feb, mar]:
units.append(month['Units'])
# Concatenate the list: quarter1
quarter1 = pd.concat(units, axis='rows')
quarter2 = pd.concat([jan['Units'], feb['Units'], mar['Units']], axis='rows')
# Print slices from quarter1
print(quarter1.loc['jan 27, 2015':'feb 2, 2015'], **sp)
print(quarter1.loc['feb 26, 2015':'mar 7, 2015'], **sp)
print((quarter1 == quarter2).all())
medals = []
for medal in medal_types:
# Create the file name: file_name
file_name = "%s_top5.csv" % medal
# Create list of column names: columns
columns = ['Country', medal]
# Read file_name into a DataFrame: df
medal_df = pd.read_csv(file_name, header=0,
index_col='Country', names=columns)
# Append medal_df to medals
medals.append(medal_df)
# Concatenate medals horizontally: medals
medals = pd.concat(medals, axis='columns')
# Print medals
print(medals, **sp)
|
1d0e7850dcae154598f35ca4682960070b86db34 | hyo-eun-kim/algorithm-study | /ch09/saeyoon/ch9_6_saeyoon.py | 3,562 | 4.0625 | 4 | """
## 9-6. 원형 큐 디자인
원형 큐를 디자인하라.
MyCircularQueue(k): Constructor, set the size of the queue to be k.
Front: Get the front item from the queue. If the queue is empty, return -1.
Rear: Get the last item from the queue. If the queue is empty, return -1.
enQueue(value): Insert an element into the circular queue. Return true if the operation is successful.
deQueue(): Delete an element from the circular queue. Return true if the operation is successful.
isEmpty(): Checks whether the circular queue is empty or not.
isFull(): Checks whether the circular queue is full or not.
"""
from typing import *
class MyCircularQueue:
def __init__(self, k: int):
self.q = [None] * k
self.max = k
self.size = self.front = self.rear = 0
def enQueue(self, value: int) -> bool:
if self.isFull():
return False
self.rear = (self.rear + 1) % self.max
self.q[self.rear] = value
self.size += 1
return True
def deQueue(self) -> bool:
if self.isEmpty():
return False
self.front = (self.front + 1) % self.max
self.size -= 1
return True
def Front(self) -> int:
if self.isEmpty():
return -1
return self.q[(self.front + 1) % self.max]
def Rear(self) -> int:
if self.isEmpty():
return -1
return self.q[(self.rear) % self.max]
def isEmpty(self) -> bool:
return self.size == 0
def isFull(self) -> bool:
return self.size == self.max
class MyCircularQueue2:
# size 변수 없이 구현
# 실제로 front 변수는 첫번째 원소의 이전을 가리키며
# 환형 큐는 꽉 차있는지 확인을 위해 최대 원소 수보다 하나 큰 크기의 큐를 가짐
def __init__(self, k: int):
self.q = [None] * (k+1)
self.max = k+1
self.front = self.rear = 0
def enQueue(self, value: int) -> bool:
if self.isFull():
return False
self.rear = (self.rear + 1) % self.max
self.q[self.rear] = value
return True
def deQueue(self) -> bool:
if self.isEmpty():
return False
self.front = (self.front + 1) % self.max
return True
def Front(self) -> int:
if self.isEmpty():
return -1
return self.q[(self.front + 1) % self.max]
def Rear(self) -> int:
if self.isEmpty():
return -1
return self.q[(self.rear) % self.max]
def isEmpty(self) -> bool:
return self.front == self.rear
def isFull(self) -> bool:
return self.front == (self.rear + 1) % self.max
if __name__ == '__main__':
cq = MyCircularQueue(3)
print(cq.enQueue(1)) # return True
print(cq.enQueue(2)) # return True
print(cq.enQueue(3)) # return True
print(cq.enQueue(4)) # return False, the queue is full
print(cq.Rear()) # return 3
print(cq.isFull()) # return True
print(cq.deQueue()) # return True
print(cq.enQueue(4)) # return True
print(cq.Rear()) # return 4
print(cq.Front()) # return 2
cq2 = MyCircularQueue(3)
print(cq2.enQueue(1)) # return True
print(cq2.enQueue(2)) # return True
print(cq2.enQueue(3)) # return True
print(cq2.enQueue(4)) # return False, the queue is full
print(cq2.Rear()) # return 3
print(cq2.isFull()) # return True
print(cq2.deQueue()) # return True
print(cq2.enQueue(4)) # return True
print(cq2.Rear()) # return 4
print(cq2.Front()) # return 2 |
1921981eb5629096e6dfb4ee69a5d2f49b39ff84 | deayqf/Online-Compiler | /python.py | 901 | 3.796875 | 4 | class Node:
def __init__( self ):
self.val = None
self.next = None
def setVal( self, val ):
self.val = val
def initNext( self ):
self.next = Node()
def moveToNext( self ):
return self.next
def hasNext( self ):
if self.next:
return True
else:
return False
def printVal( self ):
print( self.val )
class List:
def __init__( self, num ):
self.head = Node()
self.length = num
temp = self.head
for i in range( num ):
temp.setVal( i )
temp.initNext()
temp = temp.moveToNext()
def printList( self ):
print( 'List length = ' + str( self.length ) )
temp = self.head
while temp.hasNext():
temp.printVal()
temp = temp.moveToNext()
list = List( 10 )
list.printList()
|
11bd930b3ada385f5efc2abc415cbddcfab444a8 | OanaApostol/ITOD | /tests/string_operations_unittests/test_lowercase.py | 1,040 | 4.1875 | 4 | """This module aims to test the lowercase method."""
import unittest
class Lower(unittest.TestCase):
def test_lower_existence(self):
self.Lower = Lower("aaaa")
def test_lowercase_null_values(self):
with self.assertRaises(TypeError):
Lower(None)
def test_lowercase_empty_values(self):
with self.assertRaises(TypeError):
Lower("")
def test_lowercase_null(self):
with self.assertRaises(TypeError):
Lower("!23~")
def test_lowercase_lower_value(self):
text = "aaaa"
actual = Lower(text)
expected = "aaaa"
self.assertEqual(actual, expected)
def test_lowercase_lower_value(self):
text = "AAAA"
actual = Lower(text)
expected = "aaaa"
self.assertEqual(actual, expected)
def test_lowercase_lower_value(self):
text = "1anDv"
actual = Lower(text)
expected = "1andv"
self.assertEqual(actual, expected)
if __name__ == '__main__':
unittest.main()
|
36b41286f939161e14c89631e7aaae8a9cee3312 | XiaoLing941212/Summer-Leet-Code | /7.16 - BF(985), DFS(988), Recursive(894)/894. All Possible Full Binary Trees.py | 1,415 | 3.9375 | 4 | '''
A full binary tree is a binary tree where each node has exactly 0 or 2 children.
Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree.
Each node of each tree in the answer must have node.val = 0.
You may return the final list of trees in any order.
Example 1:
Input: 7
Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
'''
#Recursive:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.memo = {}
def allPossibleFBT(self, N: int) -> List[TreeNode]:
if N in self.memo:
return self.memo[N]
if N == 0:
return []
if N == 1:
return [TreeNode(0)]
res = []
for i in range(1, N):
left, right = self.allPossibleFBT(i), self.allPossibleFBT(N-1-i)
for l in left:
for r in right:
root = TreeNode(0)
root.left = l
root.right = r
res.append(root)
self.memo[N] = res
return self.memo[N]
|
9a2201ff64e1814d8f57e3e3debc0031d33cfe9d | andrewyen64/letsbrewcode-python | /4-Bool-ifElse-Ternary/notes.py | 905 | 3.921875 | 4 | # Write a function that returns true if number passed in is even
def is_even(num):
return num % 2 == 0
def is_qualified(age, state):
return age >= 18 and state == 'CA'
print(is_even(99))
print(is_even(100))
print(is_qualified(17, 'CA'))
# ===========================
# if condition:
# stmt1
# stmt2
# elif: (<- else if)
# stmt3
# stmt4
# else:
# stmt5
# ====== FizzBuzz ======
# If number is divisible by:
# 3 -> Fizz
# 5 -> Buzz
# 3 and 5 -> FizzBuzz
def fizzbuzz(num):
print(num, '-> ', end='')
if num % 5 == 0 and num % 3 == 0:
print('FizzBuzz')
elif num % 3 == 0:
print('Fizz')
elif num % 5 == 0:
print('Buzz')
else:
print(num)
fizzbuzz(10)
# =================================
def starts_with_vowel(name):
return name[0] in 'AEIOUaeiou'
print(starts_with_vowel('Adam'))
print(starts_with_vowel('Kate'))
|
d8a4adad128a23afbd4c207c50e2058ce99ad259 | melodist/CodingPractice | /src/LeetCode/Koko Eating Bananas.py | 1,113 | 3.6875 | 4 | """
https://leetcode.com/problems/koko-eating-bananas
Using binary search
"""
#1. My Solution (591ms)
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
def calculcateSpeed(piles, speed):
hours = 0
for k in piles:
q, r = divmod(k, speed)
hours += q if r == 0 else q + 1
return hours
left = 1
right = max(piles)
while left <= right:
mid = int((left + right) / 2)
if calculcateSpeed(piles, mid) <= h:
right = mid - 1
else:
left = mid + 1
return left
#2. Other Solution (372ms)
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
def canFinishEating(k):
res=0
for p in piles:
res += ceil(p/k)
return res <= h
l, r = 1, max(piles)
while l <= r:
mid = (l+r)//2
if canFinishEating(mid):
r = mid-1
else:
l = mid+1
return l
|
a903a6283fc7b0b91ece85c6f68ebe66170c140f | sugia/leetcode | /Repeated Substring Pattern.py | 1,103 | 4 | 4 | '''
Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.
Example 2:
Input: "aba"
Output: False
Example 3:
Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
'''
class Solution(object):
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
for length in xrange(1, len(s)):
if len(s) % length != 0:
continue
box = set()
for start in xrange(0, len(s) - length + 1, length):
# print start, start+length, s[start:start+length]
token = s[start:start+length]
box.add(token)
if len(box) == 1:
return True
return False
|
3b5f907997c5f2b2283eead4e73b102db22d99a8 | darksacred/Python_L2 | /L_2_2.py | 141 | 3.515625 | 4 | el = input("Введите значения: ").split()
for i in range(0, len(el)-1, 2):
el[i], el[i+1] = el[i+1], el[i]
print(el)
|
2e14630ea49373e6e312b0108292a3417b477055 | mickeyouyou/Path_Plan | /A_Star/A_Star.py | 8,459 | 3.859375 | 4 | """
A* 寻路算法
"""
class Array2D:
def __init__(self, w, h, mapdata=[]):
self.w = w
self.h = h
if mapdata:
self.data = mapdata
else:
self.data = [[0 for y in range(h)] for x in range(w)] # CAUTION!!! data列表包含w个子列表,每个子列表含h个元素
def showArray2D(self):
for y in range(self.h):
for x in range(self.w):
print(self.data[x][y], end=' ')
print("")
def __getitem__(self, item):
return self.data[item]
class Point:
"""
表示一个点
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if self.x == other.x and self.y == other.y:
return True
return False
def __str__(self):
# return "x:"+str(self.x)+",y:"+str(self.y)
return '(x:{}, y:{})'.format(self.x, self.y)
class AStar:
class Node: # 描述AStar算法中的节点数据
def __init__(self, point, endPoint, g=0):
self.point = point # 自己的坐标
self.father = None # 父节点
self.g = g # g值,g值在用到的时候会重新算
self.h = (abs(endPoint.x - point.x) + abs(endPoint.y - point.y)) * 10 # 计算h值
def __init__(self, map2d, startPoint, endPoint, passTag=0):
"""
构造AStar算法的启动条件
:param map2d: Array2D类型的寻路数组
:param startPoint: Point类型的寻路起点
:param endPoint: Point类型的寻路终点
:param passTag: int类型的可行走标记(若地图数据!=passTag即为障碍)
"""
# 开启表
self.openList = []
# 关闭表
self.closeList = []
# 寻路地图
self.map2d = map2d
# 起点终点
self.startPoint = startPoint
self.endPoint = endPoint
# 可行走标记
self.passTag = passTag
def getMinNode(self):
"""
获得openlist中F值最小的节点
:return: Node
"""
currentNode = self.openList[0]
for node in self.openList:
if node.g + node.h < currentNode.g + currentNode.h:
currentNode = node
return currentNode
def pointInCloseList(self, point):
for node in self.closeList:
if node.point == point:
return True
return False
def pointInOpenList(self, point):
for node in self.openList:
if node.point == point:
return node
return None
def endPointInCloseList(self):
for node in self.openList:
if node.point == self.endPoint:
return node
return None
def searchNear(self, minF, offsetX, offsetY):
"""
搜索节点周围的点, 更新openlist, 重新计算G值、设置father(如有需要)
:param minF:
:param offsetX:
:param offsetY:
:return:
"""
# 越界检测
if minF.point.x + offsetX < 0 or minF.point.x + offsetX > self.map2d.w - 1 or minF.point.y + offsetY < 0 or minF.point.y + offsetY > self.map2d.h - 1:
return
# 如果是障碍,就忽略
if self.map2d[minF.point.x + offsetX][minF.point.y + offsetY] != self.passTag:
return
# 如果在关闭表中,就忽略
if self.pointInCloseList(Point(minF.point.x + offsetX, minF.point.y + offsetY)):
return
# 设置单位花费
if offsetX == 0 or offsetY == 0:
step = 10
else:
step = 14
# 如果不在openList中,就把它加入openlist
currentNode = self.pointInOpenList(Point(minF.point.x + offsetX, minF.point.y + offsetY))
if not currentNode:
currentNode = AStar.Node(Point(minF.point.x + offsetX, minF.point.y + offsetY), self.endPoint,
g=minF.g + step)
currentNode.father = minF
self.openList.append(currentNode)
return
# 如果在openList中,判断minF到当前点的G是否更小
if minF.g + step < currentNode.g: # 如果更小,就重新计算g值,并且改变father
currentNode.g = minF.g + step
currentNode.father = minF
def setNearOnce(self, x, y):
"""
将障碍物周围节点区域置位不可行
:param x: 障碍物节点x坐标
:param y: 障碍物节点坐标
:return: None, 按引用修改类对象map2d信息
"""
offset = 1
points = [[-offset, offset], [0, offset], [offset, offset], [-offset, 0],
[offset, 0], [-offset, -offset], [0, -offset], [offset, -offset]]
for point in points:
if 0 <= x + point[0] < self.map2d.w and 0 <= y + point[1] < self.map2d.h:
self.map2d.data[x + point[0]][y + point[1]] = 1
def expansion(self, offset=0):
"""
地图障碍物膨胀
:param offset: 膨胀次数
:return: None, 按引用修改类对象map2d信息
"""
for i in range(offset):
barrierxy = list() # 不可行区域坐标点
for x in range(self.map2d.w):
for y in range(self.map2d.h):
if self.map2d.data[x][y] not in [self.passTag, 'S', 'E']:
barrierxy.append([x, y])
for xy in barrierxy:
self.setNearOnce(xy[0], xy[1])
def start(self):
"""
开始寻路
:return: None或Point列表(路径)
"""
# 1.将起点放入开启列表
startNode = AStar.Node(self.startPoint, self.endPoint)
self.openList.append(startNode)
# 2.主循环逻辑
while True:
# 找到F值最小的点
minF = self.getMinNode()
# 把这个点加入closeList中,并且在openList中删除它
self.closeList.append(minF)
self.openList.remove(minF)
# 判断这个节点的上下左右节点
self.searchNear(minF, -1, 1)
self.searchNear(minF, 0, 1)
self.searchNear(minF, 1, 1)
self.searchNear(minF, -1, 0)
self.searchNear(minF, 1, 0)
self.searchNear(minF, -1, -1)
self.searchNear(minF, 0, -1)
self.searchNear(minF, 1, -1)
'''
self.searchNear(minF,0,-1)
self.searchNear(minF, 0, 1)
self.searchNear(minF, -1, 0)
self.searchNear(minF, 1, 0)
'''
# 判断是否终止
point = self.endPointInCloseList()
if point: # 如果终点在关闭表中,就返回结果
# print("关闭表中")
cPoint = point
pathList = []
while True:
if cPoint.father:
pathList.append(cPoint.point)
cPoint = cPoint.father
else:
# print(pathList)
# print(list(reversed(pathList)))
# print(pathList.reverse())
return list(reversed(pathList))
if len(self.openList) == 0:
return None
if __name__ == '__main__':
# 创建一个10*10的地图
map2d = Array2D(15, 15)
# 设置障碍
for i in range(6):
map2d[3][i] = 1
for i in range(4):
map2d[10][i] = 1
# 显示地图当前样子
print("Input Map:")
map2d.showArray2D()
# 创建AStar对象,并设置起点为0,0终点为9,0
pStart, pEnd = Point(0, 0), Point(14, 0)
aStar = AStar(map2d, pStart, pEnd)
aStar.expansion(offset=1)
print("----------------------\nExpansion Map:")
aStar.map2d.showArray2D()
# 开始寻路
pathList = aStar.start()
# 遍历路径点,在map2d上以'8'显示
if pathList:
print("----------------------\nRoute Node:")
for point in pathList:
map2d[point.x][point.y] = '#'
print('{}:{}'.format(pathList.index(point), point), end=' ')
print("\n----------------------\nRoute:")
# 再次显示地图
map2d[pStart.x][pStart.y], map2d[pEnd.x][pEnd.y] = 'S', 'E'
map2d.showArray2D()
else:
print("No Path found")
|
208f59eebfc58d1bf697d015c903138945effb8c | Dhadhazi/PD17-OOPQuiz | /quiz_brain.py | 842 | 3.59375 | 4 | class QuizBrain:
def __init__(self, question_list):
self.question_number = 0
self.question_list = question_list
self.score = 0
def still_has_questions(self):
return len(self.question_list) > self.question_number
def next_question(self):
question = self.question_list[self.question_number]
self.question_number += 1
user_answer = input(f"Q.{self.question_number}: {question.text} (True/False): ")
self.check_answer(user_answer, question.answer)
def check_answer(self, user_answer, question_answer):
if (user_answer.lower() == question_answer.lower()):
self.score += 1
print("You got it right!")
else:
print("Wrong answer mateee")
print(f"Your current score is: {self.score}/{self.question_number}\n") |
c9faf8712ce7b092a5741c709f7b4a9beefc9b33 | vikash-india/DeveloperNotes2Myself | /languages/python/src/concepts/P002_HelloWorld.py | 526 | 4.15625 | 4 | # Description: "Hello World" Program in Python
print("Hello World!")
print('Hello Again! But in single quotes')
print("You can't enter double quotes inside double quoted string but can use ' like this.")
print('Similarly you can enter " inside single quoted string.')
print('Or you can escape single quotes like this \' inside single quoted string.')
print("Or you can escape double quotes like this \" inside double quoted string.")
# Mnemonics: Double Quotes, Single Quotes, One Inside the Other & Escape Quotes
|
a10443761947bcd8faa475a81fc643b44f0e9881 | marquesarthur/programming_problems | /leetcode/btree/tilt.py | 1,135 | 3.859375 | 4 | from leetcode.btree.binary_tree import BTree
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def tilt_sum(self, root):
if not root:
return 0, 0
sum_left, tilt_left = self.tilt_sum(root.left)
sum_right, tilt_right = self.tilt_sum(root.right)
return root.val + sum_left + sum_right, abs(sum_left - sum_right) + tilt_left + tilt_right
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
sum_left, tilt_left = self.tilt_sum(root.left)
sum_right, tilt_right = self.tilt_sum(root.right)
return abs(sum_left - sum_right) + tilt_left + tilt_right
#
# tree = BTree(6)
# tree.insert(4)
# tree.insert(9)
# tree.insert(7)
# tree.insert(11)
# tree.insert(2)
# tree.insert(1)
# tree.insert(4)
# tree.insert(5)
tree = BTree(4)
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
print(Solution().findTilt(tree)) |
c944defe9f6d6fec58fe7e78dce406a8887e93fd | jiaoqiyuan/Tests | /Python/python-practice/chapter8-func/greeter.py | 682 | 4.09375 | 4 | def greet_user(username):
"""显示简单的问候语"""
print("Hello, " + username.title() + "!")
greet_user('jesse')
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print("\nPlease tell me your name:")
f_name = input("First name:")
l_name = input("Last name:")
if (f_name == 'q') or (l_name == 'q'):
break
formatted_name = get_formatted_name(f_name, l_name)
print("\nHello, " + formatted_name + "!")
def city_country(city, country):
string = city.title() + ", " + country.title()
return string
string = city_country('beijing', 'china')
print(string) |
4b76b782d0f955ab9d99c3c8cab5306584c60560 | rocker2019/python_homework | /Second/grammar.py | 1,271 | 4.1875 | 4 | print('Basic Grammar')
# ################# 常量与变量 #################
'''
均存在内存中,常量是不可变的变量
命名规则
常量:一般采用大写字母,单词间下划线相连,如 PI | APP_URL
变量;只能是字母、数字和下划线的组合,但不能以数字开头,不能使用python关键字作为变量名
'''
# ################# 变量命名方法 #################
'''
驼峰式写法:firstName
下划线连接式写法:first_name
'''
# ################# 数字类型 ################
print("1 + 2 = {}".format(1 + 2)) # 使用format,{}作为占位符
print("7 % 2 = {}".format(7 % 2))
print("12 // 5 = {}".format(12 // 5))
print("10 * 2 = %d" % (10 * 2)) # 使用%, %s作为占位符
print("15 / 2 = %d, 4 - 5 = %d" % (15 / 2, 4 - 5))
print("3 ** 4 = %d" % (3 ** 4))
a = 101
b = 100
print(f'{a} is bigger than {b}') # version > 3.6
print("0.1 + 0.2 = {}".format(0.1 + 0.2)) # 结果包含的小数位数可能是不确定的
# ################# 布尔类型 ################
'''
1. True Or False,注意不是true or false
2. 0、空字符串、None 都被看作False,其他数值和非空字符串被看作True
3. 可进行正常的逻辑与或非运算 and or not
'''
|
61a095644b32444109ac2e37987cf399b5ea90be | zhukaijun0629/Programming_Daily-Practice | /2020-09-28_Sorting_a_list_with_3 unique_numbers.py | 665 | 4.1875 | 4 | """
Hi, here's your problem today. This problem was recently asked by Google:
Given a list of numbers with only 3 unique numbers (1, 2, 3), sort the list in O(n) time.
Example 1:
Input: [3, 3, 2, 1, 3, 2, 1]
Output: [1, 1, 2, 2, 3, 3, 3]
"""
def sortNums(nums):
mid = 2
left = 0
right = len(nums)-1
i=0
while i<right:
if nums[i]<mid:
nums[left],nums[i]=nums[i],nums[left]
left+=1
i+=1
elif nums[i]>mid:
nums[i],nums[right]=nums[right],nums[i]
right-=1
else:
i+=1
return nums
print(sortNums([3, 3, 2, 1, 3, 2, 1]))
# [1, 1, 2, 2, 3, 3, 3]
|
56baa0ac18495aa9b6b384396632fe04e9fe1508 | dogsoft0937/SEOULIT_PYTHON_LEARN | /day1/score.py | 190 | 3.53125 | 4 | score=70
if score>80:
print("Good")
elif score>60:
print("So Good")
elif score > 40:
print("20 Good")
elif score > 20:
print("10 Good")
else:
print("Very Good") |
10b14c7d97a05932fb34e9dff6ed0fa0ca65b571 | Eric2D/generator | /row_omitter/omitter.py | 2,286 | 3.9375 | 4 | # Searches unique content and deletes the row containing it
import io
import os
import sys
def counter(count):
try:
count = input('How many phrases would you like to omit?\n\n')
return count
except SyntaxError:
print 'Please use a number.\n\n'
return
except NameError:
print 'Please use a number.\n\n'
return
def the_gen():
count = None
# to check input for an actual number
while count < 0:
count = counter(count)
# Opens file content you would like to search and creates a list
reading = open("../ZZ_data_ZZ/content.txt")
lines = reading.readlines()
reading.close()
# open file for writing
pen = open("../ZZ_data_ZZ/results.txt", 'w')
num = 0
term_list = []
checks_balances = []
# loops for each count making a list of search terms in lowercase
for x in range (count):
num = num + 1
new_term = raw_input("What is the new term? " + str(num) + "\n\n")
term = [new_term.lower()]
term_list = term_list + term
num = 0
remain_check = 0
# calls on lines which is a list of each row in the content.txt file
for x in lines:
num = num + 1
# make line lowercase
content = x.lower()
# search for term
for y in term_list:
finding = content.find(y)
# conditions for finding term to be deleted
if finding != -1:
no_luck = False
break
if finding == -1:
no_luck = True
# for carrying over special title sections // the exceptions
if content.find('#----#') != -1:
no_luck = True
# lines with unfound items will be written
if no_luck == True:
pen.write(x)
# Found items will be saved to be written to remains
if no_luck == False:
to_remains = [x]
checks_balances = checks_balances + to_remains
print "Working - " + str(num) + " / " + str(len(lines))
pen.close()
# Writing to remains for the sake of double checking content.
# good lord please check your content!
remains = open("../ZZ_data_ZZ/remains.txt", 'w')
num = 0
for x in checks_balances:
num = num + 1
remains.write(x)
print "Writing remains - " + str(num) + " / " + str(len(checks_balances))
remains.close()
sys.exit()
the_gen()
print "\nOpen the results.txt file and search 'Found' or 'Couldn't find' to quickly check "
"results\nAnd open remains.txt to see the left over content.\n"
|
c5fbdf222fe2149f0105e867d7b1493db8c2dcce | GitDeus/1_Lab_Python | /4. Строки/4.2___Lab_Python.py | 325 | 3.921875 | 4 | #Дана строка. Вывести первый, последний и средний (если он есть)) символы.
#2
def get_string(string):
print('first', string[0])
if len(string) % 2:
print('mid',string[len(string)//2])
print('last',string[len(string)-1])
get_string('denis') |
cbb0cc893e383894f07c74fb036f0c3f0e3aceba | GatzZ/Leetcode | /229. Majority Element II.py | 1,286 | 3.578125 | 4 | # coding=utf-8
# Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
# The algorithm should run in linear time and in O(1) space.
# 如何找到所有出现次数严格大于总数1 / k的数? 提示: 保存(k – 1)个数!!!!
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return []
candidate1 = -99999999999999
candidate2 = -100000000000000
count1 = 0
count2 = 0
for num in nums:
if num == candidate1:
count1 += 1
elif num == candidate2:
count2 += 1
elif count1 == 0:
candidate1 = num
count1 = 1
elif count2 == 0:
candidate2 = num
count2 = 1
else:
count1 -= 1
count2 -= 1
return [candidate for candidate in (candidate1, candidate2) if nums.count(candidate) > len(nums) / 3]
# why count(1) will not be canceled out? because candidate2 and count2 help us protect.
# < n/3 times happens:count1 -=1; count2 -=1
nums = [1, 1, 2, 3, 4]
print Solution().majorityElement(nums)
|
46ec3286ed9b8a4122deb7c0dc333a216d947038 | SemHiel/PythonExtra | /pythonturtle/test3.py | 354 | 3.609375 | 4 | import turtle
sem = turtle.Turtle()
sem.getscreen().bgcolor("#994444")
sem.speed(100)
sem.penup()
sem.goto((-200,100))
sem.pendown()
def star(turtle, size):
if size <= 10:
return
else:
turtle.begin_fill()
for i in range(5):
turtle.forward(size)
star(turtle, size/3)
turtle.left(216)
turtle.end_fill()
star(sem, 360)
turtle.done()
|
13a39b28e715ea5aacd0d6e8c9aa7f25f66282e6 | anggieladorador/ejerciciospy | /saludo.py | 129 | 3.796875 | 4 | #ejercicio 1 python
#Ingrese su nombre: Perico
#Hola, Perico
print("ingrese su nombre")
name = input()
print("hola "+name) |
3a3372214b0fa776c3c7b90515873d6b86f6c4f7 | Axiom-Cloud-Inc/interview | /tree/tree_answers.py | 3,658 | 3.59375 | 4 | import json
class Node:
def __init__(self, name):
self.name = name
self._parent = None
self._children = set()
self.value = None
def __repr__(self):
return f'{self.id} = {self.value}'
def __iter__(self):
yield self
for child in self.children:
yield from child
def __len__(self):
counter = 0
for _ in self:
counter += 1
return counter
@property
def parent(self):
return self._parent
@property
def children(self):
return self._children
@property
def id(self, sep='.'):
"""
Path of this Node from the root
:param str sep: Separator char
:return str: Path to Node from relative Node self
"""
if self.parent is None:
return self.name
return f'{self.parent.id}{sep}{self.name}'
@classmethod
def parse(cls, config):
"""
Recursively parse a dictionary to create a tree
:param dict config: Dictionary to parse into Nodes
:return Iterable[Node]: Iterable of newly created Nodes
"""
nodes = set()
for k, v in config.items():
# Create node object
node = cls(k)
# Add current node to set of nodes parsed at this level
nodes.add(node)
# Ignore children if null value found
if v is None:
continue
# Add any children nodes recursively
children = cls.parse(v)
for child in children:
node.add_child(child)
return nodes
@classmethod
def load(cls, file):
"""
Load a JSON file into a tree object
* Assume top level has only one key (root) *
:param str file: JSON tree file path
:return Node: Root Node of tree created from file
"""
with open(file, 'r') as r:
config = json.load(r)
return cls.parse(config).pop()
def add_child(self, node):
"""
Add a child node
:param Node node: Child to add
"""
self.children.add(node)
node._parent = self
def get(self, path, sep='.'):
"""
Get a node by ID
:param str path: Relative path to node
:param str sep: Separator char
:return Node: Node at path, or raise KeyError if not found
"""
name, *remaining = path.split(sep)
for child in self._children:
if child.name != name:
continue
if remaining:
return child.get(sep.join(remaining), sep=sep)
return child
raise KeyError
def update(self, payload):
"""
Update node values in the tree by ID
:param dict payload: Dictionary tree ID / value pairs
"""
for k, v in payload.items():
try:
node = self.get(k)
except KeyError:
pass
else:
node.value = v
#########
# TESTS #
#########
tree = Node.load('tree.json')
assert len(tree) == 21
payload = {
'rack1.sg1': 10,
'rack1.sg1.cmp1': 5,
'rack1.sg1.ckt1.case2': 20,
'rack1.sg2.ckt1': 30,
'rack2.sg1.ckt1.case1': 20,
'rack2.sg1.ckt1.case5': 20, # Does not exist
}
tree.update(payload)
assert tree.get('rack1.sg1').value == 10
assert tree.get('rack1.sg1.cmp1').value == 5
assert tree.get('rack2.sg1.ckt1.case1').value == 20
assert tree.get('rack1.sg1.cmp2').value == None
try:
tree.get('rack2.sg1.ckt1.case5')
assert False
except KeyError:
assert True
|
1add1ffa3e654f4afe56ba90df8256a651bf162a | cartoonqq/CoPython3 | /p_print.py | 1,284 | 3.625 | 4 |
# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.runoob.com
import pymysql
'''
# 用户输入数字
num1 = input('输入第一个数字:')
num2 = input('输入第二个数字:')
# 求和
sum = float(num1) + float(num2)
# 显示计算结果
print('数字 {0} 和 {1} 相加结果为: {2}'.format(num1, num2, sum))
print(100+200)
'''
n = 123
f = 456.789
s1 = 'Hello, world'
s2 = 'Hello, \'Adam\''
s3 = r'Hello, "Bart"'
s4 = r'''Hello,
Lisa!'''
print('\r\'Hello, \"Bart\"\'')
print(r'''Hello,
Lisa!''')
print('{3},{1},{2},{0},{p1}'.format(n,f,s1,s2,p1=f))
print('%5s,%10d%20s'%('aa',22,s1))
print('%10s%10s%10s'%('name','age','sex') )
print('%50d%%'%(len('25991')))
# -*- coding: utf-8 -*-
year1 = 72
year2 = 85
p_year=year2-year1
print('p_up:%d,%.2f%%'%(p_year,p_year/year1*100))
#复合赋值:
#a,b=a,a+b:右边的表达式会在赋值变动之前执行。
#斐波那契数列
def p_seq():
try:
i=int(input('max number:'))
a,b=0,1
while b < i:
print(b,end='@') #print可以不换行同时制定分隔符
a,b=b,a+b #复合赋值:此处的写法与:a=b;b=a+b分2行写是有不同效果的。右边的表达式会在赋值变动之前执行。
except Exception as e:
print(e)
p_seq() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.