blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0d0f4ba0c6334651c3987a5d76a0b8a2722cd326 | NavyaKola/PythonPractice1 | /HackerRank/PyPrac/Collections/ordereddic.py | 387 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 7 18:36:50 2018
@author: navya
"""
N=int(input());
from collections import OrderedDict;
itemnames=OrderedDict();
for i in range(N):
item, space, quantity = input().rpartition(' ')
itemnames[item] = itemnames.get(item, 0) + int(quantity)
for item, quantity in itemnames.items():
print(item, quantity)
|
fbff0c560dbc6f8505eb6bc7f399c203c0edac45 | Abdulvaliy/rock-paper-scissors | /Rock, Paper, Scissors.py | 1,319 | 4.1875 | 4 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
import random
your_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors. "))
comp = random.randint(0, 2)
if your_choice == 0 and comp == 1:
print(f"You choose rock{rock}\nYour computer chosen paper {paper}.\nYou lose.")
elif your_choice == 1 and comp == 2:
print(f"You choose paper{paper}\nYour computer chosen scissors {scissors}.\nYou lose.")
elif your_choice == 2 and comp == 0:
print(f"You choose scissors{scissors}\nYour computer chosen rock {rock}.\nYou lose.")
elif your_choice == 1 and comp == 0:
print(f"You choose paper{paper}\nYour computer chosen rock {rock}.\nYou win.")
elif your_choice == 2 and comp == 1:
print(f"You choose scissors{scissors}\nYour computer chosen paper paper{paper}.\nYou win.")
elif your_choice == 0 and comp == 2:
print(f"You choose rock{rock}\nYour computer chosen scissors {scissors}.\nYou win.")
else:
print("Both you have chosen the same. No one win!")
|
e1bd25dfb95e88c2c68f496e5aa2598382fcd4c9 | ArdaOzcan/boink-python-demo | /lexer.py | 10,427 | 3.5 | 4 | from enum import Enum
from errors import ErrorHandler, UnknownTokenError
class TokenType(Enum):
"""Enum to hold information about a token's type. Derives from Enum class."""
EOF = 0 # End of file
NEW_LINE = 1 # \n
INT_LITERAL = 2 # 0, 1, 2, 123, 314 ...
FLOAT_LITERAL = 3 # 0.123123, 3.1415, 2.72 ...
PLUS = 4 # +
MINUS = 5 # -
STAR = 6 # *
SLASH = 7 # /
AMPERSAND_AMPERSAND = 8 # &&
PIPE_PIPE = 9 # ||
WORD = 10 # hello, lol, x, y, z ...
FUNC_DEF = 11 # fn
EQUALS = 12 # =
L_PAR = 13 # (
R_PAR = 14 # )
SEMI_COLON = 15 # ;
DYNAMIC_TYPE = 16 # dyn
INT_TYPE = 17 # int
COMMA = 18 # ,
BOOL_LITERAL = 19 # true, false
BOOL_TYPE = 20 # bool
FLOAT_TYPE = 21 # float
RIGHT_ARROW = 22 # ->
GIVE = 23 # give
IF = 24 # if
GREATER = 25 # >
GREATER_EQUALS = 26 # >=
LESS = 27 # <
LESS_EQUALS = 28 # <=
EQUALS_EQUALS = 29 # ==
# Dict to hold information about existing keywords and
# the corresponding token type to separate regular words
# (e.g. variable names) from keywords.
KEYWORDS = {"fn": TokenType.FUNC_DEF,
"dyn": TokenType.DYNAMIC_TYPE,
"int": TokenType.INT_TYPE,
"false": TokenType.BOOL_LITERAL,
"true": TokenType.BOOL_LITERAL,
"bool": TokenType.BOOL_TYPE,
"float": TokenType.FLOAT_TYPE,
"give": TokenType.GIVE,
"if": TokenType.IF}
class Token:
"""Simple data structure to hold information about a token."""
def __init__(self, token_type, val, pos):
"""Construct a Token object.
Args:
token_type (TokenType): Type of the token.
val (any): Value of the Token, usually the string that the token refers to.
pos (int): 1D starting position of the token.
"""
self.token_type = token_type
self.val = val
self.pos = pos
def __str__(self):
return f"{self.token_type}, {repr(self.val)}"
def __repr__(self):
return self.__str__()
class Lexer:
"""Lexer of the program.
Lexer loops through every character and converts them to tokens
or raises errors if an unknown character or character sequence occurs.
"""
def __init__(self, text, error_handler):
"""Construct a Lexer object.
Args:
text (str): Text of the program.
error_handler (ErrorHandler): Error handler of the program.
"""
self.text = text
self.pos = 0
self.error_handler = error_handler
def convert_pos_to_line(self, pos):
"""Convert a 1D position to a 2D position that is
the line number and the offset from the previous newline.
Args:
pos (int): 1D position of a character.
Returns:
tuple: New 2D position with the line number and offset.
"""
if pos >= len(self.text):
return None
i = 0
line_count = 0
offset_to_new_line = 0
char = self.text[i]
while i < pos:
offset_to_new_line += 1
if char == '\n':
line_count += 1
offset_to_new_line = 0
i += 1
char = self.text[i]
return (line_count + 1, offset_to_new_line + 1)
def get_next_number_token(self):
"""Return the next number (whole or floating) as a token.
Returns:
Token: Token of the next number.
"""
result = ""
start_pos = self.pos
while self.current_char() != None and self.current_char().isdigit():
result += self.current_char()
self.pos += 1
if self.current_char() == '.': # It is a floating number.
result += self.current_char()
self.pos += 1
while self.current_char() != None and self.current_char().isdigit():
result += self.current_char()
self.pos += 1
return Token(TokenType.FLOAT_LITERAL, float(result), start_pos)
else:
return Token(TokenType.INT_LITERAL, int(result), start_pos)
def peek(self, amount=1):
"""Return the character with the offset of amount
from the current position. Return None if the character
is out of range.
Args:
amount (int, optional): Offset from the current character. Defaults to 1.
Returns:
char: Peeked character.
"""
if self.pos + amount < len(self.text) - 1:
return self.text[self.pos + amount]
return None
def is_ahead(self, text):
"""Check if a text is ahead from the current character.
Args:
text (str): Text to be checked if is ahead.
Returns:
bool: If the text is ahead.
"""
index = 0
while index < len(text):
if self.peek(index) != text[index]:
return False
index += 1
if self.peek(index) == None:
return False
return True
def get_next_word_token(self):
"""Get the next word token and separate keywords
with regular word.
Returns:
Token: The next word token.
"""
result = ""
start_pos = self.pos
while self.current_char() != None and self.current_char().isalpha():
result += self.current_char()
self.pos += 1
if result in KEYWORDS: # Is a keyword.
val = result
if KEYWORDS[result] == TokenType.BOOL_LITERAL:
val = (result == "true")
return Token(KEYWORDS[result], val, start_pos)
return Token(TokenType.WORD, result, start_pos)
def ignore_white_space(self):
"""Pass whitespace until it isn't whitespace."""
while self.current_char() != None and self.current_char() == ' ':
self.pos += 1
def ignore_comment(self):
"""Pass characters until it's newline."""
while self.current_char() not in ('\n', None):
self.pos += 1
def get_next_token(self):
"""Return the next token or call a method that would.
this method is the entry point for getting the next.
Returns:
Token: Token to be returned.
"""
self.ignore_white_space()
if self.current_char() == '#':
self.ignore_comment()
return self.get_next_token()
if self.current_char() == None:
return Token(TokenType.EOF, None, self.pos)
if self.current_char().isdigit():
return self.get_next_number_token()
if self.current_char().isalpha():
return self.get_next_word_token()
if self.current_char() == '+':
token = Token(TokenType.PLUS, self.current_char(), self.pos)
self.pos += 1
return token
if self.current_char() == ',':
token = Token(TokenType.COMMA, self.current_char(), self.pos)
self.pos += 1
return token
if self.current_char() == '-':
if self.is_ahead('->'):
start_pos = self.pos
self.pos += len('->')
return Token(TokenType.RIGHT_ARROW, '->', start_pos)
token = Token(TokenType.MINUS, self.current_char(), self.pos)
self.pos += 1
return token
if self.current_char() == '*':
token = Token(TokenType.STAR, self.current_char(), self.pos)
self.pos += 1
return token
if self.current_char() == '/':
token = Token(TokenType.SLASH, self.current_char(), self.pos)
self.pos += 1
return token
if self.current_char() == '(':
token = Token(TokenType.L_PAR, self.current_char(), self.pos)
self.pos += 1
return token
if self.current_char() == ')':
token = Token(TokenType.R_PAR, self.current_char(), self.pos)
self.pos += 1
return token
if self.current_char() == '=':
if self.is_ahead('=='):
start_pos = self.pos
self.pos += len('==')
return Token(TokenType.EQUALS_EQUALS, '==', start_pos)
token = Token(TokenType.EQUALS, self.current_char(), self.pos)
self.pos += 1
return token
if self.current_char() == ';':
token = Token(TokenType.SEMI_COLON, self.current_char(), self.pos)
self.pos += 1
return token
if self.current_char() == '\n':
token = Token(TokenType.NEW_LINE, self.current_char(), self.pos)
self.pos += 1
return token
if self.current_char() == '>':
if self.is_ahead('>='):
start_pos = self.pos
self.pos += len('>=')
return Token(TokenType.GREATER_EQUALS, '>=', start_pos)
token = Token(TokenType.GREATER, self.current_char(), self.pos)
self.pos += 1
return token
if self.current_char() == '<':
if self.is_ahead('<='):
start_pos = self.pos
self.pos += len('<=')
return Token(TokenType.LESS_EQUALS, '<=', start_pos)
token = Token(TokenType.LESS, self.current_char(), self.pos)
self.pos += 1
return token
if self.is_ahead('&&'):
start_pos = self.pos
self.pos += len('&&')
return Token(TokenType.AMPERSAND_AMPERSAND, '&&', start_pos)
if self.is_ahead('||'):
start_pos = self.pos
self.pos += len('||')
return Token(TokenType.PIPE_PIPE, '||', start_pos)
self.error_handler.error(
UnknownTokenError(f"Character '{self.current_char()}' is not known",
self.pos))
self.pos += 1
return self.get_next_token()
def current_char(self):
"""Get the current char with the current pos.
Return None if the pos is out of range.
Returns:
chr: The character to be returned.
"""
if self.pos > len(self.text) - 1:
return None
return self.text[self.pos]
|
ee9c7140c09e5bb34ac47564cd7a54e0bc502590 | distributed-system-analysis/smallfile | /parser_data_types.py | 2,188 | 3.5 | 4 | import argparse
import os
from smallfile import SmallfileWorkload
TypeExc = argparse.ArgumentTypeError
# if we throw exceptions, do it with this
# so caller can specifically catch them
class SmfParseException(Exception):
pass
# the next few routines implement data types
# of smallfile parameters
def boolean(boolstr):
if isinstance(boolstr, bool):
return boolstr
b = boolstr.lower()
if b == "y" or b == "yes" or b == "t" or b == "true":
bval = True
elif b == "n" or b == "no" or b == "f" or b == "false":
bval = False
else:
raise TypeExc("boolean value must be y|yes|t|true|n|no|f|false")
return bval
def positive_integer(posint_str):
intval = int(posint_str)
if intval <= 0:
raise TypeExc("integer value greater than zero expected")
return intval
def non_negative_integer(nonneg_str):
intval = int(nonneg_str)
if intval < 0:
raise TypeExc("non-negative integer value expected")
return intval
def host_set(hostname_list_str):
if os.path.isfile(hostname_list_str):
with open(hostname_list_str, "r") as f:
hostname_list = [record.strip() for record in f.readlines()]
else:
hostname_list = hostname_list_str.strip().split(",")
if len(hostname_list) < 2:
hostname_list = hostname_list_str.strip().split()
if len(hostname_list) == 0:
raise TypeExc("host list must be non-empty")
return hostname_list
def directory_list(directory_list_str):
directory_list = directory_list_str.strip().split(",")
if len(directory_list) == 1:
directory_list = directory_list_str.strip().split()
if len(directory_list) == 0:
raise TypeExc("directory list must be non-empty")
return directory_list
def file_size_distrib(fsdistrib_str):
# FIXME: should be a data type
if fsdistrib_str == "exponential":
return SmallfileWorkload.fsdistr_random_exponential
elif fsdistrib_str == "fixed":
return SmallfileWorkload.fsdistr_fixed
else:
# should never get here
raise TypeExc('file size distribution must be either "exponential" or "fixed"')
|
8f6c73873d8c7002bb84dcea7cfaa8cf83eb8fa5 | devilhtc/leetcode-solutions | /0x041b_1051.Height_Checker/solution.py | 187 | 3.65625 | 4 | class Solution:
def heightChecker(self, heights: List[int]) -> int:
heights2 = sorted(heights)
return sum(1 for i in range(len(heights)) if heights[i] != heights2[i])
|
78ef05d4e467b46521e56972bcbe490bad3d63ab | leontis/Thinkful_projects | /Fizz_buzz.py | 540 | 3.859375 | 4 | import sys
if len(sys.argv) == 1:
try:
n = int(raw_input("Enter an integer: "))
except ValueError:
print "Enter a valid integer"
elif len(sys.argv) >1:
try:
n = int(sys.argv[1])
except ValueError:
print "No valid integer! will use 100 ..."
n = 100
print "Fizz buzz counting up to ", n
my_list = [i for i in range(0,n+1)]
print my_list
for i in range(1,n+1):
if i % 3 == 0 and i % 5 != 0:
my_list[i] = "fizz"
elif i % 5 == 0 and i % 3 != 0:
my_list[i] = "buzz"
for i in range(0,n+1):
print my_list[i], "\n"
|
6d3ec84dedf06ec3014846219fdb492fd461bfda | ws0110/python_example | /4.control/ex_nestfunc.py | 1,363 | 4 | 4 |
####### range(): range(['시작값:0'], '종료값', ['증가값:1'])
print(list(range(10)))
print(list(range(5, 10)))
print(list(range(10, 0, -1)))
print(list(range(10, 20, 2)))
####### enumerate(): enumerate('객체', ['인덱스시작값:0']) 인덱스,Value 함께 조회
L = [10, 20, 30, 40]
for i in enumerate(L):
print(i)
for i in enumerate(L, 100):
print(i)
####### LIST 내장
I1 = (i ** 2 for i in range(5))
print(list(I1))
L1 = ['apple', 'banana', 'orange', 'kiwi']
I2 = (i for i in L1 if len(i) > 5)
print(list(I2))
L3 = [1, 2, 3]
L4 = [4, 5, 6]
I3 = (x*y for x in L3 for y in L4)
print(list(I3))
######## Filter 함수
def getBiggerThan20(i):
return i > 20
L5 = [10, 25, 30]
I4 = filter(getBiggerThan20, L5) # filter(lambda i: i > 20, L) 가능
print(list(I4))
########### ZIP
X = [10, 20, 30]
Y = ['A', 'B', 'C', 'D'] # D는 무시 됨
ret = list(zip(X, Y))
print(ret)
X2, Y2 = zip(*ret) ## 풀기
print(X2, Y2)
########### MAP
L6 = [1, 2, 3]
def add10(i):
return i+10
I5 = (i for i in map(add10, L6))
print(list(I5))
L7 = [4, 5, 6]
I6 = (i for i in map(pow, L6, L7)) ## 매개변수 2개 이상
print(list(I6))
########### FOR 성능
L8 = ['apple', 'banana', 'orange', 'kiwi']
print(', '.join(L8)) ### print문 단 한번 실행으로 for문 사용해서 print() 매번 실행하는것 보다 효율적!!
|
a3e8467499000703a2236abad02372a693aee36c | lucashsouza/Desafios-Python | /CursoEmVideo/Aula16/ex072.py | 391 | 3.796875 | 4 | c = ('Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez',
'Onze', 'Doze', 'Treze', 'Quatorze', 'Quinze', 'Dezesseis', 'Dezessete',
'Dezoito', 'Dezenove', 'Vinte')
print(c)
n = int(input('Digite um numero de 1 a 20: '))
if n > 20 or n < 0:
print('Tente novamente. Digite um numero de 1 a 20: ')
else:
print(f'Você digitou: {c[n - 1]}')
|
ea8f140f4f4085295281c046d88a0a87e9f9c0b6 | vtt-info/Micropython-10 | /Triode-Car/microbit(only)/2.1 Control motor speed with button/main.py | 1,635 | 3.5 | 4 | from microbit import *
'''
设计一个控制电机转速的函数。
创建的函数可以添加参数(自变量)。
调用函数时输入自变量即可如同套用一个公式一样使用函数。
write_analog()取值范围为0-1023,将控制microbit对应引脚输出1024级占空比的PWM。
若我们设计将电机转速等分为10级,则应该将1023分10等份再乘以函数自变量。
占空比越大,转速越慢,占空比越低,转速越快。
若设计转速从0-10逐级增大,则应1023-1023-1023/10*value。
int()将使其数值取整。
'''
def left_motor_speed(value):
if value>=0 and value<=10:
pin14.write_analog(int(1023-1023/10*value))
else:
print('Values range from 0 to 10')
def right_motor_speed(value):
if value>=0 and value<=10:
pin15.write_analog(int(1023-1023/10*value))
else:
print('Values range from 0 to 10')
'''创建一个变量并设置初始值为0'''
speed = 0
while True:
'''执行到break即退出循环,此处用类似于if
当按钮A被按下过一次,speed变量加1'''
while button_a.was_pressed():
speed += 1
break
'''当按钮B被按下过一次,speed变量减1'''
while button_b.was_pressed():
speed -= 1
break
'''当变量speed值小于0或大于10时将值设为0'''
while speed < 0 or speed > 10:
speed = 0
break
'''变量speed值同时控制左右电机的转速'''
left_motor_speed(speed)
right_motor_speed(speed)
'''显示speed值'''
display.show(speed, delay=500, wait=True, loop=False, clear=False)
|
2cd16c38299e827ca802ac80e34b8ec3fc91fb71 | marshyn/nc-2020fall-python-final | /Final Project/final_03.py | 5,554 | 3.75 | 4 | # Recolor Square
# how to run in terminal
# drag file
# python3 coding.py (or name of file)
# how to close window with keyboard commands
# control ^ + c (with the terminal window selected and active)
import time
from random import *
from graphics import *
from math import sqrt
win = GraphWin("Maze game", 800, 800)
win.setBackground("floralwhite")
# clicky clicky
keyClicked = win.checkMouse()
def menu(followDirections_text, menuButton_color):
# stuff, text, button
"""
win = GraphWin("Maze game", 800, 800)
win.setBackground("floralwhite")
"""
"""
"""
# title text
title = Text(Point(400, 200), "Squares")
title.setSize(30)
title.draw(win)
# INSTRUCTION STUFF
# the actual instructions
instructions = Text(Point(400, 400), followDirections_text)
instructions.setSize(16)
instructions.draw(win)
"""
# instruction button
instructionsButton = Polygon(Point(300, 400), Point(500, 475))
instructionsButton.setFill(menuButton_color)
instructionsButton.draw(win)
# instruction button text
instructionsButton_text = Text(Point(400, 37.5), "Instructions")
instructionsButton_text.setSize(18)
instructionsButton_text.draw(win)
"""
"""
# BACK MENU STUFF
# back menu button
backMenu =
backMenu.setFill(menuButton_color)
backMenu.draw(win)
# back menu text
backMenu_text = Text(Point(662.5, 950), "Back")
backMenu_text.setSize(16)
backMenu_text.draw(win)
# button
button =
button.setFill(menuButton_color)
button.draw(win)
"""
# PLAY STUFF
# play button text
playButton_text = Text(Point(400, 500), "Play")
playButton_text.setSize(20)
playButton_text.draw(win)
# The Player
player = Circle(Point(20,20), 10)
def playerDraw():
player.setFill("red")
player.setOutline("red")
player.draw(win)
# move the player
def playerMove():
while True:
key = win.checkKey()
if key == "Left":
player.move(-5,0)
if key == "Right":
player.move(5,0)
if key == "Up":
player.move(0,-5)
if key == "Down":
player.move(0,5)
# player's position
def playerPosition():
playerCenter = player.getCenter()
playerX = playerCenter.getX()
playerY = playerCenter.getY()
playerCoord = Point(playerX, playerY)
print(playerCoord)
"""
def displayPlayer():
activeClick = win.getMouse()
if activeClick == True:
"""
"""
def treeDraw(x1, y1, x2, y2, x3, y3):
tree = Polygon(Point(x1, y1), Point(x2, y2), Point(x3, y3))
tree.draw(win)
"""
# identifies the center of a shape
def hitBox(tile):
hitPoint_center = tile.getCenter()
hitPoint_x = hitPoint_center.getX()
hitPoint_y = hitPoint_center.getY()
hitBoxCoord = Point(hitPoint_x, hitPoint_y)
#print(hitBoxCoord)
"""
#test hitbox function
testRec = Rectangle(Point(300,300), Point(400,400))
testRec.draw(win)
hitBox(testRec)
"""
""""
def tileIdentify(tileColor):
if tileColor == "green":
return green
print("green tile frmo tileIdentify function")
if tileColor == "red":
return red
def tileChange(tileColor):
if tileColor == "green":
wallGreen.undraw(win)
wallRed.draw(win)
#if tileColor == "red":
"""
def tileIdentify(tileDirection):
if tileDirection == "left":
return left
print("this tile is a left arrow tile")
if tileColor == "red":
return tileDirection
if tileDirection == "Left":
return key
if tileDirection == "Right":
return key
if tileDirection == "Up":
return key
if key == "Down":
tileDirection key
def tileChange(tileColor):
if tileColor == "green":
wallGreen.undraw(win)
wallRed.draw(win)
#if tileColor == "red":
# Exit
# exit text
exitButtonText = Text(Point(740,765), "EXIT")
#exitButtonText = Text(Point(300,300), "EXIT")
exitButtonText.setSize(14)
exitButtonText.draw(win)
"""
# exit button
exitButton = Rectangle(Point(700, 750), Point(780, 780))
exitButton.setFill("gold")
exitButton.draw(win)
"""
# draw the green wall
"""
# ???????
def wallGreenDraw(sizeDimension):
x1 = randint(100, 700)
wallGreen = Rectangle(Point(x1,x1), Point(x1 + sizeDimension, x1 + sizeDimension))
wallGreen.setFill("green")
wallGreen.setOutline("green")
wallGreen.draw(win)
"""
"""
x1 = 0
y1 = 75
sizeDimension = 50
"""
def tileGreen_draw():
global tileGreen
tileGreen = Rectangle(Point(0,75), Point(50, 125))
tileGreen.setFill("green")
tileGreen.setOutline("green")
tileGreen.draw(win)
return tileGreen
print("Green tile........")
"""
tileRed = Rectangle(Point(x1 + 200,y1 + 200), Point(x1 + 200 + sizeDimension, y1 + 200 + sizeDimension))
tileRed.setFill("red")
tileRed.setOutline("red")
tileRed.draw(win)
"""
####################################### testing. .. please work
tileGreen_draw()
hitBox(tileGreen) # should print (25, 100)
# hitbox function should be used beforehand
"""
while True:
hitBox(player)
"""
followDirections_text = "Run over the tiles and change their colors. \n Get to the end!"
menuButton_color = "ghostwhite"
menu(followDirections_text, menuButton_color)
tileIdentify(tileGreen_draw)
playerDraw()
playerMove()
"""
# using wallGreenDraw function
wallGreenDraw(50)
"""
####################################### extra
time.sleep(1)
input("Press enter to close this window.")
|
1baa0ee553afac35416b6a673b3f88645b10ef22 | tanetch/CP3-Tanet-Chanthsithiporn | /Exercise8_Tanet_C.py | 991 | 3.765625 | 4 | username = "admin"
password = "0000"
UserInputUsername = input("Username: ")
UserInputPassword = input("Password: ")
if UserInputUsername == username and UserInputPassword == password:
print("Log in completed")
print("Service List")
print("1. One-side document printing 0.5 THB per page")
print("2. Two-side document printing 1 THB per page")
print("3. Photo printing 5 THB per page")
UserSelect = int(input("Select the service: "))
if UserSelect == 1:
amount = int(input("Enter amount of page: "))
price = 0.5*amount
print("Total: ",price,"THB")
elif UserSelect == 2:
amount = int(input("Enter amount of page: "))
price = 1*amount
print("Total: ",price,"THB")
elif UserSelect == 3:
amount = int(input("Enter amount of page: "))
price = 5*amount
print("Total:",price,"THB")
else:
print("Error.")
else:
print("Error.")
|
1b4102ce5d1790206ce24ad437c180b93073ef67 | loveleen-kaur21/fundamentals-of-programming-pt-1-unit-project-loveleen-hardaway | /Stopwatch.py | 318 | 4.03125 | 4 | import time
def stopwatch():
start = input("Press enter to start the timer")
print("the timer has started")
begin = time.time()
endtimer = input("Press enter to stop the timer")
end = time.time()
elapsed = end - begin
elapsed = int(elapsed)
print("The time elapsed is", elapsed,)
|
be6803ef24c7547de2411e25dc60957ff511d3fa | SimonSlominski/Codewars | /7_kyu/7_kyu_Shortest Word.py | 343 | 4.21875 | 4 | """ All tasks come from www.codewars.com """
"""
TASK: Shortest Word
Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
"""
def find_short(s):
words_length = [len(word) for word in s.split(' ')]
return min(words_length)
|
ffadd4af1acdaf6e6ae5b9265723653b31909851 | polineto/introducao_ciencia_computacao_python | /Parte_1/conta_primos.py | 511 | 3.65625 | 4 | def n_primos(n):
count = 0
div = 0
primos = 0
numbers = range(2, (n + 1), 1) #intervalo de todos os números a serem testados
for num in numbers: #testa todos os números no intervalo
while num > div:
div += 1
if num % div == 0:
count += 1
if count == 2: #se o número for primo
primos += 1 #computo o número na contagem
count = 0 #zero a contagem para o próximo loop
div = 0
return primos
|
345e40cfc1dab87cbacfff9fafc9dbb51342d199 | saiyerniakhil/GUVI-CodeKata | /Beginner/Set 1/challenge4.py | 158 | 3.796875 | 4 | try:
x = input()
if x.isalpha() and len(x) == 1 :
print("Alphabet",end="")
else:
print('no',end="")
except:
print('no',end="") |
001445d57e2c405b2f7318e309d0f9fc1ac2baf4 | orangeblacktree/thegame | /gamedata/levels/basics/__init__.py | 8,107 | 4.34375 | 4 | # ------------------------------------------------------------------
# basics/__init__.py
#
# Teaches basics
# ------------------------------------------------------------------
import os
import pygame
import shared
import objects
import userspace
from vec2d import Vec2d
from level import Level
import image
helps = {
'move': """
# In thegame, you do things through code. We shall use Python, a popular
# programming language. This tab will give you instructions that help
# you through the game.
#
# Open a new tab (File Menu -> New Tab) and paste in the following code:
player.move('right')
# Now run the code (while on the new tab, Run Menu -> Run). You should see the
# red block move one step to the right.
""",
'otherdirs': """
# Well done!
#
# 'player' refers to the player object (the red block). 'move' is a function you
# called on the player, which made it move. You gave it a parameter that
# specified the direction to move in.
#
# The other directions are '%s', '%s' and '%s'. Try them too.
""",
'loops': """
# Well done!
#
# 'player' refers to the player object (the red block). 'move' is a function you
# called on the player, which made it move. You gave it a parameter that
# specified the direction to move in.
#
# The other directions are '%s', '%s' and '%s'. Try them too.
""",
'output': """
# You can print text to the output console using the 'output' function. Try
# running the code below:
output('Hello, world!')
""",
'variables': """
# Variables allow you to assign names to values. The below code assigns the value
# 5 to a variable called 'number' and prints it.
number = 5
output(number)
# Try creating your own variable and printing it.
""",
'lists': """
# We have seen numbers, strings (such as 'left' and 'right') and complex objects
# such as the player. An interesting type that is built into Python is the 'list'.
# A list is simply an ordered collection of elements. Each of these elements is
# yet another Python object.
#
# Here we create a list named 'l' and print it.
l = [1, 2, 3, 4] # a list of the numbers 1, 2, 3 and 4
output(l)
# Try printing your own list.
""",
'loops': """
# Good job!
#
# Loops run the same code multiple times. The 'for' loop can be used to iterate
# over items in a list. Each time it runs the code with a different element of
# the list. In the below example, "output(i)" is run repeatedly with different
# values for 'i'. The for statement above it says that these values for i must
# be picked from the list [1, 2, 3]. The code to be run inside a for loop must
# be indented.
for i in [1, 2, 3]:
output(i)
output('done!')
# Let's get back to the game. Try running the following piece of code. The
# wait(s) function pauses execution for 's' seconds.
# do this three times
for i in range(3):
# move in each direction
for dir in ['left', 'up', 'right', 'down']:
output('Going ' + dir + '!')
player.move(dir)
wait(1) # wait for 1 second so we don't move too fast
# If your code ever gets stuck in an infinite loop you can use cancel its
# execution with Run Menu -> Cancel.
""",
'end': """
# Move the player to the yellow square to complete the level.
"""
}
base_path = os.path.join('gamedata', 'levels', 'basics')
grid_path = os.path.join(base_path, 'grid.png')
player_path = os.path.join(base_path, 'player.png')
endblock_path = os.path.join(base_path, 'end.png')
grid_step = 32
end_pos = Vec2d(0, 0) #updated later
def in_bounds(vec):
return vec.x > grid_step and vec.x < shared.dim.x - grid_step and vec.y > grid_step and vec.y < shared.dim.y - grid_step
# help state info
inoutput = False
invariables = False
inlists = False
inloops = False
oldsize = 0
moved = False
otherdirs = []
def output(s):
global inoutput
global invariables
global oldsize
global inlists
global inloops
userspace.output(s)
if inoutput:
inoutput = False
shared.gui.help_page.append_text(helps['variables'])
oldsize = len(userspace.space)
invariables = True
elif invariables and len(userspace.space) > oldsize:
invariables = False
shared.gui.help_page.append_text(helps['lists'])
inlists = True
elif inlists and type(s) == list:
inlists = False
shared.gui.help_page.set_text(helps['loops'])
inloops = True
# the main level class
class Main(Level):
# called in the beginning of the game
def __init__(self):
Level.__init__(self)
self.name = "Basics 1"
self.data.completed = False
self.won = False
# called when the level starts
def start(self):
global inoutput
inoutput = False
global invariables
invariables = False
global inlists
inlists = False
global inloops
inloops = False
global moved
moved = False
global otherdirs
otherdirs = []
end_pos = shared.dim + Vec2d(200, 200)
shared.gui.help_page.set_text(helps['move'])
# use our own output function
userspace.space['output'] = output
# make the background grid
objects.create(image.Image, grid_path, (0, 0))
# make the player
player = objects.create(_Player, grid_step * Vec2d(5.5, 5.5))
userspace.space['player'] = player.proxy
# called each step during the level
def step(self, elapsed):
pass
# called on pygame events
def event(self, event):
pass
# called when the level ends
def stop(self):
objects.destroy_all()
userspace.space['output'] = userspace.output #restore output()
if not self.won:
shared.gui.help_page.clear_text()
# Player interface visible to user code
class Player:
def move(self, dirstr):
global moved
global otherdirs
global inloops
player = objects.proxy_map[self]
dirs = { 'left': Vec2d(-grid_step, 0), 'right': Vec2d(grid_step, 0),
'up': Vec2d(0, -grid_step), 'down': Vec2d(0, grid_step) }
vec = dirs.get(dirstr)
if vec:
if not moved:
otherdirs = list(dirs.iterkeys())
otherdirs.remove(dirstr)
shared.gui.help_page.append_text(
helps['otherdirs'] % tuple(otherdirs))
moved = True
elif dirstr in otherdirs:
shared.gui.help_page.append_text(helps['output'])
global inoutput
inoutput = True
otherdirs = []
elif inloops:
shared.gui.help_page.set_text(helps['end'])
global end_pos
end_pos = shared.dim - grid_step * Vec2d(6, 6)
objects.create(image.Image, endblock_path, end_pos)
inloops = False
player.move(vec)
# check if we won
pos = player.pos
if (pos.x > end_pos.x and pos.x < end_pos.x + grid_step
and pos.y > end_pos.y and pos.y < end_pos.y + grid_step):
shared.levelmgr.get_current_level().data.completed = True
shared.levelmgr.get_current_level().won = True
shared.levelmgr.request_next_level()
shared.gui.help_page.set_text("# Well done! You completed 'Basics 1'")
else:
userspace.output("Error: '%s' is not a valid direction!" % (dirstr))
# internal Player
class _Player:
proxy_type = Player
# object events
def __init__(self, proxy, pos):
self.pos = Vec2d(pos)
self.sprite = pygame.image.load(player_path)
def destroy(self):
del userspace.space['player']
def step(self, elapsed):
pass
def draw(self):
# our origin is at 16, 16 relative to the image (on the center)
shared.canvas.blit(self.sprite, self.pos - grid_step * Vec2d(0.5, 0.5))
# player functions
def move(self, vec):
new = self.pos + vec
if (in_bounds(new)):
self.pos = new
|
f03292811c97cb9d40b68f82e2a7d8ae29470310 | guissebr/coding-challenges | /palindrome.py | 274 | 4.0625 | 4 | word = 'HannaH'
#recursive approach
def isPalindrome(x):
if len(x) < 2: return True
if x[0] != x[-1]: return False
return isPalindrome(x[1:-1])
print isPalindrome(word)
#non-recursive approach
isPalindrome = word == word[::-1]
print isPalindrome
print -2%2 |
88b8bd18d24712787d55e71da10058d0f1cf18ff | liuluyang/mk | /py3-study/函数编程课上代码/1902/11-04/月考试题及答案_1902_1102.py | 5,782 | 3.625 | 4 |
"""
月考
"""
"""
注:
每个题单独定义一个函数
如果标明需要返回值的,必须要有返回值
"""
"""
第一题:
返回一个列表
列表包含数字、字符串、列表、元祖、字典、集合六种数据
"""
def func_01():
result = [1, 'abc', [1, 2, 3], (1, 2, 3), {1:2, 3:4}, {1, 2}]
return result
"""
第二题:
s = 'k1:v1|| k2:v2|||k3:v3| |k4:v4'
s_new = 'k1:v1,k2:v2,k3:v3,k4:v4'
把字符串s处理成一个新的字符串s_new并返回
"""
def func_02():
s = 'k1:v1|| k2:v2|||k3:v3| |k4:v4'
result = s.replace('|', ' ').split()
result = ','.join(result)
return result
# func_02()
"""
第三题:
lst = [1, 2, 3, 'a', 4, 'b', 5]
计算列表lst里面所有数字的和
并返回计算结果
"""
def func_03():
lst = [1, 2, 3, 'a', 4, 'b', 5]
count = 0
for n in lst:
if isinstance(n, int):
count += n
return count
# func_03()
"""
第四题:
lst = [['老王', '开车'], ['去', '上班!']]
text = '老王开车去上班!'
把列表lst转换成字符串text并返回
"""
def func_04():
lst = [['老王', '开车'], ['去', '上班!']]
text = ''
for per in lst:
text += ''.join(per)
return text
# func_04()
"""
第五题:
用循环打印出下面的菱形:大小不必完全一样
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
"""
def func_05(num):
nums_01 = list(range(1, num, 2))
nums_02 = nums_01[::-1][1:]
for i in nums_01+nums_02:
print(('*'*i).center(num))
# func_05(10)
"""
第六题:
找出工资最高的人,并返回他的名字
data = {'佩奇':5000, '老男孩':6000, '海峰':7000, '马JJ':8000, '老村长':9000, '黑姑娘':10000}
"""
def func_06():
data = {'佩奇': 5000, '老男孩': 6000, '海峰': 7000, '马JJ': 8000, '老村长': 9000,
'黑姑娘': 10000}
max_salary = 0
result = None
for name, salary in data.items():
if salary > max_salary:
result = name
return result
# func_06()
#
"""
第七题:
读取user_info.txt的信息
当输入某个人的姓名时,打印出这个人的电话号码
注:当输入的人名不存时程序不能出错,可以返回提示信息
"""
def func_07():
with open('file/user_info.txt', 'r', encoding='utf8') as f:
info_dict = {}
for line in f:
line_lst = line.split()
info_dict[line_lst[0]] = line_lst[-1]
while True:
name = input('请输入要查询的名字:')
if name == 'q':
break
print(info_dict.get(name, '未找到!'))
# func_07()
#
"""
第八题:
工资单.txt 里面姓名是三个字的,他们工资的总和是多少,返回工资总和
"""
def func_08():
with open('file/工资单.txt', 'r', encoding='utf8') as f:
f.readline()
salary_all = 0
for line in f:
line_lst =line.split()
if len(line_lst[0]) == 3:
salary_all += int(line_lst[-1])
return salary_all
# func_08()
#
"""
第九题:
我的作品_打乱.txt 里面是被打乱的作品
需要最后整理成 我的作品_整理.txt 的样子
"""
def func_09():
with open('file/我的作品_打乱.txt', 'r', encoding='utf8') as f:
data = {}
for line in f:
line_lst = line.split('.')
data[line_lst[0]] = line
with open('file/我的作品_new.txt', 'w', encoding='utf8') as f_new:
for k in sorted(data.keys()):
f_new.write(data[k])
# func_09()
#
"""
第十题:
从车牌号.txt 文件里面找出所有符合要求的车牌号,
判断一下符合规范的车牌里面,号码是否全部都不一样
如果全部不一样返回True
否则返回False
"""
def func_10():
with open('file/车牌号.txt', 'r', encoding='utf8') as f:
cards = []
for card in f.read().split():
if not card.isdigit() and not card.isalpha():
cards.append(card)
return len(cards) == len(set(cards))
# print(func_10())
"""
第十一题:
写个函数
每次调用该函数返回一个符合要求的车牌号
车牌号要求:
五位数、必须同时包含数字和大写字母
"""
def func_11():
import random
import string
params = string.ascii_uppercase + string.digits
while True:
card = ''
for i in range(5):
card += random.choice(params)
if not card.isdigit() and not card.isalpha():
return card
# print(func_11())
"""
第十二题:
把一百个不同的符合要求的车牌号写入文件
要求:每行十个,每个车牌号之间用空格隔开
"""
def func12():
with open('file/cards.txt', 'w', encoding='utf8') as f:
cards_set = set()
while True:
cards_set.add(func_11())
if len(cards_set) == 100:
break
for i in range(10):
cards = [cards_set.pop() for i in range(10)]
f.write(' '.join(cards) + '\n') |
c4857e5f615c6642eb904b4ce2919d909844220c | 99ashr/PyCode | /Basics_of_python/Generators/generator expression.py | 875 | 4.59375 | 5 | #!/usr/bin/env python3
#* --------------------------- Generator Expression --------------------------- #
# ! Just like lambda function and list comprehension generator expressions are used to create anonymous generator function.
# ---------------------------------------------------------------------------- #
#* ---------------------------- list comprehension ---------------------------- #
# r = [u+2 for u in range(6, 0, -1)]
# print("r:", r)
a = range(6, 0, -1)
print("Generator expression", end=":\t")
c = (x+2 for x in a)
print(c) # This is gonna give the generator function id as output
# print(min(c)) # Minimum of all the numbers
# To get the result out of a generator expression use a for loop
print("Generator Expression Output: ")
for r in c:
print(r)
#* ------------------------------------ EOF ----------------------------------- #
|
3e230146f4c70f5c4e26b71288f063c4385baa76 | alexarirok/functions-in-python | /fun3.py | 185 | 4 | 4 | x=int(input("Place a value "))
y=int(input("Place a second value "))
z=int(input("Place a third value "))
def average(x, y, z):
k=x+y+z
avg=k/3
print(avg)
average(x, y, z) |
f8f820892a1923e41777b3d15bc0ca409bc2f18d | jonojace/tensorflow-models | /eager_tutorial/3_custom_training_basics_keras_layers.py | 2,752 | 4.25 | 4 | import matplotlib.pyplot as plt
import tensorflow as tf
tf.enable_eager_execution()
#using python state
x = tf.zeros([10, 10])
x += 2
print(x)
#x here is a tensor, which are immutable stateless objects
#tensorflow has variables that are mutable and stateful objects
v = tf.Variable(1.0)
assert v.numpy() == 1.0
#re-assign the value
v.assign(3.0)
assert v.numpy() == 3.0
#use 'v' in a tensorflow operation like tf.square() and reassign
v.assign(tf.square(v))
assert v.numpy() == 9.0
'''
Example: Fitting a linear model
In this tutorial, we'll walk through a trivial example of a simple linear
model: f(x) = x * W + b, which has two variables - W and b. Furthermore,
we'll synthesize data such that a well trained model would have W = 3.0
and b = 2.0.
'''
class LinearModel(tf.keras.Model):
def __init__(self):
super(LinearModel, self).__init__()
self.dense = tf.keras.layers.Dense(1)
def __call__(self, inputs, training=False):
return self.dense(inputs)
model = LinearModel()
model(tf.zeros([1]))
assert model(3.0).numpy() == 15.0
#we define a loss fn
def loss(predicted_y, desired_y):
return tf.reduce_mean(tf.square(predicted_y - desired_y))
#we synthesise the training data with some noise
TRUE_W = 3.0
TRUE_b = 2.0
NUM_EXAMPLES = 1000
inputs = tf.random_normal(shape=[NUM_EXAMPLES])
noise = tf.random_normal(shape=[NUM_EXAMPLES])
outputs = inputs * TRUE_W + TRUE_b + noise
#before we train the model lets plot the models predictions in red
#and the training data in blue
plt.scatter(inputs, outputs, c='b')
plt.scatter(inputs, model(inputs), c='r')
plt.show()
print('Current loss: ')
print(loss(model(inputs), outputs).numpy())
#we will build up the basic math for gradient descent ourselves
def train(model, inputs, outputs, learning_rate):
with tf.GradientTape() as t:
current_loss = loss(model(inputs), outputs)
dW, db = t.gradient(current_loss, [model.W, model.b])
model.W.assign_sub(learning_rate * dW)
model.b.assign_sub(learning_rate * db)
#now we repeatedly run through the training data and see how W and b evolve
model = Model()
#collect the history of W-values and b-values to plot later
Ws, bs = [], []
epochs = range(10)
for epoch in epochs:
Ws.append(model.W.numpy())
bs.append(model.b.numpy())
current_loss = loss(model(inputs), outputs)
train(model, inputs, outputs, learning_rate=0.1)
#note the use of the new f string
print(
f'Epoch {epoch}: W={Ws[-1]:.2f} b={bs[-1]:.2f}, loss={current_loss:.5f}')
# Let's plot it all
plt.plot(epochs, Ws, 'r',
epochs, bs, 'b')
plt.plot([TRUE_W] * len(epochs), 'r--',
[TRUE_b] * len(epochs), 'b--')
plt.legend(['W', 'b', 'true W', 'true_b'])
plt.show()
|
1d6ac4c9fe5c1d4ed0e859e12bd7c0c01e5410cc | sandeepshiven/python-practice | /functions/pig_latin.py | 403 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 20 23:01:25 2019
@author: sandeep
"""
def pig_latin(word):
first_word = word[0]
if first_word.lower() in 'aeiou':
pig_word = word + 'ay'
else:
pig_word = word[1:] + first_word + 'ay'
return pig_word
print(pig_latin(input("Enter a word to convert into pig latin\n"))) |
c647270b3f2da7502cf6d0a3f41953e270a8fad8 | tunguyen17/python-chat-server | /client.py | 6,728 | 3.640625 | 4 | #!/usr/bin/env python
"""
Python client
Support command-line argument:
-h [host name]
-p [port number]
If no command-line argument is provided the program will use the default values
[host name] = 'localhost'
[port number] = '4213'
"""
#import socket for creating point of connection
import socket
#import thread
from threading import Thread
#import sys for standard inputs
import sys
class Client(object):
def __init__(self, inputPort = 4213):
'A client class that can communicate with a server'
#host name of server
self.host = 'localhost'
#server port
self.port = inputPort
#If there is an inline-command the first argument is the port
self.cmdln = sys.argv
if 1<len(self.cmdln)<6:
hFlag = True
pFlag = True
for i in range(len(self.cmdln)):
#find the host flag
if self.cmdln[i] == '-h' and hFlag:
try:
self.host = self.cmdln[i+1]
hFlag = False
#exception to catch the case when user does not input anything after flag
except IndexError:
print '\033[91mInvalid host name\033[0m'
sys.exit(0)
#find the port flag
if self.cmdln[i] == '-p' and pFlag:
try:
print 'hi'
self.port = int(self.cmdln[i+1])
pFlag = False
#exception to catch the case when user does not input anything after flag and input a non number as port
except (IndexError, ValueError):
print '\033[91mInvalid port number\033[0m'
sys.exit(0)
break
print 'Server address: ', self.host, ':', self.port
#maximum size of data sent
self.size = 1024
#key from server for verification
self.key = '123234123'
#creating a socket
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Status of client
self.run = True
def client_send(self):
'Method to send data. We run this as a thread.'
print 'Sending thread started'
#sending loop
while self.run:
#input message from raw_input
message = raw_input()
#checking terminaltion condition
if message == 'quit()':
#Tell the server that client is quiting
self.client.send(message)
#Close connection, kill the socket
#terminate the sending loop
self.run = False
#sending message
else:
#handeling socket.Error exception
try:
#send message
self.client.send(message)
except socket.error:
print '\033[91m' + 'Unable to send message to server.' + '\033[0m'
#terminate the sending loop
self.run = False
print 'Sending thread ended'
def client_recieve(self):
print 'Recieving socket started'
#recieving loop
while self.run:
#catching exception when recieving data
try:
data = self.client.recv(self.size)
except:
print('\033[91m' + 'Server not responding!' + '\033[0m')
#terminate the sending + recieving thread
self.run = False
#server response the quiting message from user
if data == '!#@quit**':
#terminate the sending + recieving thread
self.run = False
#server closing flag
elif data == '!#@Server**quit*##':
print '\033[91m' + 'Server closed!' + '\033[0m'
print 'Please press ENTER to close sending thread'
#terminate the sending + recieving thread
self.run = False
elif data:
print '\033[1;32m' , ' ', data, '\033[1;m'
print 'Recieving thread stopped'
#################################################
def connect(self):
'Method to connect to server. Return True if connection established'
print('\033[94m' + 'Connecting to server at ' + str(self.host) + ':' + str(self.port) + '\033[0m')
try:
#attempting to connect to server
self.client.connect((self.host,self.port))
#testing server connection
self.client.send('ping')
#server response to test
data = self.client.recv(self.size)
#Checking if server is requesting key
if data == '!#@KeyRequest1213**':
self.client.send(self.key)
#Response from server
data = self.client.recv(self.size)
#Checking server response
if data == 'Client validated!':
#printing server response
print data
print('\33[94m ' + 'Connected to chat server. ') + '\33[0m'
return True
else:
self.client.close()
print 'ERROR:' , data
return False
except socket.error:
print('\33[91m ' + 'Unable to connect to server' + '\33[0m')
def start(self):
#testing connection
self.client.send('SERVER')
data = self.client.recv(self.size)
#Sending username to server
#checking if username is valid
while data!='!#@useraccepted**':
usr = raw_input("Username: ")
while len(usr) < 1:
print 'Invalid username.'
usr = raw_input("Username: ")
self.client.send(usr)
data = self.client.recv(self.size)
if data == '!#@useraccepted**':
print '\33[92mUser accepted\33[0m'
else:
print data
#Starting thread for sending and recieving
thRcv = Thread(target = self.client_recieve)
thSnd = Thread(target = self.client_send)
thSnd.start()
thRcv.start()
#waiting for the sending and recieving thread to reach terminal condition
thSnd.join()
thRcv.join()
#close socket
self.client.close()
print 'Socket killed. Disconnected from server'
#Main method
def main():
student = Client()
if student.connect():
student.start()
#Only run the method within its own module
if __name__ == '__main__':
main()
|
1c5ff3a5c9f85846fbe85d6277f25f6811c15c95 | TetianaSob/Python-Projects | /Generators_Expressions.py | 372 | 3.625 | 4 | # Generators_Expressions.py
def nums():
for num in range(1,10):
yield num
g = nums()
print(next(g)) # 1
print(next(g)) # 2
print(next(g)) # 3
print("\n")
g1 = (num for num in range(1,10))
print(next(g1)) # 1
print(next(g1)) # 2
print(next(g1)) # 3
print("\n")
l = [n for n in range(1,10)]
print(l) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
c9032c7e348f3783cfdaaf2d3a3d049bbfda4e9a | rashed091/Algorithm-and-Data-structures | /Basic/iterator_functions.py | 480 | 3.625 | 4 | from itertools import *
# iter
nums = [1, 2, 3, 4, 5]
iters = [iter(nums)] * 2
print(list(id(itr) for itr in iters))
def better_grouper(inputs, n):
iters = [iter(inputs)] * n
return zip(*iters)
def grouper(inputs, n, fillvalue=None):
iters = [iter(inputs)] * n
return zip_longest(*iters, fillvalue=fillvalue)
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list(better_grouper(nums, 2)))
print(list(better_grouper(nums, 4)))
print(list(grouper(nums, 4)))
|
31c78833e5cb8a5725f23557999523bb99dcf01a | u14e/py-scripts | /leetcode/test_005.py | 668 | 3.65625 | 4 | ###############################################################################
# https://leetcode.com/problems/longest-palindromic-substring/
###############################################################################
def longest_palindromic_substr(s):
m = ''
for i in range(len(s)):
for j in range(len(s), i, -1):
if len(m) > j - i:
break
if s[i:j] == s[i:j][::-1]:
print(i, j)
m = s[i:j]
break
return m
def test_longest_palindromic_substr():
assert longest_palindromic_substr('babad') == 'aba'
assert longest_palindromic_substr('cbbd') == 'bb' |
7f469bb3d7d50f0000b7c08c41c88254b32e90ed | enatielly/studying-python | /usingpackges.py | 1,544 | 4.15625 | 4 | import pandas as pd
csv_path = '/home/enatielly/workspace/studying-python/TopSellingAlbums.csv'
df = pd.read_csv(csv_path)
df.head()
# Access to the column Length
x = df[['Length']]
x
# Get the column as a series
x = df['Length']
x
# Get the column as a dataframe
x = type(df[['Artist']])
x
# Access to multiple columns
y = df[['Artist','Length','Genre']]
y
# Access the value on the first row and the first column
df.iloc[0, 0]
# Access the value on the second row and the first column
df.iloc[1,0]
# Access the value on the first row and the third column
df.iloc[0,2]
# Access the column using the name
df.loc[1, 'Artist']
# Access the column using the name
df.loc[1, 'Artist']
# Access the column using the name
df.loc[0, 'Released']
# Access the column using the name
df.loc[1, 'Released']
# Slicing the dataframe
df.iloc[0:2, 0:3]
# Slicing the dataframe using name
df.loc[0:2, 'Artist':'Released']
# Use a variable q to store the column Rating as a dataframe
q=df[['Rating']]
q
#Assign the variable q to the dataframe that is made up of the column Released and Artist:
q=df[['Released','Artist']]
q
#Access the 2nd row and the 3rd column of df:
df.iloc[1,2]
#Use the following list to convert the dataframe index df to
# characters and assign it to df_new; find the element corresponding to
# the row index a and column 'Artist'. Then select the rows a through d for the column 'Artist'
new_index=['a','b','c','d','e','f','g','h']
df_new=df
df_new.index=new_index
df_new.loc['a','Artist']
df_new.loc['a':'d','Artist']
|
619c4aa77156ed14a370c939c0d69ceb63907429 | dfeusse/2018_practice | /dailyPython/06_june/28_findVowels.py | 1,078 | 4.40625 | 4 | '''
We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters).
So given a string "super", we should return a list of [2, 4].
Some examples:
Mmmm => []
Super => [2,4]
Apple => [1,5]
YoMama -> [1,2,4,6]
NOTE: Vowels in this context refers to English Language Vowels - a e i o u y
NOTE: this is indexed from [1..n] (not zero indexed!)
'''
def vowel_indices(word):
index = 1
answer = []
for i in word:
if i.lower() in ['a', 'e', 'i', 'o', 'u','y']:
answer.append(index)
index += 1
return answer
print vowel_indices('Mmmm')# => []
print vowel_indices('Super') #=> [2,4]
print vowel_indices('Apple' )#=> [1,5]
print vowel_indices('YoMama')# -> [1,2,4,6]
'''
def vowel_indices(word):
return [i+1 for i,c in enumerate(word.lower()) if c in 'aeiouy']
'''
''' The enumerate() function adds a counter to an iterable.
my_list = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(my_list, 1):
print(c, value)
# Output:
# 1 apple
# 2 banana
# 3 grapes
# 4 pear |
0aecd774ab103b7dd3e47409831c3b69b4930475 | rockingrohit9639/GUIdevelopment | /ratings.py | 531 | 3.640625 | 4 | from tkinter import *
import tkinter.messagebox as tmsg
def rate():
print(value.get())
with open("ratings.txt", "a") as f:
f.write(str(value.get()))
f.write("\n")
tmsg.showinfo("Have a nice day.", "Thanks for rating us.")
value.set(0)
root = Tk()
root.geometry("400x200")
root.title("Rating")
value = IntVar()
Label(root, text="Please rate us from (0-10)")
sliderVal = Scale(root, from_=0, to=10,orient=HORIZONTAL, variable=value).pack()
Button(text="Submit", command=rate).pack()
root.mainloop() |
a265787cfb8405962a05d7bbc304bd7095d04984 | raynald/Codeforces | /334/2E.py | 1,348 | 3.71875 | 4 | """
Grundy number and Sprague-Grundy's Theorem
The smallest whole number which is not the Grundy number of any state that can be reached in the next step
Losing if Grundy number is 0
case 1) k is even
f(0) = 0, f(1) = 1, f(2) = 2, f(3) = 0, f(4) = 1
for n >= 2, f(2n-1) = 0, f(2n) = 1
case 2) k is odd
f(0) = 0, f(1) = 1, f(2) = 0, f(3) = 1, f(4) = 2, f(5) = 0, f(6) = 2,
for n >= 2, f(2n) > 0, f(2n + 1) = 0
"""
import sys
def mex(x):
if x == 0:
return 1
if x == 1:
return 2
return 1
def find(x, k):
if k % 2:
if x == 0:
return 0
if x == 1:
return 1
if x == 2:
return 0
if x == 3:
return 1
if x == 4:
return 2
if x % 2:
return 0
else:
return mex(find(x / 2, k))
else:
if x == 0:
return 0
if x == 1:
return 1
if x == 2:
return 2
return (x + 1) % 2
line = sys.stdin.readline()
n, k = line.strip().split(" ")
n = int(n)
k = int(k)
line = sys.stdin.readline()
array = line.strip().split(" ")
ans = -1
for item in array:
item = int(item)
x = find(item, k)
if ans == -1:
ans = x
else:
ans ^= x
if ans == 0:
print "Nicky"
else:
print "Kevin"
|
a0e99ef91a69321faacb8d30398886d13bc22c4e | gsporto/Faculdade | /Prog/Visual/ex01Place.py | 1,163 | 3.5625 | 4 | from tkinter import *
class janela(Tk):
def __init__(self):
super().__init__()
self.title('Janela Principal')
self.minsize(550, 150)
self.configure(bg='#888')
self.inicialize()
def inicialize(self):
lbNome = Label(text='Nome:')
lbTel = Label(text='Telefone:')
lbEmail = Label(text='Email:')
lbEnd = Label(text='Endereço:')
etNome = Entry()
etTel = Entry()
etEmail = Entry()
etEnd = Entry()
lbNome.config(width=25, height=1,font=(None, 10))
lbTel.config(width=25, height=1, font=(None, 10))
lbEmail.config(width=25, height=1, font=(None, 10))
lbEnd.config(width=25, height=1, font=(None, 10))
etEmail.config(width=50)
etNome.config(width=50)
etTel.config(width=50)
etEnd.config(width=50)
lbNome.place(x=0,y=10)
lbTel.place(x=0,y=30)
lbEmail.place(x=0,y=50)
lbEnd.place(x=0,y=70)
etNome.place(x=200,y=10)
etTel.place(x=200,y=30)
etEmail.place(x=200,y=50)
etEnd.place(x=200,y=70)
root = janela()
root.mainloop()
|
9de646ab0c37cbe6d2f01feec0b32591b31a7a50 | sbsdevlec/PythonEx | /Hello/Lecture/Question/1/gugu5.py | 249 | 3.890625 | 4 |
print("-"*190)
for i in range(1,20): print("{0:5d}단 ".format(i), end=" ")
print()
print("-"*190)
for i in range(1,20):
for j in range(1,20):
print("{0:2d}*{1:2d}={2:3d}".format(j,i,i*j), end=" ")
print()
print("-"*190)
|
38a33706a48a6f3e4eec3bc1208d8118bc1295f5 | zhuzhilin3/test | /pytest-demo1/src/testedu/test1.py | 613 | 3.546875 | 4 | #coding=utf-8
def helloword():
print "hello word,你好世界"
def testhello():
print "test hello word"
if __name__ == "__main__":
helloword()
testhello()
a=1
b=input("请输入数字:")
c=a+int(b)
print c
strtemp=""
inputfile=open('input.txt',mode='r')
for line in inputfile.readlines():
strtemp=strtemp+line
print(strtemp)
outputfile=open('outsavefile.txt',mode='w')
outputfile.writelines(strtemp)
outputfile.writelines("\n"+str(c))
outputfile.writelines("\n以上是输出保持的结果")
outputfile.close()
|
ebe7c8d175a09a9aefc956b43a8e2382d73b596d | RokeAbbey/PythohTutol | /c9/new_init_demon.py | 1,666 | 3.703125 | 4 | # coding=utf-8
# the order of init and new
print u'----------------------------'
class A(object):
def __new__(cls):
print u'A.class __new__'
return super(A, cls).__new__(cls)
def __init__(self):
print u'A.class __init__'
self.a = u'a'
class B(A):
def __new__(cls):
print u'B.class __new__'
return super(B, cls).__new__(cls)
def __init__(self):
print u'B.class __init__'
self.b = u'b'
super(B, self).__init__()
b = B()
print b.b
print u'----------------------------'
"""
同个类中的__new__与__init__ 的总参数数量最好一致,其中必填参数的数量必须一致eg: B.__new__ 与 B.__init__
__new__中的参数不会传给__init__ , 我猜测只是各自拿一份copy而已.
执行顺序:先__new__ 后 __init__
"""
class A(object):
def __new__(cls, aa):
print u'A.__new__ : '+unicode(aa)
return super(A, cls).__new__(cls) # aa, 看来new的参数不一定会影响__init__(当然 我也不敢保证不影响)
def __init__(self, aa):
print u'A.__init__ : '+unicode(aa) # bb
self.a = u'a'
class B(A):
def __new__(cls):
print u'B.__new__ : '+unicode(u'bb') # bb
return super(B, cls).__new__(cls, u'aa')
def __init__(self, bb=None, bbb=None):
self.b = u'b'
print u'B.__init__ : '+unicode(bb) # bb
super(B, self).__init__(bb)
b = B() # 不报错
# b = B(u'bb') #报错, 因为b.__new__ 参数表不够
b2 = A.__new__(B, u'aa')
print b2 # 虽然是 B类型, 但是没有b属性
print hasattr(b, u'b')
print hasattr(b2, u'b')
|
efec1d3a6c4987e8b59aad4ca467ca341f91f88f | plelukas/TK | /zad2/AST.py | 3,714 | 3.625 | 4 |
class Node(object):
def __str__(self):
return self.printTree()
class BinExpr(Node):
def __init__(self, op, left, right):
self.op = op
self.left = left
self.right = right
class Const(Node):
def __init__(self, value):
self.value = value
class Integer(Const):
pass
class Float(Const):
pass
class String(Const):
pass
class Variable(Node):
pass
class Program(Node):
def __init__(self, declarations, fundefs, instructions):
self.declarations = declarations
self.fundefs = fundefs
self.instructions = instructions
class Declarations(Node):
def __init__(self):
self.declarations = []
def addDeclaration(self, declaration):
self.declarations.append(declaration)
class Declaration(Node):
def __init__(self, typ, inits):
self.typ = typ
self.inits = inits
class Inits(Node):
def __init__(self):
self.inits = []
def addInit(self, init):
self.inits.append(init)
class Init(Node):
def __init__(self, id, expression):
self.id = id
self.expression = expression
class Instructions(Node):
def __init__(self):
self.instructions = []
def addInstruction(self, instruction):
self.instructions.append(instruction)
class PrintInstruction(Node):
def __init__(self, expressions):
self.expressions = expressions
class LabeledInstruction(Node):
def __init__(self, id, instruction):
self.id = id
self.instruction = instruction
class AssignmentInstruction(Node):
def __init__(self, id, expression):
self.id = id
self.expression = expression
class ChoiceInstruction(Node):
def __init__(self, condition, instruction, instruction2=None):
self.condition = condition
self.instruction = instruction
self.instruction2 = instruction2
class WhileInstruction(Node):
def __init__(self, condition, instruction):
self.condition = condition
self.instruction = instruction
class RepeatInstruction(Node):
def __init__(self, instructions, condition):
self.instructions = instructions
self.condition = condition
class ReturnInstruction(Node):
def __init__(self, expression):
self.expression = expression
class ContinueInstruction(Node):
pass
class BreakInstruction(Node):
pass
class CompoundInstuction(Node):
def __init__(self, declarations, instructions):
self.declarations = declarations
self.instructions = instructions
class Expressions(Node):
def __init__(self):
self.expressions = []
def addExpression(self, expr):
self.expressions.append(expr)
class GroupedExpression(Node):
def __init__(self, interior):
self.interior = interior
class NamedExpression(Node):
def __init__(self, id, expressions):
self.id = id
self.expressions = expressions
class Fundefs(Node):
def __init__(self):
self.fundefs = []
def addFundef(self, fundef):
self.fundefs.append(fundef)
class Fundef(Node):
def __init__(self, type, id, args, compound_instr):
self.id = id
self.type = type
self.args = args
self.compound_instr = compound_instr
class Arguments(Node):
def __init__(self):
self.args = []
def addArgument(self, arg):
self.args.append(arg)
class Argument(Node):
def __init__(self, type, id):
self.type = type
self.id = id
|
9a1bd5aad659c7c3239bf254e469a066be26b5f2 | accuLucca/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1 | /Semana 4/calculadora.py | 302 | 4.125 | 4 | quant = int(input("Digite quantos numeros deverao ser calculados: "))
soma=0
valor=1
if quant != 0:
while (quant != 0):
valor = int(input("Insira Numero: "))
soma = soma + valor
quant = quant - 1
else:
print("Numero negativo Invalido ")
print("Resultado da soma: ",soma) |
7ec13bc97f15809be1101a11554b47275f07656c | izzie1349/SimpleCalculator | /calculator.py | 4,627 | 4.125 | 4 | import math
def addition(num_1, num_2):
return num_1+num_2
def subtraction(num_1, num_2):
return num_1-num_2
def multiplication(num_1, num_2):
return num_1*num_2
def division(num_1, num_2):
return num_1/num_2
def square_root(num_1):
return math.sqrt(num_1)
def mean(num_1, num_2):
return (num_1+num_2)/2
def power(num_1, num_2):
return num_1**num_2
def cosine(num_1):
return math.cos(num_1)
def range_between_operands(num_1, num_2):
range_ = []
for num in range(num_1+1, num_2):
range_.append(num)
return range_
def enter_operands():
operands = {}
try:
operands['num_1'] = int(input('enter first number: '))
operands['num_2'] = int(input('enter second number: '))
except ValueError:
print('Not a valid operand: please input an integer')
return operands
def choose_operation():
valid_operations = ['+', '-', '*', '/', 's', 'm', 'p', 'c', 'r']
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
s for square root
m for mean
p for power
c for cosine
r for range (this prints the numbers exclusive between operands)
''')
for op in valid_operations:
if op == operation:
return op
break
else:
raise Exception("'{}' is not a valid operand: please input a valid operation.".format(operation))
def calculate():
# cal = Calculator()
operand = enter_operands()
operation = choose_operation()
if operation == '+':
sum_ = addition(operand['num_1'], operand['num_2'])
print("{} + {} is: ".format(operand['num_1'],
operand['num_2']), sum_)
elif operation == '-':
difference = subtraction(operand['num_1'], operand['num_2'])
print("{} - {} is: ".format(operand['num_1'],
operand['num_2']), difference)
elif operation == '*':
product = multiplication(operand['num_1'], operand['num_2'])
print("{} * {} is: ".format(operand['num_1'],
operand['num_2']), product)
elif operation == '/':
quotient = division(operand['num_1'], operand['num_2'])
print("{} / {} is: ".format(operand['num_1'],
operand['num_2']), quotient)
elif operation == 's':
try:
sqroot = square_root(operand['num_1'])
print("the square root of {} is: ".format(operand['num_1'], sqroot))
except ValueError:
print('s: square root, does not take in negative numbers')
elif operation == 'm':
avg = mean(operand['num_1'], operand['num_2'])
print("The mean of {} and {} is: ".format(operand['num_1'],
operand['num_2']), avg)
elif operation == 'p':
power_ = power(operand['num_1'], operand['num_2'])
print("{} to the power of {} is: ".format(operand['num_1'],
operand['num_2'], sqroot))
elif operation == 'c':
cos = cosine(operand['num_1'])
print("the cosine of {} is: ".format(operand['num_1'], cos))
elif operation == 'r':
range_ = range_between_operands(operand['num_1'], operand['num_2'])
print("The range between {} and {} exclusive is : ".format(operand['num_1'],
operand['num_2'],
range_))
again()
def again():
calculate_again = input('''
Would you like to use Calculator again?
Y for yes
N for no
''')
# Accept 'y' or 'Y' by adding str.upper()
if calculate_again.upper() == 'Y':
calculate()
# Accept 'n' or 'N' by adding str.upper()
elif calculate_again.upper() == 'N':
print('''
Thanks for using Calculator!
Come back anytime :)
''')
else:
again()
if __name__ == '__main__':
print('''
Welcome to Calculator!
You will be asked to enter two operands and an operation to be performed on
them. For example: <5> and <2>, and <+>, will return <7>. If a particular
operation requires only one operand, it will neglect the second operand
entered. For example: <36> and <2>, and <s> (for square root) will return the
the square root of 36.
''')
calculate()
|
ad6d2f5c29b405c245be357905ee297c49e2c6b5 | jwbaek/Project-Euler | /Python/Euler_40_49.py | 10,557 | 3.875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Jackie
#
# Created: 28/01/2013
# Copyright: (c) Jackie 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
import math
import itertools
from decimal import *
from Common_Functions import *
"""
PROBLEM 40
An irrational decimal fraction is created by concatenating
the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part,
find the value of the following expression.
d1 d10 d100 d1000 d10000 d100000 d1000000
"""
def prob40():
i = 1
li = []
while 1:
li.extend(numToList(i))
if len(li) > 1000000:
break
i += 1
print len(li)
terms = [1,10,100,1000,10000,100000,1000000]
prodSoFar = 1
for num in terms:
prodSoFar *= li[num-1]
return prodSoFar
"""
PROBLEM 41
We shall say that an n-digit number is pandigital if
it makes use of all the digits 1 to n exactly once.
For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
"""
import itertools
def prob41():
maxSoFar = 2143
numdigits = 4
while numdigits < 10:
for li in list(itertools.permutations(range(1,numdigits+1), numdigits)):
currNum = listToNum(li)
if li[-1]%2 == 1 and sum(li)%3 != 0 and isPrime(currNum):
maxSoFar = currNum
numdigits += 1
return maxSoFar
"""
PROBLEM 42
The nth term of the sequence of triangle numbers is given by,
tn = ?n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding
to its alphabetical position and adding these values we form a word value.
For example, the word value for SKY is 19 + 11 + 25 = 55 = t10.
If the word value is a triangle number then we shall call the word
a triangle word.
Using words.txt (right click and 'Save Link/Target As...'),
a 16K text file containing nearly two-thousand common English words,
how many are triangle words?
"""
def prob42():
f = open("C:\Users\Jackie\Documents\Project Euler\Python\prob42.txt", "r")
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet = alphabet.upper()
alphadict= dict((char, alphabet.find(char)+1) for char in alphabet)
wordValues = []
for line in f:
listWords = line.split("\",\"")
listWords[0] = listWords[0][1:]
listWords[-1] = listWords[-1][:-1]
wordValues = [sum([alphadict[char] for char in word]) for word in listWords]
# wordValues is list of values of all words in txt file
# list all triangle numbers below maxValue
maxValue = max(wordValues)
currValue = 1
triangleDict = {} # contains all triangle numbers
i = 2
while currValue <= maxValue:
triangleDict[currValue] = 1
currValue += i
i += 1
# count number of triangle words
triangleWords = 0
for value in wordValues:
if value in triangleDict:
triangleWords += 1
return triangleWords
"""
PROBLEM 43
The number, 1406357289, is a 0 to 9 pandigital number
because it is made up of each of the digits 0 to 9 in some order,
but it also has a rather interesting sub-string divisibility property.
Let d1 be the 1st digit, d2 be the 2nd digit, and so on.
In this way, we note the following:
d2d3d4=406 is divisible by 2
d3d4d5=063 is divisible by 3
d4d5d6=635 is divisible by 5
d5d6d7=357 is divisible by 7
d6d7d8=572 is divisible by 11
d7d8d9=728 is divisible by 13
d8d9d10=289 is divisible by 17
Find the sum of all 0 to 9 pandigital numbers with this property.
"""
def prob43():
digits = [0,1,2,3,4,6,7,8,9]
perm = list(itertools.permutations(digits, 9))
sumSoFar = 0
for num in perm:
num = list(num)
if num[3]%2 != 0:
continue
num.insert(5,5)
if meetsConstraints(num):
sumSoFar += listToNum(num)
return sumSoFar
def meetsConstraints(li):
return listToNum(li[7:10])%17 == 0 and listToNum(li[6:9])%13 == 0 and listToNum(li[5:8])%11 == 0 and listToNum(li[4:7])%7 == 0 and listToNum(li[2:5])%3 == 0
"""
PROBLEM 44
Pentagonal numbers are generated by the formula,
Pn=n(3n-1)/2. The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8.
However, their difference, 70 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk,
for which their sum and difference is pentagonal and
D = |Pk - Pj| is minimised; what is the value of D?
SOLUTION NOT VERY GOOD. (found ONE solution that happened to be right..)
"""
def prob44():
minimum = -1
#pent_numbers = [1, 5, 12]
pent_numbers = [pentNumber(n) for n in range(1,5001)]
n = 4
curr_first = 0
curr_second = 1
for i in pent_numbers:
for j in pent_numbers:
if i != j and diffSumPentagonal(i,j) != -1:
print i,
print j,
print j-i
return
# returns the diff of two pent numbers only if
# both the diff and the sum is pentagonal
# if not, returns -1
def diffSumPentagonal(pent1, pent2):
sumPents = pent1 + pent2
diffPents = abs(pent1 - pent2)
if isPentagonal(sumPents) and isPentagonal(diffPents):
return diffPents
return -1
"""
last = list_pents[-1]
if diffPents not in list_pents:
return -1
elif sumPents < list_pents[-1] and sumPents not in list_pents:
return -1
else:
while last < sumPents:
last = pentNumber(len(list_pents) + 1)
list_pents.append(last)
if last != sumPents:
return -1
return diffPents
"""
def pentNumber(n):
return n*(3*n-1)/2
"""
PROBLEM 45
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n-1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n-1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
"""
def prob45():
n = 144
while True:
curr = n*(2*n -1)
if isPentagonal(curr):
return curr
n += 1
def isPentagonal(n):
x = (math.sqrt(24*n + 1) + 1 )/6
if math.floor(x) == x:
return True
return False
"""
PROBLEM 46
It was proposed by Christian Goldbach that every odd composite number can be written
as the sum of a prime and twice a square.
9 = 7 + 2*1^2
15 = 7 + 222
21 = 3 + 232
25 = 7 + 232
27 = 19 + 222
33 = 31 + 212
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
"""
def prob46():
curr = 9
primes = set([2,3,5,7])
while True:
if isPrime(curr):
primes.add(curr)
else:
if not isGoldbach(curr,primes):
return curr
curr += 2
def isGoldbach(n, primes):
toSquare = 1
twiceSquare = 2*toSquare*toSquare
remaining = n - twiceSquare
while remaining > 0:
if remaining in primes:
return True
toSquare += 1
twiceSquare = 2*toSquare*toSquare
remaining = n - twiceSquare
return False
"""
PROBLEM 47
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 x 7
15 = 3 x 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2? x 7 x 23
645 = 3 x 5 x 43
646 = 2 x 17 x 19.
Find the first four consecutive integers to have four distinct primes factors.
What is the first of these numbers?
"""
def prob47():
i = 124914
primes = [2,3,5,7]
while True:
if lenprimeFactors(i) != 4:
i += 1
continue
elif lenprimeFactors(i + 1) != 4:
i += 2
continue
elif lenprimeFactors(i + 2) != 4:
i += 3
continue
elif lenprimeFactors(i + 3) != 4:
print i
i += 4
continue
return i
def lenPrimeFactors(n):
return len(set(prime_factors(n)))
# taken off stackoverflow
def prime_factors(n):
factors = []
d = 2
while (n > 1):
while (n%d==0):
factors.append(d)
n /= d
d = d + 1
if (d*d>n):
if (n>1): factors.append(n);
break;
return factors
"""
PROBLEM 48
The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
"""
def prob48():
sumSoFar = 0
for i in range(1,1001):
sumSoFar += i**i
sumSoFar %= 10000000000
return sumSoFar
"""
PROBLEM 49
The arithmetic sequence, 1487, 4817, 8147,
in which each of the terms increases by 3330, is unusual in two ways:
(i) each of the three terms are prime, and,
(ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes,
exhibiting this property, but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?
"""
def prob49():
curr = 1000
primesTo= prime_sieve(10000)
primesUnder = prime_sieve(1000)
primes = primesTo - primesUnder
primes -= set([1487, 4817, 8147])
for p in primes:
found = [p]
for p2 in primes:
if p != p2 and isAnagram(p,p2):
found.append(p2)
if len(found) >= 3:
seq = isArithmetic(found)
if seq:
return seq
def isAnagram(a,b):
return sorted(str(a)) == sorted(str(b))
def isArithmetic(li):
li.sort()
for seq in itertools.combinations(li,3):
if (seq[1] - seq[0]) == (seq[2] - seq[1]):
return seq
return False
|
6d8a97cfd339cafcbb534992c87bde63f1d42940 | vakhnin/geekbrains-python | /homeWork2/normal/task.py | 4,618 | 4.4375 | 4 | # Задача-1:
# Дан список, заполненный произвольными целыми числами, получите новый список,
# элементами которого будут квадратные корни элементов исходного списка,
# но только если результаты извлечения корня не имеют десятичной части и
# если такой корень вообще можно извлечь
# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] Результат: [3, 5, 2]
import math
print("\nЗадача-1\n")
numArr = [2, -5, 8, 9, -25, 25, 4]
resArr = []
for num in numArr:
if num >= 0:
sqrtNum = math.sqrt(num)
if sqrtNum == int(sqrtNum):
resArr.append(int(sqrtNum))
print("Массив круглых корней: ", resArr)
# Задача-2: Дана дата в формате dd.mm.yyyy, например: 02.11.2013.
# Ваша задача вывести дату в текстовом виде, например: второе ноября 2013 года.
# Склонением пренебречь (2000 года, 2010 года)
print("\nЗадача-2\n")
days = ("первое",
"второе",
"третье",
"четвертое",
"пятое",
"шестое",
"седьмое",
"восьмое",
"девятое",
"десятое",
"одиннадцатое",
"двенадцатое",
"тренадцатое",
"четырнадцатое",
"пятнадцатое",
"шестнадцатое",
"семьнадцатое",
"восемьнадцатое",
"девятнадцатое",
"двадцатое")
months = ("января",
"февраля",
"марта",
"апреля",
"мая",
"июня",
"июля",
"августа",
"сентября",
"октября",
"ноября",
"декабря")
datesArr = ("02.11.2013", "20.05.2000", "21.01.2007", "23.03.1999", "29.12.2010", "31.12.2011", "30.10.2015")
for date in datesArr:
if len(date.split(".")) != 3:
print("Ошибка во входных данных: ", date)
break
day, month, year = date.split(".")
day = int(day) - 1
month = int(month) - 1
if day < 20:
dayStr = days[day]
elif day < 29:
dayStr = "двадцать " + days[day - 20]
elif day == 29:
dayStr = "тридцатое"
elif day == 30:
dayStr = "тридцать первое"
else:
print("Ошибка во входных данных: ", date)
break
print(f"{date}: {dayStr} {months[month]} {year} года")
# Задача-3: Напишите алгоритм, заполняющий список произвольными целыми числами
# в диапазоне от -100 до 100. В списке должно быть n - элементов.
# Подсказка:
# для получения случайного числа используйте функцию randint() модуля random
import random # Про то, что import нужно помещать в начало кода знаю. Перенес import ближе к задаче для наглядности.
print("\nЗадача-3\n")
n = 15
randNumbersArr = []
for _ in range(n):
randNumbersArr.append(random.randint(-100, 100))
print(randNumbersArr)
# Задача-4: Дан список, заполненный произвольными целыми числами.
# Получите новый список, элементами которого будут:
# а) неповторяющиеся элементы исходного списка:
# например, lst = [1, 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 2, 4, 5, 6]
# б) элементы исходного списка, которые не имеют повторений:
# например, lst = [1 , 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 4, 6]
print("\nЗадача-4\n")
lst = [1, 2, 4, 5, 6, 2, 5, 2]
print("Элементы списка, без повторов:")
print(set(lst))
notDoubleItemsArr = []
for item in set(lst):
if lst.count(item) == 1:
notDoubleItemsArr.append(item)
print("Элементы списка, которые не имеют повторений:")
print(notDoubleItemsArr)
|
c6ca9b599131eb992bad48984f358d1d61aebedb | sajadtorkamani/python-katas | /remove_letter/solution.py | 197 | 3.8125 | 4 | def remove_letter(string, n):
result = string
letters_to_remove = sorted(string)[:n]
for letter in letters_to_remove:
result = result.replace(letter, '', 1)
return result
|
c98148d7ebc9ea4ef18a104c316b1a9c5f690b82 | slothman5566/TDDPractice | /32. Longest Valid Parentheses/test.py | 1,011 | 3.703125 | 4 | import unittest
from main import Solution
class ExampleCase(unittest.TestCase):
def setUp(self):
self.testObject=Solution()
def test_case_1(self):
input= "(()"
target=2
self.assertEqual(target,self.testObject.longestValidParentheses(input),"The longest valid parentheses substring is ()")
def test_case_2(self):
input= ")()())"
target=4
self.assertEqual(target,self.testObject.longestValidParentheses(input),"The longest valid parentheses substring is()()")
def test_case_3(self):
input= "()(()"
target=2
self.assertEqual(target,self.testObject.longestValidParentheses(input),"The longest valid parentheses substring is()")
def test_case_4(self):
input= ")()())()()("
target=4
self.assertEqual(target,self.testObject.longestValidParentheses(input),"The longest valid parentheses substring is ()()")
if __name__ == '__main__':
unittest.main() |
7e38d21a8900aca5912a81e43e97dd5bde25fc34 | githubvit/study | /hfpython/day21/01 组合.py | 1,507 | 4.34375 | 4 | # 解决类与类之间代码冗余问题有两种解决方案:1、继承 2、组合
# 1、继承:描述的是类与类之间,什么是什么的关系
# 2、组合:描述的是类与类之间的关系,是一种什么有什么关系
# 一个类产生的对象,该对象拥有一个属性,这个属性的值是来自于另外一个类的对象
class Date:
def __init__(self,year,mon,day):
self.year = year
self.mon = mon
self.day = day
def tell_birth(self):
print('出生年月日<%s-%s-%s>' % (self.year, self.mon, self.day))
class OldboyPeople:
school = 'oldboy'
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
class OldboyTeacher(OldboyPeople):
def __init__(self,name,age,sex,level,salary):
super().__init__(name,age,sex)
self.level=level
self.salary=salary
def change_score(self):
print('teacher %s is changing score' %self.name)
class Oldboystudent(OldboyPeople):
def __init__(self,name,age,sex,course,):
super().__init__(name,age,sex,)
self.course=course
def choose(self):
print('student %s choose course' %self.name)
tea1=OldboyTeacher('egon',18,'male',9,3.1)
date_obj=Date(2000,1,1)
# date_obj.tell_birth()
tea1.birth=date_obj
# print(tea1.birth)
# tea1.birth.tell_birth()
# tea1.change_score()
stu1=Oldboystudent('张三',16,'male','linux')
stu1.birth=Date(2002,3,3)
stu1.birth.tell_birth()
|
a09c555213f4d850b0f3f3a45ae3150f23041e35 | rogatka/data-structures-and-algorithms | /interview/coding/hard/shortest-path-obstacle-avoidance.py | 3,645 | 4.09375 | 4 | '''Find the shortest path between two points in an nxn matrix with obstacles. The starting point A can be anywhere in
the matrix, and the end point B can be anywhere in the matrix. The matrix is filled with Os and Xs. Os represent open
spaces that can be moved to, and Xs represent obstacles that are not available. Valid movements are
left, right, up, or down.'''
from data_structures.graphs.adjacency_matrix import AdjacencyMatrix
import operator
import sys
def gridToGraph(matrix):
'''Converts 2D array to adjacency matrix'''
n = len(matrix)
graph = AdjacencyMatrix(n)
for i in range(n):
for j in range(n):
if matrix[i][j] == "O":
graph.addEdge(i, j)
return graph
def heuristic(start, end):
'''Manhattan Distance heuristic'''
return abs(start[0]-end[0]) + abs(start[1]-end[1])
def path(cameFrom, current):
'''Recreates path'''
totalPath = [current]
while current in cameFrom.keys():
current = cameFrom[current]
totalPath.append(current)
return totalPath
def aStar(start, end, graph):
'''A* Search Algorithm'''
# Evaluated nodes
closedSet = set()
# Unevaluated nodes
openSet = set()
openSet.add(start)
# Most efficient way to reach node
cameFrom = {}
# Cost of getting to each node from start node
# Initially cost of getting to any node is infinite, except for start
gScore = {}
for i in range(len(graph)):
for j in range(len(graph)):
gScore[(i, j)] = sys.maxsize
# Cost of getting to goal node from start node
fScore = gScore
gScore[start] = 0
fScore[start] = heuristic(start, end)
while openSet is not None:
current = None
tmp = sorted(fScore.items(), key=operator.itemgetter(1))
for i in tmp:
if i[0] in openSet:
current = i[0]
break
#current = min(key for key, value in fScore.items() if key in openSet)
if current == end:
return path(cameFrom, current)
openSet.remove(current)
closedSet.add(current)
currentNeighbors = [(current[0]+1, current[1]), (current[0], current[1]+1),(current[0]-1, current[1]), \
(current[0], current[1]-1),]
for neighbor in currentNeighbors:
if neighbor in closedSet:
continue # Ignore evaluated neighbors
if not graph.hasEdge(neighbor[0], neighbor[1]):
continue
if neighbor[0] < 0 or neighbor[1] < 0 or neighbor[0] > len(graph)-1 or neighbor[1] > len(graph)-1:
continue
tmp_gScore = gScore[current]+1 # Assumption is that graph is unweighted
# If graph is weighted, adjust tmp_gScore to variable cost
if neighbor not in openSet: # New node discovered
openSet.add(neighbor)
elif tmp_gScore >= gScore[neighbor]: # Ignore more expensive paths
continue
# Running best path
cameFrom[neighbor] = current
gScore[neighbor] = tmp_gScore
fScore[neighbor] = gScore[neighbor] + heuristic(neighbor, end)
return -1
# Example test case
if __name__ == "__main__":
testMatrix = [['X', 'X', 'O', 'X', 'X', 'X'], ['O', 'O', 'O', 'X', 'X', 'O'], ['O', 'X', 'O', 'O', 'O', 'O'], \
['O', 'X', 'X', 'O', 'X', 'X'], ['O', 'O', 'O', 'O', 'X', 'O'], ['O', 'X', 'O', 'O', 'O', 'O']]
test = gridToGraph(testMatrix)
print(aStar((0,2), (5,5), test)) |
569097f274ccf72c9c8f8c30be3f2217e5fbdf0f | aqutw/python_01_practice | /10-1gen_list.py | 229 | 3.78125 | 4 | print range(1, 11)
a = []
for v in xrange(1,11):
a.append(v*v)
print a
print 'More shorten way....'
print [x * x for x in range(1, 11)]
print '---do Task---'
print range(1,100,2)
print [ x*(x+1) for x in range(1,100,2) ]
|
d1e22397748a6f7992252f02022496b6cfb072bc | macWeinstock/Dynamic_Programming | /dynProg.py | 2,240 | 3.859375 | 4 | #This program uses dynamic programming to find whether a single string can be broken up
#into english words
#Author: Mac Weinstock
#USAGE: python3 dynProg.py < [FILENAME]
import sys
#Read in 10k word dictionary
def readDict(file):
tempDict = []
f = open(file, "r")
for line in f:
tempDict.append(line)
f.close()
return tempDict
#Store dictionary globally to improve performance (only need to read once)
dictList = readDict("dictionary_10k_sample/diction10k.txt")
#Search the dictionary for desired word
def dictSearch(w):
for word in dictList:
word = word.strip()
if w == word:
return True
return False
#Iterative method to split each word provided
def split(string):
n = len(string)
splitAt = []
splArr = []
#Append the split word to stored array and the index of the split to another array
for i in range(0,n):
splArr.append(-1)
splitAt.append(0)
splArr.append(1)
for i in range(n-1, -1, -1):
splArr[i] = 0
for j in range(i, n):
if (splArr[j+1] == 1) and (dictSearch(string[i:j+1]) == True):
splArr[i] = 1
splitAt[i] = j+1
return splArr, splitAt
# def memo(i, phrase):
# n = len(phrase)
# splitAt = []
# splArr = []
# for i in range(0,n):
# splArr.append(-1)
# splitAt.append(0)
# splArr.append(1)
# if splArr[i] == 1:
# return True
# if splArr[i] == 0:
# return False
# if splArr[i] == -1:
# for j in range(i, n-1):
# if memo(j+1, phrase) and dictSearch(phrase[i:j+1]):
# splitArr[i] = 1
# splitAt[i] = j+1
# return splArr, splitAt
def main(file):
strList = []
fLen = file[0]
#Parse the provided file
for line in file[1:]:
line = line.strip()
strList.append(line)
i = 1
#Print the desired output of split array into single words
for line in strList:
l = len(line)
print(f"Phrase {i}:\n{line}\n")
print("Iterative attempt:")
res, splitAt = split(line)
if res[0] == 1:
print("YES, can be split\n")
print("===== words are below =====")
for j in range(0, len(splitAt)):
if splitAt[j] != 0:
print(line[j:splitAt[j]])
print("============================\n")
else:
print("NO, cannot be split\n")
i += 1
return 0
if __name__ == "__main__":
main(sys.stdin.readlines())
|
e8b04d9d4515beeeb8bee64d0986483fe4b59175 | zubie7a/Algorithms | /HackerRank/Python_Learn/03_Strings/04_String_Mutations.py | 308 | 3.84375 | 4 | # https://www.hackerrank.com/challenges/python-mutations
def mutate_string(string, position, character):
# Strings are immutable, so find out a way to modify a char.
l = list(string)
l[position] = character
# return "".join(l)
return string[:position] + character + string[position + 1:]
|
971c089cc6a15611d3c963252923aa6c9f349266 | wxhheian/ptcb | /ch1/ex1.3a.py | 3,130 | 4.21875 | 4 | #deque对象,是一个新的双向队列对象,类似于list对象
#class collections.deque([iterable[,maxlen]])
#如果maxlen没有指定,则deques可以增加到任意长度,否则限定长度。当限定长度的deque满了,当新项加入时,同样数量的项就从另一端弹出
###################双向队列(deque)对象支持以下方法:#############
#append(x) 添加x到右端
#appendleft(x) 添加x到左端
#clear() 移除所有元素
#copy() 创建一份浅拷贝
#count(x) #计算deque中x元素的个数
#extend(iterable) #拓展deque的右侧,通过添加iterable参数中的元素
#extendleft(iterable) #注意参数顺序被反过来添加
#index(x[,start[,stop]]) #返回第 x 个元素(从 start 开始计算,在 stop 之前)。返回第一个匹配,如果没找到的话,升起 ValueError 。
#insert(i,x) #在位置i插入x
#pop() popleft()
#remove(value) #移除找到的第一个value
#reversed() #将deque逆序排列
#rotate(1) #向右循环移动n步 rotate(1) #向左循环1步
#maxlen #Deque的最大长度
###################################################
>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements
... print(elem.upper())
G
H
I
>>> d.append('j') # add a new entry to the right side
>>> d.appendleft('f') # add a new entry to the left side
>>> d # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
>>> list(d) # list the contents of the deque
['g', 'h', 'i']
>>> d[0] # peek at leftmost item
'g'
>>> d[-1] # peek at rightmost item
'i'
>>> list(reversed(d)) # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d # search the deque
True
>>> d.extend('jkl') # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1) # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1) # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> deque(reversed(d)) # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear() # empty the deque
>>> d.pop() # cannot pop from an empty deque
Traceback (most recent call last):
File "<pyshell#6>", line 1, in -toplevel-
d.pop()
IndexError: pop from an empty deque
>>> d.extendleft('abc') # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])
>>> new=deque(d,3)
>>> new
deque(['c', 'c', 1], maxlen=3)
>>> new.append('a')
>>> new
deque(['c', 1, 'a'], maxlen=3)
>>>q=deque(maxlen=3) #创建一个长度为3的队列
|
5173f11b91ecec0efa68df75aba700ce7e76c544 | rafaelperazzo/programacao-web | /moodledata/vpl_data/8/usersdata/86/4113/submittedfiles/imc.py | 383 | 3.875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
#entrada
p = input('digite o valor do peso em kilos:')
a = input('digite o valor da altura em metros:')
imc = p/(a**2)
if imc<20:
print('ABAIXO')
elif 20<=imc<=25:
print('NORMAL')
elif 25<=imc<=30:
print('SOBREPESO')
elif 30<=imc<=40:
print('OBESIDADE')
elif imc>=40:
print('OBESIDADE GRAVE')
|
aa7e778dd077ad5141cd360e93b3dfeeade55f1f | PutuGdeUKDW/UG9_B_71210816 | /3_B_71210816.py | 189 | 3.8125 | 4 | A = int(input("Nilai 1 : "))
B = int(input("Nilai 2 : "))
C = int(input("Nilai 3 : "))
hasil = (A+B+C)/3
print("Rata-Rata dari {A}+{B}+{C} adalah ".format(A=A, B=B, C=C), hasil)
|
f793dd69ee9bbda24f0ea5a86216a4e583ef887c | quinn3111993/nguyenphuongquynh-fundamental-c4e21 | /session2/homework/hw3_BMI.py | 424 | 4.1875 | 4 | #Write a program that asks user their height (cm) and weight (kg), and then calculate their BMI
h = int(input("Your height (cm): "))
w = int(input("Your weight (kg): "))
h_m = h/100
bmi_index = w/(h_m**2)
if bmi_index < 16:
print("Severely underweigh!")
elif bmi_index < 18.5:
print("Underweight!")
elif bmi_index < 25:
print("Normal!")
elif bmi_index < 30:
print("Overweight!")
else:
print("Obese!")
|
46b3ff889c72f3317c2a4f7ae7beab34e7a62267 | CodeForContribute/Algos-DataStructures | /TreeCodes/checking&Printing/leaf_traversal_bt_same_or_not.py | 1,671 | 3.625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def isLeaf(root):
if not root:
return
return (root.left is None) and (root.right is None)
def isSameLeafTraversal(root1, root2):
if not root1 or not root2:
return False
stack1 = list()
stack2 = list()
stack1.append(root1)
stack2.append(root2)
while len(stack1) or len(stack2):
if len(stack1) == 0 or len(stack2) == 0:
return False
temp1 = stack1.pop()
while temp1 is not None and not isLeaf(temp1):
if temp1.right:
stack1.append(temp1.right)
if temp1.left:
stack1.append(temp1.left)
temp1 = stack1.pop()
temp2 = stack2.pop()
while temp2 is not None and not isLeaf(temp2):
if temp2.right:
stack2.append(temp2.right)
if temp2.left:
stack2.append(temp2.left)
temp2 = stack2.pop()
if not temp2 or not temp1:
return False
if temp1 and temp2:
if temp1.data != temp2.data:
return False
return True
if __name__ == '__main__':
root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.right.left = Node(6)
root1.right.right = Node(7)
root2 = Node(0)
root2.left = Node(1)
root2.right = Node(5)
root2.left.right = Node(4)
root2.right.left = Node(6)
root2.right.right = Node(7)
if isSameLeafTraversal(root1, root2):
print("Same")
else:
print("Not Same")
|
d1d8cd31f9024a8123f2d6a2fb55a226a61dd5b3 | thestud/BlackJack | /Card.py | 2,394 | 3.78125 | 4 | class Card():
"""docstring for Card"""
def __init__(self,number,suite,face_card):
self.number = number
self.suite = suite
self.face_card = face_card
@staticmethod
def getSuite(index):
SUITE_HEARTS = "HEARTS"
SUITE_DIAMONDS = "DIAMONDS"
SUITE_SPADES = "SPADES"
SUITE_CLUBS = "CLUBS"
if index == 1:
return SUITE_HEARTS
if index == 2:
return SUITE_DIAMONDS
if index == 3:
return SUITE_SPADES
if index == 4:
return SUITE_CLUBS
@staticmethod
def getFaceCard(index):
FACE_CARD_KING = "KING"
FACE_CARD_QUEEN = "QUEEN"
FACE_CARD_JACK = "JACK"
if index == 11:
return FACE_CARD_JACK
if index == 12:
return FACE_CARD_QUEEN
if index == 13:
return FACE_CARD_KING
def __str__(self):
if self.number == 1:
name_of_card = "Ace"
elif self.number > 10:
name_of_card = self.face_card
else:
name_of_card = str(self.number)
return name_of_card + " of " + self.suite
def formatNumber(self,number):
if number < 10:
return " " + str(number)
else:
return str(number)
def formatCardNumber(self):
if self.number < 11:
return self.formatNumber(self.number)
return self.face_card
def formatTopRow(self):
if self.number < 10:
print("|" + str(self.number) + " |")
elif self.number == 10:
print("|" + str(self.number) + " |")
elif self.number == 11:
print("|" + self.face_card + " |")
elif self.number == 12:
print("|" + self.face_card + " |")
elif self.number == 13:
print("|" + self.face_card + " |")
def formatBottomRow(self):
if self.number < 10:
print("| " + str(self.number) + "|")
elif self.number == 10:
print("| " + str(self.number) + "|")
elif self.number == 11:
print("| " + self.face_card + "|")
elif self.number == 12:
print("| " + self.face_card + "|")
elif self.number == 13:
print("| " + self.face_card + "|")
def formatSuites(self):
if self.suite == Card.getSuite(2):
print("|DIAMON|")
elif self.suite == Card.getSuite(4):
print("|" + self.suite + " |")
else:
print("|" + self.suite + "|")
def displayCard(self):
print("/------\\")
self.formatTopRow()
print("| |")
self.formatSuites()
self.formatBottomRow()
print("\\------/")
@staticmethod
def displayBlankCard():
print("/------\\")
print("|- - - |")
print("| - - |")
print("|- - - |")
print("| - - |")
print("\\------/")
|
d752e95eb7921e9df8037fec64acb2cb2270dc04 | Saswati08/Data-Structures-and-Algorithms | /String/remainder_with_seven.py | 557 | 3.671875 | 4 | #Function should return the required answer
#You are not allowed to convert string to integer
def remainderWith7(st):
#Code here
div = [1, 3, 2, -1, -3, -2]
n = 6
i = len(st) - 1
pr = 0
ind = 0
while(i >= 0):
pr += int(st[i]) * div[ind]
ind = (ind + 1) % n
i -= 1
return pr % 7
#{
# Driver Code Starts
if __name__=='__main__':
t = int(input())
for i in range(t):
str = input().strip()
print(remainderWith7(str))
# Contributed by: Harshit Sidhwa
# } Driver Code Ends
|
cbaf34c298dc845a72fb98109b03cb1bb7682bee | vertical-space/Monash_021013 | /factorial.py | 1,261 | 3.890625 | 4 | import doctest
def factorial(n):
'''
Returns the product of n!, equivalent to:
n*n-1*n-2*n-3...*n-(n-1)
>>> factorial(1)
1
>>> factorial(20)
'''
assert isinstance(n,int)
assert n > 0
tally = 1
while n:
tally *= n
n -= 1
return tally
#for i in range(1,10):
# print i, factorial(i)
def fibonacci(n):
'''returns the nth value in the fibonacci sequence
F(N) = F(N-1) + F(N-2)
F(0) = 0, f(1) = 1
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(2)
1
>>> fibonacci(3)
3
>>> fibonacci(4)
5
'''
assert n >= 0
assert isinstance(n, int)
a, b = 0, 1
while n > 0:
a, b = b, a+b
n -= 1
return a
tests = [
[0, 0],
[1, 1],
[2, 1],
[3, 2],
[5, 5],
]
for input, expected_result in tests:
assert fibonacci(input) == expected_result
def base_count(seq,base):
return seq.count(base)
def gc_content(seq):
return 1.0*(seq.count("G")+seq.count("C"))/len(seq)*100
print base_count("ATCGCGGGATTCGTATATAGG", "A")
print gc_content("ATCGCGGGATTCGTATATAGG"), "%"
if __name__ == "__main__":
doctest.testmod()
|
14a8a11f9faaa8b5f5d4c363e42748a598eab0f2 | santigr17/VectorProcessor-Arqui2 | /imageEncriptTest.py | 2,099 | 3.609375 | 4 | from PIL import Image
im = 0
pix = 0
size = 0
xorKey=172
INT_BITS = 8 #tamano de bits
despKey = 3
sumKey=172
opcion1 = ""
opcion2 = ""
while(1):
print("Digite 'e' para encriptar")
print("Digite 'd' para desencriptar")
print("Digite 'x' para cerrar la ejecucion")
opcion1 = input("Opcion: ")
if(opcion1 == "x"):
break
else:
print("1 para XOR ")
print("2 para Desplazamiento circular")
print("3 para Suma ")
print("4 para Especial ")
print("Digite 'x' para cerrar la ejecucion")
opcion2 = input("Opcion: ")
if(opcion2 == "x"):
break
elif(opcion1 == "e"):
im = Image.open('img.png') # Can be many different formats
pix = im.load()
size = im.size
else:
im = Image.open('img' + opcion2 + '.png') # Can be many different formats
pix = im.load()
size = im.size
for i in range(size[0]):
for j in range(size[1]):
pixel = pix[i,j]
encript = 0
if(int(opcion2) == 1):
encript = pixel[0] ^ xorKey
elif(int(opcion2) == 2):
if(opcion1=="d"): #shift left
encript = ((pixel[0] << despKey)|(pixel[0] >> (8 - despKey)))& 255
else: # shift right
encript = ((pixel[0] >> despKey)|(pixel[0] << (8 - despKey)))& 255
elif(int(opcion2) == 3):
if(opcion1=="d"):
encript = (pixel[0] - sumKey)&255
else:
encript = (pixel[0] + sumKey)&255
elif(int(opcion2) == 4):
if(opcion1=="d"):
encript = ((pixel[0] << despKey)|(pixel[0] >> (8 - despKey)))& 255
else:
encript = ((pixel[0] >> despKey)|(pixel[0] << (8 - despKey)))& 255
tupla = (encript,encript,encript)
pix[i,j] = tupla
im.save('img' + opcion2 + '.png')
|
4601459071ef0fa30b5059c8857cb3e9609c4717 | Devadanam/Test_Python | /Session06/q3.py | 482 | 3.90625 | 4 | '''Q3 Write a Python function to check whether a number is in a given range.'''
''' suppose range(2,10) and get a number from the user and check wether it is in the range between 2,10 '''
def isInRange(n):
if n in range(2,10):
return True
else:
return False
number = int(input("Enter a number : "))
result = isInRange(number)
if result == True:
print("The number {} is in the range".format(number))
else:
print("The number {} is not in the range".format(number))
|
5990f521bae198c8f5e85b8b6810807caf36a24b | emaitee/bot-training | /hotel_booking.py | 2,622 | 4.03125 | 4 | # Import sqlite3
import sqlite3
# Open connection to DB
conn = sqlite3.connect('hotels.db')
# Create a cursor
c = conn.cursor()
# Define area and price
area, price = "south", "hi"
t = (area, price)
# Execute the query
c.execute('SELECT * FROM hotels WHERE area = ? AND price=?', t)
# Print the results
print(c.fetchall())
### Explore DB with natural language
# Define find_hotels()
def find_hotels(params):
# Create the base query
query = 'SELECT * FROM hotels'
# Add filter clauses for each of the parameters
if len(params) > 0:
filters = ["{}=?".format(k) for k in params]
query += " WHERE " + " and ".join(filters)
# Create the tuple of values
t = tuple(params.values())
# Open connection to DB
conn = sqlite3.connect('hotels.db')
# Create a cursor
c = conn.cursor()
# Execute the query
c.execute(query, t)
# Return the results
return c.fetchall()
# Create the dictionary of column names and values
params = {"area": "south", "price": "lo"}
# Find the hotels that match the parameters
print(find_hotels(params))
#############3
# Define respond()
# Define respond()
def respond(message):
# Extract the entities
entities = interpreter.parse(message)["entities"]
# Initialize an empty params dictionary
params = {}
# Fill the dictionary with entities
for ent in entities:
params[ent["entity"]] = str(ent["value"])
# Find hotels that match the dictionary
results = find_hotels(params)
# Get the names of the hotels and index of the response
names = [r[0] for r in results]
n = min(len(results),3)
# Select the nth element of the responses array
return responses[n].format(*names)
# Test the respond() function
respond("I want an expensive hotel in the south of town")
######### Refined Search
# Define a respond function, taking the message and existing params as input
def respond(message, params):
# Extract the entities
entities = interpreter.parse(message)["entities"]
# Fill the dictionary with entities
for ent in entities:
params[ent["entity"]] = str(ent["value"])
# Find the hotels
results = find_hotels(params)
names = [r[0] for r in results]
n = min(len(results), 3)
# Return the appropriate response
return responses[n].format(*names), params
# Initialize params dictionary
params = {}
# Pass the messages to the bot
for message in ["I want an expensive hotel", "in the north of town"]:
print("USER: {}".format(message))
response, params = respond(message, params)
print("BOT: {}".format(response)) |
83b673500a351578631feb15344c664cd245b8a6 | quantbruce/leetcode_test | /数据结构相关/树/437. 路径总和 III(*).py | 2,858 | 3.90625 | 4 | 437. 路径总和 III
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
返回 3。和等于 8 的路径有:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
##################方法1:双层递归法
###该法效率较低,因为递归层数过深,需要再优化
"""
执行用时 :
728 ms
, 在所有 Python3 提交中击败了
53.99%
的用户
内存消耗 :
14.6 MB
, 在所有 Python3 提交中击败了
25.00%
的用户
"""
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
if not root: return 0
it = self.countPath(root, sum)
it_left = self.pathSum(root.left, sum)
it_right = self.pathSum(root.right, sum)
return it + it_left + it_right
def countPath(self, root, sum):
if not root: return 0
sum -= root.val
return (1 if sum==0 else 0)+self.countPath(root.left, sum)+\
self.countPath(root.right, sum)
https://leetcode-cn.com/problems/path-sum-iii/solution/437lu-jing-zong-he-iii-di-gui-fang-shi-by-ming-zhi/
https://leetcode-cn.com/problems/path-sum-iii/solution/hot-100-437lu-jing-zong-he-iii-python3-li-jie-di-g/
#########################方法二,前缀和法。最优
#####tips: 细节还没完全吃透
"""
执行用时 :
52 ms
, 在所有 Python3 提交中击败了
98.90%
的用户
内存消耗 :
14.4 MB
, 在所有 Python3 提交中击败了
25.00%
的用户
"""
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
prefixSumTree = {0:1}
self.count = 0
prefixSum = 0
self.dfs(root, sum, prefixSum, prefixSumTree)
return self.count
def dfs(self, root, sum, prefixSum, prefixSumTree):
if not root:
return 0
prefixSum += root.val
oldSum = prefixSum - sum
if oldSum in prefixSumTree:
self.count += prefixSumTree[oldSum]
prefixSumTree[prefixSum] = prefixSumTree.get(prefixSum, 0) + 1
self.dfs(root.left, sum, prefixSum, prefixSumTree)
self.dfs(root.right, sum, prefixSum, prefixSumTree)
'''一定要注意在递归回到上一层的时候要把当前层的prefixSum的个数-1,类似回溯,要把条件重置'''
prefixSumTree[prefixSum] -= 1
https://leetcode-cn.com/problems/path-sum-iii/solution/hot-100-437lu-jing-zong-he-iii-python3-li-jie-di-g/
|
5b6207d51797efd7d62af894f92893e6e6a185b3 | jasujon/Start-Python | /lession16/index.py | 1,438 | 4.5625 | 5 | #------------------------------Tuples Intro---------------------------
#Tuples Data Structure
#Tuples Store Any Datatype (like List)
#Most important tuples are immutable, once tuples is created you cant update
# example = ('one','two','three') #this is a tuples
#now you cant no append , no insert , no pop , no remove
#tuples are faster than list
#Tuples can use Method ()
#count
#index
#len function
#slicing
#------------------------------Looping in Tuples---------------------------
# mixed = (2,45,6,2.9)
# for num in mixed :
# print(num)
#------------------------------Tuples With One Element---------------------------
# #num = (1) # its not a tuples
# num = (1,) # tuples
# #output <class 'tuple'>
# print(type(num))
# #output <class 'int'>
#------------------------------Tuples Without Parenthesis---------------------------
# lang = 'Python','javaScript','Php','Laravel'
# # print(type(lang))
# #output : <class 'tuple'>
# print(lang)
# #output : ('Python', 'javaScript', 'Php', 'Laravel')
#------------------------------Tuples Unpacking---------------------------
# lang = ('Python','javaScript','Php','Laravel')
# lang1,lang2,lang3,lang4 =(lang)
# print(lang1)
# #output : Python
#------------------------------Function returning two values---------------------------
def func(num1,num2):
add = num1 + num2
multiple = num1 * num2
return add,multiple
print(func(2,3))
#output (5, 6) |
ac70417cc3f961af1bed7bb060810bd17ab93c17 | Brunaldo2911/pruebas_aprendizaje_python | /prueba_de_los_helados.py | 414 | 4 | 4 | apatece_helado = input(" Te apetece un helado? (SI / NO )")
tienes_dinero = input("tienes dinero para el helado? (SI / NO )" )
tio_helados = input("Esta el tio de los helados (SI / NO )" )
esta_la_tia = input("Estas con tu tia? (SI / NO )" )
if apatece_helado == "SI" and (tienes_dinero == "NO" or esta_la_tia == "SI") and tio_helados == "SI":
print("Comprate un helado")
else:
print("No compres ni shit") |
d9e87cdc2f1a185d0c64eb8e2731399addfa81e8 | wangpengda1210/Rock-Paper-Scissors | /Problems/Count up the squares/main.py | 201 | 3.8125 | 4 | # put your python code here
num_sum = int(input())
square_sum = num_sum ** 2
while num_sum != 0:
next_num = int(input())
num_sum += next_num
square_sum += next_num ** 2
print(square_sum)
|
002590ffd2cf35a842bd1cdbf7d98391d3288bcb | SeedofWInd/LeetCoding | /Facebook/253_Meeting_Rooms_II.py | 2,762 | 3.96875 | 4 |
"""
Description
____________
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
For example,
Given [[0, 30],[5, 10],[15, 20]],
return 2.
Approach/Complexity
______________
map
++++
The core is to calculate the overlap.
Have a map where
1. key is the start and end time
2. initial value is 1 for start and -1 for end
3. +1, -1 for identical start, end time
Loop through the SORTED map
record
current_rooms === current opened rooms
rooms === maximum rooms opened
return rooms
Heap
+++++
heap = []
1. Sort the intervals by start
2. loop through intervals
start, end = interval.start, interval.end
a. when ending comes before the new start
if len(heap) != 0 and heap[0] <= start:
heapq.heappop()
b.heapq.heappush(heap, end)
Two Arrays
++++++++++
1. create two arrays of sorted starttime and endtime
===> starts, ends
2. res, endpoint = 0, 0
for i in starts:
when start comes before ending, increment res, else increment endpoint
return result
Complexity
++++++++++
Time - O(Nlog(N))
Space - O(N)
"""
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
# MAP
class Solution(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
from collections import defaultdict
dic = defaultdict(int)
for i in intervals:
dic[i.start] += 1
dic[i.end] -= 1
dic = sorted(dic.items())
current_rooms, rooms = 0, 0
for i in dic:
current_rooms += i[1]
rooms = max(rooms, current_rooms)
return rooms
#Heap
class Solution(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
import heapq
intervals.sort(key=lambda x: x.start)
heap = []
for interval in intervals:
start = interval.start
if len(heap) != 0 and heap[0] <= start:
heapq.heappop(heap)
heapq.heappush(heap, interval.end)
return len(heap)
# Two arrays
class Solution(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
starts = sorted([interval.start for interval in intervals])
ends = sorted([interval.end for interval in intervals])
res, endpoint = 0, 0
for i in starts:
if i < ends[endpoint]:
res += 1
else:
endpoint += 1
return res
|
78d82e1cc10de851f33861cf7e51eb83203772e1 | txtbits/daw-python | /intro_python/Ejercicios entradasalida/ejercicio2.py | 472 | 4.1875 | 4 | # Escribir un programa que pregunte al usuario dos nmeros y luego muestre la suma, el producto y la media de los dos nmeros
numero = raw_input('Elige un numero ')
numero2 = raw_input('Elige otro numero ')
numero = int(numero)
numero2 = int(numero2)
print 'La suma de los numeros es: ', numero + numero2
print 'El producto de los numeros es: ', numero * numero2
print 'La media de los numeros es: ', (numero+numero2)/2.
raw_input('Pulse la tecla enter para finalizar')
|
468bab76382ee744af5d7b96047cf53e58f04371 | megamattman/battleship | /battleship.py | 11,835 | 3.765625 | 4 | ########
#TODO
# Ships that are more tan one grid space
# Playable by player in console
# Some GUI
########
from random import randint
import battleship_test
import game_board_module
import battleship_module
#battle field parameters
board_rows = 10;
board_cols = 10;
#debug message vars
debug = 1
ship_gen_error_msg = "Incorrect ships"
ship_gen_error_flg = 0
#end debug mesg vars
#class to hold row/col
class coords (object):
def __init__ (self, row = 0, col = 0) :
self.row = row
self.col = col
#board that has the boat locations
master_board = game_board_module.game_board(board_rows, board_cols, 'O', 'F')
#board that has players hit locations
player_board = game_board_module.game_board(board_rows, board_cols, 'O', 'X')
#Dictionary of battleships, the key is the letter that fills in the master board
battleships ={}
if (debug):
print("master board")
master_board.print_board()
print("\nplayer board")
player_board.print_board()
#Fills a space in on the master boards, represents a 'boat'
#If the random location is already filled, call the fucntion again
#NOTE: A generation count to break the function if it falls into a deep recursive loop
# This can happen if asked to gen more ships than available spaces or bad luck
def add_random_enemy_ship(board, gen):
#Recursive function breaker
if (gen >= 10):
ship_gen_error_flg = 1
return -1
#generate random location
row = randint(0, board.rows-1)
col = randint(0, board.cols-1)
if (debug):
print("New ship at %s,%d"%( chr(ord('A')+row),col))
#if failed to add the ship, try again
if (add_enemy_ship(board,row,col) == False):
add_random_enemy_ship(board, gen+1)
#return no_ships
return board.filled_spaces
#actually add the ship
def add_enemy_ship (board, row, col):
return board.fill_space(row,col)
#Output message when ship is hit
def output_hit_string(battleships,ship_id):
if (ship_id == 'F') :
print ("fishing ship has been hit!")
else :
ship_name = battleships[ship_id].name
if battleships[ship_id].ship_hit() == True:
print ("YOU SUNK MY %s!"% ship_name.upper())
#Take the player shot coords return True on Hit, False on miss
def player_shot(row, col, player_board, master_board, battleships):
#Check if already shot, is_space_empty(false) on play board
if (player_board.is_space_empty(row,col) == True):
# if NOT empty there a boat, check for empty
if (master_board.is_space_empty(row,col) == False) :
# if boat set player board to hit
player_board.set_space(row,col, 'H', 1)
output_hit_string(battleships, master_board.get_space(row,col))
return True
else:
#if not set player board location to X
player_board.fill_space(row,col)
return False
else:
print ("Location %d,%d has already been hit" % (row,col))
return False
#Add random ships
no_battleships = 5;
for i in range (5):
add_random_enemy_ship(master_board, 0)
#Check correct number of ships
battleship_test.check_battleship_number(5,master_board.filled_spaces)
#end random ship add
print ("ADD A SHIP TEST")
#add ship in known location
if (master_board.get_space(0,0) != '0') :
master_board.fill_space(0,0)
battleship_test.check_battleship_number(6,master_board.filled_spaces)
master_board.fill_space(0,0)
battleship_test.check_battleship_number(6,master_board.filled_spaces)
master_board.print_board()
#Set up known empty space
master_board.empty_space(1,1)
#Player shot test
print("PLAYER MISS TEST")
#Miss before, After and repeat cases
miss_row = 1
miss_col = 1
battleship_test.check_grid_pos(player_board, miss_row,miss_col, 'O', "Empty Space")
battleship_test.check_result(player_shot(miss_row,miss_col,player_board,master_board,battleships), False, "Empty Space")
battleship_test.check_grid_pos(player_board, miss_row,miss_col, 'X', "Player Miss")
battleship_test.check_result(player_shot(miss_row,miss_col,player_board,master_board,battleships), False, "Prev miss shot")
battleship_test.check_grid_pos(player_board, miss_row,miss_col, 'X', "Player Repeated Miss")
#end miss
#player hit
print("PLAYER HIT TEST")
hit_row = 0
hit_col = 0
battleship_test.check_grid_pos(player_board, hit_row,hit_col, 'O', "Before player hit")
battleship_test.check_result(player_shot(hit_row,hit_col,player_board,master_board,battleships), True, "Good shot")
battleship_test.check_grid_pos(player_board, hit_row,hit_col, 'H', "Player Hit")
battleship_test.check_result(player_shot(hit_row,hit_col,player_board,master_board,battleships), False, "Prev hit shot")
battleship_test.check_grid_pos(player_board, hit_row,hit_col, 'H', "Hit repeat")
#end player shot test
#Adding a larger boat
print("DEPLOY THE MATTAZOR")
#Create it
battleship_matt = battleship_module.battleship("Mattazor", 4)
#DEPLOY THE BOAT
for i in range(4):
master_board.set_space(2,int(i),'M',1)
battleship_test.check_grid_pos(master_board, 2,i, 'M', "Mattazor Deploy" + str(i))
#TRACK THE SHIP
battleships['M'] = battleship_matt
master_board.print_board()
for i in range(4):
battleship_test.check_grid_pos(player_board, 2,i, player_board.empty_char, "Before Mattazor hit" + str(i))
battleship_test.check_result(player_shot(2,i,player_board,master_board,battleships), True, "Good shot Mattazor" + str(i))
battleship_test.check_grid_pos(player_board, 2,i, 'H', "Player Hit Mattazor" + str(i))
battleship_test.check_result(player_shot(2,i,player_board,master_board,battleships), False, "Prev hit shot Mattazor" + str(i))
battleship_test.check_grid_pos(player_board, 2,i, 'H', "Hit repeat Mattazor" + str(i))
mattazor_destroyed = battleships['M'].hits >= battleships['M'].size
battleship_test.check_result(mattazor_destroyed, True, "MATTAZOR DESTROYED")
#Will return a list of coords in the coords object format
#Will check 'end' of potential coord range,
#If out of bound will return empty
def get_list_of_coords (row, col, facing, size, board):
ship_coords =[]
if facing == 'U':
if (row-size) < 0 :
return ship_coords
for i in range(size):
ship_coords.append(coords(row-i,col))
elif facing == 'D':
if (row+size) > board.rows-1 :
return ship_coords
for i in range(size):
ship_coords.append(coords(row+i,col))
elif facing == 'L':
if (col-size) < 0 :
return ship_coords
for i in range(size):
ship_coords.append(coords(row,col-i))
elif facing == 'R':
if (col+size) > board.cols-1 :
return ship_coords
for i in range(size):
ship_coords.append(coords(row,col+i))
return ship_coords
##Get list of coords tests
test_coords = get_list_of_coords(4,4,'U',2, master_board)
for items in test_coords:
print str(items.row) + " " +str(items.col)
battleship_test.check_result(len(test_coords), 2, "2 space ship")
##End of get_coord_list tests
#Makes sure all coords have a particular char
#Standard use would be checking if all coords are empty for boat placement
#Made more generic to make function more useful
def check_valid_ship_coords(ship_coords, board, legal_char):
for item in ship_coords:
row = item.row
col = item.col
if (board.get_space(row,col) != legal_char):
print("Occupied space %d,%d" % (row, col))
return False
return True
#check the request facing to determine if valid
#if not valid, return empty list
def check_facing (row, col, facing, size, board) :
possible_ship_coords = get_list_of_coords(row, col, facing, size, board)
#return false if ships coords can't be attained
if not possible_ship_coords :
if (debug) :
print("No possible coords, facing %s" %facing)
return possible_ship_coords
#Check all positions are empty
if (check_valid_ship_coords(possible_ship_coords, board, board.empty_char) == True):
return possible_ship_coords
#if there is an occupied space in the coord list return empty list
possible_ship_coords =[]
return possible_ship_coords
#Place the ship
#update the master board with the location of the ship
def place_ship (battleship, board):
for coord in battleship.coords :
print("Placing ship %s at loc %d,%d with char %s" %(battleship.name, coord.row, coord.col, battleship.ship_id))
board.set_space(coord.row, coord.col, battleship.ship_id, 1)
##test object class
class ship_place_test(object):
def __init__ (self, ship, coords, facing):
self.facing = facing
self.ship = ship
self.coords = coords
ships_to_place = [ship_place_test(battleship_module.battleship("Mattazor", 4, "M"), coords(0,0), "D"),
ship_place_test(battleship_module.battleship("Lukiator", 3, "L"), coords(0,4), "R"),
ship_place_test(battleship_module.battleship("Olidactyl", 2, "I"), coords(3,3), "L"),
ship_place_test(battleship_module.battleship("SuperDan", 4, "S"), coords(0,0), "D"),
ship_place_test(battleship_module.battleship("Timmy", 4, "T"), coords(1,1), "L")]
#clear the board
master_board.init_board()
master_board.print_board()
##Place all the ships in the ship_to_place list
#Test cases
# --Valid ships of different sizes
# --Invalid 'first choice' facing
# --Invalid position (no available facings)
for i in range(len(ships_to_place)):
ship_to_place = ships_to_place[i]
u_coords = check_facing(ship_to_place.coords.row, ship_to_place.coords.col, 'U', ship_to_place.ship.size, master_board)
d_coords = check_facing(ship_to_place.coords.row, ship_to_place.coords.col, 'D', ship_to_place.ship.size, master_board)
l_coords = check_facing(ship_to_place.coords.row, ship_to_place.coords.col, 'L', ship_to_place.ship.size, master_board)
r_coords = check_facing(ship_to_place.coords.row, ship_to_place.coords.col, 'R', ship_to_place.ship.size, master_board)
#Automated decision making, when the first choice is not
alternate_facings = []
available_coords = {}
if d_coords :
available_coords["D"] = d_coords
alternate_facings.append("D")
if l_coords :
available_coords["L"] = l_coords
alternate_facings.append("L")
if u_coords :
available_coords["U"] = u_coords
alternate_facings.append("U")
if r_coords :
available_coords["R"] = r_coords
alternate_facings.append("R")
if not available_coords:
print ("The ship %s location %d,%d, has no suitable facings" % (ship_to_place.ship.name, ship_to_place.coords.row, ship_to_place.coords.col))
continue
if ship_to_place.facing in available_coords:
requested_coords = available_coords[ship_to_place.facing]
#Check the correct number of coords generated for ship size
else:
facing = alternate_facings[randint(0, len(alternate_facings)-1)]
print("Original facing %s not available selecting facing %s" %(ship_to_place.facing, facing))
requested_coords = available_coords[facing]
ship_to_place.ship.coords = requested_coords
battleship_test.check_result(len(ship_to_place.ship.coords), ship_to_place.ship.size, "Coord count check for " + ship_to_place.ship.name)
place_ship(ship_to_place.ship, master_board)
#check the ships ID is in the grid where expected
for coord in ship_to_place.ship.coords:
row = coord.row
col = coord.col
battleship_test.check_grid_pos(master_board, row, col, ship_to_place.ship.ship_id, "Checking grid space for " + ship_to_place.ship.name)
master_board.print_board()
|
3b7a57298264c638cbb53657adaafcb350ab53cd | ZhengLiangliang1996/Leetcode_ML_Daily | /Tree/95_UniqueBinarySearchTreeII.py | 843 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
@lru_cache(None)
def dfs(st, end):
if st > end: return [None]
ans = []
for i in range(st, end+1):
left = dfs(st, i-1)
right = dfs(i+1, end)
for l in left:
for r in right:
root = TreeNode(i)
root.left = l
root.right = r
ans.append(root)
return ans
return dfs(1, n)
|
e3b3551948754861f156840abc6f93b3715d0969 | Arko98/Alogirthms | /Competitive_Coding/Merge_Intervals.py | 478 | 3.640625 | 4 | # Problem URL: https://leetcode.com/problems/merge-intervals
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
merged = [intervals[0]]
for i in range(1, len(intervals)):
if merged[-1][1] < intervals[i][0]: merged.append(intervals[i]) # No Merge
else: merged[-1][1] = max(merged[-1][1], intervals[i][1]) # change entry accordingly
return merged |
4bd40384978a11cb183453776fbba6575ddd2cab | szymonsiczek/testing | /Automatic folder cleaner.py | 1,356 | 4.0625 | 4 | #! python3
# This program segregates files in a given folder
# into a folders named after the type of files
from pathlib import Path
import os, shutil
def findFileTypesInFolder(folder):
finalListofFileTypes = []
for filename in os.listdir(folder):
suffix = Path(os.path.join(folderToClean, filename)).suffix.strip('.')
if suffix not in finalListofFileTypes:
finalListofFileTypes.append(suffix)
return finalListofFileTypes
def getSuffixWithoutDot(file):
return Path(os.path.join(folderToClean, file)).suffix.strip('.')
# Ask user which folder needs to be cleaned
print('Please enter the absolute path of a folder, that needs to be cleaned:')
folderToClean = input()
# Define file types in a given folder
finalListOfFileTypes = findFileTypesInFolder(folderToClean)
# Create a new folder for every type of file
for filetype in finalListOfFileTypes:
newFolder =(os.path.join(folderToClean, (filetype.lower())))
if not os.path.exists(newFolder):
os.makedirs(newFolder)
# Segregate files into acuurate folders
for filename in os.listdir(folderToClean):
if os.path.isfile(os.path.join(folderToClean,filename)):
if getSuffixWithoutDot(filename).lower() == filetype.lower():
shutil.move((os.path.join(folderToClean,filename)), newFolder)
|
437a3ec8711ae3a48e9e63afe38b9a431378403b | abramspl/python_nauka | /wycinki.py | 337 | 3.734375 | 4 | gracze=['piotr','lukasz','paulina','maciek','kuba']
print('Dzisiaj w gry planszowe beda grac nastepujacy gracze:\n')
for gracz in gracze:
print(gracz.title())
print('\nPierwsza trojka graczy to:')
print(gracze[0:3])
print('\nTrzej srodkowi gracze to:')
print(gracze[1:4])
print('\nOstatnia trojka to:')
print(gracze[-3:]) |
933956a920ce838a3b2bfe76153dcae7cd09960b | abitofm/python-scripts | /Fibonacci.py | 603 | 4.21875 | 4 | #Calculate the Fibonacci number on any requested place in the sequence.
def FibPrint(place, fib):
print('The Fibonacci number on place ' + str(place) + ' of the sequence is ' + str(fib))
n = input('Enter the place in the sequence: ')
nr = int(n)
Fibonacci = 1
FibonacciO = 0
if nr <= 0 :
print('Invalid entry')
exit()
if nr == 1 :
FibPrint(nr, 0)
exit()
if nr == 2 :
FibPrint(nr, 1)
exit()
if nr > 2 :
pl = nr - 2
for item in range(pl) :
FibonacciN = Fibonacci + FibonacciO
FibonacciO = Fibonacci
Fibonacci = FibonacciN
FibPrint(nr, FibonacciN)
|
089bf418ef902cb37ac26380633b3caa253fecde | akashvshroff/Puzzles_Challenges | /daily_coding_problem_22.py | 1,261 | 4.1875 | 4 | def find_reconstruction(words, match):
"""
Given a dictionary of words and a string made up of those words (no spaces),
return the original sentence in a list. If there is more than one possible
reconstruction, return any of them. If there is no possible reconstruction,
then return null.
For example, given the set of words 'quick', 'brown', 'the', 'fox', and the
string "thequickbrownfox", you should return
['the', 'quick', 'brown', 'fox'].
Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the
string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond]
or ['bedbath', 'and', 'beyond'].
"""
seq = []
temp_word = ''
for letter in match:
temp_word += letter
if temp_word in words:
seq.append(temp_word)
words.remove(temp_word)
temp_word = ''
if temp_word: # didn't find the last word
return None
else:
return seq
print(find_reconstruction(['bed', 'bath', 'bedbath', 'and', 'beyond'], 'bedbathandbeyond'))
print(find_reconstruction(['quick', 'brown', 'the', 'fox'], 'thequickbrownfox'))
# now with a word missing
print(find_reconstruction(['quick', 'brown', 'fox'], 'thequickbrownfox'))
|
feed9214df26c9316f54702a080adbfec3c69070 | kensj/leetcode-hackerrank-euler | /LeetCode/104.py | 643 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return max(self.maxDepthRec(root, 0, []))
def maxDepthRec(self, root, depth, maxd):
if root is None:
return [0]
if root:
self.maxDepthRec(root.left, depth+1, maxd)
self.maxDepthRec(root.right, depth+1, maxd)
maxd.append(depth+1)
return maxd |
e3818c0c22ae56717b396869c2dedbfe48e24fb0 | Cerasel/Cerasel | /module 4/app1.py | 1,171 | 4.03125 | 4 | shop1 = {'mere': 10, 'pere': 15, 'prune': 6, 'ananas': 20}
shop2 = {'mere': 11, 'pere': 15, 'prune': 6}
shop3 = {'mere': 10, 'pere': 16, 'prune': 7, 'papaya': 25}
need_to_buy = {'mere': 2, 'pere': 3, 'prune': 6}
available_shops={'profi': shop1, 'kauf': shop2,'lidl': shop3}
def best_buy(shops: dict, cart: dict):
total = {}
smallest_cost=None
_best_buy=''
for product, quanty in cart.items():
# print(product, quanty)
for shop_name, shop_products in shops.items():
# print(shop_name, shop_products)
price = shop_products.get(product)
# print(product, quanty, price)
cost = quanty * price
# print(shop_name, product, cost)
saved_cost = total.get(shop_name, 0)
new_saved_cost = saved_cost + cost
total[shop_name] = new_saved_cost
for shop_name, total_cost in total.items() :
print(shop_name, total_cost)
if smallest_cost is None or smallest_cost > total_cost :
smallest_cost = total_cost
_best_buy = shop_name
print(smallest_cost,_best_buy)
best_buy(shops=available_shops, cart=need_to_buy) |
427d01a6e4e2d00fb297c8290bb85006559283e5 | harnoors/AirBNB | /Assignmet7_354.py | 8,594 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
#
# In[ ]:
# importing module
import pyodbc
#connection creation
connection = pyodbc.connect('driver={SQL Server};Server=cypress.csil.sfu.ca;Trusted_Connection=yes;')
cur = connection.cursor()
cont=1
while cont==1 :
print("Home:\n")
print("What would you like to do in this session?")
print("\t 1.Search a Listing ")
print("\t 2.Book a Listing (Only if you know the listing ID) ")
print("\t 3.Write a Review ")
print("\t ENTER YOUR CHOICE (1 , 2 or 3) ")
a=int (input())
while(a!=1 and a!=2 and a!=3):
print("INVALID CHOICE !")
print("\t ENTER YOUR CHOICE (1 , 2 or 3) ")
a=int (input())
while (a==1 or a==2 or a==3 or a==4):
if a==1:
print("Input the filters of your search:\n")
print("\t1.Start Date And End Date\n")
print("\t2.Start And End Date + Minimum And Maximum Price.\n")
print("\t3.Start And End Date + number of bedrooms.\n")
print("\t4.Start And End Date + number of bedrooms + Minimum And Maximum Price.\n")
print("\tplease enter your choice from 1 , 2 , 3 or 4")
searchCriteria=int(input())
#start and end date
if(searchCriteria==1):
StartDate=input("Enter the start date in the format (YYYY-MM-DD) : \n")
EndDate=input("Enter the end date in the format (YYYY-MM-DD) : \n")
SQL_Command=("SELECT DISTINCT id,name,number_of_bedrooms,SUBSTRING(description,1,25),MAX(price) FROM Listings,Calendar WHERE id=listing_id AND (date >= ? AND date <= ? )AND id NOT IN (SELECT listing_id FROM Calendar WHERE (date >= ? AND date <= ?) AND (available = 0)) GROUP BY id,name,SUBSTRING(description,1,25),number_of_bedrooms")
cur.execute(SQL_Command,StartDate,EndDate,StartDate,EndDate)
#START AND END DATE+PRICE
elif(searchCriteria==2):
StartDate=input("Enter the start date in the format (YYYY-MM-DD) : \n")
EndDate=input("Enter the end date in the format (YYYY-MM-DD) : \n")
mini=int(input("Enter the minimum price : \n"))
maxi=int(input("Enter the maximum price : \n"))
SQL_Command=("SELECT DISTINCT id,name,number_of_bedrooms,SUBSTRING(description,1,25),MAX(price) FROM Listings,Calendar WHERE id=listing_id AND (date >= ? AND date <= ? )AND (price >= ? AND price <= ?) AND id NOT IN (SELECT listing_id FROM Calendar WHERE (date >= ? AND date <= ?) AND (price >= ? AND price <= ? AND available = 0)) GROUP BY id,name,SUBSTRING(description,1,25),number_of_bedrooms")
cur.execute(SQL_Command,StartDate,EndDate,mini,maxi,StartDate,EndDate,mini,maxi);
#START AND END DATE+bedrooms
elif(searchCriteria==3):
StartDate=input("Enter the start date in the format (YYYY-MM-DD) : \n")
EndDate=input("Enter the end date in the format (YYYY-MM-DD) : \n")
Count=int(input("Enter the number of bedrooms : \n"))
SQL_Command="SELECT DISTINCT id,name,number_of_bedrooms,LEFT(description,25),MAX(price) FROM Listings,Calendar WHERE number_of_bedrooms= ? AND id=listing_id AND (date >= ? AND date <= ? )AND id NOT IN (SELECT listing_id FROM Calendar WHERE (date >= ? AND date <= ?) AND available = 0) GROUP BY id,name,LEFT(description,25),number_of_bedrooms"
cur.execute(SQL_Command,Count,StartDate,EndDate,StartDate,EndDate);
#START AND END DATE+PRICE+BEDROOMS
elif (searchCriteria==4):
StartDate = input('Enter a Startdate in YYYY-MM-DD format:\n')
EndDate = input('Enter a Enddate in YYYY-MM-DD format:\n')
mini= int(input('Please enter minimum price\n'))
maxi= int(input('Please enter maximum price\n'))
Count= int(input("Please Enter Number of Bedrooms:\n"))
SQL_Command="SELECT DISTINCT id,name,number_of_bedrooms,LEFT(description,25),MAX(price) FROM Listings,Calendar WHERE number_of_bedrooms= ? AND price >= ? AND price <= ? and id=listing_id AND (date >= ? AND date <= ? )AND id NOT IN (SELECT listing_id FROM Calendar WHERE (date >= ? AND date <= ?) AND (price >= ? AND price <= ? AND available = 0)) GROUP BY id,name,LEFT(description,25),number_of_bedrooms"
cur.execute(SQL_Command,Count,mini,maxi,StartDate,EndDate,StartDate,EndDate,mini,maxi)
results = cur.fetchall()
print("\nSearch result are : \n")
if len(results) == 0:
print("\n ERROR! \n\t NO DATA FOUND.\n")
else:
print("\nSearch result is : \n")
for i in results:
print ("Listings ID :" , i[0])
print ("Name : " , i[1])
print ("Number of bedrooms : " , i[2])
print ("Discription : " , i[3])
print ("Price : " , i[4])
print("\n")
print("Enter 1 to Search again, 2 to book a listing or 0 to go to home.\n")
a=int(input())
#book listing
if a==2:
#input-lid,name,stayfrom and stay to
Lid=int(input("Enter the listing ID"))
name=input("please enter your name.")
Noguests=int(input("Enter the number of Guests."))
#genrating BID
SQL=("SELECT MAX(id),COUNT(id) FROM Bookings")
cur.execute(SQL)
results=cur.fetchall()
if results[0][1]==0:
Bid=1
elif results[0][1]==1:
Bid=2
else:
Bid= int(results[0][0])+1
#SQL to insert inputed data
SQL = ("INSERT INTO Bookings(id,listing_id,guest_name,stay_from,stay_to,number_of_guests) VALUES (?,?,?,?,?,?)")
Values = [Bid,Lid,name,StartDate,EndDate,Noguests]
cur.execute(SQL,Values)
print("Thank you for your reservation.\n Your Booking ID is : ",Bid)
connection.commit()
print("\n\nEnter 2 to Book another listing or 0 to go to home.\n")
a=int(input())
#write review
if a==3:
name=input("please enter your name : ")
SQL=(" SELECT * FROM Bookings WHERE guest_name=? ")
cur.execute(SQL,name)
results=cur.fetchall()
if len(results)==0:
print("Error!\n\tNo Data Found with this name.\nEnter 3 try again or 0 to exit to home")
a=int(input())
else:
itr=1
print("\n\n")
for i in results:
print("Booking - ",itr)
print ("Booking ID :" ,i[0])
print ("Listing ID : " ,i[1])
print ("Guest name : " ,i[2])
print ("Stay from : " ,i[3])
print ("Stay to : " ,i[4])
print("\n")
itr=itr+1
Bid=int(input("For which Booking would you like to submit a review ? (please enter the booking Id from above list) "))
Lid=int(input("please enter the Listing id Id from above list:"))
comment=input('Enter your review')
#genrating Review id
SQL=("SELECT MAX(id),COUNT(id) FROM Reviews")
cur.execute(SQL)
results=cur.fetchall()
if results[0][1]==0:
Rid=1
elif results[0][1]==1:
Rid=2
else:
Rid= int(results[0][0])+1
#if date>stayTo:
SQL=("INSERT INTO Reviews (id,listing_id,comments,guest_name) VALUES (?,?,?,?);")
Values = [Rid,int(Lid),comment,name]
cur.execute(SQL,Values)
connection.commit()
print("Enter 3 to add another review or 0 to go to home")
a=int(input())
print("Enter 1 to continue or 0 to end you session.")
cont=int(input())
connection.commit()
connection.close()
# ###
# In[ ]:
|
f192b941c2b2d9d8ff4cd2e5d31a7c658adc08cb | HSx3/TIL | /algorithm/day05/3. String/연습3_brute.py | 715 | 3.578125 | 4 | def bruteForce(text, pattern):
i, j =0, 0
while j < len(pattern) and i < len(text):
if text[i] != pattern[j]:
i = i - j
j = -1
i += 1
j += 1
if j == len(pattern):
return i - len(pattern)
else:
return i
def bruteForce2(text, pattern):
for i in range(len(text)-len(pattern)+1):
cnt =0
for j in range(len(pattern)):
if text[i+j] != pattern[j]:
break
else: cnt += 1
if(cnt >= len(pattern)) : return i
return -1
text = "TTTTAACCA"
pattern = "TTA"
print("{}".format(bruteForce(text, pattern)))
print("{}".format(bruteForce2(text, pattern)))
print(text.find(pattern)) |
7571aa5d01ea212b196163457a0471d23af04395 | CaptainCode7/Password-Generator | /passgenerator.py | 1,741 | 4.1875 | 4 | # Generate a random password with or without symbols between 6-20 characters
import random
import string
add_symbols = bool
pass_length = int
def yes_or_no(question):
while 'invalid response':
user_input = str(input('Would you like symbols in your passwords?: (y/n): ')).lower().strip()
if user_input == 'y':
return True
if user_input == 'n':
return False
else:
print('Invalid response... Please enter (y/n)\n')
return yes_or_no(question)
add_symbols = yes_or_no(add_symbols)
def password_length(length):
password_question = input('How long do you want your password? (6-20) ')
while 5 < int(password_question) < 21:
return password_question
else:
print('Invalid response... Please enter a number between 6 and 20) ')
return password_length(length)
pass_length = password_length(pass_length)
def random_string(string_length=int):
"""Generate a random string of letters, digits and special characters """
if add_symbols:
password_characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(password_characters) for i in range(string_length))
else:
password_characters = string.ascii_letters + string.digits
return ''.join(random.choice(password_characters) for i in range(string_length))
print("\nGenerating Random String password with letters, digits and special characters ")
print("First Random String ", random_string(int(pass_length)))
print("Second Random String", random_string(int(pass_length)))
print("Third Random String", random_string(int(pass_length)))
# For command prompt terminal
input('Press ENTER to exit') |
a753c804d8dd2400b01191d4501f248af36bcf72 | SvenLC/CESI-Algorithmique | /tableaux/exercice8.py | 331 | 3.59375 | 4 | # Ecrivez un algo remplissant un tableau de 6 sur 13, avec des zéros
def remplir_tableau(longeur, largeur):
tableau = []
for i in range(0, longeur):
tableau.append([])
print(tableau)
for y in range(0, largeur):
tableau[i].append(0)
return tableau
print(remplir_tableau(6, 13))
|
09ce63378ccfd087fb05fd0e80dd26e7e0b14d22 | renkeji/leetcode | /python/src/main/python/Q123.py | 1,131 | 3.75 | 4 | from src.main.python.Solution import Solution
# Say you have an array for which the ith element is the price of a given stock on day i.
#
# Design an algorithm to find the maximum profit. You may complete at most two transactions.
#
# Note:
# You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
class Q123(Solution):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_p = 0
if prices:
profits = [0] * len(prices)
buy, sell = prices[0], prices[-1]
diff1, diff2 = 0, 0
for i in range(len(prices)):
if prices[i] > buy:
diff1 = max(diff1, prices[i] - buy)
else:
buy = prices[i]
if prices[-i-1] < sell:
diff2 = max(diff2, sell - prices[-i-1])
else:
sell = prices[-i-1]
profits[i] += diff1
profits[-i-1] += diff2
max_p = max(profits)
return max_p
|
a35a012de0a1952b5976dbb21942f06b76532f21 | Aigerimmsadir/BFDjango | /week1/informatics/2938.py | 63 | 3.609375 | 4 | num1 = int(input())
num2 = int(input())
print(int(num2/num1)) |
d0203c346d2ae60e8a5b32fe17756cc84c5730d6 | emilyhmoore/python-washu-2014 | /PythonDay2.py | 1,800 | 3.78125 | 4 | class Burger():
def_init_(self, filling, doneness, size, toppings, container):
self.filling = filling
self.doneness = doneness
self.size = size
if self.toppings_allowed(toppings):
self.toppings=toppings
else:
self.toppings=[]
self.toppings = self.toppings_allowed
self.container = container
def _str_(self):
return "I'm a %s %s burger topped with %s" % (self.doneness,self.filling, toppings)
def tastiness(self):
if "cheese" in toppings:
return "VERY GOOD"
elif self.doneness=="raw":
return "yuck!"
def toppings_allowed(self, attempted_toppings):
allowed_toppings = ["cheese, "tomato", "onion", "lettuce", "bacon"]
toppings=[]
for topping in attempted_toppings:
if topping in allowed_toppings:
toppings.append(topping)
return toppings
def cook(self):
time_for_size=0
if self.doneness=="raw":
time_for_doneness=0
elif self.doneness=="rare"
time_for_doneness = 5
elif self.doneness=="medium"
time_for_doneness = 6
elif self.doneness=="well done"
time_for_doneness = 8
else:
return "UNKNOWN"
return self.size * 4 * time_for_doneness
rare_burger = Burger("beef", "medium", "0.33", ["cheese"], "bread")
class VeggieBurger(Burger):
def_int_(self, toppings_ordered, container)
Burger._init_(self, "veggie patty", "medium", 0.35, toppings_ordered, container)
def toppings_allowed(self, attempted_toppings):
allowed_toppings = ["cheese, "tomato", "onion", "lettuce"]
toppings=[]
for toppings in attempted_toppings:
if topping in allowed_toppings:
toppings.append(topping)
return toppings
def cooking_time(self):
return 6
veggie_burger=VeggieBurger(["tomato", "bacon"], "bread")
print veggie_burger.cooking_time()
print veggie_burger.tastiness()
print veggie_burger
def first(x):
x[0]
|
b8ce5f57b508857135f6f16cdbe9640214c17e5a | 1324aman/test | /assignment21july/factorial.py | 188 | 4.25 | 4 | # Program to find factorial of a number
number = int(input())
factorial = 1
for i in range(2, number + 1):
factorial *= i
print('factorial of {0} is {1} '.format(number, factorial))
|
c8de965f3a91bc07de0a5ad8b678292210d52165 | de-kyutae/project_smartwellness | /web_/lotto_generator/lotto.py | 915 | 3.828125 | 4 | import random
#### https://wikidocs.net/94699
# lotto_num = []
# while len(lotto_num) != 6:
# num = random.randint(1, 45)
# if num not in lotto_num:
# lotto_num.append(num)
# lotto_num_order = sorted(lotto_num)
# print(lotto_num_order)
####
#
button = 'y'
button = input("로또 번호를 생성하시겠습니가? (y/n) > ")
while True:
if button == 'y' or 'yes' or 'Y':
times = input("몇 번 하겠습니까? > ")
lotto_num = []
if times.isdigit():
for i in range(len(times)):
while len(lotto_num) != 6:
num = random.randint(1, 45)
if num not in lotto_num:
lotto_num.append(num)
lotto_num_order = sorted(lotto_num)
print(lotto_num_order)
if button == 'n' or 'N' or 'NO' or 'no' or 'No':
break
|
88579dc3d32dd6ba859cdcb212af81e3bf56b48e | Orbi76/lecture0 | /name.py | 74 | 3.796875 | 4 | name = input()
print("Hello, {name}!")
for num in [1, 2, 3, 4]
print(num)
|
4c4875a22e83da51b4e22034a7e6fd6164cde461 | KickItAndCode/Algorithms | /Recursion/Nqueens.py | 3,956 | 3.984375 | 4 | # 51. N-Queens
# The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
# Given an integer n, return all distinct solutions to the n-queens puzzle.
# Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
# Example:
# Input: 4
# Output: [
# [".Q..", // Solution 1
# "...Q",
# "Q...",
# "..Q."],
# ["..Q.", // Solution 2
# "Q...",
# "...Q",
# ".Q.."]
# ]
# Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
# def solveNQueens(n):
# def helper(row):
# if row == n:
# # all queens legally places
# result.append(col_placement[:])
# return
# for col in range(n):
# if all(abs(c-col) not in (0, row-i) for i, c in enumerate(col_placement[:row])):
# col_placement[row] = col
# helper(row + 1)
# result = []
# col_placement = [0] * n
# helper(0)
# return result
# print(solveNQueens(4))
def solveNQueens(n):
def helper(row, n, colPlacements, res):
if row == n:
# all n queens ahve been placed in the n rows. We have reached the bottom of our recursion. We can now add the colplacements to the result
res.append(generateBoardFromPlacements(colPlacements, n))
return
# try all columns in the current row that we are making a choice on.
# the colPlacements list will hold the column we place a queen for the i'th row
# so if I have [1,3,0,2] that means it s a 4x4 grid
# row index 0 has a queen placed in column index 1
# row index 1 has a queen placed in column index 3
# row index 2 has a queen placed in column index 0
# row index 3 has a queen placed in column index 2
for col in range(n):
# record a column placement for this row
colPlacements.append(col)
# if it is a valid placement we recurse t work on the nedt row row +1 in a recursive call
if isValid(colPlacements):
helper(row + 1, n, colPlacements, res)
# we are done exploring with the placement and now we will remove it from our colplacements we will loop back around and try more columnb placements for this row if theyre are any left
del colPlacements[-1]
def isValid(colPlacements):
rowWeAreValidatingOn = len(colPlacements) - 1
# loop and check our placements in every row previous against the placement that we just made
for ithQueenRow in range(rowWeAreValidatingOn):
# Get the absolute difference between:
# The column of the already placed queen we are comparing against -> colPlacements.get(ithQueenRow)
# The column of the queen we just placed -> colPlacements.get(rowWeAreValidatingOn)
distance = abs(
colPlacements[ithQueenRow] - colPlacements[rowWeAreValidatingOn])
# if the absolute distance is 0
# then we placed in a columb being attacked by the i'th queen
# if the absolute distance is == rowDistance
# then queen is getting attacked diagonally
rowDistance = rowWeAreValidatingOn - ithQueenRow
if distance == 0 or distance == rowDistance:
return False
return True
def generateBoardFromPlacements(colPlacements, n):
board = []
totalItemsPlaced = len(colPlacements)
for row in range(totalItemsPlaced):
s = ''
for col in range(n):
if col == colPlacements[row]:
s += "Q"
else:
s += '.'
board.append(s)
return board
res = []
helper(0, n, [], res)
return res
print(solveNQueens(4))
|
e47a147789d300abbaa8ef89cf2989f162d6ac34 | shravan-shandilya/algo_practice | /sum_string.py | 346 | 3.734375 | 4 | #!/usr/bin/python
def sum_string(str):
for i in range(len(str)-2):
if int(str[i])+int(str[i+1]) == int(str[i+2]):
continue
else:
return False
return True
print sum_string("1234566324")
print sum_string("12358")
print sum_string("112358")
print sum_string("01123")
print sum_string("123234134124")
|
6e68b0049d8cf4ca66c0b8d4d8ee2177d4c6682f | Nadim-Nion/Python-Programming | /break and continue.py | 247 | 3.671875 | 4 | # we cant use break and continue keyword outside the loop, otherwise it will show an error
#We have to use these keyword inside the if cndition.
i=1
while i<=100 :
if i==50 :
break
print(i)
i = i + 1
print("My Name is Nion")
|
1036152fa4a389cc674a0fe07b07c8743edd1a0f | Manuel-Python/PythonLearning | /number_list2.py | 563 | 4.03125 | 4 | empty_kist = []
even = [2,4,6,8]
odd = [1,3,5,7,9]
# numbers = even + odd
# print(numbers)
#
# sorted_numbers = sorted(numbers)
# print(sorted_numbers)
# print(numbers)
#
# digits = list("432985617") #sorted("432985617")
# print(digits)
#
# #more_numbers = list(numbers)
# #more_numbers = numbers[:]
# more_numbers = numbers.copy()
# print(more_numbers)
# print(numbers is more_numbers)
# print(numbers == more_numbers)
numbers = [even, odd]
print(numbers)
for number_list in numbers:
print(number_list)
for value in number_list:
print(value) |
1c1bdbc7c037b48d8180725ab50e69ffdf363af4 | PaulineNgugi2010/Practice | /exercise2.py | 871 | 3.6875 | 4 | '''file_name = raw_input("Enter file_name: ")
if len(file_name) ==0:
print "Next time enter something"
sys.exit()
try:
file_name = open(file_name, "r")
except IOError:
print "There was an error reading file"
sys.exit()
file_text = file.read()
file.close()
print file_text
list = ['pauline', 1, 3, 'John']
tuple = ('heroku', 14, 17, 'damaris')
list[3] = 2000
print list
tinydict = {'name:' 'Pauline', 'Age:', 26, 'Religion:', 'Christian'}
print tinydict
'''
items = [1, 2, 4, 4, 5 ,6, 7]
items2 = [45,67,86]
#print cmp(items, items2)
#print max(items2)
'''def maxno(num1):
max1 = None
for i in num1:
if i > max1: max1 = i
return i
print maxno([3, 4, 5, 90])
#print max(items)
'''
def reverse1(item):
for i in range(len(item) - 1, -1, -1):
print item[i]
# print items [::-1]
# del items[1:2];
# print items
reverse1([1, 2, 3, 4, 78, 45])
|
793b00d2049a48773e00442880d87510a25a04d3 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/leetcode/LeetcodePythonProject/leetcode_0051_0100/LeetCode099_RecoverBinarySearchTree.py | 1,127 | 3.703125 | 4 | '''
Created on Jan 31, 2017
@author: MT
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if not root: return
self.first = None
self.second = None
self.prev = None
self.inOrder(root)
if self.second and self.first:
val = self.second.val
self.second.val = self.first.val
self.first.val = val
def inOrder(self, root):
if not root:
return
self.inOrder(root.left)
if self.prev:
if root.val < self.prev.val:
if not self.first:
self.first = self.prev
self.second = root
self.prev = root
self.inOrder(root.right)
def test(self):
pass
if __name__ == '__main__':
Solution().test() |
a55389ad34ae76bbb10663130bf2dca2bd7018b6 | pythonjmc/guess-the-number | /guess-the-number-update.py | 1,616 | 3.640625 | 4 | import random
INVITE = "Suggest a number"
QUITTER = -1
QUIT_TXT = 'q'
QUIT_MSG = "Thanks for playing!"
QUIT_CONFIRMER = "Are you sure to leave the game ? (O/n) ?"
def confirmer_quitter():
confi = input(QUIT_CONFIRMER)
if confi == 'n':
return False
else:
return True
def jouer_tour():
nbr_secret = random.randint(1,100)
nbr_saisies = 0
while True:
nbr_joueur = input(INVITE)
if nbr_joueur == QUIT_TXT:
if confirmer_quitter():
return QUITTER
else:
continue
nbr_saisies = nbr_saisies + 1
if nbr_secret == int(nbr_joueur):
print("Correct")
return nbr_saisies
elif nbr_secret > int(nbr_joueur):
print("To small")
else:
print("To big")
total_tours = 0
total_saisies = 0
msg_stat = 0
while True:
total_tours = total_tours + 1
print("We go around " + str(total_tours))
print("forward to the guesswork!")
ce_tour = jouer_tour()
if ce_tour == QUITTER:
total_tours = total_tours - 1
if total_tours == 0:
msg_stat = "First round not finish ! " + "Would you restart ?"
else:
moy = str(total_saisies / float(total_tours))
msg_stat = "You did " + str(total_tours) + "round(s). Average of" + str(moy)
total_saisies = total_saisies + ce_tour
print("TYou did " + str(ce_tour) + "entries.")
moy = str(total_saisies / float(total_tours))
print("Your average number of entries/round= " + moy)
print("")
print(QUIT_MSG)
print(msg_stat)
|
53241eb8936747d3695d9b7697de9e35088d7a94 | MrDzhofik/Life_game | /main.py | 4,236 | 3.546875 | 4 | import pygame
import copy
class Board:
# создание поля
def __init__(self, width, height, left=10, top=10, cell_size=30):
self.width = width
self.height = height
self.board = [[0] * width for _ in range(height)]
# значения по умолчанию
self.set_view(left, top, cell_size)
# настройка внешнего вида
def set_view(self, left, top, cell_size):
self.left = left
self.top = top
self.cell_size = cell_size
def render(self):
color = ["black","green", "white", "blue", "yellow","red"]
for j in range(self.width):
for i in range(self.height):
pygame.draw.rect(screen, pygame.Color(color[self.board[i][j]]),
(self.left + self.cell_size * j, self.top + self.cell_size * i,
self.cell_size, self.cell_size))
pygame.draw.rect(screen, (255, 255, 255), (self.left + self.cell_size * j, self.top + self.cell_size * i,
self.cell_size, self.cell_size), 1)
def get_cell(self, mouse_pos):
cell_x = (mouse_pos[0] - self.left) // self.cell_size
cell_y = (mouse_pos[1] - self.top) // self.cell_size
if cell_x < 0 or cell_y < 0 or cell_x >= self.width or cell_y >= self.height:
return None
return cell_y, cell_x
def on_click(self, cell):
pass
def on_click_line(self, cell):
pass
def get_click(self, mouse_pos, msb):
cell = self.get_cell(mouse_pos)
if cell:
if msb == 1:
self.on_click(cell)
else:
self.on_click_line(cell)
class Life(Board):
def __init__(self, width, height, left=10, top=10, cell_size=30):
super().__init__(width, height, left, top, cell_size)
def on_click(self, cell):
self.board[cell[0]][cell[1]] = (self.board[cell[0]][cell[1]] + 1) % 2
def next_move(self):
# сохраняем поле
tmp_board = copy.deepcopy(self.board)
# пересчитываем
for y in range(self.height):
for x in range(self.width):
# сумма окружающих клеток
s = 0
for dy in range(-1, 2):
for dx in range(-1, 2):
if x + dx < 0 or x + dx >= self.width or y + dy < 0 or y + dy >= self.height:
continue
s += self.board[y + dy][x + dx]
s -= self.board[y][x]
if s == 3:
tmp_board[y][x] = 1
elif s < 2 or s > 3:
tmp_board[y][x] = 0
# обновляем поле
self.board = copy.deepcopy(tmp_board)
if __name__ == '__main__':
pygame.init()
size = width, height = 800, 600
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Игра «Жизнь»')
board = Life(53, 40, 0, 0, 15)
game_on = False
speed = 10
ticks = 0
fps = 60
clock = pygame.time.Clock()
running = True
while running:
screen.fill((0, 0, 0))
for event in pygame.event.get():
# при закрытии окна
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE or event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:
game_on = not game_on
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
board.get_click(event.pos, 1)
if event.button == 4:
speed += 1
if event.button == 5:
speed -= 1
# отрисовка и изменение свойств объектов
board.render()
# обновление экрана
if ticks >= speed:
if game_on:
board.next_move()
ticks = 0
pygame.display.flip()
clock.tick(fps)
ticks +=1
pygame.quit() |
5357f3226d19536f79e70db7637aa60cf8005fe8 | lucemia/cake | /6.py | 664 | 3.890625 | 4 | # https://www.interviewcake.com/question/python/rectangular-love
def inter(a, b, c, d):
if a <= c <= b:
return c, min(b, d)
if c <= a <= d:
return a, min(b, d)
return 0, 0
def solve(rect1, rect2):
min_x, max_x = inter(rect1["x"], rect1["x"] + rect1["width"], rect2["x"], rect2["x"] + rect2["width"])
min_y, max_y = inter(rect1["y"], rect1["y"] + rect1["height"], rect2["y"], rect2["y"] + rect2["height"])
if min_x == max_x == 0:
return {}
if min_y == max_y == 0:
return {}
return {
"x": min_x,
"y": min_y,
"width": max_x - min_x,
"height": max_y - min_y
}
|
7cd57acc6b796d20247b0ed45da9594b04afd336 | arjangupta/google-foobar | /braille-translation/solution.py | 2,510 | 4.0625 | 4 | def solution(s):
# Parameter s is the plain text word
output_str = ""
if type(s) is not str:
return output_str
for char in s:
output_str += braille_encode(char)
return output_str
def braille_encode(char):
# The encoding pattern followed here is given at https://braillebug.org/braillebug_answers.asp#w
# Known data for encoding
capital_char_prefix = "000001"
space_char_encoding = "000000"
letter_arr = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z']
first10_letter_decimal_values = [32, 48, 36, 38, 34, 52, 54, 50, 20, 22]
w_encoding = "010111" # w is an exception to the pattern. Binary string is found by: ( '0' + bin(22 + 1)[2:] )
# Begin building encoded char string
if char == ' ':
return space_char_encoding
encoded_str = ""
if char.isupper():
encoded_str += capital_char_prefix
char = char.lower()
if char == 'w':
encoded_str += w_encoding
return encoded_str
# Find which row and column the character belongs to
letter_column = letter_arr.index(char) % len(first10_letter_decimal_values)
letter_row = letter_arr.index(char) / len(first10_letter_decimal_values)
# The 3rd dot is raised if it's in the second row, and the 3rd and 6th dot is raised in the third row
letter_decimal_value = first10_letter_decimal_values[letter_column]
if letter_row == 1:
letter_decimal_value += 8
elif letter_row == 2:
letter_decimal_value += (8 + 1)
letter_binary_value = bin(letter_decimal_value)[2:] # omit the '0b' prefix
# Ensure that the binary string has a length of 6
if len(letter_binary_value) < 6:
number_of_zeros_to_prefix = 6 - len(letter_binary_value)
letter_binary_value = ('0' * number_of_zeros_to_prefix) + letter_binary_value
encoded_str += letter_binary_value
return encoded_str
def main():
# Read file without new lines
test_cases_file = open("test_cases.txt")
line_arr = [line[:-1] for line in test_cases_file]
# Run all three test cases
for i in range(0, len(line_arr), 2):
text_str = line_arr[i]
solved_str = solution( text_str )
binary_str = line_arr[i + 1]
if solved_str == binary_str:
print "TEST CASE #" + str(i) + " PASSED"
else:
print "TEST CASE #" + str(i) + " FAILED"
if __name__ == "__main__":
main() |
d7859bdf87e61c06e9365dab6f09ec3e8679c251 | ACM-VIT/PyFlask_2k18 | /datatypes/examples/string.py | 2,516 | 4.59375 | 5 | # Python Strings Examples
# capitalize
str = "this is string example....wow!!!";
print "str.capitalize() : ", str.capitalize()
str.capitalize() : This is string example....wow!!!
#count
str = "this is string example....wow!!!";
sub = "i";
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
sub = "wow";
print "str.count(sub) : ", str.count(sub)
str.count(sub, 4, 40) : 2
str.count(sub) : 1
#endswith
str = "this is string example....wow!!!";
suffix = "wow!!!";
print str.endswith(suffix)
print str.endswith(suffix,20)
suffix = "is";
print str.endswith(suffix, 2, 4)
print str.endswith(suffix, 2, 6)
True
True
True
False
#find
str1 = "this is string example....wow!!!";
str2 = "exam";
print str1.find(str2)
print str1.find(str2, 10)
print str1.find(str2, 40)
15
15
-1
#isalnum
str = "this2009"; # No space in this string
print str.isalnum()
str = "this is string example....wow!!!";
print str.isalnum()
True
False
#isalpha
str = "this"; # No space & digit in this string
print str.isalpha()
str = "this is string example....wow!!!";
print str.isalpha()
True
False
#isdigit
str = "123456"; # Only digit in this string
print str.isdigit()
str = "this is string example....wow!!!";
print str.isdigit()
True
False
#islower
str = "THIS is string example....wow!!!";
print str.islower()
str = "this is string example....wow!!!";
print str.islower()
False
True
#isalnum
str = u"this2009";
print str.isnumeric()
str = u"23443434";
print str.isnumeric()
False
True
#isupper
str = "THIS IS STRING EXAMPLE....WOW!!!";
print str.isupper()
str = "THIS is string example....wow!!!";
print str.isupper()
True
False
#len
str = "this is string example....wow!!!";
print "Length of the string: ", len(str)
Length of the string: 32
#islower
str = "THIS IS STRING EXAMPLE....WOW!!!";
print str.lower()
this is string example....wow!!!
#strip
str = "0000000this is string example....wow!!!0000000";
print str.strip( '0' )
this is string example....wow!!!
#replace
str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
print str.replace("is", "was", 3)
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
#join
s = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print s.join( seq )
a-b-c
#split
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( )
print str.split(' ', 1 )
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd'] |
e8d29ade9df695f4692e0586c5e82b94a6b645ff | PninaWinegarten/GoogleProject | /sentences_trie.py | 1,413 | 4.03125 | 4 |
class Node:
"""Define a single node in the trie"""
def __init__(self, char):
self.char = char
self.sentences_indexes = {}
self.children = {}
self.is_leaf = True
class SentencesTrie:
def __init__(self):
self.root = Node("")
def insert_sentence(self, sentence, index):
"""Insert the sentence to the trie"""
sentence = sentence.lower()
current_node = self.root
for ch in sentence:
if index[0] not in current_node.sentences_indexes:
current_node.sentences_indexes[index[0]] = index[1]
if not current_node.is_leaf:
if ch not in current_node.children:
current_node.children[ch] = Node(ch)
else:
current_node.is_leaf = False
current_node.children[ch] = Node(ch)
current_node = current_node.children[ch]
current_node.sentences_indexes[index[0]] = index[1]
def search_sentence(self, sentence, node):
"""Search for a sentence in the trie, start in the given node"""
sentence = sentence
current_node = self.root
for ch in sentence:
if ch not in current_node.children or current_node.is_leaf:
return None, node
current_node = current_node.children[ch]
return current_node.sentences_indexes, current_node
|
439b129bfeb1b49ca623f23d89d44d4f20c2ba91 | jnfrye/python_interactive_math | /py_interactive_math/formatting/display_math.py | 708 | 3.5 | 4 | """The base class for displaying mathematical expressions.
"""
from ..math.formula import Formula
class DisplayMath:
"""Base class for displaying mathematical expressions.
This handles rendering of the input formula (it can be thought of as a
`\begin{equation}...\end{equation}` block from LaTeX.)
"""
def __init__(
self,
formula: {
'type': Formula, 'help': "Formula to be rendered."},
name: {
'type': str, 'help': "Name of this expression "
"(for cross-referencing)"}):
"""Instantiate an object of this class."""
self.formula = formula
self.name = name
|
62892ee842bdee163944feb9658c75d8dd76616a | elisamartin/Data-Structures | /heap/max_heap.py | 2,343 | 3.875 | 4 | class Heap:
def __init__(self):
self.storage = []
def insert(self, value):
self.storage.append(value)
self._bubble_up(len(self.storage) - 1)
def delete(self):
swapped_value = self.storage[0]
self.storage[0] = self.storage[-1]
self.storage[-1] = swapped_value
self.storage.pop(-1)
self._sift_down(0)
return swapped_value
def get_max(self):
return self.storage[0]
def get_size(self):
return len(self.storage)
def _bubble_up(self, index):
# in worst case elem will need to make its way to the top of the heap
while index > 0:
# get parent elem of this index
parent = (index - 1) // 2
# check if elem at index is higjer priority then parent elem
if self.storage[index] > self.storage[parent]:
# if it is, swap them
self.storage[index], self.storage[parent] = self.storage[parent], self.storage[index]
# update index to be new spot that swapped elem now resides at
index = parent
else:
# otherwise, our element is at a valid spot in the heap
# we no longer need to buble up -> break
break
def _sift_down(self, index):
my_index = index
if len(self.storage) < 2:
return
while (2 * index) + 1 < len(self.storage):
left_child = (2 * index) + 1
right_child = (2 * index) + 2
if right_child > len(self.storage) - 1:
if self.storage[left_child] > self.storage[index]:
swapped_value = self.storage[left_child]
self.storage[left_child] = self.storage[index]
self.storage[index] = swapped_value
index = left_child
elif self.storage[left_child] > self.storage[right_child]:
if self.storage[left_child] > self.storage[index]:
swapped_value = self.storage[left_child]
self.storage[left_child] = self.storage[index]
self.storage[index] = swapped_value
index = left_child
else:
break
elif self.storage[right_child] > self.storage[index]:
swapped_value = self.storage[right_child]
self.storage[right_child] = self.storage[index]
self.storage[index] = swapped_value
index = right_child
else:
break
|
970f836a8fbc41796c322d269b6b8911fcd0e919 | vg11395n/Python | /24_packages.py | 513 | 3.78125 | 4 | # Task # 1: Create a function called dice and each time we roll t gives randon numbers
# Step 1. Create a class called Dice
# Step 2. Create a function called roll()
import random
from pathlib import Path
path = Path()
for file in path.glob("*.py"):
print(file)
# glob method is used to find a file in directory
class Dice:
def roll(self):
first = random.randint(1, 6)
second = random.randint(1, 6)
return first, second
dice = Dice()
print(dice.roll())
|
b62c1c3b2b3b1c3f8d0a66d1e0ca714404e8f333 | wonju5332/source | /PythonClass/Chap_11_oBject_cLass/distance_between_two_points.py | 586 | 4.125 | 4 | class point(object):
"""Represnets a point in 2-d space."""
import math
print(point) # class 'point'
blank = point() #인스턴스화 되었다.
print(blank) # 클래스와 메모리에 저장된 장소를 출력한다.
blank.x = 3.0
blank.y = 4.0
print(blank.y) #blank가 가리키는 객체로 가서 y의 값을 취하라.(y에 대입)
print(blank.x)
print('(%d, %d)' % (blank.x, blank.y))
distance = math.sqrt(blank.x**2 + blank.y**2) #int형식인듯? 계산되네
print(distance) # 5
def print_point(p):
print ('(%g, %g)' % (p.x, p.y))
print_point(blank)
|
597fec3b3fe25496691674e49749a0b5b8d0a5b7 | ag93/Leetcode | /Keyboard-Row.py | 679 | 3.859375 | 4 | class Solution:
def findWords(self, words: List[str]) -> List[str]:
row1 = set(['q','w','e','r','t','y','u','i','o','p'])
row2 = set(['a','s','d','f','g','h','j','k','l'])
row3 = set(['z','x','c','v','b','n','n','m'])
def convert_to_set(word):
s = set()
for c in word:
s.add(c.lower())
return s
result = []
for word in words:
word_set = convert_to_set(word)
if word_set.issubset(row1) or word_set.issubset(row2) or word_set.issubset(row3):
result.append(word)
return(result) |
b640e7212dfb0c646572b86ca0881c25236083b8 | HariMuthu/Python_Code | /Code/big_no_in_list.py | 653 | 3.96875 | 4 | #Finding the biggest number in the list
a = [int(a) for a in input('Enter the list of number : ').split()]
print(a)
l = len(a)
#print('L : ', l)
for i in range(0,l):
#print('\n' , a[i])
for j in range(i+1,l):
# print( 'j : ', j , '\n a[j] : ', a[j])
# b = j
if a[i] < a[j]:
break
else:
continue
else:
if i < (l-1):
print(a[i], 'is big')
break
else:
print(a[i], 'is big')
print('Finding the biggest number in different way')
b = [int(b) for b in input('Enter another set of numbers : ').split()]
max=0
for i in b:
if i > max:
max = i
print(max, ' is a maximum number')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.