blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
a0dbfb33ce7ede89c8328f5df0783cad98dac193 | phouse512/EECS-348 | /Sudoku/sudoku.py | 9,934 | 4.03125 | 4 | #!/usr/bin/env python
import struct, string, math, copy
from time import time
#this will be the game object your player will manipulate
class SudokuBoard:
#the constructor for the SudokuBoard
def __init__(self, size, board, constraintChecks):
self.BoardSize = size #the size of the board
self.CurrentGameboard= board #the current state of the game board
self.ConstraintChecks = constraintChecks
#This function will create a new sudoku board object with
#with the input value placed on the GameBoard row and col are
#both zero-indexed
def set_value(self, row, col, value):
self.CurrentGameboard[row][col]=value #add the value to the appropriate position on the board
return SudokuBoard(self.BoardSize, self.CurrentGameboard, self.ConstraintChecks) #return a new board of the same size with the value added
# parse_file
#this function will parse a sudoku text file (like those posted on the website)
#into a BoardSize, and a 2d array [row,col] which holds the value of each cell.
# array elements witha value of 0 are considered to be empty
def parse_file(filename):
f = open(filename, 'r')
BoardSize = int( f.readline())
NumVals = int(f.readline())
#initialize a blank board
board= [ [ 0 for i in range(BoardSize) ] for j in range(BoardSize) ]
#populate the board with initial values
for i in range(NumVals):
line = f.readline()
chars = line.split()
row = int(chars[0])
col = int(chars[1])
val = int(chars[2])
board[row-1][col-1]=val
return board
#takes in an array representing a sudoku board and tests to
#see if it has been filled in correctly
def iscomplete( BoardArray ):
size = len(BoardArray)
subsquare = int(math.sqrt(size))
#check each cell on the board for a 0, or if the value of the cell
#is present elsewhere within the same row, column, or square
for row in range(size):
for col in range(size):
if BoardArray[row][col]==0:
return False
for i in range(size):
if ((BoardArray[row][i] == BoardArray[row][col]) and i != col):
return False
if ((BoardArray[i][col] == BoardArray[row][col]) and i != row):
return False
#determine which square the cell is in
SquareRow = row // subsquare
SquareCol = col // subsquare
for i in range(subsquare):
for j in range(subsquare):
if((BoardArray[SquareRow*subsquare + i][SquareCol*subsquare + j] == BoardArray[row][col])
and (SquareRow*subsquare + i != row) and (SquareCol*subsquare + j != col)):
return False
return True
# creates a SudokuBoard object initialized with values from a text file like those found on the course website
def init_board( file_name ):
board = parse_file(file_name)
return SudokuBoard(len(board), board, 0)
# check to see if adding a value to a board will still allow for the board to be valid, returns True
# if the board with the new value is valid, otherwise returns false
def checkConstraints(board, newRow, newCol, newEntry):
size = len(board)
#get size of smaller squares
smallsquare = int(math.sqrt(size))
# check if any other cell in the row, column, or grid of the test cell has the test value
for i in range(size):
# check if rows are valid
if (board[newRow][i] == newEntry):
return False
# check if columns are valid
if (board[i][newCol] == newEntry):
return False
# determine which square the cell is in
currentSquareRow = newRow // smallsquare
currentSquareCol = newCol // smallsquare
for x in range(smallsquare):
for y in range(smallsquare):
testRow = currentSquareRow*smallsquare + x
testCol = currentSquareCol*smallsquare + y
if(board[testRow][testCol] == newEntry):
return False
return True
def getNextCell( sudoku ):
for row in range(sudoku.BoardSize):
for col in range(sudoku.BoardSize):
if ( sudoku.CurrentGameboard[row][col] == 0 ): return row, col
return -1, -1
def backtracking(sudoku):
global start_time
current_time = time()-start_time
if (current_time) > 30:
print 'Time Limit Exceeded \n'
return True
print int(current_time)
print "\n"
if((int(current_time)%10 == 0) and (current_time > 0)):
PrintBoard(sudoku)
#PrintBoard(sudoku)
nextrow, nextcol = getNextCell( sudoku )
if ( nextrow == nextcol == -1 ): return True
for value in range(1, sudoku.BoardSize+1):
sudoku.ConstraintChecks += 1
if checkConstraints(sudoku.CurrentGameboard, nextrow, nextcol, value):
sudoku.set_value(nextrow, nextcol, value)
## if board is full (must be valid due to constraint checks) - then return true
if (backtracking(sudoku)):
return True
## if value is not valid, leave blank
sudoku.set_value(nextrow, nextcol, 0)
## keep going
return False
def createEmptyPossibility(sudoku):
possibilityMatrix = [[range(1,sudoku.BoardSize+1) for row in range(sudoku.BoardSize)] for col in range(sudoku.BoardSize)]
for row in range(sudoku.BoardSize):
for col in range(sudoku.BoardSize):
value = sudoku.CurrentGameboard[row][col]
if (value != 0):
possibilityMatrix = updatePossibilityMatrix(sudoku, possibilityMatrix, row, col, value, 'removeFromPossibilityMatrix')
return possibilityMatrix
def updatePossibilityMatrix(sudoku, possibilityMatrix, currentRow, currentCol, value, action):
size = len(possibilityMatrix)
# if the value is in the same row/column, remove value
for i in range(size):
if action == 'removeFromPossibilityMatrix':
if (value in possibilityMatrix[currentRow][i]):
possibilityMatrix[currentRow][i].remove(value)
if (value in possibilityMatrix[i][currentCol]):
possibilityMatrix[i][currentCol].remove(value)
elif action == 'addFromPossibilityMatrix':
if (checkConstraints(sudoku.CurrentGameboard, currentRow, i, value) and (value not in possibilityMatrix[currentRow][i])):
possibilityMatrix[currentRow][i].append(value)
if (checkConstraints(sudoku.CurrentGameboard, i, currentCol, value) and (value not in possibilityMatrix[i][currentCol])):
possibilityMatrix[i][currentCol].append(value)
# calculate the subsquare
subsquare = int(math.sqrt(size))
SquareRow = currentRow // subsquare
SquareCol = currentCol // subsquare
for i in range(subsquare):
for j in range(subsquare):
row, col = SquareRow * subsquare + i, SquareCol * subsquare + j
if(value in possibilityMatrix[row][col] and action == 'removeFromPossibilityMatrix'):
possibilityMatrix[row][col].remove(value)
elif (action == 'addFromPossibilityMatrix' and (value not in possibilityMatrix[row][col]) and checkConstraints(sudoku.CurrentGameboard, row, col, value)):
possibilityMatrix[row][col].append(value)
return possibilityMatrix
# forward checking algorithm
def forwardChecking(sudoku, possibilityMatrix):
global start_time
if ( time() - start_time ) > 10:
print 'Time Limit Exceeded \n'
return True
if((time()-start_time)%10 == 0):
PrintBoard(sudoku)
nextrow, nextcol = getNextCell(sudoku)
#if board is full (and thereby valid), finish
if ( nextrow == nextcol == -1 ):
return True
# create a copy of the new possibilityMatrix, but use deepcopy because there are objects that need to be copied
newPossibilityMatrix = copy.deepcopy(possibilityMatrix[nextrow][nextcol])
for value in newPossibilityMatrix:
sudoku.ConstraintChecks += 1
if checkConstraints(sudoku.CurrentGameboard, nextrow, nextcol, value):
sudoku.set_value(nextrow, nextcol, value)
updatePossibilityMatrix(sudoku, possibilityMatrix, nextrow, nextcol, value, 'removeFromPossibilityMatrix')
if (forwardChecking(sudoku, possibilityMatrix)):
return True
sudoku.set_value(nextrow, nextcol, 0)
updatePossibilityMatrix(sudoku, possibilityMatrix, nextrow, nextcol, value, 'addFromPossibilityMatrix')
return False
def PrintBoard(sudokuboard):
board = sudokuboard.CurrentGameboard
size = len(board)
for i in range(size):
for j in range(size):
print board[i][j], "\t",
if(j == size-1):
print ""
print ""
x = input("Please input the size of the sudoku board (4,9,16): ")
if (x == 4 or x == 9 or x == 16 or x == 25):
puzzle_path = "%s_%s.sudoku" % (x, x)
else:
print "Please enter a valid size \n"
print "Testing backtracking \n"
backtrackBoard = init_board(puzzle_path)
start_time = time()
final = backtracking(backtrackBoard)
passed_time = time() - start_time
print 'Length of Time: %.2f' % passed_time
print 'Number of checks: %d' % backtrackBoard.ConstraintChecks
PrintBoard(backtrackBoard)
print 'Testing forward checking\n'
forwardCheckBoard = init_board(puzzle_path)
start_time = time()
possibilityMatrix = createEmptyPossibility(forwardCheckBoard)
final = forwardChecking(forwardCheckBoard, possibilityMatrix)
passed_time = time() - start_time
print 'Length of Time: %.2f' % passed_time
print 'Number of checks: %d' % forwardCheckBoard.ConstraintChecks
PrintBoard(forwardCheckBoard)
|
cce7eac35e4be919fa31b450a62aba7956e308ed | ContactTracingCU/Stop-the-Spread-Server | /contactTracing/coordinateMath.py | 690 | 3.671875 | 4 | # coordinateMath.py takes two coordinates and returns distance in feet
# oder of coordinates in lat and long lists (function parameters) does not matter
import math
def coordinateMath(lats, longs):
# convert to km * convert to ft
convert = (20000 / 180) * 3280.84
# radius of the eart
radius = 6378
location1_lat = lats[0] * convert
location1_long = longs[0] * convert
location2_lat = lats[1] * convert
location2_long = longs[1] * convert
dist = math.sqrt((location2_lat - location1_lat)**2 + (location2_long-location1_long)**2)
# print('Distance in a straight line from location 1 to location 2 is: {} feet'.format(distInFeet))
return dist |
a988ee095cdb926c6815c5e84f90cd08ad05ea9d | adam-weiler/GA-Reinforcement-Exercises | /2-Programming-Fundamentals/exercise.py | 1,654 | 4.46875 | 4 | #Exercise 1
all_grades = ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F'] #List stores all letter grades.
def display_grade(num_grade, position): #Returns percent grade and letter grade.
return (f'With a grade of {num_grade}, you get an {all_grades[position]}.')
def get_letter_grade(num_grade): #Based on user input, calls display_grade with appropriate reference for the list.
if 97 <= num_grade < 100:
return display_grade(num_grade, 0)
elif 93 <= num_grade < 97:
return display_grade(num_grade, 1)
elif 90 <= num_grade < 93:
return display_grade(num_grade, 2)
elif 87 <= num_grade < 90:
return display_grade(num_grade, 3)
elif 83 <= num_grade < 87:
return display_grade(num_grade, 4)
elif 80 <= num_grade < 83:
return display_grade(num_grade, 5)
elif 77 <= num_grade < 80:
return display_grade(num_grade, 6)
elif 73 <= num_grade < 77:
return display_grade(num_grade, 7)
elif 70 <= num_grade < 73:
return display_grade(num_grade, 8)
elif 67 <= num_grade < 70:
return display_grade(num_grade, 9)
elif 63 <= num_grade < 67:
return display_grade(num_grade, 10)
elif 60 <= num_grade < 63:
return display_grade(num_grade, 11)
elif 0 <= num_grade < 60:
return display_grade(num_grade, 12)
else:
return ('That is an invalid selection.')
def ask_for_grade(): #Asks user for their grade as a percentage.
print('What is your grade percentage?')
grade_percentage = float(input())
return get_letter_grade(grade_percentage)
print(ask_for_grade())
|
c0c56717224a5329dc0e77ee82a66844ff813dd9 | ashish-bisht/ds_algo_handbook | /top_k_elements/kth_smallest_num.py | 614 | 3.921875 | 4 | import heapq
def find_Kth_smallest_number(nums, k):
heapq.heapify(nums)
res = float("inf")
for _ in range(k):
res = heapq.heappop(nums)
return res
def main():
print("Kth smallest number is: " +
str(find_Kth_smallest_number([1, 5, 12, 2, 11, 5], 3)))
# since there are two 5s in the input array, our 3rd and 4th smallest numbers should be a '5'
print("Kth smallest number is: " +
str(find_Kth_smallest_number([1, 5, 12, 2, 11, 5], 4)))
print("Kth smallest number is: " +
str(find_Kth_smallest_number([5, 12, 11, -1, 12], 3)))
main()
|
e397fcd70619f636e588717d18f1fd92a753706f | Nicholas-Riegel/FreeCodeCamp-Python-Solutions | /budget_app/test0.py | 2,514 | 3.578125 | 4 | class Category:
def __init__(x, name):
x.name = name
x.ledger = list()
x.balance = 0
def deposit(x, amount, description):
x.ledger.append({
'amount': amount,
'description': description,
})
x.balance += amount
def withdraw(x, amount, description):
if x.check_funds(amount):
x.ledger.append({
'amount': 0-amount,
'description': description,
})
x.balance -= amount
def get_balance(x):
return x.balance
def transfer(x, amount, budget_category):
if x.check_funds(amount):
x.ledger.append({
'amount': 0-amount,
'description': 'Transfer to ' + budget_category.name,
})
x.balance -= amount
budget_category.balance += amount
budget_category.ledger.append({
'amount': amount,
'description': 'Transfer from ' + x.name,
})
def check_funds(x, amount):
if x.balance > amount:
return True
else:
return False
def __str__(x):
result = x.name.center(30, '*') + '\n'
for y in x.ledger:
result += y['description'].ljust(23) + format(y['amount'], '.2f').rjust(7) + '\n'
result += 'Total: ' + format(x.balance, '.2f')
return result
Food = Category('Food')
Food.deposit(100, 'Initial deposit')
Food.withdraw(20.75, 'Apples')
Clothing = Category('Clothing')
Clothing.deposit(100, 'Initial deposit')
Food.transfer(20, Clothing)
Clothing.withdraw(56.72, 'Jeans')
Beer = Category('Beer')
Beer.deposit(200, 'Initial deposit')
Beer.withdraw(76.42, 'Guiness')
Beer.withdraw(25.00, 'Guiness')
print(Food)
print(Clothing)
print(Beer)
category_list = list()
category_list.append(Food)
category_list.append(Clothing)
category_list.append(Beer)
def create_spend_chart(categories_list):
result = 'Percentage spent by category'
total_withdrawals = 0
withdrawals_by_cat = dict()
for x in category_list:
withdrawals_by_cat[x.name] = 0
for y in x.ledger:
if y['amount'] < 0 and y['description'].split(' ')[0] != 'Transfer':
total_withdrawals += y['amount'] * -1
withdrawals_by_cat[x.name] += y['amount'] * -1
print('\nTotal Withdrawals:', total_withdrawals)
print(withdrawals_by_cat)
create_spend_chart(category_list)
|
ffba21062dcd7ccb77324f8942cebabf011736e7 | Sobolp/GB_python_base | /HW2/3.py | 558 | 4.25 | 4 | """
3. Сформировать из введенного числа обратное по порядку входящих в него
цифр и вывести на экран. Например, если введено число 3486,
то надо вывести число 6843.
"""
a = str(int(input('Введите натуральное число: ')))
def reverse(s):
# print(s)
if len(s) == 2:
return s[-1] + s[0]
if len(s) == 1:
return s[0]
return s[-1] + reverse(s[1:len(s) - 1]) + s[0]
print(reverse(a))
|
9420b34ca340d2db7677bc45561175fc8cbb8759 | markimoo999/MYPYTHONSTUFF | /wholeClass.py | 961 | 4.15625 | 4 | import random
i = 0
score = 0
othscore = 0
print ("let's play rock paper scissors!")
while i<5:
options = ["rock", "paper", "scissors"]
computer= random.randint(0,2)
comChoice = options[computer]
print( comChoice)
player = input("rock, paper, scissors,\n")
if comChoice==player:
print ("tie")
elif player == "rock" and comChoice=="paper" or player=="scissors" and comChoice=="rock" or player == "paper" and comChoice=="scissors":
print ("you lose")
othscore = othscore + 1
score = score - 1
elif (player == "rock" and comChoice=="scissors" or player=="scissors" and comChoice=="paper" or player == "paper" and comChoice=="rock"):
print ("you win")
score = score + 1
othscore = othscore - 1
i =i+1
print( "i'm done. your score was ", score, " and my score was ", othscore,".")
|
63580791d826a7fa56f90e3262aca432bbef8c9b | buichitrung2001/Project1 | /Basic/test2_global_variable.py | 974 | 3.65625 | 4 | '''
def spam():
print(eggs) #biến eggs đc coi là biến toàn cục
eggs = 42
spam()
print(eggs)
'''
#=================================================================================================
'''
def spam():
eggs = 'spam local' #biến eggs lại đc coi là biến địa phương vì ta đã khai báo eggs = ...
print(eggs) # prints 'spam local'
def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'
'''
#=================================================================================================
'''
def spam():
print(eggs) # ERROR!
eggs = 'spam local'
eggs = 'global'
spam()
'''
#=================================================================================================
#Using global var in function
'''
def spam():
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs)
'''
|
8583509ae7b2df36d13e2619e2fc4a7f4ca3ac6f | Marthalamule/Advent-of-Code-2017-Python3 | /Day1/solution.py | 2,610 | 4.125 | 4 | # Advent of Code 2017, Day One
# Python 3.6
# You're standing in a room with "digitization quarantine" written in LEDs along one wall. The only door is locked,
# but it includes a small interface. "Restricted Area - Strictly No Digitized Users Allowed."
#
# It goes on to explain that you may only leave by solving a captcha to prove you're not a human. Apparently,
# you only get one millisecond to solve the captcha: too fast for a normal human, but it feels like hours to you.
#
# The captcha requires you to review a sequence of digits (your puzzle input) and find the sum of all digits that
# match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the
# list.
#
# For example:
#
# 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2)
# matches the fourth digit.
# 1111 produces 4 because each digit (all 1) matches the next.
# 1234 produces 0 because no digit matches the next.
# 91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
#
# What is the solution to your captcha?
captcha_num = 0
digit_list = []
with open('day_one_input.txt', 'r') as si:
for digit in si.read():
digit_list.append(int(digit))
shift_list = digit_list[1:] + digit_list[:1]
for digit_one, digit_two in zip(digit_list, shift_list):
if digit_one == digit_two:
captcha_num += digit_one
print(captcha_num)
# --- Part Two ---
#
# You notice a progress bar that jumps to 50% completion. Apparently, the door isn't yet satisfied,
# but it did emit a star as encouragement. The instructions change:
#
# Now, instead of considering the next digit, it wants you to consider the digit halfway around the circular list.
# That is, if your list contains 10 items, only include a digit in your sum if the digit 10/2 = 5 steps forward matches
# it. Fortunately, your list has an even number of elements.
#
# For example:
#
# 1212 produces 6: the list contains 4 items, and all four digits match the digit 2 items ahead.
# 1221 produces 0, because every comparison is between a 1 and a 2.
# 123425 produces 4, because both 2s match each other, but no other digit has a match.
# 123123 produces 12.
# 12131415 produces 4.
#
# What is the solution to your new captcha?
captcha_half = 0
half_list = len(digit_list)//2
shift_list = digit_list[half_list:] + digit_list[:half_list]
for digit_one, digit_two in zip(digit_list, shift_list):
if digit_one == digit_two:
captcha_half += digit_one
print(captcha_half)
|
ea5a27618665cd1a2a0d6231a775b9c0cc554337 | GodBlackCoder/python-study | /py/oop/iter.py | 293 | 3.59375 | 4 | class Fib(object):
def __init__(self, bound):
self.bound = bound
self.a,self.b = 0,1
def __iter__(self):
return self
def next(self):
self.a,self.b = self.b , self.a + self.b
if self.a > self.bound :
raise StopIteration()
return self.a
for n in Fib(100):
print n
|
c64ba593ed0f4fccfb4f022a7b750ad8d598b712 | ElHa07/Python | /Curso Python/Aula07/Exercicios/Exercicios01.py | 311 | 3.8125 | 4 | # Exercicio em Python 01
#Exercicios: Faça um programa que mostre na tela uma contagem regreciva para o estouro de fogos de artificios, indo de 10 até 0, com uma pausa de 1 segundo entre eles
from time import sleep
for cont in range(10, -1, -1):
print(cont)
sleep(0.5)
print('FELIZ ANO NOVO !')
|
306ba26c7f57b2c9e7de7c1788f0159d0c8606f2 | haveano/codeacademy-python_v1 | /05_Lists and Dictionaries/01_Python Lists and Dictionaries/13_Remove a Few Things.py | 664 | 4.15625 | 4 | """
Remove a Few Things
Sometimes you need to remove something from a list.
beatles = ["john","paul","george","ringo","stuart"]
beatles.remove("stuart")
print beatles
>> ["john","paul","george","ringo"]
We create a list called beatles with 5 strings.
Then, we remove the first item from beatles that matches the string "stuart". Note that .remove(item) does not return anything.
Finally, we print out that list just to see that "stuart" was actually removed.
Instructions
Remove 'dagger' from the list of items stored in the backpack variable.
"""
backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
print backpack
backpack.remove("dagger")
print backpack
|
8745ff328ad007b8dcd86c2bfa633496d8dc4753 | saidskander/holbertonschool-higher_level_programming | /0x03-python-data_structures/7-add_tuple.py | 275 | 3.71875 | 4 | #!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
i = ()
for x in (tuple_a, tuple_b):
if len(x) == 0:
x = (0, 0)
elif len(x) == 1:
x = (x[0], 0)
if i == ():
i = x
return x[0] + i[0], x[1] + i[1]
|
2b4ac0f3817427bb3533f1c07fabfba147bfac75 | chdprimary/python-practice | /codewars-solutions/find_the_odd_int.py | 320 | 4 | 4 | # Given an array, find the int that appears an odd number of times.
# There will always be only one integer that appears an odd number of times.
def find_it(seq):
for item in seq:
indices = [i for i, v in enumerate(seq) if seq[i] == item]
if len(indices) % 2 != 0:
return seq[indices[0]] |
99b71452b7026161c59995738337c04d49110686 | shuruqbo/saudidevorg | /day34.py | 537 | 4.15625 | 4 | #function 1
def thisFunction(fruits):
for x in fruits:
print(x)
f = [ "banana", "ornges", " apples"]
thisFunction(f)
print("-----")
# function 2
def thisFunction2(x):
return x * 3
print(thisFunction2(2))
print("-----")
# function 3
def thisFunction3(*kids):
print(kids)
thisFunction3("sara", "mohammed ", "ahmad")
print("-----")
# function 4
def thisRecursion(rec):
if(rec > 0):
results = rec + thisRecursion(rec-1)
print(results)
else:
results = 0
return results
print("recursion example:")
thisRecursion(8)
|
5bbe332f683e3b9228bf058887cc4d31e164e2b4 | oreo0701/openbigdata | /01_jumptopy/end_of_chap/basic_test_02.py | 514 | 4 | 4 | def ordinal(number):
if number == 1:
return "1st"
elif number == 2:
return "2nd"
elif number == 3:
return "3rd"
elif number >= 4:
return f"{number}th"
count = 0
while True:
name = (input("안녕하세요. 이름을 입력하세요: "))
count += 1
if count <= 10:
print(f"Hi {name}!! You are {ordinal(count)} person come here!\n")
else:
print(f"Sorry {name}. The event is closed because you are {ordinal(count)} person come here\n")
|
05864e466481d6231ca3e195009a01ab5e4f9064 | AZelentsov343/interview_tasks | /merge_overlapping_intevals.py | 854 | 3.984375 | 4 | #You are given an array of intervals - that is, an array of tuple
#(start, end). The array may not be sorted, and could contain
#overlapping intervals. Return another array where the overlapping
#intervals are merged.
#For example:
#[(1, 3), (5, 8), (4, 10), (20, 25)]
#This input should return [(1, 3), (4, 10), (20, 25)] since (5, 8) and
#(4, 10) can be merged into (4, 10).
def merge(intervals): #O(n * log(n))
intervals = sorted(intervals, key = lambda x: x[0]) #O(n * log(n))
output = []
ending = None
for i, interval in enumerate(intervals): #O(n)
if i == 0 or interval[0] > ending:
output.append(interval)
ending = interval[1]
elif ending < interval[1]:
output[-1][1] = interval[1]
ending = interval[1]
return output
print(merge([(1, 3), (5, 8), (4, 10), (20, 25)]))
# [(1, 3), (4, 10), (20, 25)]
|
74987aa6edbbbbbcd62eddba7f9120e87437a12d | chithien0909/Competitive-Programming | /Leetcode/Leetcode - Add Binary.py | 1,757 | 3.734375 | 4 | """
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
Each string consists only of '0' or '1' characters.
1 <= a.length, b.length <= 10^4
Each string is either "0" or doesn't contain any leading zero.
"""
class Solution:
def addBinary(self, a: str, b: str) -> str:
if len(a) * len(b) == 0: return a + b
a = a[::-1]
b = b[::-1]
c = '0'
ans = []
lesserLength = min(len(a), len(b))
for i in range(lesserLength):
if a[i] == b[i]:
ans.append(c)
c = a[i]
else:
if c == '1':
ans.append('0')
else:
ans.append('1')
for i in range(lesserLength, len(a)):
if c == '1':
if a[i] == '1':
ans.append('0')
else:
ans.append('1')
c = '0'
else:
ans.append(c)
ans.append(a[lesserLength +1 :])
break
for i in range(lesserLength, len(b)):
if c == '1':
if b[i] == '1':
ans.append('0')
else:
ans.append('1')
c = '0'
else:
ans.append(c)
ans.append(b[lesserLength +1 :])
break
ans.append(c)
ans = ''.join(ans[::-1]).lstrip('0')
return '0' if len(ans) == 0 else ans
s = Solution()
print(s.addBinary("0", "0")) |
7c5153a26dd6c37cc82b8482fa90d83345d53a4e | mateosceia/repositorio | /practica 2/ej 6.py | 324 | 4.03125 | 4 | caracter1 = input("Inserte una palabra: ")
caracter2 = input("Inserte una palabra: ")
caracter3 = input("Inserte una palabra: ")
caracter4 = input("Inserte una palabra: ")
caracter5 = input("Inserte una palabra: ")
lista = [caracter1, caracter2, caracter3, caracter4, caracter5]
lista1 = list(reversed(lista))
print(lista1)
|
beb25ce3261d087270ff2618c0a68dce20c42638 | meghanagottapu/Leetcode-Solutions | /leetcode_py/Implement Stack using Queues.py | 1,484 | 4 | 4 | class Stack:
# initialize your data structure here.
def __init__(self):
self.q1 = []
# @param x, an integer
# @return nothing
def push(self, x):
self.q1.append(x)
# @return nothing
# remove the tail
def pop(self):
lens = len(self.q1)
for i in range(lens - 1):
tmp = self.q1.pop(0)
self.q1.append(tmp)
self.q1.pop(0)
# @return an integer
# get the tail of the queue
def top(self):
lens = len(self.q1)
for i in range(lens):
tmp = self.q1.pop(0)
self.q1.append(tmp)
return tmp
# @return an boolean
def empty(self):
if self.q1:
return False
return True
class Stack:
# initialize your data structure here.
def __init__(self):
self.q1 = []
self.q2 = []
# @param x, an integer
# @return nothing
def push(self, x):
self.q1.append(x)
# @return nothing
def pop(self):
while self.q1:
tmp = self.q1.pop(0)
if self.q1:
self.q2.append(tmp)
self.q1 = self.q2
self.q2 = []
# @return an integer
def top(self):
while self.q1:
tmp = self.q1.pop(0)
self.q2.append(tmp)
self.q1 = self.q2
self.q2 = []
return tmp
# @return an boolean
def empty(self):
if self.q1:
return False
return True
|
0aa42d312ec115769fa5e58e290995a007a8cc94 | chenhh/Uva | /uva_488.py | 650 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Authors: Hung-Hsin Chen <chenhh@par.cse.nsysu.edu.tw>
License: GPL v2
status: AC
difficulty: 1
http://luckycat.kshs.kh.edu.tw/homework/q488.htm
"""
def wave(A):
msg = []
for idx in range(1, A+1):
msg.append(str(idx)*(idx))
for idx in range(A-1, 0, -1):
msg.append(str(idx)*(idx))
return msg
def main():
n = int(input())
for idx in range(n):
_ = input()
A = int(input())
F = int(input())
for jdx in range(F):
msg = wave(A)
print("\n".join(msg))
if idx != n-1 or jdx != F-1:
print ()
if __name__ == '__main__':
main() |
4cde02547b3b5101c1c08716111c3590e53e606b | aymane081/python_algo | /trees/add_one_row_to_tree.py | 1,408 | 3.796875 | 4 | # 623
from utils.treeNode import TreeNode
# time: O(N)
# space: O(N) or the max number of node at each level
class Solution:
def add_row(self, root, v, d):
if d == 1:
new_root = TreeNode(v)
new_root.left = root
return new_root
current_level = [root]
while d > 2:
d -= 1
new_level = []
for node in current_level:
if node.left:
new_level.append(node.left)
if node.right:
new_level.append(node.right)
current_level = new_level
# current_level is at d - 1
for node in current_level:
node.left, node.left.left = TreeNode(v), node.left
node.right, node.right.right = TreeNode(v), node.right
return root
# one = TreeNode(1)
# two = TreeNode(2)
# three = TreeNode(3)
# four = TreeNode(4)
# five = TreeNode(5)
# six = TreeNode(6)
# four.left = two
# four.right = six
# two.left = three
# two.right = one
# six.left = five
one = TreeNode(1)
two = TreeNode(2)
three = TreeNode(3)
four = TreeNode(4)
five = TreeNode(5)
six = TreeNode(6)
four.left = two
# four.right = six
two.left = three
two.right = one
# six.left = five
print(four)
print('==============')
solution = Solution()
print(solution.add_row(four, 1, 3))
|
55991f54f97e266eb8edd28f1289a9cf967a8628 | ghamerly/nondeterminism | /sat.py | 409 | 3.625 | 4 | from nondeterminism import *
@nondeterministic
def satisfiable(formula):
x = guess()
y = guess()
z = guess()
if formula(x, y, z):
accept()
else:
reject()
def formula(x, y, z):
return ((x or y) and
(y or z) and
(not x or z))
if satisfiable(formula):
print('The formula is satisfiable')
else:
print('The formula is not satisfiable')
|
1478cf0d29a995e228431766446935f942b7779b | Mahisakapal/jenkins | /my.py | 221 | 3.8125 | 4 | i=1
while i<=11:
print(F"help {i}")
i=i+1
# now we will take sum
total =0
i = 1
while i<=10 :
total += i # herer totao is zero but it incer by i
i += 1 # this is same as i = i + 1
|
7f1f5e98015a0d83bad57d8892926adde2b23b4b | Gustovus/PFB_problemsets | /Python_Problemsets/problemset4_split.py | 216 | 3.625 | 4 | #!/usr/bin/env
import sys
species = "sapiens, erectus, neanderthalensis"
print(species)
print (species.split(','))
species_list = species.split(',')
print(sorted(species_list))
print(sorted(species_list,key=len))
|
87fff2fae7615a897d6383294c89be77c255f2ff | sreevidyachintala/Sending-Mail | /email1.py | 790 | 3.953125 | 4 | def sendmail():
send=int(input("How many friends to send email:\n"))
friends=[]
emails=[]
message=input("Enter Message To Send:\n")
if send!=0:
for s in range(0,send):
name=input("Enter Friend Name:\n")
email=input("Enter Friend Email:\n")
friends.append(name)
emails.append(email)
print(s)
import smtplib
server=smtplib.SMTP("smtp.gmail.com",587)
server.starttls()#transport layer security#ssl
server.login("sreevidyachintala16@gmail.com","kvsb8897523679")
for friend in range(0,len(friends)):
print(message,":",friends[friend],":",emails[friend])
server.sendmail("sreevidyachintala16@gmail.com",emails[friend],message)
server.quit()
sendmail()
|
c3cbba6634fdfc964a815ac64cfd523c38306cf9 | Adarsh1193/Python-Udemy-Course | /Control Structures/Coding Challenge 2.py | 182 | 3.625 | 4 | food = ["Pizza", "Chicken Bowl", "Burger", "Burrito", "Momos"]
print(food)
print(food[2])
food.append("Mozzarella Sticks")
print(food)
food.insert(3, "Tacos")
print(food) |
ec36d1b4ce3c53e6c7fc3f912d1fe5381e7089aa | KangMin-gu/Python_work | /Hello/test/Step12_Quiz.py | 672 | 3.59375 | 4 | #-*- coding:utf-8 -*-
'''
input() 함수를 이용해서 숫자를 입력 받아서
2 를 입력하면 구구단 2단 출력
3 을 입력하면 구구산 3단 출력
.
.
하는 코드를 작성해 보세요.
출력형식
- 구구단 2 단 -
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
.
.
'''
dan=input("출력할 구구단:")
info=u'- 구구단 {} 단 -'.format(dan)
print info
for i in range(1, 10, 1):
# i를 1~9 까지 변하게 하고 결과값을 계산한다.
result=dan*i
# 결과값을 형식에 맞게 출력하기
print '{} x {} = {}'.format(dan, i, result)
|
bdfa5a80bdfafd09ee4075e67960f17003024a9a | lyuts/hack-a-vator2015 | /floor.py | 2,562 | 3.515625 | 4 | from person import Person
from signalslot import Signal
class Floor(object):
def __init__(self, num, height):
"""
height = ft
"""
self.__num = num
self.__height = height
self.__people = [] # people currently on the floor (not necessarily waiting for elevators)
self.__queue = [] # people requested the elevator and currently waiting for one
self.__signal_elevator_requested = Signal(args=['from_floor', 'to_floor'])
self.__signal_people_boarded = Signal(args=['elevator_id', 'floor_num', 'people'])
@property
def height(self):
return self.__height
@property
def num(self):
return self.__num
@property
def people(self):
return self.__people
@property
def queue(self):
return self.__queue
@property
def signal_elevator_requested(self):
return self.__signal_elevator_requested
@property
def signal_people_boarded(self):
return self.__signal_people_boarded
def door_opened(self, floor_num, direction, available_capacity, people_inside, elevator_id, **kwargs):
if floor_num != self.num:
return
newcomers = []
for p in self.queue:
print 'Checking', p
if len(people_inside) == 0:
newcomers.append(p)
elif len(newcomers) < available_capacity and goes_up == (p.curr_floor < p.dest_floor):
newcomers.append(p)
for n in newcomers:
self.queue.remove(n)
print 'Floor [%s] %s will board' % (self.num, len(newcomers))
self.signal_people_boarded.emit(elevator_id=elevator_id, floor_num=self.num, people=newcomers)
def tick(self, timedelta):
# example
# if self.num == 3:
p = None
if self.num == 1:
pass
# p = Person(self.num, 2)
# self.people.append(p)
elif len(self.people) > 0:
p = self.people.pop(0)
if p:
self.signal_elevator_requested.emit(from_floor=p.curr_floor, to_floor=p.dest_floor)
self.__queue.append(p)
pass
def getNextPerson(self):
"""
return list of people waiting for the elevator
"""
# gen random number to represent how many people are waiting
if self.__num == 1:
# gen new person
pass
else:
# take new person from the list
pass
def elevator_doors_open(self, id, **kwargs):
pass
|
8241d85965f24a91f130830fa323cec3930f1383 | 21tushar/Python-Tutorials | /Dictionaries(sentdex).py | 133 | 3.96875 | 4 | dict = {'Michael': [22, 'White'], 'Bob': [20, 'Red'], 'Alex': [24, 'Green']}
for key, value in dict.items():
print(key, value)
|
5787ec43116155d2b16d300bcb9a768c707c223a | jjnich/Personal | /py/eu7.py | 328 | 3.8125 | 4 | import math
from time import time
def isPrime( n ):
if n % 2 == 0 and n > 2: return False
return all(n%i for i in range(3, int(math.sqrt(n))+1, 2))
guess=3
primeCount=1
t=time()
while primeCount<10001:
if isPrime(guess):
primeCount+=1
if primeCount==10001:break
guess+=2
print "time",time()-t,"\nanswer",guess
|
0d6e40b6c22a1c989e6c4e2c2212909e41cf4deb | limuzi19942018/personal_python | /data_structure/dict_class.py | 940 | 4.40625 | 4 |
'''
创建一个字典
dict1 = {"key1": "value1", "key2": "value2"}
print(dict1)
创建一个空字典
dict2 = {}
print(dict2)
通过键来访问一个字典里面的key值
dict1 = {"key1": "value1", "key2": "value2"}
print(dict1["key1"])
通过字典的get方法来获取一个值,没有该键,可以指定一个值返回,在这里我们指定的是None
dict1 = {"key1": "value1", "key2": "value2"}
print(dict1.get("key1", None))
遍历字典
dict1 = {"key1": "value1", "key2": "value2"}
for item in dict1:
print(item, dict1[item])
往字典里面添加一个元素
dict1 = {"key1": "value1", "key2": "value2"}
dict1["key3"] = "value3"
for item in dict1:
print(item, dict1[item])
判断一个键是否在字典里面
dict1 = {"key1": "value1", "key2": "value2"}
key = "key1"
if key in dict1:
print(dict1[key])
'''
dict1 = {"key1": "value1", "key2": "value2"}
key = "key1"
if key in dict1:
print(dict1[key])
|
338c5fd01c1d83de5586b347dcabeae06dbcbbfc | the-carpnter/codewars-level-7-kata | /rule_of_divisibility_7.py | 136 | 3.5 | 4 | def seven(m, steps=0):
if len(str(m)) <= 2:
return m, steps
return seven(int(str(m)[:-1]) - 2*int(str(m)[-1]), steps+1)
|
0ef4973d2ec3bcd01950a8d02a72389b2b72053a | yeongseon/PyCon-KR-2019 | /05-Mock/src/calculator_2.py | 941 | 3.78125 | 4 | """
"""
import logging
logging.basicConfig(level=logging.INFO)
class Calculator():
"""Calculator class"""
def __init__(self):
self.logger = logging.getLogger(self.__class__.__name__)
"""
def add(self, a, b):
self.logger.info(
"add {a} to {b} is {result}".format(
a=a, b=b, result=a + b
))
return a + b
"""
def add(self, a, b):
if not isinstance(a, int):
raise ValueError
if not isinstance(b, int):
raise ValueError
self.logger.info(
"add {a} to {b} is {result}".format(
a=a, b=b, result=a + b
))
return a + b
@staticmethod
def subtract(a, b):
return a - b
@staticmethod
def multiply(a, b):
return a * b
@staticmethod
def divide(a, b):
return a / b
calculator = Calculator()
calculator.add(1, 2)
|
cb20a0c16eb6e4c941d2353e35363b77acaff3d6 | NguyenVanThanhHust/Python_Learning | /Draps_TV_Advance/Advanced_Lecture2_argparge.py | 1,547 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 11 19:00:29 2018
@author: admin
"""
# =============================================================================
#
# to learn how to use argparse
# argument parsing for python program
# =============================================================================
# This function is to take a number and return its finbonatci
import argparse
def fib(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
def Main():
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action = "store_true")
group.add_argument("-q", "--quite", action = "store_true")
parser.add_argument("num", help = "The finbonatci number you you wish to calculate", type = int)
# -o for shortcut of --output
parser.add_argument("-o", "--output", help = "Output result to a file ", \
action = "store_true")
args = parser.parse_args()
result = fib(args.num)
print("The " + str(args.num)+"th fib number is " + str(result))
# if args.output:
# f = open("finbonatci.txt", "a")
# f.write(str(result) + '\n')
if args.verbose:
print("The " + str(args.num) + "th fib number is " + str(result))
elif args.quite:
print(result)
else:
print("Fib " + str(result))
if __name__ == '__main__':
Main()
# how to use
# open command in folder containing this file
# command : python Advanced_Lecture2_argparge.py -h
# above cmd is to show option
# below cmd is to show calculate
# command : python Advanced_Lecture2_argparge.py 10
|
2a1f2599ad261b8a4d6a67ca87bfb766b855c9a9 | srinathsubbaraman/python_assignments | /problem set 2/power.py | 567 | 4.1875 | 4 | '''
Name :power.py
Date :04/12/2017
Author :srinath.subbaraman
Question::A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is_power that takes parameters a and b and returns True if a is a power of b. Note: you will have to think about the base case.?
'''
def is_power(a,b):
if a==b:
return True
elif a%b==0:
return is_power(a/b,b)
else:
print 'not divisible'
return False
a=int(raw_input('enter the first number'))
b=int(raw_input('enter the second number'))
print is_power(a,b)
|
04c1eff5968e5d50305cc1a78f0b1f5e081fd007 | atucom/dotfiles | /bin/atu-ip-consolidator.py | 980 | 3.53125 | 4 | #!/usr/bin/env python3
#takes in a file of one-per-line IPs and consolidates them into ranges
#@atucom
import ipaddress
import argparse
import sys
import re
result = []
def consolidate(ipobj):
result.append(ipobj)
for ipstr in iparry:
ipstr = ipstr.strip(' \t\r')
ipobj2 = ipaddress.ip_address(ipstr)
if ipobj + 1 == ipobj2:
result.append(ipobj2)
iparry.remove(ipstr)
consolidate(ipobj2)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("FILE" ,help='The input file of one-per-line IPs to consolidate')
args = parser.parse_args()
if args.FILE:
with open(args.FILE, 'r') as f:
iparry = f.read().splitlines()
for ipstr in iparry:
ipstr = ipstr.strip(' \t\r')
consolidate(ipaddress.ip_address(ipstr))
if ipaddress.ip_address(ipstr) == result[-1]:
print(result[-1])
else:
print("%s - %s" % (ipaddress.ip_address(ipstr), result[-1]))
else:
exit(1) |
43ea297ba9c568850b70ac19be0d5190ab3d1ca6 | mollinaca/ac | /code/practice/arc/arc018/a.py | 103 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
H,B = map(float,input().split())
print (B*((H/100)**2))
|
617eb2ccc7cd635065dcd1088b7619e70bdb424e | orehush/pasha-labs | /lab4_heap.py | 881 | 3.921875 | 4 | def max_heapify(array, i):
left = 2 * i + 1
right = 2 * i + 2
length = len(array) - 1
largest = i
if left <= length and array[left] > array[i]:
largest = left
if right <= length and array[right] > array[largest]:
largest = right
if largest != i:
array[i], array[largest] = array[largest], array[i]
max_heapify(array, largest)
def build_max_heap(array):
for i in reversed(range(len(array)//2)):
max_heapify(array, i)
def print_heap(array):
row = 0
index = 0
cnt = 1
while index < len(array):
print(array[index], end=' ')
if cnt == index + 1:
row += 1
cnt += 2**row
print()
index += 1
if __name__ == '__main__':
arr = [4, 5, 4, 78, 43, 56, 21, 67, 33, 56, 87, 5, 44]
build_max_heap(arr)
print(arr)
print_heap(arr)
|
2ed65d6fe9753deee555f8d865d85ed750ed47b4 | alexalvg/cursoPython | /EjsListas-Tuplas.py/DUDA4.8.py | 480 | 4.1875 | 4 | #Escribir un programa que pida al usuario una palabra
# y muestre por pantalla si es un palíndromo.
word = list(input("Introduce una palabra: "))
#LIST te hace una lista separandote cada uno de las letras
#ejemplo: word = list(input(introduce la palabra...))
#print(word) --> ["h", "o", "l", "a"]
print(word)
word_al_reves = word
word_al_reves.reverse()
reves = word_al_reves
print(reves)
if word == reves:
print("Es un palíndromo")
else:
print("no es un palíndromo") |
28cff074996c7ef8a6ab25e4eec1d73b79c62577 | infinite-Joy/programming-languages | /python-projects/algo_and_ds/ipo.py | 2,177 | 3.53125 | 4 | """
for each we can add the
greedy solution
we sort based on the capital that is provided and the one that we have currently
based on that we choose the one with the highet profits
and for the answer we add the profits of the chosen projects.
"""
from heapq import heappush, heappop
def find_max_capital(profits, capital, k, w):
cp = sorted(list(zip(capital, profits)))
profit_heap = []
curr = w
j = 0
for i in range(k):
while j < len(cp) and curr >= cp[j][0]:
heappush(profit_heap, (-cp[j][1], j))
# curr_max_capital = cp[profit_heap[0][1]][1]
j += 1
if profit_heap:
max_capital = heappop(profit_heap)[1] # once we have accepted a project we should probably not use that anymore.
curr_max_capital = cp[max_capital][1]
curr += curr_max_capital
return curr
# k = 2
# w = 0
# profits = [1,2,3]
# capital = [0,1,1]
# print(find_max_capital(profits, capital, k, w))
# k = 3
# w = 0
# profits = [1,2,3]
# capital = [0,1,2]
# print(find_max_capital(profits, capital, k, w))
k = 1
w = 0
profits = [1,2,3]
capital = [1,1,2]
print(find_max_capital(profits, capital, k, w))
# ===================
# current implementation
from heapq import heappop, heappush
class Solution:
def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:
def find_max_capital(profits, capital, k, w):
cp = sorted(list(zip(capital, profits)))
profit_heap = []
curr = w
j = 0
for i in range(k):
while j < len(cp) and curr >= cp[j][0]:
heappush(profit_heap, (-cp[j][1], j))
# curr_max_capital = cp[profit_heap[0][1]][1]
j += 1
# once we have accepted a project we should probably not use that anymore.
if profit_heap:
max_capital = heappop(profit_heap)[1]
curr_max_capital = cp[max_capital][1]
curr += curr_max_capital
return curr
return find_max_capital(profits, capital, k, w) |
6068eca6626fb450205b4db88031cfc8acd6e201 | Abdoulaye77/Abdoulaye77 | /TP 1 PYTHON/tp1_exercice11.py | 420 | 3.765625 | 4 |
from random import randrange
n = 0
print("\t\t\t\t=== LE JEU DU PLUS OU MOINS ===\n\n")
nm = randrange(1, 100)
while n != nm:
print("Quel est le nombre ?")
n = input()
n = int(n)
if n < nm:
print("C'est trop petit !\n")
elif n > nm:
print("C'est trop grand !\n")
else:
print("Félicitations, vous avez trouvé le nombre mystère !!!\n")
|
f8eb78fb94b74490a419e65be3ee082eb8c3758b | MartinKotkamae/prog_alused | /yl3.3.py | 146 | 3.5625 | 4 | import random
taringuarv = int(input("Täringute arv: "))
while taringuarv > 0:
arv = random.randint(1,6)
print(arv)
taringuarv -= 1 |
5e75483cd3374249c60d395c678fc87117bef144 | arnabs542/Competitive-Programming | /Codelearn.io/Basic Algorithm/Sequence/isMonotonous.py | 540 | 3.578125 | 4 | # Cho một mảng các số nguyên,
# bạn hãy viết hàm kiểm tra xem các phần tử của mảng có tạo thành một dãy số tăng dần hoặc giảm dần hay không,
# nếu có return true, ngược lại return false.
def isMonotonous(sequence):
f = 1
for i in range(len(sequence)-1):
if sequence[i]<=sequence[i+1]:
f = 0
break
if f:
return True
for i in range(len(sequence)-1):
if sequence[i]>=sequence[i+1]:
return False
return True |
a0650bc877e065e0657d2ecc6e38078d35195638 | AngelVasquez20/APCSP | /Challenge 10.py | 342 | 3.765625 | 4 | def standard():
par_3 = int(input("How many par 3 holes are there?"))
par_5 = int(input("How many par 5 holes are there?"))
adjust = int(input("Difficulty adjustment?"))
shot_3 = (par_3 * 3)
shot_5 = (par_5 * 5)
scratch = (shot_5 + shot_3) - adjust
print("The standard scratch is " + str(scratch))
standard()
|
fd55976b60c8ab2a04ecb9e7d3d1e39d62020253 | setnicka/advent-of-code-2020 | /25-Combo_Breaker/solve.py | 578 | 3.515625 | 4 | #!/usr/bin/python3
card_pkey = int(input())
door_pkey = int(input())
card_loop_size = 0
v = 1
while v != card_pkey:
v = (v * 7) % 20201227
card_loop_size += 1
print("Card loop size is", card_loop_size)
# door_loop_size = 0
# v = 1
# while v != door_pkey:
# v = (v * 7) % 20201227
# door_loop_size += 1
# print("Door loop size is", door_loop_size)
v = 1
for i in range(card_loop_size):
v = (v * door_pkey) % 20201227
print("Encryption key:", v)
# v = 1
# for i in range(door_loop_size):
# v = (v * card_pkey) % 20201227
# print("Encryption key:", v)
|
b46cbb995127a3db8227bc9292911589178b077e | sssandesh9918/Python-Basics | /Functions/5.py | 512 | 4.15625 | 4 | '''Write a Python function to calculate the factorial of a number (a non-negative
integer). The function accepts the number as an argument.'''
#using inbuilt function
import math
print(math.factorial(4))
#using user defined function
def fact(n):
z=1
if n==0:
return 1
for i in range(n,0,-1):
z=z*i
return z
n=int(input("Enter a non-negative number to find the factorial of"))
try:
if n>0:
z=fact(n)
print(z)
except:
print("Please enter positive number only")
|
e9f582b3da53faad87f1819634e162136476ea57 | tyronehunt/learnpythonthehardway | /lpthw_ch8_printing.py | 325 | 3.546875 | 4 | formatter = "{} {} {} {}"
print (formatter.format(1,2,3,4))
print (formatter.format("one","two","three","four"))
print (formatter.format(True,False,True,False))
print (formatter.format(formatter,formatter,formatter,formatter ))
print(formatter.format(
"The owl",
"and the",
"pussy cat",
"went out to sea"
)) |
ee5a785ceccd00f395aa9ac79985f896df1caa70 | mqueiroz1995/algorithms | /data_structures/src/Queue.py | 352 | 3.671875 | 4 | from src.LinkedList import LinkedList
class Queue:
def __init__(self):
self.lst = LinkedList()
def is_empty(self):
return len(self.lst) == 0
def enqueue(self, data):
self.lst.insert_tail(data)
def dequeue(self):
return self.lst.remove_head()
def peek(self):
return self.lst.get_head()
|
be153400b5a9524fcbb922680c89793a39b97188 | s1c5000/learn_code | /python_study/Study/Numpy_study.py | 5,339 | 3.796875 | 4 | #다차원 배열을 효과적으로 처리할 수 있도록 도와주는 도구, 기본 list보다 빠르다
import numpy as np
a = [0,1,2,4]
array = np.array(a)
print(array) # [0 1 2 4]
print(array.size) # 4
print(array.dtype) # int32
print(array.shape) # (4,)
print(array.ndim) # 1
print(array.reshape((2,2)))
array1 = np.arange(4) # 0~3배열 만들기
print(array1) # [0 1 2 3]
array2 = np.zeros((4,4), dtype=float) # 4*4 이고 값들이 0인 행렬을 만듬, dtype로 type설정 가능
print(array2)
'''
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
'''
array3 = np.ones((3,3), dtype=str) # dtype를 문자열로도 지정가능
print(array3)
print(array3.shape) # (3, 3)
array4 = np.random.randint(0,10,(3,3)) # 0부터9까지 정수를 랜덤하게 초기화된 3*3배열 만들기
print(array4)
print()
array5 = np.random.normal(0,1,(3,3)) # 평균이 0이고 표준편차가 1인 표준정규를 띄는 배열
print(array5)
print()
print(np.concatenate([array, array1],)) # concatenate : 행렬 합치기, 1*4행렬을 합쳐서 1*8행렬 만든다,
# [0 1 2 4 0 1 2 3], axis는 축을 의미 1은 세로축 0은 가로축
array6 = np.concatenate([array4,array5], axis = 1) # 3*3행렬 2개를 합쳐서 3*6행렬이된다. "axis = 1" 세로를 축으로 합침
print(array6)
print(array6.shape) # (3, 6)
array7 = array1.reshape((2,2)) # 1*4 행렬을 2*2 행렬로 만들어준다
print(array7)
array8 = np.arange(8).reshape(2,4) # 0부터8까지 2*4행렬로 만들라
left, right = np.split(array8, [2], axis=1) #3번째열을 기준으로 세로로 나눠라
print(left.shape) #(2, 2)
print(array8)
'''
[[0 1 2 3]
[4 5 6 7]]'''
print(left)
'''
[[0 1]
[4 5]]'''
print(right[1][1]) # 7
array9 = array8 * 10 # 각 원소에 10을 곱한다, 더하기 빼기 나누기 가능
print(array9)
# 서로다른 형태의 배열도 연산가능, 행을 우선으로 한다.
array10 = np.arange(4) # [0,1,2,3]
print(array8 + array10)
'''
[[ 0 2 4 6]
[ 4 6 8 10]]
'''
# 2*4 행렬 + 1*4행렬의 덧샘시 1*4행렬의 값들이 2*4행렬의 행마다 더해진다.
# 4*4 행렬 + 4*1행렬의 경우 4*1행렬의 값들이 4*4행렬의 열마다 더해진다.
# 마스킹
array11 = np.arange(16).reshape(4,4)
print()
array12 = array11 < 10 # bool형태로 배열생성
print(array12)
'''
[[ True True True True]
[ True True True True]
[ True True False False]
[False False False False]]
'''
array11[array12] = 100 # 마스킹 된 배열을 사용해서 특정원소의 값들을 조작할 수 있다.
print(array11)
'''
[[100 100 100 100]
[100 100 100 100]
[100 100 10 11]
[ 12 13 14 15]]
'''
print(np.max(array11)) # 최댓값 100
print(np.min(array11)) # 최솟값 10
print(np.sum(array11)) # 합 1075
print(np.mean(array11)) # 평균 67.1875
# 행과 열에 대해서도 연산이 가능
print(np.sum(array11, axis=0)) # [312 313 224 226] 가로축끼리 더한다. (열 별 합계)
print(np.mean(array11, axis= 1)) #[100. 100. 55.25 13.5 ] 세로축끼리 평균을 냄 ( 행 별 평균)
# 저장과 불러오기
array13 = np.arange(0,16).reshape(4,4)
#np.save('C:/Users/LEEMINJUN/python_study/Study/numpy_saved.npy', array13) # 단일객체 저장
result = np.load('C:/Users/LEEMINJUN/python_study/Study/numpy_saved.npy') # 단일객체 불러오기
print(result)
array14 = np.arange(5)
array15 = np.arange(7)
#np.savez('C:/Users/LEEMINJUN/python_study/Study/numpy_savez.npz', first_array = array14, second_array = array15) # 복수객체 저장
# 복수일때 확장자는 npz를 쓰고, '이름 = 변수' 형태로 저장,
data = np.load('C:/Users/LEEMINJUN/python_study/Study/numpy_savez.npz') # 파일을 불러온다
result1 = data['first_array'] # 파일에서 이름으로 찾아 꺼내 쓴다
result2 = data['second_array']
print(result1, result2) #[0 1 2 3 4] [0 1 2 3 4 5 6]
array16 = np.arange(10,0,-1) #[10 9 8 7 6 5 4 3 2 1]
array16.sort() # sort()함수는 기본적으로 오름차순으로 정렬을 수행한다
print(array16) # [ 1 2 3 4 5 6 7 8 9 10]
print(array16[::-1]) #[10 9 8 7 6 5 4 3 2 1] , 내림차순
array17 = np.array([[1,6,2],[9,2,7],[7,2,4]])
array17.sort(axis=0) # 가로축으로 정렬(열을 기준으로 정렬)
print(array17)
'''
[[1 2 2]
[7 2 4]
[9 6 7]]
'''
#균일한 간격으로 데이터 생성
array18 = np.linspace(0,10,5) # 0부터 10까지 5개의 데이터를 균일하게 생성하라
print(array18) # [ 0. 2.5 5. 7.5 10. ]
# 난수의 재연 ( 실행마다 결과 동일)
np.random.seed(9) # seed 값을 9에서 4로 바꾼뒤 다시 9로 바꿔서 출력을해보면 처음9로 실행했을때의 값이 바뀌지않고 나온다.
print(np.random.randint(0,10,(2,4)))
t = np.random.randint(0,10,(2,2))
print(t)
# numpy배열객체의 복사
array19 = np.arange(0,10)
array20 = array19 # numpy의 배열은 주소를 공유하게된다.
array20[0] = 99 # 주소가 같으므로 array19의 값도 바뀐다.
print(array19) # [99 1 2 3 4 5 6 7 8 9]
array21 = np.arange(0,10)
array22 = array21.copy() # array21의 값이 복사되서 array22에 할당
array22[0] = 99 # 주소가 달라서 array21의 값은 바뀌지않는다.
print(array21) # [0 1 2 3 4 5 6 7 8 9]
#중복원소 제거
array23 = np.array([1,1,2,2,2,4,4,4])
print(np.unique(array23)) #[1 2 4]
|
652ad3f7423dc4adb1dff7dd95915c19e6d4a938 | bMedarski/SoftUni | /Python/ProgramingBasic/ComplexConditionalStatements/02.SmallShop.py | 1,146 | 3.8125 | 4 | product = input().lower()
town = input().lower()
quantity = float(input())
if product == 'coffee' and town == 'sofia':
print(quantity*0.5)
elif product == 'coffee' and town == 'plovdiv':
print(quantity*0.4)
elif product == 'coffee' and town == 'varna':
print(quantity * 0.45)
elif product == 'water' and town == 'sofia':
print(quantity*0.8)
elif product == 'water' and town == 'plovdiv':
print(quantity*0.7)
elif product == 'water' and town == 'varna':
print(quantity * 0.7)
elif product == 'beer' and town == 'sofia':
print(quantity*1.2)
elif product == 'beer' and town == 'plovdiv':
print(quantity*1.15)
elif product == 'beer' and town == 'varna':
print(quantity * 1.10)
elif product == 'sweets' and town == 'sofia':
print(quantity*1.45)
elif product == 'sweets' and town == 'plovdiv':
print(quantity*1.3)
elif product == 'sweets' and town == 'varna':
print(quantity * 1.35)
elif product == 'peanuts' and town == 'sofia':
print(quantity*1.60)
elif product == 'peanuts' and town == 'plovdiv':
print(quantity*1.50)
elif product == 'peanuts' and town == 'varna':
print(quantity * 1.55) |
a1810e8b8423e6a3c078870f7d10655fd2b1c440 | jethridge13/Project-Euler-Python-Scripts | /21.py | 1,027 | 3.75 | 4 | # The sum of all amicable numbers under 10000
import time
import functions
def isAmicable(n):
divisors = functions.getDivisors(n)
if len(divisors) > 0:
divisors.remove(max(divisors))
dSum = sum(divisors)
sumDivisors = functions.getDivisors(dSum)
if len(sumDivisors) > 0:
sumDivisors.remove(max(sumDivisors))
secondSum = sum(sumDivisors)
if secondSum == n and secondSum != dSum:
return (n, dSum)
return (-1, -1)
start = time.time()
amicableNumbers = []
for i in range(1, 10000):
if i not in amicableNumbers:
d = isAmicable(i)
if d[0] != -1:
if d[0] not in amicableNumbers:
amicableNumbers.append(d[0])
if d[1] not in amicableNumbers:
amicableNumbers.append(d[1])
print(amicableNumbers)
print("The sum of all amicable numbers between 1 and 10,000 is " + str(sum(amicableNumbers)) + ".")
functions.printTimeElapsed(start)
# Answer: The sum of all amicable numbers between 1 and 10,000 is 31626. |
8b7fe0be8530289d22bbd45e43fb8a1b0b07a0e1 | lpython2006e/student-practices | /12_Nguyen_Lam_Manh_Tuyen/3.4.py | 1,409 | 4.15625 | 4 | #Update previous one, allow to enter multiple classmate, at end, allow to save to file as CSV format
import pandas
def getinput():
while True:
name = input("Please input student name\n")
if len(name)<=12:
break
else:
print("Name can only contain a maximum of 12 characters")
continue
while True:
birth = input("Please input student birthday mm/dd/yy \n")
if len(birth)<=8:
break
else:
print("Birthday can only contain a maximum of 8 characters")
continue
while True:
email = input("Please input student email\n")
if len(email)<=50:
break
else:
print("Name can only contain a maximum of 50 characters")
continue
return name,birth,email
def multiple_input():
name, birthday, email=[],[],[]
num=int(input(" How many students do you want to add?\n"))
for i in range(0,num):
temp=list(getinput())
name.append(temp[0])
birthday.append(temp[1])
email.append(temp[2])
return name, birthday, email
class_list=list(multiple_input())
print("Your enter the Student info:",class_list)
filename = input("Please input file name \n")
df = pandas.DataFrame(data={"Name": class_list[0], "Birthday": class_list[1],"Email":class_list[2]})
df.to_csv(filename, sep=',',index=False) |
9cdfb2f5837107c742f1c30826e27b358b0a6e81 | sharmak/python | /ds/Coins.py | 1,575 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 20 22:51:29 2014
@author: kishor
"""
"""
Given a value N, if we want to make change for N cents, and
we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins,
how many ways can we make the change? The order of coins doesn’t matter.
For example, for N = 4 and S = {1,2,3},
there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}.
So output should be 4.
For N = 10 and S = {2, 5, 3, 6},
there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5}
and {5,5}. So the output should be 5.
To understand this, we need handle two cases:
a) Exclude Nth value
b) Include Nth value
"""
from copy import deepcopy
def coins(s, n):
if n == 0:
return 1
if n < 0:
return 0
if len(s) == 0:
return 0
# Case1: exclude nth value
s1 = deepcopy(s)
removed_value = s1.pop()
w1 = coins(s1, n)
# Case 2 include nth value
s2 = deepcopy(s)
w2 = coins(s2, n-removed_value)
return w1 + w2
def coins_dp(s, n):
bag = list()
bag.append(0)
max_count = 0
for i in xrange(1,n+1):
curr_count = 0
for coin in s:
if i - coin < 0:
continue
curr_count = bag[i-coin] + 1
if curr_count > max_count:
max_count = curr_count
bag.append(max_count)
#print bag
return bag[-1]
if __name__ == '__main__':
print coins([1,2,3], 4)
print coins([2,5,3,6], 10)
print coins_dp([1,2,3], 4)
print coins_dp([2,5,3,6], 10) |
5caf9f5c7ed1974db41652cb917c47c39343f954 | coding-Benny/algorithm-interview | /Programmers/Level1/add-digits-of-number.py | 311 | 3.5 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/12931
def solution(n: int) -> int:
total = 0
while n > 0:
digit = n % 10
total += digit
n = n // 10
return total
if __name__ == '__main__':
res = solution(123)
print(res)
res = solution(987)
print(res)
|
8c6d991e038ad5cb5e56dc39adf5b989e5f2d232 | HalfLeaf/interview | /docs/bytedance/leetcode/editor/cn/1/[21]合并两个有序链表.py | 1,087 | 4.0625 | 4 | # 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
#
#
#
# 示例 1:
#
#
# 输入:l1 = [1,2,4], l2 = [1,3,4]
# 输出:[1,1,2,3,4,4]
#
#
# 示例 2:
#
#
# 输入:l1 = [], l2 = []
# 输出:[]
#
#
# 示例 3:
#
#
# 输入:l1 = [], l2 = [0]
# 输出:[0]
#
#
#
#
# 提示:
#
#
# 两个链表的节点数目范围是 [0, 50]
# -100 <= Node.val <= 100
# l1 和 l2 均按 非递减顺序 排列
#
# Related Topics 递归 链表
# 👍 1495 👎 0
# 21 - merge-two-sorted-lists
from typing import List
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
s = Solution()
print(s.()) |
dd7e4dd24494c0bfd0d68a57520010596d4c8770 | snehashis1997/mlp-ondevice-training | /scripts/histogram.py | 4,566 | 3.875 | 4 | #Mahdi
#This file reads the output from the simulator
#and generates the histogram based on the values and accuracy
import matplotlib.pyplot as plt
import struct
import math
import sys
########################## ONLY CHANGE THIS SECTION ###########################
int_bits = 5
frac_bits = 10
base = 2
###############################################################################
# function for returning fractions
def calcul(val):
totalfrac = 0
intval = int(val[1:(int_bits+1)],base)
for i in range(int_bits + 1, frac_bits + int_bits + 1):
frac = int(val[i],base) * base**(-(i-int_bits))
totalfrac += frac
if (int(val[0], 0) == 0): return(totalfrac + intval)
else: return(-1 * (totalfrac + intval))
# function for returning fractions
def calcul2(val):
totalfrac = 0
intval = int(val[1:(int_bits+2)],2)
for i in range(int_bits + 2, frac_bits + int_bits + 1):
frac = int(val[i],0) * base**(-(i-int_bits-1))
totalfrac += frac
if (int(val[0], 0) == 0): return(totalfrac + intval)
else: return(-1 * (totalfrac + intval))
# function for parsing the data
def data_parser(text, dic):
for i, j in dic.iteritems():
text = text.replace(i,j)
return text
values = [1.2, 2.3, 1.2]
bins=[0.2, 1.1, 2.4, 3.5]
r = []
acc = []
reps = {'*':' ','+':' ',':':' ','=':' ',' ':' ','\n':''}
realreps = open("realreps.dat","r")
inputfile = open("out.dat","r")
outputfile = open("out2.dat","w")
#read the values in fixed.point format and do the computation
#every line has arguments
for line in realreps:
line2 = data_parser(line, reps)
temp = line2.split(" ")
print("Here is real rep values:")
print(float(temp[0]) + float(temp[2]))
print(float(temp[0]) * float(temp[2]))
#Exact values from computation: now in log domain
print("Here is real rep values in log:")
num1 = math.log(float(temp[0]), base)
num2 = math.log(float(temp[2]),base)
cf = math.log(1 + base ** (-abs(num1-num2)), base)
print(math.pow(base, max(num1, num2) + cf ))
print(math.pow(base, math.log(float(temp[0]),base) + math.log(float(temp[2]),base)) )
#Approximation: values from computation in log domain
print("Approximated cf in log:")
num1 = math.log(float(temp[0]), base)
num2 = math.log(float(temp[2]),base)
print(num1, num2)
cf = base ** (-abs(num1-num2)) #in hardware approx. using a shifter
print(math.pow(base, max(num1, num2) + cf ))
print(math.pow(base, math.log(float(temp[0]),base) + math.log(float(temp[2]),base)) )
opType = input()
#read back the generated values from verilog computation
print("Here is values read back from FPGA:")
if(opType == "add"):
for line in inputfile:
line2 = data_parser(line, reps)
temp = line2.split(" ")
#unpack the string values to binary
val1 = struct.unpack('16s', temp[0])[0] #X
val2 = struct.unpack('16s', temp[8])[0] #Y
res = struct.unpack('16s', temp[13])[0]
#compute exact and approx values
exact = (base ** calcul(res))
approx = (base**calcul(val1) + base**calcul(val2))
dev = abs(approx - exact)
print( calcul(val1) ,"+", calcul(val2), "=", calcul(res))
print( "Exact number:" , (base**calcul(val1) + base**calcul(val2)) )
print( "Hardware Approx. number:", base ** calcul(res))
print( "r is:", abs(calcul(val1) - calcul(val2)), "acc rate is:", abs(exact - dev)/exact )
r.insert (0, abs(calcul(val1) - calcul(val2))) # r = |X - Y|
acc.insert (0, abs(exact - dev) / exact) # acc% = approx./exact
elif (opType == "mult"):
for line in inputfile:
line2 = data_parser(line, reps)
temp = line2.split(" ")
#unpack the string values to binary
val1 = struct.unpack('16s', temp[0])[0] #X
val2 = struct.unpack('16s', temp[8])[0] #Y
res = struct.unpack('17s', temp[13])[0]
#compute exact and approx values
exact = (base ** calcul2(res))
approx = (base**calcul(val1) * base**calcul(val2))
dev = abs(approx - exact)
print( calcul(val1) ,"*", calcul(val2), "=", calcul2(res), "which was", res)
print( "Exact number:" , (base**calcul(val1) * base**calcul(val2)) )
print( "Hardware Approx. number:", base ** calcul2(res))
r.insert (0, abs(calcul(val1) - calcul(val2))) # r = |X - Y|
acc.insert (0, abs(exact - dev) / exact) # acc% = approx./exact
else:
print("Sorry, operator not supported.")
sys.exit(0)
plt.scatter(r,acc)
plt.xlabel('r = |X - Y|', fontsize=18)
plt.ylabel('accuracy %', fontsize=16)
plt.show()
#close files
inputfile.close()
outputfile.close()
|
55eca6762a36901da4660bca6861da13d6d20967 | flavius87/aprendiendo-python | /11-ejercicios/ejercicio3.py | 424 | 4 | 4 | """
Ejercicio 3: programa que compruebe si una variable está vacía.
Y si está vacía rellenarla con texto en minúscula y mostrarlo en mayúsculas.
"""
# comprobar variable
texto = ""
if len(texto.strip()) <= 0:
print("La variable está vacía")
else:
print("La variable tiene contenido", len(texto))
variable_vacia = "piletazo"
if len(texto) <= 0:
print(variable_vacia)
print(variable_vacia.upper())
|
e08ff65de14ef591ff549ea982d48f241f46febd | sandeepyadav10011995/Data-Structures | /Pattern-Two Pointers/7. DutchNationalFlag.py | 2,323 | 4.15625 | 4 | """
In problems where we deal with sorted arrays (or LinkedLists) and need to find a set of elements that fulfill certain
constraints, the Two Pointers approach becomes quite useful. The set of elements could be a pair, a triplet or even a
sub-array.
Problem Statement : Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the
array as objects, hence, we can’t count 0s, 1s, and 2s to recreate the array.
The flag of the Netherlands consists of three colors: red, white and blue; and since our input array
also consists of three different numbers that is why it is called Dutch National Flag problem.
Algo: We can use a Two Pointers approach while iterating through the array. Let’s say the two pointers are called low
and high which are pointing to the first and the last element of the array respectively. So while iterating, we
will move all 0s before low and all 2s after high so that in the end, all 1s will be between low and high.
Example 1:
Input: [1, 0, 2, 1, 0]
Output: [0, 0, 1, 1, 2]
Example 2:
Input: [2, 2, 0, 1, 2, 0]
Output: [0, 0, 1, 2, 2, 2,]
"""
from typing import List
from collections import deque
class DutchNationalFlag:
@staticmethod
def dutch_flag_sort(nums: List[int]) -> List[int]:
# all elements < low ==> 0 and,
# all elements > high ==> 2
# all elements from >= low and < i ==> 1
low = 0
high = len(nums) - 1
i = 0
while i <= high:
if nums[i] == 0:
nums[i], nums[low] = nums[low], nums[i]
# Increment "i" and "low"
i += 1
low += 1
elif nums[i] == 1:
i += 1
else: # The case for nums[i] == 2
nums[i], nums[high] = nums[high], nums[i]
# Decrement "high" only, after the swapping the number at index "i" ==> Ca be anything i.e, 0, 1, 2.
high -= 1
def main():
dnf = DutchNationalFlag()
arr = [1, 0, 2, 1, 0]
dnf.dutch_flag_sort(arr)
print(arr)
arr = [2, 2, 0, 1, 2, 0]
dnf.dutch_flag_sort(arr)
print(arr)
main()
"""
Time Complexity: N(for-loop)*N*N(creating sub-arrays) ==> O(N^3)
Space Complexity: O(N)
"""
|
6e9e0df78035905766fd132682d4b885cd635f9b | ankurmukherjeeuiuc/BinomialBlackScholes_Richardson-Extrapolation | /BinomialBS_Richardson Extrapolation.py | 6,541 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
import pandas as pd
import os
import matplotlib.pyplot as plt
import numpy as np
# Binomial Tree Option Valuation Cox, Ross, Rubinstein method by "www.quantandfinancial.com"
import matplotlib.pyplot as plt
import numpy as np
def Binomial(n, S, K, r, v, t, PutCall):
At = t/n
u = np.exp(v*np.sqrt(At))
d = 1./u
p = (np.exp(r*At)-d) / (u-d)
#Binomial price tree
stockvalue = np.zeros((n+1,n+1))
stockvalue[0,0] = S
for i in range(1,n+1):
stockvalue[i,0] = stockvalue[i-1,0]*u
for j in range(1,i+1):
stockvalue[i,j] = stockvalue[i-1,j-1]*d
#option value at final node
optionvalue = np.zeros((n+1,n+1))
for j in range(n+1):
if PutCall=="C": # Call
optionvalue[n,j] = max(0, stockvalue[n,j]-K)
elif PutCall=="P": #Put
optionvalue[n,j] = max(0, K-stockvalue[n,j])
#backward calculation for option price
for i in range(n-1,-1,-1):
for j in range(i+1):
if PutCall=="P":
optionvalue[i,j] = max(0,
K-stockvalue[i,j],
np.exp(-r*At)*(p*optionvalue[i+1,j]+(1-p)*optionvalue[i+1,j+1]))
elif PutCall=="C":
optionvalue[i,j] = max(0,
stockvalue[i,j]-K,
np.exp(-r*At)*(p*optionvalue[i+1,j]+(1-p)*optionvalue[i+1,j+1]))
return optionvalue[0,0]
# Inputs
n = 300 #input("Enter number of binomial steps: ") #number of steps
S = 100 #input("Enter the initial underlying asset price: ") #initial underlying asset price
r = 0.03 #input("Enter the risk-free interest rate: ") #risk-free interest rate
K = 105 #input("Enter the option strike price: ") #strike price
v = 0.2 #input("Enter the volatility factor: ") #volatility
t = 1.
"""### put"""
z = [-x + K - Binomial(n, S, K, r, v, t, "P") for x in range(K)]
z += [-Binomial(n, S, K, r, v, t, "P")] * (K)
plt.plot(range(2*K), z, color='red')
plt.axis([0, 2*K, min(z) - 10, max(z) + 10])
plt.xlabel('Underlying asset price')
plt.ylabel('Profits')
plt.axvline(x=K, linestyle='--', color='black')
plt.axhline(y=0, linestyle=':', color='black')
plt.title('American Put Option')
plt.text(105, 0, 'K')
plt.show()
"""### Plot the Put Price Over time"""
price_list_of_Binomial_put=[]
for i in range(1,201):
price_list_of_Binomial_put.append(Binomial(i, S, K, r, v, t, "P"))
plt.plot(price_list_of_Binomial_put)
len(price_list_of_Binomial_put)
"""### Balck Scholes

### Black Scholes Library
http://code.mibian.net/
"""
import mibian
"""BS([underlyingPrice, strikePrice, interestRate,
daysToExpiration], volatility=x, callPrice=y, putPrice=z)"""
c=mibian.BS([100,105,3,365],volatility=20)
c.putPrice
def american_put_black_scholes(initial_stock_price, strike_price, rf_rate, maturity, sigma, num_steps):
# Parameter initialization
deltaT = maturity/num_steps
up_factor = np.exp(sigma*np.sqrt(deltaT))
down_factor = 1.0/up_factor
p = (np.exp(rf_rate*deltaT)-down_factor)/(up_factor-down_factor)
# Binomial Price Tree
stock_values = np.zeros((num_steps+1, num_steps+1))
stock_values[0,0] = initial_stock_price
for i in range(1, num_steps+1):
stock_values[i, 0] = stock_values[i-1, 0]*up_factor
for j in range(1, i+1):
stock_values[i, j] = stock_values[i-1, j-1] * down_factor
# savetxt('stock_values.csv', stock_values, delimiter=',')
# Option Price at Final Node
option_values = np.zeros((num_steps+1, num_steps+1))
for i in range(num_steps+1):
option_values[num_steps, i] = max(0, strike_price-stock_values[num_steps, i])
# Backward calculation for initial options price
for j in range(num_steps-1):
option_values[num_steps, j] = mibian.BS([100,105,3,365],volatility=20).putPrice
for i in range(num_steps-2, -1, -1):
for j in range(i+1):
option_values[i, j] = max(0,
strike_price - stock_values[i, j],
np.exp(-rf_rate*deltaT) * (p * option_values[i+1, j] + (1-p) * option_values[i+1, j+1]))
# savetxt('option_values.csv', option_values, delimiter=',')
return option_values[0,0]
price_list_of_American_put=[]
for i in range(1,201):
price_list_of_American_put.append(american_put_black_scholes(100,105,.03,1,.2,i))
plt.plot(price_list_of_American_put)
len(price_list_of_American_put)
def richardson_extrapolation(initial_stock_price,
strike_price,
rf_rate, maturity,
sigma,
num_steps):
Two_BBSN = 2 * american_put_black_scholes(initial_stock_price,
strike_price,
rf_rate, maturity,
sigma, num_steps)
BBSN_div_two = american_put_black_scholes(initial_stock_price,
strike_price,
rf_rate,
maturity,
sigma,
int(num_steps/2))
return float(Two_BBSN-BBSN_div_two)
richardson_extrapolation(100,105,.03,1,.2,200)
price_list_of_American_put_richardson_extrapolation=[]
for i in range(25,225):
price_list_of_American_put_richardson_extrapolation.append(richardson_extrapolation(100,105,.03,1,.2,i))
plt.plot(price_list_of_American_put_richardson_extrapolation)
len(price_list_of_American_put_richardson_extrapolation)
df_summary=pd.DataFrame({"Binomial_put":price_list_of_Binomial_put,
"Black Scholes American_put":price_list_of_American_put,
"richardson_extrapolation Put":price_list_of_American_put_richardson_extrapolation})
df_summary_abs_error=abs(df_summary-9.472992)
df_summary_abs_error.plot()
plt.title('Put Price error vs # of Steps')
plt.xlabel('Steps')
plt.ylabel('Error')
plt.show()
np.log(df_summary_abs_error).plot()
plt.title('Put Price LN(error) vs # of Steps')
plt.xlabel('Steps')
plt.ylabel('Ln(Error)')
plt.show()
# In[ ]:
|
ee9ff4a7dd428657e4e65989e9eb61fdd4badd68 | deepbluech/leetcode | /Search in Rotated Sorted Array.py | 1,768 | 3.546875 | 4 | __author__ = 'Administrator'
class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def search(self, A, target):
n = len(A)
if n == 0:
return -1
if n == 1:
if A[0] == target:
return 0
else:
return -1
if A[n-1] > A[0]:
return self.binary_search(A, target, 0, n-1)
break_idx = self.find_break_index(A, 0, n-1)
print break_idx
largest_val = A[break_idx - 1]
smallest_val = A[break_idx]
head_val = A[0]
tail_val = A[n-1]
if target >= smallest_val and target <= tail_val:
return self.binary_search(A, target, break_idx, n-1)
if target >= head_val and target <= largest_val:
return self.binary_search(A, target, 0, break_idx)
return -1
def find_break_index(self, A, start, end):
if end - start == 1:
return end
if end - start == 0:
return -1
mid = start + (end - start) / 2
while A[mid] > A[start]:
start = mid
mid = (mid + 1 + end) / 2
return self.find_break_index(A, start, mid)
def binary_search(self, A, target, start, end):
if start > end or start < 0 or end >= len(A):
return -1
mid = start + (end - start) / 2
if A[mid] == target:
return mid
elif A[mid] < target:
return self.binary_search(A, target, mid+1, end)
else:
return self.binary_search(A, target, start, mid-1)
if __name__ == '__main__':
s = Solution()
#no duplicate
A = [1,1,1,0,1]
print s.find_break_index(A, 0, len(A)-1) |
f247d650a968595e9d9f7b45c78843d34a7f58f3 | danielafrimi/Advanced-Pratical-Course-In-Machine-Learning | /EX3/Manifold_Learning.py | 9,798 | 3.609375 | 4 | from scipy.spatial.distance import pdist, squareform
from EX3.Manifold_visualizer import *
from sklearn.manifold import LocallyLinearEmbedding
def digits_example():
'''
Example code to show you how to load the MNIST data and plot it.
'''
# load the MNIST data:
digits = datasets.load_digits()
data = digits.data / 255.
labels = digits.target
# plot examples:
plt.gray()
for i in range(10):
plt.subplot(2, 5, i+1)
plt.axis('off')
plt.imshow(np.reshape(data[i, :], (8, 8)))
plt.title("Digit " + str(labels[i]))
plt.show()
def swiss_roll_example():
'''
Example code to show you how to load the swiss roll data and plot it.
'''
# load the dataset:
X, color = datasets.samples_generator.make_swiss_roll(n_samples=2000)
# plot the data:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=color, cmap=plt.cm.Spectral)
plt.show()
def faces_example(path):
'''
Example code to show you how to load the faces data.
'''
with open(path, 'rb') as f:
X = pickle.load(f)
num_images, num_pixels = np.shape(X)
d = int(num_pixels**0.5)
print("The number of images in the data set is " + str(num_images))
print("The image size is " + str(d) + " by " + str(d))
# plot some examples of faces:
plt.gray()
for i in range(4):
plt.subplot(2, 2, i+1)
plt.imshow(np.reshape(X[i, :], (d, d)))
plt.show()
def plot_with_images(X, images, title, image_num=25):
'''
A plot function for viewing images in their embedded locations. The
function receives the embedding (X) and the original images (images) and
plots the images along with the embeddings.
:param X: Nxd embedding matrix (after dimensionality reduction).
:param images: NxD original data matrix of images.
:param title: The title of the plot.
:param num_to_plot: Number of images to plot along with the scatter plot.
:return: the figure object.
'''
n, pixels = np.shape(images)
img_size = int(pixels**0.5)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title(title)
# get the size of the embedded images for plotting:
x_size = (max(X[:, 0]) - min(X[:, 0])) * 0.08
y_size = (max(X[:, 1]) - min(X[:, 1])) * 0.08
# draw random images and plot them in their relevant place:
for i in range(image_num):
img_num = np.random.choice(n)
x0, y0 = X[img_num, 0] - x_size / 2., X[img_num, 1] - y_size / 2.
x1, y1 = X[img_num, 0] + x_size / 2., X[img_num, 1] + y_size / 2.
img = images[img_num, :].reshape(img_size, img_size)
ax.imshow(img, aspect='auto', cmap=plt.cm.gray, zorder=100000, extent=(x0, x1, y0, y1))
# draw the scatter plot of the embedded data points:
ax.scatter(X[:, 0], X[:, 1], marker='.', alpha=0.7)
return fig
def MDS(X, d):
'''
Given a NxN pairwise distance matrix and the number of desired dimensions,
return the dimensionally reduced data points matrix after using MDS.
:param X: NxN distance matrix.
:param d: the dimension.
:return: Nxd reduced data point matrix.
'''
N = len(X)
H = np.eye(N) - 1 / N
S = -0.5 * np.dot(np.dot(H, X), H)
# S is PSD and symmetric matrix. therefore S diagonalize matrix, and we can find the eigen vectors/values of S
eigenValues, eigenVectors = np.linalg.eig(S)
# Order the eigen vectors/values from the biggest to lowest
idx = eigenValues.argsort()[::-1]
eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:, idx]
# Takes the first d eigvalue and the corresponded eighvectors
Y = np.dot(eigenVectors[:, :d], np.diag(np.sqrt(eigenValues[:d])))
# Each row i (Y_i) is the new vector in the lowest space correspond to X_i
return Y, eigenValues
def LLE(X, d, k):
'''
Given a NxD data matrix, return the dimensionally reduced data matrix after
using the LLE algorithm.
:param X: NxD data matrix.
:param d: the dimension.
:param k: the number of neighbors for the weight extraction.
:return: Nxd reduced data matrix.
'''
embedding = LocallyLinearEmbedding(n_neighbors=k, n_components=d)
X_embedded = embedding.fit_transform(X)
return X_embedded
def create_similarity_kernel(X, sigma):
"""
:param X:
:param sigma:
:return:
"""
pairwise_dists = squareform(pdist(X, 'euclidean'))
K = np.exp(-pairwise_dists ** 2 / sigma)
return K
def DiffusionMap(X, d, sigma, t):
'''
Given a NxD data matrix, return the dimensionally reduced data matrix after
using the Diffusion Map algorithm. The k parameter allows restricting the
kernel matrix to only the k nearest neighbor of each data point.
:param X: NxD data matrix.
:param d: the dimension.
:param sigma: the sigma of the gaussian for the kernel matrix transformation.
:param t: the scale of the diffusion (amount of time steps).
:return: Nxd reduced data matrix.
'''
similarity_matrix = create_similarity_kernel(X, sigma)
# Normalize th rows
similarity_matrix /= similarity_matrix.sum(axis=1).reshape(-1, 1)
# Diagonalize the similarity matrix.
eigenvalues, eigenvectors = np.linalg.eigh(similarity_matrix)
# Order the eigenvalues & eigenvectors in descent order
eigenvalues = eigenvalues[::-1]
eigenvectors = eigenvectors[:, ::-1]
# Select only the eigenvectors corresponding to the 2...(d + 1) highest eigenvalues.
d_eigenvectors = eigenvectors[:, 1:d + 1]
d_eigenvalues = eigenvalues[1:d + 1]
# Return those eigenvectors, where the i-th eigenvector is multiplied by (\lambda_i)^t
return np.power(d_eigenvalues, t) * d_eigenvectors
def rotate_in_high_dim_and_inject_noise(low_dim_data, dim=3, noise_std=0.125):
"""
This function takes a data in low dimension and project it to high dimension
while performing a random rotation and adding gaussian noise in the high dimension.
:param low_dim_data: The low dimensional data.
:param dim: The high dimension to use.
:param noise_std: Standard deviation of the gaussian noise to add in the high dimension.
:return: The high dimensional data and the rotation matrix that was used.
"""
N, low_dim = low_dim_data.shape
# Pad each low vector with zeros to obtain a 'dim'-dimensional vectors.
padded_data = np.pad(array=low_dim_data,
pad_width=((0, 0), (0, dim - low_dim)),
mode='constant')
# Random square matrix
gaussian_matrix = np.random.rand(dim, dim)
# Q is Ortogonal matrix -> it means this is a rotation matrix. 'every square matrix can decompose of QR'
rotation_matrix, _ = np.linalg.qr(gaussian_matrix)
# Rotate the padded vectors using the random generated rotation matrix.
rotated_data_high_dim = np.dot(padded_data, rotation_matrix)
# Add noise
rotated_data_high_dim += np.random.normal(loc=0, scale=noise_std,
size=rotated_data_high_dim.shape)
return rotated_data_high_dim, rotation_matrix
def get_gaussians_2d(k=8, n=128, std=0.05):
"""
Generate a synthetic dataset containing k gaussians,
where each one is centered on the unit circle
(and the distance on the sphere between each center is the same).
Each gaussian has a standard deviation std, and contains n points.
:param k: The amount of gaussians to create
:param std: The standard deviation of each gaussian
:param n: The number of points per gaussian
:returns: An array of shape (N, 2) where each row contains a 2D point in the dataset.
"""
angles = np.linspace(start=0, stop=2 * np.pi, num=k, endpoint=False)
centers = np.stack([np.cos(angles), np.sin(angles)], axis=1)
# Create an empty array that will contain the generated points.
points = np.empty(shape=(k * n, 2), dtype=np.float64)
# For each one of the k centers, generate the points by sampling from a normal distribution in each axis.
for i in range(k):
points[i * n: i * n + n, 0] = np.random.normal(loc=centers[i, 0], scale=std, size=n)
points[i * n: i * n + n, 1] = np.random.normal(loc=centers[i, 1], scale=std, size=n)
plt.figure()
plt.scatter(points[:, 0], points[:, 1], s=5)
plt.show()
return points
def scree_plot(noise_std_arr=None, high_dim=128):
"""
:param noise_std_arr:
:param high_dim:
:return:
"""
if noise_std_arr is None:
noise_std_arr = [0, 0.05, 0.1, 0.13, 0.2, 0.3, 0.4]
low_dim_dataset = get_gaussians_2d()
for noise_std in noise_std_arr:
high_dim_noise_injected, _ = rotate_in_high_dim_and_inject_noise(low_dim_dataset, dim=high_dim,
noise_std=noise_std)
embedded_data_mds, eigenvalues = MDS(distance_matrix(high_dim_noise_injected, high_dim_noise_injected), d=2)
plot_embedded_data(high_dim_noise_injected, embedded_data_mds, title="MDS Embedded data with noise {}".format(noise_std))
plot_eigenvalues(eigenvalues, number_eigenvalues=10,
title=f'MDS_distance_matrix_eigenvalues_with_noise_{noise_std:.2f}')
if __name__ == '__main__':
# MDS_swiss_roll()
# LLE_swiss_roll()
# diffusion_map_swiss_roll()
# scree_plot()
faces_embeddings()
|
1cff851d01595a74c23a4f7c6540f61cdfd0a025 | georgeescobra/algorithmPractice | /random.py | 1,357 | 3.875 | 4 | """
these are questions I had a tough time answering during interviews
Questions to work on:
- algorithm for amount of deletions between two strings
-
"""
def consecutiveHighLows(test):
"""
Given an array of ints
return the longest consecutive highs or consecutive lows:
[1,2,3,4] -> 4
[1,3,2,1,4,5] -> 3 (3,2,1) or (1,4,5)
Solved it pretty fast rn, but during the test I didnt fully understand the question well enough
"""
upCount = 1
downCount = 1
upMax = 0
downMax = 0
index = 0
while(index < len(test)-1):
if(test[index] < test[index + 1]): # going up
upCount += 1
downMax = max(downCount, downMax)
downCount = 1
elif(test[index] > test[index + 1]): # going down
downCount += 1
upMax = max(upCount, upMax)
upCount = 1
else:
downMax = max(downCount, downMax)
upMax = max(upCount, upMax)
downCount = 1
upCount = 1
index += 1
upMax = max(upMax, upCount)
downMax = max(downMax, downCount)
return max(upMax, downMax)
print(consecutiveHighLows([1,2,3,4]))
print(consecutiveHighLows([1,3,2,1,4,5]))
print(consecutiveHighLows([1,3,2,2,0,1,4,5])) |
80ef10e555b966961d302da8c542498bc9b681ed | jali-clarke/Python | /SMS Python Practice/student.py | 5,753 | 4.40625 | 4 | class StudentsandCourses:
'''Courses and the students enrolled in them.
The class creates a dictionary of courses and their students and a list
of all students, with each student appearing once in that list. It will
support adding new students, new courses, students enroling and dropping
courses. It will also be able to analyse the common courses of students and
what courses a student is taking.
Attributes:
- self.CourseDict (dictionary): a dictionary of all given courses and the
student enrolled in each course.
-self.studentlist (list): a list of all students, whether or not they are
enroled in a course.
'''
def __init__(self):
'''(self) -> Nonetype
Creates an initially empty dictionary for courses and their class lists
and an empty list for students to be created into.
Parameters:
-Does not take any arguements other than self
'''
self.CourseDict = {}
self.studentlist = []
def Student(self, student):
'''(str) -> Nonetype
Adds a student to the student list.
Parameters:
-Must take only one str arguement, it cannot work with more than one
student.
'''
if student not in self.studentlist:
self.studentlist.append(student)
else:
return 'ERROR: Student ' +str(student) + ' already exists.'
def course(self, Coursename, student):
'''(str, str) -> Nonetype
If coursename is not already a course in CourseDict, it will create
a new key (course) in CourseDict and enroll the student in that course
as a key. If the course already exists, it will just enroll the student
in the course as a new key. If student does not exist in studentlist,
an error will be returned. If the CourseDict value list has 30 members
the course is full and it will return a message stating this.
Parameters:
-Takes 2 str as arguements.
'''
if student in self.studentlist:
if Coursename not in self.CourseDict:
self.CourseDict[Coursename]= [student]
elif Coursename in self.CourseDict:
if len(self.CourseDict[Coursename]) < 30:
self.CourseDict[Coursename].append(student)
else:
return 'ERROR: Course ' + str(Coursename) + ' is full.'
else:
return 'ERROR: Student ' + str(student) + ' does not exist.'
def dropcourse(self, Coursename, student):
'''(str, str) -> Nonetype
Removes a student from a course; if student does not exist in
Student.studentlist, raises an error, if student not in course,
function does nothing.
Parameters:
-Can only take two str arguments are parameters
'''
if student in self.studentlist:
if student in self.CourseDict[Coursename]:
self.CourseDict[Coursename].remove(student)
else:
return 'ERROR: Student ' + str(student) + ' does not exist.'
def givecourses(self, student):
'''(str) -> str
Return a string of the given student and what courses their taking.
Parameters:
-only takes one str argument
'''
if student in self.studentlist:
listcourses = '' + str(student) + ' is taking '
courselist = []
for course in self.CourseDict:
if student in self.CourseDict[course]:
courselist.append(course)
if len(courselist) == 0:
return str(student) + ' is not taking any courses.'
else:
courselist.sort()
for course in courselist:
listcourses += str(course) + ', '
listcourses = listcourses[:-2]
return listcourses
else:
return 'ERROR: Student ' + str(student) + ' does not exist.'
def commoncourses(self, name1, name2):
'''(str, str) -> str
Return a string of the common courses shared between name1 and
name2 in alphabetical order.
Parameters:
-takes two str arguments
'''
courselist = []
if (name1 in self.studentlist) and (name2 in self.studentlist):
for course in self.CourseDict:
if (name1 in self.CourseDict[course]) and\
(name2 in self.CourseDict[course]):
courselist.append(course)
courselist.sort()
return courselist
if (name1 not in self.studentlist) and (name2 not in self.studentlist):
return 'ERROR: Student ' + str(name1) + ' does not exist.' + '\n' +\
'ERROR: Student ' + str(name2) + ' does not exist.'
if name1 not in self.studentlist:
return 'ERROR: Student ' + str(name1) + ' does not exist.'
if name2 not in self.studentlist:
return 'ERROR: Student ' + str(name2) + ' does not exist.'
def classlist(self, course):
'''(str) -> list
Returns a list of students in the given course in alphabetical
order.
Parameters:
-takes one str argument
'''
classlist = []
if course in self.CourseDict:
for name in self.CourseDict[course]:
classlist.append(name)
classlist.sort()
return classlist
else:
return 'No one is taking ' + str(course) + '.'
|
9e09c5d298d545a16c2b29afabffbcf714b7384b | amigo7777/-Pyhton-2 | /Getsbi.py | 157 | 3.90625 | 4 | b = input()
s = input().split()
for i in range(len(s)):
if b.lower() in s[i] or b.upper() in s[i]:
print(s[i])
else:
continue
|
92c49a8144654593d7fb7c76b95e04cef17e4e5d | DuyKhangTruong/AI_Gomoku | /gomoku.py | 1,564 | 3.59375 | 4 | from board import Board
from policy import Policy
from AI_Gomoku import AI
class Gomoku:
def __init__(self):
self.player1 = Policy("X")
self.AI_Sec = AI("O")
self.board = Board()
self.computer = Policy(self.AI_Sec.shape)
# self is object itself (in this case gomoku)
# capitalize objects and classes
def play(self):
while True:
turn_x = input("Player 1 turn x: ")
turn_y = input("Player 1 turn y: ")
while not (self.player1.CheckLegal(self.board, int(turn_x), int(turn_y))):
print("Please type again")
turn_x = input("Player 1 turn x: ")
turn_y = input("Player 1 turn y: ")
self.player1.MakeMove(self.board, int(turn_x), int(turn_y))
if self.player1.checkWin(self.board, int(turn_x), int(turn_y)):
print("Player 1 wins")
return
#turn_x = input("Player 2 turn x: ")
#turn_y = input("Player 2 turn y: ")
# while not (self.player2.CheckLegal(self.board, int(turn_x), int(turn_y))):
#turn_x = input("Player 2 turn x: ")
#turn_y = input("Player 2 turn y: ")
computerMove = self.AI_Sec.findBestMove(self.board)
x, y = computerMove[0], computerMove[1]
print(x)
print(y)
self.computer.MakeMove(self.board, x, y)
if self.computer.checkWin(self.board, x, y):
print("Computer wins")
return
game = Gomoku()
game.play()
|
10537da4631fefb46009c0b77090dfae5c465b5c | IMDCGP105-1819/portfolio-Fred-Wright | /Text Adventure game/BadPokerGame.py | 126,751 | 3.609375 | 4 | import sys
print("Welcome back to the World Series Of Poker, I'm Lon McEachern and im here with Antonio Esfandiari")
print("Esfandiari: Hey")
print("And we are mere minutes away from finding out the final competitor to the main event, with the winner winning the illustrious WSOP bracelet")
print("During this session, there will only be the table consisting of these 2 players, tune in tomorrow night for that (next game)")
print("Esfandiari: Ive won 3 of them braclets and they're only collecting dust in a cabinet, they're here for that magical, life-changing fifteen million dollar payout")
print("Lon: Yes of course, the highest prize-pot in the history of the main event, from the huge 8 thousand plus entrants, we have already deterined 8 players on the final table.")
print("Esfandiari: Yeah, seriously strong set of players.")
print("We are here on the pinultimate table of the World Series Of Poker main event with only 2 contestents left, of course we have Mr Antoine Labat")
print("Esfandiari: Guy's come from from france with no real history, yet he's taken down some big dogs to get here, and would be only the third frenchamn to get to the main event.")
print("Lon: And he's up against...")
print("Your dad: Look, payday's already big, enough for some of your mom's treatment, you know it, I know it, but dont focus on that, everybody's already so proud of you, anything you do now, is just a bonus, Okay?")
print("You let out a strong but shakey, nervous breath.. ")
print("Your dad firmly places his hands on your shoulders, giving you a mild shake.")
print("Dad: What's your name!?")
name = str(input())
print("Do you know how to play poker!?")
Played_before = input()
while True:
if Played_before == "yes":
print("Good, because your here cause of how good you've played through this tournament.")
print("MANAGER: TIME TO GO!")
print("If ever you need my help, do: run hand through hair")
print("i'll cough once to Fold, twice to Check/Call or three times to go big, you shouldnt need me though")
print("Dont really know why we still have that camera on you, but whatever.")
print("MANAGER: CAMERA'S ARE ROLLING, COME ON NOW!!")
print(name,", You got this!")
print("As you're walking away, your dad yells:")
print("Im Proud of you son!")
print("While walking through the back towards the poker table on stage, I walk up to you.")
print("So, everything you can do is, chipcount, check, call, raise, which will lead to how much you wish to raise")
print("all in, fold and RHTH, run hand through hair, to get some help")
print("Try to enjoy")
break
if Played_before == "no":
print("Your dad sigh's as if he's dissapointed")
print("Clearly you've been relying on our cheating tactic's a little too much")
print("MANAGER: TIME TO GO!")
print("Right, when you play you hand and you don't know what to do, do: run hand through hair")
print("i'll cough once to Fold, twice to Check/Call or three times to go big")
print("That camera on you has helped quite alot through this journey, it still has its uses")
print("if you do it too many times, someone may clock on, and we dont want that.")
print("MANAGER: CAMERA'S ARE ROLLING, COME ON NOW!!")
print(name, ", You got this!")
print("As you're walking away, your dad yells:")
print("Im Proud of you son!")
print("While walking through the back towards the poker table on stage, I walk up to you.")
print("Im sure you understand cards themselves, otherwise we have a big problem, google it")
print("In poker, the aim is to reduce your opponents chips to 0, you do this by winning hands, at the start of each hand you are dealt 2 cards like 4♣ 9♦")
print("The best 5 cards from your hand and the table are used.")
print("Hand in order or worth from best to worst are Royal Flush: A♣ K♣ Q♣ J♣ 10♣, Straight flush J♣ 10♣ 9♣ 8♣ 7♣, Four of a kind: K♣ K♠ K♥ K♦ 10♦")
print("Full house: K♦ K♠ K♥ 10♠ 10♥, Flush: A♥ 5♥ 6♥ 9♥ J♥, Straight: 5♥ 6♠ 7♠ 8♥ 9♦, Three of a kind: 5♥ 5♦ 5♠ 8♥ 9♦, Two pair: 4♣ 4♦ 7♠ K♠ K♠")
print("One pair: 7♠ 7♣ 9♠ 10♣ K♠ and finally High Card: 2♥ 3♦ 6♣ 8♠ Q♣")
print("Higher cards of the same value win hands, so a pair of Kings beat a pair of 10's")
print("On each hand you can Fold, Check/Call or Raise/All in,")
print("Fold means the hand ends and your opponents take the chips you've put in. Useful if you have a bad hand")
print("Call means put in the same amount of chips as what the current highest amount is, or if none are in, then you can simply check.")
print("Raise means increase the amount if chips others need to input to continue with the hand.")
print("And all in... well means what it say's on the tin")
print("You still following?")
following = input()
if following == "yes":
print("Just checking, ha!, you see what i did there?... Ok.")
print("The hand starts, you put in some chips then the flop comes, the first 3 cards, you then proceed")
print("On the flop you could get a royal flush, highly unlikely but possible, if so, play like you only have a pair, and try to win as many chips as possible")
print("Going All in straight away could scare opponents into folding, and you dont gain any chips")
print("After the flop, there is the turn, another card, then the river, after it all plays out the player with the best hand wins.")
print("The BabySteps feature is enable for if you need it, type !Help when prompted, but apparently your dad does some good advising... hmmm")
print("So, everything you can do is, chipcount, check, call, raise, which will lead to how much you wish to raise")
print("all in, fold and RHTH, run hand through hair, to get some help")
break
if following == "no":
print("You're a lost cause, google it.")
print("When you're done, come back")
print("I'll enable the BabySteps feature during the first table vs Labat, if you're stuck or dont know what to do, type !Help when prompted")
print("So, everything you can do is, chipcount, check, call, raise, which will lead to how much you wish to raise")
print("all in, fold and RHTH, run hand through hair, to get some help")
break
else:
print("What? A simple yes or no would do")
following = input()
else:
print("I can tell you're nervous, you just mumbled, say that again?")
Played_before = input()
Chipcount = 550000
labat_chips = 300000
dad_coughs = 0
A = "What would you like to do?"
if dad_coughs == 3:
print("The security guard seems to pick up on your dads coughing")
if dad_coughs == 5:
print("The security guard walks over to your dad, politely asking him to stop coughing")
if dad_coughs == 7:
print("A switch seems to go off in the guards head, he calls over the MANAGER and proceeds to whisper in his ear")
print("The manager looks at you, then at your dad, and squints his eyes, looking cautiously")
if dad_coughs == 9:
print("The MANAGER walks over and shoves your cards to the dealer, the security guards graps a hold of you and chucks you out of the buidling")
print("You had enough warnings. You dont get any payout for the tournament, your mum dies of cancer, all beacuse of you.")
sys.exit(0)
print("Lon: And he's up against", name)
print("Esfandiari: Complete nobody, he's from England, has no competitive poker, say's he's playing for his sick mother but i dont buy it! ")
print("Probably a cover story for how he's been playing underground, racking up wins and needs a way to launder money")
print("Lon: Ha! You really do think the worst of people.")
print("Esfandiari: When you've been in the buisness as long as me, nothing suprises me anymore,")
print("Esfandiari: Some guy said he was playing for his grandma's funeral costs, but she was just on a holiday in the bahamas!")
print("Lon: 'sighs' Let's just get down to it, for the final place on the main event table its Antoine Labat versus", name, "!")
print("As you walk through the curtains, applause already fills the room, you wave to thank your newfound supporters, showing respect, you shake your opponents hand, and take your seat.")
print("You quickly do a stack count, you're on", Chipcount, "chips" "while he's on", labat_chips, "chips")
print("The applause dies down, minor talking fills the room, a hell of a lot better than silence, the dealer shuffles.")
print("WARNING: IF YOU INPUT WORDS WHEN PROMPTED FOR NUMBERS, VISE VERSA OR BE A GENERAL IDIOT, THIS GAME WILL BREAK.")
print("She announces the beginning of the game and proceeds to deal you and your opponent 2 cards.")
print("You take a deep breath in, exhale hard but silent, shuffle into your seat, notice the lights have dimmed from the audience in shine off the table")
print("Before you know it, you feel right at home.")
print("You look at your first hand, its a 4♣ 9♠, Labat raises to 30k, you fold immediately")
print("Oh boy...")
print("5 hands go by quickly, minor amounts get's raised between you and Labat, however it amasses to nothing")
print("you see the next hand to be 4♠ & 5♠")
print(A)
hand1 = input()
playing = True
hand1_stake = 5000
hand1_pot = 0
while playing == True:
if hand1 == "fold":
print("As there is nothing to lose, and all to gain, this is pointless")
hand1 = input()
if hand1 == "check" or hand1 == "call":
print("Labat calmly puts in the Blind, not revealing anything.")
Chipcount = Chipcount - hand1_stake
labat_chips = labat_chips - hand1_stake
hand1_pot = hand1_stake * 2
break
if hand1 == "raise":
while playing == True:
print("How much would you like to raise?")
raise1 = int(input())
if raise1 < 10000:
print("Thats too low, lowest bet is 10000")
if raise1 >= 10000 and raise1 < 100000:
print("Labat calmly puts in the calls your raise, not revealing anything.")
Chipcount = Chipcount - raise1
labat_chips = labat_chips - raise1
hand1_pot = raise1 * 2
break
if raise1 >= 100000 and raise1 < 200000:
print("As you collect the chips and put them into the middle, a hush falls through the room.")
print("Labat takes a few seconds to consider, arranges the chips needed to call, licks his lips and calls.")
Chipcount = Chipcount - raise1
labat_chips = labat_chips - raise1
hand1_pot = raise1 * 2
break
if raise1 >= 200000 and raise1 < Chipcount:
print("You grab the chips needed, a large stack, but you hear your dad cough a loud 2 coughs, maybe play things a little steadier")
print(A)
hand1 = input()
if raise1 > Chipcount:
print("You dont have that much chips to use, you have:", Chipcount)
print(A)
hand1 = input()
if raise1 == Chipcount:
print("You grab the chips needed, a large stack, but you hear your dad cough a loud 2 coughs, maybe play things a little steadier")
print(A)
hand1 = input()
else:
print("That is not a valid bet")
print("What would you like to do?")
hand1 = input()
break
if hand1 == "RHTH":
print("Your dad coughs twice")
print(A)
hand1 = input()
dad_coughs = dad_coughs + 1
if hand1 == "AllIn":
print("You grab all your chips, a large stack, but you hear your dad cough a loud 2 coughs, maybe play things a little steadier")
print(A)
hand1 = input()
if hand1 == "chipcount":
print(Chipcount)
print(A)
hand1 = input()
if hand1 == "!Help":
print("You have:", Chipcount, "Chips, id reccomend just calling as your hand is mediocre but has a lot of potential.")
print("You can do: chipcount, check, call, raise, which will lead to how much you wish to raise, all in, fold !Help and run hand through hair")
hand1 = input()
else:
print("Whats that? Type !Help if you're lost")
hand1 = input()
print("The dealer put one card aside, and reveals the flop:")
print("|3♠||10♦||K♠|")
print("Labat takes his time carefully, but cautiously looking at the cards")
print("He proceeds to check.")
print("You have:", Chipcount, "Labat has:", labat_chips, "& the pot is:", hand1_pot)
print(A)
hand2 = input()
while playing == True:
if hand2 == "fold":
print("As there is nothing to lose, and all to gain, this is pointless")
hand2 = input()
if hand2 == "check" or hand2 == "call":
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Labat doesnt move, clearly in deep thought, after 30 seconds, he reaches for an amount of chips")
print("Dealer: Raise 70 thousand.")
labat_chips = labat_chips - 70000
hand1_pot = hand1_pot + 70000
print(A)
hand3 = input()
while playing == True:
if hand3 == "fold":
print("Folding a flush is a hard thing to do, however it seemingly must be done.")
print("You throw your cards face down, he chooses to flip his cards face up, A pair of kings!")
print("Your flush would have beat his kings, with the river left, your chances of winning were high, but its all in the past now.")
print("Its the fist major hand, but as all hands pass, blinds will be raised to a point where you must go big or home.")
labat_chips = labat_chips + hand1_pot
hand1_pot = hand1_pot - hand1_pot
break
if hand3 == "raise":
print("How much would you like to raise?")
raise3 = int(input())
while playing == True:
if raise3 <= 70000:
print("Thats too low, lowest bet is 70001")
raise3 = int(input())
if raise3 > 70000 and raise3 < 100000:
Chipcount = Chipcount - raise3
labat_chips = labat_chips - (raise3 - 70000)
hand1_pot = hand1_pot + ((raise3 * 2) - 70000)
if labat_chips < 100000:
print("You put", raise3, "chips to the middle, with your bet, Labat would be left with a small amount")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise3), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Your father yells: Come on!")
print("The room falls to silence as the dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if labat_chips >= 100000:
print("Labat sees your weak re-raise, and capitalises immediately, he places 1 chip towards the middle and exclaims: All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise3), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Your father yells: Come on!")
print("The room falls to silence as the dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if raise3 >= 100000 and raise3 < labat_chips:
Chipcount = Chipcount - raise3
labat_chips = labat_chips - (raise3 - 70000)
hand1_pot = hand1_pot + ((raise3 * 2) - 70000)
print("You put", raise3, "chips to the middle, with your bet, Labat would be left with a small amount")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise3), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Your father yells: Come on!")
print("The room falls to silence as the dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if raise3 == labat_chips:
print("You put", raise3, "chips to the middle, with your bet, Labat would be all in.")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - (labat_chips + 70000)
hand1_pot = hand1_pot + ((labat_chips) * 2) + 70000
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if raise3 > labat_chips:
print("Labat only has", labat_chips, "Please only bet and amount he can call.")
raise3 = int(input())
else:
print("Thats an invalid bet")
raise3 = int(input())
break
if hand3 == "check" or hand3 == "call":
Chipcount = Chipcount - 70000
hand1_pot = hand1_pot + 70000
print("You take a while, thinking about the hand, after some time, place down the chips needed to call.")
print("The dealer puts another card away for the river...")
print("She puts down the three of hearts")
print("The board is: |3♠||10♦||K♠||9♠||3♥|")
print("Labat thinks long and hard, surveying the cards, 4 minutes pass")
print("He puts a single chip into the middle and exclaims: All in")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", labat_chips, "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if hand3 == "RHTH":
print("Your dad coughs three times")
print(A)
hand3 = input()
dad_coughs = dad_coughs + 1
if hand3 == "allin":
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - (labat_chips + 70000)
hand1_pot = hand1_pot + ((labat_chips * 2) + 70000)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if hand3 == "chipcount":
print("You have:", Chipcount, "Chips and Labat has:", labat_chips, "chips.")
print(A)
hand3 = input()
if hand3 == "!Help":
print("You have:", Chipcount, "Chips, id reccomend Raising as you have a flush.")
print("You can do: chipcount, check, call, raise, which will lead to how much you wish to raise, all in, fold !Help and run hand through hair")
hand3 = input()
else:
print("Whats that? Type !Help if you're lost")
hand3 = input()
break
if hand2 == "raise":
print("How much would you like to raise?")
raise2 = int(input())
while playing == True:
if raise2 < 10000:
print("Thats too low, lowest bet is 10000")
raise2 = int(input())
if raise2 >= 10000 and raise2 < 100000:
Chipcount = Chipcount - raise2
labat_chips = labat_chips - raise2
hand1_pot = hand1_pot + (raise2 * 2)
if labat_chips < 100000:
print("You put", raise2, "chips to the middle, with your bet, Labat would be left with a small amount")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise2), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if labat_chips >= 100000:
print("Labat takes his time, but in the end, calls.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Labat doesnt move, clearly in deep thought, after 30 seconds, he reaches for an amount of chips")
print("Dealer: Raise 70 thousand.")
labat_chips = labat_chips - 70000
hand1_pot = hand1_pot + 70000
print(A)
hand4 = input()
while playing == True:
if hand4 == "fold":
print("Folding a flush is a hard thing to do, however it seemingly must be done.")
print("You throw your cards face down, he chooses to flip his cards face up, A pair of kings!")
print("Your flush would hve beat his kings, with the river left, your chances of winning were high, but its all in the past now.")
print("Its the fist major hand, but as all hands pass, blinds will be raised to a point where you must go big or home.")
labat_chips = labat_chips + hand1_pot
hand1_pot = hand1_pot - hand1_pot
break
if hand4 == "raise":
print("How much would you like to raise?")
raise4 = int(input())
while playing == True:
if raise4 <= 70000:
print("Thats too low, lowest bet is 70001")
raise4 = int(input())
if raise4 > 70000 and raise4 < 100000:
Chipcount = Chipcount - raise4
labat_chips = labat_chips - (raise4 - 70000)
hand1_pot = hand1_pot + ((raise4 * 2) - 70000)
if labat_chips < 100000:
print("You put", raise4, "chips to the middle, with your bet, Labat would be left with a small amount")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise4), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Your father yells: Come on!")
print("The room falls to silence as the dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
if labat_chips >= 100000:
print("Labat sees your weak re-raise, and capitalises immediately, he places 1 chip towards the middle and exclaims: All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise4), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Your father yells: Come on!")
print("The room falls to silence as the dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if raise4 >= 100000 and raise4 < labat_chips:
Chipcount = Chipcount - raise4
labat_chips = labat_chips - (raise4 - 70000)
hand1_pot = hand1_pot + ((raise4 * 2) - 70000)
print("You put", raise4, "chips to the middle, with your bet, Labat would be left with a small amount")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise4), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Your father yells: Come on!")
print("The room falls to silence as the dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if raise4 > labat_chips:
print("You cant bet that amount as Labat only has", labat_chips, "chips.")
raise4 = int(input())
if raise4 == labat_chips:
print("You put", labat_chips, "chips to the middle")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips - 70000
hand1_pot = hand1_pot + (labat_chips * 2) + 70000
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
else:
print("Thats an invalid bet")
raise4 = int(input())
break
if hand4 == "check" or hand4 == "call":
Chipcount = Chipcount - 70000
hand1_pot = hand1_pot + 70000
print("You take a while, thinking about the hand, after some time, place down the chips needed to call.")
print("The dealer puts another card away for the river...")
print("She puts down the three of hearts")
print("The board is: |3♠||10♦||K♠||9♠||3♥|")
print("Labat thinks long and hard, surveying the cards, 4 minutes pass")
print("He puts a single chip into the middle and exclaims: All in")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if hand4 == "RHTH":
print("Your dad coughs three times")
print(A)
hand4 = input()
if hand4 == "allin":
print("You put", labat_chips, "chips to the middle")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips - 70000
hand1_pot = hand1_pot + (labat_chips * 2) + 70000
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if hand4 == "chipcount":
print("You have:", Chipcount, "Chips")
print(A)
hand4 = input()
if hand4 == "!Help":
print("You have:", Chipcount, "Chips, id reccomend Raising as you have a flush.")
print("You can do: chipcount, check, call, raise, which will lead to how much you wish to raise, all in, fold !Help and run hand through hair")
hand4 = input()
else:
print("Whats that? Type !Help if you're lost")
hand4 = input() #
break
if raise2 > labat_chips:
print("Labat only has", labat_chips, "Please only bet and amount he can call.")
print(A)
raise2 = int(input())
if raise2 >= 100000 and raise2 < 200000:
Chipcount = Chipcount - raise2
labat_chips = labat_chips - raise2
hand1_pot = hand1_pot + (raise2 * 2)
if labat_chips < 100000:
print("You put", raise2, "chips to the middle, with your bet, Labat would be left with a small amount")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise2), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if labat_chips >= 100000:
print("Labat takes a long while, but in the end, calls.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Labat doesnt move, clearly in deep thought, after 30 seconds, he reaches for an amount of chips")
print("Dealer: Raise 70 thousand.")
labat_chips = labat_chips - 70000
hand1_pot = hand1_pot + 70000
print(A)
hand5 = input()
while playing == True:
if hand5 == "fold":
print("Folding a flush is a hard thing to do, however it seemingly must be done.")
print("You throw your cards face down, he chooses to flip his cards face up, A pair of kings!")
print("Your flush would hve beat his kings, with the river left, your chances of winning were high, but its all in the past now.")
print("Its the fist major hand, but as all hands pass, blinds will be raised to a point where you must go big or home.")
labat_chips = labat_chips + hand1_pot
hand1_pot = hand1_pot - hand1_pot
break
if hand5 == "raise":
print("How much would you like to raise?")
raise5 = int(input())
while playing == True:
if raise5 <= 70000:
print("Thats too low, lowest bet is 70001")
raise5 = int(input())
if raise5 > 70000 and raise5 < 100000:
Chipcount = Chipcount - raise5
labat_chips = labat_chips - (raise5 - 70000)
hand1_pot = hand1_pot + (raise5 * 2)
if labat_chips < 100000:
print("You put", raise5, "chips to the middle, with your bet, Labat would be left with a small amount")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise5), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Your father yells: Come on!")
print("The room falls to silence as the dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + ((labat_chips * 2) - 70000)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if labat_chips >= 100000:
print("Labat sees your weak re-raise, and capitalises immediately, he places 1 chip towards the middle and exclaims: All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise5), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Your father yells: Come on!")
print("The room falls to silence as the dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
else:
print("You cant do that")
print(A)
handX = input()
break
if raise5 >= 100000 and raise5 <= labat_chips:
Chipcount = Chipcount - raise5
hand1_pot = hand1_pot + raise5 + (raise5 - 70000)
labat_chips = labat_chips - (raise5 - 70000)
print("You put", raise5, "chips to the middle, with your bet, Labat would be left with a small amount")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise5), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Your father yells: Come on!")
print("The room falls to silence as the dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if raise5 > labat_chips:
print("Labat only has", labat_chips, "Please only bet an amount he can call.")
raise5 = int(input())
if raise5 == labat_chips:
print("You put", labat_chips, "chips to the middle")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips - 70000
hand1_pot = hand1_pot + (labat_chips * 2) + 70000
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
else:
print("Thats an invalid bet")
raise4 = int(input())
break
if hand5 == "check" or hand5 == "call":
Chipcount = Chipcount - 70000
hand1_pot = hand1_pot + 70000
print("You take a while, thinking about the hand, after some time, place down the chips needed to call.")
print("The dealer puts another card away for the river...")
print("She puts down the three of hearts")
print("The board is: |3♠||10♦||K♠||9♠||3♥|")
print("Labat thinks long and hard, surveying the cards, 4 minutes pass")
print("He puts a single chip into the middle and exclaims: All in")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", labat_chips, "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if hand5 == "RHTH":
print("Your dad coughs three times")
print(A)
hand5 = input()
dad_coughs = dad_coughs + 1
if hand5 == "allin":
print("You put", labat_chips, "chips to the middle, with your bet, Labat would be all in.")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips - 70000
hand1_pot = hand1_pot + (labat_chips * 2) + 70000
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if hand5 == "chipcount":
print("You have:", Chipcount, "Chips and Labat has:", labat_chips, "chips.")
print(A)
hand5 = input()
if hand5 == "!Help":
print("You have:", Chipcount, "Chips, id reccomend Raising as you have a flush.")
print("You can do: chipcount, check, call, raise, which will lead to how much you wish to raise, all in, fold !Help and run hand through hair")
hand5 = input()
else:
print("Whats that? Type !Help if you're lost")
hand5 = input()
break
if raise2 >= 200000 and raise2 < labat_chips:
print("You put", raise2, "chips to the middle, with your bet, Labat would be left with a small amount")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("You can either call or fold, and in a situation like this, no help can be given.")
print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise2), "to call.")
print(A)
handX = input()
while playing == True:
if handX == "call":
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
if handX == "fold":
print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat")
print("You throw your cards away and labat takes the big amount in the pot.")
print("He also just throws away his cards not allowing you to see them")
print("Dad: Your getting hasty son! This is your time!")
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
break
else:
print("You cant do that")
print(A)
handX = input()
break
if raise2 == labat_chips:
print("You put", raise2, "chips to the middle, with your bet, Labat would be all in.")
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
print("You now have", Chipcount, "chips")
print("Labat now has", labat_chips, "chips")
print("Dad: Maybe going all in was not the best idea on the first main hand")
break
else:
print("That is not a valid bet")
raise2 = int(input())
break
if hand2 == "RHTH":
print("Your dad coughs twice")
print(A)
hand2 = input()
dad_coughs = dad_coughs + 1
if hand2 == "all in":
print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip")
print("He twiddles with it through his fingers and thumbs, he places it on the table and says:")
print("All in.")
print("As per rules of the game, both players place down their hand.")
print("You place your 4♠ & 5♠, he places...")
print("K♥...")
print("K♦!!! A pair of kings, with a king on the board!?")
print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!")
print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!")
print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!")
print("The room's silence has erupted, your father is shouting for the right card to come")
print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.")
print("The dealer puts one card away, and with no theatrical building, puts down..")
print("The 9 of Spades!!!! A Flush!!!")
print("Your father lets out a roar and you let out a huge sigh")
print("The dealer puts another card away for the river...")
print("She puts down.. The three of hearts")
print("A full house.. 'Its alright", name, "You're still in this!")
Chipcount = Chipcount - labat_chips
hand1_pot = hand1_pot + (labat_chips * 2)
labat_chips = labat_chips - labat_chips
labat_chips = labat_chips + hand1_pot
break
if hand2 == "chipcount":
print(Chipcount)
print(A)
hand2 = input()
if hand2 == "!Help":
print("You have:", Chipcount, "Chips, id reccomend just calling as your hand is mediocre but has a lot of potential.")
print("You can do: chipcount, check, call, raise, which will lead to how much you wish to raise, all in, fold !Help and run hand through hair")
hand2 = input()
else:
print("Whats that? Type !Help if you're lost")
hand2 = input()
print(Chipcount, labat_chips)
if Chipcount < 300000:
print("Esfandiari: Its been a bad start for", name, "Labat with one good hand, and a little bit of luck asserts a 300k lead.")
labat_chips = 475000
Chipcount = 375000
print("Lon: Yes however dont count", name, "out, we said before that both these players have taken down big players to get here, however", name, "i believe has that better track record.")
print("Esfandiari: Im prosuming you're talking about that nasty bluff against Phil Ivey, trip ace's versus a pair of 2's!", name, "has got balls, no doubt")
print("Lon: I was reffering to when he knocked you out with the strai-")
print("Esfandiari: Shutup! I would rather not relive that terrible experience.")
print("Lon: Ha! Well we are back after 2 hours 30 of close action, after a few decent hands for", name, "he's back to only being 100k behind")
if Chipcount >= 300000 and Chipcount < 450000:
print("Esfandiari: Its been a alright start for", name, "Now both are moderately even in this showdown.")
print("And i think", name, "has it in him to do this.")
print("Lon: Yes however dont count Labat out, we said before that both these players have taken down big players to get here, however Labat i believe has that better track record.")
print("Esfandiari: Im prosuming you're talking about that nasty bluff against Phil Ivey, trip ace's versus a pair of 2's! Labat has got balls, no doubt")
print("Lon: Theres also", name, "Who knocked you out with the strai-")
print("Esfandiari: Shutup! I would rather not relive that terrible experience.")
print("Lon: Ha! Well we are back after 2 hours 30 of close action, after a few decent hands for", name, "he's now take a minor lead of 50k")
Chipcount = 450000
labat_chips = 400000
if Chipcount >= 450000:
Chipcount = 575000
labat_chips = 275000
print("Esfandiari: Its been a good start for", name, "Getting out of the first major hand is a skill all great players need")
print("And i think", name, "has it in him to do this.")
print("Lon: Yes however dont count Labat out, we said before that both these players have taken down big players to get here, however Labat i believe has that better track record.")
print("Esfandiari: Im prosuming you're talking about that nasty bluff against Phil Ivey, trip ace's versus a pair of 2's! Labat has got balls, no doubt")
print("Lon: I was reffering to when he knocked you out with the strai-")
print("Esfandiari: Shutup! I would rather not relive that terrible experience.")
print("Lon: Ha! Well we are back after 2 hours 30 of close action, after a few decent hands for", name, "he's now take a commanding lead of 300k")
print("We now resume the action.")
print("With a couple of good hands, you feel momentum is now on your side, lets see if the next hand can convert it.")
print("The dealer shuffles, passing both you and Labat 2 cards, you reveal them to be:")
print("Q♠ & Q♦")
print(A)
hand1 = input()
labat_chips = labat_chips - 25000
Chipcount = Chipcount - 25000
hand2pot = 50000
while playing == True:
pre-flop
if hand1 == "fold":
unable
if hand1 == "check" or hand1 == "call":
flop
hand2 = input()
while playing == True:
if hand2 == "fold":
unable
if hand2 == "check" or hand2 == "call":
turn
hand3 = input()
while playing == True:
if hand3 == "fold":
unable
if hand3 == "check" or hand3 == "call":
river
hand4 = input()
while playing == True:
if hand4 == "fold":
unable
if hand4 == "check" or hand4 == "call":
allin
if hand4 == "raise":
raise1 = int(input())
while playing == True:
if raise1 < 10000:
no
if raise1 >= 10000 and raise1 < 100000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise1 >= 100000 and raise1 < 200000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise1 >= 200000 and raise1 < labat_chips:
fold
if raise1 > labat_chips:
no
if raise1 == labat_chips:
allin
else:
print("Please place a valid bet")
raise1 = int(input())
break
if hand4 == "RHTH":
p
if hand4 == "AllIn":
z
if hand4 == "chipcount":
z
if hand4 == "!Help":
z
else:
print("Whats that? Type !Help if you're lost")
hand4 = input()
break
if hand3 == "raise":
raise2 = int(input())
while playing == True:
if raise2 < 10000:
no
if raise2 >= 10000 and raise2 < 100000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
calls
river
hand5 = input()
while playing == True:
if hand5 == "fold":
unable
if hand5 == "check" or hand5 == "call":
ok
if hand5 == "raise":
raise3 = int(input())
while playing == True:
if raise3 < 10000:
no
if raise3 >= 10000 and raise3 < 100000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise3 >= 100000 and raise3 < 200000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise3 >= 200000 and raise3 < labat_chips:
fold
if raise3 > labat_chips:
no
if raise3 == labat_chips:
allin
else:
print("Please place a valid bet")
raise3 = int(input())
break
if hand5 == "RHTH":
p
if hand5 == "AllIn":
z
if hand5 == "chipcount":
z
if hand5 == "!Help":
z
else:
print("Whats that? Type !Help if you're lost")
hand5 = input()
break
if raise2 >= 100000 and raise2 < 200000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
calls
river
hand6 = input()
while playing == True:
if hand6 == "fold":
unable
if hand6 == "check" or hand6 == "call":
ok
if hand6 == "raise":
raise4 = int(input())
while playing == True:
if raise4 < 10000:
no
if raise4 >= 10000 and raise4 < 100000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise4 >= 100000 and raise4 < 200000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise4 >= 200000 and raise4 < labat_chips:
fold
if raise4 > labat_chips:
no
if raise4 == labat_chips:
allin
else:
print("Please place a valid bet")
raise4 = int(input())
break
if hand6 == "RHTH":
p
if hand6 == "AllIn":
z
if hand6 == "chipcount":
z
if hand6 == "!Help":
z
else:
print("Whats that? Type !Help if you're lost")
hand6 = input()
break
if raise2 >= 200000 and raise2 < labat_chips:
fold
if raise2 > labat_chips:
no
if raise2 == labat_chips:
allin
else:
print("Please place a valid bet")
raise2 = int(input())
break
if hand3 == "RHTH":
p
if hand3 == "AllIn":
z
if hand3 == "chipcount":
z
if hand3 == "!Help":
z
else:
print("Whats that? Type !Help if you're lost")
hand3 = input()
break
if hand2 == "raise":
raise5 = int(input())
while playing == True:
if raise5 < 10000:
no
if raise5 >= 10000 and raise5 < 100000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise5 >= 100000 and raise5 < 200000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise5 >= 200000 and raise5 < labat_chips:
fold
if raise5 > labat_chips:
no
if raise5 == labat_chips:
allin
else:
print("Please place a valid bet")
raise1 = int(input())
break
if hand2 == "RHTH":
p
if hand2 == "AllIn":
z
if hand2 == "chipcount":
z
if hand2 == "!Help":
z
else:
print("Whats that? Type !Help if you're lost")
hand2 = input()
break
if hand1 == "raise":
if raise = 70k:
raise6 = int(input())
while playing == True:
if raise6 < 10000:
no
if raise6 >= 10000 and raise6 < 125000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
flop
hand7 = input()
while playing == True:
if hand7 == "fold":
unable
if hand7 == "check" or hand7 == "call":
turn
hand8 = input()
while playing == True:
if hand8 == "fold":
unable
if hand8 == "check" or hand8 == "call":
allin
if hand8 == "raise":
raise7 = int(input())
while playing == True:
if raise7 < 10000:
no
if raise7 >= 10000 and raise7 < 100000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
river
hand9 = input()
while playing == True:
if hand9 == "fold":
unable
if hand9 == "check" or hand9 == "call":
allin
if hand9 == "raise":
raise8 = int(input())
while playing == True:
if raise8 < 10000:
no
if raise8 >= 10000 and raise8 < 100000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise8 >= 100000 and raise8 < 200000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise8 >= 200000 and raise8 < labat_chips:
fold
if raise8 > labat_chips:
no
if raise8 == labat_chips:
allin
else:
print("Please place a valid bet")
raise8 = int(input())
break
if hand9 == "RHTH":
p
if hand9 == "AllIn":
z
if hand9 == "chipcount":
z
if hand9 == "!Help":
z
else:
print("Whats that? Type !Help if you're lost")
hand9 = input()
break
if raise7 >= 100000 and raise7 < 200000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
river
hand10 = input()
while playing == True:
if hand10 == "fold":
unable
if hand10 == "check" or hand10 == "call":
allin
if hand10 == "raise":
raise9 = int(input())
while playing == True:
if raise9 < 10000:
no
if raise9 >= 10000 and raise9 < 100000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise9 >= 100000 and raise9 < 200000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise9 >= 200000 and raise9 < labat_chips:
fold
if raise9 > labat_chips:
no
if raise9 == labat_chips:
allin
else:
print("Please place a valid bet")
raise9 = int(input())
break
if hand10 == "RHTH":
p
if hand10 == "AllIn":
z
if hand10 == "chipcount":
z
if hand10 == "!Help":
z
else:
print("Whats that? Type !Help if you're lost")
hand10 = input()
break
if raise7 >= 200000 and raise7 < labat_chips:
fold
if raise7 > labat_chips:
no
if raise7 == labat_chips:
allin
else:
print("Please place a valid bet")
raise7 = int(input())
break
if hand8 == "RHTH":
p
if hand8 == "AllIn":
z
if hand8 == "chipcount":
z
if hand8 == "!Help":
z
else:
print("Whats that? Type !Help if you're lost")
hand4 = input()
break
if hand7 == "raise":
raise10 = int(input())
while playing == True:
if raise10 < 10000:
no
if raise10 >= 10000 and raise10 < 100000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise10 >= 100000 and raise10 < 200000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise10 >= 200000 and raise10 < labat_chips:
fold
if raise10 > labat_chips:
no
if raise10 == labat_chips:
allin
else:
print("Please place a valid bet")
raise10 = int(input())
break
if hand7 == "RHTH":
p
if hand7 == "AllIn":
z
if hand7 == "chipcount":
z
if hand7 == "!Help":
z
else:
print("Whats that? Type !Help if you're lost")
hand7 = input()
break
if raise6 >= 125000 and raise6 < 200000:
if labat_chips < 100000:
k
if labat_chips >= 100000:
k
if raise6 >= 200000 and raise6 < labat_chips:
fold
if raise6 > labat_chips:
no
if raise6 == labat_chips:
allin
else:
print("Please place a valid bet")
raise6 = int(input())
break
if hand1 == "RHTH":
p
if hand1 == "AllIn":
z
if hand1 == "chipcount":
z
if hand1 == "!Help":
z
else:
print("Whats that? Type !Help if you're lost")
hand1 = input()
|
da810493e68a6051f44dba7fd1b9081624d3f35e | Guitatto/trabalho | /exercício5.py | 1,614 | 3.78125 | 4 | #Um posto está vendendo combustíveis com a seguinte tabela de descontos:
#Álcool:
#até 20 litros, desconto de 3% por litro
#acima de 20 litros, desconto de 5% por litro
#Gasolina:
#até 20 litros, desconto de 4% por litro
#acima de 20 litros, desconto de 6% por litro Escreva um algoritmo que leia o número de litros vendidos, o tipo de combustível (codificado da seguinte forma: A-álcool, G-gasolina), calcule e imprima o valor a ser pago pelo cliente sabendo-se que o preço do litro da gasolina é R$ 2,50 o preço do litro do álcool é R$ 1,90.
tipo = float(input('Qual Tipo de Aditivo voce que Adicionar 1 - Gasolina ou 2 - Alcool: '))
quantidade = float(input('informe a quantidade: '))
if tipo == 2:
if quantidade <= 20:
valorAlcool = quantidade * 1.90
descontoA1 = (3 * valorAlcool) / 100
valorAlcool = (valorAlcool -descontoA1)
print(f'O valor a ser pago é de: {valorAlcool}')
if quantidade > 20:
valorAlcool = quantidade * 1.90
descontoA2 = (6 * valorAlcool) / 100
valorAlcool = (valorAlcool -descontoA2)
print(f'O valor a ser pago é de: {valorAlcool}')
if tipo == 1:
if quantidade <= 20:
valorGasolina = quantidade * 2.50
descontoG1 = (3 * valorGasolina) / 100
valorGasolina = (valorGasolina -descontoG1)
print(f'O valor a ser pago é de: {valorGasolina}')
if quantidade > 20:
valorGasolina = quantidade * 2.50
descontoG2 = (6 * valorGasolina) / 100
valorGasolina = (valorGasolina -descontoG2)
print(f'O valor a ser pago é de: {valorGasolina}') |
79e7ac40da24cbf5eb35076221c78918d7fd7ba0 | ZhiyuSun/leetcode-practice | /501-800/529_扫雷游戏.py | 3,179 | 3.5625 | 4 | """
让我们一起来玩扫雷游戏!
给定一个代表游戏板的二维字符矩阵。 'M' 代表一个未挖出的地雷,'E' 代表一个未挖出的空方块,'B' 代表没有相邻(上,下,左,右,和所有4个对角线)地雷的已挖出的空白方块,数字('1' 到 '8')表示有多少地雷与这块已挖出的方块相邻,'X' 则表示一个已挖出的地雷。
现在给出在所有未挖出的方块中('M'或者'E')的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板:
如果一个地雷('M')被挖出,游戏就结束了- 把它改为 'X'。
如果一个没有相邻地雷的空方块('E')被挖出,修改它为('B'),并且所有和其相邻的方块都应该被递归地揭露。
如果一个至少与一个地雷相邻的空方块('E')被挖出,修改它为数字('1'到'8'),表示相邻地雷的数量。
如果在此次点击中,若无更多方块可被揭露,则返回面板。
示例 1:
输入:
[['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'M', 'E', 'E'],
['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E']]
Click : [3,0]
输出:
[['B', '1', 'E', '1', 'B'],
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]
"""
from typing import List
# 2020.08.20 继续直奔题解
class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
dir_x = [0, 1, 0, -1, 1, 1, -1, -1]
dir_y = [1, 0, -1, 0, 1, -1, 1, -1]
def dfs(board, x, y):
count = 0
for i in range(0, 8):
tx = x + dir_x[i]
ty = y + dir_y[i]
if tx < 0 or tx >= len(board) or ty < 0 or ty >= len(board[0]):
continue
if board[tx][ty] == 'M':
count += 1
if count > 0:
board[x][y] = str(count)
else:
board[x][y] = 'B'
for i in range(0, 8):
tx = x + dir_x[i]
ty = y + dir_y[i]
if tx < 0 or tx >= len(board) or ty < 0 or ty >= len(board[0]) or board[tx][ty] != 'E':
continue
dfs(board, tx, ty)
x, y = click[0], click[1]
if board[x][y] == 'M':
board[x][y] = 'X'
else:
dfs(board, x, y)
return board
# 超哥版,绝了
class Solution1:
def updateBoard(self, board, click):
row, col = click[0], click[1]
dirs = ((-1, 0), (1, 0), (0, 1), (0, -1), (-1, 1), (-1, -1), (1, 1), (1, -1))
if 0 <= row < len(board) and 0 <= col < len(board[0]):
if board[row][col] == 'M':
board[row][col] = 'X'
elif board[row][col] == 'E':
n = sum([board[row + r][col + c] == 'M' for r, c in dirs if 0 <= row + r < len(board) and 0 <= col + c < len(board[0])])
board[row][col] = n and str(n) or 'B'
for r, c in dirs * (not n):
self.updateBoard(board, [row + r, col + c])
return board |
4f1e768f7d674ef1fb2dc2950b23a9e302177dbe | iykat/Google_Get_Ahead_Africa_21 | /longest_path_in_tree.py | 2,246 | 4.21875 | 4 | # Write a function that computes the length of the longest path of consecutive integers in a tree.
# A node in the tree has a value and a set of children nodes.
# A tree has no cycles and each node has exactly one parent.
# A path where each node has a value 1 greater than its parent is a path of consecutive integers (e.g. 1,2,3 not 1,3,5).
# A few things to clarify:
# Integers are all positive
# Integers appear only once in the tree
"""
suggested solution
class Tree:
def __init__(self, value, *children):
self.value = value
self.children = children
# It's Python, so we walk the tree by iterating through it, yielding the length of
# the path ending at each node we encounter, then take the max of that.
def longest_path(tree):
def rec(current, parent_value=0, parent_path_length=0):
# Length of the longest chain this node is a part of.
current_path_length = (parent_path_length + 1
if current.value == parent_value + 1 else 1)
# Emit the length for this node
yield current_path_length
# Recurse into the children
for child in current.children:
# For each of the descendant nodes, emit their lengths as well
for value in rec(child, current.value, current_path_length):
yield value
# Take the overall maximum length.
return max(*rec(tree))
# "Tests"
if __name__ == '__main__':
assert longest_path(
Tree(1,
Tree(2,
Tree(4)),
Tree(3))
) == 2
assert longest_path(
Tree(5,
Tree(6),
Tree(7,
Tree(8,
Tree(9,
Tree(15),
Tree(10))),
Tree(12)))
) == 4
print( longest_path(
Tree(1,
Tree(2,
Tree(4)),
Tree(3))
) )
print( longest_path(
Tree(5,
Tree(6),
Tree(7,
Tree(8,
Tree(9,
Tree(15),
Tree(10))),
Tree(12)))
))
"""
#my variation of the solution to be updated
|
ba4e7b43760a700cce52e03bd5fab16cd6990365 | somrathumayan/numpy-practice | /copy_vs_view.py | 839 | 3.8125 | 4 | import numpy as np
arr1 = np.array([1,2,3,4,5,6,7,8,9])
x = arr1.copy()
arr1[0] = 42
print("Latest Value of arr1 is : ", arr1) # change accepted & showed the last value
print("After copy value of x is : ", x) # after copy value
print("*****************************************************")
arr2 = np.array([1,2,3,4,5,6])
y = arr2.view()
arr2[0] = 33
print("Latest Value of arr2 is : ", arr2) # change accepted & showed the last value (both value same)
print("After view value of y is : ", y) # after copy value (both value same)
print("*****************************************************")
arr3 = np.array([1,2,3,4,5,6,7,8,9]) # Check if Array Owns it's Data
m = arr3.copy()
n = arr3.view()
print("Copy Value is ", m.base)
print("View Value is ", n.base)
print("*****************************************************")
|
34a8e0bacf199262ace6a1ffb7fd909404fcc6e6 | spoonless/bctraining_python3 | /moyenne_fonction.py | 703 | 3.640625 | 4 | '''
Created on 16 sept. 2019
@author: david
'''
MOYENNE = 170
def demander_taille():
"""Cette fonction demande sa taille à l’utilisateur et retourne la valeur
saisie sous la forme d’un nombre."""
taille_saisie = input("Quelle est votre taille ? ")
return float(taille_saisie) * 100
def comparer_taille(taille1, taille2=MOYENNE):
return taille1 - taille2
def afficher_difference_moyenne(difference_moyenne):
print(f"Vous avez un écart de {difference_moyenne:.0f} cm par rapport à la moyenne qui est de {MOYENNE} cm.")
if __name__ == "__main__":
taille = demander_taille()
difference = comparer_taille(taille)
afficher_difference_moyenne(difference)
|
5e60c9359db886412c9c08c9a436341a55aa413e | ronbakrac/Data-Structure-Projects | /Binary Search Tree/TupleTrees.py | 4,350 | 4.40625 | 4 | '''Provides basic operations for Binary Search Trees using
a tuple representation. In this representation, a BST is
either an empty tuple or a length-3 tuple consisting of a data value,
a BST called the left subtree and a BST called the right subtree
'''
def is_bintree(T):
if type(T) is not tuple:
return False
if T == (): # empty tree
return True
if len(T) != 3:
return False
return is_bintree(T[1]) and is_bintree(T[2])
def bst_min(T):
# assumption: T is a binary search tree
if T == ():
return None
if T[1] == ():
return T[0]
return bst_min(T[1])
def bst_max(T):
# assumption: T is a binary search tree
if T == ():
return None
if T[2] == ():
return T[0]
return bst_max(T[2])
def is_bst(T):
"Returns True if T is a binary search tree"
if not is_bintree(T):
return False
if T == ():
return True
if not is_bst(T[1]) or not is_bst(T[2]): # recursion!
return False
if T[1] == () and T[2] == ():
return True
if T[2] == ():
return bst_max(T[1]) < T[0]
if T[1] == ():
return T[0] < bst_min(T[2])
return bst_max(T[1]) < T[0] < bst_min(T[2])
def bst_search(T,x):
"Returns the subtree whose data item equals x"
if T == ():
return None
if T[0] == x:
return T
if x < T[0]:
return bst_search(T[1],x)
return bst_search(T[2],x)
def bst_insert(T,x):
"returns the tree resulting from insertion of data item x"
if T == ():
return (x,(),())
if x > T[0]:
return (T[0],T[1],bst_insert(T[2],x))
return (T[0],bst_insert(T[1],x),T[2])
def delete_min(T):
'''Returns the tree that results when the smallest element in T
has been deleted'''
if T == ():
return T
if not T[1]: # No left subtree – minimum value is the root value
return T[2]
else: # Minimum value is in the left subtree
return (T[0],delete_min(T[1]),T[2])
def bst_delete(T,x):
'''Returns the tree that results when the data item x
has been deleted from T'''
assert T, "deleting from an empty tree"
if x < T[0]:
return (T[0], bst_delete(T[1],x), T[2])
elif x > T[0]:
return (T[0], T[1], bst_delete(T[2],x))
else:
# single child cases
if not T[1]:
return T[2]
elif not T[2]:
return T[1]
else:
# two children case
return (bst_min(T[2]) , T[1], delete_min(T[2]) )
def print_bintree(T,indent=0):
"Prints the tree using indentation to show the structure"
if not T:
print('*')
return
else:
print(T[0])
print(' '*(indent + T[0]-1)+'---', end = '')
print_bintree(T[1],indent+3)
print(' '*(indent + T[0]-1)+'---', end = '')
print_bintree(T[2],indent+3)
def print_func_space(x):
"prints a value x followed by a space"
print(x,end=' ')
def inorder(T, f):
"Applies the function f to root value of each subtree of T"
if not is_bst(T):
return
if not T:
return
inorder(T[1],f) # apply f to the root value of each subtree of T[1]
f(T[0]) # apply f to the root value of T
inorder(T[2],f) # apply f to the root value of each subtree of T[2]
def createBST(values):
'''Creates and returns the binary search tree obtained by inserting,
in order, the values in tuple values into an initially empty tree'''
K = ()
for x in values:
K = bst_insert(K,x) # ***
return K
if __name__ == '__main__':
# code to test the functions in this module
t = ('Joe','Bob', 'Phil', 'Paul', 'Marc', 'Jean', 'Jerry',
'Alice', 'Anne')
K = createBST(t)
print('\nTree elements in sorted order\n')
inorder(K,print_func_space)
print()
print('\nPrint full tree\n')
print_bintree(K)
print("\nDelete Bob and print tree\n")
K = bst_delete(K,'Bob')
print_bintree(K)
print() # print a blank line
print("\nPrint subtree at 'Phil'\n")
print_bintree(bst_search(K,'Phil'))
print()
|
7bb0bfec2c22baff3175659c124c4e68181bd157 | suecharo/ToudaiInshi | /2015_summer/question_3.py | 335 | 3.765625 | 4 | # coding: utf-8
def question_3():
f = open("program.txt", "r")
read_file = f.read()
l_line = read_file.split("\n")
for i in range(len(l_line) - 1):
now_line = l_line[i]
next_line = l_line[i + 1]
if now_line == next_line:
print(now_line)
if __name__ == "__main__":
question_3()
|
f64f446a83d3643ac9025081755b2b5f3ad46481 | jacareds/Unis | /IA_Atividade4/Fatoração_Recursiva.py | 354 | 3.875 | 4 | '''def fatorial(n):
if n == 0 or n == 1:
return 1
else:
return n * fatorial(n-1)'''
lista = [12,15,7]
def fatR(n):
if n == 0:
return 1
else:
return n * fatR(n-1)
cal = max(lista)
print("Usando a lista ", lista, ". Valor máximo dos números encontrado em sua fatoração recursiva: ", fatR(cal))
|
8e29ac713a114ceb484dcf6ee4c87b488274b853 | Rooters123/code_calc | /leetcode/初级算法-数组/04判断是否有重复项.py | 989 | 3.5 | 4 | #encoding = utf-8
# 给定一个整数数组,判断是否存在重复元素。
#
# 如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
class Solution:
def maxProfit(self, nums):
# 第一种解法,对数组进行排序,如果相邻两个元素相同,那么就代表存在重复值
# nums.sort()
# for i in range(len(nums) - 1 ):
# if nums[i] == nums[i + 1] :
# return True
# return False
#第二种解法:利用python的集合进行自动去重
# print(set(nums))
# return len(nums) != len(set(nums))
# 第三种:
nums = "".join(str(s) for s in nums)
print(nums)
for i in range(len(nums)):
if nums.find(nums[i]) != nums.rfind(nums[i]):
return False
return True
s = Solution()
print(s.maxProfit([1,2,3,4,4]))
|
48e5afc2c8b958d12e11e3da2a0dcb0b2ab586d0 | akhil-s-kumar/Python | /Calculator.py | 1,715 | 4.125 | 4 | ####### Calculator #######
#Developer : Akhil S Kumar
#Date Created : 9/06/2019
#https://www.github.com/akhil-s-kumar
print("Hello friend, Can you introduce your name please? ")
name=input()
print('Hello', name, 'Tell me the operation you want to do?')
cont = "y" or "Y"
while cont.lower() == "y" or cont.upper() == "Y":
print("For addition press 1")
print("For differnce press 2")
print("For product press 3")
print("For Division press 4")
print("For power press 5")
print("For remainder press 6")
n=int(input("Enter your option: "))
if n is 1:
x=float(input("Enter the first number: "))
y=float(input("Enter the second number: "))
z=x+y
print("The sum of the number is {0}".format(z))
elif n is 2:
x=float(input("Enter the first number: "))
y=float(input("Enter the second number: "))
z=x-y
print("The difference of the number is {0}".format(z))
elif n is 3:
x=float(input("Enter the first number: "))
y=float(input("Enter the second number: "))
z=x*y
print("The product of the number is {0}".format(z))
elif n is 4:
x=float(input("Enter the first number: "))
y=float(input("Enter the second number: "))
z=x/y
print("The division of the number is {0}".format(z))
elif n is 5:
x=float(input("Enter the base number: "))
y=float(input("Enter the power number: "))
z=x**y
print("The power of the number is {0}".format(z))
elif n is 6:
x=float(input("Enter the divident: "))
y=float(input("Enter the divisor: "))
z=x%y
print("The remainder of the number is {0}".format(z))
else:
print("Press the correct operant")
cont = input("Do you want to continue? (y/n)")
if cont == "n":
break
|
439e2249c22612279164fed5b93deb5556c85b59 | Mahizer/lesson3 | /task6.py | 1,193 | 3.890625 | 4 | # 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
# но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
# Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки,
# но каждое слово должно начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func().
def inf_func(word):
return word.title()
user_sen = input('Введите слово или предложение: ')
alp = ord('a')
alp = set(''.join([chr(i) for i in range(alp, alp + 26)]))
if set(user_sen) & set(alp):
print(inf_func(user_sen))
else:
print('Можно вводить только латинские буквы!')
|
45e653be91a0776c1af43b0e2d4512bfc290ac03 | sachasi/daily-python-practice | /edabit/very_easy/sum_polygon_angles.py | 117 | 3.5625 | 4 | # Return the total sum of internal angles (in degrees)
def sum_polygon(n):
return (n-2)*180
print(sum_polygon(24))
|
175d1d1fc8e3894dd6dc9e8f5608a96a13c55aba | ericgarig/daily-coding-problem | /022-sentence-from-string.py | 1,487 | 4.03125 | 4 | """
Daily Coding Problem - 2018-10-29.
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.
E.g.:
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'].
"""
def words_from_str(str='', word_list=[]):
"""Given a list of words and a string, return the broken out string."""
sentence_list = []
while str:
for i in word_list:
if str.startswith(i):
sentence_list.append(i)
str = str[len(i):]
break
else:
return None
return sentence_list
print(words_from_str("thequickbrownfox", ['quick', 'brown', 'the', 'fox']))
print(words_from_str("bedbathandbeyond", ['bed', 'bath', 'bedbath', 'and', 'beyond']))
print(words_from_str("bedbathandbeyond", ['bath', 'bedbath', 'bed', 'and', 'beyond']))
print(words_from_str("bedbathandbeyond", ['bed', 'bathand', 'bath', 'and', 'beyond']))
print(words_from_str("invalidsentence", []))
print(words_from_str("abcd", ['b', 'a', 'c', 'e']))
print(words_from_str("abcd", ['b', 'a', 'c', 'd']))
|
0330968eb0a0df0806b275d67f3d45b3a90e6b44 | phamdinhkhanh/FirstPackagePython | /src/sum.py | 167 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 23:08:32 2018
@author: laptopTCC
"""
def sum(x, y):
print('Sum of {}, {}: {}'.format(x, y, x+y))
return x+y |
5a95c8e4dedb2f37b89011e6fdd9993c636c482d | DanTeegan/DevOps_Course | /Week 3 - Python Basics (Data types, Loops, Control Flow, 4 pillars OOP)/Exercises/DNA string parsing/DNA task.py | 653 | 3.65625 | 4 |
class Dna:
def dna_counter(self):
dna = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"
A = []
C = []
G = []
T = []
for letter in dna:
if letter == "A":
A.append(letter)
if letter == "C":
C.append(letter)
if letter == "G":
G.append(letter)
if letter == "T":
T.append(letter)
A_count = len(A)
C_count = len(C)
G_count = len(G)
T_count = len(T)
print(A_count, C_count, G_count, T_count)
dna1 = Dna()
dna1.dna_counter()
|
d085fc145f1ddba1fe5f3205c232c1ea6bcc1edd | dnjssla94/Studing | /python/grammer/module.py | 2,084 | 3.546875 | 4 |
#파이썬 클레스의 멤버 변수와 함수에는 항상 self가 붙어야한다.
#double underbar는 외부에서 접근 못하는 함수를 표시하는 약속
class FishCakeMaker:
def __init__(self, **kwargs):#생성자. 클래스 내의 함수는 self가 반드시 있어야함.
self.size = 10
self.flavor = "red bin"
self.price = 100
if "size" in kwargs:
self.size = kwargs.get("size")
if "flavor" in kwargs:
self.flavor = kwargs.get("flavor")
if "price" in kwargs:
self.price = kwargs.get("price")
# def __del__(self):#소멸자
# print("삭제되었습니다.")
def __lt__ (self,other): #연산자 오버로딩
return self.price < other.price
def __le__ (self,other): #연산자 오버로딩
return self.price <= other.price
def __gt__ (self,other): #연산자 오버로딩
return self.price > other.price
def __ge__ (self,other): #연산자 오버로딩
return self.price >= other.price
def __eq__ (self,other): #연산자 오버로딩
return self.price == other.price
def __ne__ (self,other): #연산자 오버로딩
return self.price != other.price
def __str__(self):#__str__: 객체를 프린트하면 출력
return "class fishCakeMaker (size: {}, price: {}, flavor: {})".format(self.size,self.price,self.flavor)
def show(self):
print("붕어빵 종류 {}".format(self.flavor))
print("붕어빵 크기 {}".format(self.size))
print("붕어빵 가격 {}".format(self.price))
print("*"*60)
class MarketGoods(FishCakeMaker):#상속
def __init__(self, margin=1000, **kwargs):
super().__init__(**kwargs)#부모클래스 생성자 호출 꼭 해주자
self._market_price = self.price+margin
def show(self):
print(self.flavor,self._market_price)
print(__name__)
if __name__ == "__main__":
print(__name__)
fish1 = MarketGoods(size = 25, price = 400)
fish1.show()
def add(a,b):
return a+b |
6f7c124a70a59951febde4d606c4ddd20b1c3ee5 | chbrown/scripts | /intersect | 729 | 3.546875 | 4 | #!/usr/bin/env python
import argparse
from collections import Counter
def iter_counts(files):
counter = Counter()
for file in files:
lines = (line.rstrip() for line in file)
counter.update(set(lines))
return counter
def main():
parser = argparse.ArgumentParser(
description='Find lines shared by all files.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('files', nargs='+', type=argparse.FileType('r'))
opts = parser.parse_args()
counter = iter_counts(opts.files)
minimum = len(opts.files)
for line, count in counter.items():
if count >= minimum:
print(line)
if __name__ == '__main__':
exit(main())
|
ad5e98655b6a1589d0bac9beccf0ee79fd8acc11 | sayedsadat98/python-data-structure-algorithms | /LinkedList/LinkedListClass/LinkedList.py | 2,570 | 3.9375 | 4 | import random
" All important methods of Doubly Linked List can be found here"
class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
currentNode = self.head
while currentNode:
yield currentNode
currentNode = currentNode.next
def __str__(self):
values = [str(x.value) for x in self]
return '<->'.join(values)
def __len__(self):
count = 0
currentNode = self.head
while currentNode:
count += 1
currentNode = currentNode.next
return count
def add(self, value):
newNode = Node(value)
if self.head is None:
self.head = newNode
self.tail = newNode
else:
newNode.next = None
self.tail.next = newNode
newNode.prev = self.tail
self.tail = newNode
def delete(self, index):
'''
index : Starts from 0
'''
if self.head is None:
print('Invalid')
return
elif index == 0:
targetNode = self.head
targetNode.next.prev = None
self.head = targetNode.next
elif index >= (len(self)) - 1:
targetNode = self.tail
targetNode.prev.next = None
self.tail = targetNode.prev
else:
pointer = 0
currentNode = self.head
while pointer < index:
currentNode = currentNode.next
pointer += 1
nextNode = currentNode.next
prevNode = currentNode.prev
prevNode.next = nextNode
nextNode.prev = prevNode
def generate_values(self, n, minVal, maxVal):
for i in range(n):
num = random.randint(minVal, maxVal)
self.add(num)
# print('Value is', num)
def reverse(self):
currentNode = self.tail
while currentNode:
print(currentNode.value)
currentNode = currentNode.prev
# list = LinkedList()
# list.add(2)
# list.add(5)
# list.add(7)
# list.add(6)
# list.add(8)
# list.add(8)
# # list.generate_values(15, 1, 9)
# print(list)
# # print(len(list))
#
# list.delete(5)
# print(list)
# list.reverse()
# print(list)
# list.delete(2)
# print((list))
# list.delete(2)
# print((list))
|
8025a3ea9c2d2bbd14ff0e2d346fd20236539933 | chantelprows/bioinformatics-algorithms | /venv/Lib/CS 418/Part 3/overlapGraph.py | 552 | 3.59375 | 4 | def overlap(patterns):
k = len(patterns[0])
dict = {}
for pattern in patterns:
suffix = pattern[1:]
for pattern2 in patterns:
prefix = pattern2[:k - 1]
if suffix == prefix and pattern != pattern2:
dict[pattern] = pattern2
break
return dict
# dnaList = []
# f = open("rosalind_ba3c.txt", "r")
# f1 = f.readlines()
# for dna in f1:
# dnaList.append(dna.strip('\n'))
# f.close()
#
# dict = (overlap(dnaList))
# for x in dict:
# print(x + ' -> ' + dict[x]) |
9e5db858004fa37b8a208332f1f26c2f2a03e24c | frasca17/pcs2-homework1 | /Sets4.py | 175 | 3.90625 | 4 | N = int(raw_input())#total number of country stamps it's a number
country_stamps= set()
for stamp in range(0, N):
country_stamps.add(raw_input())
print len(country_stamps) |
e6847af76046b5f7bce77612cb98fccf19d5726d | brandoneng000/LeetCode | /easy/283.py | 675 | 3.703125 | 4 | from typing import List
class Solution(object):
def moveZeroes(self, nums: List[int]) -> None:
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
index = 0
size = len(nums)
while index < size:
check = nums[index]
if check == 0:
size -= 1
nums.pop(index)
nums.append(0)
else:
index += 1
def main():
sol = Solution()
print(sol.moveZeroes([0,1,0,3,12]))
print(sol.moveZeroes([0]))
print(sol.moveZeroes([0,0,0,0,1]))
if __name__ == '__main__':
main() |
3ce9d780ffdfe1d55df015c5436aa3defc541ae4 | kolodnikovm/blackjack | /app/View/gameview.py | 1,837 | 3.859375 | 4 | """ Модуль view проги """
class GameView():
def __init__(self, controller, model):
self.controller = controller
self.model = model
# добавляет view компонент в слушатели model
self.model.add_observer(self)
def model_changed(self):
""" Отображает измененый набор карт и очков для игрока. """
print("My score: {}".format(self.model.user.score), end='\n'+'-'*40+'\n')
print("My cards:{}".format(self.model.user.hand), end='\n'+'-'*40+'\n')
def game_status(self, u, c):
""" Принтует финальный статус игры """
status = ("\nUser's score:{} || Computer's score: {}\nMy cards{}" +
"\nComps's{}\nTotal score: User: {}, Computer: {}") \
.format(u.score, c.score, u.hand, c.hand, u.total, c.total)
print(status)
def show_game(self):
""" Выводит информацю о начале игры и запускает игровой цикл. """
print('\nGame started\n')
#отобразить стартовое состояние игры
print("My score: {}".format(self.model.user.score), end='\n'+'-'*40+'\n')
print("My cards:{}".format(self.model.user.hand), end='\n'+'-'*40+'\n')
while self.controller.checker(*self.controller.get_players()):
opt = input('Hit or Stand [h]/[s] - ')
if opt == 'h':
self.controller.hit_all()
elif opt == 's':
self.controller.computer_fill()
elif opt == 'e':
raise Exception
self.controller.game_over()
self.game_status(*self.controller.get_players())
|
3a222865acf7be795acccbbbeda5e1255b5a153f | chunweiliu/leetcode2 | /convert_a_number_to_hexadecimal.py | 1,568 | 3.515625 | 4 | class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
Question:
- What's the range for the input number?
=> 32 bits
- How about negative number?
=> Python use 2's complement already
"""
import string
hexdigits = string.hexdigits[:16] # 0123456789abcdef
hex_string = ''
for i in range(0, 32, 4):
hex_string = hexdigits[num & 15] + hex_string
num >>= 4
return hex_string.lstrip('0')
def toHex2(self, num):
sixteen = 16
hex_table = {}
for i in range(sixteen):
if i > 10:
hex_table[i] = chr(i - 10 + ord('a'))
else:
hex_table[i] = str(i)
hex_str = ''
while num:
hex_str = hex_table[num % sixteen] + hex_str
num /= sixteen
return hex_str
def toHex_dumb_buggy(self, num):
# Covert number to bits
negative = True if num < 0 else False
if negative:
num *= (-1)
bits = [0] * 32
i = 0
while num:
bits[i] = num & 1
num >>= 1
i += 1
# Convert bits to hex
hex_str = ''
for i in range(0, 32, 4):
digit = 8 * bits[i + 3] + 4 * bits[i + 2] + 2 * bits[i + 1] + 1 * bits[i]
char = chr(digit - 10 + ord('a')) if digit > 10 else str(digit)
hex_str = char + hex_str
return hex_str
print Solution().toHex(26) |
67eeb1441122bc4294810778c18a69acd0d22ff4 | andriiglukhyi/leetcode | /look-say.py | 352 | 3.59375 | 4 | def looksay(look):
look = str(look)
prev, count, say = look[0], 1, ''
for char in look[1:]:
if char == prev:
count += 1
continue
say += str(count) + prev
prev = char
count = 1
print(say + str(count) + prev)
return say + str(count) + prev
# if 'main' == __name__:
looksay(8)
|
c955e367178c31effbfe53a1a328984af5f19c14 | lovehoneyginger/LearnPython | /compound interest.py | 325 | 3.890625 | 4 | print("Enter the principle amount")
a = float(input())
print("Enter the interest rate")
b = float(input())
print("Enter the number of times interest applied per time period")
c = int(input())
print("Enter the number of years")
d = float(input())
e = a * ((1 +(b/(c*100)))**(d*c))
print("The total amount to pay : " + str(e))
|
8cb08aa9a3533b3e85209839c9f6252579abab4c | Rajeshdraksharapu/Leetcode-Prblems | /findNumInArray.py | 1,987 | 3.703125 | 4 |
nums = [7,8,9,10,11,12,13,1,4,5,6]
#nums=[3,1,2]
#nums=[6,7,8,0,1,2,3,4,5,6]
#This one is O(2Logn) Approach is Little slower than O(logn) Approach
search=7
def binarySearch(nums,pivot,start,end,search):
if pivot==0:
start=0
end=len(nums)-1
elif search>=nums[pivot] and search<=nums[end]:
start=pivot-1
end=end
else:
start=start
end=pivot
while start<=end:
mid=(start+end)//2
if nums[mid]==search:
return mid
else:
if nums[mid]<search:
start=mid+1
else:
end=mid-1
else:
return -1
# Approach 1
#Finding Pivot
pivot=0
def findingPivot(nums,start,end):
global pivot
midValue=(start+end)//2
if nums[midValue]>nums[midValue+1]:
pivot=midValue+1
else:
if nums[midValue]>nums[start]:
start=midValue+1
end=end
return findingPivot(nums,start,end)
else:
start=start
end=midValue
return findingPivot(nums,start,end)
return pivot
start=0
end=len(nums)-1
if len(nums)>2:
piviot=findingPivot(nums,start,end)
result= binarySearch(nums,
piviot,
start,
end,
search)
print(result)
else:
piviot=0
result= binarySearch(nums,piviot,start,end,search)
print(result)
#Approach 2
def findElementInRotatedArray(nums,search):
start=0
end=len(nums)-1
while start<=end:
mid=(start+end)//2
if nums[mid]==search:
return mid
else:
if nums[start]<nums[mid]:
if nums[start]>search and search<nums[mid]:
end=mid-1
else:
start=mid+1
else:
if nums[end]<search and search<nums[mid]:
start=mid+1
else:
end=mid-1
print(findElementInRotatedArray(nums,search)) |
b3de4314dad918b2466e7519e68b81f1d07c8d5a | Luisa158/TallerAlgoritmos | /Algoritmo5a.py | 112 | 3.6875 | 4 |
print("Bienvenido")
print("La ecuación es (55+9)%9 ")
resultado= (55+9)%9
print("respuesta " +str(resultado))
|
675953b4c749b8936377df8547e67fe555435019 | Mecknavorz/Basic-Conways-Game-of-Life | /conways.py | 4,567 | 3.59375 | 4 | '''
-conway's game of life
-made by Tzara Northcut @Mecknavorz
-requires pygame
'''
#import the stuff we need
import pygame, sys, time
#-----------------------------------------
#initalize some variables and other things
#-----------------------------------------
width = 6 #cell size width
height = 6 #cell size height
space = 2 #thickness of world lines
#create the 2d array where we actually store vairables of cells
world = [[0 for x in range(100)] for y in range(100)]
#initialzie pygame
pygame.init()
size = [100*(width+space)+space, 100*(height+space)+space] #window size
screen = pygame.display.set_mode(size) #make the window the right size
#set spme colors
BLACK = ( 0, 0, 0) #background color
WHITE = (255, 255, 255) #color of world
GREEN = ( 0, 0, 0) #color of cells that are alive and well
RED = (255, 0, 0) #colors of the cells about to die
#speed stuff
clock = pygame.time.Clock() #clock used to manage game speed
pause = True #used to control the steps, might not need this
laststep = time.time()
#used to keep runing until the game is closed
done = False
#-------------------------------------
#some functions to be used in the game
#-------------------------------------
#determine #of cells nearby
def getclose(x, y):
nearby = 0
#avoid out of bounds error and make the grid a torroid
if(x+1) > 99:
x = 0
if(y+1) > 99:
y = 0
#swcan nearby squares and if there's something there add 1 to the count
if world[x-1][y-1]:
nearby += 1
if world[x][y-1]:
nearby += 1
if world[x+1][y-1]:
nearby += 1
if world[x-1][y]:
nearby += 1
if world[x+1][y]:
nearby += 1
if world[x-1][y+1]:
nearby += 1
if world[x][y+1]:
nearby += 1
if world[x+1][y+1]:
nearby += 1
return nearby
#calculate next step
def nextStep():
for x in range(len(world)):
for y in range(len(world[0])):
near = getclose(x, y)
if near < 2: #if there are less than two neighbors then kill the cell
world[x][y] = 0
if near > 3: #if there are more than three neighbors then kill the cell
world[x][y] = 0
if (world[x][y] == 0) and (near == 3): #if there are 3 neighbors near a dead cell, revive it
world[x][y] = 1
#clear the board
def clear():
for x in range(len(world)):
for y in range(len(world[0])):
world[x][y] = 0
#---------------------
#the initale game loop
#---------------------
while not done:
#to make sure the game quits when we need it to
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN: #if we get a click
pos = pygame.mouse.get_pos() #find where the click was
#change the pixel coords into game coords
x = pos[1] // (height+space)
y = pos[0] // (width+space)
#add or remove the cell that's there
if world[x][y] == 0: #if the tile is empty add a cell
world[x][y] = 1
#print("nearby: ", getclose(x, y)) #used for debugging
else: #else if there's something there, remove the cell
world[x][y] = 0
#print("click: ", pos, "grid coord: ", x, y) #debug stuff
elif event.type == pygame.KEYDOWN: #pause the game when space is pressed
if event.key == pygame.K_SPACE:
#print('space pressed')
if pause:
pause = False
elif not pause:
pause = True
elif event.key == pygame.K_RIGHT: #if we presws the right key go forward a step
nextStep() #calculate the next
elif event.key == pygame.K_ESCAPE:
clear()
#draw the world
screen.fill(BLACK)
#maybe move this to a seprate function to help with effeciency?
for x in range(len(world)):
for y in range(len(world[0])):
color = WHITE
if world[x][y] == 1:
color = GREEN
pygame.draw.rect(screen, color, [(space+width)*y+space, (space+height)*x+space, width, height])
#set frame rate
clock.tick(60)
if (not pause) and ((time.time() - laststep) > .1):
laststep = time.time()
#print(laststep)
nextStep()
#update screen
pygame.display.flip()
#if we;ve gotten this far (eg out of the while loop) we know it's time to quit
pygame.quit()
|
9d32acf04c7176a48a93b1d5aea6bc55909828e2 | nicobritos/kiri-surveys-webapp | /python_scrapper/scripts/excel_parser_q.py | 1,507 | 3.5 | 4 | # -*- coding: utf-8 -*-
import pandas
import json
import re
def remove_spaces(s):
return re.sub(r"\s\s+", " ", str(s)).strip()
def main():
df = pandas.read_excel('questions2.xlsx', 'definitions', header=None)
questions = []
index = 0
for i in df.iterrows():
values = i[1].tolist()
question = {
'id': index,
'n': remove_spaces(values[0]),
'f': True if values[1] == 1 else False,
'a': True
}
if values[2] == 1:
question['t'] = 'c'
valid_values = question['v'] = []
for j in range(3, len(values), 2):
if not pandas.isna(values[j]) and not pandas.isna(values[j+1]):
d = {
'v': int(values[j]),
'd': remove_spaces(values[j+1])
}
valid_values.append(d)
elif values[2] == 2:
question['t'] = 'm',
valid_values = question['v'] = []
for j in range(3, len(values)):
if not pandas.isna(values[j]):
valid_values.append(remove_spaces(values[j])),
else:
question['t'] = 't'
question['v'] = None
index += 1
questions.append(question)
with open('out_q.json', 'w', encoding='utf8') as f:
json.dump(questions, f, indent=2, sort_keys=True, ensure_ascii=False)
print('Done')
if __name__ == '__main__':
main()
|
2da888a7d82a23ff3b81bcf5a977f46f16fc6991 | sky-dream/LeetCodeProblemsStudy | /[0212][Hard][Word_Search_II]/Word_Search_II.py | 1,499 | 3.640625 | 4 | # https://leetcode.com/problems/word-search-ii/discuss/59804/27-lines-uses-complex-numbers
# leetcode time cost : 444 ms
# leetcode memory cost : 43.4 MB
class Solution:
# def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
def findWords(self, board, words):
root = {}
for word in words:
node = root
for c in word:
node = node.setdefault(c, {})
# d.setdefault() return the same as d.get(),but a little fast and can handle not exist key.
node[None] = True
board = {i + 1j*j: c
for i, row in enumerate(board)
for j, c in enumerate(row)}
found = []
def search(node, z, word):
if node.pop(None, None):
found.append(word)
c = board.get(z)
if c in node:
board[z] = None
for k in range(4):
search(node[c], z + 1j**k, word + c)
board[z] = c
for z in board:
search(root, z, '')
return found
def main():
board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]]
words = ["oath","pea","eat","rain"] #expect is ["oath","eat"]
obj = Solution()
result = obj.findWords(board, words)
assert result == ["oath","eat"], ["hint: result is wrong"]
print("return result is :",result)
if __name__ =='__main__':
main() |
5486fc3f02d8baddccf6a44e76345850668e6b0a | fanxinwei/Problem_Solving_with_Algorithms_and_Data_Structures | /Chapter2/test.py | 249 | 3.609375 | 4 | # listA = [1,2,3,4,5]
# print (listA)
# listA.pop(0)
# print (listA)
# d = dict(zip(list(range(10)), list(range(40, 50))))
# print(d[1])
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 }
for i in range(4):
for one in d:
print(one) |
cf469cd1bcfceea12e2f07f2a200985a6140d975 | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/lnsjoh002/question3.py | 870 | 3.859375 | 4 |
message = input("Enter the message: \n")
repeat = eval(input("Enter the message repeat count: \n"))
thickness = eval(input("Enter the frame thickness: \n"))
num_dash = len(message) + (2* thickness)
for i in range(thickness):
print('|' * i , end="")
print('+', end='')
print('-' * num_dash , end='')
print('+' , end="")
print('|' * i)
num_dash -=2
gap =" "
for i in range(repeat):
print('|' * thickness, end="")
print(gap, message, gap, sep="", end="")
print('|' * thickness)
num_dash2 = len(message)+2
upright = thickness -1
for i in range(thickness):
print('|' * (upright), end="")
print('+', end='')
print('-' * num_dash2 ,end="")
print('+', end="")
print('|' * upright)
upright-=1
num_dash2 +=2
|
3a8094d1c1a58bec07a3ce6a3bef98b4c26a3559 | jlarson497/Lab1 | /GuessingGame.py | 737 | 4.28125 | 4 | from random import randrange
#This program generates a number between 1 and 10, and has the user guess what it is until they get it right on
rand = randrange(0,10) #random int generated
guess = int(input("Guess a number between 0 and 10: ")) #integer input from user
answerCorrect = False #boolean for controlling the while loop
while answerCorrect == False: #loop goes on until the user gets the answer right, at which point the boolean
if guess > rand: #becomes true and stops the loop
print("Too High!")
guess = int(input("Try again: "))
if guess < rand:
print("Too Low!")
guess = int(input("Try again: "))
else:
answerCorrect = True
print("Right on!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.