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 |
|---|---|---|---|---|---|---|
5fe617888604e6f055a33366111e42bc9dd0a5f9 | JuanSebastianOG/Analisis-Numerico | /Talleres/PrimerCorte/PrimerTaller/Ejercicio13.py | 611 | 3.9375 | 4 | #Algoritmo que permite calcular una aproximaciรณn a la raiz n-esima de un nรบmero
def raizN( n, N, x ):
tol = 10e-8
it = 0
xn = 1
while abs(xn) > tol:
it = it + 1
xn = ((N / (x ** (n - 1))) - x ) / n
x = x + xn
print("La raiz", n, "-esima del numero", N, "es aproximadamente", x)
print("Se tuvieron un total de:", it, "iteraciones. ")
if __name__ == "__main__":
N = float(input("Digite un numero. "))
n = float(input("Digite el valor de la raiz a calcular. "))
x = float(input("Digite un valor inicial. "))
raizN( n, N, x )
|
b5a229b2ab30b0efc4c2718be4ac8f4d99742b55 | innovationcode/Sorting | /project/iterative_sorting.py | 1,975 | 4.34375 | 4 | # Complete the selection_sort() function below in class with your instructor
def selection_sort( arr ):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for j in range(cur_index, len(arr)):
if arr[j] < arr[smallest_index]:
smallest_index = j
# TO-DO: swap
arr[smallest_index], arr[cur_index] = arr[cur_index], arr[smallest_index]
return arr
print("Selection_sort : {}".format(selection_sort([5,7,3,2,1,8,5,12,15])))
# TO-DO: implement the Insertion Sort function below
def insertion_sort( arr ):
if len(arr) == 0:
return arr
for i in range(len(arr)):
j = i + 1
for j in range(len(arr)):
if arr[i] < arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
print("Insertion_sort : {}".format(insertion_sort([3,4,2,1,5,0])))
# STRETCH: implement the Bubble Sort function below
def bubble_sort( arr ):
if len(arr) == 0:
return arr
for i in range(len(arr)):
for j in range(len(arr) - 1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
print("Bubble_sort : {}".format(bubble_sort([3,4,2,1,5,0])))
# STRETCH: implement the Count Sort function below
def count_sort( arr, maximum=-1 ):
if len(arr) == 0:
return arr
counter = [0] * (max(arr) + 1)
#print(counter)
for i in arr:
if arr[i] >=0:
counter[i] += 1
#print(counter)
else:
return "Error, negative numbers not allowed in Count Sort"
k = 0
for i in range( len( counter ) ):
while 0 < counter[i]:
arr[k] = i
k += 1
counter[i] -= 1
return arr
print("Count_sort : {}".format(count_sort([1,0,4,3,2,1,4,3,2,4,3,4,4])))
|
27b5953e8b4dff1c7d41c461d5b74a9623761fdc | Roderich25/mac | /design-patterns/poultry.py | 777 | 3.578125 | 4 | class Duck:
def quack(self):
print("Quack")
def fly(self):
print("I'm flying")
class Turkey:
def gobble(self):
print("Gobble gobble")
def fly(self):
print("I'm flying a short distance")
class TurkeyAdapter:
def __init__(self, adaptee):
self.adaptee = adaptee
def quack(self):
self.adaptee.gobble()
def fly(self):
for _ in range(5):
self.adaptee.fly()
def duck_interaction(duck):
duck.quack()
duck.fly()
duck = Duck()
turkey = Turkey()
turkey_adapter = TurkeyAdapter(turkey)
print("The Turkey says ...")
turkey.gobble()
turkey.fly()
print("\nThe Duck says ...")
duck_interaction(duck)
print("\nThe TurkeyAdapter says ...")
duck_interaction(turkey_adapter)
|
4366b965dc637f5beeda2bfdcdd64755782d2641 | chrisxue815/leetcode_python | /problems/test_0572_recursive_dfs.py | 1,437 | 3.578125 | 4 | import unittest
from typing import Optional
import utils
from tree import TreeNode
def height(root):
if not root:
return -1
return 1 + max(height(root.left), height(root.right))
def match(a, b):
if not a:
return not b
if not b:
return False
return a.val == b.val and match(a.left, b.left) and match(a.right, b.right)
# O(n) time. O(log(n)) space. Recursive DFS.
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
subtree_height = height(subRoot)
def dfs(curr):
if not curr:
return False, -1
left_match, left_height = dfs(curr.left)
if left_match:
return True, -1
right_match, right_height = dfs(curr.right)
if right_match:
return True, -1
curr_height = 1 + max(left_height, right_height)
if curr_height == subtree_height and match(curr, subRoot):
return True, -1
return False, curr_height
return dfs(root)[0]
class Test(unittest.TestCase):
def test(self):
utils.test(self, __file__, Solution, process_args=self.process_args)
@staticmethod
def process_args(args):
args.root = TreeNode.from_array(args.root)
args.subRoot = TreeNode.from_array(args.subRoot)
if __name__ == '__main__':
unittest.main()
|
3d90b07fdf4d813c986ddc2ca998e6ad1579faf1 | tabeatheunicorn/general_pythondebugging | /generichelpermodule/Decorators/simpledebug.py | 1,743 | 3.65625 | 4 | import functools
import time
def decorator(func):
"""Boilerplate decorator code"""
@functools.wraps(func) # this ensures that the functions metadatat is not messed up.
def wrapper_decorator(*args, **kwargs):
# Do something before
value = func(*args, **kwargs)
# Do something after
return value
return wrapper_decorator
def timer(func):
"""Print the runtime of the decorated function. """
@functools.wraps(func)
def wrapper_timer(*args, **kwargs):
start_time = time.perf_counter() # 1
value = func(*args, **kwargs)
end_time = time.perf_counter() # 2
run_time = end_time - start_time # 3
print(f"Finished {func.__name__!r} in {run_time:.4f} secs")
return value
return wrapper_timer
def call_counter(func):
"""Count how often a function is called."""
@functools.wraps(func)
def helper(*args, **kwargs):
helper.calls += 1
return func(*args, **kwargs)
helper.calls = 0
return helper
class Debugger(object):
import logging
logger = logging.getLogger(f"{__file__}.Debugger")
""" Debug a method and return it back"""
enabled = False
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
if self.enabled:
self.logger.debug(f'Entering : {self.func.__name__}')
self.logger.debug(f'args, kwargs : {args, kwargs}')
result = self.func(*args, **kwargs)
self.logger.debug(f'{self.func.__name__} returned : {result}')
return result
else:
self.logger.debug(f'Not enabled, just calling the function.')
return self.func(*args, **kwargs)
|
aada262d4ea96da6898f6282de30a72cbbd73871 | Vaild/python-learn | /learn/day_19/1_ๅ ้.py | 670 | 3.609375 | 4 | #!/usr/bin/python3
# coding = UTF-8
# code by va1id
import threading
import time
NUM = 0
lock1 = threading.Lock()
lock2 = threading.Lock()
def work1(num):
global NUM
for i in range(num):
lock1.acquire()
NUM += 1
lock1.release()
print(NUM)
def work2(num):
global NUM
for i in range(num):
lock1.acquire()
NUM += 1
lock1.release()
print(NUM)
if __name__ == '__main__':
x = threading.Thread(target=work1, args=(1000000, ))
x.start()
y = threading.Thread(target=work2, args=(1000000, ))
y.start()
x.join()
y.join()
while len(threading.enumerate()) != 1:
print(NUM) |
3baef6e68bb38bd39dddee92d9a667cae7c37e13 | lazyxu/pythonvm | /tests/dict.py | 64 | 3.546875 | 4 | d = {1: "hello", "world": 2}
print d
print d[1]
print d["world"] |
b4ca0ad1b04bf810e24a05b5cbbf57ff3546985a | kirane61/letsUpgrade | /Day4/Day4Assignmnet.py | 725 | 4.1875 | 4 | # Assignmnet for Day 4
# You all are pilots, you have to land a plane, the altitude required for landing a plane is 1000ft,
# if it is less than that tell pilot to land the plane, or it is more than that less than 5000ft ask the pilot to "come down to 1000ft",
# else if it is more than 5000ft ask the pilot to "go around and try later"
# Example : Input - 1000
# Output - Safe to land
#Example : Input - 4500
# Output - Bring down to 1000
#Example : Input - 6500
# Output - Turn Around
altitude = int(input("Enter the altitude of the plane: "))
if altitude <= 1000:
print("Safe to land")
elif altitude >1000 and altitude <=5000:
print("Bring down to 1000 ft")
elif altitude > 5000:
print("Turn Around")
|
56021e5ab57897b6dd942de4f78bf29c0a3ed81c | stefanonu/Python | /Lab5/Lab5Package/Addition.py | 201 | 3.65625 | 4 | def addition(list):
c=1;
for iterator in list:
c=c+iterator
return c
def additionWithParam(number,list):
c=1;
for iterator in list:
c=c+iterator+number
return c |
8360a27e23aebf55d63fbb9bd0d17067921f19f7 | gsiegman/Tic-Tac-Toe | /tic_tac_toe.py | 2,955 | 3.984375 | 4 | class Player(object):
"""
A Tic-Tac-Toe Player
"""
SYMBOLS = ('X', 'O',)
PLAYER_TYPES = ('human', 'computer',)
def __init__(self, symbol, player_type, game):
if symbol not in self.SYMBOLS:
# better validation could be done to
# ensure uniqueness to other player
raise Exception(
"Invalid game symbol, must be 'X' or 'O'."
)
self.symbol = symbol
if player_type not in self.PLAYER_TYPES:
raise Exception(
"Invalid player type, must be 'human' or 'computer'"
)
self.player_type = player_type
self.game = game
def play(self):
getattr(self, '%s_play' % self.player_type)()
def human_play(self):
while True:
play_spot = raw_input("Please enter your move: ")
if self.game.is_valid_play(play_spot):
self.game.board[self.game.board.index(play_spot)] = self.symbol
self.game.display_board()
break
else:
self.game.display_board()
def computer_play(self):
print 'computer played'
class Game(object):
"""
A Game of Tic-Tac-Toe
"""
WINNING_COMBINATIONS = [
[0, 1, 2], [3, 4, 5],
[6, 7, 8], [0, 3, 6],
[1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6],
]
def __init__(self):
self.board = [
'1', '2', '3',
'4', '5', '6',
'7', '8', '9'
]
#used as game terminator
#even if there isn't a winner
self.valid_moves_count = 0
def display_board(self):
rows = [self.board[0:3], self.board[3:6], self.board[6:9]]
for row in rows:
print ' '.join(row)
def is_valid_play(self, play_spot):
if str(play_spot) not in self.board:
print 'Invalid play, please select another spot.'
return False
self.valid_moves_count += 1
return True
def has_winner(self):
for combo in self.WINNING_COMBINATIONS:
if self.board[combo[0]] == self.board[combo[1]] == self.board[combo[2]]:
print 'Player with "%s" wins!' % self.board[combo[0]]
return True
def is_game_over(self):
# need to add check for winning condition when
# completed.
return self.has_winner() or self.valid_moves_count == 9
def play():
"""
Runs the game loop
"""
game = Game()
game.display_board()
player_1 = Player('X', 'human', game)
player_2 = Player('O', 'human', game)
while 1:
player_1.play()
if game.is_game_over():
break
player_2.play()
if game.is_game_over():
break
if __name__ == "__main__":
play()
|
d1623519ab0638ca54ff7dff7f97787aee87151d | L16H7/coding_bootcamp_algo_data_structure_python | /Sprial_matrix.py | 350 | 3.953125 | 4 | def spiral_matrix(size):
number = 0
matrix = [[0]*3 for i in range(size)]
for row in range(size):
for col in range(size):
if col
print(row,col)
matrix[row][col] = number + 1
col += 1
return matrix
if __name__ == '__main__':
n_matrix = 3
print(spiral_matrix(n_matrix)) |
3bcfe608f3ec275aca13670a487320dc19205989 | ievagaj/ED-D4-DIAMOND | /main.py | 529 | 4.09375 | 4 | row = int(input("Enter the number of rows:"))
for i in range(row):
print(" "*(row-i) + " *" *(i+1))
for j in range(row-1):
print(" "* (j+2) + " *"* (row-1-j))
row = int(input("Enter the number of rows:"))
for i in range(row):
print(" "*(row-i-1) + " *"*(i+1))
for j in range(row-1,0,-1):
print(" "*(row-j) + " *"*(j))
for row in range(6):
for col in range(7):
if (row==0 and col%3!=0) or (row==1 and col%3==0) or (row-col==2) or (row+col==8):
print("*", end="")
else:
print(" ", end="")
print() |
80ef4106ab61798ced52bb1258d45bfa4918a0cf | IvanFekete/fatic-dialogue | /dialog.py | 2,499 | 3.53125 | 4 | import random
#download information will be used from files
commonQuestions = []
commonAnswers = []
questionsWithPattern = []
answersWithPattern = []
invitePhrases = []
byePhrases = []
words = []
isQuestion = lambda sentence: sentence.find("?") != -1
containsPattern = lambda sentence: sentence.find("*") != -1
def downloadPatterns(filename) :
f = open(filename, "r")
for text in f:
if isQuestion(text):
if containsPattern(text) :
questionsWithPattern.append(text[:-1])
else :
commonQuestions.append(text[:-1])
else :
if containsPattern(text) :
answersWithPattern.append(text[:-1])
else :
commonAnswers.append(text[:-1])
f.close()
def downloadWords(filename) :
f = open(filename, "r")
for x in f:
words.append(x[:-1])
f.close()
random.shuffle(words)
def downloadInvitePhrases(filename) :
f = open(filename, "r")
for x in f:
invitePhrases.append(x[:-1])
f.close()
def downloadByePhrases(filename) :
f = open(filename, "r")
for x in f:
byePhrases.append(x[:-1])
f.close()
def init():
downloadWords("nouns.txt")
downloadPatterns("patterns.txt")
downloadInvitePhrases("hello.txt")
downloadByePhrases("bye.txt")
#answer algorithms
def findWordWithMaximalOccurencesNumber(text):
result = ""
resultCount = 0
for word in words:
count = text.count(word)
if count != 0 and resultCount < count:
resultCount = count
result = word
return result
lastAnswer = ""
def getCommonAnswer(common):
answer = random.choice(common)
while answer == lastAnswer :
answer = random.choice(common)
return answer
def match(text, common, withPatterns):
answer = ""
keyword = findWordWithMaximalOccurencesNumber(text)
if keyword == "" or random.randint(0, 10) < 3:
return getCommonAnswer(common)
else :
return random.choice(withPatterns).replace("*", keyword)
isInvitePhrase = lambda s: s.lower().find("hello") != -1 or s.lower().find("hi") != -1 or s.lower().find("hey") != -1
def response(text):
if lastAnswer == "" and isInvitePhrase(text) :
return random.choice(invitePhrases)
if text.lower().find("bye") != -1:
return random.choice(byePhrases)
if isQuestion(text):
return match(text, commonAnswers, answersWithPattern)
else:
return match(text, commonQuestions, questionsWithPattern)
init()
print(len(words))
print("Hello, Biba, lets talk! Enter what you want to say below.")
while lastAnswer.lower().find("bye") == -1:
s = input("Biba:")
answer = response(s)
print("Boba: " + answer)
lastAnswer = answer
|
61c5272ceaff822a23f81dda8a4bb30f20c5efc6 | eneopetoku/Learning-Python | /continue example 2.py | 124 | 3.875 | 4 | var=10
while var>0:
var=var-1
if var ==5:
continue
print('Current value :',var)
print('See you again')
|
e70e383871978f0dd9ca6b82091f5d474e3ea3f0 | Enhory/practicas | /programacion2/ejercicio2_Operadores/ejercicio02.py | 177 | 3.78125 | 4 | cadena = input("Escribe tu Nombre: ")
r = len(cadena)
print("Longitud: ", r)
print("ยฟLa longitud de tu nombre es mayor o igual que 3 y menor que 10?: ", r >= 3 and r < 10)
|
e9228fcc3fda45bb6cdede77736e895eec7a003a | kaka0525/Leet-code-practice | /shortestWordDistance.py | 901 | 4.28125 | 4 | def shortest_word_distance(l, word1, word2):
"""
Given a list of words and two words word1 and word2, return the shortest
distance between these two words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = "coding", word2 = "practice", return 3.
Given word1 = "makes", word2 = "coding", return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are
both in the list.
"""
difference = []
word1_idx = [i for i, j in enumerate(l) if j == word1]
word2_idx = [i for i, j in enumerate(l) if j == word2]
for i in word1_idx:
for j in word2_idx:
difference.append(abs(i - j))
return min(difference)
shortest_word_distance(l=["practice", "makes", "perfect", "coding", "makes"],
word1="makes", word2="coding")
|
cd720b18aafd5ab8de8f5a972d920eab6fe6ed78 | vedantvajre/Day8-and-Day9-Homework | /9.8.py | 1,552 | 3.78125 | 4 | class User():
def __init__(self, first_name, last_name, password, username, email):
self.first_name = first_name
self.last_name = last_name
self.password = password
self.username = username
self.email = email
def describe_user(self):
print("First name: " + self.first_name, 'Last name: ' + self.last_name, 'Password: ' + self.password, 'Username: ' + self.username, 'Email ID: ' + self.email)
def greet_user(self):
print("Hello " + self.first_name.title() + " " + self.last_name.title() + ". Welcome to " + self.username.title() + "'s profile!")
class Admin(User):
def __init__(self, first_name, last_name, password, username, email):
super().__init__(first_name, last_name, password, username, email)
self.privileges = Privileges()
class Privileges():
def __init__(self, privileges=[]):
self.privileges = privileges
def show_privileges(self):
print("\nPrivileges:")
if self.privileges:
for privilege in self.privileges:
print("- " + privilege)
else:
print("")
user1 = Admin('Vedant', 'Vajre', 'coolbeans1234', 'VedantVajre', 'vedantvajre@gmail.com')
user1.describe_user()
user1.privileges.show_privileges()
print("\nAdding privileges:")
eric_privileges = [
'can reset passwords',
'can moderate discussions',
'can suspend accounts',
]
user1.privileges.privileges = eric_privileges
user1.privileges.show_privileges() |
9f223e8369f38a15f71daa20cacb6eaf431d46e7 | chriszhuu/Imaginary-Bus-Network | /bus system1/bus.py | 1,082 | 3.859375 | 4 | class Bus(object):
num = 0
all = [] # list of all objects in Bus
def __init__(self, route):
self.ID = Bus.num
self.route = route # bus route is a list with 3 items
self.origin = route[0] # bus origin is the first item in the list
self.destination = route[1:] # bus destinations are the remaining items
self.curCap = 0 # current capacity
self.capacity = 3
Bus.num = Bus.num + 1
Bus.all.append(self)
self.curLoc = None # current location
def getRoute(self):
return self.route
def getID(self):
return self.ID
def setCapacity(self,num):
self.capacity = num
def __str__(self):
return "Route "+str(self.getID())+" bus starts from "+self.route[0]\
+", goes to "+self.route[1]+" and "+self.route[2]
def isFull(self):
if self.curCap == self.capacity:
return True
else:
return False
def locate(self):
return self.curLoc
def passengerCount(self):
return self.curCap
|
aba4c6d2b2ce1ae970317d7a2a4b1d030859cfb6 | vijeeshtp/python22 | /dict4.py | 1,208 | 3.609375 | 4 | data = {
"123" : {
"name" : "anand",
"marks" : {
"sem1" : {
"sub1" :1,
"sub2" :2,
"sub3" :3
},
"sem2" : {
"sub1" :1,
"sub2" :2,
"sub3" :3
},
"sem3" : {
"sub1" :1,
"sub2" :2,
"sub3" :3
}
}
},
"456": {
"name": "seetha",
"marks": {
"sem1": {
"sub1": 2,
"sub2": 2,
"sub3": 2
},
"sem2": {
"sub1": 3,
"sub2": 3,
"sub3": 3
},
"sem3": {
"sub1": 4,
"sub2": 4,
"sub3": 4
}
}
}
}
print (data)
for rollno, details in data.items ():
marks = details ["marks"]
totalMark = 0
for sem, subjects in marks.items () :
semTotal =0
for sub, mark in subjects.items():
semTotal = semTotal+ mark
totalMark = totalMark + semTotal
print (rollno, details["name"], totalMark)
|
3989074ae61a266750f3532f18d120494a7d09ea | GabriellAlmeidaa/Python_UNIESI | /NP1/Equaรงรฃo_de_segundo_grau.py | 305 | 3.734375 | 4 | a = float(input('Insira o valor de A: '))
b = float(input('Insira o valor de B: '))
c = float(input('Insira o valor de C: '))
delta = b**2 - 4*a*c
print ('Delta = ', delta)
rdel = delta**0.5
print ('Raiz de delta = ', rdel)
x1 = (-b+rdel)/(2*a)
x2 = (-b-rdel)/(2*a)
print ('x1 = ', x1)
print ('x2 = ', x2) |
8939527185f38ab89bbd7dfe7c2125b03b61493c | shahnwaz123/python-exam-prepration-edyoda- | /FOR LOOP & WHILE LOOP.py | 1,525 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # FOR LOOP & WHILE LOOP
# In[8]:
# Example:Lets try iterating for loop with list-
# In[9]:
list1= ['harry','marry','larry']
for item in list1:
print(item)
# In[ ]:
# Lets try to iteratting for loopwith tuple-
# In[10]:
list2= ('harry','marry','larry')
for item in list2:
print(item)
# In[11]:
# but we cannot iterate all data type like list and tuple.
# In[12]:
# Lets have a another iteration with list.
# In[14]:
list3= [['harry',15],['marry',45],['larry',35]]
for item ,lollypop in list3:
print(item,'number of lollypop',lollypop)
# In[16]:
# lets typecaste with dictonary and use for loop in it-
# In[17]:
list3= [['harry',15],['marry',45],['larry',35]]
dict1=dict(list3)
print(dict1)
# In[ ]:
# in dict you have to use [.items()] fuction to iterate for loop:
# example-
# In[33]:
dict2={'harry': 15, 'marry': 45, 'larry': 35}
for item in dict2:
print(item)
# In[30]:
dict2={'harry': 15, 'marry': 45, 'larry': 35}
for item,lollypop in dict2.items():
print(item,'number of lollypop',lollypop)
# In[ ]:
# make a list with random name and numeric value and should print numeric value graeter than 6.
# In[58]:
list6=['harry',22,33,'rohan',78,5,4,'manoj']
for item in list6:
if str(item).isnumeric() and item>=6:
print(item)
# # WHILE LOOP
# In[59]:
# while loop run untile condition is satisfied-
# In[60]:
# Example-
# In[66]:
i=0
while (i<=20):
print(i)
i=i+1
# In[ ]:
|
5bb5f1c88dcb8ca4d3c1a86762aa922619182850 | josejpalacios/codecademy-flask | /Module 01: Introduction to Flask/Lesson 02: Build Your First Flask App/Exercise 06: Review.py | 776 | 3.609375 | 4 | # Learned:
# - Import Flask class
# - Create Flask application object
# - Create routes for handling requests from different URLs
# - Create variable rules to handle dynamic URLS
from flask import Flask
app = Flask(__name__)
@app.route('/')
@app.route('/home')
def home():
return '<h1>Hello, World!</h1>'
@app.route('/reporter/<int:reporter_id>')
def reporter(reporter_id):
return f'''
<h2>Reporter {reporter_id} Bio</h2>
<a href="/">Return to home page</a>
'''
# Create third view function. Add <article_name> to URL path
@app.route('/article/<article_name>')
# Add article_name to article function
def article(article_name):
return """
<h2>{article_name.replace('-', ' ').title()}</h2>
<a href="/">Return back to home page</a>
"""
|
23df2c764181c0858befc52b0fd395674dfbd59a | shuzhancnjx/leetcode- | /Programming-Algorithm/Max Points on a Line.py | 1,668 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 31 09:54:33 2015
@author: ZSHU
"""
# Definition for a point.
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Solution:
# @param {Point[]} points
# @return {integer}
def maxPoints(self, points):
if len(points)<=2:
return len(points)
else:
maxpoints=0
for i in range(len(points)-1):
dic={}
repeated=0
for j in range(i+1,len(points)):
if points[i].x==points[j].x and points[i].y==points[j].y:
if repeated==0: repeated+=2
else: repeated+=1
else:
if (float(points[i].x-points[j].x))==0:
slope=str(points[i].x)+'xline'
elif (float(points[i].y-points[j].y))==0:
slope=str(points[i].y)+'yline'
else:
slope=(float(points[i].y-points[j].y))/(float(points[i].x-points[j].x))
dic[slope]=dic.get(slope,1)+1
if len(dic)>0 and repeated>0 and max(dic.values())+repeated-1>maxpoints:
maxpoints=max(dic.values())+repeated-1
elif len(dic)>0 and repeated==0 and max(dic.values())>maxpoints:
maxpoints=max(dic.values())
elif len(dic)==0 and repeated>maxpoints:
maxpoints=repeated
else:
continue
return maxpoints
|
2b84d7054bd23a14734558c3276e90ab36ae84a3 | ashish3x3/competitive-programming-python | /Hackerrank/Algorithms/Strings/finding_no_of_common_character_in_all_substring.py | 663 | 3.671875 | 4 |
# https://www.hackerrank.com/challenges/gem-stones/problem
import sys
from collections import defaultdict
def gemstones(arr):
mp = defaultdict(list)
for i in xrange(len(arr)):
for j in arr[i]:
if j not in mp:
mp[j].append(i)
elif j in mp and i not in mp[j]:
mp[j].append(i)
cnt = 0
for k,v in mp.iteritems():
if len(v) == len(arr):
cnt+=1
return cnt
n = int(raw_input().strip())
arr = []
arr_i = 0
for arr_i in xrange(n):
arr_t = str(raw_input().strip())
arr.append(arr_t)
result = gemstones(arr)
print(result)
|
bf79472a4d45b131914940fb4cefaadc79031951 | HenleyChiu2/HackerRank-Solutions-Python | /Problem Solving/Plus_Minus.py | 636 | 3.671875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr):
pos_count = 0
neg_count = 0
zero_count = 0
for num in arr:
if num > 0:
pos_count += 1
elif num == 0:
zero_count += 1
else:
neg_count += 1
print("%.6f" % (pos_count / len(arr)))
print("%.6f" % (neg_count / len(arr)))
print("%.6f" % (zero_count / len(arr)))
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr) |
05163253b930fae1fdcb88df0d0fd9555da19d5f | beppe2hd/Explainable_AI_investigation | /single_pred.py | 2,017 | 3.6875 | 4 | '''
The code allow the user to test single features vector in the validation dataset
It takes as input the row of the features vector of interest in the validation dataset
It returns the analyzed vector and plots the corresponding plot
'''
import sys
import pandas as pd
import numpy as np
from sklearn import preprocessing
import matplotlib.pyplot as plt
import keras.utils
import innvestigate
import innvestigate.utils as iutils
# Get the csv file and load it as pandas data frame
def get_data(val_data_path):
val = pd.read_csv(val_data_path)
return val
# The pandas data frame for validation is splitted in "data" and "ground truth"
# moreover the csv head is removed. The data are scaled between 0 and 1.
def get_combined_data(val_data_path):
val = pd.read_csv(val_data_path)
# The Ground truth of validation dataset is dropped
# and stored in the variable valGT
valGT = val.Class
val.drop(['Class'], axis=1, inplace=True)
# Data vector for train and validation are scaled between 0 and 1
# and structured as Pandas Data Frame
val = val.values # returns a numpy array
min_max_scaler_test = preprocessing.MinMaxScaler()
val = min_max_scaler_test.fit_transform(val)
val = pd.DataFrame(val)
return val, valGT
# The dataset (both val and test) are preprocessed and
val, valGT = get_combined_data('myval.csv')
if len(sys.argv)==2:
row_num = int(sys.argv[1])
if row_num < len(valGT):
print("I'll try test the row #: ", row_num)
else:
print("Row is out of index")
sys.exit(1)
else:
print("Wrong number of arguments")
sys.exit(1)
model = keras.models.load_model("model_cc")
# Stripping the softmax activation from the model
model_wo_sm = iutils.keras.graph.model_wo_softmax(model)
# Creating an analyzer
gradient_analyzer = innvestigate.analyzer.Gradient(model_wo_sm)
# Applying the analyzer
analysis = gradient_analyzer.analyze(val.loc[[row_num]])
print(analysis)
plt.plot(analysis[0])
plt.show()
|
9d918db516e620732d9453c407cd9915b1fc2a54 | madeibao/PythonAlgorithm | /PartB/pyๆฏๅฆๅญๅจ้ๅค็ๅ
็ด .py | 534 | 3.640625 | 4 |
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
d={}
for ix,num in enumerate(nums):
if num not in d:
d[num]=ix
# ๅฆๆๅทฒ็ปๅญๅจไบ่ฟไธชๅ
็ด ็่ฏ๏ผๅฐฑๅญๅ
ธ็ๆไฝใ
else:
if ix-d[num]<=k:
return True
else:
d[num]=ix
return False
if __name__ == "__main__":
s = Solution()
nums = [1,2,3,1]
k = 3
print(s.containsNearbyDuplicate(nums, k))
|
7b6c36767fa4e1edfbf6218175d1545e3bcaceb2 | WesGtoX/Intro-Computer-Science-with-Python-Part02 | /Week2/Tarefa 02/Exercicio_02_ordem_lexicografica.py | 917 | 3.671875 | 4 | def primeiro_lex(lista):
lexico = ''
i = 0
for palavra in lista:
if lexico == '':
lexico = palavra
else:
if ord(palavra[i]) < ord(lexico[i]):
lexico = palavra
elif ord(palavra[i]) == ord(lexico[i]):
letra_igual(palavra, lexico, i+1)
return lexico
def letra_igual(palavra, lexico, i):
if ord(palavra[i]) == ord(primeiro_lex[i]):
letra_igual(palavra, primeiro_lex, i+1)
else:
lexico = palavra
return lexico
# def test_primeiro_lex0():
# assert primeiro_lex(['oฤบรก', 'A', 'a', 'casa']) == 'A'
#
#
# def test_primeiro_lex1():
# assert primeiro_lex(['AAAAAA', 'b']) == 'AAAAAA'
#
#
# def test_primeiro_lex2():
# assert primeiro_lex(['ola', 'rrrrrrr', 'olo' 'qqq', 'zcasa']) == 'ola'
#
#
# def test_primeiro_lex3():
# assert primeiro_lex(['AAAAAA', 'AAAB' 'b']) == 'AAAAAA'
|
c1016735f558ecab91be457a742f1267b3144f96 | jy100aaa/tictactoe | /tictactoe.py | 4,514 | 3.84375 | 4 | import sys
import os
"""
python 2.7 compatible code
"""
def str_to_int(val):
try:
return int(val)
except Exception as e:
return ''
def main(argv=sys.argv):
os.system('cls' if os.name == 'nt' else 'clear')
turn = 1
while True:
print 'Enter board size (NxN): '
sys.stdout.write('>> ')
board_size = raw_input()
board_size = str_to_int(board_size)
if type(board_size) is int and board_size >= 3:
tic_tac_toe = TicTacToe(board_size)
break
while True:
print 'Enter name for Player 1:'
sys.stdout.write('>> ')
player_1 = raw_input()
if len(player_1) > 0:
break
while True:
print 'Enter name for Player 2:'
sys.stdout.write('>> ')
player_2 = raw_input()
if len(player_2) > 0:
break
while True:
while True:
tic_tac_toe.printArr()
if turn == 1:
print player_1 + ', choose a box to place an "O" into:'
else:
print player_2 + ', choose a box to place an "X" into:'
sys.stdout.write('>> ')
value = raw_input()
value = str_to_int(value)
if type(value) is int:
if tic_tac_toe.place(turn, value) is True:
turn = -1 if turn == 1 else 1
break
result = tic_tac_toe.determine()
if result != 0:
tic_tac_toe.printArr()
if result == 1 or result == 2:
winner = player_1 if result == 1 else player_2
print 'Congraturations ' + winner + ' ! You have won'
elif result == 3:
print 'Draw!'
break
return
class TicTacToe():
def __init__(self, size):
self.arr_size = size
self.arr = []
for x in xrange(size):
self.arr.append([0] * size)
def place(self, turn, value):
if type(value) is not int:
return False
if value < 0 or value > pow(2, self.arr_size):
return False
col = (value - 1) / self.arr_size
row = (value - 1) % self.arr_size
if self.arr[col][row] != 0:
return False
else:
self.arr[col][row] = turn
return True
def printArr(self):
os.system('cls' if os.name == 'nt' else 'clear')
print ' '
for x in xrange(self.arr_size):
txt = ''
for y in xrange(self.arr_size):
val = (self.arr_size * x) + y + 1
if self.arr[x][y] == 0:
txt += str(val).center(8)
elif self.arr[x][y] == -1:
txt += 'X'.center(8)
else:
txt += 'O'.center(8)
if y < self.arr_size - 1:
txt += '|'
print txt
print '-' * len(txt)
print ' '
"""
determining game with a brute force approach
return value
0: not done
1: player 1 won
2: player 2 won
3: draw
"""
def determine(self):
completed = True
for x in xrange(self.arr_size):
for y in xrange(self.arr_size):
if self.arr[x][y] == 0:
completed = False
continue
if x + 2 < self.arr_size and y + 2 < self.arr_size:
new_arr = []
for t in self.arr[x:x+3]:
new_arr.append(t[y:y+3])
result = self.check(new_arr)
if result == 1 or result == 2:
return result
return 0 if not completed else 3
def check(self, arr):
# horizontal check
for x in arr:
if sum(x) == -3:
return 2
elif sum(x) == 3:
return 1
# vertical check
for x in range(3):
summ = 0
for y in range(3):
summ += arr[y][x]
if summ == -3:
return 2
elif summ == 3:
return 1
# diagonal check
axe1 = arr[0][0] + arr[1][1] + arr[2][2]
axe2 = arr[0][2] + arr[1][1] + arr[2][0]
if axe1 == -3 or axe2 == -3:
return 2
elif axe1 == 3 or axe2 == 3:
return 1
return 0
if __name__ == '__main__':
main()
|
57a35fa4e182974a46aa439d387f6390b2ecddfe | kimi9527/chess-yi | /chess/chess_piece.py | 2,256 | 3.828125 | 4 | # coding=utf-8
MAX_X = 8
MAX_Y = 9
class ChessPiece(object):
"""
ๆฃๅญ็ฑป
"""
def __init__(self, x: int, y: int, is_red: bool, is_north: bool):
self._x = x
self._y = y
self._is_red = is_red # ๆฏๅฆ็บขๆน
self._is_north = is_north # ๆฏๅฆๅๆน
@property
def is_red(self):
"""
get is red
"""
return self._is_red
@property
def is_north(self):
"""
get is north
"""
return self._is_north
@property
def image(self):
"""
่ทๅๆฃๅญ็ฑปๅพๅ
"""
raise NotImplementedError
@property
def xy(self):
"""
get xy
"""
return self._x, self._y
def can_move(self, pieces: dict, dx: int, dy: int):
"""
can move
"""
if abs(dx) + abs(dy) == 0:
return False
new_x = self._x + dx
new_y = self._y + dy
# ่พน็ๆฃๆต
if new_x < 0 or new_x > MAX_X:
return False
if new_y < 0 or new_y > MAX_Y:
return False
if ((new_x, new_y) in pieces and
(pieces[new_x, new_y].is_red == self.is_red)):
return False
return True
def counts(self, pieces: dict, dx: int, dy: int):
"""
่ฎก็ฎ x๏ผx+dxไน้ด็ๆฃๅญ
่ฎก็ฎ y, y+dyไน้ด็ๆฃๅญ
"""
sx = 0
sy = 0
if dx != 0:
if dx > 0:
sx = 1
else:
sx = -1
if dy != 0:
if dy > 0:
sy = 1
else:
sy = -1
x = self._x + sx
y = self._y + sy
new_x = self._x + dx
new_y = self._y + dy
res = 0
while x != new_x or y != new_y:
if (x, y) in pieces:
res += 1
x += sx
y += sy
return res
def get_moves(self, pieces: dict):
"""
่ทๅๆๆ่ฝ็งปๅจ็ไฝ็ฝฎ
"""
raise NotImplementedError
def move(self, dx: int, dy: int):
"""
็งปๅจๆฃๅญ๏ผ็งปๅจๅๅบ่ฏฅ็กฎ่ฎค่ฝๅค็งปๅจ
"""
self._x += dx
self._y += dy
|
7fe63b361147d407ce9209bdb3b76612d87dcfbc | Nihileshnatarajan/Class-12-Practicals | /Practicals/4.py | 867 | 4.0625 | 4 | ID = ['ABC','DEF','GHI'] #list containing the bike ID's in string
OUT = [9.55,10.11,10.23] #list containing the time the bike was taken in float
def add_bike():
bikeId = input("Enter bikeID ")
if bikeId == 'ZZZ':
print('Goodbye, Have a nice day')
raise SystemExit
ID.append(bikeId)
OUT.append(float(input("Enter the time ")))
return f'Bike {bikeId} added'
def bike():
Id = input('enter bikeID : ')
if Id not in ID:
return 'Error, BIKEID NOT FOUND'
OUT_time = OUT[ID.index(Id)]
curr_time = float(input('enter the current time : '))
return f'Time difference : {curr_time - OUT_time}'
while True:
choice = input('1. Do you want to add bikes or \n2. Search Bikes (1/2) : ')
if choice == '1':
print(add_bike())
elif choice == '2':
print(bike())
|
fd6a4ae981e959c59fd94cdf09f59dc399f72d11 | vijaysawant/Python | /PatternPrinting/pattern3.py | 290 | 3.65625 | 4 | '''
input = 4
*
* *
* * *
* * * *
'''
def pattern(row):
for i in range(0,row):
for j in range(0,row):
if (i+j+1 < row):
print " \t",
else: # (i+j+1 >= row)
print "*\t",
print
if __name__ == "__main__":
row = input("Enter num of rows : ")
pattern(row) |
72139f0aabad0dd28b9e1f762243322ee6f219dc | alphawaseem/MultiUserBlog | /passwordlib.py | 1,102 | 4.375 | 4 | """
This module helps to hash passwords with random salts
"""
# Import neccessary modules
import random
from string import letters
import hashlib
def make_salt(length=5):
"""
returns a random salt of default length of 5
"""
return ''.join(random.choice(letters) for x in range(length))
def make_pw_hash(name, pw, salt=None):
"""
returns a salt and hashed value in the format %s,%salt
If salt in not given then it creates a new salt and returns
hashed value with salt. Else use that salt to generate hash this
is useful when verifying the hash with raw values.
It uses sha512 and mix of name password and salt.
"""
if not salt:
salt = make_salt()
h = hashlib.sha512(name + pw + salt).hexdigest()
return '%s,%s' % (salt, h)
def verify_pw_hash(name, password, h):
"""
returns True/False if name and password generates same given hash
which contains salt. We use this salt value to regenerate the hash
and match it with given hash.
"""
salt = h.split(',')[0]
return h == make_pw_hash(name, password, salt)
|
39c86a6a27c4d5f8ce61217a5877949ce8c158ee | SerjVankovich/BANX_parser | /take_banks.py | 1,426 | 3.625 | 4 | # The func which build dict with banks
def take_banks(array_vklads, array_cont):
banks_array = []
banks_names = get_banks_names(array_vklads)
banks_names = list(set(banks_names + get_banks_names(array_cont)))
print(banks_names)
for name in banks_names:
bank = Bank(name)
banks_array.append(bank)
for dict in array_vklads:
for key in dict.keys():
if key == 'bank':
id = banks_names.index(dict[key])
banks_array[id].len_vklads += 1
for dict in array_cont:
for key in dict.keys():
if key == 'bank':
try:
id = banks_names.index(dict[key])
banks_array[id].len_kred += 1
except ValueError:
pass
array = []
for bank in banks_array:
dict = {
'bank': bank.bank,
'len_cred': str(bank.len_kred),
'len_vklads': str(bank.len_vklads)
}
array.append(dict)
return array
def get_banks_names(array):
names = []
for dict in array:
for value in dict.values():
if dict['bank'] not in names:
names.append(dict['bank'])
return names
class Bank():
def __init__(self, bank):
self.bank = bank
self.len_kred = 0
self.len_vklads = 0
|
e93312d47abfe2cb41b45edee0101d30851b5dcf | linheimx/python_master | /fluent_python/contextmanager/mirror.py | 1,013 | 3.59375 | 4 | import sys
class LookingGlass(object):
def __enter__(self):
self.original_write = sys.stdout.write
sys.stdout.write = self.reverse_write
return "ABCDEFG"
def reverse_write(self, text):
self.original_write(text[::-1])
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.write = self.original_write
if exc_type is ZeroDivisionError:
print("Please DO NOT divide by zero!")
return True
if __name__ == "__main__":
with LookingGlass() as what:
print("Alice, Kitty and Snowdrop") # pordwonS dna yttiK ,ecilA
print(what) # GFEDCBA
print(what) # ABCDEFG
print("123456789") # pordwonS dna yttiK ,ecilA
print("-*" * 20)
manager = LookingGlass()
print(manager) # <__main__.LookingGlass object at 0x10062be80>
monster = manager.__enter__()
print(monster) # GFEDCBA
print(monster == "ABCDEFG") # eurT
manager.__exit__(None, None, None)
print(monster) # ABCDEFG |
61b0365d754a53986e3c68df82dc19b29be24b69 | CypherING/python_work | /rivers.py | 331 | 4.125 | 4 | rivers = {
'nile': 'egypt',
'hwang ho': 'china',
'indus': 'india'
}
for river, country in rivers.items():
print("The " + river.title() + " flows through " +
country.title())
print("\nRivers: ")
for river in rivers.keys():
print(river.title())
print("\nCountries: ")
for country in rivers.values():
print(country.title()) |
08580d9149ec457aac1c510aef63b8ba420c7da0 | apalala/exercism | /python/clock/clock.py | 565 | 3.640625 | 4 |
class Clock():
def __init__(self, hours, minutes):
self.minute_of_the_day = (hours * 60 + minutes) % (24 * 60)
def add(self, minutes):
return Clock(0, self.minute_of_the_day + minutes)
def _hours_and_minutes(self):
return (self.minute_of_the_day // 60, self.minute_of_the_day % 60)
def __hash__(self):
return hash(self.minute_of_the_day)
def __eq__(self, other):
return self.minute_of_the_day == other.minute_of_the_day
def __str__(self):
return '%02d:%02d' % self._hours_and_minutes()
|
d3b4a2ca5ab04d0fba293b6d070fb082d888d038 | pynoor/exercism | /pangram.py | 411 | 3.6875 | 4 | def is_pangram(sentence = "This is a sentence"):
count = 0
new = str.lower(sentence)
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n",\
"o","p","q","r","s","t","u","v","w","x","y","z"]
for x in alphabet :
if x in new :
count = count + 1
if count >= 26 :
return True
else :
return False
|
7b67fd41e42a3262007ff0a44aa211cc2512de23 | dgu12/Russian-BS | /russian.py | 14,424 | 3.640625 | 4 | # Daniel Gu
'''
This program allows the user to play a the game Russian BS versus an AI
opponent.
'''
import sys
import random
# Define some useful constants.
BELIEVE = 0
BS = 1
# Global list of ranks.
ranks = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
# Global list of aliases for cards.
dcards = ["S1", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "S10", "S11", "S12", "S13",
"C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10", "C11", "C12", "C13",
"D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D10", "D11", "D12", "D13",
"H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9", "H10", "H11", "H12", "H13",]
cstr = [str(i) for i in range(1, 53)]
# Make a dictionary of cards. We associate each card in the standard deck with
# an integer in [0, 51] according to the following mapping:
# 0 - 12: Ace - King of spades
# 13 - 25: Ace - King of clubs
# 26 - 38: Ace - King of diamonds
# 39 - 51: Ace - King of hearts
# In this mapping, the residue mod 13 gives the rank of the card (with jack as
# 11, queen as 12, king as 13), and the integer division by 13 gives the suit
# (0 is spades, 1 is clubs, 2 is diamonds, and 3 is hearts). Furthermore, the
# bottom "half" consists of black cards, whereas the top "half" consists of
# black cards.
def makeCards():
carddict = dict()
for i in range(13):
key1 = "S" + str(i)
key2 = "C" + str(i)
key3 = "D" + str(i)
key4 = "H" + str(i)
carddict[key1] = i
carddict[key2] = i + 13
carddict[key3] = i + 26
carddict[key4] = i + 39
return carddict
# PLAYER CLASS---------------------------------------------------------------//
class Player:
'''Class for a player in the game Russian BS'''
# Member variables:
# pid -> the player ID as assigned by the game.
# isAI -> flag determining whether player is AI or not.
# carddict -> a dictionary for translating cards.
# state -> dictionary holding state of game of other players
# game_state -> holds the state of the current round
# game_hist -> holds the entire history of the game so far.
# nplayers -> number of players
# Takes a list of cards and a flag for whether the player is AI or not.
def __init__(self, PID, pcards, AI, nplayers):
self.pid = PID
self.AI = AI
self.carddict = makeCards()
# Holds the knowledge of all players' cards.
self.state = dict()
for i in range(nplayers):
self.state[i] = []
self.state[PID] = pcards
self.state["out"] = []
self.game_state = []
self.game_hist = []
self.nplayers = nplayers
# AI FUNCTIONS-----------------------------------------------------------\\
# TODO: Eventually change this to a class-inheritance style system.
# Basic AI which always plays a valid move if it goes first; otherwise it
# randomly picks between "believe" and "BS".
def moveAI(self, first = False):
random.seed()
if first:
l = []
# Pick a random card and declare it correctly.
card = random.choice(self.getCards())
l.append(card)
# Get the rank of the card.
rank = card % 13
# Remove the card from our hand.
self.removeCards(self.pid, l)
return (rank, 1, card)
else:
# Return BELIEVE or BS uniformly at random.
return random.randint(0, 1)
# ACCESSORS--------------------------------------------------------------\\
# Accessor for the PID of the player.
def getPID(self):
return self.pid
# Accessor which returns the list of cards held by the player.
def getCards(self):
return self.state[self.pid]
# Get the cards which are NOT held by the player.
def getOtherCards(self):
other = []
for i in range(52):
if i not in self.state[self.pid]:
other.append(i)
return other
# Accessors which returns whether the player is an AI/
def isAI(self):
return self.AI
# MUTATORS---------------------------------------------------------------\\
# Add cards in the numeric format.
def addCards(self, pid, cards, cdict = False):
if cdict:
for card in cards:
self.state[pid].append(self.carddict[card])
else:
self.state[pid] += cards
def removeCards(self, pid, cards, cdict = False):
if cdict:
for card in cards:
if self.carddict[card] in self.state[pid]:
self.state[pid].remove(self.carddict[card])
else:
for card in cards:
if card in self.state[pid]:
self.state[pid].remove(card)
# Get the game state.
def getGameState(self, state):
self.game_state = state
# Get the game history, which is supposed to hold previous opponent
# decisions.
def getGameHistory(self, hist):
self.game_hist.append(hist)
# MOVE FUNCTIONS AND HELPERS---------------------------------------------\\
def prompt(self, rank):
print "The current rank is %s" % ranks[rank]
is_card = raw_input("Play Cards?>> ")
if is_card.strip() == "YES":
dnum = raw_input("Declared Number>> ")
actual = raw_input("Actual>> ")
translated = actual.strip().split()
while dnum not in cstr or int(dnum) != len(translated) or not self.isSubset(translated):
print "Enter a proper subset of your cards."
dnum = raw_input("Declared Number>> ")
actual = raw_input("Actual>> ")
translated = actual.strip().split()
# Remove the cards we're playing.
self.removeCards(self.pid, self.translate(actual))
# Input should be 1-indexed rank.
return (rank, int(dnum), self.translate(actual))
elif is_card.strip() == "NO":
action = raw_input("Action>> ")
while action.strip() != BELIEVE and action.strip() != BS:
print "Enter BELIEVE or BS"
action = raw_input("Action>> ")
if action.strip() == "BELIEVE":
return BELIEVE
else:
return BS
# Moves which are not "believe" or "BS" should be formatted as follows:
# ([rank] [# of cards] [list of actual cards])
# i.e. a 3-tuple of which the first element is the rank, second element is
# the number of cards played, and the third is list of the actual card.
def playMove(self, first = False, rank = None):
if first:
if self.AI:
move = self.moveAI(first = True)
else:
self.printCards()
drank = raw_input("Declared Rank>> ")
dnum = raw_input("Declared Number>> ")
actual = raw_input("Actual>> ")
translated = actual.strip().split()
while drank not in ranks or dnum not in cstr or int(dnum) != len(translated) or not self.isSubset(translated):
print "Enter a proper rank and a subset of your cards."
drank = raw_input("Declared Rank>> ")
dnum = raw_input("Declared Number")
actual = raw_input("Actual>> ")
translated = actual.strip().split()
# Remove the cards we've played.
self.removeCards(self.pid, self.translate(actual))
# Input should be 1-indexed rank.
move = (self.convertRank(drank), int(dnum), self.translate(actual))
else:
if not self.AI and rank != None:
self.printCards()
# Get a move from the command line.
move = self.prompt(rank)
else:
move = self.moveAI()
return move
# Uses the global ranks list to convert a rank to its internal
# representation (i.e., in range(13)).
def convertRank(self, rank):
return ranks.index(rank)
# Checks to see whether the actual move is a playable move, i.e. a subset
# of the player's current cards. Looks at cards from the command line.
def isSubset(self, cardlist):
# Copy our list so we don't have to deal with aliasing issues.
cards = [i for i in self.getCards()]
for card in cardlist:
if card in self.carddict.keys():
card = self.carddict[card]
if card in cards:
cards.remove(card)
else:
return False
else:
return False
return True
# Converts a list of cards from external format to internal format.
def convert(self, cardlist):
converted = []
for card in cardlist:
converted.append(self.carddict[card])
return converted
# Parses an entered list of cards into internal format.
def translate(self, movestr):
temp = movestr.strip().split()
cards = [self.carddict[i] for i in temp]
return cards
# Prints the cards in external format.
def printCards(self):
cards = self.getCards()
print "Player %d's cards: " % self.pid
for card in cards:
name = ""
suit = card / 13
rank = (card % 13) + 1
if suit == 0:
name = "S" + str(rank)
elif suit == 1:
name = "C" + str(rank)
elif suit == 2:
name = "D" + str(rank)
else:
name = "H" + str(rank)
print "%s" % name
# RUSSIANBS CLASS------------------------------------------------------------//
class RussianBS:
'''Runs the game of Russian BS.'''
# Member variables:
# nplayers -> The number of players in the game
# player_list -> A list holding every player in the game
# out -> Holds cards which are out of the game.
# round -> Holds the state of the current round.
# won -> Integer holding who won the game (or -1)
# turn -> The PID of the player whose turn it is
# AI is expected to be a list of booleans of length num_players
def __init__(self, num_players, AI):
self.nplayers = num_players
self.player_list = range(num_players)
# Randomly deal cards to each player.
random.seed()
# Each player gets a least base cards:
quotient = 52 / num_players # Integer division.
remainder = 52 % num_players
pool = range(52)
for i in range(num_players):
if remainder > 0:
cards = random.sample(pool, quotient + 1)
remainder -= 1
else:
cards = random.sample(pool, quotient)
# Get rid of the cards we've already assigned.
for card in cards:
pool.remove(card)
# Create our player
self.player_list[i] = Player(i, cards, AI[i], num_players)
# List of cards which are out of the game.
self.out = []
self.round = []
self.won = -1
self.turn = 0
# Runs the game.
def runGame(self):
while self.won == -1:
self.updateRound()
print "Player %d has won!" % self.won
# Runs each round of the game. Moves are kept as a tuple of
# the list of cards declared, and the list of cards played.
# self.round keeps the PID of the player that made the move followed by
# the actual move.
#
# All cards here should be in their internal representation (i.e., in
# range(52)).
def updateRound(self):
ended = False
correct = False
first = True
rank = None
total_cards = 0
while not ended:
for player in self.player_list:
print "Player %d has %d cards." % (player.getPID(), len(player.getCards()))
print "Player %d's turn." % self.turn
# We already check for valid moves in playerMove() member function.
move = self.player_list[self.turn].playMove(first = first, rank = rank)
first = False
if rank == None:
rank = move[0] # The rank is held in the first coordinate.
if (move == BELIEVE or move == BS) and self.round != []:
# The last player didn't lie.
if self.isEqual(self.round[-1]):
if move == BELIEVE:
# If we correctly believe, the cards exit the game.
all_cards = []
for tup in self.round:
current_pid, current_cards = tup[0], tup[3]
all_cards += current_cards
# Each player gains the information that the cards
# they played go out.
self.player_list[current_pid].addCards("out", current_cards)
self.out += all_cards
correct = True
elif move == BS:
# We guessed wrong, so the current player gets all of the cards.
# In addition, all of the other players learn that this player
# gets all of the cards.
all_cards = []
for i in range(len(self.round)):
all_cards += self.round[i][3]
# Now give the cards to the current player, and information
# to the other players.
for player in self.player_list:
player.addCards(self.turn, all_cards)
# The last player did lie.
else:
if move == BELIEVE:
# We guessed wrong, so the current player gets all of the cards.
# In addition, all of the other players learn that this player
# gets all of the cards.
all_cards = []
for i in range(len(self.round)):
all_cards += self.round[i][3]
# Now give the cards to the current player, and information
# to the other players.
for player in self.player_list:
player.addCards(self.turn, all_cards)
elif move == BS:
# We guessed right, so the previous player takes all of the
# cards and each player learns the cards played.
all_cards = []
for i in range(len(self.round)):
all_cards += self.round[i][3]
# Now give the cards to the previous player, and information
# to the other players.
for player in self.player_list:
player.addCards(self.turn - 1, all_cards)
correct = True
# Now reset everything for the next round and end the turn.
# Update the histories for each player.
for player in self.player_list:
player.getGameHistory(self.round)
# Reset self.round.
self.round = []
if not correct:
self.turn = (self.turn + 1) % self.nplayers
self.won = self.hasWon()
ended = True
# Otherwise, add the move the our internal state.
else:
(rank, num, cards) = move
print "Player %d has played %d cards of rank %s" % (self.turn, num, ranks[rank])
tup = (self.turn, rank, num, cards)
self.round.append(tup)
self.turn = (self.turn + 1) % self.nplayers
# A player has won if they have no cards at the end of their turn.
def hasWon(self):
for player in self.player_list:
if len(player.getCards()) == 0:
return player.getPID()
return -1
# Given a move, determines whether the player lied while making the move.
def isEqual(self, move):
(PID, rank, number, cards) = move
if len(cards) == number:
for card in cards:
if card % 13 != rank:
return False
return True
else:
return False
# GAME FUNCTIONS-------------------------------------------------------------//
# Runs a game of RussianBS, using the classes defined above.
def playGame():
# Get the number of players
nplayers = int(raw_input("Number of players>> "))
nAI = int(raw_input("Number of AI players>> "))
AI = range(nplayers)
for i in range(nplayers):
if i < nAI:
AI[i] = True
else:
AI[i] = False
game = RussianBS(nplayers, AI)
game.runGame()
q = raw_input("Quit?>> ")
if q == "Y":
return True
else:
return False
# MAIN-----------------------------------------------------------------------//
if __name__ == '__main__':
done = False
while not done:
done = playGame()
|
c2f0a1b969ff51321362d7c48c4004d18b09bf90 | huxiaolei1997/PythonWork | /Python่ฟ้ถ/2-3.py | 353 | 3.84375 | 4 | # -*- coding: utf-8 -*-
import math
def add(x, y, f):
return f(x) + f(y)
print (add(25, 9, math.sqrt))
# ่ฟ้ไผ ๅ
ฅไบไธไธชmath.sqrtไฝไธบๅฝๆฐ็ๅ้๏ผๆไปฅaddๅฝๆฐๅฎ้
ๆง่ก็ไปฃ็ ๆฏabs(25) + abs(9)
# ๆ่
ไนๅฏไปฅๅ
def sqrt1(a):
return math.sqrt(a)
def add2(x, y, f):
return f(x) + f(y)
print (add2(25, 9, sqrt1)) |
4b93941db861c8fad04d890965e7c5cbbc114f50 | Shaunwei/Leetcode-python-1 | /String/RegularExpressionMatching/isMatchII.py | 2,215 | 4.15625 | 4 | #!/usr/bin/python
"""
Regular Expression Matching
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") -> false
isMatch("aa","aa") -> true
isMatch("aaa","aa") -> false
isMatch("aa", "a*") -> true
isMatch("aa", ".*") -> true
isMatch("ab", ".*") -> true
isMatch("aab", "c*a*b") -> true
"""
class Solution:
# @param s, an input string
# @param p, a pattern string
# @return a boolean
def isMatch(self, s, p):
res = [[False for i in xrange(len(p)+1)] for j in xrange(len(s)+1)]
res[0][0] = True
for i in xrange(1,len(p)+1):
if p[i-1] == '*':
if i >= 2: res[0][i] = res[0][i-2]
for i in xrange(1,len(s)+1):
for j in xrange(1,len(p)+1):
if p[j-1] == '.': res[i][j] = res[i-1][j-1]
elif p[j-1] == '*':
res[i][j] = res[i][j-1] or res[i][j-2] or \
(res[i-1][j] and (s[i-1]==p[j-2] or p[j-2]=='.'))
else: res[i][j] = res[i-1][j-1] and s[i-1]==p[j-1]
return res[len(s)][len(p)]
if __name__=="__main__":
s1 = ["aa","aa","aaa","aa","aa","ab","aab","", "ab", "aaa","a","a", "bb", "bb"]
s2 = ["a","aa","aa","a*",".*",".*","c*a*b","bab",".*c","a.a",".","ab*",".bab","*"]
# T, F, T, F, T, T, T, F, F, T, T, T, F, F
for i in xrange(len(s1)):
print Solution().isMatch(s1[i],s2[i])
"""
Note that this problem is NOT the same as Wildcard Matching.
The major difference is the meaning of "*" in the string.
Here, "*" means 0 or more preceding element. For example, the last test case in the problem description:
isMatch("aab",""c*a*b")
The pattern : "c*a*b" means, there can be 0 or more 'c', 0 or more 'a' and one b.
e.g., "ccaab", "aab", "ccb", "b" are all valid strings for this pattern, thus the correct answer for this test case is also true (0 'c', 2 'a' and 1 'b').
This is DP version, more efficient.
"""
|
4e6d45077c3739b4e176765f104a4e231c3bf26a | 4ster/skillsmart-algo2 | /t1/trees.py | 6,854 | 3.71875 | 4 | class SimpleTreeNode:
def __init__(self, val, parent):
self.NodeValue = val # ะทะฝะฐัะตะฝะธะต ะฒ ัะทะปะต
self.Parent = parent # ัะพะดะธัะตะปั ะธะปะธ None ะดะปั ะบะพัะฝั
self.Children = [] # ัะฟะธัะพะบ ะดะพัะตัะฝะธั
ัะทะปะพะฒ
class SimpleTree:
def __init__(self, root):
self.Root = root # ะบะพัะตะฝั, ะผะพะถะตั ะฑััั None
# ะดะพะฑะฐะฒะปัะตั ะฒ ัะทะตะป ParentNode ะดะพัะตัะฝะธะผ ัะทะตะป NewChild
def AddChild(self, ParentNode, NewChild):
if ParentNode is not None:
NewChild.Parent = ParentNode
ParentNode.Children.append(NewChild)
return True # ะฒะฐั ะบะพะด ะดะพะฑะฐะฒะปะตะฝะธั ะฝะพะฒะพะณะพ ะดะพัะตัะฝะตะณะพ ัะทะปะฐ ัััะตััะฒัััะตะผั ParentNode
# ัะดะฐะปัะตั ัะทะตะป
def DeleteNode(self, NodeToDelete):
# ะฝะต ัะดะฐะปัะตะผ ะบะพัะตะฝั
if NodeToDelete.Parent is not None:
NodeToDelete.Parent.Children.remove(NodeToDelete)
NodeToDelete.Parent = None
return True # ะฒะฐั ะบะพะด ัะดะฐะปะตะฝะธั ัััะตััะฒัััะตะณะพ ัะทะปะฐ NodeToDelete
# ะฒะพะทะฒัะฐัะฐะตั ัะฟะธัะพะบ ะฒัะตั
ัะทะปะพะฒ
def GetAllNodes(self):
# ะฒ ัะปััะฐะต ะฟัััะพะณะพ ะดะตัะตะฒะฐ ะฒะพะทะฒัะฐัะฐะตะผ ะฟัััะพะน ัะฟะธัะพะบ
if self.Root is None:
return []
# ะฒะฐั ะบะพะด ะฒัะดะฐัะธ ะฒัะตั
ัะทะปะพะฒ ะดะตัะตะฒะฐ ะฒ ะพะฟัะตะดะตะปัะฝะฝะพะผ
# ะดะพะฑะฐะฒะปัะตะผ ะฒ ัะฟะธัะพะบ ะฒัะตั
ัะทะปะพะฒ ะบะพัะตะฝั
all_nodes = [self.Root]
# ะทะฐะฒะพะดะธะผ ัะฟะธัะพะบ ะดะปั ั
ัะฐะฝะตะฝะธั ัะทะปะพะฒ, ั ะบะพัะพััั
ะฑัะดะตะผ ะฟัะพะฒะตัััั ะดะพัะตัะฝะธะต
queue = [self.Root, ]
# ะฟัะพั
ะพะดะธะผ ะฟะพ ะฒัะตะผ ัะทะปะฐะผ ะฒ ััะพะผ ัะฟะธัะบะต
while len(queue) > 0:
# ะทะฐะฑะธัะฐะตะผ ะพะดะธะฝ ัะทะตะป
q = queue.pop()
# ะตัะปะธ ั ะฝะตะณะพ ะตััั ะดะพัะตัะฝะธะต ัะทะปั, ะดะพะฑะฐะฒะปัะตะผ ะธั
ะฒ ัะฟะธัะพะบ ะฒัะตั
ัะทะปะพะฒ ะธ ะฒัะฟะธัะพะบ ะดะปั ะฟัะพะฒะตัะบะธ ะดะพัะตัะฝะธั
if len(q.Children) > 0:
queue.extend(q.Children)
all_nodes.extend(q.Children)
return all_nodes
# ะฝะฐั
ะพะดะธั ะฒัะต ัะทะปั ะฟะพ ะทะฐะดะฐะฝะฝะพะผั ะทะฝะฐัะตะฝะธั
def FindNodesByValue(self, val):
# ะฒะฐั ะบะพะด ะฟะพะธัะบะฐ ัะทะปะพะฒ ะฟะพ ะทะฝะฐัะตะฝะธั
if self.Root is None:
return []
# ัะฟะธัะพะบ ะดะปั ั
ัะฐะฝะตะฝะธั ะฒัะตั
ัะทะปะพะฒ
all_nodes = []
# ะฟัะพะฒะตััะตะผ ะทะฝะฐัะตะฝะธะต ะฒ ะบะพัะฝะต ะธ ะดะพะฑะฐะฒะปัะตะผ, ะตัะปะธ ะฟะพะดั
ะพะดะธั
if self.Root.NodeValue == val:
all_nodes.append(self.Root)
# ะฒ ัะฟะธัะพะบ ะดะปั ะฟะพะธัะบะฐ ะดะพัะตัะฝะธั
ัะปะตะผะตะฝัะพะฒ ะดะพะฑะฐะฒะปัะตะผ ะบะพัะตะฝั
queue = [self.Root]
# ะฟะพะบะฐ ัะฟะธัะพะบ ะฝะต ะฟัััะพะน
while len(queue) > 0:
# ะทะฐะฑะธัะฐะตะผ ัะปะตะผะตะฝั ะธะท ัะฟะธัะบะฐ
q = queue.pop()
# ะตัะปะธ ั ััะพะณะพ ัะปะตะผะตะฝัะฐ ะตััั ะดะพัะตัะฝะธะต
if len(q.Children) > 0:
# ะดะพะฑะฐะฒะปัะตะผ ะธั
ัะฟะธัะพะบ ะฒ ัะฟะธัะพะบ ะดะปั ะฟะพะธัะบะฐ ะดะพัะตัะฝะธั
queue.extend(q.Children)
# ะฟัะพะฒะตััะตะผ ะบะฐะถะดัะน ัะปะตะผะตะฝั ัะฟะธัะบะฐ ะฝะฐ ัะพะฒะฟะฐะดะฐััะธะต ั val ะทะฝะฐัะตะฝะธั ะธ ะดะพะฑะฐะฒะปัะตะผ ะฒ ัะฟะธัะพะบ ะฒัะตั
ัะทะปะพะฒ, ะตัะปะธ ะฝัะถะฝะพ
for c in q.Children:
if c.NodeValue == val:
all_nodes.append(c)
return all_nodes
# ะฟะตัะตะผะตัะฐะตั ัะทะตะป ะดะตัะตะฒะฐ
def MoveNode(self, OriginalNode, NewParent):
# ะฒะฐั ะบะพะด ะฟะตัะตะผะตัะตะฝะธั ัะทะปะฐ ะฒะผะตััะต ั ะตะณะพ ะฟะพะดะดะตัะตะฒะพะผ --
# ะฒ ะบะฐัะตััะฒะต ะดะพัะตัะฝะตะณะพ ะดะปั ัะทะปะฐ NewParent
# ัะดะฐะปัะตะผ OriginalNode ะธะท ัะฟะธัะบะฐ ะดะพัะตัะฝะธั
ั ะตะณะพ ัะพะดะธัะตะปั
OriginalNode.Parent.Children.remove(OriginalNode)
# ะทะฐะดะฐะตะผ ะฝะพะฒัะน ัะพะปะธัะตะปััะบะธะน ัะทะตะป ะดะปั OriginalNode
OriginalNode.Parent = NewParent
# ะดะพะฑะฐะฒะปัะตะผ OriginalNode ะฒ ัะฟะธัะพะบ ะดะพัะตัะฝะธั
ัะทะปะฐ NewParent
NewParent.Children.append(OriginalNode)
return True
# ััะธัะฐะตั ะฒัะต ัะทะปั ะฒ ะดะตัะตะฒะต
def Count(self):
# ะบะพะปะธัะตััะฒะพ ะฒัะตั
ัะทะปะพะฒ ะฒ ะดะตัะตะฒะต
cnt = 0
# ะตัะปะธ ะดะตัะตะฒะพ ะฝะตะฟัััะพะต, ัะพ ััะธัะฐะตะผ ะบะพัะตะฝั
if self.Root is not None:
cnt += 1
else:
return 0
# ะดะพะฑะฐะฒะปัะตะผ ะฒ ัะฟะธัะพะบ ะดะปั ะฟะพะธัะบะฐ ะดะพัะตัะฝะธั
ัะทะปะพะฒ ะบะพัะตะฝั
queue = [self.Root]
# ะฟะพะบะฐ ััะพั ัะฟะธัะพะบ ะฝะตะฟัััะพะน
while len(queue) > 0:
# ะดะพััะฐะตะผ ะพะดะธะฝ ัะปะตะผะตะฝั
q = queue.pop()
# ะตัะปะธ ั ะฝะตะณะพ ะตััั ะดะพัะตัะฝะธะต
if len(q.Children) > 0:
# ะดะพะฑะฐะฒะปัะตะผ ะธั
ะฒ ัะฟะธัะพะบ ะดะปั ะฟะพะธัะบะฐ ะดะพัะตัะฝะธั
ัะปะตะผะตะฝัะพะฒ
queue.extend(q.Children)
# ะธ ัะฒะตะปะธัะธะฒะฐะตะผ ััะตััะธะบ ะฝะฐ ะธั
ะบะพะปะธัะตััะฒะพ
cnt += len(q.Children)
return cnt
# ััะธัะฐะตั ะปะธัััั ะฒ ะดะตัะตะฒะต
def LeafCount(self):
if self.Root is None:
return 0
# ะบะพะปะธัะตััะฒะพ ะปะธัััะตะฒ ะฒ ะดะตัะตะฒะต
cnt = 0
# ะตัะปะธ ะฒ ะดะตัะตะฒะต ัะพะปัะบะพ ะบะพัะตะฝั, ัะพ ััะพ ะตะดะธะฝััะฒะตะฝะฝัะน ะปะธัั - ะฒะพะทะฒัะฐัะฐะตะผ 1
if len(self.Root.Children) == 0:
return 1
else:
# ะธะฝะฐัะต ะดะพะฑะฐะฒะปัะตะผ ะฒ ัะฟะธัะพะบ ะดะปั ะฟะพะธัะบะฐ ะดะพัะตัะฝะธั
ัะปะตะผะตะฝัะพะฒ ะบะพัะตะฝั
queue = [self.Root]
# ะฟะพะบะฐ ััะพั ัะฟะธัะพะบ ะฝะตะฟััั
while len(queue) > 0:
# ะดะพััะฐะตะผ ะธะท ะฝะตะณะพ ะพะดะธะฝ ัะปะตะผะตะฝั
q = queue.pop()
# ะตัะปะธ ั ััะพะณะพ ัะปะตะผะตะฝัะฐ ะตััั ะดะพัะตัะฝะธะต
if len(q.Children) > 0:
# ะดะพะฑะฐะฒะปัะตะผ ะธั
ัะฟะธัะพะบ ะฒ ัะฟะธัะพะบ ะดะปั ะฟะพะธัะบะฐ ะดะพัะตัะฝะธั
queue.extend(q.Children)
# ะฟัะพั
ะพะดะธะผ ะฟะพ ัะฟะธัะบั ะดะพัะตัะฝะธั
ัะตะบััะตะณะพ ัะปะตะผะตะฝัะฐ ะธ ััะธัะฐะตะผ ะปะธัััั
for c in q.Children:
if len(c.Children) == 0:
cnt += 1
return cnt
|
2d900664f5a9c109c9bbef4b93a55be607062840 | adrianxplay/python_unittesting | /curp_calculator.py | 1,049 | 3.875 | 4 | # -*- coding: utf-8 -*-
def calculator(last_name, second_name, name, birth_date, gender):
vowel = ['a', 'e', 'i', 'o', 'u']
curp = ''
# First letter of last_name
if last_name[0] == 'รฑ':
curp += "x"
else:
curp += last_name[0]
# First vowel of last_name
for letter in last_name:
if letter in vowel:
curp += letter
break
if second_name[0] == 'รฑ':
curp += "x"
else:
curp += second_name[0]
if name[0] == 'รฑ':
curp += "x"
else:
curp += name[0]
date = birth_date.split("/")
curp += date[2][2:]
curp += date[1]
curp += date[0]
curp += gender
curp += "df"
curp += get_consonant(last_name[2:])
curp += get_consonant(second_name[1:])
curp += get_consonant(name[1:])
return curp
def get_consonant(str):
vowel = ['a', 'e', 'i', 'o', 'u']
for i in str:
if i not in vowel:
if i == 'รฑ':
return "x"
else:
return i
|
f91f2d2e40ad95039fc69f925773c1b51614f12e | Deepkumarbhakat/Python-Repo | /list2.py | 164 | 4.03125 | 4 | # Write a Python program to multiplies all the items in a list.
a=[int(i) for i in input( ).split()]
print(a)
mul = 1
for i in a:
mul = mul * i
print(mul)
|
4984edfc32a3187030b8ecd9db1d38f17afe2727 | qqmadeinchina/myhomeocde | /homework_zero_class/lesson15/่ฏปๅๅคงๆไปถ-times_2.py | 1,978 | 3.578125 | 4 | #!D:\Program Files\Anaconda3
# -*- coding: utf-8 -*-
# @Time : 2020/8/7 0:29
# @Author : ่่ๅ
# @File : ่ฏปๅๅคงๆไปถ-times_2.py
# @Software: PyCharm Community Edition
# read()ๆฅ่ฏปๅๅ
ๅฎน็ๆถๅ
# ๅฎไผ็ดๆฅๅฐๅ
จ้จๅ
ๅฎน่ฏปๅๅบๆฅใๅฆๆ่ฆ่ฏปๅ็ๅ
ๅฎนๆฏ่พๅคง๏ผไผไธๆฌกๆงๅ ่ฝฝๅฐๅ
ๅญๅฝไธญ๏ผ่ฟไธชๆถๅๅฐฑๅฎนๆๅฏผ่ดๅ
ๅญๆบขๅบ
file_name = 'demo2.txt'
try:
with open(file_name,encoding='utf-8') as file_obj:
help(file_obj.read)
content = file_obj.read()
print(content)
except FileNotFoundError:
print(f'{file_name}ๆไปถไธๅญๅจ')
file_name = 'demo2.txt'
try:
with open(file_name,encoding='utf-8') as file_obj:
help(file_obj.read)
content = file_obj.read(-1)
print(content)
except FileNotFoundError:
print(f'{file_name}ๆไปถไธๅญๅจ')
file_name = 'demo2.txt'
try:
with open(file_name,encoding='utf-8') as file_obj:
content = file_obj.read(6)
print(len(content),content,end="")
content = file_obj.read(6)
print(len(content),content,end="")
content = file_obj.read(6)
print(len(content),content,end="")
content = file_obj.read(6)
print(len(content),content,end="")
except FileNotFoundError:
print(f'{file_name}ๆไปถไธๅญๅจ')
# 6 ็ฝๆฅไพๅฑฑๅฐฝ
# 6 ้ปๆฒณๅ
ฅๆตทๆต
# 6 ๆฌฒ็ฉทๅ้็ฎ
# 5 ๆดไธไธๅฑๆฅผ
# ๅฆๆ่ฎพ็ฝฎ็่ฟไธชsizeๅคงไบๅฉไฝๅญ็ฌฆ็ๆฐ้๏ผๅฎไผไธไธๅ
จ้จๆๅฉไฝ็้จๅ่ฏปๅ
try:
with open(file_name,encoding='utf-8') as file_obj:
# ๅฎไนไธไธชๅ้๏ผๆๅฎๆฏๆฌก่ฏปๅๅญ็ฌฆ็ๆฐ้
chunk = 100
# ๅๅปบไธไธชๅพช็ฏๆฅ่ฏปๅๆไปถ็ๅ
ๅฎน
while True:
content = file_obj.read(chunk)
# ้ๅบๅพช็ฏ
if not content:
# ๅ
ๅฎน่ฏปๅฎไบ ้ๅบๅพช็ฏ
break
print(content,end='')
except FileNotFoundError:
print(f'{file_name}ๆไปถไธๅญๅจ') |
ec96ec57cb0b92126e81e98adad28292f1524599 | emarteca/TurtleWalk | /selfAvoiding_randomDist.py | 6,434 | 3.734375 | 4 | from turtle import Turtle
import random
import math
import interceptInRange
# Like the second implementation of the fixed-distance self-avoiding walk, this walk
# is no longer angle-based (it's component-based instead, and got rid of the slow
# turtle.setHeading(...) command).
# The functionality is the same as for the previous random-distance walk
# Again, if the walk gets stuck for 100 tries (i.e. checking 100 points) then it exits.
# function to run the self-avoiding walk
# t --> the turtle
# x and y --> the x and y coordinates of the starting position respectively
# rep --> number of steps for the walk (unless it gets stuck)
def selfAvoidingWalk_randomDist(t, x, y, rep):
# first 3 points can't cross
t.up()
t.goto(x, y)
t.down()
arrayOfPoints = [(x, y)] # list of points in the walk
x += (t.screen.window_width() / 2) * (random.random()) * ((-1) ** random.randint(1, 2))
y += (t.screen.window_height() / 2) * (random.random()) * ((-1) ** random.randint(1, 2))
arrayOfPoints += [(x, y)]
t.goto(x, y)
(m, b) = solveLinearEquation(arrayOfPoints[0], arrayOfPoints[1]) # list of linear equations (in form (slope, y-intercept)) for all adjacent pairs of points in the walk
linearEquations = [(m, b)]
x += (t.screen.window_width() / 2) * (random.random()) * ((-1) ** random.randint(1, 2))
y += (t.screen.window_height() / 2) * (random.random()) * ((-1) ** random.randint(1, 2))
arrayOfPoints += [(x, y)]
t.goto(x, y)
(m, b) = solveLinearEquation(arrayOfPoints[1], arrayOfPoints[2])
linearEquations += [(m, b)]
# here, 3 points exist and 2 lines have been drawn.
# len(arrayOfPoints) == 3 and 2 iterations have been done
for index in range(rep - 2): # index == 0 when len(arrayOfPoints) == 3. So, last element is arrayOfPoints[index + 2]
done = False
stuck = 0
while not done:
# pick a random component and its corresponding component
# the * ((-1) ** (random.randint(1, 2))) is to ensure that the component could be in any of the 4 quadrants
w = (t.screen.window_width() / 2) * (random.random()) * ((-1) ** random.randint(1, 2))
z = (t.screen.window_height() / 2) * (random.random()) * ((-1) ** random.randint(1, 2))
if abs(x + w) < t.screen.window_width() / 2 and abs(y + z) < t.screen.window_height() / 2: # check if the point is within the window
(currentX, currentY) = (x + w, y + z) # coordinates to test
(previousX, previousY) = arrayOfPoints[len(arrayOfPoints) - 1] # last recorded point (before new point)
for index in range(len(linearEquations) - 1):
(slope, intercept) = linearEquations[index] # linear equation for the points being checked
if previousX == currentX: # no linear equation joins these points (2 y-values for the same x-value)
# print("Zero division error.")
break
(testSlope, testIntercept) = solveLinearEquation((previousX, previousY), (currentX, currentY)) # find the linear equation joining the points
if testSlope == slope: # the lines are parallel (no POI)
# print("Zero division error.")
break
# find the POI
(xi, yi) = pointOfIntersection((slope, intercept), (testSlope, testIntercept))
# now check where the POI is in relation to the points tested.
check = interceptInRange.interceptInRange((previousX, previousY), (currentX, currentY), arrayOfPoints[index], arrayOfPoints[index + 1], (xi, yi))
if check == -1: # if the intercept was in range, then the point is not valid
stuck += 1
break
# if the POI is not in range, and this is the last valid point to be checked, then the new point is a valid point (i.e. no POIs were in range)
if check == 1 and (slope, intercept) == linearEquations[len(linearEquations) - 2]:
done = True
if stuck >= 100: # don't check 100 or more points - then the walk is stuck
break
# if the walk has checked >= 100 new points and none are valid, then the walk is stuck
if stuck >= 100:
print('\nWalk stuck! Exiting...')
break # exit the walk
# if the point is valid, update the position and add the new point to the record
x += w
y += z
t.goto(x, y)
arrayOfPoints += [(x, y)]
(Slope, Intercept) = solveLinearEquation(arrayOfPoints[index + 2], arrayOfPoints[index + 3])
linearEquations += [(Slope, Intercept)]
# function to find the line joining 2 points
# returns the line as (m, b) where m is the slope and b is the y-intercept
# pointA and pointB --> the 2 points to find the line between
def solveLinearEquation(pointA, pointB):
# y = mx + b
(ax, ay) = pointA
(bx, by) = pointB
m = (by - ay) / (bx - ax)
# b = y - mx
b = by - (m * bx)
return (m, b)
# function to find the point of intersection between 2 lines
# returns the point as (x, y)
# each line is passed in as a tuple (m, b) where m is the slope and b is the y-intercept
# lineA and lineB --> the 2 lines to find the POI of
def pointOfIntersection(lineA, lineB):
# y = mx + b
# y = cx + d
# At the POI, the x and y coordinates are the same
# mx + b = cx + d
# mx - cx = d - b
# x(m - c) = d - b
# x = (d - b) / (m - c)
(m, b) = lineA
(c, d) = lineB
xi = (d - b) / (m - c)
yi = (m * xi) + b
return (xi, yi)
# main function controls user inputs and runs the program
def main():
t = Turtle()
# promp user for number of steps in the walk
iterations = int(input("Enter the number of reps: "))
t.pencolor("red")
t.screen.bgcolor("black")
# run the walk with the parameters specified
# this walk starts at the origin (centre of the window) every time
selfAvoidingWalk_randomDist(t, 0, 0, iterations)
t.hideturtle()
print '\n\nProgram Done!'
main()
|
30c1c9ea2c8083b6962aa239a5c7b709f78cfb53 | ravinder79/python-exercises | /functions.py | 5,990 | 4 | 4 |
# 1. Define a function named is_two. It should accept one input and return True if the passed input is
#either the number or the string 2, False otherwise
#
def is_two(x):
if x == 2 or x == '2':
return True
else:
return False
# 2. Define a function named is_vowel. It should return True if the passed string is a vowel, False otherwise.
def is_vowel(str):
if str.lower() in 'aeiou':
return True
else:
return False
#Define a function named is_consonant. It should return True if the passed string is a consonant, False otherwise.
#Use your is_vowel function to accomplish this.
def is_consonant(str):
if is_vowel(str):
return False
else:
return True
#Define a function that accepts a string that is a word.
#The function should capitalize the first letter of the word if the word starts with a consonant.
def cap(str):
if is_consonant(str[0]):
return str[0].upper()+str[1:]
else:
return str
#Define a function named calculate_tip. It should accept a tip percentage (a number between 0 and 1) and the
#bill total, and return the amount to tip.
def calculate_tip(tip_percent, total_bill):
tip = total_bill * tip_percent
return '%.2f'%tip
#Define a function named apply_discount. It should accept a original price, and a discount percentage, and return
#the price after the discount is applied.
def apply_discount(original_price, discount_percentage):
price_after_discount = (1 - discount_percentage) * original_percentage
return '%.2f'%price_after_discount
#Define a function named handle_commas. It should accept a string that is a number that contains
#commas in it as input, and return a number as output.
def handle_commas(str):
number = str.replace(',',"")
return int(number)
#Define a function named get_letter_grade. It should accept a number and return
#the letter grade associated with that number (A-F).
def letter_grade(number):
if number >= 88:
return 'A'
elif number >= 80:
return 'B'
elif number >= 67:
return 'C'
elif number >= 60:
return 'D'
else:
return 'F'
#Define a function named remove_vowels that accepts a string and returns a string with all
#the vowels removed
def remove_vowels(str):
new_word =''
for char in str:
if char.lower() not in 'aeiou':
new_word = new_word+char
return new_word
# #Define a function named normalize_name. It should accept a string and return a valid python identifier, that is:
# anything that is not a valid python identifier should be removed
# leading and trailing whitespace should be removed
# everything should be lowercase
# spaces should be replaced with underscores
# for example:
# Name will become name
# First Name will become first_name
# % Completed will become completed
def normalize_name(x):
new_word = ''
while not (x[0].isalpha() or x[0] == '_'): # this block removes any charcters from front of input except '_' and alphabets
x = x[1:]
print(x)
# x = x.strip() # this block removes any trailing white spaces
for char in x: # this block removes any non-alphanumeric characters and replaces space with '_'
if char == ' ':
new_word = new_word + '_'
elif char == "_":
new_word = new_word + char
elif not char.isalnum():
new_word = new_word
else:
new_word = new_word + char
return new_word.lower()
# Write a function named cumsum that accepts a list of numbers and returns a list that is
#the cumulative sum of the numbers in the list.
# cumsum([1, 1, 1]) returns [1, 2, 3]
# cumsum([1, 2, 3, 4]) returns [1, 3, 6, 10]
def cumsum(x):
for i in range(0,len(x)):
if i >= 1 and i < len(x)-1:
x[i] = x[i] + x[i-1]
if i == len(x)-1:
x[i] = x[i]+ x[i-1]
return x
# Create a function named twelveto24. It should accept a string in the format 10:45am or 4:30pm and return
# a string that is the representation of the time in a 24-hour format.
# Bonus write a function that does the opposite.
def twelveto24(x):
hour =''
minute = ''
a_or_p = ''
if (x[1] == ':'):
hour = hour + x[0]
minute = minute + x[2] + x[3]
a_or_p = x[4]
else:
hour = hour + x[0] + x[1]
minute = minute + x[3] + x[4]
a_or_p = x[5]
if (a_or_p == 'p') and (hour != '12'):
hour = int(hour) + 12
elif (a_or_p =='a' and hour == '12'):
hour = int(hour) - 12
else:
hour = int(hour)
if len(str(hour) + ':' + str(minute)) == 4:
return '0' + str(hour) + ':' + str(minute)
else:
return str(hour) + ':' + str(minute)
# Bonus: write a function that does the opposite.
def twentyhourto12(x):
for i in x:
hour = int(x[0] + x[1])
minute = int(x[3] + x[4])
if hour >= 12:
am_or_pm = 'pm'
else:
am_or_pm = 'am'
if hour > 12:
hour -= 12
elif hour == 0:
hour = 12
return str(hour) + ':' + str(minute) + str(am_or_pm)
# Create a function named col_index. It should accept a spreadsheet column name, and return the index number of the column.
# col_index('A') returns 1
# col_index('B') returns 2
# col_index('AA') returns 27
def col_index(x):
dictt = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8',
'i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17',
'r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'
}
y = x.lower()
n = len(x)
num = 0
for i in range(0,n):
num = (26**(n-1-i)) * int(dictt[y[i]]) +num
return num |
6d2647c4d84de679b030d61ee00da9622b77bfeb | lavifb/pyChess | /test.py | 16,230 | 3.921875 | 4 | import unittest
from Chess import Chess
from consts import EMPTY_SQUARE
class SimpleInputsTest(unittest.TestCase):
def setUp(self):
self.chess = Chess()
self.chess.setupBoard()
def test_move_e4(self):
"""
Simple e4 chess move
"""
self.chess.makeMove('e4')
self.assertEqual(self.chess.board[1][4], EMPTY_SQUARE)
self.assertEqual(self.chess.board[3][4], 'WP')
def test_taking_turns(self):
"""
Turns change only after legal moves
"""
self.chess.makeMove('e4')
self.assertEqual(self.chess.turn, 1)
self.chess.makeMove('e5')
self.assertEqual(self.chess.turn, 0)
with self.assertRaises(ValueError):
self.chess.makeMove('e5')
self.assertEqual(self.chess.turn, 0)
def test_move_e2e4(self):
"""
Simple e2-e4 chess move
"""
self.chess.makeMove('e2-e4')
self.assertEqual(self.chess.board[1][4], EMPTY_SQUARE)
self.assertEqual(self.chess.board[3][4], 'WP')
def test_move_e3e4(self):
"""
Illegal e3-e4 chess move
"""
with self.assertRaises(ValueError):
self.chess.makeMove('e3-e4')
self.assertEqual(self.chess.board[1][4], 'WP')
self.assertEqual(self.chess.board[3][4], EMPTY_SQUARE)
def test_move_Nf3(self):
"""
Simple Nf3 chess move
"""
self.chess.makeMove('Nf3')
self.assertEqual(self.chess.board[3][4], EMPTY_SQUARE)
self.assertEqual(self.chess.board[1][4], 'WP')
self.assertEqual(self.chess.board[0][6], EMPTY_SQUARE)
self.assertEqual(self.chess.board[2][5], 'WN')
def test_bad_input(self):
"""
Bad input chess move
"""
with self.assertRaises(ValueError):
self.chess.makeMove('nf4')
self.assertEqual(self.chess.board[3][4], EMPTY_SQUARE)
self.assertEqual(self.chess.board[1][4], 'WP')
self.assertEqual(self.chess.board[0][6], 'WN')
self.assertEqual(self.chess.board[0][1], 'WN')
def test_illegal_move_input(self):
"""
Bad e5 chess move
"""
with self.assertRaises(ValueError):
self.chess.makeMove('e5')
self.assertEqual(self.chess.board[3][4], EMPTY_SQUARE)
self.assertEqual(self.chess.board[1][4], 'WP')
def test_pos_conv(self):
"""
Position to array coord conversion
"""
self.assertEqual(self.chess.convertPosToCoords('a4'), (3,0))
self.assertEqual(self.chess.convertPosToCoords('g5'), (4,6))
class PawnMovesTest(unittest.TestCase):
def setUp(self):
self.chess = Chess()
self.chess.setSquare('b2', 'WP')
self.chess.setSquare('c2', 'WP')
self.chess.setSquare('c3', 'BP')
self.chess.setSquare('d2', 'WP')
self.chess.setSquare('d3', 'WP')
def test_illegal_hop1(self):
"""
Illegal pawn hopping over other color
"""
with self.assertRaises(ValueError):
self.chess.makeMove('c4')
self.assertEqual(self.chess.checkSquare('c2'), 'WP')
self.assertEqual(self.chess.checkSquare('c3'), 'BP')
self.assertEqual(self.chess.checkSquare('d2'), 'WP')
self.assertEqual(self.chess.checkSquare('d3'), 'WP')
self.assertEqual(self.chess.checkSquare('c4'), EMPTY_SQUARE)
def test_illegal_hop2(self):
"""
Illegal pawn hopping over same color
"""
with self.assertRaises(ValueError):
self.chess.makeMove('d2-d4')
self.assertEqual(self.chess.checkSquare('c2'), 'WP')
self.assertEqual(self.chess.checkSquare('c3'), 'BP')
self.assertEqual(self.chess.checkSquare('d2'), 'WP')
self.assertEqual(self.chess.checkSquare('d3'), 'WP')
self.assertEqual(self.chess.checkSquare('d4'), EMPTY_SQUARE)
def test_move_correct_pawn(self):
"""
Move correct pawn of doubled pawns
"""
self.chess.makeMove('d4')
self.assertEqual(self.chess.checkSquare('c2'), 'WP')
self.assertEqual(self.chess.checkSquare('c3'), 'BP')
self.assertEqual(self.chess.checkSquare('d2'), 'WP')
self.assertEqual(self.chess.checkSquare('d4'), 'WP')
self.assertEqual(self.chess.checkSquare('d3'), EMPTY_SQUARE)
def test_move_illegal_capture_input1(self):
"""
Illegal capture input
"""
with self.assertRaises(ValueError):
self.chess.makeMove('c3')
self.assertEqual(self.chess.checkSquare('c2'), 'WP')
self.assertEqual(self.chess.checkSquare('c3'), 'BP')
self.assertEqual(self.chess.checkSquare('d2'), 'WP')
self.assertEqual(self.chess.checkSquare('d3'), 'WP')
def test_move_illegal_capture_input2(self):
"""
Illegal capture input
"""
with self.assertRaises(ValueError):
self.chess.makeMove('axc3')
self.assertEqual(self.chess.checkSquare('c2'), 'WP')
self.assertEqual(self.chess.checkSquare('c3'), 'BP')
self.assertEqual(self.chess.checkSquare('d2'), 'WP')
self.assertEqual(self.chess.checkSquare('d3'), 'WP')
def test_move_capture_input1(self):
"""
Capture input dxc3
"""
self.chess.makeMove('dxc3')
self.assertEqual(self.chess.checkSquare('b2'), 'WP')
self.assertEqual(self.chess.checkSquare('c2'), 'WP')
self.assertEqual(self.chess.checkSquare('c3'), 'WP')
self.assertEqual(self.chess.checkSquare('d2'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('d3'), 'WP')
def test_move_capture_input2(self):
"""
Capture input bxc3
"""
self.chess.makeMove('bxc3')
self.assertEqual(self.chess.checkSquare('b2'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('c2'), 'WP')
self.assertEqual(self.chess.checkSquare('c3'), 'WP')
self.assertEqual(self.chess.checkSquare('d2'), 'WP')
self.assertEqual(self.chess.checkSquare('d3'), 'WP')
# def test_en_passant(self):
# """
# En passant
# """
# self.chess.setSquare('a4', 'BP')
# self.chess.makeMove('b4')
# self.chess.makeMove('axb3')
# self.assertEqual(self.chess.checkSquare('a4'), EMPTY_SQUARE)
# self.assertEqual(self.chess.checkSquare('b4'), EMPTY_SQUARE)
# self.assertEqual(self.chess.checkSquare('b3'), 'BP')
# def test_no_en_passant(self):
# """
# No en passant
# """
# self.chess.setSquare('a4', 'BP')
# self.chess.setSquare('g8', 'BK')
# self.chess.makeMove('b4')
# self.chess.makeMove('Kf7')
# self.chess.makeMove('d4')
# with self.assertRaises(ValueError):
# self.chess.makeMove('axb3')
# self.assertEqual(self.chess.checkSquare('a4'), 'BP')
# self.assertEqual(self.chess.checkSquare('b4'), 'WP')
# self.assertEqual(self.chess.checkSquare('b3'), EMPTY_SQUARE)
class KnightMovesTest(unittest.TestCase):
def setUp(self):
self.chess = Chess()
self.chess.setSquare('g1', 'WN')
self.chess.setSquare('h3', 'BB')
self.chess.setSquare('d4', 'WP')
def test_move1(self):
"""
Move knight
"""
self.chess.makeMove('Nf3')
self.assertEqual(self.chess.checkSquare('g1'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('f3'), 'WN')
def test_move_to_occupied(self):
"""
Cant move knight to occupied
"""
with self.assertRaises(ValueError):
self.chess.makeMove('Nh3')
self.assertEqual(self.chess.checkSquare('h3'), 'BB')
self.assertEqual(self.chess.checkSquare('g1'), 'WN')
def test_capture(self):
"""
Knight captures occupied
"""
self.chess.makeMove('Nxh3')
self.assertEqual(self.chess.checkSquare('g1'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('h3'), 'WN')
def test_bad_capture(self):
"""
Knight doesnt capture own piece occupied
"""
self.chess.makeMove('Ne2')
self.chess.makeMove('Bg4')
with self.assertRaises(ValueError):
self.chess.makeMove('Nd4')
with self.assertRaises(ValueError):
self.chess.makeMove('Nxd4')
self.assertEqual(self.chess.checkSquare('g1'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('e2'), 'WN')
self.assertEqual(self.chess.checkSquare('d4'), 'WP')
self.chess.makeMove('d5')
self.assertEqual(self.chess.checkSquare('d4'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('d5'), 'WP')
def test_ambig_move1(self):
"""
Test ambiguous move
"""
self.chess.setSquare('e1', 'WN')
with self.assertRaises(ValueError):
self.chess.makeMove('Nf3')
self.chess.makeMove('Ne1-f3')
self.assertEqual(self.chess.checkSquare('g1'), 'WN')
self.assertEqual(self.chess.checkSquare('e1'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('f3'), 'WN')
def test_ambig_move2(self):
"""
Test ambiguous move
"""
self.chess.setSquare('e1', 'WN')
with self.assertRaises(ValueError):
self.chess.makeMove('Nf3')
self.chess.makeMove('Ng1-f3')
self.assertEqual(self.chess.checkSquare('e1'), 'WN')
self.assertEqual(self.chess.checkSquare('g1'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('f3'), 'WN')
class QueenMovesTest(unittest.TestCase):
"""
Tests for Queen moves. Implicitly also tests rooks and bishop logic
"""
def setUp(self):
self.chess = Chess()
self.chess.setSquare('e3', 'WQ')
def test_queen_moves(self):
"""
Test a bunch of valid and invalid queen moves
"""
self.chess.makeMove('Qe7')
self.chess.turn = 0
self.assertEqual(self.chess.checkSquare('e7'), 'WQ')
self.assertEqual(self.chess.checkSquare('e3'), EMPTY_SQUARE)
self.chess.makeMove('Qg5')
self.chess.turn = 0
with self.assertRaises(ValueError):
self.chess.makeMove('Qg5')
self.chess.makeMove('Qb5')
self.chess.turn = 0
self.chess.makeMove('Qf1')
self.chess.turn = 0
with self.assertRaises(ValueError):
self.chess.makeMove('Qg5')
with self.assertRaises(ValueError):
self.chess.makeMove('Qg3')
self.chess.makeMove('Qg2')
def test_blocked_queen_moves(self):
"""
Test queen moves while blocked by pieces
"""
self.chess.setSquare('e4', 'WP')
self.chess.setSquare('d4', 'BP')
with self.assertRaises(ValueError):
self.chess.makeMove('Qe7')
with self.assertRaises(ValueError):
self.chess.makeMove('Qxe7')
with self.assertRaises(ValueError):
self.chess.makeMove('Qe4')
with self.assertRaises(ValueError):
self.chess.makeMove('Qxe4')
with self.assertRaises(ValueError):
self.chess.makeMove('Qc5')
with self.assertRaises(ValueError):
self.chess.makeMove('Qxc5')
with self.assertRaises(ValueError):
self.chess.makeMove('Qd4')
self.chess.makeMove('Qxd4')
self.assertEqual(self.chess.checkSquare('d4'), 'WQ')
self.assertEqual(self.chess.checkSquare('e3'), EMPTY_SQUARE)
class BishopRookMovesTest(unittest.TestCase):
"""
Tests for Bishop and Rook moves
"""
def setUp(self):
self.chess = Chess()
self.chess.setSquare('e3', 'WB')
self.chess.setSquare('b7', 'BR')
def test__moves(self):
"""
Test a bunch of valid and invalid bishop and rook moves
"""
self.chess.makeMove('Bc5')
self.chess.makeMove('Rb6')
with self.assertRaises(ValueError):
self.chess.makeMove('Ba7')
with self.assertRaises(ValueError):
self.chess.makeMove('Ba5')
self.chess.makeMove('Ba3')
self.chess.makeMove('Rf6')
self.chess.makeMove('Bb2')
self.chess.makeMove('Rf8')
class CastlingTest(unittest.TestCase):
"""
Tests for Castling
"""
def setUp(self):
self.chess = Chess()
self.chess.setSquare('e1', 'WK')
self.chess.setSquare('h1', 'WR')
self.chess.setSquare('e8', 'BK')
self.chess.setSquare('a8', 'BR')
def test_castling(self):
"""
Test castling
"""
self.chess.makeMove('O-O')
self.chess.makeMove('O-O-O')
self.chess.printBoard()
self.assertEqual(self.chess.checkSquare('e1'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('f1'), 'WR')
self.assertEqual(self.chess.checkSquare('g1'), 'WK')
self.assertEqual(self.chess.checkSquare('h1'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('e8'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('d8'), 'BR')
self.assertEqual(self.chess.checkSquare('c8'), 'BK')
self.assertEqual(self.chess.checkSquare('b8'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('a8'), EMPTY_SQUARE)
def test_blocked_castle(self):
"""
Test blocked castling
"""
self.chess.setSquare('f1', 'WB')
with self.assertRaises(ValueError):
self.chess.makeMove('0-0')
self.chess.makeMove('Be2')
self.chess.makeMove('0-0-0')
self.chess.makeMove('0-0')
def test_moved_before_castle(self):
"""
Test illegal castling after moving pieces
"""
self.chess.setSquare('a1', 'WR')
self.chess.makeMove('Rh2')
self.chess.makeMove('Ke7')
self.chess.makeMove('Rh1')
self.chess.makeMove('Ke8')
with self.assertRaises(ValueError):
self.chess.makeMove('0-0')
self.chess.makeMove('0-0-0')
with self.assertRaises(ValueError):
self.chess.makeMove('0-0-0')
def test_castle_out_of_check(self):
"""
Test illegal castling out of check
"""
self.chess.setSquare('e4', 'BQ')
with self.assertRaises(ValueError):
self.chess.makeMove('0-0')
with self.assertRaises(ValueError):
self.chess.makeMove('Rf1')
def test_castle_through_check(self):
"""
Test illegal castling through check
"""
self.chess.setSquare('f4', 'BQ')
self.chess.setSquare('c4', 'WQ')
with self.assertRaises(ValueError):
self.chess.makeMove('0-0')
self.chess.makeMove('Rf1')
with self.assertRaises(ValueError):
self.chess.makeMove('0-0')
def test_castle_into_check(self):
"""
Test illegal castling into check
"""
self.chess.setSquare('g4', 'BQ')
self.chess.setSquare('b4', 'WQ')
with self.assertRaises(ValueError):
self.chess.makeMove('0-0')
self.chess.makeMove('Rf1')
with self.assertRaises(ValueError):
self.chess.makeMove('0-0')
self.chess.makeMove('Rc8')
class PawnPromotionTest(unittest.TestCase):
def setUp(self):
self.chess = Chess()
self.chess.setSquare('e7', 'WP')
self.chess.setSquare('e2', 'BP')
self.chess.setSquare('f1', 'WN')
def test_promotion(self):
"""
Pawn promotion
"""
with self.assertRaises(ValueError):
self.chess.makeMove('e8')
with self.assertRaises(ValueError):
self.chess.makeMove('exf8')
self.chess.makeMove('e8=N')
with self.assertRaises(ValueError):
self.chess.makeMove('exf1')
with self.assertRaises(ValueError):
self.chess.makeMove('exf1=K')
self.chess.makeMove('exf1=Q')
self.assertEqual(self.chess.checkSquare('e7'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('e8'), 'WN')
self.assertEqual(self.chess.checkSquare('e2'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('e1'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('f1'), 'BQ')
def test_not_promotion(self):
"""
Not promotios
"""
self.chess.setSquare('e8', 'BB')
self.chess.setSquare('a2', 'WP')
with self.assertRaises(ValueError):
self.chess.makeMove('Ne3=R')
with self.assertRaises(ValueError):
self.chess.makeMove('e8=B')
with self.assertRaises(ValueError):
self.chess.makeMove('a4=Q')
class CheckTests(unittest.TestCase):
def setUp(self):
self.chess = Chess()
self.chess.setSquare('e1', 'WK')
self.chess.setSquare('f3', 'BN')
self.chess.setSquare('c4', 'BB')
self.chess.setSquare('d8', 'BR')
self.chess.setSquare('a2', 'WP')
def test_moving_in_check(self):
"""
No moving into check
"""
with self.assertRaises(ValueError):
self.chess.makeMove('a3')
with self.assertRaises(ValueError):
self.chess.makeMove('Ke2')
with self.assertRaises(ValueError):
self.chess.makeMove('Kd1')
self.chess.makeMove('Kf2')
self.assertEqual(self.chess.checkSquare('e1'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('f2'), 'WK')
def test_pinned_check(self):
"""
No moving pinned piece into check
"""
self.chess.setSquare('f3', 'WN')
self.chess.setSquare('b4', 'BQ')
self.chess.setSquare('d2', 'WR')
with self.assertRaises(ValueError):
self.chess.makeMove('Rd6')
self.chess.makeMove('a3')
self.assertEqual(self.chess.checkSquare('d6'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('d2'), 'WR')
def test_pawn_check1(self):
"""
No allowing pawn checks
"""
self.chess.setSquare('f3', 'WN')
self.chess.setSquare('f2', 'BP')
self.chess.setSquare('e2', 'BP')
with self.assertRaises(ValueError):
self.chess.makeMove('a3')
self.chess.makeMove('Kxf2')
self.assertEqual(self.chess.checkSquare('e1'), EMPTY_SQUARE)
self.assertEqual(self.chess.checkSquare('f2'), 'WK')
def test_pawn_check2(self):
"""
King not in check in front of pawn
"""
self.chess.setSquare('f3', 'WN')
self.chess.setSquare('e2', 'BP')
self.chess.makeMove('a3')
def test_block_check(self):
"""
Check should be able to be blocked
"""
self.chess.setSquare('f3', 'WN')
self.chess.setSquare('b4', 'BQ')
self.chess.setSquare('g5', 'WB')
self.chess.makeMove('Bd2')
if __name__ == '__main__':
unittest.main() |
55bdd6a318bb44fd0db418836f4ba4355f60a49f | geeveekee/100_days_of_Code | /d6.py | 2,060 | 3.671875 | 4 | import random
print("""
_
| |
| |__ __ _ _ __ __ _ _ __ ___ __ _ _ __
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
__/ |
|___/
""")
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
words = ('ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra ').split()
word_generated = random.choice(words)
print(word_generated)
display = []
for word in word_generated:
display += "_"
game_over = False
lives = 6
while not game_over:
guess = input("Guess a letter: ").lower()
i=0
if guess in display:
print("You have already guessed that letter")
for x in word_generated:
if x == guess:
display[i] = guess
i+=1
print(f"{' '.join(display)}")
print(HANGMANPICS[lives])
if guess not in word_generated:
lives -=1
print(f"{guess} is not in the word")
if lives == 0:
print("You loose!")
print(f"The correct word was {word_generated}")
game_over = True
if '_' not in display:
game_over = True
print("You win!")
|
1f1288274db10f50eb215d725662075b201b8666 | wagnersistemalima/Mundo-1-Python-Curso-em-Video | /pacote dawload/projetos progamas em Python/desafio023 Separando dรญgitos de um nรบmero.py | 884 | 4.125 | 4 | # Desafio023 Separando digitos de um nรบmero.
# Faรงa um progama que leia um numero de 0 a 9999 e mostre na tela cada um dos digitos separados.
# Ex: digite um numero 1834
# unidade: 4 / dezena: 3 / centena: 8 / milhar: 1
hipotese = True
while hipotese:
numero = int(input('Informe um nรบmero:')) #
unidade = numero // 1 % 10
dezena = numero // 10 % 100
centena = numero // 100 % 1000
milhar = numero // 1000
print('Unidade รฉ {}'.format(unidade))
print('dezena รฉ {}'.format(dezena))
print('Centena รฉ {}'.format(centena))
print('Milhar รฉ {}'.format(milhar))
print('-=-'*10)
print('Quer continuar: [1] Sim / [2] Nรฃo')
opcao = int(input('Sua opcaรต:'))
while opcao < 1 or opcao > 2:
print('Quer continuar: [1] Sim / [2] Nรฃo')
opcao = int(input('Sua opรงรฃo:'))
if opcao == 2:
hipotese = False
|
578b3a135c5a8a9d82a260cfa53e75aa0b20982c | tjwilks/heartDiseasePrediction | /src/modelling/feature_selection.py | 3,747 | 3.578125 | 4 | from sklearn.ensemble import RandomForestClassifier
import re
class FeatureSelector:
"""
A class for searching selecting features based on
missing value proportion or feature importance rank
methods
Attributes
----------
X_data : pandas dataframe
pandas dataframe containing data to be used for training
on and predicting output variable y_data
y_data : numpy array
numpy array containing output variable to be predicted by
X_data
col_na_proportion : dict
dictionary containing the proportion of missing values
present in each variable within X_data for the purpose of
missing value based feature selection
missing_value_filter : float
threshold to above which columns that had a greater
proportion of missing values before imputation (as
is recorded in col_na_proportion) are removed
feature_importance_rank_filter : int
threshold bellow which columns with a lower
feature importance rank are removed
Methods
-------
select_on_missing_value_proportion
removes columns that had a proportion of missing
values before imputation (as is recorded in
col_na_proportion) above threshold set by missing_value_filter
select_on_feature_importance_rank
removes columns that have a lower feature importance rank
than threshold set by feature_importance_rank_filter
"""
def __init__(self, X_data, y_data, col_na_proportion, missing_value_filter, feature_importance_rank_filter):
self.X_data = X_data
self.y_data = y_data
self.col_na_proportion = col_na_proportion
self.missing_value_filter = missing_value_filter
self.feature_importance_rank_filter = feature_importance_rank_filter
self.feature_importance_dict = None
def select_on_missing_value_proportion(self):
cols_na_proportion_above_filter = self.col_na_proportion[self.col_na_proportion > self.missing_value_filter]
cols_with_x_prop_missing_values = cols_na_proportion_above_filter.index
one_hot_cols = [col for col in self.X_data.columns if bool(re.search("_one_hot", col))]
non_one_hot_cols = [col for col in self.X_data.columns if bool(re.search("_one_hot", col)) is False]
cols_to_drop_one_hot = [col for col in one_hot_cols if re.split(r"_[^_]{0,20}_one_hot", col)[0] in cols_with_x_prop_missing_values]
cols_to_drop_normal = [col for col in non_one_hot_cols if col in cols_with_x_prop_missing_values]
cols_to_drop_total = list(set(cols_to_drop_normal).union(set(cols_to_drop_one_hot)))
self.X_data = self.X_data.drop(cols_to_drop_total, axis=1)
def select_on_feature_importance_rank(self):
model = RandomForestClassifier(n_estimators=200, max_features=5, max_leaf_nodes=25, n_jobs=-1, oob_score=True)
model.fit(self.X_data.to_numpy(), self.y_data)
feature_importances = model.feature_importances_
importance_rank = 1
self.feature_importance_dict = {}
for feature_importance, feature in sorted(zip(feature_importances, self.X_data.columns), reverse=True):
self.feature_importance_dict[feature] = (importance_rank, feature_importance)
importance_rank += 1
self.selected_features = [feature for feature, rank_score in self.feature_importance_dict.items() if
rank_score[0] <= self.feature_importance_rank_filter]
self.X_data = self.X_data.loc[:, self.selected_features]
self.X_data = self.X_data.to_numpy()
|
ceeacb2fe10ed2c58ab837dd8b7707822aa2eb15 | immortal0820/learn-python3 | /data_struct/reference.py | 523 | 4.09375 | 4 | #!/usr/bin/env python3
print("Simple arguments")
shoplist = ['apple', 'banana', 'mango']
print('Origner shoplist is', shoplist)
mylist = shoplist # ๅคๅถไธไธชๅ่กจๆ่
็ฑปไผผ็ๅบๅๆ่
ๅ
ถไปๅคๆ็ๅฏน่ฑก๏ผๅฟ
้กปไฝฟ็จๅ็ๆไฝ็ฌฆๆฅๅๅพๆท่ด
# ๅ่กจ็ๅคๅถ่ฏญๅฅไธๅๅปบๆท่ด
del shoplist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
print('Copy by making a full slice')
mylist = shoplist[:]
del shoplist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
|
ae498ad0d2e48e8ba643cecb93d850f95492a9ad | LabharPL/python | /json_example.py | 2,013 | 3.734375 | 4 | # import json
#
#
# # some JSON:
# x = '{ "name":"John", "age":30, "city":"New York"}'
#
# # parse x:
# y = json.loads(x)
#
# # the result is a Python dictionary:
# print(y["city"])
#
#
# # a Python object (dict):
# x = {
# "name": "John",
# "age": 30,
# "city": "New York"
# }
#
# # convert into JSON:
# y = json.dumps(x)
#
# # the result is a JSON string:
# print(y)
# import re
#
# str = "The rain in Spain"
# x = re.findall("ai", str)
# print(x)
#
# import requests
# r = requests.get('https://api.github.com')
# # <Response [200]>
# print(r)
#
# if r.status_code == 200:
# print('Success!')
# elif r.status_code == 404:
# print('Not Found.')
# import requests
# from requests.exceptions import HTTPError
#
# for url in ['https://api.github.com', 'https://api.github.com/invalid']:
# try:
# response = requests.get(url)
#
# # If the response was successful, no Exception will be raised
# response.raise_for_status()
# except HTTPError as http_err:
# print(f'HTTP error occurred: {http_err}') # Python 3.6
# except Exception as err:
# print(f'Other error occurred: {err}') # Python 3.6
# else:
# print('Success!')
#
# try:
# f = open("demofile.txt")
# print('tu jest f', f)
#
# f.write("Lorum Ipsum")
# except:
# print("Something went wrong when writing to the file")
# finally:
# f.close()
# print("Something else went wrong")
#
# print("Enter your name:")
# x = input()
# print("Hello ", x)
#
# print("Enter your name:")
# x = raw_input()
# print("Hello ", x)
# myorder = "I have a {carname}, it is a {model}."
# print(myorder.format(carname = "Ford", model = "Mustang"))
f = open("demofile.txt", "rt")
print(f.read(122))
print('+++++++++++++++++++++++++++++++++')
f = open("demofile.txt", "r")
for x in f:
print(x)
f.close()
f = open("demofile.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile.txt", "r")
print(f.read()) |
73ed661778442247a8220f0de7c59d56e410dfa1 | SURGroup/UQpy | /docs/code/distributions/user_defined/plot_user_defined.py | 3,161 | 3.71875 | 4 | """
User-defined Rosenbrock distribution
=====================================
This examples shows the use of the multivariate normal distributions class. In particular:
"""
import numpy as np
from UQpy.distributions import DistributionND
import matplotlib.pyplot as plt
#%% md
#
# Example with a custom distribution
# ----------------------------------
# In order to define a new distribution, the user must extend the one of the abstract base classes
# :class:`.DistributionContinuous1D`, :class:`.DistributionDiscrete1D` or :class:`.DistributionND`.
# For the purpose of this example a
# new multivariate Rosenbrock distribution is defined. Note that three methods are implemented, namely, the
# :code:`__init__`
# which allows the user to define custom distribution arguments, as well as the pdf and log_pdf of this new
# distribution. Note that it is required for the user to call the :code:`__init__` method of the baseclass by providing
# all arguments names and values required in the custom distribution initializer. In our case, the parameter name
# :code:`p` and its values are provided to the :code:`super().__init__` method.
#%%
class Rosenbrock(DistributionND):
def __init__(self, p=20.):
super().__init__(p=p)
def pdf(self, x):
return np.exp(-(100 * (x[:, 1] - x[:, 0] ** 2) ** 2 + (1 - x[:, 0]) ** 2) / self.parameters['p'])
def log_pdf(self, x):
return -(100 * (x[:, 1] - x[:, 0] ** 2) ** 2 + (1 - x[:, 0]) ** 2) / self.parameters['p']
#%% md
#
# Initialize custom distribution
# ----------------------------------
# Given the newly defined distribution class, a Rosenbrock distribution object can be defined by providing to the
# initializer the user-defined argument :code:`p`. Since the Rosenbrock distribution extends the
# :class:`.DistributionND` class, methods
# and attributes of the baseclass are already available. For instance, the user can retrieve the already defined
# parameters using the :code:`parameters` attribute and subsequently update them using the :code:`update_parameters`
# method.
#%%
dist = Rosenbrock(p=20)
print(dist.parameters)
dist.update_parameters(p=40)
print(dist.parameters)
dist = Rosenbrock(p=20)
print(dist.parameters)
#%% md
#
# Plot pdf of the user defined distribution
# ------------------------------------------
#
#%%
fig, ax = plt.subplots(figsize=(8, 5))
x = np.arange(-5, 8, 0.1)
y = np.arange(-5, 50, 0.1)
X, Y = np.meshgrid(x, y)
Z = dist.pdf(x=np.concatenate([X.reshape((-1, 1)), Y.reshape((-1, 1))], axis=1))
CS = ax.contour(X, Y, Z.reshape(X.shape))
ax.clabel(CS, inline=1, fontsize=10)
ax.set_title('Contour plot of custom pdf - Rosenbrock')
plt.show()
#%% md
#
# Check if the user-defined distribution has rvs, pdf and update_parameters method
# ----------------------------------------------------------------------------------
#
#%%
print('Does the rosenbrock distribution have an rvs method?')
print(hasattr(dist, 'rvs'))
print('Does the rosenbrock distribution have an pdf method?')
print(hasattr(dist, 'pdf'))
print('Does the rosenbrock distribution have an update_parameters method?')
print(hasattr(dist, 'update_parameters')) |
84f3ddd7342143271b182ee05cbb4efebc3238ca | jing1988a/python_fb | /ๅฅฝๅง,ๆๅ่ฟๆฏ่ฆๆgoogle/medium/KnightProbabilityinChessboard688.py | 2,045 | 3.875 | 4 | # On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1).
#
# A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
#
#
#
#
#
#
# Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.
#
# The knight continues moving until it has made exactly K moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.
#
#
#
# Example:
#
# Input: 3, 2, 0, 0
# Output: 0.0625
# Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
# From each of those positions, there are also two moves that will keep the knight on the board.
# The total probability the knight stays on the board is 0.0625.
#
#
# Note:
#
# N will be between 1 and 25.
# K will be between 0 and 100.
# The knight always initially starts on the board.
class Solution:
def knightProbability(self, N, K, r, c):
"""
:type N: int
:type K: int
:type r: int
:type c: int
:rtype: float
"""
dp=[[0 for i in range(N)] for i in range(N)]
dp[r][c]=1
step=0
while step<K:
newDP=[[0 for i in range(N)] for i in range(N)]
for i in range(N):
for j in range(N):
for x , y in [ [-1 , -2] , [-2 , -1] , [-2 , 1] , [-1 , 2] , [1 , 2] , [2 , 1] , [2 , -1] , [1 , -2]]:
preI=i+x
preJ=j+y
if 0<=preI<N and 0<=preJ<N:
newDP[i][j]+=dp[preI][preJ]/8
dp=newDP
step+=1
ans=0
for i in range(N):
ans+=sum(dp[i])
return ans |
0cfba21ca82b1824fd987a86ad2009d0f2f46bf8 | Divisekara/Python-Codes-First-sem | /PA2/PA2 2013/PA2-18/Asitha/pa2-18-2013.py | 1,624 | 3.640625 | 4 | N=0
matrix=[]
def getText():
try:
fo=open("FileIn.txt","r")
L=[]
while True:
L.append(fo.readline().split())
if L[-1]==[]:
L.pop(-1)
break
fo.close()
except IOError:
print "File not found"
pass
else:
try:
global N
global matrix
N=int(L.pop(0)[0])
if not 3<=N<=20:
print "Out of range input."
else:
for i in L:
matrix.append(map(int,i))
except ValueError:
print "Enter integers only."
pass
def take_surrounding(i,j):
total=0
n=0
for k in range(i-1,i+2):
for l in range(j-1,j+2):
if k==-1 or l==-1:
continue
try:
total+=matrix[k][l]
except IndexError:
pass
else:
n=n+1
return total/n
def process():
solution=[]
for i in range(N):
row=[]
for j in range(N):
row.append(take_surrounding(i,j))
solution.append(row)
return solution
def show(L):
lines=[]
for i in L:
row=" ".join(map(str,i))
lines.append(row)
display="\n".join(lines)
print display
return display
def saveFile(s):
try:
fc=open("result.txt","w")
fc.write(s)
fc.close()
except IOError:
print "File Error."
pass
try:
getText()
saveFile(show(process()))
except:
print "Something went wrong."
pass
|
eabd3fc5b251a797060ff9d55481eeccfb86fa4f | Simple2001/blood-donation | /bloodonation.py | 2,706 | 3.625 | 4 | import sys
import csv
reciever=[]
bankdata=[]
#making sure that we donot need to run the code again and again to do more than one things; im using while true here which is always true.
while True:
print('\n1. type info. of blood donor\n2. take info. of blood donor using unique id\n3. type info. of reciever \n4. get data of reciever using unique id.')
ch = int(input('\ntype the number of your choice. :'))
if ch==1:
print('\ntype the following information.:')
name=input("Donor name:")
id=input("\nUnique id:")
phno=input("\nPhone Number:")
email=input("\nEmail id:")
add=input("\nAddress:")
bg=input("\nBloodGroup")
age=int(input("\nAge:"))
with open('bankdata.csv','a',newline='') as f:
thewriter=csv.writer(f)
thewriter.writerow([id,name,phno,email,add,bg,age])
f.close()
print("\n\ndone.")
elif ch==3:
print("\ntype the following info.:")
Rid=input('\nReciepent ID:')
name=input("Reciepent Name:")
sex=input("Gender:")
bg=input("BloodGroup:")
Hname=input("Hospital Name:")
with open('reciever.csv','a',newline='') as R:
writ=csv.writer(R)
writ.writerow([Rid,name,sex,bg,Hname])
R.close()
print("\n\ndone")
elif ch==2:
with open('bankdata.csv','r') as f:
reader=csv.reader(f)
for row in reader:
bankdata.append(row)
uid=input('\nunique id:')
col=[x[0]for x in bankdata]
if uid in col:
for x in range(0,len(bankdata)):
if uid==bankdata[x][0]:
print(bankdata[x])
else:
print("\nInvalid Donor ID!!")
f.close()
elif ch==4:
with open('reciever.csv','r') as R:
reader=csv.reader(R)
for row in reader:
reciever.append(row)
Rid=input('\nReciever ID:')
col=[x[0]for x in reciever]
if Rid in col:
for x in range(0,len(reciever)):
if Rid==reciever[x][0]:
print(reciever[x])
else:
print('\nInvalid ID')
R.close()
else:
print("\n\ntype numbers between 1 to 4")
sys.exit(1) |
ce483aabc39c2757e229147b1d05d051841a9db4 | priyankchheda/algorithms | /linked_list/remove_duplicates_singly.py | 1,786 | 3.96875 | 4 | """ Remove duplicates from singly linked list
input: 1 -> 6 -> 1 -> 4 -> 2 -> 2 -> 4
output: 1 -> 6 -> 4 -> 2
"""
class Node:
""" Node class contains everything related to Linked List node """
def __init__(self, data):
""" initializing single node with data """
self.data = data
self.next = None
class LinkedList:
""" Singly Linked List is a linear data structure """
def __init__(self):
""" initializing singly linked list with zero node """
self.head = None
def insert_head(self, data):
""" inserts node at the start of linked list """
node = Node(data)
node.next = self.head
self.head = node
def print(self):
""" prints entire linked list without changing underlying data """
current = self.head
while current is not None:
print(" ->", current.data, end="")
current = current.next
print()
def remove_duplicates(self):
""" removes duplicates from list """
duplicates = set()
previous = None
current = self.head
while current is not None:
if current.data not in duplicates:
duplicates.add(current.data)
previous = current
else:
previous.next = current.next
current = current.next
def main():
""" operational function """
linkedlist = LinkedList()
linkedlist.insert_head(4)
linkedlist.insert_head(2)
linkedlist.insert_head(2)
linkedlist.insert_head(4)
linkedlist.insert_head(1)
linkedlist.insert_head(6)
linkedlist.insert_head(1)
linkedlist.print()
linkedlist.remove_duplicates()
linkedlist.print()
if __name__ == '__main__':
main()
|
e4f83f29f3ffd84657835bac7242cd8ea1a45d48 | claudiogar/learningPython | /test.py | 691 | 3.9375 | 4 | from algos.quicksort import quicksort
from algos.mergesort import mergesort
from data_structures import tree
def tree_test():
root = tree.Tree(0)
child1 = root.addChild(1)
child2 = child1.addChild(2)
child3 = child1.addChild(3)
child4 = child2.addChild(4)
child5 = child4.addChild(5)
# 0
# 1
# 2 3
# 4
# 5
print(root.countNodes())
print("depth: "+(str(root.depth())))
pass
def quicksort_test():
array = [5,1,4,57,2,4,9,90]
quicksort(array)
print(array)
pass
def mergesort_test():
array = [5,1,4,57,2,4,9,90]
array = mergesort(array, 0 , len(array)-1)
print(array)
pass
mergesort_test() |
16412c4b71e865794904f8b1294ba1a832639783 | UPan111/python | /casion.py | 416 | 3.65625 | 4 | #casion
import random
sMax = 0
for i in range(3):
print('round:', i + 1)
input('go')
d1 = random.randint(1, 6)
d2 = random.randint(1, 6)
if d1 + d2 > sMax:
sMax = d1 + d2
print('Player', '\tDice1:', d1, 'Dice2', d2, '\tscore:', d1 + d2)
d3 = random.randint(1, 6)
d4 = random.randint(1, 6)
print('AI', '\tDice3:', d3, 'Dice4', d4, '\tscore:', d3 + d4)
print('Best:',sMax)
|
82fd1c288d6b569380470a0753030bf09b7292a0 | amoghkapalli/ProjectEuler | /Problem4.py | 593 | 3.9375 | 4 | '''A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 ร 99.
Find the largest palindrome made from the product of two 3-digit numbers.'''
from math import ceil
first_num=100
max_product=0
def palindrome_checker(num):
s=str(num)
first_frag=s[0: len(s)/2]
second_frag=s[int(ceil(len(s)/2.0)):]
return first_frag == second_frag[::-1]
for x in range(100, 1000):
for y in range(100, 1000):
z=x*y
if palindrome_checker(z):
if z>max_product:
max_product=z
print max_product |
8819a7c76c1376d974ac8450a5a0ea9abdc1877e | josejpalacios/codecademy-python3 | /Lesson 05: Loops/Lesson 01: Loops/Exercise 05: Break.py | 520 | 4.28125 | 4 | # You can stop a for loop from inside the loop by using break.
# When the program hits a break statement, control returns to the code outside of the for loop.
dog_breeds_available_for_adoption = ['french_bulldog', 'dalmatian', 'shihtzu', 'poodle', 'collie']
dog_breed_I_want = 'dalmatian'
# Create for loop
for dog_breed in dog_breeds_available_for_adoption:
print(dog_breed)
# Added if statement
if(dog_breed == dog_breed_I_want):
print("They have the dog I want!")
# Added break to stop loop
break
|
15713a4aa17b0af607f4967edc241d1f1688c313 | xaviergoby/Python-Data-Structure | /OOP/Polymorphism/SuperMethod.py | 873 | 3.640625 | 4 | class SomeBaseClass(object):
def __init__(self):
print('SomeBaseClass.__init__(self) called')
class UnsuperChild(SomeBaseClass):
def __init__(self):
print('Child.__init__(self) called')
SomeBaseClass.__init__(self)
class SuperChild(SomeBaseClass):
def __init__(self):
print('SuperChild.__init__(self) called')
super(SuperChild, self).__init__()
s = SuperChild()
print s
u = UnsuperChild()
# print "**"
print u
# print "****"
class InjectMe(SomeBaseClass):
def __init__(self):
print('InjectMe.__init__(self) called')
super(InjectMe, self).__init__()
class UnsuperInjector(UnsuperChild, InjectMe): pass
class SuperInjector(SuperChild, InjectMe): pass
print "-----------------"
x = SuperInjector()
#x.mro
y = UnsuperInjector()
print "MRO.."
print SuperInjector.mro()
print UnsuperInjector.mro() |
9e7a1c6a51d0cb40ed06a0aa71e504cca48a130b | jkaariain/python-exercises | /Kierros2/tehtava2.7.3.py | 147 | 3.5 | 4 | def main():
for i in range(1,11):
for j in range(1,11):
print("{:>4d}".format(i*j), end="")
print("")
main()
|
59847fe3139833438dff3c63e7d8eddb3ba96dab | andreishumeiko/shumeiko_project | /dz3_1.py | 292 | 3.59375 | 4 | def fdev(a, b):
try:
return a / b
except ZeroDivisionError:
return 'You cannot devide a by b=0'
try:
print(fdev((float(input('Enter the first number: '))), (float(input('Enter the second number: ')))))
except ValueError:
print('You have to use only numbers')
|
6aefafdf3fa5412adc81e00e62c147e0c446c5fc | KennyTC/Algorithm | /String/NextClosetTime.py | 1,521 | 3.921875 | 4 | # Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.
# You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid.
# Example 1:
# Input: "19:34"
# Output: "19:39"
# Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later.
# Example 2:
# Input: "23:59"
# Output: "22:22"
# Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the returned time is next day's time since it is smaller
# Simulate the clock.
def NextClosetTime2(time):
cur = 60 * int(time[:2]) + int(time[3:])
print("cur=", cur)
allowed = {int(x) for x in time if x != ':'}
while True:
cur = (cur + 1) % (24 * 60)
print("cur=(cur + 1) % (24 * 60)",cur)
if all(digit in allowed for block in divmod(cur, 60) for digit in divmod(block, 10)):# divmod(a,b)=(a//b,a%b)
return "{:02d}:{:02d}".format(*divmod(cur, 60))
# Ta sแปญ dแปฅng % ฤแป xแปญ lรฝ khi mแปt sแป nร o ฤรณ vฦฐแปฃt quรก mแปt ngฦฐแปกng mร quay lแบกi sแป ban ฤแบงu. VD. 1%12 = 13%12 =1.
# Lแปฃi dแปฅng ฤiแปu nร y, ta sแบฝ ฤแบทt 12 lร ngฦฐแปกng. Mแปt variable tฤng dแบงn, nแบฟu >12 thรฌ coi nhฦฐ quay lแบกi lร 1.
#print(NextClosetTime2("19:34"))
print(NextClosetTime2("13:59"))
|
8e309a1872270b81477e6567002c506a07b0053c | kangli-bionic/leetcode-1 | /94.py | 695 | 3.96875 | 4 | #!/usr/bin/env python
# coding=utf-8
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
ret = []
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.dfs(root)
return self.ret
def dfs(self, node):
if not node:
return
self.dfs(node.left)
self.ret.append(node.val)
self.dfs(node.right)
return
if __name__ == '__main__':
s = Solution()
print s.inorderTraversal([1,null,2,3])
|
ff0e11f6cab0ec1454d48c31c9771d2d8664e2a8 | chptcleo/PythonPractice | /com/string/string_reverse.py | 389 | 3.84375 | 4 | # print string.count('abc','c')
my_str = "abcde"
print(my_str.find("c"))
str_size = len(my_str)
# print my_str.find("e")
list = []
for i in range(str_size):
reversed_i = str_size - i - 1
list.append(my_str[reversed_i])
print("".join(list))
print(my_str.replace('a', 'x'))
print(my_str)
delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
|
c36716740ef029ef19a6362a9291d214441f5932 | ujwala14/Python-Lab | /8a.py | 367 | 4.1875 | 4 | '''Define a python function generate_n_chars()
that takes an integer n and a character c and returns a string,
n characters long. For example, generate_n_chars(5,"x") should
return the string "xxxxxโ using keyword only parameters.'''
def generate_n_chars(n,c):
return c*n
c=input('Enter char: ')
n=int(input('Enter no: '))
print(generate_n_chars(c=c,n=n))
|
e3a438207a13cb5750242ba94609e7e9224f0b8d | rahaf19-meet/meet2017y1lab4 | /Fruit_sorter.py | 221 | 4.3125 | 4 | bin1='Apples'
bin2='Oranges'
bin3='olives'
new_fruit=input('What fruit am i sorting')
if new_fruit==bin1:
print('Bin1')
elif new_fruit==bin2:
print('Bin2')
else:
print('Error! I do not recognize this fruit!')
|
c46764966de46e0ed0f1d24d80c6ac8082fb7e98 | Diefex/PyGroup | /Ejercicio3.py | 209 | 4.0625 | 4 | def is_even (k):
if (k % 2):
return False
else:
return True
if(is_even(int(input("ingresa un numero ")))):
print("este es un numero par")
else:
print("este es un numero impar") |
a4205a9c35e92a5e14a0d698b30e1b487b86d859 | irounik/Patterns.py | /4th.py | 343 | 3.90625 | 4 | n = 5
for i in range(2*n-1):
if(i < (2*n-1)//2):
for j in range(n-1-i):
print(' ', end=' ')
for j in range(i+1):
print('*', end=' ')
else:
for j in range(i-(2*n-1)//2):
print(' ', end=' ')
for j in range(n-i+(2*n-1)//2):
print('*', end=' ')
print('')
|
df22c274c8e84aa3d885b2ea83db0ea0025ad246 | KlaytonSouza/URI-PYTHON | /1010.py | 282 | 3.65625 | 4 | codP1,numP1,valP1 = input().split(" ")
codP2,numP2,valP2 = input().split(" ")
codP1 = int(codP1)
numP1 = int(numP1)
valP1 = float(valP1)
codP2 = int(codP2)
numP2 = int(numP2)
valP2 = float(valP2)
total = (numP1 * valP1) + (numP2 * valP2)
print("VALOR A PAGAR: R$ %.2f" % total)
|
2e545c894b10789be10c1bb7114e45d28a576986 | JHughes9802/Capstone_Week_2_Lab | /Student_Dataclass_Practice.py | 1,145 | 3.953125 | 4 | from dataclasses import dataclass
@dataclass
class Student:
# I don't know if I should feel weirded out or comforted by
# needing to declare data types for variables in Python.
# Furthermore, I'm curious why the datatype comes AFTER the
# variable AND why the variable needs a colon after itself.
name: str
school_id: int
gpa: float
# It's interesting that, while above doesn't require the "self" invocation,
# the return statement here needs it. I'm assuming this is mainly because we're
# overriding what's built-in, but I'm curious to find out more regarding this topic.
def __str__(self):
return f'Student name: {self.name}, ID: {self.school_id}, current GPA: {self.gpa}'
# Fake data to test output, it runs the same as before changing things to use dataclass.
# I made the "school_id" an integer (like our tech IDs) to show that int also works perfectly fine.
def main():
student1 = Student('Joe', 68413099, 3.4)
student2 = Student('Tina', 81437270, 3.6)
student3 = Student('Hank', 14742965, 3.3)
print(student1)
print(student2)
print(student3)
main() |
227d56a32ec35eb351ceefa3e0ede4ec45d3b0a5 | okurz/schatznenner | /schatznenner.py | 1,372 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random as r
adjektiven = [['sรผรer ','sรผรe ','sรผรes '],
['lieber ', 'liebe ', 'liebes '],
["lieblicher ", "liebliche ", "liebliches "],
["holder ","holde ","holdes "]]
pr = [['mein ', 'meine ','mein '],
['','',''],
['du ','du ','du '],
['du bist ein echter ', 'du bist eine echte ', 'du bist ein echtes ']]
artikels = ["der", "die", "das"]
def parse_word(x):
"""Parses the read word"""
global artikels
artikel = artikels.index(x[0:3])
wort = x.split(",")[0][4:-1] + x.split(",")[0][-1]
return artikel, wort
def get_random_compliment():
"""Gets a random and sweet compliment to name your German girlfriend"""
global adjektiven, pr, artikels
idx = r.randint(0,999)
with open('woerter.txt') as f:
lines = f.readlines()
artikel, wort = parse_word(lines[idx])
pr_idx = r.randint(0,len(pr)-1)
k = pr[pr_idx][artikel]
for num_adj in range(r.randint(1,2)):
adj_idx = r.randint(0,len(adjektiven)-1)
k = k + adjektiven[adj_idx][artikel]
schatz = r.randint(0,1)
if schatz == 1:
k = k + "Schatz" + wort.lower()
else:
k = k + wort
herzi = r.randint(0,1)
if herzi == 1:
k = k + " <3"
k = k[0].upper() + k[1:]
return k
|
21c2af6fc2313fe4a4d1b47a0f035acb72071197 | opello/adventofcode | /2015/python/08.py | 375 | 3.5625 | 4 | #!/usr/bin/env python
import re
length = 0
unEscapeLength = 0
escapeLength = 0
with open('../inputs/08.txt') as f:
for line in f:
line = line.rstrip()
length += len(line)
unEscapeLength += len(line[1:-1].decode('string_escape'))
escapeLength += len('"{0}"'.format(re.escape(line)))
print (length - unEscapeLength)
print (escapeLength - length)
|
75f3b191c83223933b686e6d8a1ec28462d8a598 | reed-qu/leetcode-cn | /MoveZeroes.py | 1,232 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/20 ไธๅ10:08
# @Title : 283. ็งปๅจ้ถ
# @Link : https://leetcode-cn.com/problems/move-zeroes/
QUESTION = """
็ปๅฎไธไธชๆฐ็ป nums๏ผ็ผๅไธไธชๅฝๆฐๅฐๆๆ 0 ็งปๅจๅฐๆฐ็ป็ๆซๅฐพ๏ผๅๆถไฟๆ้้ถๅ
็ด ็็ธๅฏน้กบๅบ
็คบไพ:
่พๅ
ฅ: [0,1,0,3,12]
่พๅบ: [1,3,12,0,0]
่ฏดๆ:
ๅฟ
้กปๅจๅๆฐ็ปไธๆไฝ๏ผไธ่ฝๆท่ด้ขๅค็ๆฐ็ปใ
ๅฐฝ้ๅๅฐๆไฝๆฌกๆฐใ
"""
THINKING = """
ๆไธค็งๆ่ทฏ
1. ไปๅคด้ๅ๏ผ้ๅฐ0๏ผๅๆพๅฐๆๅไธไฝ
2. ไปๅคด้ๅ๏ผ้ๅฐ้0๏ผๅๆพๅฐ็ฌฌไธไฝ๏ผไธไธๆฌก้ๅฐๆพๅฐ็ฌฌไบไฝ
"""
from typing import List
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
index = 0
number_of_zero = 0
length = len(nums)
while index < (length - number_of_zero):
if nums[index] == 0:
nums.pop(index)
nums.append(0)
number_of_zero += 1
else:
index += 1
print(nums)
if __name__ == '__main__':
s = Solution()
nums = [0,1,0,3,12]
print(s.moveZeroes(nums))
|
079a5cf5f46cd9f34c29010c025fa957d1c6d68e | NyntoFive/Reporter | /backend/excel_writer.py | 1,092 | 3.765625 | 4 | import xlsxwriter
def create_workbook(filename):
"""Create a new workbook on which we can work."""
workbook = xlsxwriter.Workbook(filename)
return workbook
def create_worksheet(workbook):
"""Add a new worksheet in the workbook."""
worksheet = workbook.add_worksheet()
return worksheet
def write_data(worksheet, data):
"""Write data to the worksheet."""
for row in range(len(data)):
for col in range(len(data[row])):
worksheet.write(row, col, data[row][col])
# New
worksheet.write(len(data), 0, "Avg. Age")
# len(data) will give the next index to write to
avg_formula = "=AVERAGE(B{}:B{})".format(1, len(data))
worksheet.write(len(data), 1, avg_formula)
def close_workbook(workbook):
"""Close an opened workbook."""
workbook.close()
if __name__ == '__main__':
data = [['John Doe', 38],
['Abby Dawn', 22],
['Stacey Martin', 28]]
workbook = create_workbook('sample_workbook.xlsx')
worksheet = create_worksheet(workbook)
write_data(worksheet, data)
close_workbook(workbook) |
224ec53e24cbfc34d0a625a5ea116313a3264c61 | AdamSlayer/ximena_lessons | /python files/Ximena_lessons/16-exercise3.py | 138 | 3.5625 | 4 | keys = ["ten", "twenty", "thirty"]
values = [10,20,30]
dict1 = {}
for key in range(len(keys)):
dict1=dict1+(keys[key],values[key]) |
d4240e81674ff14054a99f592bdcfb8680316067 | smartinsert/CodingProblem | /algorithmic_patterns/dynamic_programming/rod_cutting.py | 913 | 3.734375 | 4 | """
Cutting rod to maximize profit. Given available lengths and the value at which they are selling,
how will you divide the length to make maximum profit.
"""
def rod_cutting(available_lengths, price_of_each_length, length_of_the_rod):
if length_of_the_rod == 0:
return 0
dp = [[0 for _ in range(length_of_the_rod + 1)] for _ in range(len(available_lengths) + 1)]
for i in range(len(available_lengths) + 1):
for j in range(length_of_the_rod + 1):
if i == 0 or j == 0:
dp[i][j] = 0
continue
if j - available_lengths[i-1] >= 0:
dp[i][j] = max(dp[i-1][j], dp[i][j-available_lengths[i-1]] + price_of_each_length[i-1])
else:
dp[i][j] = dp[i-1][j]
return dp[len(available_lengths)][length_of_the_rod]
if __name__ == '__main__':
print(rod_cutting([1, 2, 3, 4], [2, 5, 7, 8], 5)) |
ebbfafc87bb9510d141faf3f234c9b50caf90824 | nateychau/leetcode | /other/1-4-21.py | 1,301 | 4.28125 | 4 | # Merge Two Sorted Lists
# Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
# Example 1:
# Input: l1 = [1,2,4], l2 = [1,3,4]
# Output: [1,1,2,3,4,4]
# Example 2:
# Input: l1 = [], l2 = []
# Output: []
# Example 3:
# Input: l1 = [], l2 = [0]
# Output: [0]
# Constraints:
# The number of nodes in both lists is in the range [0, 50].
# -100 <= Node.val <= 100
# Both l1 and l2 are sorted in non-decreasing order.
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = current = ListNode()
node_a = l1
node_b = l2
while node_a and node_b:
if node_a.val < node_b.val:
current.next = node_a
node_a = node_a.next
else:
current.next = node_b
node_b = node_b.next
current = current.next
current.next = node_a if node_a else node_b
return dummy.next
|
63dff0106208a17ba810b5f26ae20c7cab3ebfb5 | crileiton/curso_python | /4 Colecciones de datos/2 Conjuntos.py | 2,207 | 3.984375 | 4 | # Son colecciones desordenadas de elementos unicos, se utiliza normalmente para hacer pruebas de pertenencia a
#grupos y eliminaciรณn de elementos duplicados
# Tambien soportan operaciones matematicas avanzadas (posterior)
# Se declara asi...
conjunto = set()
print(conjunto)
# Podemos crear un conjunto con varios elementos tambien si son escritos entre llaves...asi
conjunto = {1,2,3}
print(conjunto)
# Se dice que los conjuntos son desordenados porque a medida que aรฑadimos elementos a un conjunto este orden no se conserva
#como si ocurre con las listas
# Algunos de sus metodos son...
# Metodo add
conjunto.add(4)
print(conjunto)
# Como se puede observar lo aรฑadio al final, pero que pasa si aรฑado un 0, teoricamente se debe aรฑadir al final pero...j
conjunto.add(0)
print(conjunto)
# Como podemos ver se aรฑadio al principio
# Si en lugar de aรฑadir un numero aรฑado una letra o texto
conjunto.add('H')
print(conjunto)
# Se puede observar que primero coloca todos los numeros y luego todas las letras
conjunto.add('A')
print(conjunto)
conjunto.add('Z')
print(conjunto)
# Se logra observar {0, 1, 2, 3, 4, 'A', 'Z', 'H'}
# Una forma de saber si algo existe en un grupo es asi...(como respuesta obtenemos True o False)
grupo ={'cristian','dani','gabo'}
print('dani' in grupo)
# Se puede hacer lo contrario
print('dani' not in grupo)
# Nota: Una caracteristicas de los conjuntos es que no pueden haber elementos repetidos dentro de รฉl.
test ={'cristian','cristian','cristian'}
print(test)
# Se puede observar que unicamente deja un elemento 'cristian'
# Se tiene la siguiente lista
lista = [1,2,3,3,2,1]
print(lista)
# Si transformamos la anterior lista a un conjunto
c = set(lista)
print(c)
# Lo que se puede observar es que se han eliminado los elementos repetidos
# Ahora lo que se puede hacer es convertir nuevamente el conjunto a una lista
lista_5 = list(c)
print(lista_5)
# Y ya tenemos echa la conversion directa, pero se la puede hacer en una linea asi...
miLista = [1,2,3,3,2,1]
miLista = list(set(miLista))
print(miLista)
# Este concepto tambien funciona con cadenas de caracteres asi...
cadena = "Al pan pan y al vino vino"
cadena_conver = set(cadena)
print(cadena_conver)
|
b38f6be24fdb1529b13d64a9fd4a26ffa722676c | Kimbbakar/Uva-Solutions | /Uva 10200/Uva 10200.py | 814 | 3.59375 | 4 | import math
def isPrime2(n):
if n==2 or n==3: return True
if n%2==0 or n<2: return False
l = int(n**0.5)
for i in range(3,l+1,2): # only odd numbers
if n%i==0:
return False
return True
mark = [ [0] for i in range(0,10003) ]
for i in range(10002):
mark[i]=0
for i in range(10001):
if((i*i+i+41)&1):
mark[i] = isPrime2(i*i+i+41);
if i!=0:
mark[i]+=mark[i-1]
def main():
while True:
try:
a, b = map(int, input().split())
except :
break #end of file reached
res = float(mark[b])
if a:
res-=mark[a-1];
res=res/(b-a+1);
res *= 10000;
res = math.floor( res + 0.5 );
res /= 100;
print ('%.2f' % (res) )
main() |
ff98ec227277e100eb37448c95f182f901a00bf2 | earamosb8/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 173 | 3.546875 | 4 | #!/usr/bin/python3
def no_c(my_string):
new_string = ""
for l in my_string:
if l not in "cC":
new_string = new_string + l
return(new_string)
|
9fe9bb01d924f0dd04905b91149bf0f0ed191d05 | faizsh/Assignments-SA | /ASSIGNMENT NUMBER 1/Assignment 1.5.py | 139 | 4.03125 | 4 | x=int (input('Enter the first number:'))
y=int (input('Enter the second number:'))
print('Exponential of the provided number is:',x**y)
|
c3ee6f3307644c6411e251448ac5b048911e6d2d | clara3445/javavara-assignment | /2nd week/3rd week/list_comprehensions.py | 503 | 3.515625 | 4 | x = int(input("Type a natural number: 1"))
y = int(input("Type a natural number: 1"))
z = int(input("Type a natural number: 1"))
n = int(input("Type a natural number: 2"))
answer1 = [[i, j, k] for i in range(0, x + 1) for j in range(0, y + 1) for k in range(0, z + 1)]
answer2 = [[i, j, k] for [i, j, k] in answer1 if i + j + k != n]
print(answer2)
# ์์์์ ์ ๋๋ก ์ถ๋ ฅ๋๋๋ฐ ์์์๋ง ์ถ๋ ฅ๋๋ ๊ฒ ์๋๋ผ, ๊ทธ ์์์ ์์ input์ ๋ฃ์ ๋ด์ฉ๋ ๊ฐ์ด ์ถ๋ ฅ๋ฉ๋๋น.. |
86ab768d14bb26733c98abfd9a4d704af8fa83e0 | liyong1995/pythons | /day03/demo11.py | 1,185 | 3.625 | 4 | if __name__ == '__main__':
klist = [
"good ", "good ", "study",
" good ", "good", "study ",
"good ", " good", " study",
" good ", "good", " study ",
"good ", "good ", "study",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
]
vlist = [
"good ", "good ", "study",
" good ", "good", "study ",
"good ", " good", " study",
" good ", "good", " study ",
"good ", "good ", "study",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
" day ", "day", " up",
]
keylist = [str(i).strip() for i in klist]
valuelist = [str(i).strip() for i in vlist]
kset = set(keylist)
vset = set(valuelist)
kklist = list(kset)
vvlist = list(vset)
print(kset)
print(vset)
ndict = {}
for i in kklist :
ndict[i] = vvlist[kklist.index(i)]
print(ndict)
|
6c271d3559a55ecb8ae0de8fea71f43a73403b85 | Bibin22/pythonpgms | /comprehensions/3.list mul.py | 100 | 3.609375 | 4 | A = ['a', 'b', 'c']
B = [1, 2, 3, 4]
AxB = [(x, y) for x in A for y in B]
for i in AxB:
print(i) |
84389ff242a022cc579f638088767209fe728d87 | indexcardpills/python-labs | /04_conditionals_loops/04_00_star_loop.py | 506 | 4.40625 | 4 | '''
Write a loop that for a number n prints n rows of stars in a triangle shape.
For example if n is 3, you print:
*
**
***
'''
n = 5
numbers = range(6)
for x in numbers:
if x == 1:
print("*")
if x == 2:
print("**")
if x == 3:
print("***")
if x == 4:
print("****")
if x == 5:
print("*****")
#Is there a more efficient way of doing this? Also, the initial n variable on line 13 was already provided
#here in the lab so I didn't take it out.
|
cb48d2e12eb7e209f4c9811552afd3fa95332119 | arsal-imran/python-basics | /all-random-stuff/ASSIGNMNT.py | 1,998 | 3.921875 | 4 | def usrinfo(x,y):
print("Hello " + x + "," + "you are " + str(y) + " years old.")
print("Next year you will be ", str(y+1))
def smallest(x,y,z):
RESULT= min(x,y,z)
return RESULT
def largest(x,y,z):
RESULT= max(x,y,z)
return RESULT
def pwr(x,y):
RESULT= x**y
print(str(x) + " rasie to the power " + str(y) + " is " + str(RESULT))
def add(x,y):
RESULT= x+y
print("The addition of " + str(x) + " and " + str(y) + " is " + str(RESULT))
def sub(x,y):
RESULT= x-y
print("The subtraction of " + str(x) + " and " + str(y) + " is " + str(RESULT))
def mul(x,y):
RESULT= x*y
print("The multiplication of " + str(x) + " and " + str(y) + " is " + str(RESULT))
def div(x,y):
RESULT= x/y
print("The division of " + str(x) + " and " + str(y) + " is " + str(RESULT))
def rem(x,y):
RESULT= x%y
print("The modulus of " + str(x) + " and " + str(y) + " is " + str(RESULT))
def calc(x,y):
add(x,y)
sub(x,y)
mul(x,y)
div(x,y)
pwr(x,y)
rem(x,y)
def cstr(a,b,c,d):
print(a + b + c + d)
def calc_hyp(x,y):
r = ((x**2) + (y**2))**0.5
print ("HYPOTENUSE= " + str(r))
def sqr(x):
SQ= x**2
print (SQ)
print (SQ)
print (SQ)
print (SQ)
#Alternative method
def SQR(x):
SQ= x**2
for n in range (4):
print(SQ)
def ctof(c):
f= (9.0/5.0)*c+32
return f
def ftoc(f):
c= 5.0/9.0*(f-32)
return c
def temp():
x= float(input("Enter temperature in calcius: "))
y= float(input("Enter temperature in fahrenheit: "))
print(ctof(x))
print(ftoc(y))
def dist():
x1= int(input("Enter value for x1: "))
y1= int(input("Enter value for y1: "))
x2= int(input("Enter value for x2: "))
y2= int(input("Enter value for y2: "))
dist= ((x2-x1)**2 + (y2-y1)**2)**0.5
print("The distance between points: " + "(" + str(x1) + "," + str(y1) + ")" + " and " + "(" + str(x2) + "," + str(y2) + ")" + " is " + str(dist))
|
c282c6ea4e2e37968b78a3eb4859dcc8659f6dba | DomomLLL/newpy | /jiaoben/panduan.py | 126 | 3.859375 | 4 | #!usr/bin/share
a = int(input('please input:'))
b = int(a / 2)
if a == 2*b:
print('oushu')
else:
print('jishu')
|
be7b98d039e01793f3ae20bb028cfc2cff91cc3a | armasog/Monty_Hall_Simulation | /main.py | 773 | 3.734375 | 4 | from random import randint, choice
def monty_hall(ignorant=False, iterations=100000):
player_wins = 0
for i in range(iterations+1):
car_door = randint(1, 3)
player_door = randint(1, 3)
remaining_door = 6 - car_door - player_door
if not ignorant:
if player_door != car_door: # Since the player will always switch doors
player_wins += 1
if ignorant:
if player_door != car_door and choice([remaining_door, car_door]) == remaining_door:
player_wins += 1
return float(player_wins / iterations)
print('The player wins {:.1%} in the classic Monty Hall problem and {:.1%} of the time in the ignorant Monty hall problem.'.format(monty_hall(), monty_hall(ignorant=True)))
|
fd7062926456c0d839d363007888b6c1e7cc1991 | jonggukim/Python-for-Trading | /About Python/about function.py | 728 | 3.703125 | 4 | # ํจ์ ๋ง๋ค๊ธฐ
# a3()์ ์ด๋ฆ์ ๊ฐ์ง ํจ์ ๋ง๋ค๊ธฐ - a๋ฅผ 3๋ฒ ์ถ๋ ฅํ๋ ํจ์
def a3():
print('aaa')
a3()
def a4():
return 'bbb'
print(a4()*3)
def a5():
print('before')
return ('ccc') # ํจ์ a5()์ ๊ฒฐ๊ณผ ๊ฐ์ผ๋ก ccc ๋ฅผ ์ ์ฅ. & ํด๋น ํจ์(a5()๋ฅผ ์ข
๋ฃ์ํจ๋ค
# ์ฆ, return ์ดํ์ ๊ตฌ๋ฌธ์ ์คํ๋์ง ์๋๋ค.
print('after') # return๋ค์ ์กด์ฌํ๊ธฐ์ ์คํ ๋์ง ์๋ ๊ตฌ๋ฌธ
print(a5())
# ํจ์์ ์
๋ ฅ๊ฐ ์ ์ฉํ๊ธฐ
def a(num):
print(num)
a(4)
def a_num(num):
return 'a'*num
print(a_num(8))
# ํจ์์ ์ฌ๋ฌ ์
๋ ฅ๊ฐ ์ ์ฉํ๊ธฐ
def make_string(str, num):
return str * num
print(make_string('abc', 5))
|
56d191fdaf63fffa2d54f00a66eace4b6b76e3c9 | eunjins/python | /string/case.py | 151 | 3.90625 | 4 | # upper case & lower case
str_a = "Hello Python Programming...!"
str_upper = str_a.upper()
str_lower = str_a.lower()
print(str_upper)
print(str_lower) |
aa21c287c30a56d1eac965e7b68d3962fdf64dfd | SarathM1/matlab-project | /bw1.py | 260 | 3.5625 | 4 | from PIL import Image
col = Image.open("MARS1.JPG")
gray = col.convert('L') # Converts image to grayscale
bw = gray.point(lambda x: 0 if x<128 else 255, '1') # Uses lambda function to convert image to b&w (128=255/2)
bw.save("bw1_Result.JPG")
bw.show()
|
1dc4a678fb734d4953538876f17f13d2bbe5f045 | Idris01/learn_git | /car.py | 536 | 3.9375 | 4 | class Car:
# set the numbers of Car object created
# count is a class variable and to access it
# within and outside the class use Car.count or
# <Car instance name>.count
count=0
def __init__(self,maker,name,wheel=4):
self.maker=maker
self.wheel=wheel
self.name=name
Car.count+=1
def __del__(self):
Car.count-=1
def __str__(self):
return "%s from %s" % (self.name,self.maker)
@property
def maker(self):
return self.maker
|
e94713275cbba1e3487a6a3f51fe0543e09f2da6 | divyabiyani/Python-Practice- | /2.py | 98 | 3.890625 | 4 | a=input('Enter a no.')
c=float(a) ** 0.5
print('The square root of %0.3f is %0.3f'%(float(a),c)) |
37659d8d5eec95d33aa52d2cfb7dcff5731df579 | RECKLESS6321/Github-Gist-solution | /Excrise 1.py | 160 | 4.09375 | 4 | name = input("What is your name ?:")
age = int(input("What is your age? :"))
age1 = (2020 - age) + 100
print(f"{name} you will turn 100 year old in {age1}.")
|
04e88efd95a534ea4c0e939a397f02547713e143 | EduMeurer999/Algoritmos-Seg- | /78.py | 237 | 3.796875 | 4 | senhaCorreta = "12345"
senha = input('Informe a senha: ')
c=1
while senha != senhaCorreta:
c = c+1
print("Senha invรกlida\n")
senha = input('Informe a senha novamente: ')
print("Vocรช errou a senha "+str(c-1)+" vezes")
|
cc1925d6e04e4c9fd30866be100d4ccca03143a0 | krishna6991/DailyCodingProblem | /DCP-04.py | 704 | 4.15625 | 4 | """
maximum value of each subarray of length k ,
in o(n) time complexity and o(k) space complexity
"""
from collections import deque
def printMaxWindowElement(arr,n,k):
DQ = deque()
max_arr= []
for i in range(k):
while DQ and arr[i] >= arr[DQ[-1]]:
DQ.pop()
DQ.append(i)
for i in range(k,n):
max_arr.append(arr[DQ[0]])
while DQ and DQ[0] <= i-k:
DQ.popleft()
while DQ and arr[i] >=arr[DQ[-1]]:
DQ.pop()
DQ.append(i)
max_arr.append(arr[DQ[0]])
return max_arr
if __name__=="__main__":
arr = [1,2,3,4,2,3,8,6,4,3,7]
k = 3
arr=printMaxWindowElement(arr, len(arr), k)
print(arr)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.