blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
c5b87a3edc367f76c12b0fa2734ee8deafa4b965 | jcbain/fun_side_projects | /unique_digits/unique_digits.py | 1,948 | 4.1875 | 4 | from collections import Counter
def separate_digits(val):
"""
separate the digits of a number in a list of its digits
Parameters
-----
val : int
number to separate out
Returns
-----
list
a list of ints of the digits that make up val
"""
return [int(x) for x in str(val)]
def any_intersection(x,y):
"""
check to see if there are any intersecting values between two lists
Parameters
-----
x : list
first list of values
y : list
second list of values
Returns
-----
bool
True if there is an intersection, False otherwise
"""
inter = set(x).intersection(set(y))
return bool(inter)
def run_exponential(exp,upper_bound = 10000):
"""
finds the values between 0 and an upper bound that contains all unique digits
and shares no digits with its value raised to some exponent
Parameters
-----
exp : int
exponent to raise the values to
upper_bound : int
the upper limit of where the list should stop at
Returns
lists
first list is a list the base values that meet the criteria
second list is a list of the base values that work raised to the exponent
"""
candidates_result = []
candidates_base = []
for i in range(0,upper_bound):
num = i ** exp
compound = str(i) + str(exp)
separate_compound = separate_digits(compound)
separate_num = separate_digits(num)
base_digit_counts = list(Counter(separate_digits(i)).values())
intersection_check = not any_intersection(separate_num,separate_compound)
base_check = not any(i > 1 for i in base_digit_counts)
if intersection_check & base_check:
candidates_result.append(num)
candidates_base.append(i)
return candidates_base,candidates_result
if __name__ == '__main__':
print(run_exponential(6, 1000000000))
|
e3aa84ec0856e98ffabb93f8972e58880e39ca80 | sbjacobs231/Black_Box_Game | /Board.py | 2,326 | 3.71875 | 4 | # Author: Sky Jacobson
# Date: 8/13/20
# Description: Board class has all methods relating to reading and writing to the board.
class Board:
"""
Class representing the different aspects of the board.
It has methods of retrieving the board and printing the board.
This class will be accessed by the BlackBoxGame class.
"""
def __init__(self, atom_locations):
"""
The board will be a 10x10 grid where rows 0 and 9, and columns 0 and 9
are used by the guessing player for shooting rays into the black box.
The atoms are restricted to being within rows 1-8 and columns 1-8
"""
# '' = empty
# 'a' = atom
# 'c' = corner
# 'e' = edge
# 'h' = hit
# 'u' = used edge
self._board = [
['c', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'c'],
['e', '', '', '', '', '', '', '', '', 'e'],
['e', '', '', '', '', '', '', '', '', 'e'],
['e', '', '', '', '', '', '', '', '', 'e'],
['e', '', '', '', '', '', '', '', '', 'e'],
['e', '', '', '', '', '', '', '', '', 'e'],
['e', '', '', '', '', '', '', '', '', 'e'],
['e', '', '', '', '', '', '', '', '', 'e'],
['e', '', '', '', '', '', '', '', '', 'e'],
['c', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'c']
]
self.add_atoms_to_board(atom_locations)
def add_atoms_to_board(self, atoms_locations):
"""
Upon initialization of the board, add atoms to the board
"""
for atom in atoms_locations:
atom_row = atom[0]
atom_column = atom[1]
self._board[atom_row][atom_column] = 'a'
def print_board(self):
"""
Print the board in a nice format.
"""
for row in self._board:
print(row)
def get_board(self):
"""
Get the board
"""
return self._board
def update_tile(self, row, column, char):
"""
Update the tile on the board
"""
self._board[row][column] = char
def is_unused_board_edge(self, row, column):
"""
Player's shot is an edge but not a corner
"""
if self._board[row][column] == 'e':
return True
return False |
802480d75cc45bb911de93e28e8e830b743b4db6 | Mattx2k1/Notes-for-basics | /Basics.py | 2,087 | 4.6875 | 5 | # Hello World
print("Hello World")
print()
# Drawing a shape
# Programming is just giving the computer a set of instructions
print(" /!")
print(" / !")
print(" / !")
print("/___!")
print()
# console is where we have a little window into what our program is doing
# Pyton is looking at these instructions line by line in order
# The order in which we write the instructions is very important. It matters a lot
# Variables and Data Types
# In python we'll be dealing with a lot of data, values and information
# That data can be difficult to manage
# A variable is a container where we can store certain data values, and when we use variables it's a lot easier to work with and manage the information in our programs.
# Let's start with this story
print("There once was a man named George, ")
print("he was 70 years old. ")
print("He really liked the name George, ")
print("but didn't like being 70.")
print()
# Let's say we wanted to change the name in the story from George to John, or change the age, we'd have to do it line by line. Except we have Variables which make it easier for us:
#variable_name
character_name = "John"
character_age = "35"
#Now we can just add in the variables in the story
print("There once was a man named " + character_name + ", ")
print("he was " + character_age + " years old. ")
print("He really liked the name George, ")
print("but didn't like being " + character_age + ".")
# Now all you would have to do is change the variables to update many lines in the story.
# We can update the variable simply writing it out again
character_name = "Tom"
print("There once was a man named " + character_name + ", ")
print("he was " + character_age + " years old. ")
print("He really liked the name George, ")
print("but didn't like being " + character_age + ".")
# We are storing these names as strings
# Strings are plain text
# Can store numbers, don't use quotations
character_age = 35 # can store whole numbers
character age = 35.5 # can store decimal numbers
# Boolean returns true or false values. Example:
is_male = False
|
cdd823dbe94b600742ba2158e50f516446aba57e | Mattx2k1/Notes-for-basics | /Try Except.py | 1,072 | 4.53125 | 5 | # Try Except
# Catching errors
# Anticipate errors and handle them when they occur. That way errors don't bring our program to a crashing halt
number = int(input("Enter a number: "))
print(number)
# if you enter a non number, it will cause the program to crash. So you need to be able to handle the exceptions
# Try except block is what is used for this
try:
number = int(input("Enter a number: "))
print(number)
except:
print("Invalid input")
# Specify the type of error you want to catch with this format for except:
try:
value = 10 / 0
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError:
print("Divided by zero")
except ValueError:
print("Invalid input")
# store error as a variable:
try:
value = 10 / 0
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError as err:
print("err")
except ValueError:
print("Invalid input")
# A best practice is to set up for catching specific errors. "Except:" by itself is too broad and may break your program on it's own |
0896dad37cd3b5d93a60fb30672ccd902fcdc337 | Mattx2k1/Notes-for-basics | /Guessing Game.py | 564 | 4.25 | 4 | # guessing game
# start with the variables
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
# use a while loop to continually guess the word until they get it correct
# added in the "and not" condition, and new variables to create a limit on guesses
while guess != secret_word and not (out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("Out of guesses, YOU LOSE!")
else:
print("You win!") |
c291411a49d3b4359018649b8687df61d5ce21bc | Gogapain/Programming | /Practice/03/Phyton/333.py | 340 | 3.78125 | 4 | print ("Введите первое число")
a = int(input())
print ("Введите второе число")
b = int(input())
print ("Сложение")
c = a + b
print(c)
print ("Умножение")
d = a * b
print(d)
print ("Вычитание")
f = a - b
print(f)
print ("Деление")
j = a / b
print(j)
|
8431b32905986952c2270139068ab52b5620e2e8 | asyrul21/recode-live | /gibberish.py | 146 | 3.546875 | 4 |
def factorial(number):
# set a base condition
if(number == 0 or number == 1):
return 1
# call itself
return ?
|
05dbb92432de2d6c6abf4440096b46703959c665 | TrevorJackson1/saoroleplay | /viewmobs.py | 662 | 3.5625 | 4 | import sqlite3
try:
sqliteConnection = sqlite3.connect('mobspawn.db')
cursor = sqliteConnection.cursor()
print("Successfully Connected to SQLite")
sqlite_insert_query = """select * from Location"""
count = cursor.execute(sqlite_insert_query)
sqliteConnection.commit()
print("Record inserted successfully into SqliteDb_developers table ", cursor.rowcount)
print(count.fetchall())
cursor.close()
except sqlite3.Error as error:
print("Failed to insert data into sqlite table", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
|
5284bda9251b8da6fe08e0c44d2721e87738e3ad | samsonwang/ToyPython | /PlayGround/26TicTacToe/draw_pattern.py | 1,813 | 4.34375 | 4 | #! /usr/bin/python3.6
'''
Tic Tac Toe Draw
https://www.practicepython.org/exercise/2015/11/26/27-tic-tac-toe-draw.html
- For this exercise, assume that player 1 (the first player to move) will always be X and player 2 (the second player) will always be O.
- Notice how in the example I gave coordinates for where I want to move starting from (1, 1) instead of (0, 0). To people who don’t program, starting to count at 0 is a strange concept, so it is better for the user experience if the row counts and column counts start at 1. This is not required, but whichever way you choose to implement this, it should be explained to the player.
- Ask the user to enter coordinates in the form “row,col” - a number, then a comma, then a number. Then you can use your Python skills to figure out which row and column they want their piece to be in.
- Don’t worry about checking whether someone won the game, but if a player tries to put a piece in a game position where there already is another piece, do not allow the piece to go there.
'''
import logging
# get cordinate and return a tuple
def get_player_input(str_player):
log = logging.getLogger("root")
str_cordinates = input("%s, which col and row? " % str_player)
log.debug("%s, input: %s" % (str_player, str_cordinates) )
list_cord = str_cordinates.strip().split(',')
return tuple(list_cord)
def tic_tac_toe_game():
log = logging.getLogger("root")
print("Welcome to tic tac toe")
tup_p1 = get_player_input("Player 1")
log.debug("Player 1: %s" % (tup_p1, ))
def main():
logger = logging.getLogger("root")
FORMAT = "%(filename)s:%(lineno)s %(funcName)s() %(message)s"
logging.basicConfig(format=FORMAT)
logger.setLevel(logging.DEBUG)
tic_tac_toe_game()
if __name__ == '__main__':
main()
|
d513ffbff8feeeb5420c90ad2f1406de501696b0 | samsonwang/ToyPython | /PlayGround/01DiceSimulator/01DiceSimulator.py | 602 | 3.953125 | 4 |
'''
dice simulator
author: Samson Wang
data: 2018-04-16
'''
import random
# 最大最小值
num_min = 1
num_max = 6
is_need_exit = False
while not is_need_exit :
print("==dice simulator==")
print("dice is rolling!\n min=%d, max=%d" % (num_min, num_max))
num_rand = random.randint(num_min, num_max)
print(" rand number", num_rand)
# ask whether next roll is needed
while True:
answer = input("roll dice again? (y/n): ")
if (answer == "n") :
is_need_exit = True
break;
elif (answer == "y") :
is_need_exit = False
break;
else :
print("please input \"y\" or \"n\" !!")
|
83b4a6df6bd9e5c2ec00c587a0f72e4877a4f81d | arun-p12/project-euler | /p0001_p0050/p0043.py | 1,226 | 3.6875 | 4 | '''
In 1406357289 (a 0 to 9 pandigital number), 406 (digits 2, 3, and 4) is divisible by 2.
063 (digits 3, 4, and 5) is divisible by 3, 635 (digits 4, 5, 6) is divisible by 5, etc.
The last set, 289 (digits 8, 9, and 10) is divisible by 17.
To find the sum of all 0-9 pandigital numbers with this property.
'''
def substring_divisibility():
import sys
sys.path.append('../')
import common as c
pand_list = c.permutation_numbers('9876543210')
#pand_list = ['1406357289']
primes = ['', 2, 3, 5, 7, 11, 13, 17]
(sum, result) = (0, [])
for p in pand_list:
(i, ok) = (1, True)
while(ok and (i < 8)):
# pick the 3-digit substring
if(int(p[i:i+3:]) % primes[i]): ok = False
i += 1
if(ok):
result.append(p)
sum += int(p)
print("sum = ", sum, result)
import time # get a sense of the time taken
t = time.time() # get time just before the main routine
########## the main routine #############
substring_divisibility()
########## end of main routine ###########
t = time.time() - t # and now, after the routine
print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t*1_000_000))
|
5521559091299b2af7b6c72fa20cea4dcffe9a03 | arun-p12/project-euler | /p0001_p0050/p0025.py | 1,056 | 4.125 | 4 | '''
In a Fibonacci series 1, 1, 2, 3, 5, 8, ... the first 2-digit number (13) is the 7th term.
Likewise the first 3-digit number (144) is the 12th term.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
'''
def n_digit_fibonacci(number):
digits = 1
fibonacci = [1, 1]
while(digits < number):
fibonacci.append(fibonacci[-1] + fibonacci[-2]) # next term = sum of last two terms
digits = len(str(fibonacci[-1])) # how many digits in the new term?
if(digits >= number): # is it the required length
print("fibonacci = ", len(fibonacci))
return(0)
import time # get a sense of the time taken
t = time.time() # get time just before the main routine
########## the main routine #############
number = 1000
n_digit_fibonacci(number)
########## end of main routine ###########
t = time.time() - t # and now, after the routine
print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t*1_000_000))
|
154cf1ad66e4d8fab9b523676935b615ef831d3d | arun-p12/project-euler | /p0001_p0050/p0038.py | 2,093 | 4.125 | 4 | '''
192 x 1 = 192 ; 192 x 2 = 384 ; 192 x 3 576
str(192) + str(384) + str(576) = '192384576' which is a 1-9 pandigital number.
What is the largest 1 to 9 pandigital 9-digit number that can be formed as the
concatenated product of an integer with (2, ... , n) digits?
Essentially n > 1 to rule out 918273645 (formed by 9x1 9x2 9x3 ...)
'''
'''
Cycle thru each number, get the multiples, and keep appending the string of numbers.
When length of the string goes above 9, move onto the next number.
If the length of the string is 9, check if it is pandigital. If yes, check if it is maximum
'''
def pandigital_multiple():
target = [1, 2, 3, 4, 5, 6, 7, 8, 9]
max_str = ""
#for x in range(9876, 0, -1): # start from top, and decrement
for x in range(1, 9877):
i, pand_len = 1, 0
pand_list = [] # sort and test against target
pand_str = "" # this is our actual string
while (pand_len < 9):
next_num = x * i # take each number, and multiply by the next i
pand_str += str(next_num)
for c in str(next_num): # append new number to our list
pand_list.append(int(c))
pand_len = len(pand_list)
i += 1
#print("test : ", x, pand_len, i, pand_list, pand_str, pand_cont)
if pand_len == 9:
pand_list.sort()
if pand_list == target:
if(pand_str > max_str): max_str = pand_str
print("start_num = ", "{:4d}".format(x),
"mult_upto = ", "{:1d}".format(i - 1),
"result = ", "{:10s}".format(pand_str),
"max = ", "{:10s}".format(max_str))
import time # get a sense of the time taken
t = time.time() # get time just before the main routine
########## the main routine #############
pandigital_multiple()
########## end of main routine ###########
t = time.time() - t # and now, after the routine
print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t*1_000_000))
|
77f747af457b9369b29af4eeea70e270b1eec04d | arun-p12/project-euler | /p0051_p0100/p0058.py | 1,530 | 3.875 | 4 | '''
Starting from the center, the diagonals are the four corners of a sqaure, and in
crement by 2n.
The center point is a 1x1 square, the next is a 2x2, and so on. Thus, the corners of a 4x4
square would increment by 2x4 = 8, and the diagonals would follow a pattern of
1, 3,5,7,9, 13,17,21,25, 31,37,43,49, 57,65,73,81, ...
'''
def spiral_primes(num=50001):
import sys
sys.path.append('../')
import common as c
# number of primes found, iteration number, corner values
cnt, i, adder, corner, ok = 0, 0, 0, 1, True
while(ok):
i += 1
adder += 2 # keeps increasing by 2, 4, 6, 8, ...
for j in range(4):
corner += adder
if (c.is_prime(corner)): cnt += 1 # keep tab of the primes
prime_ratio = (cnt * 100) / (i * 4 + 1)
if (prime_ratio < 10): # exit condition met?
print("side = ", 2*i + 1, "[[ ", i, cnt, i * 4 + 1,
"{:10.7f}".format((cnt * 100) / (i * 4 + 1)), " ]]")
ok = False
#print("side = ", 2*i + 1, " [[ ", i, cnt, i * 4 + 1, "{:10.7f}".format(prime_ratio, " ]]"))
import time # get a sense of the time taken
t = time.time() # get time just before the main routine
########## the main routine #############
spiral_primes()
########## end of main routine ###########
t = time.time() - t # and now, after the routine
print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t * 1_000_000))
|
4161a7c9e8861f47152e6c307c4717803824db80 | arun-p12/project-euler | /p0051_p0100/p0097.py | 729 | 3.578125 | 4 | '''
2**6972593 −1 is the first known prime number with over one million digits. Such prime numbers of
the form 2**p - 1 are called Mersenne primes.
What are the last ten digits of 28433(2**7830457)+1 ... a non-Mersenne prime.
'''
def large_non_mersenne_prime(digits=10):
print("last 10 digits = ", ((28433*(2**7830457 % (10**digits))) + 1) % (10**digits) )
import time # get a sense of the time taken
t = time.time() # get time just before the main routine
########## the main routine #############
large_non_mersenne_prime()
########## end of main routine ###########
t = time.time() - t # and now, after the routine
print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t * 1_000_000))
|
4b2acbf02454ae23294d59f96ed2ea5325fb3b2b | arun-p12/project-euler | /p0051_p0100/p0053.py | 1,255 | 3.71875 | 4 | '''
For values of n <= 100, how many combinations of nCr produces a value greater than 1,000,000
'''
def combinatoric_selection():
def ncr(n, r):
import math
return (math.factorial(n) / (math.factorial(r) * math.factorial(n - r)))
'''
nCr values for a Pascal's triangle ... 1; 1 1; 1 2 1; 1 3 3 1; 1 4 6 4 1; 1 5 10 10 5 1; etc
Thus nCr = (n-1)C(r-1) + (n-1)Cr
Code might look neat ... but, slow as hell ... due to exponential increase in # of calls
'''
def ncr_recursive(n, r):
if ((r == 0) or (n == 0)): return (1)
return (ncr_recursive(n - 1, r - 1) + ncr_recursive(n - 1, r))
target, result = 1000000, {}
for n in range(101):
for r in range(n):
val = ncr(n, r)
# print(n, r, val)
if (val > target): result[str(n) + "C" + str(r)] = val
print("count = ", len(result))
import time # get a sense of the time taken
t = time.time() # get time just before the main routine
########## the main routine #############
combinatoric_selection()
########## end of main routine ###########
t = time.time() - t # and now, after the routine
print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t * 1_000_000))
|
a2e760d49f973f472f2de9051e24d9003ac9341c | arun-p12/project-euler | /p0001_p0050/p0046.py | 1,503 | 3.90625 | 4 | '''
The smallest odd composite number that cannot be represented as the sum of a prime
and twice a square. E.g. 9 = 7 + 2(1**2) ; 27 = 19 + 2(2**2)
Originally had maintained the list of 2x^2; and then check if for every i, if
the (odd_composite - i) is in that lis. This logic took about 7s to execute.
Modified logic to compute the value of x, and if it is an integer value. [[ from OC = P + 2x^2 ]]
This reduced the execution time to 100ms!!!
'''
def goldbachs_conjecture():
num = 6000
primes = ['P'] * num
primes[0] = primes [1] = primes[2] = 'I'
for i in range(2, num):
mult = 2
while(i * mult < num):
if(primes[i]): primes[i * mult] = 'C'
mult += 1
import math
odd_comp = [i for i in range(num) if((i % 2) and (primes[i] == 'C'))]
for oc in odd_comp:
i, found = 1, False
while(i < oc):
root = math.sqrt((oc - i)/2)
if ((primes[i] == 'P') and (root == int(root))):
i = oc
found = True
i += 2
if(found == False):
print("odd composite = ", oc)
return(0)
import time # get a sense of the time taken
t = time.time() # get time just before the main routine
########## the main routine #############
goldbachs_conjecture()
########## end of main routine ###########
t = time.time() - t # and now, after the routine
print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t*1_000_000))
|
4cbef49ee1fd1c6b4a15eae4d2dee12be49475a8 | arun-p12/project-euler | /p0001_p0050/p0017.py | 2,376 | 4.125 | 4 | '''
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then
there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words,
how many letters would be used? Ignore spaces
'''
def number_letter_count(number=1000):
# number of letters in the word form, for each value
dict = {0:0, 1:3, 2:3, 3:5, 4:4, 5:4, 6:3, 7:5, 8:5, 9:4,
10:3, 11:6, 12:6, 13:8, 14:8, 15:7, 16:7, 17:9, 18:8, 19:8,
20:6, 30:6, 40:5, 50:5, 60:5, 70:7, 80:6, 90:6,
100:7, 1000:8, 'and':3}
# numeric representation of the word
dict2 = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five',
6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten',
11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen',
16:'sixteen', 17:'seventeen', 18:'eighteen', 19:'nineteen',
20:'twenty', 30:'thirty', 40:'forty', 50:'fifty',
60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety',
100:'hundred', 1000:'thousand', 'and':'and', 0:''}
def word_filler(word):
if(word): return(' ')
else: return('')
word = ''
while(number):
t = number // 1000
h = (number - t*1000) // 100
d = (number - t*1000 - h*100) // 10
u = int(number - t*1000 - h*100 - d*10)
if(t): word += dict2[t] + ' ' + dict2[1000]
if(h): word += word_filler(word) + dict2[h] + ' ' + dict2[100]
if(((t | h) > 0) & ((d | u) > 0)): word += word_filler(word) + dict2['and']
if(d >= 2): word += word_filler(word) + dict2[d*10]
if(d == 1): word += word_filler(word) + dict2[d*10 + u]
else: word += word_filler(word) + dict2[u]
number -= 1
#print("nlc_2 = ", num, "[[ ", t, h, d, u, word, " ]]")
w_len = [len(x) for x in word.split()]
return(sum(w_len))
import time # get a sense of the time taken
t = time.time() # get time just before the main routine
########## the main routine #############
num = 1000
result = number_letter_count(num)
########## end of main routine ###########
t = time.time() - t # and now, after the routine
print("Letter count in numbers upto {} = {}".format(num, result))
print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t*1_000_000))
|
1b7220240760b68c282dadd3f1f68c38e276421c | James-Lee1/Unit_3-03 | /rock_paper_scissors.py | 1,073 | 3.65625 | 4 | # coding: utf-8
import ui
import random
box = ['Rock', 'Paper', 'Scissors']
global user_picked
def rock_paper_scissors_touch_up_inside(sender):
if sender.name == "rock_button":
user_picked = 'Rock'
view['user_pick_label'].text = 'You picked Rock'
elif sender.name == "paper_button":
user_picked = 'Paper'
view['user_pick_label'].text = 'You picked paper'
elif sender.name == "scissors_button":
user_picked = 'Scissors'
view['user_pick_label'].text = 'You picked scissors'
random_number = random.randint(0, 2)
view['computer_answer'].text = 'The computer picked ' + str(box[random_number])
if user_picked == 'Rock' and box[random_number] == 'Scissors' or user_picked == 'Paper' and box[random_number] == 'Rock' or user_picked == 'Scissors' and box[random_number] == 'Paper':
view['answer_label'].text = "You win this round!"
elif user_picked == box[random_number]:
view['answer_label'].text = "Its a tie!"
else:
view['answer_label'].text = "You lost this round!"
view = ui.load_view()
view.present('full_screen')
|
98013899a93003177c9962f71beb435dad8d755f | ibrahima99/projet_ap2_ibra | /probleme 1/Probleme2.py | 3,185 | 3.75 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
:mod:`Probleme1` module
:author:Arnaud Kaderi, Elhadj Ibrahima BAH, Aboubakar Siriki DIAKITE
:date: 2019, october
:last revision: 2019, october
"""
from random import*
from Individual1 import*
from math import*
class Problem_interface():
def __init__(self, x_min, x_max):
self.__x_min = x_min
self.__x_max = x_max
def get_x_min(self):
return self.__x_min
def get_x_max(self):
return self.__x_max
def best_individual(self,population):
"""
return the best fitted individual from population. Depending on the problem, it can correspond to the individual with the highest or the lowest fitness value.
:param population: list(Individual) the list of individuals to sort.
:rtype: an Individuals to sort.
:return: the best fitted individual of population.
"""
return population[-1].get_value()
def create_individual(self):
"""
create a randomly generated indidivual for this problem.
:rtype: an Individual object.
:return: a randomly generated individual for this problem.
"""
individual = Individual_Interface(12)
individual.init_value()
return individual
def evaluate_fitness(self,individual):
"""
compute the fitness of individual for this problem.
:param individual: (an Individual object) - the individual to consider.
:rtype: an Individual object
:return: the fitness of individual for this problem
"""
sum = 0
for i in range(len(individual.get_value())):
sum +=
def sort_population(self,population):
"""
sort population from best fitted to worst fitted individuals. Depending on the problem, it can correspond to ascending or descending order with respect to the fitness function.
:param population: (list(Individual)) - the list of individuals to sort.
side effecrt: population is modified by this method.
"""
population.sort(key = lambda individual: individual.get_value())
def tournament(self,first,second):
"""
perform a tounament between two individuals, the winner is the most fitted one, it is returned.
:param first: (an Individual object) - an individual.
:param second: (an Individual object) - an individual.
rtype: Individual object
:return: the winner of the tournament
"""
if self.evaluate_fitness(first) > self.evaluate_fitness(second):
return first
else:
return second
def average_population(self,population):
"""
calculate the average population for the generation concerned
:param population:
:rtype: (int)(list(Individual)) - the list of individuals
:return: the average of the individuals according to the problem
"""
add = 0
average = 0
for e in population:
for gene in e:
add += gene
average = add/len(population)
return average
|
343749f699d3ab58b87183db7ff4f7c01194defc | rustamhse/pythonstudy | /second_program.py | 189 | 3.546875 | 4 | A = int(input('Введите A >> '))
B = int(input('Введите B >> '))
for i in range(A, B + 1):
if (i // 1000) == i % 10 and (i // 100) % 10 == (i // 10) % 10:
print(i)
|
923db06933c29ae9f9c526ce5f8289506efebf8f | novdima1/TAU-intro-selenium-1 | /tests/test_search.py | 1,167 | 3.75 | 4 | """
These tests cover DuckDuckGo searches.
Run: F:\Дима\_IT Info\tau-selenium-pytest\tau-intro-selenium-py-1>python -m pytest -n 2
"""
import pytest
from pages.search import DuckDuckGoSearchPage
from pages.result import DuckDuckGoResultPage
# Pytest parametrization — passing multiple data-items to a single test
PHRASE = [('leo', 'pard'), ('li', 'on')]
@pytest.mark.parametrize('phrase1, phrase2', PHRASE)
def test_basic_duckduckgo_search(browser, phrase1, phrase2):
search_page = DuckDuckGoSearchPage(browser)
result_page = DuckDuckGoResultPage(browser)
phrase = phrase1 + phrase2
# Given the DuckDuckGo home page is displayed
search_page.load()
# When the user searches for "panda"
search_page.search(phrase)
# Then the search result title contains "panda"
assert phrase in result_page.title()
# And the search result query is "panda"
assert phrase == result_page.search_input_value()
# And the search result links pertain to "panda"
titles = result_page.result_link_titles()
matches = [t for t in titles if phrase.lower() in t.lower()]
assert len(matches) > 0
result_page.print_info() |
c891fec31546ed93374bc833e0bb4870c7e3e188 | rmrodge/python_practice | /format_floating_point_in_string.py | 800 | 4.4375 | 4 | # Floating point number is required in programming for generating fractional numbers,
# and sometimes it requires formatting the floating-point number for programming purposes.
# There are many ways to exist in python to format the floating-point number.
# String formatting and string interpolation are used in the following script to format a floating-point number. format() method with format width is used in string formatting,
# and ‘%” symbol with the format with width is used in string interpolation.
# According to the formatting width, 5 digits are set before the decimal point, and 2 digits are set after the decimal point.
# Use of String Formatting
float1 = 563.78453
print("{:5.2f}".format(float1))
# Use of String Interpolation
float2 = 563.78453
print("%5.2f" % float2)
|
ee8b15b4515267f7742a2f0721f594e721cf7e0c | iOSDevD/EMR_System | /model/Patient.py | 12,580 | 3.96875 | 4 | """
Nikunj Upadhyay
Class: CS 521 - Fall 1
Date: 10/16/2021
Homework Problem # Project
Description of Problem (1-2 sentence summary in your own words):
Patient object which represents columns in the CSV. For example `Patient Id`
is re-presented by attribute `self.__patient_id`.
"""
import copy
from utilities.AppConstants import AppConstants
from utilities.Questionnaire import Questionnaire
class Patient:
"""Patient object which can be created from a list. List of entries
can be obtained from a CSV. For new patient it is created with
default list"""
def __init__(self, details_list=AppConstants().get_empty_data_template()):
"""Patient object Initializer which takes in list representation
of patient data in CSV. If there are mismatch between the
column count in the list, it will default to empty elements as the
provided values ["First Value","Second Value"] could be data
pertaining to any column of CSV. It helps to avoid ValueError while
unpacking the values."""
if len(details_list) != AppConstants.MAX_COLUMN_COUNT:
details_list = AppConstants().get_empty_data_template()
(self.__patient_id, self.__first_name, self.__last_name, self.__dob,
self.__gender, self.__address_line_1, self.__address_line_2,
self.__city, self.__state, self.__zip,
self.__phone, self.__email, self.__questionnaire) = list(details_list)
def get_patient_id(self):
"""Get the patient Id.
CSV column: Patient Id"""
return self.__patient_id
def get_first_name(self):
"""Get the first name of the patient.
CSV column: First Name"""
return self.__first_name
def get_last_name(self):
"""Get the last name of the patient.
CSV column: Last Name"""
return self.__last_name
def get_dob(self):
"""Get the date of birth of the patient.
CSV column: Date of Birth"""
return self.__dob
def get_gender(self):
"""Get the gender of the patient ex: Female, Male or Other.
CSV column: Gender"""
return self.__gender
def get_address_line_1(self):
"""Get the address line 1 of the patient.
CSV column: Address 1"""
return self.__address_line_1
def get_address_line_2(self):
"""Get the address line 2 of the patient.
CSV column: Address 2"""
return self.__address_line_2
def get_address_city(self):
"""Get the address city of the patient.
CSV column: City"""
return self.__city
def get_address_state(self):
"""Get the address state of the patient.
CSV column: State"""
return self.__state
def get_address_zip(self):
"""Get the address zip of the patient.
CSV column: Zip"""
return self.__zip
def get_phone(self):
"""Get the contact phone number of the patient.
CSV column: Phone"""
return self.__phone
def get__questionnaire(self):
"""Get the questionnaire string which is saved in CSV column. For
list representation use get_questionnaire_as_list()."""
return self.__questionnaire
def get_email(self):
"""Get the email-id of the patient.
CSV column: email"""
return self.__email
def set_patient_id(self, patient_id):
"""Set the patient id of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: Patient Id"""
self.__patient_id = patient_id
def set_first_name(self, first_name):
"""Set the first name of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: First Name"""
self.__first_name = first_name
def set_last_name(self, last_name):
"""Set the last name of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: Last Name"""
self.__last_name = last_name
def set_dob(self, dob):
"""Set the Date of birth of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: Date of Birth"""
self.__dob = dob
def set_gender(self, gender):
"""Set the gender of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: Gender"""
self.__gender = gender
def set_address_line_1(self, address_line_1):
"""Set the address line 1 of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: Address 1"""
self.__address_line_1 = address_line_1
def set_address_line_2(self, address_line_2):
"""Set the address line 2 of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: Address 2"""
self.__address_line_2 = address_line_2
def set_address_city(self, city):
"""Set the city of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: City"""
self.__city = city
def set_address_state(self, state):
"""Set the state of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: State"""
self.__state = state
def set_address_zip(self, address_zip):
"""Set the zip of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: Zip"""
self.__zip = address_zip
def set_phone(self, phone):
"""Set the phone of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: Phone"""
self.__phone = phone
def set_email(self, email):
"""Set the email of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: email"""
self.__email = email
def set_questionnaire(self, questionnaire):
"""Set the questionnaire of the patient. Usually for new patient this
property is set before saving to the CSV.
CSV column: Questionnaire"""
self.__questionnaire = questionnaire
def get_questionnaire_as_list(self):
"""Converts the questionnaire from string representation of list
like '[1,1,0,1]' to the actual list of integer values. In case of
error expect None.
CSV column: Questionnaire"""
try:
return eval(self.__questionnaire)
except SyntaxError:
return None
def get_list_template_to_save(self):
"""Creates a template list to be saved into CSV from the current
state of the patient object."""
# New patient would not have questionnaires answered
if len(self.__questionnaire) == 0: # Default each question to skipped
self.__questionnaire = Questionnaire(). \
get_default_questionnaire_answers()
template_list = [self.__patient_id,
self.__first_name,
self.__last_name,
self.__dob,
self.__gender,
self.__address_line_1,
self.__address_line_2,
self.__city,
self.__state,
self.__zip,
self.__phone,
self.__email,
self.__questionnaire]
return template_list
def __repr__(self):
""" Repr magic method here is can be used to print the details of the
object. Since __str__ is not available, during print of the object
value it will call __repr__ method."""
pretty_print_data_list = list() # Empty List to append strings
# Add patient id to the pretty print list
pretty_print_data_list.append(
"Patient ID: {}".format(self.get_patient_id()))
# Add DOB to the pretty print list
pretty_print_data_list.append(
"Date of Birth: {}".format(self.get_dob()))
# Add name to the pretty print list
pretty_print_data_list.append("Name: {},{}".format(
self.get_last_name(),
self.get_first_name()))
# Add address details to the pretty print list
pretty_print_data_list.append("Address:\n{},{},\n{},{}-{}".format(
self.get_address_line_1(),
self.get_address_line_2(),
self.get_address_city(),
self.get_address_state(),
self.get_address_zip()))
# Add contact details to the pretty print list
pretty_print_data_list.append(
"Contact Details:\nPhone {}\nEmail {}".format(
self.get_phone(),
self.get_email()))
# Join the list with new line character
pretty_print_str = "\n".join(pretty_print_data_list)
return pretty_print_str # Return the pretty print string
def __eq__(self, other):
"""Equality magic method helps to identify if two instance of Patient
object are equal in value. It can be used to identify the difference
between before and after patient object update changes, if there are
no changes value wise , we can skip to the CSV there by avoiding
one extra save operation."""
return (self.__patient_id == other.get_patient_id() and
self.__first_name == other.get_first_name() and
self.__last_name == other.get_last_name() and
self.__dob == other.get_dob() and
self.__gender == other.get_gender() and
self.__address_line_1 == other.get_address_line_1() and
self.__address_line_2 == other.get_address_line_2() and
self.__city == other.get_address_city() and
self.__state == other.get_address_state() and
self.__zip == other.get_address_zip() and
self.__phone == other.get_phone() and
self.__email == other.get_email() and
self.__questionnaire == other.get__questionnaire())
# Unit Tests
if __name__ == "__main__":
print("Started Executing test case in Patient")
# Patient content in list, use to create patient object.
patient_content_as_list = ["99", "Harry", "Smith", "10/09/1999", "Male",
"1 Home Drive", "Apt 2", "Boston", "MA", "02115",
"100-1000-2200", "harry@bu.edu", "[1,0,0,1]"]
# 1. Test patient object created from the list is correct or not.
patient = Patient(patient_content_as_list)
assert patient.get_patient_id() == "99" and \
patient.get_first_name() == "Harry" and \
patient.get_last_name() == "Smith" and \
patient.get_dob() == "10/09/1999" and \
patient.get_gender() == "Male" and \
patient.get_address_line_1() == "1 Home Drive" and \
patient.get_address_line_2() == "Apt 2" and \
patient.get_address_city() == "Boston" and \
patient.get_phone() == "100-1000-2200" and \
patient.get_email() == "harry@bu.edu" and \
patient.get_questionnaire_as_list() == [1, 0, 0, 1], (
"Patient object created from the content as list should "
"match with the content in the list.")
# 2. Test copy of patient should match, with "==" i.e check
# magic method __eq__() is working fine.
new_patient = copy.copy(patient)
assert new_patient == patient, (
"Copy of new patient created should match as there is no change")
# 3. Test after update the patient object should not match.
new_patient.set_address_line_1("Test Address change")
assert new_patient != patient, (
"After update patient object should not, values are different.")
# 4. Test patient object when LHS and RHS count of values don't match
patient_mismatch_content_list = ["1",
"John"] # Only 2, required 13 by class
empty_patient = Patient()
assert Patient(patient_mismatch_content_list) == empty_patient, (
"Patient object creation should not fail, it "
"should default to empty template list and sho should match with "
"patient that has no detail")
print("Success! Completed Executing test case in Patient")
|
66d3bd16816f657948253919015033a89e499f2b | iOSDevD/EMR_System | /utilities/LoginUserValidation.py | 3,544 | 4.3125 | 4 | """
Nikunj Upadhyay
Class: CS 521 - Fall 1
Date: 10/16/2021
Homework Problem # Project
Description of Problem (1-2 sentence summary in your own words):
The program illustrate that it has functions which can be used
to validate the user name and password.
"""
from utilities.AppConstants import LoginConstants
def is_logged_in_user_valid(user_name, password):
""" Function that validates if the user entered correct user name
and password. User name is case insensitive and password is case sensitive.
"""
if user_name.upper() == "HELLO" and password == "World":
return True # User input matches user name and password.
else:
return False # User input does not match user name and password.s
def perform_credential_validation(user_name_password):
"""Function that helps to perform the validation of the string containing
username and password separated by space.
Returns a tuple (Boolean, Message), the value is True if the username
and password is correct along with success message. It will return false
if the input is invalid along with the error message.
"""
is_user_valid = False # Logged in user valid flag
validation_message = "" # Error! user name and password entry.
try:
# Use default white space delimiter.
user_name_str, password_str = user_name_password.split()
# perform user name and password validation.
is_user_valid = is_logged_in_user_valid(user_name_str, password_str)
if is_user_valid: # User valid - Success
validation_message = LoginConstants.EMR_LOGIN_SUCCESS_MESSAGE
else: # User in-valid - Failure.
validation_message = \
LoginConstants.EMR_LOGIN_INVALID_CREDENTIALS_MESSAGE
except ValueError: # Error thrown in case there is no white space.
validation_message = LoginConstants.CREDENTIAL_USER_ENTRY_ERROR_MESSAGE
return is_user_valid, validation_message # Tuple - validation and message
# Unit Tests
if __name__ == "__main__":
# help to run test case efficiently.
print("Started Executing test case for functions in LoginUserValidation")
# 1. Test case check if user name and password are correct.
assert is_logged_in_user_valid("hello", "World"), (
"User name and password are valid so it should not fail.")
# Invalid password returns False.
assert is_logged_in_user_valid("hello", "test") is False, (
"User name and password are in-valid so it should fail.")
# Test user name and password string is not separated by space.
validation_result_failure = perform_credential_validation("HelloWorld")
assert validation_result_failure[0] is False and \
validation_result_failure[1] == \
LoginConstants.CREDENTIAL_USER_ENTRY_ERROR_MESSAGE, (
"As user name and password are not whitespace separated "
"or some error occurred, it should return appropriate error message.")
# Test user name and password string separated by space but does match
# with the record in the system".
validation_result_invalid_credential = \
perform_credential_validation("Hello test")
assert validation_result_invalid_credential[0] is False and \
validation_result_invalid_credential[1] == \
LoginConstants.EMR_LOGIN_INVALID_CREDENTIALS_MESSAGE, (
"User entered wrong user name or password the method should "
"return fail")
print("Success! Completed Executing test case in LoginUserValidation")
|
f7d17b2ecf5cb69aa2aa8d4f4f9042fe8ed3d471 | BuringSky/Breaking-Captchas-with-a-CNN | /utils/cnnhelper.py | 611 | 3.59375 | 4 | import matplotlib.pyplot as plt
import numpy as np
def plotHistory(H, numEpochs):
# plot the training loss and accuracy
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, numEpochs), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, numEpochs), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, numEpochs), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, numEpochs), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.show() |
6f4ffe18454ea3a2fcda85afde322bdda9f99861 | Lyunchenko/Game_of_Life | /generation.py | 1,757 | 3.546875 | 4 |
class Generation:
def __init__(self, checked_cells, gui, widht, height):
self.widht = widht
self.height = height
self.gui = gui
self.generation = checked_cells
def __eq__(self, other):
if isinstance(other, self.__class__):
return(self.generation == other.generation)
else:
return(False)
def get_count(self):
return(len(self.generation))
def get_next_generation(self):
self.next_generation = []
self.list_check = []
for cell in self.generation:
if cell not in self.list_check:
self._check_cell(cell)
return(Generation(self.next_generation, self.gui, self.widht, self.height))
def _check_cell(self, cell):
life = True if cell in self.generation else False
neighbors = self._get_neighbors(cell)
count_life_neighbors = self._count_life(neighbors)
# Переход в следующеее поколение
if ((count_life_neighbors == 3)
or (life and count_life_neighbors == 2)):
self.next_generation.append(cell)
self.gui.set_cell(cell, True)
else: self.gui.set_cell(cell, False)
self.list_check.append(cell)
# Рекурсивная проверка для соседей живой клетки
if life:
for neighbor in neighbors:
if neighbor not in self.list_check:
self._check_cell(neighbor)
def _get_neighbors(self, cell):
neighbors = []
for i in range(-1, 2):
for j in range(-1, 2):
if i==j==0: continue
x = i + cell[0]
if x<0: x = self.height-1
elif x>=self.height: x=0
y = j + cell[1]
if y<0: y = self.widht-1
elif y>=self.widht: y=0
neighbors.append([x, y])
return(neighbors)
def _count_life(self, cells):
count = 0
for cell in cells:
if cell in self.generation:
count += 1
return(count) |
c0504a4d9f2c6e6dd501dfc6e20df6d65341d013 | IonutPopovici1992/SentDex | /Python_3_Basics/built-in_functions.py | 420 | 3.59375 | 4 | import math
exampleNumber1 = -5
exampleNumber2 = 5
if abs(exampleNumber1) == exampleNumber2:
print('These are the same.')
# Help
exampleList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(min(exampleList))
print(max(exampleList))
x = 5.123
print(round(x))
x = 5.789
print(round(x))
print(math.floor(x))
print(math.ceil(x))
intMe = '55'
print(intMe)
print(int(intMe))
print(float(intMe))
strMe = 77
print(str(strMe))
|
213404dbfd2c60129e1f9d6268c1d1df36ca18bb | pbelko/primenumbers | /prime/prime.py | 540 | 3.859375 | 4 | __author__ = 'tony'
import sys
print(sys.argv)
def main() -> object:
sentence = "Enter in a number to calculate: "
number = int(input(sentence))
calculate_prime(number)
def calculate_prime(a):
if a < 2:
sentence = 'The number { } must be greater than 2.'.format(a)
print(sentence)
for i in range(2, a):
if is_prime(i):
print(i)
def is_prime(n):
for i in range(2, n):
if (n % i) == 0:
return False
return True
if __name__ == "__main__":
main()
|
1c9dc6ed91a583328aab2cfe887a1d8fce2ea0dc | yashdevilking/Data-Structure-and-Algorithm | /Code Workspace/Algorithms/5.1 HeapSort.py | 2,275 | 4 | 4 | class MaxHeap():
#we receive a list of items
def __init__(self,items = []):
self.heap = [0]
# we create a heap list and store 0 at first Index
# we will not use first Index
for i in items:
# we will store the items received in items[] in heap
self.heap.append(i)
#now we will float them up to thier proper position
self.float_up(len(self.heap) - 1)
def push(self,data):
#append at last location
self.heap.append(data)
#heapify
self.float_up(len(self.heap) - 1)
def peek(self):
#check topmost node - stored at index 1
if self.heap[1]:
return self.heap[1]
return False
def pop(self):
#case 1: more than 2 Value
#in that case swap the root to last Value
if len(self.heap) > 2:
#swap the max val and last node
self.swap(1,len(self.heap) - 1)
#pop the maximum value
max=self.heap.pop()
#call the helper fn
self.bubble_down(1)
#case 2: when one value, pop it and we have empty heap
elif len(self.heap) == 2:
max=self.heap.pop()
#case 3: no root (pop from empty heap)then return false
else:
max = False
return max
#helper methods:
def swap(self,i,j):
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
def float_up(self,index):
#find parent
parent = index//2
if index <= 1:
return
elif self.heap[index] > self.heap[parent]:
self.swap(index,parent)
#recursive call
self.float_up(parent)
def bubble_down(self,index): #max heapify
left = index * 2
right = index * 2 + 1
largest = index
if len(self.heap) > left and self.heap[largest] < self.heap[left]:
largest = left
if len(self.heap) > right and self.heap[largest] < self.heap[right]:
largest = right
if largest != index:
self.swap(index,largest)
#recursive call
self.bubble_down(largest)
#Warning: this will delete your heap
def sort_heap(self, order = 0):
temp = []
while len(self.heap) > 1:
temp.append(self.pop())
if order == 0:
return temp
return temp[::-1]
m = MaxHeap([95,3,21])
m.push(10)
print(str(m.heap[1:len(m.heap)]))
print(str(m.pop()))
print(m.sort_heap())
|
f3de6fc8407e822afc5b0d3f3b9224e62aa5d527 | jakesauter/Intro_to_Data_Science_in_Python | /single_files/nearest_coin.py | 1,494 | 3.75 | 4 |
"""
reticulate::repl_python()
"""
"""
--------------------------------------
| . | . | . | . | . | . | . | . | . |
| . | x | . | . | . | . | . | . | . |
| . | . | . | . | o | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
| o | . | . | . | . | . | . | . | . |
| . | . | o | . | . | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
-------------------------------------
We are on a grid, and have the location of every coin. Our
objective is to find the nearest coin
"""
def shortest_path(pos, coins):
shortest_path = -1
shortest_path_index = -1
for i in range(0, len(coins)):
xdist = abs(pos[0] - coins[i][0])
ydist = abs(pos[1] - coins[i][1])
totaldist = xdist + ydist
if totaldist < shortest_path or shortest_path == -1:
shortest_path = totaldist
shortest_path_index = i
return(coins[shortest_path_index])
"""
Now lets say that we have a really large board. Now our O(n) time algorith
doesn't seem to make much sense anymore ; iterating through every coin
when we really only need to check the few closest coins
BFS (breadth first search) might be a possiblity here
We not have the stipulation where up front we know the grid size, and
it might be best to switch between BST and our simple coin algorithm
written above
"""
coins = [(3,3), (5,5)]
pos = (1,1)
shortest_path(pos, coins)
|
de66237aad79ee32992daff4259adbbbda6d3323 | Cracktuar/RebirthItemTracker | /game_objects/floor.py | 1,701 | 3.640625 | 4 | import pygame
class Curse:
No_Curse, Blind, Darkness, Lost, Maze, Unknown, Labyrinth, Cursed = range(8)
class Floor(object):
'''
Stolen from item_tracker - used as an easy way to convert floors into
shortened names
'''
__floor_id_to_label = {
"f1": "B1",
"f2": "B2",
"f3": "C1",
"f4": "C2",
"f5": "D1",
"f6": "D2",
"f7": "W1",
"f8": "W2",
"f9": "SHEOL",
"f10": "CATH",
"f11": "DARK",
"f12": "CHEST",
"f1x": "BXL",
"f3x": "CXL",
"f5x": "DXL",
"f7x": "WXL",
}
def __init__(self, id, tracker, is_alternate, curse=Curse.No_Curse):
self.id = id
self.curse = curse
self.items = []
self.tracker = tracker
self.is_alt_floor = is_alternate
def add_curse(self, curse):
if curse is None:
curse = Curse.No_Curse #None is the same as no curse
self.curse=curse
if self.curse==Curse.Labyrinth:
self.id += 'x' #If we're curse of the labyrinth, then we're XL
def add_item(self, item):
self.items.append(item)
def floor_has_curse(self, curse):
return curse == self.curse
def name(self):
return Floor.__floor_id_to_label[self.id]
def __eq__(self,other):
if not isinstance(other, Floor):
return False
return other is not None and self.id==other.id
def __ne__(self,other):
if not isinstance(other, Floor):
return True
return other is None or self.id!=other.id
|
1030db41147c9a63694e861c7fea4dcf9da85549 | hnuyx/work | /other/test/002-python/mpi.pyx | 791 | 3.84375 | 4 | #!/usr/bin/env python3
import time #时间模块
# Caculate PI with Taylor series
cpdef double TaylorPi(int k):
cdef double sum = 0.0
cdef int odd = 1
cdef int i = 0
for i in xrange(k):
if odd == 1:
sum += 1.0/(2.0*i+1.0)
odd = 0
else:
sum -= 1.0/(2.0*i+1.0)
odd = 1
return sum*4.0
def caculateRunTime(int t):
before = time.time() #生成开始时间,单位为秒
timeSum = 0
cdef int k = 10000000
for i in range(t):
start = time.time()
TaylorPi(10000000)
term = time.time() - start #每次循环耗时
print("one term done, duration:",term)
timeSum += term #累加
return "total:%lf,averange:%lf"%(timeSum,timeSum/t)
print(caculateRunTime(10))
|
49658ba8dcf065cdfeb9dff7b86fa48b703191bc | hnuyx/work | /other/test/002-python/x-properity.py | 176 | 3.578125 | 4 |
class T:
a = 1
b = 2
@property
def c(self):
return self.a * self.b
if __name__ == '__main__':
a = T()
print(a.c)
a.a = 3
print(a.c)
|
9d6df0f9941d77ce9331371bfacb0688efbb442f | jtschoonhoven/ledmatrix | /ledmatrix/utilities/colors.py | 1,459 | 3.890625 | 4 | """Constants for working with colors in the terminal.
https://pypi.org/project/ansicolors/
"""
from typing import NamedTuple, Optional
from colors import color as ansicolor
ColorOrder = NamedTuple(
'ColorOrder',
[('red', int), ('green', int), ('blue', int), ('white', Optional[int])],
)
RGB = ColorOrder(red=0, green=1, blue=2, white=None)
GRB = ColorOrder(green=0, red=1, blue=2, white=None)
RGBW = ColorOrder(red=0, green=1, blue=2, white=3)
GRBW = ColorOrder(green=0, red=1, blue=2, white=3)
_ColorTuple = NamedTuple(
'Color',
[('red', int), ('green', int), ('blue', int), ('white', Optional[int])],
)
class Color(_ColorTuple):
"""Container for an RGB color value."""
def __bool__(self): # type: () -> bool
"""Return False only for black."""
return any(self)
def __str__(self): # type: () -> str
"""Format class instance as a code-friendly string."""
return self.__repr__()
def __repr__(self): # type: () -> str
"""Format the class instance as a developer-friendly string representation."""
# TODO: apply color order
return ansicolor('██', fg=(self.red, self.green, self.blue)) # type: ignore
BLACK = Color(0, 0, 0, None)
RED = Color(255, 0, 0, None)
GREEN = Color(0, 255, 0, None)
BLUE = Color(0, 0, 255, None)
YELLOW = Color(255, 255, 0, None)
TEAL = Color(0, 255, 255, None)
PINK = Color(255, 0, 255, None)
WHITE = Color(255, 255, 255, None)
|
cb99d7bbb1c4f770ca09a0c5148fb29b7de8a662 | dev1315/Multi-label-Classification-using-NLP | /Final_Toxic_Comment_Classification.py | 17,683 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Toxic Comment Classification
# >Access dataset from [here](https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/data)
# In[1]:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
sns.set_style('darkgrid')
# In[2]:
import warnings
warnings.filterwarnings("ignore")
# In[3]:
train=pd.read_csv('Data.csv')
# In[4]:
train.head()
# **This is a problem of multi-label classification many times people confuse in multi-label and multi-class.**
# * The main difference between the two is lying in the concept of being mutually exclusive
# * **Multi-class classifications** problems are those where each sample belongs to atmost one class only. Eg: In a coin toss the result can either be a heads or tails
# * Whereas in case of **Multi-label classifications** each sample may belong to more than one class. Eg: A news article may belong to sports as well as politics.
# In[5]:
#creating a new column by summing all the target columns
al=train[train.columns[2:]].sum(axis=1)
# In[6]:
info=[]
y=train.shape[0]
info.append(['with no label',len(al[al==0]),(len(al[al==0])/y)*100])
for i in train.columns[2:]:
x=len(train[train[i]==1][i])
info.append([i,x,(x/y)*100])
# In[7]:
#Created a dataframe that shows the count and percentage of comments in different categories of target column
pd.DataFrame(info,columns=['Comment type','Count','%'])
# In[8]:
#Getting the count for comments that belong to multiple categories in target columns
multi=al.value_counts()[1:]
multi
# In[9]:
plt.figure(figsize=(7,5))
sns.barplot(x=multi.index,y=multi)
plt.title('Indivisual comments that belong to multiple classes',fontsize=15)
# In[10]:
#creating a copy of dataframe
df=train.copy()
# **Calculating word count**
# In[11]:
#you might need to first install this library
import textstat
# In[12]:
#using textstat.lexicon_count to grab the no of words in each comment
df['word_count']=[textstat.lexicon_count(i,removepunct=True) for i in df['comment_text'].values]
# In[13]:
for i in train.columns[2:]:
print(df[['word_count',i]].groupby(i).mean())
print('-----------------------------------')
# It can be observed that except for severe_toxic all the comment belonging to non clean category have a lower average word count
# **Symbols like "!*@#$*&" are also used when abusive words are used**
# In[14]:
from nltk.tokenize import regexp_tokenize
# In[15]:
df['sp_char']=[len(regexp_tokenize(i,"[!@#$&]")) for i in df['comment_text'].values]
# In[16]:
for i in train.columns[2:]:
print(df[['sp_char',i]].groupby(i).mean())
print('-----------------------------------')
# It is clearly evident that there is a high probability that a comment with symbols like this !@#$& will be a non clean comment
# **Calculating Unique word count**
# * There are chances that abusive comments use words repeatively
# In[17]:
from nltk.tokenize import word_tokenize
# In[18]:
#using set to create a sequence of only unique words
df['unique_w_count']=[len(set(word_tokenize(i))) for i in df['comment_text'].values]
# In[19]:
for i in train.columns[2:]:
print(df[['unique_w_count',i]].groupby(i).mean())
print('-----------------------------------')
# It is also clear that non clean comments use less unique words
# # Lets explore through some of the comments
# In[20]:
train.comment_text[5]
# In[21]:
train.comment_text[1151]
# In[22]:
train.comment_text[8523]
# # Text Cleaning
# Most of the comments have **\n, punctuations, numbers, extra whitespaces, contractions and lots of stopwords** lets remove that first
# In[23]:
import re
import spacy
from nltk.stem.snowball import SnowballStemmer
from nltk.corpus import stopwords
from spacy.lang.en.stop_words import STOP_WORDS
from textblob import TextBlob
# Function for removing **\n**
# In[24]:
def slash_n(text):
#removing \n
text=re.sub('\n',' ',text)
#converting whole string into lowercase
text=text.lower()
return text
# In[25]:
CONTRACTION_MAP = {
"ain't": "is not",
"aren't": "are not",
"can't": "cannot",
"can't've": "cannot have",
"'cause": "because",
"could've": "could have",
"couldn't": "could not",
"couldn't've": "could not have",
"didn't": "did not",
"doesn't": "does not",
"don't": "do not",
"hadn't": "had not",
"hadn't've": "had not have",
"hasn't": "has not",
"haven't": "have not",
"he'd": "he would",
"he'd've": "he would have",
"he'll": "he will",
"he'll've": "he he will have",
"he's": "he is",
"how'd": "how did",
"how'd'y": "how do you",
"how'll": "how will",
"how's": "how is",
"I'd": "I would",
"I'd've": "I would have",
"I'll": "I will",
"I'll've": "I will have",
"I'm": "I am",
"I've": "I have",
"i'd": "i would",
"i'd've": "i would have",
"i'll": "i will",
"i'll've": "i will have",
"i'm": "i am",
"i've": "i have",
"isn't": "is not",
"it'd": "it would",
"it'd've": "it would have",
"it'll": "it will",
"it'll've": "it will have",
"it's": "it is",
"let's": "let us",
"ma'am": "madam",
"mayn't": "may not",
"might've": "might have",
"mightn't": "might not",
"mightn't've": "might not have",
"must've": "must have",
"mustn't": "must not",
"mustn't've": "must not have",
"needn't": "need not",
"needn't've": "need not have",
"o'clock": "of the clock",
"oughtn't": "ought not",
"oughtn't've": "ought not have",
"shan't": "shall not",
"sha'n't": "shall not",
"shan't've": "shall not have",
"she'd": "she would",
"she'd've": "she would have",
"she'll": "she will",
"she'll've": "she will have",
"she's": "she is",
"should've": "should have",
"shouldn't": "should not",
"shouldn't've": "should not have",
"so've": "so have",
"so's": "so as",
"that'd": "that would",
"that'd've": "that would have",
"that's": "that is",
"there'd": "there would",
"there'd've": "there would have",
"there's": "there is",
"they'd": "they would",
"they'd've": "they would have",
"they'll": "they will",
"they'll've": "they will have",
"they're": "they are",
"they've": "they have",
"to've": "to have",
"wasn't": "was not",
"we'd": "we would",
"we'd've": "we would have",
"we'll": "we will",
"we'll've": "we will have",
"we're": "we are",
"we've": "we have",
"weren't": "were not",
"what'll": "what will",
"what'll've": "what will have",
"what're": "what are",
"what's": "what is",
"what've": "what have",
"when's": "when is",
"when've": "when have",
"where'd": "where did",
"where's": "where is",
"where've": "where have",
"who'll": "who will",
"who'll've": "who will have",
"who's": "who is",
"who've": "who have",
"why's": "why is",
"why've": "why have",
"will've": "will have",
"won't": "will not",
"won't've": "will not have",
"would've": "would have",
"wouldn't": "would not",
"wouldn't've": "would not have",
"y'all": "you all",
"y'all'd": "you all would",
"y'all'd've": "you all would have",
"y'all're": "you all are",
"y'all've": "you all have",
"you'd": "you would",
"you'd've": "you would have",
"you'll": "you will",
"you'll've": "you will have",
"you're": "you are",
"you've": "you have"
}
# <font size ='4'>**Dealing with contractions**</font>
# * A contraction is an abbreviation for a sequence of words
# * eg: "you'll" is a contraction of "you will"
# In[26]:
def contraction(text):
"""
This function will return the text in an expanded form which is in common English. It also helps in generalising the tokens
"""
tokens=word_tokenize(text)
tok=[]
for i in tokens:
if i in CONTRACTION_MAP.keys():
tok.append(CONTRACTION_MAP[i])
else:
tok.append(i)
return ' '.join(tok)
# **Created a combined list of Stopwords taken form nltk corpus and spacy library**
# In[27]:
#using stopwords from both libraries
nltk_sw=stopwords.words('english')
spacy_sw=list(STOP_WORDS)
#removing duplicates by converting list into set
stopword=list(set(nltk_sw+spacy_sw))
# **Removing** Punctuations, Stopwords, Whitespaces and Non Alphabatics.
# In[28]:
nlp=spacy.load('en_core_web_md')
# In[29]:
def sw(text):
text=textstat.remove_punctuation(text) #removing punctuations
tokens=text.split()
tok=[]
for i in tokens:
if i not in stopword: #removing stopwords
i=i.strip() #removing all leading and trailing whitespaces as they will create bais in next step
if i.isalpha(): #removing non alphabatics
tok.append(i)
return ' '.join(tok)
# <font size ='4'>**Performing Lemmatizatin**</font>
# * We have used lemmatization instead of stemming because we are going to create vectors for each comment so we want the words in each comment to make some sense (whereas in case of stemming the word is broken to its stem length that may or may not make sense).
# * Their are 2 methods for lemmatization using spacy's .lemma_ or WordNetLemmatizer
# * For this problem we are using spacy's .lemma_ because its more afficient and advanced.
# In[30]:
#Using Spacy's Lemmatization
def lemma(text):
doc=nlp(text)
tok=[i.lemma_ for i in doc]
return ' '.join(tok)
# **Applying all the functions**
# In[31]:
train['comment_text']=train['comment_text'].apply(slash_n)
# In[32]:
train['comment_text']=train['comment_text'].apply(contraction)
# In[33]:
train['comment_text']=train['comment_text'].apply(sw)
# In[34]:
train['comment_text']=train['comment_text'].apply(lemma) #takes 25 mins to process
# # Generating Wordclouds for all categories
# In[36]:
from wordcloud import WordCloud
# In[37]:
def wordcloud_gen(i):
texts=train[train[i]==1]['comment_text'].values
wordcloud = WordCloud(background_color='black',width=700,height=500,colormap='viridis').generate(" ".join(texts))
plt.figure(figsize=(7, 5))
plt.imshow(wordcloud)
plt.title(str(i).upper(),fontsize=15)
plt.grid(False)
plt.axis(False)
# In[38]:
wordcloud_gen('toxic')
# In[39]:
wordcloud_gen('severe_toxic')
# In[40]:
wordcloud_gen('obscene')
# In[41]:
wordcloud_gen('threat')
# In[42]:
wordcloud_gen('insult')
# In[43]:
wordcloud_gen('identity_hate')
# These wordclouds also indicate that an indivisual comment may belongs to multiple classes as there are many
# In[44]:
texts=train['comment_text'].values
wordcloud = WordCloud(background_color='black',width=700,height=500,colormap='viridis').generate(" ".join(texts))
plt.figure(figsize=(10, 8))
plt.imshow(wordcloud)
plt.title('ALL COMMENTS',fontsize=15)
plt.grid(False)
plt.axis(False)
# **Lets Split the data to perform further operations**
# In[35]:
from sklearn.model_selection import train_test_split
# In[36]:
training, testing=train_test_split(train, random_state=42, test_size=0.30, shuffle=True)
# In[37]:
training.shape,testing.shape
# Now We'll convert these strings into vectors using **`TfidfVectorizer`**
# * We need to find the most frequently occurring terms i.e. words with high term frequency or **tf**
# * We also want a measure of how unique a word is i.e. how infrequently the word occurs across all documents i.e. inverse document frequency or **idf**
# **Hence Tf-idf**
# In[38]:
from sklearn.feature_extraction.text import TfidfVectorizer
# **Choosing an optimum value for `max_features` is very necessary especially when you are dealing with such a big dataset.**
# * If the value is set too high the memory of your system will *fail to handle the amount of data*
# * And if the value is set too low then you'd be *under-utilizing your data*
# * Also cases like over-fitiing and under-fitting may also happen.
# In[39]:
unique_words=len(set((' '.join(training['comment_text'].values)).split()))
print('Total unique words in the training corpus is ',unique_words,', this means the vectorizer can create at max ',unique_words," vectors & definitely while creating so many vectors we'll run out of memory")
# In[40]:
#I have used 2000 as max_features but a higher value could also be tried as per system configuration
tfidf=TfidfVectorizer(strip_accents='unicode',max_features=2000,min_df=2,max_df=0.9)
# Creating a seperate dataframe for `'unique_w_count','sp_char','word_count'` named `feature1`
# In[41]:
feature1=df[['unique_w_count','sp_char','word_count']]
feature1.head()
# In[42]:
from scipy.sparse import csr_matrix,hstack
from sklearn.preprocessing import MinMaxScaler
# In[43]:
scaler1=MinMaxScaler(feature_range=(0,0.5))
# **Scaling down above 3 features in range of `0,0.5`**
# In[44]:
feature1_t=scaler1.fit_transform(feature1)
feature1_t=pd.DataFrame(feature1_t)
feature1_t.head()
# Splitting these features according to train_test_split and then converting these `3 features` into sparse matrix
# In[45]:
train_feat=csr_matrix(feature1_t.iloc[training.index,:])
test_feat=csr_matrix(feature1_t.iloc[testing.index,:])
# In[46]:
train_feat.shape
# **Generated vectors for each comment that resulting in `300 more features` for classification**
# In[47]:
get_ipython().run_cell_magic('time', '', "#took 37 minutes to complete\nvec=[]\nfor i in range(train.shape[0]):\n text=train['comment_text'][i]\n print(i) #just to know the progress as there are 159571 entries\n vec.append(nlp(text).vector)")
# In[48]:
#creating a dataframe of these vectors
vectors=pd.DataFrame(vec)
# In[49]:
#Splitting these feature vectors according to train_test_split
vectrain=vectors.iloc[training.index,:]
vectest=vectors.iloc[testing.index,:]
# In[52]:
#converting into sparse matrix
train_vec=csr_matrix(vectrain)
test_vec=csr_matrix(vectest)
# ***Fitting TfidfVectorizer only on the training set.***
# In[53]:
tfidf.fit(training['comment_text'])
# In[54]:
#tfidf vectorization on training set
train_tfidf=tfidf.transform(training['comment_text'])
# Using `hstack` to stack sparse matrixes along axis=1
# In[55]:
x_train=hstack((train_tfidf,train_vec,train_feat))
# In[56]:
x_train.shape
# We can clearly see total columns i.e. `features =2303`
# * 2000 tfidf_vectors
# * 300 Vector representation on each comment
# * unique_word_count
# * word_count
# * Count of special characters
# In[57]:
y_train=training.drop(labels = ['id','comment_text'], axis=1)
# In[58]:
#tfidf vectorization on testing set
test_tfidf=tfidf.transform(testing['comment_text'])
# In[59]:
x_test=hstack((test_tfidf,test_vec,test_feat))
# In[60]:
x_test.shape
# In[61]:
y_test=testing.drop(labels = ['id','comment_text'], axis=1)
# # Model Building
# Reference for [Model Building](https://www.analyticsvidhya.com/blog/2017/08/introduction-to-multi-label-classification/)
# In[62]:
from skmultilearn.problem_transform import LabelPowerset
from skmultilearn.problem_transform import BinaryRelevance
from skmultilearn.problem_transform import ClassifierChain
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score,roc_auc_score
# # OneVsRest
# * Here the multi-label problem is decomposed into multiple independent binary classification problems
# * Here each accuracy_score depicts the accuracy of model in predicting whether the comment is say toxic or not.
# In[63]:
pred={}
log=LogisticRegression()
for i in y_train.columns:
log.fit(x_train, y_train[i])
print('For',i,'accuracy_score',round(accuracy_score(y_test[i],log.predict(x_test))*100,1),'%')
print('-------------------------------------------------')
pred[i]=log.predict_proba(x_test)[:,1]
# In[64]:
print('roc_auc_score using OneVSRest is ',roc_auc_score(y_test,pd.DataFrame(pred)))
# # BinaryRelevance
# * This one is an ensemble of single-class (Yes/No) binary classifier
# * If there are n number of different labels it will create n datasets and train for each label and will result the union of all predicted labels.
# * Here the correlation b/w the labels is not taken into account
# In[65]:
classifier = BinaryRelevance(LogisticRegression())
# In[66]:
classifier.fit(x_train, y_train)
print('Accuracy_score using BinaryRelevance is ',round(accuracy_score(y_test,classifier.predict(x_test))*100,1),'%')
print('-------------------------------------------------')
print('roc_auc_score using BinaryRelevance is ',roc_auc_score(y_test,classifier.predict_proba(x_test).toarray()))
# # Label Powerset
# * Label Powerset creates a unique class for every possible label combination that is present in the training set, this way it makes use of label correlation
# * Only problem with this method is as the no of classes increases its computational complexity also increases.
# In[67]:
log_classifier=LabelPowerset(LogisticRegression())
# In[68]:
log_classifier.fit(x_train, y_train)
print('Accuracy_score using LabelPowerset is ',round(accuracy_score(y_test,log_classifier.predict(x_test))*100,1),'%')
print('-------------------------------------------------')
print('roc_auc_score using LabelPowerset is ',roc_auc_score(y_test,log_classifier.predict_proba(x_test).toarray()))
# # ClassifierChain
# * This method uses a chain of binary classifiers
# * Each new Classifier uses the predictions of all previous classifiers
# * This was the correlation b/w labels is taken into account
# In[69]:
chain=ClassifierChain(LogisticRegression())
# In[70]:
chain.fit(x_train, y_train)
print('Accuracy_score using ClassifierChain is ',round(accuracy_score(y_test,chain.predict(x_test))*100,1),'%')
print('-------------------------------------------------')
print('roc_auc_score using ClassifierChain is ',roc_auc_score(y_test,chain.predict_proba(x_test).toarray()))
|
eef82d4c537441db718cadba2b8aa98998fe7418 | Jeff-ust/D002-2019 | /L6/connect-4.py | 3,759 | 3.59375 | 4 | def printcell(cells):
print("-" * 29)
for i in range(0, 6):
for j in range(0, 7):
print("| %s " % cells[i][j], end="")
print("|")
print("-" * 29)
cells = [[" "," "," "," "," "," "," "], [" "," "," "," "," "," "," "], \
[" "," "," "," "," "," "," "], [" "," "," "," "," "," "," "], \
[" "," "," "," "," "," "," "], [" "," "," "," "," "," "," "]]
def check_row(cells):
for row in range(0, 6):
for col in range(0, 4):
if cells[row][col] == cells[row][col+1] == cells[row][col+2] \
== cells[row][col+3] != " ":
return True
return False
def check_col(cells):
for row in range(0, 6):
for col in range(0, 3):
if cells[row][col] == cells[row-1][col] == cells[row-2][col] \
== cells[row-3][col] != " ":
return True
return False
def check_TLBR(cells):
for row in range(0, 3):
for col in range(0, 4):
if cells[row][col] == cells[row + 1][col + 1] == cells[row + 2][col + 2] ==\
cells[row + 3][col + 3] != " ":
return True
return False
def check_BLTR(cells):
for row in range(5, 2, -1):
for col in range(0, 4):
if cells[row][col] == cells[row - 1][col + 1] == cells[row - 2][col + 2] ==\
cells[row - 3][col + 3] != " ":
return True
return False
def check(cells):
if check_row(cells) or check_col(cells) or check_TLBR(cells) or check_BLTR(cells):
return True
return False
def check_draw(cells):
if cells[0][0] == cells[0][1] == cells[0][2] == cells[0][3] == cells[0][4] == cells[0][5] == cells[0][6] != " ":
return True
return False
turn = 1
printcell(cells)
while True:
if turn %2 != 0:
row = 5
col = int(input("Player 1, please enter column. From 0 to 6.\t"))
while col < 0 or col > 6:
print("Invalid input!")
col = int(input("Player 1, please enter column again.\t"))
while cells[row][col] != " ":
row = row - 1
if row < 0 :
print("The column is full!")
col = int(input("Player 1, please enter column again.\t"))
row = 5
else:
cells[row][col] = "O"
printcell(cells)
turn = turn + 1
if check(cells) == True:
print("Player 1 wins!")
break
if check_draw(cells) == True:
print("Draw!")
break
else:
row = 5
col = int(input("Player 2, please enter column. From 0 to 6.\t"))
while col < 0 or col > 6:
print("Invalid input!")
col = int(input("Player 2, please enter column again.\t"))
while cells[row][col] != " ":
row = row - 1
if row < 0 :
print("The column is full!")
col = int(input("Player 2, please enter column again.\t"))
row = 5
else:
cells[row][col] = "X"
printcell(cells)
turn = turn + 1
if check(cells) == True:
print("Player 2 wins!")
break
if check_draw(cells) == True:
print("Draw!")
break
|
b82b3928481d538244ec70a34fecb0b7ed761f3c | Jeff-ust/D002-2019 | /L2/L2Q6v1.py | 1,387 | 4.375 | 4 | #L2 Q6: Banana Guessing game
#Step 1: Import necessary modules
import random
#Step 2: Welcome Message
print('''Welcome to the Banana Guessing Game
Dave hid some bananas. Your task is to find out the number of bananas he hid.''')
#Step 3: Choose a random number between 1-100
n = random.randint(1,100)
print ("shhh, Dave hides %s bananas" % n)
# define a flag for found/not found and counter on how many trials
found = False
count = 0
#Step 4: Give three chances to the players
p = int(input("Guess a number between 1 and 100."))
while found == False:
if p < 1 or p > 100:
print("Your guess is out-of-range!")
count = count + 1
elif p > n:
print("Your guess is too high!")
count = count + 1
elif p < n:
print("Your guess is too low!")
count = count + 1
elif p == n:
found = True
count = count + 1
if count == 3 and found == False:
print("Game over.")
break
else:
#Step 5: Display a message
if found == True:
print('You got the correct guess in %d trials' % count)
print('Dave\'s banana are now all yours!')
else:
print("You failed to find the number of bananas Dave hid! Try again next")
p = int(input("Guess a number between 1 and 100."))
|
70ca08346178f87b3e7afae3e746481369cba82a | shuhsienhsu/X-Village-DS-Exercise | /bonus3.py | 746 | 4.1875 | 4 | def insertion_sort(list):
for i in range(1, len(list)):
for j in range(i):
j = i - j - 1
if(list[j] > list[j + 1]):
temp = list[j]
list[j] = list[j + 1]
list[j + 1] = temp
else:
break
def bubble_sort(list):
for i in range(len(list)):
i = len(list) - 1 - i
for j in range(i):
if(list[j + 1] < list[j]):
temp = list[j]
list[j] = list[j + 1]
list[j + 1] = temp
#def merge_sort(list):
#def quick_sort(list):
mylist = [4,3,2,1]
print(mylist)
insertion_sort(mylist)
print(mylist)
mylist2 = [2,4,3,1]
print(mylist2)
bubble_sort(mylist2)
print(mylist2) |
c44b0015fc91eb0dde169cf2de386c7d8b16ddd0 | yash-kedia/Competitve-Coding | /Graphs/trie_in_python.py | 1,614 | 3.96875 | 4 | class node:
def __init__ (self):
self.key = None
self.value = None
self.children = {}
class trie:
def __init__ (self):
self.root = node()
def insert(self,word,value):
currentword = word
currentnode = self.root
while len(currentword)>0:
if currentword[0] in currentnode.children:
currentnode = currentnode.children[currentword[0]]
currentword = currentword[1:]
else:
newnode = node()
newnode.key = currentword[0]
if len(currentword)==1:
newnode.value = value
currentnode.children[currentword[0]] = newnode
currentnode = newnode
currentword = currentword[1:]
def lookup(self,word):
currentword = word
currentnode = self.root
while len(currentword)>0:
if currentword[0] in currentnode.children:
currentnode = currentnode.children[currentword[0]]
currentword = currentword[1:]
else:
return "NOT IN TRIE"
if currentnode.value == None:
return "NONE"
return currentnode.value
def printourtrie(self):
nodes = [self.root]
while len(nodes)>0:
for letter in nodes[0].children:
nodes.append(nodes[0].children[letter])
print (nodes.pop(0).key)
def makeourtrie(words):
Trie = trie()
for word,value in words.items():
Trie.insert(word,value)
return Trie
|
6a0bc17deb88782279a2dc66446ff5853a27f21b | kevinychen/code-crunch | /problems/subtract/subtract.py | 152 | 3.515625 | 4 | import fractions
n = input()
nums = []
for i in range(n):
nums.append(input())
u = nums[0]
for z in nums[1:]:
u = fractions.gcd(u, z)
print u
|
b9ad75ed20cc080f6ad33041289f82d8669d4cb5 | rodipm/IA | /falling_ball/utils.py | 1,822 | 3.640625 | 4 | import random
import pygame
from initializer import *
from classes import *
def new_state_after_action(s, act):
rct = None
if act == 2:
if s.rect.right + s.rect.width > windowWidth:
rct = s.rect
else:
rct = pygame.Rect(s.rect.left + s.rect.width, s.rect.top, s.rect.width, s.rect.height)
elif act == 1:
if s.rect.left - s.rect.width < 0:
rct = s.rect
else:
rct = pygame.Rect(s.rect.left - s.rect.width, s.rect.top, s.rect.width, s.rect.height)
else:
rct = s.rect
newCircle = Circle(s.circle.circleX, s.circle.circleY + crclYStepFalling)
return State(rct, newCircle)
def new_rect_after_action(rect, act):
if act == 2:
if rect.right + rect.width > windowWidth:
return rect
else:
return pygame.Rect(rect.left + rect.width, rect.top, rect.width, rect.height)
elif act == 1:
if rect.left - rect.width < 0:
return rect
else:
return pygame.Rect(rect.left - rect.width, rect.top, rect.width, rect.height)
else:
return rect
def circle_falling(crclradius):
newx = 100 - crclRadius
multiplier = random.randint(1, 8)
newx *= multiplier
return newx
def calculate_score(rect, circle):
if rect.left <= circle.circleX <= rect.right:
return 1
else:
return -1
def state_to_number(s):
r = s.rect.left
c = s.circle.circleY
n = int(str(r) + str(c) + str(s.circle.circleX))
if n in QIDic:
return QIDic[n]
else:
if len(QIDic):
maximum = max(QIDic, key=QIDic.get)
QIDic[n] = QIDic[maximum] + 1
else:
QIDic[n] = 0
return QIDic[n]
def get_best_action(s):
return np.argmax(Q[state_to_number(s), :])
|
93c7334ce86f88739043c5823b28df446df088f6 | junqfisica/SDP | /backend/flaskapp/utils/file_utils.py | 5,952 | 3.75 | 4 | # Util methods to handle files.
import os
import shlex
import shutil
import subprocess as sp
import tarfile
import tempfile
from typing import List
from zipfile import ZipFile
def get_file_extension(file_name: str) -> str:
"""
Get the file extension,
file.jpg returns jpg
file returns ""
:param file_name: The name of the file, expects to be a string.
:return: The file extension
"""
try:
split_name = file_name.split(".")
if len(split_name) < 2:
return ""
return split_name.pop(-1)
except IndexError:
return ""
def zip_files(file_paths: List[str], output_path: str = None) -> str:
"""
Compress a list of files into a zip file. If output_path is not given it will be
saved as a temporary file.
:param file_paths: The list of files path to be compressed.
:param output_path: (Optional) The output file path.
:return: The path of the compressed zip file.
"""
if not output_path:
tmp_file = tempfile.NamedTemporaryFile(suffix=".zip")
output_path = tmp_file.name
tmp_file.close()
with ZipFile(file=output_path, mode='w') as zf:
for file_path in file_paths:
filename = os.path.basename(file_path)
zf.write(filename=file_path, arcname=filename)
return output_path
def tar_files(file_paths: List[str], output_path: str = None) -> str:
"""
Compress a list of files into a tar file. If output_path is not given it will be
saved as a temporary file.
:param file_paths: The list of files path to be compressed.
:param output_path: (Optional) The output file path.
:return: The path of the compressed tar file.
"""
if not output_path:
tmp_file = tempfile.NamedTemporaryFile(suffix=".tar")
output_path = tmp_file.name
tmp_file.close()
with tarfile.open(name=output_path, mode='w') as tf:
for file_path in file_paths:
filename = os.path.basename(file_path)
tf.add(name=file_path, arcname=filename)
return output_path
def archive_dir(dir_path: str, file_format: str, output_path: str = None):
"""
Compress a directory into a file_format file. If output_path is not given it will be
saved as a temporary file.
:param dir_path: The directory path to be compressed.
:param file_format: str one of "zip", "tar", "gztar", "bztar", or "xztar".
:param output_path: (Optional) The output file path.
:return: The path of the compressed file.
"""
if not output_path:
tmp_file = tempfile.NamedTemporaryFile()
output_path = tmp_file.name
tmp_file.close()
else:
file_ext = get_file_extension(file_name=output_path)
output_path = output_path.replace("." + file_ext, "")
shutil.make_archive(output_path, format=file_format, root_dir=dir_path)
return output_path
def is_dir_online(dir_path: str):
"""
Check is is dir and if exists.
:param dir_path: The directory full path.
:return: True if is a dir and exists, false otherwise.
"""
if os.path.isdir(dir_path) and os.path.exists(dir_path):
return True
else:
return False
def ssh_scp(source: str, destine: str, psw: str):
"""
:param source:
:param destine:
:param psw:
:return:
"""
if os.path.isdir(source):
cmd = shlex.split("sshpass -p '{pws}' scp -r {source} {destine}".format(pws=psw,
source=source, destine=destine))
else:
cmd = shlex.split("sshpass -p '{pws}' scp {source} {destine}".format(pws=psw,
source=source, destine=destine))
with sp.Popen(cmd,
stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE, encoding="utf-8") as p:
try:
std_out, std_err = p.communicate(timeout=3600*4)
print("done", str(std_out))
except sp.TimeoutExpired as e:
print("Timeout error", e, p.returncode)
p.kill()
std_out, std_err = p.communicate()
if p.returncode != 0: # Bad error.
raise sp.CalledProcessError(p.returncode, std_err)
elif len(std_err) != 0: # Some possible errors trowed by the running subprocess, but not critical.
raise sp.SubprocessError(std_err)
return std_out
def create_rsync_bash(user: str, host_ip: str, psw: str, files_to_download: List[str], destine=None, output_path=None):
"""
Create a bash file that uses rsync to download files from server.
:param user: The server user name.
:param host_ip: The server ip.
:param psw: The password for the user.
:param files_to_download: The list of files paths to download.
:param destine: The client destination to rsync the files.
:param output_path: The bash output file path. If none it will create a temp file.
:return: The bash file path.
"""
print(output_path)
file_tag = ""
if not output_path:
tmp_file = tempfile.NamedTemporaryFile(suffix=".sh")
output_path = tmp_file.name
tmp_file.close()
if not destine:
destine = "dest=$(pwd)\n\n" # get current dir where this bash will run.
else:
destine = "dest='{}'\n\n".format(destine)
with open(output_path, "w") as f:
f.write("#!/bin/bash\n\n")
f.write("psw='{}'\n".format(psw))
f.write("user='{}'\n".format(user))
f.write("host_ip='{}'\n".format(host_ip))
f.write(destine)
for index, path in enumerate(files_to_download):
f.write("file{}='{}'\n".format(index, path))
file_tag += ":$file{} ".format(index)
f.write("\n")
f.write('rsync -ro -P --rsh="sshpass -p $psw ssh -l $user" $host_ip{}$dest'.format(file_tag))
return output_path
|
fbf0406858a0b3cdb529472d4642b2acea5fa3d2 | shouryacool/StringSlicing.py | /02_ strings Slicing.py | 820 | 4.34375 | 4 | # greeting="Good Morning,"
# name="Harry"
# print(type(name))
# # Concatining Two Strings
# c=greeting+name
# print(c)
name="HarryIsGood"
# Performing Slicing
print(name[0:3])
print(name [:5]) #is Same as [0:4]
print(name [:4]) #is Same as [0:4]
print(name [0:]) #is Same as [0:4]
print(name [-5:-1]) # is same as name [0:4]
print(name[-4:-2]) # is same as name [1:3]
# Slicing with skip value
d=name[1::2]
print(d)
# The index in a string starts from 0 to (length-1) in Python. To slice a string, we use the following syntax:
# We can acess any Characters Of String but cant change it
# Negative Indices: Negative indices can also be used as shown in the figure above. -1 corresponds to the (length-1) index, -2 to (length-2).
# Q Why To use Negative indices???
#
#
#
#
|
a7e13dc9ed5445badc81418f39e58a168bfd37b8 | AlexanderIvanofff/Python-OOP | /Multidimensional Lists/matrix_shuffling.py | 949 | 3.828125 | 4 | def is_valid(pos, rows, cols):
return 0 <= pos[0] < rows and 0 <= pos[1] < cols
rows, cols = [int(x) for x in input().split()]
matrix = []
for _ in range(rows):
matrix.append([x for x in input().split()])
line = input().split()
while not line[0] == 'END':
if line[0] == 'swap' and len(line) == 5:
first_position = [int(line[1]), int(line[2])]
second_position = [int(line[3]), int(line[4])]
if is_valid(first_position, rows, cols) and is_valid(second_position, rows, cols):
matrix[first_position[0]][first_position[1]], matrix[second_position[0]][second_position[1]] = \
matrix[second_position[0]][second_position[1]], matrix[first_position[0]][first_position[1]]
for row in matrix:
print(' '.join(row))
else:
print('Invalid input!')
else:
print('Invalid input!')
line = input().split() |
e18e0182112fee9e9e303b9a3bb7d3d09b219509 | AlexanderIvanofff/Python-OOP | /Classes and Instances/time.py | 1,379 | 4.0625 | 4 | # Create class Employee. Upon initialization, it should receive id (number), first_name (string),
# last_name (string), salary (number). Create 3 more instance methods:
# - get_full_name() - returns "{first_name} {last_name}"
# - get_annual_salary() - returns the salary for 12 months
# - raise_salary(amount) - increase the salary by the given amount and return the new salary
from datetime import datetime, timedelta
class Time:
max_hours = 23
max_minutes = 59
max_seconds = 59
def __init__(self, hours, minutes, seconds):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
self.time_object = datetime(100, 1, 1, hour=hours, minute=minutes, second=seconds)
def set_time(self, hours, seconds, minutes):
self.hours = hours
self.seconds = seconds
self.minutes = minutes
def get_time(self):
return f"{self.hours:02d}:{self.minutes:02d}:{self.seconds:02d}"
def next_second(self):
self.time_object = self.time_object + timedelta(seconds=1)
self.hours = self.time_object.hour
self.minutes = self.time_object.minute
self.seconds = self.time_object.second
return self.get_time()
time = Time(9, 30, 59)
print(time.next_second())
time = Time(10, 59, 59)
print(time.next_second())
time = Time(23, 59, 59)
print(time.next_second())
|
3d88fc4d3f467d12de6a74adb46bbeee20b013e6 | AlexanderIvanofff/Python-OOP | /Multidimensional Lists/knight_game.py | 1,874 | 3.546875 | 4 | """
Chess is the oldest game, but it is still popular these days. For this task, we will use only one chess piece - the Knight.
The knight moves to the nearest square but not on the same row, column, or diagonal. (This can be thought of as moving
two squares horizontally, then one square vertically, or moving one square horizontally then two squares vertically - i.e.
in an "L" pattern.)
The knight game is played on a board with dimensions N x N.
You will receive a board with K for knights and '0' for empty cells. Your task is to remove knights until there are no
knights left that can attack one another.
Input Output
5 1
0K0K0
K000K
00K00
K000K
0K0K0
"""
def is_valid(pos, size):
row = pos[0]
col = pos[1]
return 0 <= row < size and 0 <= col < size
def get_killed_knights(row, col, size, board):
killed_knight = 0
rows = [-2, -1, 1, 2, 2, 1, -1, -2]
cols = [1, 2, 2, 1, -1, -2, -2, -1]
for i in range(8):
current_position = [row + rows[i], col + cols[i]]
if is_valid(current_position, size) and board[current_position[0]][current_position[1]] == "K":
killed_knight += 1
return killed_knight
n = int(input())
board = []
total_kills = 0
for _ in range(n):
board.append([x for x in input()])
while True:
most_kills = 0
to_kill = []
for row in range(n):
for col in range(n):
if board[row][col] == 'K':
killed_knights = get_killed_knights(row, col, n, board)
if killed_knights > most_kills:
most_kills = killed_knights
to_kill = [row, col]
if most_kills == 0:
break
to_kill_row = to_kill[0]
to_kill_col = to_kill[1]
board[to_kill_row][to_kill_col] = "0"
total_kills += 1
print(total_kills)
|
6ec8208d9bcfe684c064577483dcad29b874de27 | AlexanderIvanofff/Python-OOP | /List as Stacks and Queues/reverse_str.py | 194 | 4.09375 | 4 | string = input()
stack = []
for char in string:
stack.append(char)
reversed_str = ""
while len(stack) > 0:
item = stack.pop()
reversed_str += item
print(reversed_str) |
d8f89c6f971a5378300db593da07310ed7dfa31d | AlexanderIvanofff/Python-OOP | /defending classes/programmer.py | 2,311 | 4.375 | 4 | # Create a class called Programmer. Upon initialization it should receive name (string), language (string),
# skills (integer). The class should have two methods:
# - watch_course(course_name, language, skills_earned)
# o If the programmer's language is the equal to the one on the course increase his skills with the given one and
# return a message "{programmer} watched {course_name}".
# o Otherwise return "{name} does not know {language}".
# - change_language(new_language, skills_needed)
# o If the programmer has the skills and the language is different from his, change his language to the new one and
# return "{name} switched from {previous_language} to {new_language}".
# o If the programmer has the skills, but the language is the same as his return "{name} already knows {language}".
# o In the last case the programmer does not have the skills, so return "{name} needs {needed_skills} more skills"
# and don't change his language
class Programmer:
def __init__(self, name, language, skills):
self.name = name
self.language = language
self.skills = skills
def watch_course(self, course_name, language, skills_earned):
if self.language == language:
self.skills += skills_earned
return f"{self.name} watched {course_name}"
return f"{self.name} does not know {language}"
def change_language(self, new_language, skill_needed):
if self.skills >= skill_needed and not self.language == new_language:
old_language = self.language
self.language = new_language
return f"{self.name} switched from {old_language} to {new_language}"
elif self.skills >= skill_needed and self.language == new_language:
return f"{self.name} already knows {self.language}"
return f"{self.name} needs {abs(self.skills - skill_needed)} more skills"
programmer = Programmer("John", "Java", 50)
print(programmer.watch_course("Python Masterclass", "Python", 84))
print(programmer.change_language("Java", 30))
print(programmer.change_language("Python", 100))
print(programmer.watch_course("Java: zero to hero", "Java", 50))
print(programmer.change_language("Python", 100))
print(programmer.watch_course("Python Masterclass", "Python", 84)) |
7d94fef672a5ab068b48129009d0876e39745452 | panzervi8/practice | /约瑟夫环问题.py | 969 | 3.53125 | 4 | """
《幸运的基督徒》
有15个基督徒和15个非基督徒在海上遇险,为了能让一部分人活下来不得不将其中15个人扔到海里面去,
有个人想了个办法就是大家围成一个圈,由某个人开始从1报数,报到9的人就扔到海里面,他后面的人接着从1开始报数,
报到9的人继续扔到海里面,直到扔掉15个人。由于上帝的保佑,15个基督徒都幸免于难,
问这些人最开始是怎么站的,哪些位置是基督徒哪些位置是非基督徒。
"""
persons = [True] * 30 #定义一个30个人的列表
#counter 记录扔掉的人
#index 是列表的index
#number是报数
counter, index, number = 0, 0, 0
while counter < 15:
if persons[index]:
number += 1
if number == 9:
persons[index] = False
counter += 1
number = 0
index += 1
index %= 30
for person in persons:
print('基' if person else '非', end=',') |
6847b974bfa860f4dcec26f502a5b7c6c307e7e8 | learn-co-curriculum/cssi-4.8-subway-functions-lab | /subway_functions.py | 1,870 | 4.625 | 5 | # A subway story
# You hop on the subway at Union Square. As you are waiting for the train you
# take a look at the subway map. The map is about 21 inches wide and 35 inches
# tall. Let's write a function to return the area of the map:
def map_size(width, height):
map_area = width * height
return "The map is %d square inches" % (map_area)
# Now you give it a shot! It takes about 156 seconds to go between stops and
# you'll be taking the train for 3 stops. Write a function that calculates how
# long your trip will take.
def trip_length(...):
# put your code here
# The train arrives and you hop on. Guess what time it is? It's showtime! There
# are 23 people on the train and each person gives the dancers 1.5 dollars.
# Write a function that returns how much money they made.
# There is one grumpy lady on the train that doesn't like the dancing though.
# Write a function called stop_dancing that returns a message to the dancers in
# all caps.
# There is also a really enthusiastic rider who keeps shouting "Everything is
# awesome!" Write a function that returns everything is awesome 5 times.
# You are almost at your stop and you start thinking about how you are going to
# get home. You have $18 left on your metro card. Write a function that returns
# how many trips you have left.
# Call your functions below:
print "How big is that subway map?"
# Call your function here - like this:
map_size(21, 35)
# ... but that doesn't output anything. Hmm. See if you can fix it.
print "This is how long the trip will take"
trip_length(...)
print "How much money did the train dancers make?"
# call your function here
print "That lady told the train dancers to"
# call your function here
print "That guy kept shouting"
# call your function here
print "This is how many trips I have left on my metrocard"
# call your function here
|
53d5ac88f60a661a68847ca3fcde58e7288d9a85 | elizabeth-dayton/Leet-Code | /Easy Problems/palindromenumber.py | 505 | 3.59375 | 4 | def isPalindrome(x):
# :type x: int
# :rtype: bool
#Try 1 - ran in 44 ms and took 12.9 MB of memory
# if x == 0:
# return True
# x = str(x)
# y = x[::-1]
# y = y.lstrip('0')
# return x == y
#Try 2 - ran in 40 ms and took 12.9 MB of memory
# if x < 0:
# return False
# return str(x) == str(x)[::-1]
#Try 3 - ran in 36 ms and took 12.6 MB of memory
return str(x) == str(x)[::-1]
#Testing
x = 1221
print(isPalindrome(x)) |
d67a8234cc79c9cf02e5268625143dec55dd273a | elizabeth-dayton/Leet-Code | /Easy Problems/twosum.py | 912 | 3.625 | 4 | def twoSum(nums, target):
# :type nums: List[int]
# :type target: int
# :rtype: List[int]
#Try 1 - too slow (5696 ms) and takes up too much memory (13.6 MB)
# for x in range(len(nums)):
# for y in range(len(nums)):
# if nums[x] + nums[y] == target:
# if x == y:
# continue
# else:
# return [x, y]
#Try 2 - much faster (40ms) but slightly more memory (14.2 MB)
numsDict = {}
for x in range(len(nums)):
numsDict[nums[x]] = x
print (numsDict)
for x in range(len(nums)):
complement = target - nums[x]
if numsDict.get(complement) and numsDict.get(complement) != x:
return [x, numsDict.get(complement)]
#Testing
numbers = [3, 2, 3]
targetValue = 6
print(twoSum(numbers, targetValue)) |
5da2a267ea0fa9785db99ed1598eb2457809f5d0 | jingnie0222/ex_leetcode | /binary_search.py | 1,072 | 3.828125 | 4 | import pysnooper
#@pysnooper.snoop()
#递归方式,传入的数组长度一直在变,所以不能返回正确的下标,返回True或False比较好
def binary_search(lst, val):
if not lst:
return False
mid = (len(lst) - 1) // 2
if val == lst[mid]:
return True
elif val < lst[mid]:
return binary_search(lst[0:mid], val) #注意return回来
else:
return binary_search(lst[mid+1:], val) #注意return回来
#非递归方式,start和end值可以正确计算位置,所以可以返回下标值
def binary_search_2(lst, val):
n = len(lst)
start = 0
end = n - 1
while start <= end:
mid = (start + end) // 2
if val == lst[mid]:
return mid
elif val < lst[mid]:
end = mid - 1
else:
start = mid + 1
return None
my_list = [1, 2]
val = 3
res = binary_search(my_list, val)
print("binary_search:%s" % res)
res2 = binary_search_2(my_list, val)
print("binary_search_2:%s" % res2)
|
5ca8069bc59bfc01c86ad9c67f5792fb4f09e247 | lonewolf2799/Hello-World | /class.py | 1,049 | 3.984375 | 4 | class Vector:
def __init__(self,d):
""" create d-dimensional vector of zeroes"""
self._coords = []
for i in range(d):
l = float(input())
self._coords.append(l)
def __len__(self):
return len(self._coords)
def __getitem__(self,k):
return self._coords[k]
def __setitem__ (self,j,val):
self._coords[j] = val;
def __add__(self,other):
if (len(self)!=len(other)):
raise ValueError('dimensions must agree')
result = Vector(len(self))
for i in range(len(self)):
result[i] = self[i]+other[i]
return result
def __eq__(self,other):
return self._coords == other._coords
def __ne__(self,other):
return not self == other
def __str__(self):
return ('<'+str(self._coords)[1:-1]+'>')
if __name__ == "__main__":
v = Vector(3)
"""v[0] = 2
v[1] = 9
v[2] = 7"""
print(v)
c = Vector(3)
#for i in range(3):
# input(c[i])
print(c+v)
|
588f4ba78f0024c2e178b914ff2381f8e2468e7d | gserafim283010/python-520 | /classes/animal.py | 503 | 3.65625 | 4 | #!/usr/bin/python3
class Animal():
def __init__(self, **kwargs):
# def __init__(self, peso=0, idade=0, cor='', nome='', especie=''):
#def __init__(self, *args):
for k in kwargs:
self[k] = kwargs[k]
def __str__(self):
return 'Voce printou o gatinho {0}'.format(self.nome)
def __setitem__(self, key, value):
setattr(self, key, value)
gatin = Animal(nome='Lucas', cor='Rosa')
gatin2 = Animal(nome='Roger', cor='Pink')
print(gatin)
print(gatin2)
|
18bf2a7be90921ddd8111580e9627ef58b3f6c87 | gserafim283010/python-520 | /classes/humanos.py | 964 | 3.8125 | 4 | class Humano():
def __init__(self, nome, idade, cor, peso):
self.nome = nome
self.idade = idade
self.cor = cor
self.peso = peso
def envelhecer(self):
self.idade += 1
class Homem(Humano):
def __init__(self, nome, idade, cor, peso, veiculo):
# Chama o construtor da classe de quem herdou
#super(Homem, self).__init__(nome, idade, cor)
super().__init__(nome, idade, cor, peso)
self.veiculo = veiculo
def envelhecer(self):
self.idade += 2
class Mulher(Humano):
def engravidar(self):
self.peso += 200
paramahansa = Homem('Paramahansa Yogananda', 45, 'Negro', 85, 'Fan 125cc')
coen = Mulher('Monja Coen', 50, 'Branca', 50)
print(coen.peso)
coen.engravidar()
print(coen.peso)
exit()
for i in range(0, 10):
print(coen.nome, coen.idade)
coen.envelhecer()
for i in range(0, 10):
print(paramahansa.nome, paramahansa.idade)
paramahansa.envelhecer()
|
b808f7a662759a214d9b81319b32a648ca6eaa97 | wwkkww1983/LeetCode-1 | /42.接雨水/数学解法.py | 896 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/6/29 14:48
# @Author : lxd
# @File : 数学解法.py
class Solution:
def trap(self, height: list):
if len(height) < 3:
return 0
max_height, S1, S2 = 0, 0, 0
juzhen_area = max(height) * len(height)
zhuzi_area = sum(height)
for i in height:
if i > max_height:
max_height = i
S1+=max_height
max_height = 0
height.reverse()
for i in height:
if i > max_height:
max_height = i
S2+=max_height
return S1 + S2 - juzhen_area - zhuzi_area
if __name__ == '__main__':
s = Solution()
area = s.trap(
[1, 2, 3, 5, 3, 3, 2, 4, 23, 2, 4, 43, 2, 3, 45, 23, 4, 325, 234, 43, 223, 354, 345, 3, 23, 5, 54, 23, 234])
# 1729
print(area)
area = s.trap([])
# 0
print(area)
|
dd9e8c63606b8e415372e3b880a3cb8a5f220959 | wwkkww1983/LeetCode-1 | /102.二叉树的锯齿形层次遍历/栈方法.py | 893 | 3.5625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root):
dp1 = [root,]
dp2 = []
score = []
while dp1 or dp2:
line = []
while dp1:
root = dp1.pop()
if root:
line.append(root.val)
dp2.append(root.left)
dp2.append(root.right)
if line:
score.append(line)
line = []
while dp2:
root = dp2.pop()
if root:
line.append(root.val)
dp1.append(root.right)
dp1.append(root.left)
if line:
score.append(line)
return score |
d3fc9921681c489242a1aaae6f56f8251109bd6b | wwkkww1983/LeetCode-1 | /84. 柱状图中最大的矩形/栈方法.py | 1,159 | 3.53125 | 4 | class Solution:
def largestRectangleArea(self, heights):
FILO = []
area = 0
# area列表中初始化一个0, 防止heights为空时area为空
# area = [0, ]
for i in range(len(heights)):
while FILO and heights[i] < heights[FILO[-1]]:
index = FILO.pop()
if FILO:
area = max(area, heights[index] * (i-FILO[-1]-1))
# 也可以将area做成列表,面积汇总之后最后做max,用空间换时间
# area.append(heights[index] * (i - FILO[-1] - 1))
else:
area = max(area, heights[index] * i)
FILO.append(i)
while FILO:
index = FILO.pop()
if FILO:
area = max(area, heights[index] * (len(heights) - FILO[-1] - 1))
else:
area = max(area, heights[index] * len(heights))
return area
if __name__ == '__main__':
s = Solution()
area = s.largestRectangleArea([2,1,5,6,2,3])
# 10
print(area)
area = s.largestRectangleArea([5,5,4,4,3,3,2,1,2])
# 18
print(area) |
1c832205ec93dc322ab47ed90c339a9d81441282 | nyu-cds/asn264_assignment3 | /product_spark.py | 590 | 4.1875 | 4 | '''
Aditi Nair
May 7 2017
Assignment 3, Problem 2
This program creates an RDD containing the numbers from 1 to 1000,
and then uses the fold method and mul operator to multiply them all together.
'''
from pyspark import SparkContext
from operator import mul
def main():
#Create instance of SparkContext
sc = SparkContext("local", "product")
#Create RDD on the list of numbers [1,2,...,1000]
nums = sc.parallelize(range(1,1000+1))
#Use fold to aggregate data set elements by multiplicaton (ie multiply them all together)
print(nums.fold(1,mul))
if __name__ == '__main__':
main()
|
dd98e062bdeb4a660ecb8974e170ccaa80bc9f25 | nyu-cds/asn264_assignment3 | /mpi_assignment_2.py | 1,401 | 3.84375 | 4 | '''
Aditi Nair (asn264)
April 13 2017
Assignment 10, Problem 2
In this program there is an arbitrary number of processes.
Process 0 reads a value (val) from the user and verifies that it is an integer less than 100.
Process 0 sends the value to Process 1 which multiplies it by its rank (which is 1).
Process 1 sends the value to Process 2 which multiplies it by its rank (which is 2).
Etc...
The last process sends the value back to process 0, which prints the result.
Run this program with Python3 and using the command:
mpiexec -n X python mpi_assignment_2.python
- where X is any positive integer.
'''
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
if rank == 0:
#Read an integer below 100 from the user
while True:
try:
val = int(input('\nEnter an integer below 100: '))
if val < 100:
break
except ValueError:
pass
#Send to "next" process. If size=1, then val will be sent back to 0.
comm.send(val, dest=(rank+1)%size)
#Receive val from the "last" process with rank size-1.
final_val = comm.recv(source=size-1)
print ('\nFinal value is ' + str(final_val)+'\n')
else:
#Receive new val from previous process
val = comm.recv(source=rank-1)
#Multiply val by rank number
val *= rank
#Send to "next" process. If this is the last process, then val will be sent back to 0.
comm.send(val, dest=(rank+1)%size)
|
8f9fcf819fa462c40c2336cc4e10d3d63adfe334 | zoleikha-mousavipak/pythonPro | /s2_objects_boundMethods.py | 328 | 3.546875 | 4 | class A:
def __init__(self, x):
self.x = x
def get_x(self):
return self.x
class B:
def __init__(self, x):
self.x = x
def get_x(self):
return self.x
a = A(10)
print(a)
print(a.get_x())
print(A)
print(A.get_x(a))
b = B(12)
print(b.get_x())
print(B.get_x(b))
print(B.get_x(a)) |
17865909ee7bd76bbe9e08d22d06ff1981a48352 | posccis/FlyFood | /FLYFOOD_BRUTE.py | 5,379 | 3.578125 | 4 | import itertools as it #Importando a biblioteca itertools
import time
ini = time.time()
'''__Abrindo e lendo o arquivo de texto com a matriz__'''
with open("rota.txt", "r") as rotas:
rota = rotas.read()
'''__Transformando a matriz do arquivo em uma matriz para o codigo__'''
rota = [x.split() for x in rota.split('\n')]
'''___Função procurando por pontos___'''
def lookingForPointsOut(i, j, pontos = [], allcomb = []):
global rota
j +=1
#Aqui vai ler cada item de cada linha da matriz recursivamente
def lookingForPointsIn(i, j):
if j < len(rota[i]):
#Vai considerar apenas ods itens que não forem O's ou um R
if rota[i][j] != 'R' and rota[i][j] != '0':
pontos.append(rota[i][j])
else:
pass
lookingForPointsIn(i, j+1)
else:
return 0
#Aqui vai acessar cada linha da matriz recursivamente
lookingForPointsIn(i, j)
j = -1
i += 1
if i < len(rota):
lookingForPointsOut(i, j, pontos)
else:
pass
#Aqui utilizando a biblioteca itertools para fazer a permutação de cada ponto
#gerando cada percurso possivel
allcomb = list(it.permutations(pontos))
return pontos, allcomb
'''___Função procurando pelo ponto de inicio___'''
def lookingForR(i):
global rota, pointr
if 'R' in rota[i]:
#Procura por R na matriz
pointr = (i, rota[i].index('R'))
else:
lookingForR(i+1)
return pointr
'''__Função que calcula a distancia entre os pontos__'''
def Distance( i, ponto, pontoP, linha):
#Armazena na variável 'momentum' a localização
#do proximo ponto a ser calculado
momentum = (i, linha.index(ponto))
#O calculo da distancia entre os dois pontos
#que é o mesmo da diferença entre os dois
p1 = (pontoP[0] - momentum[0])
p2 = (pontoP[1] - momentum[1])
if pontoP[0] - momentum[0] < 0:
p1 = abs(pontoP[0] - momentum[0])
if pontoP[1] - momentum[1] < 0:
p2 = abs(pontoP[1] - momentum[1])
#Caso os valores da subtração dem negativos, é utilizado a função "abs()" do python
#essa função tranforma o valor em absoluto
#Após conseguir a diferença, se soma os valores
point_value = p1 + p2
return momentum, point_value
'''__Função que calcula o retorno ao ponto R__'''
def comeBack( ponto, pointr):
#O calculo é o mesmo da função Distance, porém apenas com o Ponto R
p1 = (pointr[0] - ponto[0])
p2 = (pointr[1] - ponto[1])
if p1 < 0:
p1 = abs(pointr[0] - ponto[0])
if p2 < 0:
p2 = abs(pointr[1] - ponto[1])
point_value = p1 + p2
return point_value
'''__Função que chama a função 'Distance' e conferir se o percurso entregue é mais curto que o calculado anterior__'''
def calcDis(i, point, dronometros_m, ponto, seq, pontoR, caminho, dronometros):
global pontos
#O For Loop vai iterar pelo percurso ou sequencia que foi entregue
for k in seq:
#Aqui vai iterar por cada linha até encontrar a linha na qual o ponto 'k' está
for i in range(len(rota)):
if k in rota[i]:
#Quando encontrado a linha, ele entrega e chama a função 'Distance'
ponto, ponto_valor = Distance(i, k, point, rota[i])
dronometros_m += ponto_valor
point = ponto
else:
pass
#Após ter passado por todos os pontos do percurso, ele faz o calculo do retorno ao ponto 'R'
ponto_valor = comeBack(point, pontoR)
dronometros_m += ponto_valor
#Com os calculos concluidos é comparado com o melhor percurso encontro até o momento
if dronometros_m < dronometros or dronometros == 0:
#Caso seja, as váriaveis que armazenavam os melhores valores recebem os valores calculados agora
dronometros = dronometros_m
caminho = []
caminho += seq
#e é retornado os novos valores
return caminho, dronometros
else:
#Caso não, são retornados os valores anteriores
return caminho, dronometros
'''__Função que irá iniciar o codigo e chamar as outras funções'''
def Start(caminho = [], pointr = (), dronometros = 0):
#Aqui é chamada a função que irá entregar todos os pontos e a permutação
pontos, allcomb = lookingForPointsOut(0, -1)
#Aqui é chamada a função que irá devolver a localização do ponto R
pontoR = lookingForR(0)
pointr = pontoR
#variável que irá receber a sequencia em formato de String
caminho_st = ''
#Esse For Loop irá iterar por cada um dos percursos
for i in range(len(allcomb)):
#Aqui cada um dos percursos irá ser entregue para a função 'CalcDis'
#e irá armazenar os valores armazenados nas váriaveis 'Caminho' e 'Dronometros'
caminho, dronometros = calcDis(0, pointr, 0, (), allcomb[i], pontoR, caminho, dronometros)
#Esse For Loop irá passa cada ponto dentro do caminho para uma String
for j in caminho:
caminho_st += j + ' '
return caminho_st, dronometros
#Aqui a função 'Start' é chamada e armazena os valores nas váriaveis 'Caminho' e 'Dronometros'
caminho, dronometros = Start()
print(caminho)
end = time.time()
print(end - ini)
|
3cf484e90822067f388eb3eafb4736bafbe028d9 | hoyeonkim795/solving | /progeammers/프린터.py | 566 | 3.59375 | 4 | from collections import deque
def solution(priorities, location):
answer = 0
arr = [i for i in range(len(priorities))]
queue = deque(arr)
priorities = deque(priorities)
while queue:
a = queue.popleft()
b = priorities.popleft()
for i in range(len(priorities)):
if b < priorities[i]:
priorities.append(b)
queue.append(a)
break
else:
answer += 1
if location == a:
return answer
print(solution([1, 1, 9, 1, 1, 1],0)) |
38a4004172e95104aadc8cd171d9e94181ceb4b7 | hoyeonkim795/solving | /progeammers/단속카메라.py | 379 | 3.515625 | 4 | def solution(routes):
answer = 0
routes = sorted(routes, key = lambda x: x[1])
print(routes)
last_camera = routes[0][1]
print(last_camera)
for i in range(1,len(routes)):
if last_camera > routes[i][0]:
answer += 1
last_camera = routes[i][1]
return answer
print(solution([[-20, 15], [-14, -5], [-18, -13], [-5, 3],[2,15]])) |
400a48e4f79f4152a583e96d97c8117e369343ed | hoyeonkim795/solving | /linecodingtest/1.py | 1,331 | 3.5625 | 4 | def solution(inputString):
a,b,c,d = 0,0,0,0
result = []
for i in range(len(inputString)):
if inputString[i] == '(' and (a == 0 or a ==2):
a = 1
elif inputString[i] == '{' and (b== 0 or b == 2):
b = 1
elif inputString[i] =='[' and (c == 0 or c == 2) :
c = 1
elif inputString[i] == '<' and (d ==0 or d == 2):
d = 1
elif inputString[i] == ')' and a == 1:
a = 2
elif inputString[i] =='}' and b== 1:
b=2
elif inputString[i] == ']' and c == 1:
c=2
elif inputString[i] == '>' and d ==1 :
d=2
elif inputString[i] == ')' and (a == 0 or a == 2):
a = -1
break
elif inputString[i] =='}' and (b== 0 or b == 2):
b=-1
break
elif inputString[i] == ']' and (c == 0 or c == 2):
c=-1
break
elif inputString[i] == '>' and (d ==0 or d == 2):
d=-1
break
result = [a,b,c,d]
cnt = 0
for i in range (len(result)):
if result[i] == 0:
cnt += 0
elif result[i] == 2:
cnt += 1
elif result[i] == -1:
cnt = -1
return cnt
inputString = "<>_><"
print(solution(inputString)) |
70c89a27b9d760536ef586509d4d92f88ce5c5a8 | hoyeonkim795/solving | /swexpert/회전.py | 503 | 3.734375 | 4 | def queue(arr,M):
for _ in range(M):
front = arr[0]
rear = arr[-1]
new_arr = [0]*N
new_arr[-1] = front
for i in range(N-1):
new_arr[i] = arr[i+1]
arr = new_arr
return arr[0]
tc = int(input())
for tc in range(tc):
N,M = map(int,input().split()) # 숫자개수
# 작업 횟수
arr = [0]*N
info = list(map(int,input().split()))
for i in range(N):
arr[i]+=info[i]
print(f'#{tc+1} {queue(arr,M)}')
|
c110b1f9558c93f3f9e2cec7af06ae7b2d0fe2bc | hoyeonkim795/solving | /progeammers/MaxProductOfThree.py | 336 | 3.9375 | 4 | def bubble_sort(arr):
for i in range(0, len(arr)):
for j in range(len(arr)-1, i, -1):
if arr[j-1] > arr[j]:
arr[j-1], arr[j] = arr[j], arr[j-1]
return arr
def solution(A):
A.sort()
a = A[-1]*A[-2]*A[-3]
b= A[0]*A[1]*A[-1]
if a>b:
return a
else:
return b
|
5d4e014222a74268b16a5f8c9f35992f63e32b7f | JacobStephen9999/Linked-List-2 | /Intersection.py | 1,739 | 3.765625 | 4 | #Brute Force :
#Time Complexity : O(N)
#Space Complexity : O(N)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
d = {}
current = headA
search = headB
while(current!=None):
if current not in d:
d[current] = 1
current =current.next
while (search !=None):
if search in d:
return search
search = search.next
return None
=======================
# Withoutspace
#Time Complexity : O(N)
#Space COmplexity :O(1)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
d = {}
current = headA
search = headB
countA=1
while(current!=None):
current =current.next
countA+=1
countB=1
while (search !=None):
search = search.next
countB+=1
while(countA>countB):
headA =headA.next
countA-=1
while(countB>countA):
headB =headB.next
countB-=1
while headA!=headB:
if headA!=headB:
headA =headA.next
headB = headB.next
return headB
|
e68cc119f736a7a63a84858824a2c512c2a23ea5 | Jtonna/Sprint-Challenge--Hash-BC | /hashtables/ex2/ex2.py | 1,883 | 3.75 | 4 | # Hint: You may not need all of these. Remove the unused functions.
from hashtables import (HashTable,
hash_table_insert,
hash_table_remove,
hash_table_retrieve,
hash_table_resize)
class Ticket:
def __init__(self, source, destination):
self.source = source
self.destination = destination
def reconstruct_trip(tickets, length):
hashtable = HashTable(length)
route = [None] * length
"""
let key = source
let value = destination
for each individual ticket in range(len(tickets))
insert the source and destination as the key & value
find the key with None as the value as that is the source of the journey
pass that value key:value pair to route[0]
^^
^ ---- Could be done in one line as a variable assignment
for each item we look at in the loop of the hash table
pass that value:key pair to route
^^
^ ---- also a one line variable assignment
"""
# Insert each ticket into the hash table
for individual_ticket in range(length):
flying_from = tickets[individual_ticket].source
flying_to = tickets[individual_ticket].destination
hash_table_insert(hashtable, flying_from, flying_to)
# Finds the ticket with its source as "None", since its the origin ticket
# Then sets that ticket in the Route array at index 0
route[0] = hash_table_retrieve(hashtable, "NONE")
# Loop over the rest of the table
for each_ticket in range(1, length):
# Since we already have the origin ticket we can just subtract 1 from it to get the key of the next ticket
# we then save that as the next ticket in the route
route[each_ticket] = hash_table_retrieve(hashtable, route[each_ticket - 1])
return route
|
4bdf83247446b49e1a3f063e7d62c114b9c4de13 | jeevakamal/guvi1 | /factorial.py | 83 | 3.515625 | 4 | n=int(input())
factorical=1
while n>1:
factorical*=n
n -= 1
print(factorical)
|
c1e42b7bff83e0b4a95176375f9a4c6d1c86d3f4 | Andrew7-cloud/ParkingGarage | /dictionary_examples.py | 2,922 | 4.09375 | 4 | """ Dictionaries: Unordered, Changeable, Duplicate keys not allowed """
# GENERAL #
# 1 Calcuate Dictionary Length
this_dict = {"lot1": "False", "lot2": "False", "lot3": "False"}
dict_length = len(this_dict)
print(f"GENERAL #1 Calculate Dictionary Length: {dict_length}")
# ACCESING #
# 1 Access value of key using the format: dictionary_name[key]:
this_dict = {"lot1": "False", "lot2": "False", "lot3": "False"}
selected_key = "lot2"
x = this_dict[selected_key]
print(
f"ACCESSING #1 Access value of key using the format: dictionary_name[key]: {x}")
# 2 Access the value of -a- key using the dictionary_name.get(key_name) method:
this_dict = {"lot1": "False", "lot2": "False", "lot3": "False"}
selected_key = "lot2"
x = this_dict.get(selected_key)
print(
f"ACCESSING #2 Access the value of -a- key using the dictionary_name.get(key_name) method: {x}")
# 3 Access -all- dictionary keys using the dictionary_name.key() method:
this_dict = {"lot1": "False", "lot2": "False", "lot3": "False"}
selected_key = "lot2"
x = this_dict.keys()
print(
f"ACCESSING #3 Access -all- dictionary keys using the dictionary_name.key() method: {x}")
# 4 Access -all- dictionary values using the dictionary_name.values() method:
this_dict = {"lot1": "False", "lot2": "False", "lot3": "False"}
selected_key = "lot2"
x = this_dict.keys()
print(f"ACCESSING #3 Access -all- dictionary values using the dictionary_name.values() method: {x}")
# 2 accessing the value of a key, then treatment (.get method)
this_dict = {"lot1": "False", "lot2": "False", "lot3": "False"}
selected_key = "lot2"
x = this_dict[selected_key]
print(x)
new_dict = {}
for x in range(1, 11):
str_x = str(x)
y = "False"
new_dict.fromkeys(str_x, y)
print(new_dict)
# test to change first key value pair that meets the condition (.items method)
thisdict = {1: "False", 2: "False", 3: "False", 4: "True"}
# .items pulls key value pairs
for x, y in thisdict.items():
if y == "False":
y = "True"
print(x, y)
# break ensures the first instance a value meets the "True" criteria, the code stops
break
"""
x = ('key1','key2','key3')
y=0
dicta = dict.fromkey(x,y)
"""
car = {
"lot1": "False",
"lot2": "False",
"lot3": "False"
}
print(f"Original car dictionary: {car}")
# returns each value in the car dictionary
x = car.values()
print(f"Printing the values of the dictionary: {x}") # prints each value
# loop through values, find met criteria and edit value
for item in x:
if item == "False":
item = "True"
break
print(f"Revised car dictionary: {car}")
# assess if key name exists among keys and then treatment
lot_dict = {
"lot1": "False",
"lot2": "False",
"lot3": "False"
}
selected_lot = "lot3"
if selected_lot in lot_dict:
# how do I change the value
print("Yes, 'selected_lot' is one of the keys in the dictionary")
|
4e41495c528bcfb17742592d900fb09e6d2bd84f | dansobolev/my_python | /HW4/del_element_list.py | 212 | 3.796875 | 4 | # Упражнение 6.3
names = ['John', 'Paul', 'George', 'Ringo']
list1 = []
for i in range(len(names)):
if names[i] == 'John' or names[i] == 'Paul':
list1.append(names[i])
names = list1
|
2f3eabc6a0dd23aedd8ed61d329ac5429d5c050c | dansobolev/my_python | /HW4/new_list.py | 402 | 3.828125 | 4 | # Упражнение 6.2
from math import sqrt
# На основе цикла for
spisok1 = [2, 4, 9, 16, 25]
spisok2 = []
for i in range(len(spisok1)):
spisok2.append(sqrt(spisok1[i]))
# На основе функции map
spisok = [2, 4, 9, 16, 25]
list1 = list(map(sqrt, spisok))
# В виде генератора списка
a = [sqrt(spisok[i]) for i in range(len(spisok))]
print(a) |
1b0bc967a5688ca315c1a7b4235fdb22d075d1e3 | dansobolev/my_python | /call_tel.py | 561 | 3.5 | 4 | # Упражнение 2.5
code = int(input("Введите код города: "))
per_min = int(input("Введите длительность переговора (в минутах): "))
def call_tell(v1, v2):
if v1 == 343:
print("Ваш звонок стоит",15*v2, "р")
elif v1 == 381:
print("Ваш звонок стоит",18*v2, "р")
elif v1 == 473:
print("Ваш звонок стоит",13*v2, "р")
elif v1 == 485:
print("Ваш звонок стоит",11*v2, "р")
call_tell(code, per_min)
|
adae8c5b8680d5efddddbe0c47e6aeb26a7b0446 | manishshiwal/guvi | /ex1.py | 1,103 | 3.984375 | 4 | print "hello guys"
print """this is paragraph not a sngh;e lin
this is secong line """
a=10
b=20
print "sum=",a+b
def plus (a,b):
print"funtion sum= a+b"
return a+b
print plus(a,b)
print
print
ten_things="Apples Oranges Crows Telephone Light Sugar"
print "wait there'snot 10 things in that lost, let's fix that."
stuff=ten_things.split(' ')
more_stuff=["day","night",'song','frisbee','corn','banana','girl','boy']
while len(stuff)!=10:
next_one=more_stuff.pop()
print "adding:",next_one
stuff.append(next_one)
print "there's %i items now"%len(stuff),35+15
print "there we go",stuff
print "let's do some thing with stuff"
print stuff[1]
print stuff[-1]
print stuff.pop()
print ' '.join(stuff)
print'#'.join(stuff[3:5])
print stuff[-2]
print stuff[-1]
print
print
for cat in stuff:
print cat
print
print
states={"help":'rock',"lol":"hehe",1:"one",2:"two"}
print states
print
print states[1]
print
print states["help"]
print
states[3]="three"
print states
print
state=states.get("four",None)
print state
import apple
apple.apples()
print apple.abc
|
1175e24869bfd60f46748e147879eb33e16630d1 | manishshiwal/guvi | /eveninterval.py | 123 | 3.90625 | 4 | a=int(raw_input("enter the number"))
b=int(raw_input("enter the number"))
for n in range(a+1,b):
if(n%2==0):
print n
|
c7a3e5891b5f2fa62016e98032f38d4408a4fed8 | manishshiwal/guvi | /factorial1.py | 83 | 3.59375 | 4 | az=int(raw_input("enter the number"))
sa=1
for n in range(1,az+1):
sa*=n
print sa
|
a0ddd524732e01fede68508430b956dbd0f989f1 | hadibus/scratch_nn | /mnist_runner.py | 3,223 | 3.796875 | 4 | # file mnist_runner.py
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
import numpy as np
import random
import neuralNetwork as NN
mnist = input_data.read_data_sets("/tmp/data/") # or wherever you want
# to put your data
X_train = mnist.train.images
y_train = mnist.train.labels.astype("int")
X_test = mnist.test.images
y_test = mnist.test.labels.astype("int")
print("X_train.shape=",X_train.shape," y_train.shape=",y_train.shape)
print("X_test.shape=",X_test.shape," y_test.shape=",y_test.shape)
tours = 20
batch_siz = 100
# number of neurons in layers. last is output layer size.
# number of neurons in the input layer is decided on the
# first call of forward()
num_neurons = [300,
100, # Comment this line out to run with one hidden layer.
10]
beta = 0.8
learn_rate = 0.005
nn = NN.NeuralNetwork(num_neu=num_neurons, act_func="softmax", momentum = beta, learn_rate = learn_rate)
plot_y = []
# The main loop.
for tour in range(tours):
######################################################
# This is where the testing begins. We just throw all
# the test data at it at once in one big matrix using
# the function forward().
######################################################
# construct the batch
x_test_in = X_test
y = np.zeros((x_test_in.shape[0], num_neurons[-1]))
for n in range(x_test_in.shape[0]):
y[n,y_test[n]] = 1
yhat = nn.forward(x_test_in)
# Change yhat from matrix output to a list of values
# just like how the y_test is formatted. Put yhat
# into outage list.
outage = []
rows, cols = yhat.shape
for r in range(rows):
max_idx = -1
max_val = -1
for c in range(cols):
if yhat[r,c] > max_val:
max_val = yhat[r,c]
max_idx = c
outage.append(max_idx)
# Compare outage to y_test, get percent accuracy
num_right = 0
for idx in range(len(outage)):
#print(y_test[idx], outage[idx])
if y_test[idx] == outage[idx]:
num_right += 1
acc = num_right / len(outage)
print(acc, "correct.")
# Plot how good the accuracy is for this tour
plot_y.append(acc)
##########################################################
# This is where the training begins. We use forward() as
# before, but we also use backward() to change the weights
# and train the neural network.
##########################################################
for iters in range(50): # train it for some iterations
# Get random indicies from X_train so we can have a new random batch.
# we call the new random batch x_in
idxs = [ random.randint(0, len(X_train) - 1) for i in range(batch_siz) ]
x_in = [ X_train[n] for n in idxs ]
# setup corresponding expected output from y_train and call it y
y = np.zeros((batch_siz, num_neurons[-1]))
for n in range(len(idxs)):
y[n,y_train[idxs[n]]] = 1
yhat = nn.forward(x_in)
assert(y.shape == yhat.shape)
# Apply changes to the weights via gradient descent
nn.backward(y, yhat)
plt.plot(plot_y)
titleStr = 'MNIST training with ' + str(len(num_neurons) - 1) + ' hidden layer'
if len(num_neurons) > 2:
titleStr += 's'
if beta != 0.0:
titleStr += ' and momentum'
plt.title(titleStr)
plt.xlabel('Iteration')
plt.ylabel('Proportion correct')
plt.show()
|
b7e37b9dd086a3a4e1dbcce709e378a87769fab3 | ChillBroYo/DataStructures | /trie.py | 1,745 | 3.890625 | 4 | # create Trie data structure
from trie_node import TrieNode
from collections import deque
class Trie:
def __init__(self):
self.root = TrieNode(None)
self.count = 0
def dfs_traversal_print(self):
if self.root == None:
print("None")
return False
print (self.root.value)
for child in self.root.children:
# print(child)
self.dfs_helper(self.root.children[child])
def dfs_helper(self, node_to_search_through):
# print(parent.children[node_to_search_through])
if len(node_to_search_through.children) == 0:
print (node_to_search_through.value)
return
else:
print (node_to_search_through.value)
for child in node_to_search_through.children:
self.dfs_helper(node_to_search_through.children[child])
def bfs_traversal(self):
if self.root == None:
return False
print (self.root.value)
queue = deque()
for index in self.root.children:
queue.append(self.root.children[index])
while len(queue) > 0:
val = queue.pop()
print(val.value)
for child in val.children:
queue.append(val.children[child])
return True
if __name__ == "__main__":
var = Trie()
# var.root = TrieNode(1)
# print(var.root.value)
val = TrieNode(1)
val.add_child(2)
val.children[2].add_child(6)
val.children[2].children[6].add_child(7)
val.add_child(3)
var.root = val
var.dfs_traversal_print()
print("_____")
var.bfs_traversal() |
266dd9f4d92681236380165d828e127a8dafb7ef | jagruti756/PythonTraining_Jagruti | /Assignment 2.py | 6,585 | 4.4375 | 4 | #1 Write a program in Python to perform the following operation:
If a number is divisible by 3 it should print “Consultadd” as a string
If a number is divisible by 5 it should print “Python Training” as a string
If a number is divisible by both 3 and 5 it should print “Consultadd - Python Training” as a string.
a = int(input("Enter a value: "))
x = a
if x%3 == 0 and x%5 == 0:
print("consultadd - Python Training")
elif x%3 == 0:
print("consultadd")
elif x%5 == 0:
print("Python Training")
#2 Write a program in Python to perform the following operator based task:
Ask user to choose the following option first:
If User Enter 1 - Addition
If User Enter 2 - Subtraction
If User Enter 3 - Division
If User Enter 4 - Multiplication
If User Enter 5 - Average
Ask user to enter two numbers and keep those numbers in variables num1 and num2
respectively for the first 4 options mentioned above.
Ask the user to enter two more numbers as first and second for calculating the average as
soon as the user chooses an option 5.
At the end if the answer of any operation is Negative print a statement saying “NEGATIVE”
NOTE: At a time a user can only perform one action.
option = eval(input("enter number between 1 to 5"))
num1 = eval(input("Enter num1"))
num2 = eval(input("Enter num2"))
if option <=5 and option >=0:
if option == 1:
add = num1+num2
print(add)
elif option == 2:
sub = num1-num2
print(sub)
elif option == 3:
div = num1/num2
print(div)
elif option == 4:
multiplication = num1*num2
print(multiplication)
elif option == 5:
num3= eval(input("enter the number to calculate average"))
num4= eval(input("enter the 2nd value to calculate the average"))
avg = (num1+num2+num3+num4)/4
print(avg)
elif add or sub or div or multiplication or avg <=0:
print("negative")
#3 #3.Write a program in Python to implement the given flowchart:
a,b,c = 10,20,30
avg = (a+b+c)/3
print("avg =",avg)
if avg > a and avg>b and avg>c:
print("avg is higher than a,b,c")
elif avg > a and avg>b:
print("avg is higher than a,b")
elif avg > a and avg>c:
print("avg is higher than a,c")
elif avg>b and avg>c:
print("avg is higher than b,c")
elif avg > a:
print("avg is just higher than a")
elif avg > b:
print("avg is just higher than b")
elif avg > c:
print("avg is just higher than c")
#4 Write a program in Python to break and continue if the following cases occurs:
If user enters a negative number just break the loop and print “It’s Over”
If user enters a positive number just continue in the loop and print “Good Going”
while True:
a = eval(input("enter the value "))
if a>0:
print("keep going")
continue
if a<0:
print("it's over")
break
#5 Write a program in Python which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200.
a =[]
for x in range(2000,3000):
if(x % 7==0) and (x % 5 != 0):
a.append(str(x))
print ((a))
#6 What is the output of the following code examples?
x = 123
for i in x:
print(i)
#'int' object is not iterable
# 0
#error
#1
#error
#2
#name 'true' not defined
#7 Write a program that prints all the numbers from 0 to 6 except 3 and 6.
Expected output: 0 1 2 4 5
Note: Use ‘continue’ statement
for i in range(0,6):
if i==3 or i==6:continue
print(i)
#8. Write a program that accepts a string as an input from the user and calculatethe number of digits and letters.
digits = letters = 0
raw = input("enter a string:")
for c in raw:
if c.isdigit():
digits = digits + 1
elif c.isalpha():
letters = letters + 1
print("Letters", letters)
print("Digits", digits)
#9 Write a program such that it asks users to “guess the lucky number”. If the correct number is guessed the program stops, otherwise it continues forever.
Modify the program so that it asks users whether they want to guess again each time. Use two variables, ‘number’ for the number and ‘answer’ for the answer to the question whether they want to continue guessing. The program stops if the user guesses the correct number or answers “no”. (
The program continues as long as a user has not answered “no” and has not guessed the correct
number)
lucky_num = 3
while True:
number =eval(input("guess the lucky number"))
if number != lucky_num:continue
else:
print("congratulations you have guessed it correct : ")
break
lucky_num = 3
while True:
number =eval(input("guess the lucky number"))
if number != lucky_num:
print("sorry you have guessed it wrong")
answer = eval(input(" enter 1 if you want to guess it again , other wise enter 0"))
if answer == 0:break
elif answer == 1:continue
else:
print("congratulations you have guessed it correct : ")
break
#10 Write a program that asks five times to guess the lucky number. Use a while loop and a counter,
such as
While counter <= 5:
print(“Type in the”, counter, “number”
counter=counter+1
The program asks for five guesses (no matter whether the correct number was guessed or not). If the
correct number is guessed, the program outputs “Good guess!”, otherwise it outputs “Try again!”.
After the fifth guess it stops and prints “Game over!”.
counter = 1
lucky_num = 1
while counter <=6:
number = eval(input("Enter the lucky number"))
counter = counter+1
if counter == 6:
print("game over")
break
if counter != lucky_num:
print("try again")
else:
print("Good guess")
#11 In the previous question, insert break after the “Good guess!” print statement. break will terminate
the while loop so that users do not have to continue guessing after they found the number. If the user
does not guess the number at all, print “Sorry but that was not very successful”.
counter = 1
lucky_num = 1
while counter <=6:
number = eval(input("Enter the lucky number"))
counter = counter+1
if counter == 6:
print("Sorry that was not very succesful")
break
if counter != lucky_num:
print("try again")
else:
print("Good guess")
break
|
8cd7f43659172e76b0e5dfcc688912228119bf36 | pavantej934/HackerRank_30DaysofCode | /30Days_P4.py | 301 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 17 23:11:15 2017
@author: pavantej
"""
#!/bin/python3
import sys
N = int(input().strip())
if (N % 2 != 0) or (N % 2 == 0 and 6<= N <= 20):
print ("Weird")
elif (N % 2 == 0 and (2 <= N <= 5 or N > 20)):
print ("Not Weird")
|
7f59edbbd8298d1c6c34c1f646819cb28333c5a7 | mshazman/data_munging | /weather/reader.py | 921 | 3.703125 | 4 | """This Module Contain Class To read Data from data file"""
import re
class ReadData():
"""This class object takes data file and return desired data in form of dictionary"""
def __init__(self, file):
self.file = file
def get_data(self, key, index_first, index_second):
"""This method will read data from File and return list of dictionary with
max and min temp"""
data = {}
with open(self.file) as weather_file:
days = weather_file.readlines()
for day in days[2:len(days)-1]:
day = day.split()
try:
day[index_first] = re.sub("[*]", "", day[index_first])
day[index_second] = re.sub("[*]", "", day[index_second])
data[day[key]] = [(day[index_first]), (day[index_second])]
except Exception:
pass
return data
|
f6a391044b4bf87edf998971b1a0d2a8924bd182 | shawsuraj/dailyCode | /100-days-of-code/python/Day005/fibonacci.py | 222 | 3.984375 | 4 | n = int(input("Enter the range of fibonacci: "))
a = 0
b = 1
for _ in range(0, n) :
(a, b) = (b, a + b)
print(a, end=' ')
# a = 0
# b = 1
# for _ in range(20):
# (a, b) = (b, a + b)
# print(a, end=' ')
|
66e9c916b7ea5908c091f4fd5a7a5e2821efd3de | shawsuraj/dailyCode | /100-days-of-code/python/Day006/combination.py | 270 | 4.15625 | 4 | print ("Combination finder.")
n = int(input("Enter n: "))
r = int(iinput("Enter r: "))
def factorial ( n ):
result = 1
for num in range ( 1 , n + 1 ):
result *= num
return result
print (factorial( n ) // factorial( r ) // factorial( n - r ))
|
443313237c0f2944f7531d8421ec77d5a0269cba | Alispirale/PythonTraining | /Nom_Age.py | 277 | 3.78125 | 4 | print('Quel est ton nom ?')
monNom = input()
print('Nice to meet you, ' + monNom)
print('La longueur de ton nom est de ' + str(len(monNom)) + ' caracteres')
print('Quel est ton age ?')
monAge = input()
if int(monAge)<35:
print('Tu es jeune !')
else:
print('Ok boomer') |
6a2afeb38e6a67e1412c5c86c8930cd0bd9b02f3 | AlvaroLuz/CalculoNumerico | /CN/P1/mpf.py | 284 | 3.5 | 4 | import math
import numpy as np
def funcx(x):
return np.log(x**3 - x**2 +2 )
a , b = 0.4, 1.6
epsilon = 1e-2
x =0.5
xant = x
x = funcx(x)
print(xant-x)
while (((x%100000000)-(xant%100000000))%100000000)> epsilon:
xant = x
x = funcx(x)
print(xant-x) |
6cd27984d4037cf6c9f088852427b9d780dcba83 | jkleve/Presidential-Prediction | /state_by_state/numpy_utils.py | 1,919 | 3.828125 | 4 | import numpy as np
################################################
#
# Add 2 np arrays row wise
#
################################################
def add_row_to_array(a, b):
if a.shape == (0,0):
return b
if a.shape[1] != b.shape[1]:
print("Number of columns doesn't match. %d vs %d" % (a.shape[1], b.shape[1]))
print("Can't add row to array")
return np.concatenate((a,b))
################################################
#
# Add 2 np arrays column wise
#
################################################
def add_column_to_array(a, b):
if a.shape == (0,0):
return b
if a.shape[0] != b.shape[0]:
print("Number of columns doesn't match. %d vs %d" % (a.shape[0], b.shape[0]))
print("Can't add row to array")
return np.column_stack((a,b))
################################################
#
# Split one ndarray into two
# start: start row of ndarray to extract
# stop: stop row of ndarray to extract
#
################################################
def split_into_two_ndarrays_by_rows(d, start, stop):
train = None
test = None
if stop > d.shape[0]:
print("Contraining end of test data")
stop = d.shape[0]
beginning = d[0:start]
end = d[stop+1:]
if len(beginning) > 0:
if len(end) > 0:
train = (np.concatenate((beginning,end)))
else:
train = beginning
else:
train = end
test = d[start:stop+1]
return (train, test)
################################################
#
# Split one ndarray into two
# start: start column of ndarray to extract
# stop: stop column of ndarray to extract
# TODO nothing implemented besides the extracted array
# TODO no error checking on ndarray size
################################################
def split_into_two_ndarrays_by_column(d, start, stop):
return (d[:,start:stop], np.zeros(shape=(0,0)))
|
a97e9afcfe054249032c537dd182116bf29b01ba | jkleve/Presidential-Prediction | /demographics/demo_histograms.py | 442 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
# feature 1
f1 = [69.8, 80.91, 69.72, 80.39]
bins = np.arange(65,85,1)
def gen_histogram(accuracies, bins):
mu, sigma = 100, 15
hist, bins = np.histogram(accuracies, bins=bins)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()
if __name__ == "__main__":
gen_histogram(f1, bins)
|
a5c01e4e665069b608dd1c9185ce8edd74c985d5 | JeffreyBenjaminBrown/play | /_not_music/machineLearn/obsolete/older_flow/it.py | 10,887 | 3.859375 | 4 |
# coding: utf-8
# # Programming Exercise 4: Neural Networks Learning
# In[1]:
get_ipython().magic('matplotlib inline')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import scipy.io #Used to load the OCTAVE *.mat files
import scipy.misc #Used to show matrix as an image
import matplotlib.cm as cm #Used to display images in a specific colormap
import random #To pick random images to display
import scipy.optimize #fmin_cg to train neural network
import itertools
from scipy.special import expit #Vectorized sigmoid function
# ## Utilities
# In[2]:
def prependUnityColumn(colvec):
return np.insert(colvec,0,1,axis=0)
test = np.array([[3,4]]).T
# (test, prependUnityColumn(test)) # test
# ### Sigmoids: Expit (1/(1+e^z)) is somehow faster than "fast sigmoid" (1 / (1+abs(x)))
# In[3]:
# obsolete, replaced by the sigmoid functions (which are next)
def expitPrime(colVec): return expit(colVec) * expit(1-colVec)
# the derivative of ("expit" = the sigmoid function)
# In[4]:
def _sigmoid(x): return (x / (1 + abs(x)) + 1) / 2
sigmoid = np.vectorize(_sigmoid)
# sigmoid(np.array([-10,0,10])) # test
# In[5]:
def _sigmoidPrime(x): return 1 / (2 * ((abs(x)+1)**2))
sigmoidPrime = np.vectorize(_sigmoidPrime)
# sigmoidPrime(np.array([list(range(-10,15,5))])).T # test
# In[6]:
data = np.random.rand(1000000)
get_ipython().magic('prun expit(data)')
# %prun sigmoid(data)
# %prun np.vectorize( lambda x: (x / (1 + abs(x)) + 1) / 2 )(data)
# ## Visualizing the data
# ### This visualization is (roughly) unchanged, from https://github.com/kaleko/CourseraML
# In[7]:
datafile = 'data/ex4data1.mat'
mat = scipy.io.loadmat( datafile )
X, Y = mat['X'], mat['y']
X = np.insert(X,0,1,axis=1) #Insert a column of 1's
print( "'Y' shape: %s. Unique elements in y: %s"%(mat['y'].shape,np.unique(mat['y'])) )
print( "'X' shape: %s. X[0] shape: %s"%(X.shape,X[0].shape) )
#X is 5000 images. Each image is a row. Each image has 400 pixels unrolled (20x20)
#y is a classification for each image. 1-10, where "10" is the handwritten "0"
# In[8]:
def tenToZero(digit):
if digit == 10: return 0
else: return digit
Y = np.vectorize(tenToZero)(Y)
def digitVecToBoolArray(digitVec):
# >>> I meant to use this somewhere else too
height = digitVec.shape[0]
boolArray = np.zeros((height,10))
for obs in range(height):
boolArray[obs,digitVec[obs]] = 1
return boolArray
YBool = digitVecToBoolArray(Y)
YBool;
# In[9]:
def getDatumImg(row):
"""
from a single np array with shape 1x400,
returns an image object
"""
width, height = 20, 20
square = row[1:].reshape(width,height)
return square.T
def displaySomeData(indices_to_display = None):
"""
picks 100 random rows from X,
creates a 20x20 image from each,
then stitches them together into a 10x10 grid of images,
shows it.
"""
width, height = 20, 20
nrows, ncols = 10, 10
if not indices_to_display:
indices_to_display = random.sample(range(X.shape[0]), nrows*ncols)
big_picture = np.zeros((height*nrows,width*ncols))
irow, icol = 0, 0
for idx in indices_to_display:
if icol == ncols:
irow += 1
icol = 0
iimg = getDatumImg(X[idx])
big_picture[irow*height:irow*height+iimg.shape[0],icol*width:icol*width+iimg.shape[1]] = iimg
icol += 1
fig = plt.figure(figsize=(6,6))
img = scipy.misc.toimage( big_picture )
plt.imshow(img,cmap = cm.Greys_r)
# In[10]:
displaySomeData()
# ## Make random coeffs. Architecture = list of lengths.
# In[11]:
def mkRandCoeffsSymmetric(randUnifCoeffs):
return randUnifCoeffs*2 - 1 # rand outputs in [0,1], not [-1,1]
def mkRandCoeffsSmall(randUnifCoeffs):
a,b = randUnifCoeffs.shape
e = np.sqrt(6) / np.sqrt(a+b)
return randUnifCoeffs * e
# In[12]:
def mkRandCoeffs(lengths):
# lengths :: [Int] lists input, hidden, and output layer lengths
# and it does NOT include the constant terms
acc = []
for i in range(len(lengths)-1):
acc.append(mkRandCoeffsSmall(mkRandCoeffsSymmetric(
np.random.rand(lengths[i+1],lengths[i]+1) ) ) )
return acc
mkRandCoeffs([3,2,1]) # example: 2 matrices, 3 layers (1 hidden)
# ## Forward-propogation
# In[13]:
def forward(nnInputs,coeffMats):
# nnInputs :: column vector of inputs to the neural net
# coeffMats :: list of coefficient matrices
latents = ["input layer latent vector does not exist"] # per-layer inputs to the sigmoid function
# The last layer has the same number of latent and activ values.
# Each hidden layer's latent (aka weighted input) vector is 1 neuron shorter than the corresponding activs vector.
# HOWEVER, to make indexing the list of latents the same as the list of activs,
# I give it a dummy string value at position 0.
activs = [nnInputs] # per-layer outputs from the sigmoid function
for i in range(len(coeffMats)):
newLatent = coeffMats[i].dot(activs[i])
latents.append( newLatent )
newActivs = np.vectorize(_sigmoid)( latents[i+1] ) # >>>
if i<len(coeffMats)-1: newActivs = prependUnityColumn(newActivs)
# nnInputs already has the unity column.
# The hidden layer activations get it prepended here.
# The output vector doesn't need it.
# Activations ("a") have it, latents ("z") do not.
activs.append( newActivs )
prediction = np.argmax(activs[-1])
return (latents,activs,prediction)
# In[14]:
# It works! (The smaller test's arithmetic is even human-followable.)
forward(np.array([[1,2,3]]).T
, [np.array([[5,2,0]])]
)
forward( np.array([[1,1,2]]).T
, [np.array([[1,2,3]
,[4,5,6]])
, np.array([[3,2,1]
,[5,5,5]])
] )
# ## Cost
# In[15]:
# contra tradition, neither cost needs to be scaled by 1/|obs|
def mkErrorCost(observed,predicted):
return np.sum( # -y log hx - (1-y) log (1-hx)
(-1) * observed * np.log(predicted)
- (1 - observed) * np.log(1 - predicted)
)
def mkRegularizationCost(coeffMats):
flatMats = [np.delete(x,0,axis=1).flatten()
for x in coeffMats]
return np.concatenate(np.array(flatMats)**2).sum()
mkErrorCost(np.array([[1,0]]).T # should be small
, np.array([[.99,0.01]]).T)
mkRegularizationCost([np.array([[10,1,2]])]) # should be 5
mkRegularizationCost([np.eye(1),np.eye(2)]) # should be 1
# In[16]:
def testCost():
nnInputs = np.array([[1,2,-1]]).T
observedCategs = np.array([[1,0]])
Thetas = mkRandCoeffs([2,2,2])
latents,activs,predicts = forward(nnInputs,Thetas)
ec = mkErrorCost(observedCategs,activs[-1])
rc = mkRegularizationCost(Thetas)
return (ec,rc)
testCost()
# ## Errors, and back-propogating them
# In[17]:
def mapShape(arrayList): return list(map(np.shape,arrayList))
def mkErrors(coeffMats,latents,activs,yVec):
"Returns a list of error vectors, one per layer."
nLayers = len(latents)
errs = list( range( nLayers ) ) # dummy values, just for size
errs[0] = "input layer has no error term"
errs[-1] = activs[-1] - yVec # the last layer's error is different
for i in reversed( range( 1, nLayers - 1 ) ): # indexing activs
errs[i] = ( coeffMats[i].T.dot( errs[i+1] )[1:]
# [1:] to drop the first, the "error" in the constant unity neuron
* np.vectorize(_sigmoidPrime)(latents[i]) ) # >>>
for i in range(1,len(errs)): errs[i] = errs[i].reshape((-1,1))
return errs
def testMkErrors(): return mkErrors(
[np.eye(2),np.eye(2),np.ones((2,2))]
, ["nonexistent", np.array([[1,1]]).T,np.array([[1,1]]).T, "unimportant"]
, [np.array([[1,1]]).T,np.array([[1,1]]).T,np.array([[1,1]]).T,np.array([[2,3]]).T]
, np.array([[2,3.1]]).T
)
def testMkErrors2(): return mkErrors(
[np.eye(2),np.ones((2,2))]
, ["nonexistent", np.array([[1,1]]).T, "unimportant"]
, [np.array([[1,1]]).T,np.array([[1,1]]).T,np.array([[2,3]]).T]
, np.array([[2,3.1]]).T
)
testMkErrors2()
# In[18]:
def mkObsDeltaMats(errs,activs):
"Compute the change in coefficient matrices implied by the error and activation vectors from a given observation."
nMats = len(activs)-1
acc = list(range(nMats)) # start with dummy values
for i in range(nMats):
acc[i] = errs[i+1].dot( activs[i].T )
return acc
def testMkObsDeltaMats(): # result should be 3 by 3
errs = ["nonexistent",np.ones((3,1))]
activs = [np.ones((3,1)),"unimportant"]
return mkObsDeltaMats(errs,activs)
testMkObsDeltaMats()
# ## Putting it together?
# In[19]:
def mkCoeffDeltasFromObs(coeffMats,X,YBool):
latents,activs,_ = forward(X,coeffMats)
errs = mkErrors(coeffMats,latents,activs,YBool)
return mkObsDeltaMats(errs,activs)
# In[20]:
lengths = [400,10,30,10]
XT = X.T.copy() # hopefully, extracting columns from this is faster
nObs = X.shape[0]
def run():
coeffs = mkRandCoeffs( lengths )
costAcc = []
changeAcc = list(map(lambda x: x.dot(0),coeffs)) # initCoeffs * 0
for run in range(5): # 2 is enough if convergence monotonic
costThisRun = 0
for obs in range( nObs ): # >>> inefficient, runs forward twice for each obs
# should combine with the next loop
_,activs,_ = forward( XT[:,[obs]] # >>> was: X[obs].reshape((-1,1))
, coeffs )
costThisRun += mkErrorCost( YBool[obs], activs[-1])
costAcc.append(costThisRun/nObs)
for obs in range( nObs ):
ocd = mkCoeffDeltasFromObs(
coeffs,
XT[:,[obs]],
YBool[obs].reshape((-1,1)))
changeAcc += ocd
for i in range(len(coeffs)):
coeffs[i] -= 1000 * (ocd[i] / nObs)
return costAcc # >>> also return coeffs
# In[21]:
get_ipython().magic('prun run()')
# In[22]:
"""Speed ideas:
The "fast sigmoid" f(x) = x / (1 + abs(x)) is differentiable!
scaled to [0,1]: f(x) = (x / (1 + abs(x)) + 1) / 2
more ideas (and that one) here: http://stackoverflow.com/questions/10732027/fast-sigmoid-algorithm
There's tab-completion!
repair SMSN, look at my ML notes there
transpose X once initially, not each time
YBool, latents, activs, errs might also have this prob|oppor
maybe late, when handing it to the forward-backward iterator
maybe early; decide by counting where it is used heavily
use fmin_cg, ala the original ex4.ipynb in this folder
unrollMats :: [length] -> [matrix] -> [coeff]
rollMats :: [length] -> [coeff] -> [matrix]
loop once, not twice, over the observations per set of coeffs
Concision
lengths ought only to describe the hidden layers
""";
|
4ccc972af4b0662d9b062ad8dec4fb60eafb1e98 | redkins/Demo | /code/jump7.py | 164 | 3.546875 | 4 | for i in range(1,101):
if ( i / 7 == 0 ):
continue
elif ( i % 10 == 7 ):
continue
elif ( i // 10 == 7 ):
continue
print (i)
|
6d6831c5fc145e6dc17c6679154af2549c858512 | PercivalN/Class-Notes-Graphs | /ClassNotesPt1.py | 323 | 3.609375 | 4 | """
Notes for hash table day1
class LinkedListNodes:
def __init__(self, value):
self.value = value
self.next = value
class GraphNode:
def __init__(self, value):
self.value = value
self.edges = [] # This gives as much edges as we want, These are adjacency list
"""
|
19f21e5e66535ce20858639289ddf946c016d91d | wang-xian-yan/python-example | /basis.py | 258 | 3.921875 | 4 | print('hello python')
strList = ['a', 'b', 'c']
print(len(strList))
for st in strList:
print(st)
print(strList[2])
person = {'name': 'drew.wang', 'age': 20}
print('age:', person['age'])
def showInfo():
print('name:', 'drew.wang')
showInfo()
|
c1a562f556dc8169d74e922f5ebaa2d7eb90e45f | MauricioMucci/Udemy | /Python - Aprendizado/Projeto3/lista3.py | 3,835 | 3.90625 | 4 | #Questao 1
for num in range(3,18,3):
print(num, end=" ")
print()
print()
#Questao 2
for _ in range(3):
for num in range(1,11):
print(num, end=" ")
print()
print()
aux = 0
while aux < 3:
num = 1
while num <= 10:
print(num, end=" ")
num = num + 1
print()
aux = aux + 1
#Questao 3
print()
aux = 10
while aux >= 0:
print(aux, end=" ")
aux = aux - 1
print()
#Questao 4
print()
for num in range(0,110,10):
print(num, end=" ")
print()
#Questao 5
print()
aux = 0
soma = 0
while aux < 10:
num = int(input("Digite um inteiro: "))
soma += num
aux += 1
print(f"\nA soma e: {soma}\n")
soma = 0
for _ in range(10):
num = int(input("Digite um inteiro: "))
soma += num
print(f"\nA soma e: {soma}\n")
#Questao 6
soma = 0
for _ in range(10):
num = int(input("Digite um inteiro: "))
soma += num
media = soma/10
print(f"\nA media e: {round(media,2)}\n")
#Questao 7
soma = 0
for _ in range(10):
num = int(input("Digite um inteiro: "))
while num < 0:
num = int(input("Digite novamente: "))
soma += num
media = soma/10
print(f"\nA media e: {round(media,2)}\n")
#Questao 8
for i in range(10):
num = int(input("Digite um inteiro: "))
if i == 0:
menor = num
maior = num
if num > maior:
maior = num
if num < menor:
menor = num
print(f"Maior = {maior} || Menor = {menor}")
#Questao 9
num = int(input("Digite um inteiro: "))
for i in range(1,num*2,2):
print(i, end=" ")
print()
i = 1
while num > 0:
print(i, end=" ")
i += 2
num -= 1
print()
#Questao 10
soma = 0
for num in range(0,50,2):
soma += num
print(soma)
#Questao 19
num = int(input("Digite um inteiro entre 100-999: "))
while num < 100 or num > 999:
print("\n\t[ Tente novamente ]")
num = int(input("Digite um inteiro entre 100-999: "))
resultado = 0
while num != 0:
resultado += num % 10
num = int(num / 10)
print(resultado)
#Questao 20
print("\t[ Digite 1000 para sair ]")
num = int(input("Digite um inteiro: "))
i = 1
j = 0
while num != 1000:
print("\t[ Digite 1000 para sair ]")
num = int(input("Digite um inteiro: "))
i += 1
if num % 2 == 0:
j += 1
if i != 1:
print(f"{i} valores digitados!\n{j} valores sao pares!")
#Questao 21
a, b = int(input("Digite o inicio do intervalo: ")), int(input("Digite o fim do intervalo: "))
soma = 0
multiplicacao = 1
for num in range(a,b + 1):
if num % 2 == 0:
soma += num
else:
multiplicacao *= num
print(f"Soma = {soma}\nMultiplicacao = {multiplicacao}")
#Questao 22
i = 0
soma = 0
while True:
nota = float(input("Digite uma nota entre 10-20: "))
if nota < 10 or nota > 20:
break
soma += nota
i += 1
media = soma / i
print(f"Media = {round(media,2)}")
#Questao 23
num = int(input("Digite um inteiro: "))
for i in range(1,num + 1):
if num % i == 0:
print(i, end=" ")
print()
#Questao 24
num = int(input("Digite um inteiro: "))
soma = 0
for i in range(1,num):
if num % i == 0:
soma += i
print(f"Soma = {soma}")
#Questao 26
num = int(input("Digite um inteiro: "))
while True:
if num % 11 == 0 and num % 13 == 0 and num % 17 == 0:
print(num)
break
num += 1
#Questao 27
num = int(input("Digite a serie harmonica: "))
h = 0
for i in range(1,num + 1):
h += 1 / i
print(f"O resultado e: {round(h,3)}")
#Questao 28
def fac(a):
if a == 1:
return a
return a * fac(a - 1)
num = int(input("Digite a serie: "))
e = 0
for i in range(1,num + 1):
e += 1 / fac(i)
print(f"O resultado e: {round(e,3)}")
#Questao 53
num = int(input("Digite o numero de Floyd: "))
aux = 1
j = 1
for _ in range(num):
for _ in range(j):
print(aux, end=" ")
aux +=1
print()
j += 1
|
b148c5ec3df262c70703c1e6839c3d375f7a4363 | kulbir-ahluwalia/Implementing_A_star_on_Turtlebot3 | /Phase 3/How to plot curves_modified.py | 1,186 | 3.640625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import math
fig, ax = plt.subplots()
def plot_curve(Xi,Yi,Thetai,UL,UR):
t = 0
r = 0.033
L = 0.160
dt = 0.1
Xn=Xi
Yn=Yi
Thetan = 3.14 * Thetai / 180
# Xi, Yi,Thetai: Input point's coordinates
# Xs, Ys: Start point coordinates for plot function
# Xn, Yn, Thetan: End point coordintes
while t<1:
t = t + dt
Xs = Xn
Ys = Yn
Xn += r * (UL + UR) * math.cos(Thetan) * dt
Yn += r * (UL + UR) * math.sin(Thetan) * dt
Thetan += (r / L) * (UR - UL) * dt
plt.plot([Xs, Xn], [Ys, Yn], color="blue")
Thetan = 180 * (Thetan) / 3.14
return Xn, Yn, Thetan
actions=[[5,5],[5,0],[0,5],[5,10],[10,5]]
for action in actions:
X1= plot_curve(0,0,45, action[0],action[1]) # (0,0,45) hypothetical start configuration
for action in actions:
X2=plot_curve(X1[0],X1[1],X1[2], action[0],action[1])
#to make a line from 2,6 to 4,10
#plt.plot([2, 4], [6, 10], color="blue")
plt.grid()
ax.set_aspect('equal')
plt.xlim(0,10)
plt.ylim(0,10)
plt.title('How to plot a vector in matplotlib ?',fontsize=10)
plt.show()
plt.close()
|
e76c7cc1e6789df6037f603849e2dbd81e38a7b4 | olzhas23/Flask-blog | /sql.py | 471 | 3.859375 | 4 | import sqlite3
with sqlite3.connect ("blog.db") as connection:
c=connection.cursor()
c.execute("""CREATE TABLE posts (title TEXT, post TEXT)""")
c.execute ("""INSERT INTO posts VALUES( 'hi', 'its a great morning')"""),
c.execute ("""INSERT INTO posts VALUES( 'Good', ' its a great morning')"""),
c.execute ("""INSERT INTO posts VALUES( 'Awesome', ' its a great nigh')"""),
c.execute ("""INSERT INTO posts VALUES( 'Hi dear', ' its a great day')""")
|
ac084f4d68ad55ad44690a054bd0938276b989fc | Kids-Hack-Labs/Winter2021 | /Week01/code/challenges.py | 3,695 | 4.28125 | 4 | """
Kids Hack Labs
Winter 2021 Term
Week 01
Homework Challenges: Number-guessing game
Note: Both challenges implemented at the same time
No extensions are marked as such, only challenges
The score system works by adding remaining tries as points,
meaning it's possible to get 0 points despite winning
"""
import random
def main():
random.seed()
player = input("Hello, what is your name? ")
print(f"Welcome to KHL\'s number-guessing game, {player}")
#Challenge 10: Multi-round variables
score = 0
wins = 0
total_rounds = 0
round_won = False
playing = True
#Challenge 10: Multi-round implementation
while playing:
lowest = int(input("What is the lowest number in the range? "))
highest = int(input("What is the highest number in the range? "))
#Challenge 11: Data validation
while highest <= lowest:
print(f"Highest number cannot be equal to or lower than {lowest}.")
highest = int(input("What is the highest number in the range?"))
print(f"Setting mystery number between {lowest} and {highest}...")
target = random.randrange(lowest, highest)
print("Mystery number set!")
max_tries = int(input("How many tries do you want to get?"))
#Challenge 11: Data validation
while max_tries >= (highest - lowest):
print("Not allowed. Max guesses must be less than range of numbers")
max_tries = int(input("How many tries do you want to get?"))
tries = max_tries
round_won = False
in_round = True
total_rounds += 1
while in_round:
answer = input(f"Guess a number between {lowest} and {highest},\n"+
"\"q\" or \"Q\" to quit: ")
if answer.lower() == "q":
in_round = False
playing = False
break
else:
answer = int(answer)
#Challenge 11: data validation
if not lowest <= answer <= highest:
print("Guess outside range. Try again.")
continue
tries -= 1
if answer == target:
round_won = True
in_round = False
elif answer < target:
print(f"Too low. You have {tries} tries left.")
else:
print(f"Too high. You have {tries} tries left.")
if tries == 0:
in_round = False
if playing:
if round_won:
print(f"Congrats, {player}!"+
f"You won this round after {max_tries - tries} tries")
wins += 1
score += tries
else:
print(f"Sorry, {player}. You lost this round."+
f"The mystery number was {target}")
#Challenge 10: Replay round mechanic
replay = input("Do you want to play again? (Y/y, N/n) ").lower()
#Challenge 11:Data validation
while replay != "y" and replay != "n":
replay = input("Do you want to play again? (Y/y, N/n) ").\
lower()
#Note: this boolean expression evaluates to True if the
# user chooses "yes", or to false if the user chooses "no"
playing = (replay != "n")
print(f"Here is a breakdown of your performance, {player}:\n"+
f"Rounds Played: {total_rounds}\n"+
f"Rounds Won: {wins}\n"+
f"Final Score: {score}")
if __name__ == "__main__":
main()
|
94cf5385b4d09e2b215c5bf964f7575247b6e441 | Kids-Hack-Labs/Winter2021 | /Week02/code/activity01_base.py | 623 | 4.0625 | 4 | def rewrite_message(first, last, day, month, year):
return f"{first} {last} was born in {month} {day}, {year}."
first_name = "John"
last_name = "Doe"
day = 27 #int
month = "September"
year = 2016
message = rewrite_message(first_name, last_name, day, month, year)
print(message)
first_name = input("What is your first name? ")
last_name = input("What is your last name? ")
day = int(input("What day were you born in? "))
month = input("What month were you born in? ")
year = int(input("What year were you born in? "))
print(message)
message = rewrite_message(first_name, last_name, day, month, year)
print(message)
|
71c12cbfbace9a5e7604cfcd87323b5d686ca464 | medecau/aoc | /2018/1a.py | 284 | 3.640625 | 4 | import sys
file_path = sys.argv[1]
frequency = 0
with open(file_path) as input_file:
for line in input_file:
sign, num = line[0], int(line[1:])
if sign == "+":
frequency += num
elif sign == "-":
frequency -= num
print(frequency)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.